Repository navigation
feat(auth): add metadata curation permission - #11
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughAdds a per-user permission model (metadata_curation), persists it, normalizes and exposes permissions in admin create/update handlers and current-user responses, enforces metadata curation via middleware and router wiring, sanitizes admin job responses for non-admins, and surfaces UI controls and action gating in the web app. ChangesUser Permissions and Metadata Curation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/auth/permissions.go (1)
19-21: ⚡ Quick winAvoid maintaining two separate sources for effective permissions.
effectiveAdminPermissionsduplicatesassignablePermissions. If a new permission is added in one place but not the other, admins can be authorized byHasEffectivePermissionwhile missing that permission inEffectivePermissions.Proposed refactor
-var effectiveAdminPermissions = []string{ - string(PermissionMetadataCuration), -} +func effectiveAdminPermissions() []string { + out := make([]string, 0, len(assignablePermissions)) + for p := range assignablePermissions { + out = append(out, string(p)) + } + sort.Strings(out) + return out +} ... if user.Role == "admin" { - return append([]string(nil), effectiveAdminPermissions...) + return effectiveAdminPermissions() }Also applies to: 75-77
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/auth/permissions.go` around lines 19 - 21, effectiveAdminPermissions duplicates assignablePermissions causing drift; remove the hardcoded duplication and derive the admin effective permissions from the single source assignablePermissions instead (e.g. reuse assignablePermissions or create a single helper like EffectivePermissionsForAdmin that returns assignablePermissions). Update any references to effectiveAdminPermissions and the other duplicated block (the one around lines 75-77) to call or reference the same assignablePermissions-based source so HasEffectivePermission and EffectivePermissions share one canonical permission list.web/src/pages/AdminUserDetail.tsx (1)
320-332: 💤 Low valueConsider extracting shared permission helpers.
hasAssignedPermissionandsetAssignedPermissionare duplicated in bothAdminUserDetail.tsxandAdminUsers.tsx. These could be co-located withPERMISSION_METADATA_CURATIONinlib/permissions.tsto avoid divergence.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/AdminUserDetail.tsx` around lines 320 - 332, Duplicate helper functions hasAssignedPermission and setAssignedPermission should be moved to the shared permissions module: create (or add to) lib/permissions.ts alongside PERMISSION_METADATA_CURATION, export both functions with the same signatures (hasAssignedPermission(permissions: string[] | undefined, permission: string) and setAssignedPermission(permissions: string[], permission: string, enabled: boolean)), update AdminUserDetail.tsx and AdminUsers.tsx to import these helpers from lib/permissions instead of declaring them locally, and run/adjust any type imports or tests affected by the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/auth/permissions.go`:
- Around line 19-21: effectiveAdminPermissions duplicates assignablePermissions
causing drift; remove the hardcoded duplication and derive the admin effective
permissions from the single source assignablePermissions instead (e.g. reuse
assignablePermissions or create a single helper like
EffectivePermissionsForAdmin that returns assignablePermissions). Update any
references to effectiveAdminPermissions and the other duplicated block (the one
around lines 75-77) to call or reference the same assignablePermissions-based
source so HasEffectivePermission and EffectivePermissions share one canonical
permission list.
In `@web/src/pages/AdminUserDetail.tsx`:
- Around line 320-332: Duplicate helper functions hasAssignedPermission and
setAssignedPermission should be moved to the shared permissions module: create
(or add to) lib/permissions.ts alongside PERMISSION_METADATA_CURATION, export
both functions with the same signatures (hasAssignedPermission(permissions:
string[] | undefined, permission: string) and setAssignedPermission(permissions:
string[], permission: string, enabled: boolean)), update AdminUserDetail.tsx and
AdminUsers.tsx to import these helpers from lib/permissions instead of declaring
them locally, and run/adjust any type imports or tests affected by the change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 79288549-9bf9-45ea-b394-90458fdcf778
📒 Files selected for processing (25)
internal/api/handlers/admin.gointernal/api/handlers/admin_jobs.gointernal/api/handlers/admin_jobs_test.gointernal/api/handlers/auth.gointernal/api/middleware/permissions.gointernal/api/middleware/permissions_test.gointernal/api/router.gointernal/auth/permissions.gointernal/auth/permissions_test.gointernal/auth/repository.gointernal/database/testdata/migrations/001_create_users.up.sqlinternal/models/user.gomigrations/001_schema.up.sqlmigrations/140_user_permissions.down.sqlmigrations/140_user_permissions.up.sqlweb/src/api/types.tsweb/src/components/admin/deviceOverrides.tsxweb/src/lib/permissions.tsweb/src/pages/AdminUserDetail.tsxweb/src/pages/AdminUsers.tsxweb/src/pages/ItemDetail/EpisodeContent.tsxweb/src/pages/ItemDetail/MovieContent.tsxweb/src/pages/ItemDetail/SeasonContent.tsxweb/src/pages/ItemDetail/SeriesContent.tsxweb/src/pages/ItemDetail/components/ActionBar.tsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/api/handlers/admin_jobs.go (1)
157-165: ⚡ Quick winSkip presigning artifact URLs for non-admin callers.
adminJobToResponseForClaimsbuilds the full response first, so non-admin reads still callPresignGetURLand then immediately stripDownloadURL/DownloadExpiresAt. That adds an unnecessary artifact-store dependency to a path that never returns the URL.♻️ Proposed fix
func adminJobToResponseForClaims( r *http.Request, job *models.AdminJob, store AdminJobArtifactStore, claims *auth.Claims, ) adminJobResponse { - response := adminJobToResponse(r, job, store) + if claims != nil && claims.Role == "admin" { + return adminJobToResponse(r, job, store) + } + + response := adminJobToResponse(r, job, nil) sanitizeAdminJobResponseForClaims(&response, claims) return response }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/admin_jobs.go` around lines 157 - 165, The current flow calls adminJobToResponse (which triggers store.PresignGetURL) for all callers then strips DownloadURL/DownloadExpiresAt in sanitizeAdminJobResponseForClaims, causing unnecessary presign calls; fix by making presigning conditional on the caller's admin status: update adminJobToResponseForClaims to check claims.IsAdmin and only invoke the presigning path (either by adding a skipPresign bool param to adminJobToResponse or by moving the PresignGetURL calls behind an if claims.IsAdmin) so non-admin requests never call store.PresignGetURL and non-admin responses keep DownloadURL/DownloadExpiresAt unset.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/api/handlers/admin_jobs.go`:
- Around line 157-165: The current flow calls adminJobToResponse (which triggers
store.PresignGetURL) for all callers then strips DownloadURL/DownloadExpiresAt
in sanitizeAdminJobResponseForClaims, causing unnecessary presign calls; fix by
making presigning conditional on the caller's admin status: update
adminJobToResponseForClaims to check claims.IsAdmin and only invoke the
presigning path (either by adding a skipPresign bool param to adminJobToResponse
or by moving the PresignGetURL calls behind an if claims.IsAdmin) so non-admin
requests never call store.PresignGetURL and non-admin responses keep
DownloadURL/DownloadExpiresAt unset.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 13cbfc60-a7db-4fb2-8dbe-856ded9c64b9
📒 Files selected for processing (8)
internal/api/handlers/admin.gointernal/api/handlers/admin_jobs.gointernal/api/handlers/admin_jobs_test.gointernal/auth/permissions.goweb/src/components/EditMetadataDialog.tsxweb/src/lib/permissions.tsweb/src/pages/AdminUserDetail.tsxweb/src/pages/AdminUsers.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
- web/src/pages/AdminUsers.tsx
- internal/auth/permissions.go
- internal/api/handlers/admin.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/api/handlers/admin_test.go (1)
5-11: ⚡ Quick winConsider table-driven tests for comprehensive revocation coverage.
According to the PR objectives, multiple fields trigger session revocation: role, enabled state, library access, playback quality, and permissions. A table-driven test would improve maintainability and ensure all revocation triggers are verified consistently.
📊 Example table-driven test structure
func TestUpdateRequiresSessionRevocation(t *testing.T) { tests := []struct { name string req updateUserRequest expected bool }{ { name: "permissions set triggers revocation", req: updateUserRequest{Permissions: updateStringSliceField{Set: true, Value: []string{"metadata_curation"}}}, expected: true, }, { name: "permissions not set does not trigger", req: updateUserRequest{Permissions: updateStringSliceField{Set: false}}, expected: false, }, // Add cases for Role, Enabled, LibraryIDs, PlaybackQuality, etc. } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := updateRequiresSessionRevocation(tt.req) if got != tt.expected { t.Errorf("updateRequiresSessionRevocation() = %v, want %v", got, tt.expected) } }) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/admin_test.go` around lines 5 - 11, Replace the single-case test TestUpdateRequiresSessionRevocation_ForPermissions with a table-driven test that iterates multiple cases calling updateRequiresSessionRevocation; include cases for Permissions (set vs unset), Role, Enabled, LibraryIDs, PlaybackQuality and any other fields that should trigger revocation, using updateUserRequest and updateStringSliceField to construct inputs, and assert the boolean result equals the expected value for each case; keep the original test name or create TestUpdateRequiresSessionRevocation and use t.Run with descriptive subtest names to make failures clear.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/admin_test.go`:
- Around line 5-11: Add a negative test alongside
TestUpdateRequiresSessionRevocation_ForPermissions that calls
updateRequiresSessionRevocation with an updateUserRequest where Permissions is
an updateStringSliceField with Set: false (and optionally Value matching
existing permissions) and assert it returns false; reference
updateRequiresSessionRevocation, updateUserRequest, and updateStringSliceField
so maintainers can locate the logic to ensure permission updates only trigger
revocation when Set is true.
---
Nitpick comments:
In `@internal/api/handlers/admin_test.go`:
- Around line 5-11: Replace the single-case test
TestUpdateRequiresSessionRevocation_ForPermissions with a table-driven test that
iterates multiple cases calling updateRequiresSessionRevocation; include cases
for Permissions (set vs unset), Role, Enabled, LibraryIDs, PlaybackQuality and
any other fields that should trigger revocation, using updateUserRequest and
updateStringSliceField to construct inputs, and assert the boolean result equals
the expected value for each case; keep the original test name or create
TestUpdateRequiresSessionRevocation and use t.Run with descriptive subtest names
to make failures clear.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: cb63155f-bd85-447b-9924-a5869a550980
📒 Files selected for processing (5)
internal/api/handlers/admin_jobs.gointernal/api/handlers/admin_jobs_test.gointernal/api/handlers/admin_test.gointernal/api/middleware/permissions.gointernal/api/router.go
🚧 Files skipped from review as they are similar to previous changes (4)
- internal/api/router.go
- internal/api/handlers/admin_jobs_test.go
- internal/api/handlers/admin_jobs.go
- internal/api/middleware/permissions.go
| input.MaxPlaybackQuality != nil || | ||
| input.Permissions != nil { | ||
| setClauses = append(setClauses, "access_policy_revision = access_policy_revision + 1") | ||
| } |
There was a problem hiding this comment.
Access policy revision bumped on every user edit
Medium Severity
The new access_policy_revision bump triggers when input.Role, input.Enabled, input.LibraryIDs, input.MaxPlaybackQuality, or input.Permissions is non-nil. However, both the AdminUserDetail and AdminUsers frontend forms always include role, permissions, enabled, library_ids, and max_playback_quality in the UpdateUserRequest body — even when those values haven't changed. This causes access_policy_revision to increment on every admin user edit (e.g., changing just a username), invalidating the user's existing tokens unnecessarily.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 46b10db. Configure here.
| userRepo, | ||
| apimw.NewPGMetadataTargetLibraryResolver(deps.DB), | ||
| ) | ||
| } |
There was a problem hiding this comment.
Redundant nested nil check on deps.DB
Low Severity
The if deps.DB != nil check at this location is nested inside the outer if deps.DB != nil && deps.Config != nil block, so deps.DB is guaranteed to be non-nil at this point. The conditional is always true and adds unnecessary indentation.
Reviewed by Cursor Bugbot for commit 46b10db. Configure here.
| } | ||
| value := append([]string(nil), f.Value...) | ||
| return &value | ||
| } |
There was a problem hiding this comment.
Unused Ptr() method on updateStringSliceField
Low Severity
The Ptr() method on updateStringSliceField is defined but never called anywhere. The handler at the update path directly accesses req.Permissions.Value and normalizes it inline, bypassing Ptr() entirely (unlike updateLibraryIDsField whose Ptr() IS used at req.LibraryIDs.Ptr()). This is dead code.
Reviewed by Cursor Bugbot for commit 41d2eeb. Configure here.
- Allow curators (not just admins) to view media file paths and locations - Apply library access filter to file-level access checks
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 4 total unresolved issues (including 3 from previous reviews).
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 7793597. Configure here.
| } | ||
| if len(filter.DisabledLibraryIDs) > 0 && intInSlice(file.MediaFolderID, filter.DisabledLibraryIDs) { | ||
| return false | ||
| } |
There was a problem hiding this comment.
Library access checks bypassed when quality is unrestricted
High Severity
New AllowedLibraryIDs and DisabledLibraryIDs checks were added to FileAllowedByAccess, but FilterMediaFilesByAccess still early-returns all files when MaxPlaybackQuality is empty — which is the database default. This means any user whose quality ceiling is unset (the common case) will bypass the new library-scoped file filtering entirely, potentially exposing media files from libraries outside their access.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 7793597. Configure here.
feat(auth): add metadata curation permission
feat(auth): add metadata curation permission
Six defects on byte-serving paths, all of which made the PR's monitoring and kill-switch claims narrower than documented. #2/GAP-10 -- the ABS in-flight kill switch was a production no-op. accessLog wraps every ABS route, and its statusRecorder implemented Write, WriteHeader, Hijack and Flush but not Unwrap, so http.NewResponseController dead-ended and SetWriteDeadline returned ErrNotSupported. A multi-GB audiobook pour survived a RevokeUser. The existing test passed throughout because it called handlers directly and never saw the middleware; the new test drives the mounted router over a real socket, and both new assertions fail if Unwrap is removed again. GAP-11 -- ebook, comic and PDF serving was invisible and un-killable: no meter, no transfer record, no Refuse, no watcher, on a route that serves cbz/cbr/pdf files routinely 100 MB-1 GB+. It now follows the ABS file-handler idiom. Note guardRevocationCut is deliberately *not* reused here: it keys on a session_id URL param and an ?st= token this route does not carry, so it would have compiled and silently guarded nothing. Cap-exempt per decision A4 -- admission is untouched and neither route consumes a stream slot. #10 -- the no-proxy remote transcode hop forwarded segments through a bare RollingDeadlineWriter, so bytes on the API hop went unaccounted for a supported topology. Metering is scoped to media bodies; manifests are excluded so a rewritten playlist is not counted as media, and a mid-copy failure is no longer silently discarded. #16 -- native, proxy and compat subtitle pours were entry-gated only. They now carry a transport span, a meter and an in-flight watcher. Proxy subtitle bytes are attributed only when a tracker record already exists: taking Track/Remove lifecycle ownership per subtitle request would walk straight into the overlapping-request defect (#1) that Batch 2 addresses. Compat subtitle extraction is buffered and rejects bitmap formats, so a cut stops delivery but not extraction already in progress. M2 -- the proxy deferred tracker Remove with the request context, which is already canceled on client disconnect, so the Redis DEL never happened and the key lingered until TTL -- a false over-cap window that could get a legitimate stream killed. Cleanup now uses a short bounded context. GAP-13 -- mergeStreams took the freshest record wholesale and never merged BytesServed, so a stream that poured 8 GiB at an edge could report 0. Merged as a max, not a sum: the records are two observers of one pour. Fixed in DedupeSessionInfos too, which had the same hole and feeds the admin view. #11 needed no behaviour change -- that route was already metered, registered and watched, and commit c24d839 plus this Unwrap fix are what make its cut work. Its comment claimed download-class exemption while the comment above it said the ?token= form is for iOS streaming; both facts and decision A4 are now stated. Part of #305.


Summary
metadata_curationas the first permission, including DB migration, repository support, and admin user CRUD wiring/meresponse and admin user APIs so clients can drive UI gatingPermissionMiddlewarethat authorizes item metadata curation routes (refresh, patch, match search/apply) for non-admin curators, scoped to their assigned librariesaccess_policy_revisionwhen admin edits change role, enabled state, library access, playback quality, or permissions, so stale claims are rejected after access-policy changesTesting
go test ./internal/api/handlers/... ./internal/api/middleware/... ./internal/auth/...— Passedcd web && pnpm run lint— Passed with 0 errors and existing warningscd web && pnpm run format:check— Run, failed on 18 pre-existing unformatted files outside this patchmake verify-local-paths— Passedmetadata_curationto a non-admin user and verify metadata refresh/match/patch endpoints succeed only within their library scope — Not runNote
High Risk
Expands who can mutate metadata and read partial admin job/path data; router and middleware changes are security-sensitive despite tests and sanitization.
Overview
Adds a
metadata_curationassignable permission end-to-end: users get apermissionscolumn and admin create/update APIs normalize and persist it;/meand admin user responses expose effective permissions.Authorization is split so non-admins with the permission can hit item metadata routes (refresh, patch, match) only when the item’s libraries fall within their assignment, via new
PermissionMiddleware. Most/adminroutes stay admin-only;GET /admin/jobs/{id}is reachable for curators to poll their own item-refresh jobs, with payloads/URLs stripped for non-admins. Curators can also see on-disk file paths where admins could before.Permission (and other access-policy) edits revoke sessions and bump
access_policy_revision. The web app gates metadata edit/refresh/match UI and admin user toggles on the new permission (image apply remains admin-only).Reviewed by Cursor Bugbot for commit 7793597. Bugbot is set up for automated code reviews on this repo. Configure here.
Summary by CodeRabbit
New Features
Behavior Change
Tests
Chores