Skip to content

feat(auth): add metadata curation permission - #11

Merged
Quick104 merged 12 commits into
mainfrom
t3code/eb3dedf1
May 27, 2026
Merged

Quick104 merged 12 commits into
mainfrom
t3code/eb3dedf1

Conversation

@Quick104

@Quick104 Quick104 commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Introduce assignable per-user permissions with metadata_curation as the first permission, including DB migration, repository support, and admin user CRUD wiring
  • Expose user permissions on the auth /me response and admin user APIs so clients can drive UI gating
  • Add a PermissionMiddleware that authorizes item metadata curation routes (refresh, patch, match search/apply) for non-admin curators, scoped to their assigned libraries
  • Restrict admin job detail access so non-admins can only read their own item-refresh jobs, with sensitive fields stripped
  • Bump access_policy_revision when admin edits change role, enabled state, library access, playback quality, or permissions, so stale claims are rejected after access-policy changes
  • Surface metadata tools in the web UI to users with the new permission via permission helpers and ItemDetail/ActionBar/deviceOverrides updates, and fix a conditional hook in deviceOverrides

Testing

  • go test ./internal/api/handlers/... ./internal/api/middleware/... ./internal/auth/... — Passed
  • cd web && pnpm run lint — Passed with 0 errors and existing warnings
  • cd web && pnpm run format:check — Run, failed on 18 pre-existing unformatted files outside this patch
  • make verify-local-paths — Passed
  • Manual: assign metadata_curation to a non-admin user and verify metadata refresh/match/patch endpoints succeed only within their library scope — Not run

Note

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_curation assignable permission end-to-end: users get a permissions column and admin create/update APIs normalize and persist it; /me and 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 /admin routes 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

    • Per-user permissions added with a "Metadata Curation" permission; admins can view/set it in user management.
    • UI now gates metadata refresh/edit actions and dialogs by the new permission (not just admin).
  • Behavior Change

    • Server enforces metadata-curation checks on item metadata endpoints and revokes sessions when permissions are explicitly changed.
    • Admin job responses are sanitized for non-admin callers, hiding sensitive payloads and URLs.
  • Tests

    • Added unit tests for permission logic, middleware authorization, and admin-job response sanitization.
  • Chores

    • Database migration adds a permissions column to users.

Review Change Stack

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c1fd3b23-0105-4451-a58d-3a9d8e11064b

📥 Commits

Reviewing files that changed from the base of the PR and between 41d2eeb and 7793597.

📒 Files selected for processing (6)
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/items.go
  • internal/catalog/access_filter.go
  • web/src/hooks/useAuth.test.ts
  • web/src/pages/ItemDetail/EpisodeContent.tsx
  • web/src/pages/ItemDetail/MovieContent.tsx

📝 Walkthrough

Walkthrough

Adds 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.

Changes

User Permissions and Metadata Curation

Layer / File(s) Summary
Permission contract and model updates
internal/auth/permissions.go, internal/models/user.go, internal/auth/permissions_test.go
Defines Permission type and PermissionMetadataCuration, normalization and effective/assigned permission checks; adds Permissions to User and create/update inputs.
Database schema and migrations
migrations/140_user_permissions.up.sql, migrations/140_user_permissions.down.sql, migrations/001_schema.up.sql, internal/database/testdata/migrations/001_create_users.up.sql
Adds non-null permissions text[] column with default empty array and backfills existing rows; testdata migration updated.
Repository persistence layer
internal/auth/repository.go
Includes permissions in row projection/scan; Create/Update normalize and persist permissions; Update increments access_policy_revision when permissions change.
Admin user creation and updates with permissions
internal/api/handlers/admin.go
Admin create/update request shapes accept permissions; handlers normalize permissions and pass them into model inputs; admin responses include permissions; permission updates trigger session revocation.
Admin job authorization & sanitization
internal/api/handlers/admin_jobs.go, internal/api/handlers/admin_jobs_test.go
HandleGet authorizes by request claims (canReadAdminJob); non-admin responses are sanitized (blank request payload, strip URLs, whitelist safe item_refresh result fields). Tests validate authorization and sanitization.
Permission middleware and resolver
internal/api/middleware/permissions.go, internal/api/middleware/permissions_test.go
Introduces RequireMetadataCurationForItem middleware, PG-backed MetadataTargetLibraryResolver, library-ownership checks, JSON error writer, and unit tests covering admin/permission/library scenarios.
Router integration for metadata access
internal/api/router.go
Wires PermissionMiddleware when DB present and refactors /admin routes so metadata-item endpoints use metadata-access middleware (permission or RequireAdmin fallback).
Current user response includes permissions
internal/api/handlers/auth.go
Current-user response now includes effective permissions via auth.EffectivePermissions.
Web API types and permission helpers
web/src/api/types.ts, web/src/lib/permissions.ts
Adds permissions to API types; client helpers expose PERMISSION_METADATA_CURATION, hasPermission/canCurateMetadata, and utilities to toggle assigned permissions.
Web admin user management UI
web/src/pages/AdminUserDetail.tsx, web/src/pages/AdminUsers.tsx
Admin user forms and overview show and allow editing the Metadata Curation permission; create/update requests include permissions.
Web item detail gating and ActionBar changes
web/src/pages/ItemDetail/*, web/src/pages/ItemDetail/components/ActionBar.tsx, web/src/components/EditMetadataDialog.tsx
Item detail pages compute per-user canCurateMetadata and gate metadata refresh/edit/match actions; ActionBar accepts canCurateMetadata prop; EditMetadataDialog hides images for non-admins and uses effectiveActiveSection.
Catalog item file-path access gating
internal/api/handlers/catalog_resources.go, internal/api/handlers/items.go
File and folder path visibility now depends on handler-level requestCanViewFilePaths which enforces metadata curation permission for non-admins.
Catalog access filter library scoping
internal/catalog/access_filter.go
Enforces AllowedLibraryIDs/DisabledLibraryIDs checks before resolution/quality rules.
Minor component optimization
web/src/components/admin/deviceOverrides.tsx
DeviceProfileTabs memoizes derived values and early-exits when active is null.
Test fixtures update
web/src/hooks/useAuth.test.ts
Adds permissions: [] to mocked User in auth test fixture.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 I nibble through code, permissions in tow,
A curation key where only some may go.
DB seeds the list, middleware guards the gate,
Frontend toggles bloom, handlers validate.
Hop—now metadata's kept tidy and right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.35% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(auth): add metadata curation permission' directly and clearly summarizes the primary change: introducing a new metadata curation permission system to the authentication layer.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch t3code/eb3dedf1

Comment @coderabbitai help to get the list of available commands and usage tips.

Comment thread internal/api/handlers/admin.go Resolved
Comment thread web/src/pages/AdminUsers.tsx Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
internal/auth/permissions.go (1)

19-21: ⚡ Quick win

Avoid maintaining two separate sources for effective permissions.

effectiveAdminPermissions duplicates assignablePermissions. If a new permission is added in one place but not the other, admins can be authorized by HasEffectivePermission while missing that permission in EffectivePermissions.

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 value

Consider extracting shared permission helpers.

hasAssignedPermission and setAssignedPermission are duplicated in both AdminUserDetail.tsx and AdminUsers.tsx. These could be co-located with PERMISSION_METADATA_CURATION in lib/permissions.ts to 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

📥 Commits

Reviewing files that changed from the base of the PR and between a5fbaaf and c89346f.

📒 Files selected for processing (25)
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_jobs.go
  • internal/api/handlers/admin_jobs_test.go
  • internal/api/handlers/auth.go
  • internal/api/middleware/permissions.go
  • internal/api/middleware/permissions_test.go
  • internal/api/router.go
  • internal/auth/permissions.go
  • internal/auth/permissions_test.go
  • internal/auth/repository.go
  • internal/database/testdata/migrations/001_create_users.up.sql
  • internal/models/user.go
  • migrations/001_schema.up.sql
  • migrations/140_user_permissions.down.sql
  • migrations/140_user_permissions.up.sql
  • web/src/api/types.ts
  • web/src/components/admin/deviceOverrides.tsx
  • web/src/lib/permissions.ts
  • web/src/pages/AdminUserDetail.tsx
  • web/src/pages/AdminUsers.tsx
  • web/src/pages/ItemDetail/EpisodeContent.tsx
  • web/src/pages/ItemDetail/MovieContent.tsx
  • web/src/pages/ItemDetail/SeasonContent.tsx
  • web/src/pages/ItemDetail/SeriesContent.tsx
  • web/src/pages/ItemDetail/components/ActionBar.tsx

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
internal/api/handlers/admin_jobs.go (1)

157-165: ⚡ Quick win

Skip presigning artifact URLs for non-admin callers.

adminJobToResponseForClaims builds the full response first, so non-admin reads still call PresignGetURL and then immediately strip DownloadURL/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

📥 Commits

Reviewing files that changed from the base of the PR and between c89346f and 539a5c5.

📒 Files selected for processing (8)
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_jobs.go
  • internal/api/handlers/admin_jobs_test.go
  • internal/auth/permissions.go
  • web/src/components/EditMetadataDialog.tsx
  • web/src/lib/permissions.ts
  • web/src/pages/AdminUserDetail.tsx
  • web/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/api/handlers/admin_test.go (1)

5-11: ⚡ Quick win

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 539a5c5 and 46b10db.

📒 Files selected for processing (5)
  • internal/api/handlers/admin_jobs.go
  • internal/api/handlers/admin_jobs_test.go
  • internal/api/handlers/admin_test.go
  • internal/api/middleware/permissions.go
  • internal/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

Comment thread internal/api/handlers/admin_test.go Resolved
input.MaxPlaybackQuality != nil ||
input.Permissions != nil {
setClauses = append(setClauses, "access_policy_revision = access_policy_revision + 1")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 46b10db. Configure here.

Comment thread internal/api/router.go
userRepo,
apimw.NewPGMetadataTargetLibraryResolver(deps.DB),
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 46b10db. Configure here.

}
value := append([]string(nil), f.Value...)
return &value
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

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
@Quick104
Quick104 merged commit c85ea1c into main May 27, 2026
1 of 2 checks passed
@Quick104
Quick104 deleted the t3code/eb3dedf1 branch May 27, 2026 00:05

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 4 total unresolved issues (including 3 from previous reviews).

Fix All in Cursor

❌ 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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7793597. Configure here.

CoffeeKnyte added a commit that referenced this pull request Jul 31, 2026
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.
@kody-ai kody-ai Bot mentioned this pull request Sep 27, 2026
2 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant