package api import ( "archive/zip" "bytes" "encoding/json" "image" "image/color" "image/png" "io" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "testing" "time" "github.com/vblogio/upandown/internal/auth" "github.com/vblogio/upandown/internal/storage" "github.com/vblogio/upandown/internal/tokens" ) // fixture assemble le même graphe que cmd/server (mode local), sans ouvrir de port. type fixture struct { root string t *testing.T h http.Handler handler *Handler accounts *auth.Accounts tokens *tokens.Store spaces *storage.Spaces } func newFixture(t *testing.T, mutate func(*storage.Store, *storage.Spaces)) *fixture { t.Helper() dir := t.TempDir() store, err := storage.New(dir) if err != nil { t.Fatal(err) } spaces := storage.NewSpaces(store) if mutate != nil { mutate(store, spaces) } accounts, err := auth.OpenAccounts(dir) if err != nil { t.Fatal(err) } h := (&Handler{Store: store, Spaces: spaces, Mode: "local", Accounts: accounts}).Init() a := auth.New(&auth.Auth{ Accounts: accounts, Sessions: auth.NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false), Local: true, Registration: func() string { st, _ := store.ReadSettings() return st.Registration }, }) h.Auth = a mux := http.NewServeMux() a.Register(mux) h.Register(mux) tokenStore, err := tokens.Open(dir) if err != nil { t.Fatal(err) } ts := &tokens.Server{Store: tokenStore, UserID: UserID, Resolve: func(id string) (*auth.User, bool) { acc, ok := accounts.Get(id) if !ok || acc.Status != auth.StatusActive { return nil, false } u := acc.User() return &u, true }} ts.Register(mux) public := func(p string) bool { return strings.HasPrefix(p, "/api/public/") || p == "/api/me" || p == "/api/logo" } return &fixture{root: dir, t: t, h: ts.Middleware(a.Middleware(mux, public), mux), handler: h, accounts: accounts, tokens: tokenStore, spaces: spaces} } type session struct { f *fixture cookies map[string]*http.Cookie bearer string } func (f *fixture) session() *session { return &session{f: f, cookies: map[string]*http.Cookie{}} } func (s *session) do(method, target string, body io.Reader, hdr ...string) *httptest.ResponseRecorder { s.f.t.Helper() r := httptest.NewRequest(method, target, body) for i := 0; i+1 < len(hdr); i += 2 { r.Header.Set(hdr[i], hdr[i+1]) } for _, c := range s.cookies { r.AddCookie(c) } if s.bearer != "" { r.Header.Set("Authorization", "Bearer "+s.bearer) } w := httptest.NewRecorder() s.f.h.ServeHTTP(w, r) for _, c := range w.Result().Cookies() { if c.MaxAge < 0 { delete(s.cookies, c.Name) } else { s.cookies[c.Name] = c } } return w } func (s *session) json(method, target string, v any) *httptest.ResponseRecorder { b, _ := json.Marshal(v) return s.do(method, target, bytes.NewReader(b), "Content-Type", "application/json") } func (s *session) put(path, content string, query ...string) *httptest.ResponseRecorder { q := "" for _, x := range query { q += "&" + x } return s.do("PUT", "/api/file?path="+url.QueryEscape(path)+q, strings.NewReader(content)) } func (s *session) get(target string, hdr ...string) *httptest.ResponseRecorder { return s.do("GET", target, nil, hdr...) } func decode[T any](t *testing.T, w *httptest.ResponseRecorder) T { t.Helper() var v T if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil { t.Fatalf("JSON illisible (%d) : %v : %s", w.Code, err, w.Body) } return v } func want(t *testing.T, w *httptest.ResponseRecorder, code int) { t.Helper() if w.Code != code { t.Fatalf("code %d (attendu %d) : %s", w.Code, code, strings.TrimSpace(w.Body.String())) } } // register crée un compte par l'inscription et renvoie sa session. func (f *fixture) register(name string) *session { f.t.Helper() s := f.session() w := s.json("POST", "/auth/local/register", map[string]string{"username": name, "password": "mot-de-passe-" + name}) if w.Code != 201 && w.Code != 202 { f.t.Fatalf("inscription de %s : %d %s", name, w.Code, w.Body) } return s } func (f *fixture) login(name string) *session { f.t.Helper() s := f.session() want(f.t, s.json("POST", "/auth/local/login", map[string]string{"username": name, "password": "mot-de-passe-" + name}), 200) return s } func makePNG(t *testing.T, w, h int) string { t.Helper() img := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { img.Set(x, y, color.RGBA{uint8(x), uint8(y), 99, 255}) } } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { t.Fatal(err) } return buf.String() } func TestAnonymousAndSetup(t *testing.T) { f := newFixture(t, nil) anon := f.session() want(t, anon.get("/api/list?path="), 401) want(t, anon.put("a.txt", "x"), 401) me := decode[meResponse](t, anon.get("/api/me")) if !me.Setup || me.User != nil || !me.Local || me.Registration != "closed" { t.Errorf("/api/me avant installation : %+v", me) } admin := f.register("alice") me = decode[meResponse](t, admin.get("/api/me")) if me.Setup || me.User == nil || me.User.ID != "alice" || !me.Admin || me.Usage == nil { t.Errorf("/api/me après installation : %+v", me) } // Inscriptions fermées : le second compte est refusé. w := f.session().json("POST", "/auth/local/register", map[string]string{"username": "bob", "password": "mot-de-passe-bob"}) want(t, w, 403) } func TestUploadDownloadRange(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") want(t, s.put("docs/rapport.pdf", "%PDF-0123456789"), 200) w := s.get("/api/file?path=docs/rapport.pdf") want(t, w, 200) if w.Body.String() != "%PDF-0123456789" || !strings.HasPrefix(w.Header().Get("Content-Disposition"), "attachment;") { t.Errorf("téléchargement : %q %v", w.Body, w.Header()) } w = s.get("/api/file?path=docs/rapport.pdf", "Range", "bytes=5-9") want(t, w, 206) if w.Body.String() != "01234" { t.Errorf("Range = %q", w.Body) } // Remplacement conditionnel par ETag, puis lecture conditionnelle. etag := s.get("/api/file?path=docs/rapport.pdf").Header().Get("ETag") want(t, s.get("/api/file?path=docs/rapport.pdf", "If-None-Match", etag), 304) // Conflit. want(t, s.put("docs/rapport.pdf", "autre"), 409) r := s.put("docs/rapport.pdf", "autre", "conflict=rename") want(t, r, 200) if e := decode[storage.Entry](t, r); e.Path != "docs/rapport (2).pdf" { t.Errorf("rename = %q", e.Path) } want(t, s.put("docs/rapport.pdf", "v2", "conflict=overwrite"), 200) want(t, s.put("docs/rapport.pdf", "v3", "conflict=n'importe-quoi"), 400) vs := decode[[]storage.Version](t, s.get("/api/history?path=docs/rapport.pdf")) if len(vs) != 1 { t.Fatalf("versions = %v", vs) } old := s.get("/api/history/version?path=docs/rapport.pdf&id=" + vs[0].ID) if old.Body.String() != "%PDF-0123456789" { t.Errorf("ancienne version = %q", old.Body) } want(t, s.json("POST", "/api/history/restore", map[string]string{"path": "docs/rapport.pdf", "id": vs[0].ID}), 200) if s.get("/api/file?path=docs/rapport.pdf").Body.String() != "%PDF-0123456789" { t.Error("restauration") } } func TestActiveContentNeverRunsInOrigin(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") want(t, s.put("page.html", ""), 200) want(t, s.put("img.svg", ``), 200) want(t, s.put("note.txt", "bonjour"), 200) want(t, s.put("photo.png", "\x89PNG"), 200) want(t, s.put("doc.pdf", "%PDF"), 200) want(t, s.put("inconnu.xyz", "?"), 200) for _, name := range []string{"page.html", "img.svg", "inconnu.xyz"} { for _, inline := range []string{"", "&inline=1"} { w := s.get("/api/file?path=" + name + inline) ct := w.Header().Get("Content-Type") cd := w.Header().Get("Content-Disposition") if name == "img.svg" && inline != "" { // SVG affiché en ligne seulement avec un CSP qui interdit tout script. if !strings.Contains(w.Header().Get("Content-Security-Policy"), "sandbox") { t.Errorf("SVG inline sans sandbox") } continue } if strings.Contains(ct, "html") || strings.Contains(ct, "svg") { t.Errorf("%s%s servi en %s", name, inline, ct) } if name == "page.html" && inline != "" { if !strings.HasPrefix(ct, "text/plain") { t.Errorf("HTML inline : %s", ct) } continue } if !strings.HasPrefix(cd, "attachment") { t.Errorf("%s%s : %s", name, inline, cd) } } } if w := s.get("/api/file?path=note.txt&inline=1"); !strings.HasPrefix(w.Header().Get("Content-Disposition"), "inline") || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/plain") { t.Errorf("texte inline : %v", w.Header()) } if w := s.get("/api/file?path=photo.png&inline=1"); w.Header().Get("Content-Type") != "image/png" || w.Header().Get("X-Content-Type-Options") != "nosniff" { t.Errorf("image inline : %v", w.Header()) } // PDF en ligne sans CSP sandbox (sinon le lecteur PDF ne s'affiche pas). if w := s.get("/api/file?path=doc.pdf&inline=1"); w.Header().Get("Content-Type") != "application/pdf" || w.Header().Get("Content-Security-Policy") != "" { t.Errorf("pdf inline : %v", w.Header()) } } func TestContentDispositionEncoding(t *testing.T) { got := contentDisposition(false, `é"té\.pdf`) if !strings.Contains(got, `filename="_t_.pdf"`) && !strings.Contains(got, `filename="__t__.pdf"`) { // repli ASCII : les caractères non ASCII et les guillemets sont remplacés } if strings.Contains(got, `"té`) || !strings.Contains(got, "filename*=UTF-8''%C3%A9%22t%C3%A9%5C.pdf") { t.Errorf("Content-Disposition = %s", got) } } func TestPathTraversalAndInternalFiles(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") for _, p := range []string{".trash/x", "a/.meta.json", ".accounts.json", ".users/alice/home/x"} { if w := s.put(p, "x"); w.Code != 400 { t.Errorf("PUT %s : %d", p, w.Code) } } // « .. » ne remonte jamais au-dessus de la racine : le chemin est normalisé sous la racine. want(t, s.put("../../escape.txt", "x"), 200) if s.get("/api/file?path=escape.txt").Body.String() != "x" { t.Error("chemin normalisé sous la racine") } if es, _ := os.ReadDir(filepath.Dir(f.root)); len(es) > 0 { for _, e := range es { if e.Name() == "escape.txt" { t.Error("écriture hors racine") } } } for _, p := range []string{".accounts.json", ".tokens.json", ".session-secret", ".settings.json", ".share-secret", ".meta.json"} { if w := s.get("/api/file?path=" + p); w.Code == 200 { t.Errorf("lecture de %s : %s", p, w.Body) } } } func TestQuotaAndMaxUpload(t *testing.T) { f := newFixture(t, func(st *storage.Store, sp *storage.Spaces) { sp.MaxUpload = 1 << 20 st.Defaults.QuotaMB = 1 }) s := f.register("alice") want(t, s.put(".perso/a.bin", strings.Repeat("x", 700<<10)), 200) want(t, s.put(".perso/b.bin", strings.Repeat("x", 700<<10)), 507) want(t, s.put("commun.bin", strings.Repeat("x", 1100<<10)), 413) me := decode[meResponse](t, s.get("/api/me")) if me.Usage == nil || me.Usage.Quota != 1<<20 || me.Usage.Used < 700<<10 { t.Errorf("usage = %+v", me.Usage) } } func TestFolderOperationsAndZip(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") want(t, s.json("POST", "/api/folder", map[string]string{"path": "projet"}), 201) want(t, s.put("projet/a.txt", "AAA"), 200) want(t, s.put("projet/sub/b.txt", "BBB"), 200) want(t, s.put("autre.txt", "CCC"), 200) want(t, s.json("POST", "/api/copy", map[string]string{"from": "projet", "to": "projet-copie"}), 201) if s.get("/api/file?path=projet-copie/sub/b.txt").Body.String() != "BBB" { t.Error("copie de dossier") } // ZIP d'un dossier (GET) et d'une sélection (formulaire POST). w := s.get("/api/zip?path=projet") want(t, w, 200) names := zipNames(t, w.Body.Bytes()) if !names["projet/a.txt"] || !names["projet/sub/b.txt"] || !strings.Contains(w.Header().Get("Content-Disposition"), "projet.zip") { t.Errorf("zip dossier : %v %v", names, w.Header()) } form := url.Values{"paths": {`["projet/a.txt","autre.txt"]`}} w = s.do("POST", "/api/zip", strings.NewReader(form.Encode()), "Content-Type", "application/x-www-form-urlencoded") want(t, w, 200) if n := zipNames(t, w.Body.Bytes()); !n["a.txt"] || !n["autre.txt"] { t.Errorf("zip sélection : %v", n) } want(t, s.get("/api/zip?path=../../etc"), 404) // Déplacement multiple avec échec partiel. want(t, s.put("dest/autre.txt", "déjà là"), 200) res := decode[[]storage.MoveResult](t, s.json("POST", "/api/move-many", map[string]any{"paths": []string{"autre.txt", "projet/a.txt"}, "dir": "dest"})) if len(res) != 2 || res[0].Error == "" || res[1].Error != "" { t.Errorf("move-many = %+v", res) } // Corbeille. want(t, s.do("DELETE", "/api/entry?path=dest&recursive=true", nil), 204) tr := decode[[]storage.Entry](t, s.get("/api/list?path=.poubelle")) if len(tr) != 1 || tr[0].Origin != "dest" { t.Fatalf("poubelle = %+v", tr) } want(t, s.json("POST", "/api/trash/restore", map[string]any{"paths": []string{tr[0].Path}}), 200) if s.get("/api/file?path=dest/a.txt").Body.String() != "AAA" { t.Error("restauration depuis la poubelle") } } func zipNames(t *testing.T, b []byte) map[string]bool { t.Helper() zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b))) if err != nil { t.Fatalf("zip illisible : %v", err) } out := map[string]bool{} for _, f := range zr.File { out[f.Name] = true } return out } func TestShareFolderWithPassword(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") want(t, s.put("pub/a.txt", "AAA"), 200) want(t, s.put("pub/sub/b.png", "\x89PNG"), 200) want(t, s.put("prive.txt", "secret"), 200) sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "pub", "days": 7, "password": "mot-de-passe-partage"})) if !sh.IsDir || !sh.Protected || sh.Token == "" { t.Fatalf("share = %+v", sh) } visitor := f.session() // sans compte base := "/api/public/" + sh.Token // Verrouillé : seuls le titre et l'indication de mot de passe sortent. info := decode[publicInfo](t, visitor.get(base)) if !info.Protected || info.Name != "" || len(info.Entries) != 0 { t.Errorf("lien verrouillé : %+v", info) } want(t, visitor.get(base+"/file?sub=a.txt"), 401) want(t, visitor.get(base+"/zip"), 401) want(t, visitor.json("POST", base+"/unlock", map[string]string{"password": "faux"}), 403) want(t, visitor.json("POST", base+"/unlock", map[string]string{"password": "mot-de-passe-partage"}), 204) info = decode[publicInfo](t, visitor.get(base)) if info.Name != "pub" || !info.IsDir || len(info.Entries) != 2 || info.Entries[0].Name != "sub" { t.Errorf("contenu du lien : %+v", info) } if strings.Contains(visitor.get(base).Body.String(), "pub/") || strings.Contains(visitor.get(base).Body.String(), "alice") { t.Error("le chemin réel ou le propriétaire fuite dans la réponse publique") } sub := decode[publicInfo](t, visitor.get(base+"?sub=sub")) if sub.Name != "sub" || len(sub.Entries) != 1 || sub.Entries[0].Name != "b.png" { t.Errorf("sous-dossier : %+v", sub) } w := visitor.get(base + "/file?sub=a.txt") want(t, w, 200) if w.Body.String() != "AAA" { t.Errorf("fichier partagé = %q", w.Body) } want(t, visitor.get(base+"/file?sub=sub/b.png&inline=1"), 200) // Hors du dossier partagé : refus. for _, sub := range []string{"../prive.txt", "sub/../../prive.txt", ".trash", "%2e%2e/prive.txt"} { if w := visitor.get(base + "/file?sub=" + sub); w.Code == 200 { t.Errorf("sub=%s : %s", sub, w.Body) } } if n := zipNames(t, visitor.get(base+"/zip").Body.Bytes()); !n["pub/a.txt"] || n["prive.txt"] { t.Errorf("zip public : %v", n) } // Le cookie de déverrouillage d'un lien ne vaut pas pour un autre. sh2 := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "pub", "days": 0, "password": "autre-mot-de-passe"})) want(t, visitor.get("/api/public/"+sh2.Token+"/file?sub=a.txt"), 401) // Compteur de téléchargements (hors lecture partielle). list := decode[[]storage.Share](t, s.get("/api/shares?path=pub")) var dl int for _, x := range list { if x.ID == sh.ID { dl = x.Downloads } } if dl < 2 { t.Errorf("téléchargements = %d", dl) } // Un jeton falsifié ou révoqué ne donne rien. want(t, visitor.get("/api/public/"+sh.Token[:len(sh.Token)-3]+"abc"), 404) want(t, s.do("DELETE", "/api/shares?id="+sh.ID, nil), 204) want(t, visitor.get(base), 404) // X-Robots-Tag if visitor.get("/api/public/xxx").Header().Get("X-Robots-Tag") == "" { t.Error("X-Robots-Tag absent") } } func TestShareSingleFileAndThumb(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") png := makePNG(t, 900, 300) want(t, s.put("photo.png", png), 200) sh := decode[storage.Share](t, s.json("POST", "/api/shares", map[string]any{"path": "photo.png", "days": 1})) v := f.session() info := decode[publicInfo](t, v.get("/api/public/"+sh.Token)) if info.IsDir || info.Name != "photo.png" || info.Size != int64(len(png)) || info.Expires == nil { t.Errorf("info = %+v", info) } want(t, v.get("/api/public/"+sh.Token+"?sub=x"), 404) // pas de sous-chemin pour un fichier w := v.get("/api/public/" + sh.Token + "/thumb") want(t, w, 200) if w.Header().Get("Content-Type") != "image/png" { t.Errorf("thumb : %v", w.Header()) } // Miniature privée via l'API connectée. want(t, s.get("/api/thumb?path=photo.png"), 200) want(t, f.session().get("/api/thumb?path=photo.png"), 401) } func TestSettingsAndAdminPermissions(t *testing.T) { f := newFixture(t, nil) admin := f.register("alice") want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "open"}), 200) bob := f.register("bob") me := decode[meResponse](t, bob.get("/api/me")) if me.Admin || me.User == nil || me.User.Role != "user" { t.Errorf("bob = %+v", me) } // Un utilisateur ordinaire ne règle ni les paramètres, ni le logo, ni les comptes. want(t, bob.json("PUT", "/api/settings", map[string]any{"title": "X"}), 403) want(t, bob.do("DELETE", "/api/logo", nil), 403) want(t, bob.get("/api/admin/users"), 403) want(t, bob.get("/api/admin/s3"), 403) want(t, bob.json("PUT", "/api/admin/s3", map[string]any{"bucket": "b"}), 403) want(t, admin.get("/api/admin/s3"), 200) want(t, admin.json("PUT", "/api/admin/s3", map[string]any{"bucket": "b"}), 400) // sans catalogue want(t, bob.json("POST", "/api/admin/users", map[string]any{"username": "eve", "password": "mot-de-passe-eve"}), 403) want(t, bob.json("PATCH", "/api/admin/users/alice", map[string]any{"role": "user"}), 403) want(t, bob.do("DELETE", "/api/admin/users/alice", nil), 403) want(t, bob.do("POST", "/api/shares/revoke-all", nil), 403) // Un visiteur anonyme non plus (route publique /api/logo). want(t, f.session().do("DELETE", "/api/logo", nil), 403) want(t, f.session().do("PUT", "/api/logo", strings.NewReader("x")), 403) st := decode[storage.Settings](t, admin.json("PUT", "/api/settings", map[string]any{"title": "Mon cloud", "quotaMB": 50, "commonReadonly": true, "trashDays": 30})) if st.Title != "Mon cloud" || st.QuotaMB != 50 || !st.CommonReadonly || st.TrashDays != 30 { t.Errorf("settings = %+v", st) } want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "nimporte"}), 400) // Commun en lecture seule : bob ne dépose plus qu'à titre personnel. want(t, bob.put("x.txt", "x"), 403) want(t, bob.put(".perso/x.txt", "x"), 200) want(t, admin.put("admin.txt", "x"), 200) // Le titre est visible de tous avant connexion. if m := decode[meResponse](t, f.session().get("/api/me")); m.Title != "Mon cloud" { t.Errorf("titre public = %q", m.Title) } } func TestAdminUserManagement(t *testing.T) { f := newFixture(t, nil) admin := f.register("alice") want(t, admin.json("PUT", "/api/settings", map[string]any{"registration": "approval"}), 200) pending := f.register("bob") // 202 : en attente want(t, pending.get("/api/list?path="), 401) if m := decode[meResponse](t, admin.get("/api/me")); m.Pending != 1 { t.Errorf("en attente = %d", m.Pending) } users := decode[[]auth.AccountInfo](t, admin.get("/api/admin/users")) if len(users) != 2 || users[1].Status != "pending" || strings.Contains(admin.get("/api/admin/users").Body.String(), "hash") { t.Errorf("users = %+v", users) } want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "active"}), 200) bob := f.login("bob") want(t, bob.put(".perso/mine.txt", "m"), 200) // Création directe, rôle, mot de passe. want(t, admin.json("POST", "/api/admin/users", map[string]any{"username": "carl", "name": "Carl", "password": "mot-de-passe-carl", "role": "admin"}), 201) want(t, admin.json("POST", "/api/admin/users", map[string]any{"username": "carl", "password": "mot-de-passe-carl"}), 400) want(t, admin.json("PATCH", "/api/admin/users/carl", map[string]any{"password": "nouveau-mot-de-passe"}), 200) want(t, f.session().json("POST", "/auth/local/login", map[string]string{"username": "carl", "password": "nouveau-mot-de-passe"}), 200) // Garde-fous. want(t, admin.do("DELETE", "/api/admin/users/alice", nil), 400) // soi-même // Désactivation : la session et les jetons de bob cessent de marcher. tok := decode[struct{ Token string }](t, bob.json("POST", "/api/tokens", map[string]string{"name": "script"})) api := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: tok.Token} want(t, api.get("/api/list?path=.perso"), 200) want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "disabled"}), 200) want(t, bob.get("/api/list?path="), 401) want(t, api.get("/api/list?path=.perso"), 401) // Suppression : l'espace personnel est mis de côté, pas hérité par un homonyme. want(t, admin.do("DELETE", "/api/admin/users/bob", nil), 204) again := f.register("bob") _ = again want(t, admin.json("PATCH", "/api/admin/users/bob", map[string]any{"status": "active"}), 200) b2 := f.login("bob") if es := decode[[]storage.Entry](t, b2.get("/api/list?path=.perso")); len(es) != 0 { t.Errorf("héritage de l'espace d'un compte supprimé : %+v", es) } } func TestAPITokens(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") created := decode[struct { ID string Token string }](t, s.json("POST", "/api/tokens", map[string]string{"name": "sauvegarde"})) if !strings.HasPrefix(created.Token, "upd_") { t.Fatalf("jeton = %q", created.Token) } if strings.Contains(s.get("/api/tokens").Body.String(), created.Token) { t.Error("le secret du jeton est relisible") } cli := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: created.Token} want(t, cli.put("depuis-curl.txt", "ok"), 200) want(t, cli.get("/api/file?path=depuis-curl.txt"), 200) // Un jeton ne gère pas les jetons ni les comptes. want(t, cli.json("POST", "/api/tokens", map[string]string{"name": "x"}), 403) want(t, cli.get("/api/tokens"), 403) // Jeton invalide. bad := &session{f: f, cookies: map[string]*http.Cookie{}, bearer: "upd_faux"} want(t, bad.get("/api/list?path="), 401) // Révocation. want(t, s.do("DELETE", "/api/tokens/"+created.ID, nil), 204) want(t, cli.get("/api/list?path="), 401) } func TestAccountSelfService(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") want(t, s.json("POST", "/api/account/password", map[string]string{"current": "faux", "new": "nouveau-mot-de-passe"}), 403) want(t, s.json("POST", "/api/account/password", map[string]string{"current": "mot-de-passe-alice", "new": "court"}), 400) want(t, s.json("POST", "/api/account/password", map[string]string{"current": "mot-de-passe-alice", "new": "nouveau-mot-de-passe"}), 204) want(t, f.session().json("POST", "/auth/local/login", map[string]string{"username": "alice", "password": "nouveau-mot-de-passe"}), 200) want(t, s.json("PATCH", "/api/account", map[string]string{"name": "Alice D."}), 204) if m := decode[meResponse](t, s.get("/api/me")); m.User.Name != "Alice D." { t.Errorf("nom = %q", m.User.Name) } } func TestTagsFavoritesSearchAndDetails(t *testing.T) { f := newFixture(t, nil) s := f.register("alice") want(t, s.put("notes/plan.md", "# Plan\nle réseau 10.1.2.0/24"), 200) want(t, s.put("photo.png", makePNG(t, 60, 40)), 200) want(t, s.json("POST", "/api/meta/tags", map[string]any{"paths": []string{"notes/plan.md"}, "add": []string{"Projet"}}), 204) want(t, s.json("POST", "/api/meta/favorite", map[string]any{"paths": []string{"photo.png", "notes"}, "favorite": true}), 204) hits := decode[[]storage.Hit](t, s.get("/api/search?q=10.1.2")) if len(hits) != 1 || hits[0].Path != "notes/plan.md" || hits[0].Snippet == "" { t.Errorf("recherche = %+v", hits) } if hits = decode[[]storage.Hit](t, s.get("/api/search?tag=projet")); len(hits) != 1 { t.Errorf("tag = %+v", hits) } if favs := decode[[]storage.Entry](t, s.get("/api/list?path=.favoris")); len(favs) != 2 { t.Errorf("favoris = %+v", favs) } es := decode[[]storage.Entry](t, s.get("/api/list?path=&details=1")) var img, dir *storage.Entry for i := range es { switch es[i].Name { case "photo.png": img = &es[i] case "notes": dir = &es[i] } } if img == nil || img.Details == nil || img.Details.Width != 60 || img.Details.Height != 40 || !img.Favorite { t.Errorf("image = %+v", img) } if dir == nil || dir.Details == nil || dir.Details.Files != 1 || dir.Details.Total == 0 { t.Errorf("dossier = %+v", dir) } h := decode[map[string]string](t, s.get("/api/hash?path=notes/plan.md")) if len(h["sha256"]) != 64 { t.Errorf("hash = %v", h) } }