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") } }) } }