diff --git a/internal/api/admin_requests.go b/internal/api/admin_requests.go new file mode 100644 index 00000000..63bf97ab --- /dev/null +++ b/internal/api/admin_requests.go @@ -0,0 +1,152 @@ +package api + +import ( + "encoding/json" + "errors" + "net/http" + "strconv" + + "github.com/go-chi/chi/v5" + + "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "git.fabledsword.com/bvandeusen/minstrel/internal/lidarr" + "git.fabledsword.com/bvandeusen/minstrel/internal/lidarrrequests" +) + +// validRequestStatuses is the set of allowed values for the ?status= param. +var validRequestStatuses = map[string]bool{ + "pending": true, + "approved": true, + "rejected": true, + "completed": true, + "failed": true, +} + +// handleListAdminRequests implements GET /api/admin/requests. +// ?status= defaults to "pending"; ?limit= defaults to 50, max 200. +func (h *handlers) handleListAdminRequests(w http.ResponseWriter, r *http.Request) { + status := r.URL.Query().Get("status") + if status == "" { + status = "pending" + } + if !validRequestStatuses[status] { + writeAdminJSONErr(w, http.StatusBadRequest, "invalid_status") + return + } + + limitStr := r.URL.Query().Get("limit") + limit := 50 + if limitStr != "" { + v, err := strconv.Atoi(limitStr) + if err != nil || v <= 0 { + writeAdminJSONErr(w, http.StatusBadRequest, "invalid_limit") + return + } + if v > 200 { + v = 200 + } + limit = v + } + + rows, err := h.lidarrRequests.ListByStatus(r.Context(), status, int32(limit)) + if err != nil { + h.logger.Error("admin: list requests", "err", err) + writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + return + } + + out := make([]requestView, 0, len(rows)) + for _, row := range rows { + out = append(out, requestViewFrom(row)) + } + writeJSON(w, http.StatusOK, out) +} + +// approveRequestBody is the optional JSON body for POST /api/admin/requests/:id/approve. +type approveRequestBody struct { + QualityProfileID int `json:"quality_profile_id"` + RootFolderPath string `json:"root_folder_path"` +} + +// handleApproveRequest implements POST /api/admin/requests/:id/approve. +func (h *handlers) handleApproveRequest(w http.ResponseWriter, r *http.Request) { + admin, ok := auth.UserFromContext(r.Context()) + if !ok { + writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") + return + } + + id, ok := parseUUID(chi.URLParam(r, "id")) + if !ok { + writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + return + } + + var body approveRequestBody + // Body is entirely optional; ignore decode errors. + _ = json.NewDecoder(r.Body).Decode(&body) + + row, err := h.lidarrRequests.Approve(r.Context(), id, admin.ID, lidarrrequests.ApproveOverrides{ + QualityProfileID: body.QualityProfileID, + RootFolderPath: body.RootFolderPath, + }) + if err != nil { + switch { + case errors.Is(err, lidarrrequests.ErrLidarrDisabled): + writeAdminJSONErr(w, http.StatusServiceUnavailable, "lidarr_disabled") + case errors.Is(err, lidarrrequests.ErrNotFound): + writeAdminJSONErr(w, http.StatusNotFound, "request_not_found") + case errors.Is(err, lidarrrequests.ErrNotPending): + writeAdminJSONErr(w, http.StatusConflict, "request_not_pending") + case errors.Is(err, lidarr.ErrUnreachable): + writeAdminJSONErr(w, http.StatusServiceUnavailable, "lidarr_unreachable") + case errors.Is(err, lidarr.ErrAuthFailed): + writeAdminJSONErr(w, http.StatusServiceUnavailable, "lidarr_auth_failed") + default: + h.logger.Error("admin: approve request", "err", err) + writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + } + return + } + + writeJSON(w, http.StatusOK, requestViewFrom(row)) +} + +// rejectRequestBody is the optional JSON body for POST /api/admin/requests/:id/reject. +type rejectRequestBody struct { + Notes string `json:"notes"` +} + +// handleRejectRequest implements POST /api/admin/requests/:id/reject. +func (h *handlers) handleRejectRequest(w http.ResponseWriter, r *http.Request) { + admin, ok := auth.UserFromContext(r.Context()) + if !ok { + writeAdminJSONErr(w, http.StatusUnauthorized, "unauthorized") + return + } + + id, ok := parseUUID(chi.URLParam(r, "id")) + if !ok { + writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") + return + } + + var body rejectRequestBody + _ = json.NewDecoder(r.Body).Decode(&body) + + row, err := h.lidarrRequests.Reject(r.Context(), id, admin.ID, body.Notes) + if err != nil { + switch { + case errors.Is(err, lidarrrequests.ErrNotFound): + writeAdminJSONErr(w, http.StatusNotFound, "request_not_found") + case errors.Is(err, lidarrrequests.ErrNotPending): + writeAdminJSONErr(w, http.StatusConflict, "request_not_pending") + default: + h.logger.Error("admin: reject request", "err", err) + writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") + } + return + } + + writeJSON(w, http.StatusOK, requestViewFrom(row)) +} diff --git a/internal/api/admin_requests_test.go b/internal/api/admin_requests_test.go new file mode 100644 index 00000000..490e055c --- /dev/null +++ b/internal/api/admin_requests_test.go @@ -0,0 +1,446 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/go-chi/chi/v5" + + "git.fabledsword.com/bvandeusen/minstrel/internal/auth" + "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/lidarr" + "git.fabledsword.com/bvandeusen/minstrel/internal/lidarrconfig" + "git.fabledsword.com/bvandeusen/minstrel/internal/lidarrrequests" +) + +// newAdminRequestsRouter builds a test chi router with the three admin/requests +// endpoints. RequireAdmin middleware is applied. Tests inject a user into +// context directly (skipping RequireUser). +func newAdminRequestsRouter(h *handlers) chi.Router { + r := chi.NewRouter() + r.Route("/api/admin", func(admin chi.Router) { + admin.Use(auth.RequireAdmin()) + admin.Get("/requests", h.handleListAdminRequests) + admin.Post("/requests/{id}/approve", h.handleApproveRequest) + admin.Post("/requests/{id}/reject", h.handleRejectRequest) + }) + return r +} + +// doAdminRequestReq fires an HTTP request at the admin requests router with +// the given user injected into context (bypassing RequireUser). +func doAdminRequestReq(t *testing.T, h *handlers, method, path string, body []byte, user dbq.User) *httptest.ResponseRecorder { + t.Helper() + var reqBody *bytes.Buffer + if body != nil { + reqBody = bytes.NewBuffer(body) + } else { + reqBody = bytes.NewBuffer(nil) + } + req := httptest.NewRequest(method, path, reqBody) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + req = req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), user)) + w := httptest.NewRecorder() + newAdminRequestsRouter(h).ServeHTTP(w, req) + return w +} + +// testHandlersWithClientFn creates a handlers instance with a real clientFn +// so Service.Approve actually calls Lidarr during tests. +func testHandlersWithClientFn(t *testing.T) (*handlers, *lidarrconfig.Service) { + t.Helper() + h, _ := testHandlers(t) + lidarrCfg := lidarrconfig.New(h.pool) + clientFn := func() *lidarr.Client { + cfg, err := lidarrCfg.Get(context.Background()) + if err != nil || !cfg.Enabled || cfg.BaseURL == "" { + return nil + } + return lidarr.NewClient(cfg.BaseURL, cfg.APIKey) + } + h.lidarrRequests = lidarrrequests.NewService(h.pool, lidarrCfg, clientFn, nil) + return h, lidarrCfg +} + +// seedPendingArtistRequest creates a pending artist-kind lidarr request row +// for the given user and returns its parsed requestView. +func seedPendingArtistRequest(t *testing.T, h *handlers, user dbq.User, artistMBID, artistName string) requestView { + t.Helper() + return createArtistRequest(t, h, user, artistMBID, artistName) +} + +// TestHandleListAdminRequests_DefaultStatus_Pending seeds 2 pending + 1 rejected +// and verifies that GET without ?status returns only the 2 pending rows. +func TestHandleListAdminRequests_DefaultStatus_Pending(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + createArtistRequest(t, h, alice, "mbid-pending-1", "Pending Artist 1") + createArtistRequest(t, h, alice, "mbid-pending-2", "Pending Artist 2") + + // Reject one request directly via service. + rv3 := createArtistRequest(t, h, alice, "mbid-reject-1", "Reject Me") + _, err := h.lidarrRequests.Reject(context.Background(), rv3.ID, admin.ID, "test") + if err != nil { + t.Fatalf("reject seed: %v", err) + } + + w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests", nil, admin) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + + var results []requestView + if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if len(results) != 2 { + t.Fatalf("len(results) = %d, want 2 (pending only)", len(results)) + } + for _, rv := range results { + if rv.Status != "pending" { + t.Errorf("result status = %q, want pending", rv.Status) + } + } +} + +// TestHandleListAdminRequests_StatusFilter verifies GET ?status=rejected returns +// only rejected rows. +func TestHandleListAdminRequests_StatusFilter(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + createArtistRequest(t, h, alice, "mbid-pending-f1", "Pending Filter 1") + + rv2 := createArtistRequest(t, h, alice, "mbid-rejected-f1", "Rejected Filter 1") + _, err := h.lidarrRequests.Reject(context.Background(), rv2.ID, admin.ID, "") + if err != nil { + t.Fatalf("reject seed: %v", err) + } + + w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=rejected", nil, admin) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + + var results []requestView + if err := json.Unmarshal(w.Body.Bytes(), &results); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if len(results) != 1 { + t.Fatalf("len(results) = %d, want 1 rejected row", len(results)) + } + if results[0].Status != "rejected" { + t.Errorf("status = %q, want rejected", results[0].Status) + } +} + +// TestHandleListAdminRequests_BadStatus_400 verifies GET with an invalid +// ?status returns 400. +func TestHandleListAdminRequests_BadStatus_400(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + admin := seedUser(t, h.pool, "admin", "pw", true) + + w := doAdminRequestReq(t, h, http.MethodGet, "/api/admin/requests?status=garbage", nil, admin) + if w.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", w.Code, w.Body.String()) + } + var resp map[string]string + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if resp["error"] != "invalid_status" { + t.Errorf("error = %q, want invalid_status", resp["error"]) + } +} + +// TestHandleApproveRequest_HappyPath seeds a Lidarr stub, seeds a pending +// artist request, and verifies POST /approve → 200 with row status=approved. +func TestHandleApproveRequest_HappyPath(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":1}`)) + })) + t.Cleanup(stub.Close) + + saveLidarrConfig(t, h, stub.URL, true) + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-approve", "Approve Me") + + w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + + var got requestView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if got.Status != "approved" { + t.Errorf("status = %q, want approved", got.Status) + } + if got.ID != rv.ID { + t.Errorf("id mismatch") + } +} + +// TestHandleApproveRequest_OverrideUsed seeds config with default qp=1/root="/m", +// approves with override qp=5/root="/other", verifies the stub received those +// values and the row reflects the overrides. +func TestHandleApproveRequest_OverrideUsed(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + var capturedBody []byte + stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + buf := make([]byte, 4096) + n, _ := r.Body.Read(buf) + capturedBody = buf[:n] + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":1}`)) + })) + t.Cleanup(stub.Close) + + // Save config with default qp=1, root="/m". + if err := lidarrconfig.New(h.pool).Save(context.Background(), lidarrconfig.Config{ + Enabled: true, + BaseURL: stub.URL, + APIKey: "test-key", + DefaultQualityProfileID: 1, + DefaultRootFolderPath: "/m", + }); err != nil { + t.Fatalf("save config: %v", err) + } + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-override", "Override Me") + + body := []byte(`{"quality_profile_id":5,"root_folder_path":"/other"}`) + w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", body, admin) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + + // Verify stub received the override values. + var stubPayload map[string]any + if err := json.Unmarshal(capturedBody, &stubPayload); err != nil { + t.Fatalf("decode stub payload: %v; body = %s", err, capturedBody) + } + if qp, _ := stubPayload["qualityProfileId"].(float64); int(qp) != 5 { + t.Errorf("stub qualityProfileId = %v, want 5", stubPayload["qualityProfileId"]) + } + if rf, _ := stubPayload["rootFolderPath"].(string); rf != "/other" { + t.Errorf("stub rootFolderPath = %q, want /other", rf) + } + + // Verify the returned row reflects the overrides. + var got requestView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode response: %v; body = %s", err, w.Body.String()) + } + if got.QualityProfileID == nil || *got.QualityProfileID != 5 { + t.Errorf("quality_profile_id = %v, want 5", got.QualityProfileID) + } + if got.RootFolderPath == nil || *got.RootFolderPath != "/other" { + t.Errorf("root_folder_path = %v, want /other", got.RootFolderPath) + } +} + +// TestHandleApproveRequest_LidarrUnreachable_503 points config at an unreachable +// port and verifies POST /approve → 503 lidarr_unreachable, row stays pending. +func TestHandleApproveRequest_LidarrUnreachable_503(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + saveLidarrConfig(t, h, "http://127.0.0.1:1", true) + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-unreachable", "Unreachable") + + w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin) + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503; body = %s", w.Code, w.Body.String()) + } + var resp map[string]string + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if resp["error"] != "lidarr_unreachable" { + t.Errorf("error = %q, want lidarr_unreachable", resp["error"]) + } + + // Row must still be pending. + rows, err := h.lidarrRequests.ListByStatus(context.Background(), "pending", 10) + if err != nil { + t.Fatalf("list pending: %v", err) + } + found := false + for _, r := range rows { + if r.ID == rv.ID { + found = true + break + } + } + if !found { + t.Error("row is no longer pending after failed approve") + } +} + +// TestHandleApproveRequest_NotPending_409 pre-rejects a row and verifies +// POST /approve → 409 request_not_pending. +func TestHandleApproveRequest_NotPending_409(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + // Need an enabled Lidarr config so Approve reaches the not-pending check. + stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":1}`)) + })) + t.Cleanup(stub.Close) + saveLidarrConfig(t, h, stub.URL, true) + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-notpending", "Not Pending") + + // Pre-reject the row. + _, err := h.lidarrRequests.Reject(context.Background(), rv.ID, admin.ID, "pre-rejected") + if err != nil { + t.Fatalf("pre-reject: %v", err) + } + + w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/approve", nil, admin) + if w.Code != http.StatusConflict { + t.Fatalf("status = %d, want 409; body = %s", w.Code, w.Body.String()) + } + var resp map[string]string + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if resp["error"] != "request_not_pending" { + t.Errorf("error = %q, want request_not_pending", resp["error"]) + } +} + +// TestHandleRejectRequest_HappyPath verifies POST /reject with notes returns +// 200 and the row transitions to rejected with notes saved. +func TestHandleRejectRequest_HappyPath(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject", "Reject Me") + + body := []byte(`{"notes":"low-quality release; will look for the remaster"}`) + w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", body, admin) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + + var got requestView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if got.Status != "rejected" { + t.Errorf("status = %q, want rejected", got.Status) + } + if got.Notes == nil || *got.Notes != "low-quality release; will look for the remaster" { + t.Errorf("notes = %v, want expected string", got.Notes) + } +} + +// TestHandleRejectRequest_NoNotes_OK verifies POST /reject with empty body +// returns 200 (notes are optional). +func TestHandleRejectRequest_NoNotes_OK(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + alice := seedUser(t, h.pool, "alice", "pw", false) + admin := seedUser(t, h.pool, "admin", "pw", true) + + rv := seedPendingArtistRequest(t, h, alice, "artist-mbid-reject-nonotes", "Reject No Notes") + + w := doAdminRequestReq(t, h, http.MethodPost, "/api/admin/requests/"+uuidToString(rv.ID)+"/reject", nil, admin) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String()) + } + + var got requestView + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if got.Status != "rejected" { + t.Errorf("status = %q, want rejected", got.Status) + } +} + +// TestAdminRequestsEndpoints_NonAdmin403 is a table-driven test verifying that +// all 3 admin request endpoints reject non-admin users with 403. +func TestAdminRequestsEndpoints_NonAdmin403(t *testing.T) { + h, _ := testHandlersWithClientFn(t) + resetLidarrState(t, h) + + nonAdmin := seedUser(t, h.pool, "regular", "pw", false) + + // Use a placeholder UUID for the ID endpoints. + fakeID := "00000000-0000-0000-0000-000000000001" + + cases := []struct { + method string + path string + body []byte + }{ + {http.MethodGet, "/api/admin/requests", nil}, + {http.MethodPost, "/api/admin/requests/" + fakeID + "/approve", nil}, + {http.MethodPost, "/api/admin/requests/" + fakeID + "/reject", nil}, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.method+" "+tc.path, func(t *testing.T) { + w := doAdminRequestReq(t, h, tc.method, tc.path, tc.body, nonAdmin) + if w.Code != http.StatusForbidden { + t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String()) + } + var resp map[string]string + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("decode: %v; body = %s", err, w.Body.String()) + } + if resp["error"] != "not_authorized" { + t.Errorf("error = %q, want not_authorized", resp["error"]) + } + }) + } +} diff --git a/internal/api/api.go b/internal/api/api.go index 9fa9bd93..e654fa2f 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -68,6 +68,9 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Post("/lidarr/test", h.handleTestLidarrConnection) admin.Get("/lidarr/quality-profiles", h.handleListQualityProfiles) admin.Get("/lidarr/root-folders", h.handleListRootFolders) + admin.Get("/requests", h.handleListAdminRequests) + admin.Post("/requests/{id}/approve", h.handleApproveRequest) + admin.Post("/requests/{id}/reject", h.handleRejectRequest) }) }) })