package api import ( "archive/zip" "bytes" "io" "net/http" "net/http/httptest" "os" "path/filepath" "reflect" "testing" "chfs-ng/internal/auth" "chfs-ng/internal/storage" ) func TestFolderDownloadModes(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "parent", "child"), 0o755); err != nil { t.Fatal(err) } for _, p := range []string{ filepath.Join(root, "parent", "a.txt"), filepath.Join(root, "parent", "child", "b.txt"), } { if err := os.WriteFile(p, []byte("x"), 0o644); err != nil { t.Fatal(err) } } mk := func(mode string) *Server { return &Server{ Store: storage.Local{Root: root}, Auth: &auth.Manager{ Accounts: map[string]*auth.Account{}, Guest: &auth.Account{Mask: auth.Read | auth.Write | auth.Delete}, }, FolderDownload: mode, } } for _, tc := range []struct { mode, path string want int }{ {"disable", "parent", http.StatusForbidden}, {"leaf", "parent", http.StatusForbidden}, {"leaf", "parent/child", http.StatusOK}, {"enable", "parent", http.StatusOK}, } { t.Run(tc.mode+"-"+tc.path, func(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/chfs/downloaddir/"+tc.path, nil) w := httptest.NewRecorder() mk(tc.mode).Handler().ServeHTTP(w, req) if w.Code != tc.want { t.Fatalf("status=%d want=%d body=%s", w.Code, tc.want, w.Body.String()) } }) } } func TestFolderDownloadZipContainsOnlyReadableFiles(t *testing.T) { root := t.TempDir() if err := os.MkdirAll(filepath.Join(root, "parent", "child"), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(root, "parent", "a.txt"), []byte("A"), 0o644); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(root, "parent", "child", "b.txt"), []byte("B"), 0o644); err != nil { t.Fatal(err) } s := &Server{Store: storage.Local{Root: root}, Auth: &auth.Manager{Accounts: map[string]*auth.Account{}, Guest: &auth.Account{Mask: auth.Read | auth.Write | auth.Delete}}, FolderDownload: "enable"} r := httptest.NewRequest(http.MethodGet, "/chfs/downloaddir/parent", nil) w := httptest.NewRecorder() s.Handler().ServeHTTP(w, r) if w.Code != http.StatusOK { t.Fatalf("status=%d", w.Code) } zr, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len())) if err != nil { t.Fatalf("invalid zip: %v", err) } got := map[string]string{} for _, f := range zr.File { body, err := f.Open() if err != nil { t.Fatal(err) } b, err := io.ReadAll(body) body.Close() if err != nil { t.Fatal(err) } got[f.Name] = string(b) } want := map[string]string{"a.txt": "A", "child/b.txt": "B"} if !reflect.DeepEqual(got, want) { t.Fatalf("zip entries=%#v want=%#v", got, want) } }