package api import ( "bytes" "context" "encoding/json" "io" "mime/multipart" "net/http" "net/http/httptest" "testing" "mediarr/auth" "mediarr/ident" "mediarr/identity" "mediarr/node" ) type apiTestEnv struct { node node.Node server *httptest.Server } func newAPITestEnv(t *testing.T) *apiTestEnv { t.Helper() t.Chdir(t.TempDir()) err, n := node.NewNode(node.NewNodeParams{ DatabaseName: "api", StoragePath: "store", ClusterKeyPath: "cluster.key", }) if err != nil { t.Fatalf("NewNode : %v", err) } t.Cleanup(func() { if err := n.Close(); err != nil { t.Errorf("Close : %v", err) } }) if err := n.Up(); err != nil { t.Fatalf("Up : %v", err) } server := httptest.NewServer(NewServer(&n).Handler()) t.Cleanup(server.Close) return &apiTestEnv{node: n, server: server} } func TestAPIWorkflow(t *testing.T) { env := newAPITestEnv(t) ctx := context.Background() client := env.server.Client() if _, err := env.node.Auth().CreateUser(ctx, auth.CreateUserParams{ Login: "admin", Password: "password123", Role: identity.RoleAdmin, }); err != nil { t.Fatalf("CreateUser(admin) : %v", err) } response, body := doJSON(t, client, http.MethodGet, env.server.URL+"/api/health", "", nil) requireStatus(t, response, body, http.StatusOK) response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", "", nil) requireStatus(t, response, body, http.StatusUnauthorized) response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{ "login": "admin", "password": "password123", }) requireStatus(t, response, body, http.StatusOK) login := decodeBody[loginResponse](t, body) if login.Token == "" || login.Principal.ID == "" || login.Account.Login != "admin" { t.Fatalf("login = %+v", login) } if len(response.Cookies()) == 0 { t.Fatal("cookie de session absent") } token := login.Token response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", token, nil) requireStatus(t, response, body, http.StatusOK) me := decodeBody[userDTO](t, body) if me.Principal.ID != login.Principal.ID || me.Account.Login != "admin" { t.Fatalf("me = %+v", me) } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/libraries", token, map[string]any{ "name": "Films", }) requireStatus(t, response, body, http.StatusCreated) library := decodeBody[documentDTO](t, body) if library.Kind != "library" || library.Name != "Films" || library.PolicyID == nil { t.Fatalf("bibliothèque = %+v", library) } response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/libraries", token, nil) requireStatus(t, response, body, http.StatusOK) libraries := decodeBody[[]documentDTO](t, body) if len(libraries) != 1 || libraries[0].ID != library.ID { t.Fatalf("bibliothèques = %+v", libraries) } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+library.ID+"/children", token, map[string]any{ "kind": "video", "name": "film.mkv", }) requireStatus(t, response, body, http.StatusCreated) video := decodeBody[documentDTO](t, body) if video.Kind != "video" || video.ParentID == nil || *video.ParentID != library.ID { t.Fatalf("vidéo = %+v", video) } response, body = doUpload(t, client, env.server.URL+"/api/documents/"+video.ID+"/versions", token, "film.mkv", []byte("contenu v1")) requireStatus(t, response, body, http.StatusCreated) first := decodeBody[versionDTO](t, body) if first.Seq != 1 || first.Size != int64(len("contenu v1")) || first.DocumentID != video.ID { t.Fatalf("version 1 = %+v", first) } response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+video.ID+"/versions", token, nil) requireStatus(t, response, body, http.StatusOK) versions := decodeBody[[]versionDTO](t, body) if len(versions) != 1 || versions[0].ID != first.ID { t.Fatalf("versions = %+v", versions) } response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+video.ID+"/head", token, nil) requireStatus(t, response, body, http.StatusOK) head := decodeBody[struct { Version *versionDTO `json:"version"` }](t, body) if head.Version == nil || head.Version.ID != first.ID { t.Fatalf("head = %+v", head) } response, downloaded := doRaw(t, client, http.MethodGet, env.server.URL+"/api/versions/"+first.ID, token, nil, "") requireStatus(t, response, downloaded, http.StatusOK) if string(downloaded) != "contenu v1" { t.Fatalf("contenu téléchargé = %q", downloaded) } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/head", token, map[string]string{ "version_id": first.ID, }) requireStatus(t, response, body, http.StatusOK) if decodeBody[versionDTO](t, body).ID != first.ID { t.Fatal("version tête incohérente") } response, body = doUpload(t, client, env.server.URL+"/api/documents/"+video.ID+"/versions", token, "film.mkv", []byte("contenu v2")) requireStatus(t, response, body, http.StatusCreated) second := decodeBody[versionDTO](t, body) if second.Seq != 2 { t.Fatalf("version 2 = %+v", second) } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/head", token, map[string]string{ "version_id": second.ID, }) requireStatus(t, response, body, http.StatusOK) response, body = doJSON(t, client, http.MethodDelete, env.server.URL+"/api/versions/"+first.ID, token, nil) requireStatus(t, response, body, http.StatusNoContent) response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/versions/"+first.ID, token, nil) requireStatus(t, response, body, http.StatusGone) response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/retention", token, nil) requireStatus(t, response, body, http.StatusOK) retention := decodeBody[retentionDTO](t, body) if retention.Kept < 1 { t.Fatalf("rétention = %+v", retention) } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/versions/"+second.ID+"/verify", token, nil) requireStatus(t, response, body, http.StatusNoContent) response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/rename", token, map[string]string{ "name": "film-renamed.mkv", }) requireStatus(t, response, body, http.StatusOK) if decodeBody[documentDTO](t, body).Name != "film-renamed.mkv" { t.Fatal("renommage incohérent") } response, body = doJSON(t, client, http.MethodPut, env.server.URL+"/api/documents/"+video.ID+"/metadata", token, map[string]any{ "metadata": map[string]any{"tag": "test"}, }) requireStatus(t, response, body, http.StatusOK) if string(decodeBody[documentDTO](t, body).Metadata) != `{"tag":"test"}` { t.Fatalf("métadonnées = %s", body) } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+library.ID+"/children", token, map[string]any{ "kind": "folder", "name": "Dossier", }) requireStatus(t, response, body, http.StatusCreated) folder := decodeBody[documentDTO](t, body) response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/move", token, map[string]string{ "parent_id": folder.ID, }) requireStatus(t, response, body, http.StatusOK) moved := decodeBody[documentDTO](t, body) if moved.ParentID == nil || *moved.ParentID != folder.ID { t.Fatalf("déplacement = %+v", moved) } response, body = doJSON(t, client, http.MethodDelete, env.server.URL+"/api/documents/"+video.ID, token, nil) requireStatus(t, response, body, http.StatusOK) trashed := decodeBody[documentDTO](t, body) if trashed.DeletedAt == nil { t.Fatal("document non mis à la corbeille") } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/restore", token, nil) requireStatus(t, response, body, http.StatusOK) if decodeBody[documentDTO](t, body).DeletedAt != nil { t.Fatal("document non restauré") } response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/users", token, map[string]string{ "login": "member", "password": "password123", "role": identity.RoleMember, }) requireStatus(t, response, body, http.StatusCreated) response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{ "login": "member", "password": "password123", }) requireStatus(t, response, body, http.StatusOK) memberToken := decodeBody[loginResponse](t, body).Token response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/maintenance/gc", memberToken, nil) requireStatus(t, response, body, http.StatusForbidden) response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/maintenance/gc", token, nil) requireStatus(t, response, body, http.StatusOK) response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/logout", token, nil) requireStatus(t, response, body, http.StatusNoContent) response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", token, nil) requireStatus(t, response, body, http.StatusUnauthorized) } func TestAPILoginRejectsInvalidCredentials(t *testing.T) { env := newAPITestEnv(t) client := env.server.Client() response, body := doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{ "login": "missing", "password": "password123", }) requireStatus(t, response, body, http.StatusUnauthorized) } func TestAPIDocumentNotFound(t *testing.T) { env := newAPITestEnv(t) ctx := context.Background() client := env.server.Client() if _, err := env.node.Auth().CreateUser(ctx, auth.CreateUserParams{ Login: "admin", Password: "password123", Role: identity.RoleAdmin, }); err != nil { t.Fatalf("CreateUser : %v", err) } _, body := doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{ "login": "admin", "password": "password123", }) token := decodeBody[loginResponse](t, body).Token missing := ident.MustParse("00000000-0000-7000-8000-000000000999").String() response, body := doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+missing, token, nil) requireStatus(t, response, body, http.StatusNotFound) } func doJSON(t *testing.T, client *http.Client, method, url, token string, body any) (*http.Response, []byte) { t.Helper() var reader io.Reader if body != nil { encoded, err := json.Marshal(body) if err != nil { t.Fatalf("Marshal : %v", err) } reader = bytes.NewReader(encoded) } request, err := http.NewRequest(method, url, reader) if err != nil { t.Fatalf("NewRequest : %v", err) } if body != nil { request.Header.Set("Content-Type", "application/json") } if token != "" { request.Header.Set("Authorization", "Bearer "+token) } response, err := client.Do(request) if err != nil { t.Fatalf("%s %s : %v", method, url, err) } data, err := io.ReadAll(response.Body) if err != nil { _ = response.Body.Close() t.Fatalf("ReadAll : %v", err) } _ = response.Body.Close() return response, data } func doUpload(t *testing.T, client *http.Client, url, token, filename string, content []byte) (*http.Response, []byte) { t.Helper() body := &bytes.Buffer{} writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", filename) if err != nil { t.Fatalf("CreateFormFile : %v", err) } if _, err := part.Write(content); err != nil { t.Fatalf("Write : %v", err) } if err := writer.WriteField("message", "test"); err != nil { t.Fatalf("WriteField : %v", err) } if err := writer.Close(); err != nil { t.Fatalf("Close : %v", err) } request, err := http.NewRequest(http.MethodPost, url, body) if err != nil { t.Fatalf("NewRequest : %v", err) } request.Header.Set("Content-Type", writer.FormDataContentType()) request.Header.Set("Authorization", "Bearer "+token) response, err := client.Do(request) if err != nil { t.Fatalf("POST %s : %v", url, err) } data, err := io.ReadAll(response.Body) if err != nil { _ = response.Body.Close() t.Fatalf("ReadAll : %v", err) } _ = response.Body.Close() return response, data } func doRaw(t *testing.T, client *http.Client, method, url, token string, body io.Reader, contentType string) (*http.Response, []byte) { t.Helper() request, err := http.NewRequest(method, url, body) if err != nil { t.Fatalf("NewRequest : %v", err) } if contentType != "" { request.Header.Set("Content-Type", contentType) } if token != "" { request.Header.Set("Authorization", "Bearer "+token) } response, err := client.Do(request) if err != nil { t.Fatalf("%s %s : %v", method, url, err) } data, err := io.ReadAll(response.Body) if err != nil { _ = response.Body.Close() t.Fatalf("ReadAll : %v", err) } _ = response.Body.Close() return response, data } func decodeBody[T any](t *testing.T, body []byte) T { t.Helper() var value T if err := json.Unmarshal(body, &value); err != nil { t.Fatalf("Unmarshal %s : %v", body, err) } return value } func requireStatus(t *testing.T, response *http.Response, body []byte, want int) { t.Helper() if response.StatusCode != want { t.Fatalf("status = %d, attendu %d: %s", response.StatusCode, want, body) } }