Repository navigation
fix(web): show admin chrome only on the admin account's primary profile - #131
Conversation
The top-right ServerActivity indicator and the sidebar Admin section were gated on the account-level role alone, so every profile on an admin account — including child profiles — saw admin system notifications and the indicator polled four admin endpoints on their behalf. Gate both on the active profile being the household primary, matching the existing is_primary idiom in SettingsLayout and the server-side quota exemption. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Warning Review limit reached
More reviews will be available in 35 minutes. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more credits in the billing tab to continue. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughIntroduce an acting-admin policy: server middleware enforces primary-profile-aware admin checks and permission middleware uses the checker; router wires the checker into admin routes; frontend adds isActingAdmin/useIsActingAdmin and updates permission checks and many UI components to use the new hook. ChangesActing-admin policy and UI gating
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
🚥 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 unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@web/src/App.tsx`:
- Around line 175-180: The admin-gate logic in RequireAdmin (currently reading
profile from useAuth()) is inconsistent with the rest of the UI which uses
useCurrentProfile(); update RequireAdmin to derive the active profile via
useCurrentProfile() instead of useAuth(). Locate the gating checks in the
component that uses user/profile (the RequireAdmin logic in App.tsx) and replace
the profile reference with the value returned from useCurrentProfile(), keeping
the same role check on user from useAuth(); ensure you import useCurrentProfile
and maintain the existing primary-profile check (profile.is_primary) so Admin
routes match AppSidebar and Layout behavior.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1bdf703d-6622-4bc9-a9a0-bec841973f92
📒 Files selected for processing (3)
web/src/App.tsxweb/src/components/AppSidebar.tsxweb/src/components/Layout.tsx
… gates RequireAdmin/RequirePrimaryOrAdmin read the profile from useAuth(), but the admin chrome (AppSidebar, Layout) gates on useCurrentProfile(), which resolves the selected profile. Use the same source in the route gates so the redirect and the visible admin UI can never disagree. Co-Authored-By: Claude Fable 5 <[email protected]>
Address code-review findings on the primary-profile admin gate: - Add isActingAdmin to web/src/lib/permissions.ts as the single client-side definition of the policy (admin role + primary or no profile), with a useIsActingAdmin hook on top. Route gates, sidebar, Layout, and realtime channel gating all use it now, so the gate and the chrome can no longer disagree on null-profile handling. - Convert the admin-gated surfaces the original change missed (MediaItemMenu, EditMetadataDialog images tab, AddToCollectionDialog, MarkerEditor, theme CatalogBrowser, PersonDetail, SettingsLayout, ItemDetail content pages) so an admin on a non-primary profile is a regular viewer everywhere, not just in the sidebar. - Make the role-derived permission bypass (metadata curation, marker edit) follow the same policy on both client and server. - Enforce the policy server-side: RequireActingAdmin middleware refuses admin routes when the request declares a non-primary profile via X-Profile-Id, and the metadata-curation middleware holds admins on non-primary profiles to explicitly assigned permissions. - Stop spreading the profiles query result from useCurrentProfile so route gates only re-render when the resolved profile changes, and make it safe outside AuthProvider. Co-Authored-By: Claude Fable 5 <[email protected]>
Code review follow-up — addressed in a18f1e2A review pass over this PR surfaced 7 findings (3 correctness/consistency, 2 completeness, 2 quality). All are addressed: 1. Policy was UI-only — no server enforcement ✅ 2. Other admin-gated surfaces were missed ✅ 3. Gate vs. chrome disagreed on null profile ✅ 4. Predicate duplicated 4 ways with variant semantics ✅ 5. Two sources of truth for the current profile across gates ✅ 6. 7. Stale cached Behavior change to note: Verification: full 🤖 Generated with Claude Code |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
internal/api/middleware/permissions_test.go (1)
56-77: ⚡ Quick winAdd a regression test for the checker-error path.
RequireMetadataCurationForItemnow returns500 internal_errorwhencheckPrimaryfails, but the new profile-aware tests only cover allow/forbid outcomes. A single case here would lock down that new failure-mode contract.Also applies to: 79-100
🤖 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/middleware/permissions_test.go` around lines 56 - 77, Add a regression test that asserts RequireMetadataCurationForItem returns HTTP 500 when the PrimaryProfileChecker returns an error: update the test using runMetadataCurationMiddlewareWithProfile by passing a fake checker implementation that returns (false, error) (or make checkPrimary return an error) and assert the response code is http.StatusInternalServerError; replicate the same error-case test in the other profile-aware test block covering lines 79-100 so the new failure-mode contract is locked down.web/src/components/RealtimeEventsProvider.test.tsx (1)
26-32: ⚡ Quick winAdd a non-primary-profile fixture for the new fallback path.
This mock still renders the provider as acting admin (
profile: null), so the new!actingAdminbranch inawaitAdminJob(...)never gets exercised here. A focused case withprofile: { id: "kid", is_primary: false }would lock in the "poll instead of waiting on admin channels" behavior that this PR is relying on.🤖 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/components/RealtimeEventsProvider.test.tsx` around lines 26 - 32, The test mock for authentication always returns profile: null so the !actingAdmin branch in awaitAdminJob(...) is never exercised; add a focused fixture and test that returns useAuth/useOptionalAuth => { user: mockState.user, profile: { id: "kid", is_primary: false } } (or create a separate test case that swaps the mock) and assert that awaitAdminJob falls back to polling rather than waiting on admin channels; update RealtimeEventsProvider.test.tsx to include this non-primary-profile mock and the corresponding expectation.
🤖 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/middleware/auth.go`:
- Around line 213-230: The actingAdminAllowed function currently treats an
unresolved profile (found == false) as allowed; change it to fail-closed: after
calling checkPrimary(r.Context(), userID, profileID) return false, nil when
found is false, and only allow when isPrimary is true. Keep the existing
early-returns for checkPrimary == nil and empty declaredProfileID(r) unchanged;
update the final return logic so it returns isPrimary (not !found || isPrimary)
and still propagate errors from checkPrimary.
In `@web/src/hooks/useIsActingAdmin.ts`:
- Around line 10-13: useIsActingAdmin currently treats profile null the same for
"no profile selected" and "profile still loading", causing transient admin
access; update useCurrentProfile to expose an explicit unresolved/loading flag
(e.g., return { profile, isProfileUnresolved } or similar) and then change
useIsActingAdmin to early-return false while that unresolved flag is true before
calling isActingAdmin(user, profile); ensure types/signatures for
useCurrentProfile and useIsActingAdmin are updated accordingly so callers can
rely on the explicit unresolved state.
In `@web/src/lib/permissions.ts`:
- Around line 25-35: The profile parameter in hasPermission must fail closed
instead of treating undefined like null; update hasPermission (and its callers)
so profile is required or undefined is rejected: either remove the optional
marker so the signature is profile: Pick<Profile,"is_primary"> | null and update
all call sites to pass a resolved profile or explicit null, or add an explicit
guard at the top of hasPermission (if (profile === undefined) throw new
Error("profile must be provided or explicit null")) before calling
isActingAdmin(user, profile) to force callers to supply the resolved profile or
explicit null; ensure references to isActingAdmin and hasPermission are updated
accordingly.
---
Nitpick comments:
In `@internal/api/middleware/permissions_test.go`:
- Around line 56-77: Add a regression test that asserts
RequireMetadataCurationForItem returns HTTP 500 when the PrimaryProfileChecker
returns an error: update the test using runMetadataCurationMiddlewareWithProfile
by passing a fake checker implementation that returns (false, error) (or make
checkPrimary return an error) and assert the response code is
http.StatusInternalServerError; replicate the same error-case test in the other
profile-aware test block covering lines 79-100 so the new failure-mode contract
is locked down.
In `@web/src/components/RealtimeEventsProvider.test.tsx`:
- Around line 26-32: The test mock for authentication always returns profile:
null so the !actingAdmin branch in awaitAdminJob(...) is never exercised; add a
focused fixture and test that returns useAuth/useOptionalAuth => { user:
mockState.user, profile: { id: "kid", is_primary: false } } (or create a
separate test case that swaps the mock) and assert that awaitAdminJob falls back
to polling rather than waiting on admin channels; update
RealtimeEventsProvider.test.tsx to include this non-primary-profile mock and the
corresponding expectation.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d37ee409-168c-4e1f-8e38-9f6e62b4d463
📒 Files selected for processing (30)
internal/api/middleware/acting_admin_test.gointernal/api/middleware/auth.gointernal/api/middleware/permissions.gointernal/api/middleware/permissions_test.gointernal/api/router.goweb/src/App.tsxweb/src/components/AddToCollectionDialog.tsxweb/src/components/AppSidebar.test.tsxweb/src/components/AppSidebar.tsxweb/src/components/EditMetadataDialog.tsxweb/src/components/Layout.tsxweb/src/components/MediaItemMenu.tsxweb/src/components/RealtimeEventsProvider.test.tsxweb/src/components/RealtimeEventsProvider.tsxweb/src/components/markers/MarkerEditor.tsxweb/src/components/theme/CatalogBrowser.tsxweb/src/hooks/useCurrentProfile.tsweb/src/hooks/useIsActingAdmin.tsweb/src/lib/permissions.tsweb/src/pages/ItemDetail/EpisodeContent.test.tsxweb/src/pages/ItemDetail/EpisodeContent.tsxweb/src/pages/ItemDetail/MovieContent.test.tsxweb/src/pages/ItemDetail/MovieContent.tsxweb/src/pages/ItemDetail/SeasonContent.test.tsxweb/src/pages/ItemDetail/SeasonContent.tsxweb/src/pages/ItemDetail/SeriesContent.tsxweb/src/pages/PersonDetail.tsxweb/src/pages/SettingsLayout.test.tsxweb/src/pages/SettingsLayout.tsxweb/src/playback/WatchPlaybackChrome.tsx
✅ Files skipped from review due to trivial changes (1)
- web/src/pages/ItemDetail/EpisodeContent.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/components/AppSidebar.tsx
Address review feedback on the acting-admin gate: - Server: actingAdminAllowed now denies when the declared profile cannot be resolved to one of the caller's profiles, so a bogus X-Profile-Id can no longer restore admin powers to a non-primary session. - Client: useIsActingAdmin returns false while a selected profile id has not yet resolved (e.g. hard refresh before the profiles query returns), instead of briefly treating it as "no profile selected". useCurrentProfile exposes hasSelectedProfile to make that state distinguishable. - hasPermission/canCurateMetadata/canEditMarkers now require the profile argument (resolved profile or explicit null), so a missed call site fails the typecheck instead of silently restoring the admin bypass. Co-Authored-By: Claude Fable 5 <[email protected]>
…le (#131) * fix(web): show admin chrome only on the admin account's primary profile The top-right ServerActivity indicator and the sidebar Admin section were gated on the account-level role alone, so every profile on an admin account — including child profiles — saw admin system notifications and the indicator polled four admin endpoints on their behalf. Gate both on the active profile being the household primary, matching the existing is_primary idiom in SettingsLayout and the server-side quota exemption. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web): resolve active profile via useCurrentProfile in admin route gates RequireAdmin/RequirePrimaryOrAdmin read the profile from useAuth(), but the admin chrome (AppSidebar, Layout) gates on useCurrentProfile(), which resolves the selected profile. Use the same source in the route gates so the redirect and the visible admin UI can never disagree. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web,api): centralize acting-admin policy and enforce it server-side Address code-review findings on the primary-profile admin gate: - Add isActingAdmin to web/src/lib/permissions.ts as the single client-side definition of the policy (admin role + primary or no profile), with a useIsActingAdmin hook on top. Route gates, sidebar, Layout, and realtime channel gating all use it now, so the gate and the chrome can no longer disagree on null-profile handling. - Convert the admin-gated surfaces the original change missed (MediaItemMenu, EditMetadataDialog images tab, AddToCollectionDialog, MarkerEditor, theme CatalogBrowser, PersonDetail, SettingsLayout, ItemDetail content pages) so an admin on a non-primary profile is a regular viewer everywhere, not just in the sidebar. - Make the role-derived permission bypass (metadata curation, marker edit) follow the same policy on both client and server. - Enforce the policy server-side: RequireActingAdmin middleware refuses admin routes when the request declares a non-primary profile via X-Profile-Id, and the metadata-curation middleware holds admins on non-primary profiles to explicitly assigned permissions. - Stop spreading the profiles query result from useCurrentProfile so route gates only re-render when the resolved profile changes, and make it safe outside AuthProvider. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web,api): fail closed on unresolved profiles in acting-admin policy Address review feedback on the acting-admin gate: - Server: actingAdminAllowed now denies when the declared profile cannot be resolved to one of the caller's profiles, so a bogus X-Profile-Id can no longer restore admin powers to a non-primary session. - Client: useIsActingAdmin returns false while a selected profile id has not yet resolved (e.g. hard refresh before the profiles query returns), instead of briefly treating it as "no profile selected". useCurrentProfile exposes hasSelectedProfile to make that state distinguishable. - hasPermission/canCurateMetadata/canEditMarkers now require the profile argument (resolved profile or explicit null), so a missed call site fails the typecheck instead of silently restoring the admin bypass. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Code <[email protected]> Co-authored-by: Quick <[email protected]>
Problem
The admin system-activity indicator (the upper-right notifications) and the sidebar Admin section were gated on the account-level role alone (
user?.role === "admin"). Silo separates login accounts from household profiles, so every profile on an admin account — including a kid's profile — saw the admin chrome. The activity indicator also polls four admin endpoints (useAdminSessions,useTasks,useActiveScans,useAdminLibraries) on behalf of whoever is looking at it, so non-primary profiles were fetching other users' active sessions, scan and task state. On top of that,/admincould be deep-linked by URL from any profile on the account.Fix
The policy is "an admin account only acts with admin powers through its household primary profile (or with no profile selected, e.g. right after login)", and it now lives in exactly one place per side:
Client
isActingAdmin(user, profile)inweb/src/lib/permissions.tsis the single definition; theuseIsActingAdmin()hook wraps it for components. Route gates (RequireAdmin,RequirePrimaryOrAdmin), the sidebar Admin link, theServerActivitychrome, and the admin realtime channel subscription all share it, so the gate and the visible UI can no longer disagree about null-profile handling.hasPermission→ metadata curation, marker editing) follows the same policy: an admin on a non-primary profile keeps only explicitly assigned permissions.useCurrentProfileno longer spreads the whole react-query result (which defeated TanStack v5 tracked-properties and re-rendered route-gate subtrees on everyisFetchingflip); it returns{ profile, isLoading }and is safe outsideAuthProvider.Server
RequireActingAdminmiddleware replacesRequireAdminon the admin route groups: when a request declares an active profile (X-Profile-Id) that belongs to the admin account but is not primary, admin endpoints return 403. Requests with no declared profile behave as before.X-Profile-Idis client-asserted, so this is a policy boundary for well-behaved clients (including PIN-locked profiles using stock clients), not a defense against the account holder. A hard boundary would require profile tokens on admin routes — out of scope here.Why this approach
It matches the idiom the codebase already established:
SettingsLayout.tsxgates profile management onis_primary, and the server-side transcription-quota exemption (#127 follow-up) treats "admin account acting as itself or through its primary profile" as the privileged combination — other profiles on the admin account are regular viewers. Centralizing the predicate (one function per side) follows the repo guideline that duplicate logic across files is a code smell.Behavior changes to note
/admin/*while that profile is declared. Switching to the primary profile (or deselecting the profile) restores everything.RequirePrimaryOrAdmin-gated settings (household profile management) are now also closed to an admin acting through a non-primary profile.Follow-up candidates
Verification
go build ./internal/...,go vet ./internal/api/..., fullgo test ./internal/api/...pass; new middleware tests cover primary/non-primary/no-profile/unknown-profile/checker-error paths for bothRequireActingAdminand the curation bypass.tsc -b+ vite), ESLint (0 errors, warnings pre-existing), prettier, and the full frontend suite (187 files / 1,033 tests) pass.AI-use disclosure
Diagnosed, implemented, and verified with Claude Code under human direction and review.
🤖 Generated with Claude Code
Summary by CodeRabbit
Changes
Tests