feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -0,0 +1,356 @@
|
||||
// Package nodefiles provides bounded, rooted file operations. The node accepts
|
||||
// a host identity and relative names, never a caller-supplied absolute root.
|
||||
package nodefiles
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxFileBytes = 20 << 20
|
||||
const MaxMessageBytes = 30 << 20
|
||||
|
||||
type Info struct {
|
||||
NameValue string `json:"name"`
|
||||
SizeValue int64 `json:"size"`
|
||||
ModeValue uint32 `json:"mode"`
|
||||
Modified time.Time `json:"modified"`
|
||||
}
|
||||
|
||||
func (i Info) Name() string { return i.NameValue }
|
||||
func (i Info) Size() int64 { return i.SizeValue }
|
||||
func (i Info) Mode() fs.FileMode { return fs.FileMode(i.ModeValue) }
|
||||
func (i Info) ModTime() time.Time { return i.Modified }
|
||||
func (i Info) IsDir() bool { return i.Mode().IsDir() }
|
||||
func (i Info) Sys() any { return nil }
|
||||
func (i Info) Type() fs.FileMode { return i.Mode().Type() }
|
||||
func (i Info) Info() (fs.FileInfo, error) { return i, nil }
|
||||
func info(i fs.FileInfo) Info { return Info{i.Name(), i.Size(), uint32(i.Mode()), i.ModTime()} }
|
||||
|
||||
type Request struct {
|
||||
HostName string `json:"hostName"`
|
||||
Operation string `json:"operation"`
|
||||
Path string `json:"path"`
|
||||
To string `json:"to,omitempty"`
|
||||
Data []byte `json:"data,omitempty"`
|
||||
Overwrite bool `json:"overwrite,omitempty"`
|
||||
Mode uint32 `json:"mode,omitempty"`
|
||||
Budget uint64 `json:"budget,omitempty"`
|
||||
}
|
||||
type Response struct {
|
||||
Info Info `json:"info"`
|
||||
Entries []Info `json:"entries,omitempty"`
|
||||
Data []byte `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Trash []TrashEntry `json:"trash,omitempty"`
|
||||
}
|
||||
type Call func(context.Context, Request) (Response, error)
|
||||
type Root struct {
|
||||
ctx context.Context
|
||||
host string
|
||||
call Call
|
||||
}
|
||||
|
||||
func New(ctx context.Context, host string, call Call) *Root { return &Root{ctx, host, call} }
|
||||
func (r *Root) Close() error { return nil }
|
||||
func (r *Root) Action(q Request) (Response, error) { return r.execute(q) }
|
||||
func (r *Root) execute(q Request) (Response, error) {
|
||||
q.HostName = r.host
|
||||
out, err := r.call(r.ctx, q)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
switch out.Error {
|
||||
case "":
|
||||
case "not_found":
|
||||
err = fs.ErrNotExist
|
||||
case "exists":
|
||||
err = fs.ErrExist
|
||||
case "denied":
|
||||
err = fs.ErrPermission
|
||||
default:
|
||||
err = errors.New("文件操作失败")
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
func (r *Root) Lstat(name string) (fs.FileInfo, error) {
|
||||
out, err := r.execute(Request{Operation: "stat", Path: name})
|
||||
return out.Info, err
|
||||
}
|
||||
func (r *Root) Open(name string) (*File, error) {
|
||||
out, err := r.execute(Request{Operation: "read", Path: name})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &File{reader: bytes.NewReader(out.Data), info: out.Info, entries: out.Entries}, nil
|
||||
}
|
||||
func (r *Root) OpenFile(name string, flag int, mode fs.FileMode) (*File, error) {
|
||||
if flag&os.O_WRONLY == 0 {
|
||||
return nil, fs.ErrPermission
|
||||
}
|
||||
overwrite := flag&os.O_TRUNC != 0
|
||||
return &File{root: r, name: name, write: true, overwrite: overwrite, mode: mode}, nil
|
||||
}
|
||||
func (r *Root) MkdirAll(name string, mode fs.FileMode) error {
|
||||
_, err := r.execute(Request{Operation: "mkdir", Path: name, Mode: uint32(mode.Perm())})
|
||||
return err
|
||||
}
|
||||
func (r *Root) Rename(from, to string) error {
|
||||
_, err := r.execute(Request{Operation: "rename", Path: from, To: to})
|
||||
return err
|
||||
}
|
||||
func (r *Root) Remove(name string) error {
|
||||
_, err := r.execute(Request{Operation: "remove", Path: name})
|
||||
return err
|
||||
}
|
||||
func (r *Root) RemoveAll(name string) error {
|
||||
if name != ".sea-trash" {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
_, err := r.execute(Request{Operation: "empty_trash", Path: name})
|
||||
return err
|
||||
}
|
||||
|
||||
type File struct {
|
||||
root *Root
|
||||
name string
|
||||
write, overwrite, closed bool
|
||||
mode fs.FileMode
|
||||
buffer bytes.Buffer
|
||||
reader *bytes.Reader
|
||||
info Info
|
||||
entries []Info
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (f *File) Abort() { f.closed = true; f.buffer.Reset() }
|
||||
func (f *File) Stat() (fs.FileInfo, error) { return f.info, nil }
|
||||
func (f *File) Read(b []byte) (int, error) {
|
||||
if f.reader == nil {
|
||||
return 0, fs.ErrPermission
|
||||
}
|
||||
return f.reader.Read(b)
|
||||
}
|
||||
func (f *File) Seek(offset int64, whence int) (int64, error) {
|
||||
if f.reader == nil {
|
||||
return 0, fs.ErrPermission
|
||||
}
|
||||
return f.reader.Seek(offset, whence)
|
||||
}
|
||||
func (f *File) Write(b []byte) (int, error) {
|
||||
if f.closed || !f.write {
|
||||
return 0, fs.ErrPermission
|
||||
}
|
||||
if len(b) > MaxFileBytes-f.buffer.Len() {
|
||||
return 0, errors.New("文件超过20 MB")
|
||||
}
|
||||
return f.buffer.Write(b)
|
||||
}
|
||||
func (f *File) ReadDir(n int) ([]fs.DirEntry, error) {
|
||||
if !f.info.IsDir() {
|
||||
return nil, errors.New("不是目录")
|
||||
}
|
||||
take := len(f.entries)
|
||||
if n > 0 && n < take {
|
||||
take = n
|
||||
}
|
||||
out := make([]fs.DirEntry, take)
|
||||
for i := range out {
|
||||
out[i] = f.entries[i]
|
||||
}
|
||||
f.entries = f.entries[take:]
|
||||
if take == 0 && n > 0 {
|
||||
return out, io.EOF
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (f *File) Close() error {
|
||||
if f.closed {
|
||||
return f.closeErr
|
||||
}
|
||||
f.closed = true
|
||||
if f.write {
|
||||
_, f.closeErr = f.root.execute(Request{Operation: "write", Path: f.name, Data: f.buffer.Bytes(), Overwrite: f.overwrite, Mode: uint32(f.mode.Perm())})
|
||||
}
|
||||
return f.closeErr
|
||||
}
|
||||
|
||||
func validName(name string) bool {
|
||||
return name != "" && !strings.HasPrefix(name, "/") && !filepath.IsAbs(name) && !strings.ContainsAny(name, ":\\\x00\r\n") && name != ".." && !strings.HasPrefix(filepath.ToSlash(filepath.Clean(name)), "../")
|
||||
}
|
||||
func check(root *os.Root, name string) error {
|
||||
if !validName(name) {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
parts := strings.Split(filepath.ToSlash(filepath.Clean(name)), "/")
|
||||
p := ""
|
||||
for _, part := range parts {
|
||||
p = filepath.Join(p, part)
|
||||
i, err := root.Lstat(p)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if i.Mode()&fs.ModeSymlink != 0 {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func Execute(rootPath string, q Request) (out Response) {
|
||||
err := execute(rootPath, q, &out)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
out.Error = "not_found"
|
||||
case errors.Is(err, fs.ErrExist):
|
||||
out.Error = "exists"
|
||||
case errors.Is(err, fs.ErrPermission):
|
||||
out.Error = "denied"
|
||||
default:
|
||||
out.Error = "failed"
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
func execute(rootPath string, q Request, out *Response) error {
|
||||
root, err := os.OpenRoot(rootPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
if isAdvanced(q.Operation) {
|
||||
return advanced(root, q, out)
|
||||
}
|
||||
if (IsProtectedPath(q.Path) && !(q.Operation == "empty_trash" && q.Path == ".sea-trash")) || (q.To != "" && IsProtectedPath(q.To)) {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if err = check(root, q.Path); err != nil {
|
||||
return err
|
||||
}
|
||||
switch q.Operation {
|
||||
case "stat":
|
||||
i, e := root.Lstat(q.Path)
|
||||
if e == nil {
|
||||
out.Info = info(i)
|
||||
}
|
||||
return e
|
||||
case "read":
|
||||
f, e := root.Open(q.Path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer f.Close()
|
||||
i, e := f.Stat()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
out.Info = info(i)
|
||||
if i.IsDir() {
|
||||
entries, e := f.ReadDir(10001)
|
||||
if e != nil && e != io.EOF {
|
||||
return e
|
||||
}
|
||||
if len(entries) > 10000 {
|
||||
return errors.New("目录文件过多")
|
||||
}
|
||||
out.Entries = []Info{}
|
||||
for _, entry := range entries {
|
||||
v, e := entry.Info()
|
||||
if e == nil {
|
||||
out.Entries = append(out.Entries, info(v))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !i.Mode().IsRegular() || i.Size() > MaxFileBytes {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
out.Data, e = io.ReadAll(io.LimitReader(f, MaxFileBytes+1))
|
||||
if len(out.Data) > MaxFileBytes {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
return e
|
||||
case "write":
|
||||
if q.Path == "." || len(q.Data) > MaxFileBytes {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if i, e := root.Lstat(q.Path); e == nil {
|
||||
if !q.Overwrite {
|
||||
return fs.ErrExist
|
||||
}
|
||||
if !i.Mode().IsRegular() {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
} else if !errors.Is(e, fs.ErrNotExist) {
|
||||
return e
|
||||
}
|
||||
// Stage in the destination directory so interruptions preserve old contents.
|
||||
random := make([]byte, 16)
|
||||
if _, err = rand.Read(random); err != nil {
|
||||
return err
|
||||
}
|
||||
temp := filepath.Join(filepath.Dir(q.Path), ".sea-upload-"+hex.EncodeToString(random))
|
||||
f, e := root.OpenFile(temp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer root.Remove(temp)
|
||||
_, e = f.Write(q.Data)
|
||||
if e == nil {
|
||||
e = f.Sync()
|
||||
}
|
||||
closeErr := f.Close()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
if !q.Overwrite {
|
||||
if _, e = root.Lstat(q.Path); e == nil {
|
||||
return fs.ErrExist
|
||||
}
|
||||
if !errors.Is(e, fs.ErrNotExist) {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return root.Rename(temp, q.Path)
|
||||
case "mkdir":
|
||||
if q.Path == "." {
|
||||
return nil
|
||||
}
|
||||
return root.MkdirAll(q.Path, 0770)
|
||||
case "rename":
|
||||
if q.Path == "." || !strings.HasPrefix(q.To, ".sea-trash/") {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if err = check(root, q.To); err != nil {
|
||||
return err
|
||||
}
|
||||
return root.Rename(q.Path, q.To)
|
||||
case "remove":
|
||||
if q.Path == "." {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
return root.Remove(q.Path)
|
||||
case "empty_trash":
|
||||
if q.Path != ".sea-trash" {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
return root.RemoveAll(q.Path)
|
||||
default:
|
||||
return fs.ErrPermission
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package nodefiles
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBufferedWritesRequireSuccessfulCommit(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "index.txt")
|
||||
if err := os.WriteFile(file, []byte("original"), 0660); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
root := New(context.Background(), "sv0123456789", func(_ context.Context, q Request) (Response, error) { return Execute(dir, q), nil })
|
||||
f, _ := root.OpenFile("index.txt", os.O_WRONLY|os.O_TRUNC, 0660)
|
||||
_, _ = f.Write([]byte("partial"))
|
||||
f.Abort()
|
||||
_ = f.Close()
|
||||
raw, _ := os.ReadFile(file)
|
||||
if string(raw) != "original" {
|
||||
t.Fatal("aborted upload changed original")
|
||||
}
|
||||
f, _ = root.OpenFile("index.txt", os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0660)
|
||||
_, _ = f.Write([]byte("new"))
|
||||
if err := f.Close(); !errors.Is(err, fs.ErrExist) {
|
||||
t.Fatalf("exclusive write: %v", err)
|
||||
}
|
||||
f, _ = root.OpenFile("index.txt", os.O_WRONLY|os.O_TRUNC, 0660)
|
||||
_, _ = f.Write([]byte("committed"))
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ = os.ReadFile(file)
|
||||
if string(raw) != "committed" {
|
||||
t.Fatal("successful commit missing")
|
||||
}
|
||||
}
|
||||
func TestSymlinkEscapeDenied(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
_ = os.WriteFile(filepath.Join(outside, "secret"), []byte("marker"), 0600)
|
||||
if err := os.Symlink(outside, filepath.Join(dir, "escape")); err != nil {
|
||||
t.Skip("symlinks unavailable")
|
||||
}
|
||||
out := Execute(dir, Request{Operation: "read", Path: "escape/secret"})
|
||||
if out.Error != "denied" || len(out.Data) != 0 {
|
||||
t.Fatal("symlink escape read")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
package nodefiles
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxExpanded = 256 << 20
|
||||
|
||||
type TrashEntry struct {
|
||||
ID string `json:"id"`
|
||||
OriginalPath string `json:"originalPath"`
|
||||
Name string `json:"name"`
|
||||
DeletedAt time.Time `json:"deletedAt"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
func isAdvanced(op string) bool {
|
||||
switch op {
|
||||
case "move", "copy", "zip", "extract", "trash", "trash_list", "restore":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsProtectedPath identifies platform-owned configuration and runtime paths.
|
||||
func IsProtectedPath(name string) bool {
|
||||
return protected(path.Clean(strings.ReplaceAll(name, "\\", "/")))
|
||||
}
|
||||
|
||||
func protected(name string) bool {
|
||||
for _, v := range strings.Split(name, "/") {
|
||||
if v == ".sea-runtime" || v == ".user.ini" || v == ".sea-trash" || strings.HasPrefix(v, ".sea-op-") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func userPath(root *os.Root, name string) error {
|
||||
if name == "." || path.Clean(name) != name || protected(name) {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
return check(root, name)
|
||||
}
|
||||
func absent(root *os.Root, name string) error {
|
||||
if _, e := root.Lstat(name); e == nil {
|
||||
return fs.ErrExist
|
||||
} else if !errors.Is(e, fs.ErrNotExist) {
|
||||
return e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func opID() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
_, e := rand.Read(b)
|
||||
return hex.EncodeToString(b), e
|
||||
}
|
||||
func advanced(root *os.Root, q Request, out *Response) error {
|
||||
if q.Operation == "trash_list" {
|
||||
return listTrash(root, out)
|
||||
}
|
||||
if q.Operation == "restore" {
|
||||
if len(q.Path) != 32 || strings.Trim(q.Path, "0123456789abcdef") != "" {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if e := userPath(root, q.To); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := absent(root, q.To); e != nil {
|
||||
return e
|
||||
}
|
||||
from := ".sea-trash/" + q.Path
|
||||
if e := check(root, from); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := root.MkdirAll(path.Dir(q.To), 0770); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := root.Rename(from, q.To); e != nil {
|
||||
return e
|
||||
}
|
||||
_ = root.Remove(from + ".json")
|
||||
return nil
|
||||
}
|
||||
if e := userPath(root, q.Path); e != nil {
|
||||
return e
|
||||
}
|
||||
if q.Operation == "trash" {
|
||||
id, e := opID()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = root.MkdirAll(".sea-trash", 0770); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = check(root, ".sea-trash"); e != nil {
|
||||
return e
|
||||
}
|
||||
i, e := root.Lstat(q.Path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
entry := TrashEntry{ID: id, OriginalPath: q.Path, Name: path.Base(q.Path), DeletedAt: time.Now().UTC(), Size: i.Size()}
|
||||
raw, _ := json.Marshal(entry)
|
||||
f, e := root.OpenFile(".sea-trash/"+id+".json", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = f.Write(raw)
|
||||
closeErr := f.Close()
|
||||
if e == nil {
|
||||
e = closeErr
|
||||
}
|
||||
if e == nil {
|
||||
e = root.Rename(q.Path, ".sea-trash/"+id)
|
||||
}
|
||||
if e != nil {
|
||||
root.Remove(".sea-trash/" + id + ".json")
|
||||
}
|
||||
return e
|
||||
}
|
||||
if e := userPath(root, q.To); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := absent(root, q.To); e != nil {
|
||||
return e
|
||||
}
|
||||
if q.To == q.Path || strings.HasPrefix(q.To, q.Path+"/") {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if q.Operation == "move" {
|
||||
return root.Rename(q.Path, q.To)
|
||||
}
|
||||
budget := q.Budget
|
||||
if budget > maxExpanded {
|
||||
budget = maxExpanded
|
||||
}
|
||||
id, e := opID()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
stage := path.Join(path.Dir(q.To), ".sea-op-"+id)
|
||||
defer root.RemoveAll(stage)
|
||||
switch q.Operation {
|
||||
case "copy":
|
||||
if e = copyTree(root, q.Path, stage, &budget, new(int)); e != nil {
|
||||
return e
|
||||
}
|
||||
case "zip":
|
||||
f, e := root.OpenFile(stage, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
z := zip.NewWriter(&budgetWriter{w: f, left: budget})
|
||||
e = zipTree(root, z, q.Path, path.Base(q.Path), new(int), newZipBudget())
|
||||
if closeErr := z.Close(); e == nil {
|
||||
e = closeErr
|
||||
}
|
||||
if closeErr := f.Close(); e == nil {
|
||||
e = closeErr
|
||||
}
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
case "extract":
|
||||
f, e := root.Open(q.Path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
i, e := f.Stat()
|
||||
if e != nil || !i.Mode().IsRegular() || i.Size() > MaxFileBytes {
|
||||
f.Close()
|
||||
return fs.ErrPermission
|
||||
}
|
||||
data, e := io.ReadAll(io.LimitReader(f, MaxFileBytes+1))
|
||||
f.Close()
|
||||
if e != nil || len(data) > MaxFileBytes {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
z, e := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if len(z.File) > 10000 {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if e = root.Mkdir(stage, 0770); e != nil {
|
||||
return e
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, entry := range z.File {
|
||||
name := strings.TrimSuffix(entry.Name, "/")
|
||||
if name == "" || path.Clean(name) != name || !validName(name) || strings.HasPrefix(name, "/") || protected(name) || entry.Mode()&fs.ModeSymlink != 0 || (!entry.Mode().IsRegular() && !entry.FileInfo().IsDir()) || seen[name] {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
seen[name] = true
|
||||
target := path.Join(stage, name)
|
||||
if e = check(root, target); e != nil {
|
||||
return e
|
||||
}
|
||||
if entry.FileInfo().IsDir() {
|
||||
if e = root.MkdirAll(target, 0770); e != nil {
|
||||
return e
|
||||
}
|
||||
continue
|
||||
}
|
||||
if entry.UncompressedSize64 > budget {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if e = root.MkdirAll(path.Dir(target), 0770); e != nil {
|
||||
return e
|
||||
}
|
||||
input, e := entry.Open()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
output, e := root.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
|
||||
if e != nil {
|
||||
input.Close()
|
||||
return e
|
||||
}
|
||||
n, e := io.Copy(output, io.LimitReader(input, int64(budget)+1))
|
||||
input.Close()
|
||||
output.Close()
|
||||
if e != nil || uint64(n) > budget {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
budget -= uint64(n)
|
||||
}
|
||||
default:
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if e = check(root, q.To); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = absent(root, q.To); e != nil {
|
||||
return e
|
||||
}
|
||||
return root.Rename(stage, q.To)
|
||||
}
|
||||
|
||||
type budgetWriter struct {
|
||||
w io.Writer
|
||||
left uint64
|
||||
}
|
||||
|
||||
func (w *budgetWriter) Write(b []byte) (int, error) {
|
||||
if uint64(len(b)) > w.left {
|
||||
return 0, fs.ErrPermission
|
||||
}
|
||||
n, e := w.w.Write(b)
|
||||
w.left -= uint64(n)
|
||||
return n, e
|
||||
}
|
||||
func copyTree(root *os.Root, from, to string, budget *uint64, count *int) error {
|
||||
*count++
|
||||
if *count > 10000 {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if e := check(root, from); e != nil {
|
||||
return e
|
||||
}
|
||||
i, e := root.Lstat(from)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if i.IsDir() {
|
||||
if e = root.Mkdir(to, 0770); e != nil {
|
||||
return e
|
||||
}
|
||||
dir, e := root.Open(from)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
entries, e := dir.ReadDir(10001)
|
||||
dir.Close()
|
||||
if e != nil && e != io.EOF {
|
||||
return e
|
||||
}
|
||||
for _, entry := range entries {
|
||||
source := path.Join(from, entry.Name())
|
||||
if protected(source) {
|
||||
continue
|
||||
}
|
||||
if e = copyTree(root, source, path.Join(to, entry.Name()), budget, count); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !i.Mode().IsRegular() || uint64(i.Size()) > *budget {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
input, e := root.Open(from)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer input.Close()
|
||||
output, e := root.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
n, e := io.Copy(output, io.LimitReader(input, int64(*budget)+1))
|
||||
output.Close()
|
||||
if e != nil || uint64(n) > *budget {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
*budget -= uint64(n)
|
||||
return nil
|
||||
}
|
||||
func zipTree(root *os.Root, z *zip.Writer, name, archiveName string, count *int, inputBudget *uint64) error {
|
||||
*count++
|
||||
if *count > 10000 {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if e := check(root, name); e != nil {
|
||||
return e
|
||||
}
|
||||
i, e := root.Lstat(name)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if i.IsDir() {
|
||||
dir, e := root.Open(name)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
entries, e := dir.ReadDir(10001)
|
||||
dir.Close()
|
||||
if e != nil && e != io.EOF {
|
||||
return e
|
||||
}
|
||||
for _, entry := range entries {
|
||||
source := path.Join(name, entry.Name())
|
||||
if protected(source) {
|
||||
continue
|
||||
}
|
||||
if e = zipTree(root, z, source, path.Join(archiveName, entry.Name()), count, inputBudget); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !i.Mode().IsRegular() {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
if uint64(i.Size()) > *inputBudget {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
*inputBudget -= uint64(i.Size())
|
||||
header, e := zip.FileInfoHeader(i)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
header.Name = archiveName
|
||||
header.Method = zip.Deflate
|
||||
dst, e := z.CreateHeader(header)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
f, e := root.Open(name)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer f.Close()
|
||||
_, e = io.Copy(dst, io.LimitReader(f, maxExpanded+1))
|
||||
return e
|
||||
}
|
||||
func listTrash(root *os.Root, out *Response) error {
|
||||
out.Trash = []TrashEntry{}
|
||||
if e := check(root, ".sea-trash"); e != nil {
|
||||
return e
|
||||
}
|
||||
dir, e := root.Open(".sea-trash")
|
||||
if errors.Is(e, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
entries, e := dir.ReadDir(10001)
|
||||
dir.Close()
|
||||
if e != nil && e != io.EOF {
|
||||
return e
|
||||
}
|
||||
if len(entries) > 10000 {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !strings.HasSuffix(entry.Name(), ".json") {
|
||||
continue
|
||||
}
|
||||
name := ".sea-trash/" + entry.Name()
|
||||
if check(root, name) != nil {
|
||||
continue
|
||||
}
|
||||
f, e := root.Open(name)
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
var v TrashEntry
|
||||
e = json.NewDecoder(io.LimitReader(f, 4096)).Decode(&v)
|
||||
f.Close()
|
||||
if e == nil && len(v.ID) == 32 && strings.Trim(v.ID, "0123456789abcdef") == "" && entry.Name() == v.ID+".json" && userPath(root, v.OriginalPath) == nil {
|
||||
if _, e = root.Lstat(".sea-trash/" + v.ID); e == nil {
|
||||
out.Trash = append(out.Trash, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newZipBudget() *uint64 { v := uint64(maxExpanded); return &v }
|
||||
@@ -0,0 +1,77 @@
|
||||
package nodefiles
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFileOperationsRoundTripAndQuota(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
os.Mkdir(filepath.Join(dir, "source"), 0770)
|
||||
os.WriteFile(filepath.Join(dir, "source", "hello.txt"), []byte("security-marker"), 0660)
|
||||
call := func(q Request) Response { return Execute(dir, q) }
|
||||
if v := call(Request{Operation: "copy", Path: "source", To: "too-small", Budget: 2}); v.Error == "" {
|
||||
t.Fatal("copy ignored remaining quota")
|
||||
}
|
||||
if _, e := os.Stat(filepath.Join(dir, "too-small")); !os.IsNotExist(e) {
|
||||
t.Fatal("failed copy left target")
|
||||
}
|
||||
for _, q := range []Request{{Operation: "copy", Path: "source", To: "copy", Budget: 1024}, {Operation: "move", Path: "copy", To: "moved"}, {Operation: "zip", Path: "source", To: "source.zip", Budget: 4096}, {Operation: "extract", Path: "source.zip", To: "expanded", Budget: 4096}, {Operation: "trash", Path: "moved"}} {
|
||||
if v := call(q); v.Error != "" {
|
||||
t.Fatalf("%s: %s", q.Operation, v.Error)
|
||||
}
|
||||
}
|
||||
list := call(Request{Operation: "trash_list"})
|
||||
if list.Error != "" || len(list.Trash) != 1 || list.Trash[0].OriginalPath != "moved" {
|
||||
t.Fatalf("trash %+v", list)
|
||||
}
|
||||
if v := call(Request{Operation: "restore", Path: list.Trash[0].ID, To: "restored"}); v.Error != "" {
|
||||
t.Fatal(v.Error)
|
||||
}
|
||||
raw, e := os.ReadFile(filepath.Join(dir, "restored", "hello.txt"))
|
||||
if e != nil || string(raw) != "security-marker" {
|
||||
t.Fatal("restoration lost content")
|
||||
}
|
||||
if v := call(Request{Operation: "copy", Path: "source", To: "source/nested", Budget: 100}); v.Error == "" {
|
||||
t.Fatal("recursive copy accepted")
|
||||
}
|
||||
for _, name := range []string{".sea-runtime", ".user.ini", ".sea-trash/abc", "../outside", "/etc/passwd"} {
|
||||
if v := call(Request{Operation: "copy", Path: "source", To: name, Budget: 4096}); v.Error == "" {
|
||||
t.Fatalf("reserved destination %s accepted", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestExtractRejectsZipSlipSymlinksAndBombs(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
mode os.FileMode
|
||||
data string
|
||||
budget uint64
|
||||
}{{"../escape", 0660, "x", 1024}, {"/escape", 0660, "x", 1024}, {".sea-runtime/secret", 0660, "x", 1024}, {"link", os.ModeSymlink | 0777, "/etc/passwd", 1024}, {"large.txt", 0660, "xxxxxxxxxxxxxxxxxxxxxxxxx", 2}} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
var buf bytes.Buffer
|
||||
z := zip.NewWriter(&buf)
|
||||
header := &zip.FileHeader{Name: test.name, Method: zip.Deflate}
|
||||
header.SetMode(test.mode)
|
||||
f, _ := z.CreateHeader(header)
|
||||
f.Write([]byte(test.data))
|
||||
z.Close()
|
||||
os.WriteFile(filepath.Join(dir, "bad.zip"), buf.Bytes(), 0660)
|
||||
v := Execute(dir, Request{Operation: "extract", Path: "bad.zip", To: "target", Budget: test.budget})
|
||||
if v.Error == "" {
|
||||
t.Fatal("unsafe archive accepted")
|
||||
}
|
||||
if _, e := os.Stat(filepath.Join(dir, "target")); !os.IsNotExist(e) {
|
||||
t.Fatal("failed extraction published target")
|
||||
}
|
||||
stages, _ := filepath.Glob(filepath.Join(dir, ".sea-op-*"))
|
||||
if len(stages) > 0 {
|
||||
t.Fatal("failed extraction left staging files")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package nodefiles
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPlatformConfigurationCannotBeReadOrReplaced(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(root, ".sea-runtime"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := []byte("PLATFORM_CONFIGURATION_SENTINEL")
|
||||
for _, name := range []string{".user.ini", ".sea-runtime/launch.env"} {
|
||||
if err := os.WriteFile(filepath.Join(root, name), original, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "ordinary.txt"), []byte("ordinary"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{".user.ini", ".sea-runtime/launch.env", "new/../.sea-runtime/launch.env"} {
|
||||
for _, operation := range []string{"read", "stat", "write", "remove", "mkdir"} {
|
||||
out := Execute(root, Request{Operation: operation, Path: name, Data: []byte("replaced"), Overwrite: true})
|
||||
if out.Error != "denied" {
|
||||
t.Fatalf("%s %s: %+v", operation, name, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
if out := Execute(root, Request{Operation: "rename", Path: "ordinary.txt", To: ".user.ini"}); out.Error != "denied" {
|
||||
t.Fatalf("rename onto protected file accepted: %+v", out)
|
||||
}
|
||||
for _, name := range []string{".user.ini", ".sea-runtime/launch.env"} {
|
||||
content, err := os.ReadFile(filepath.Join(root, name))
|
||||
if err != nil || string(content) != string(original) {
|
||||
t.Fatal("platform file changed", name, err)
|
||||
}
|
||||
}
|
||||
if out := Execute(root, Request{Operation: "read", Path: "ordinary.txt"}); out.Error != "" || string(out.Data) != "ordinary" {
|
||||
t.Fatal("ordinary file read blocked", out.Error)
|
||||
}
|
||||
// Trash is still accessible only through its dedicated API, including emptying.
|
||||
if err := os.Mkdir(filepath.Join(root, ".sea-trash"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out := Execute(root, Request{Operation: "empty_trash", Path: ".sea-trash"}); out.Error != "" {
|
||||
t.Fatal("dedicated trash cleanup blocked", out.Error)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user