Repository navigation
fix(catalog): return nothing when a requested library is outside the viewer's access - #1953
Conversation
…viewer's access A catalog query for a library the viewer cannot access, or one that does not exist, intersected to an empty library set. The preview plan then emitted no library predicate and returned the whole catalog, with totals. Narrow requested libraries through one helper that reports when a requested or imposed scope leaves no library, and make the preview plan match nothing in that case for item and episode scopes. The episode entries fast path and the search sort expression use the same helper.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 44 minutes. View limit detailsLimit details: You’ve used all 4 included reviews currently available. Review configuration: ⚙️ Run configuration
📒 Files selected for processing (8)
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (6)
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review. 📝 WalkthroughWalkthroughCatalog query paths now share effective library-scope resolution. Empty requested or restricted scopes produce no matches. Unit and database-backed tests cover scope handling across query types and paging modes. ChangesCatalog library access scope
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Bug fix Suggested reviewers: Merge Risk: ⚪ Minimal · up to No actionable issue remains that would prevent merging after normal checks. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The change tightens library access and consistently scopes results and totals. No introduced security issue was identified in the inspected paths, but end-to-end account/profile request handling and deployment validation remain incomplete. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 5 files. (1 skipped: 1 unsupported.) ✨ 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 |
Quick104
left a comment
There was a problem hiding this comment.
The fix is correct. In buildPreviewPagePlan, singleEpisodeCatalogLibraryID and the search sort path, I traced every combination of no request, nil or empty allowlist, a request with no overlap, disabled libraries, and an unrestricted viewer asking for a nonexistent library. Each one now matches nothing where it should. The inline comments are a test gap and cleanup, and none of them blocks the fix.
The same bug one layer up (medium, pre-existing, needs your call). intersectCatalogDefinitionLibraries (internal/catalog/catalog_resolver.go:1990) returns nil when a live smart collection's saved library_ids don't overlap the collection's own libraries. Its callers (catalog_resolver.go:716/718 and :2142/2144, catalog_collection_cursor.go:100/102) write that nil back into def.LibraryIDs, so effectiveLibraryScope sees no request and 1 = 0 never fires.
- Trigger: an admin saves a collection on library 2 whose definition has
library_ids: [1](create and update don't cross-check the two), or library 1 is deleted from a collection on [1, 2] whose definition names [1]. - Impact:
source=library_collectionreturns every library to an unrestricted viewer and every allowed library to a restricted one. It never goes past the viewer's allowlist, so the result is wrong collection contents, not an access leak. The legacy collection handler and jellycompat already return empty in this case. - Repair: have that helper report an empty intersection, and map it to the same empty result.
I found this by reading the code and did not reproduce it against a database. Your call whether it belongs in this PR or a follow-up.
Validation line. Validation tasks: lists passed cases only. #1250 C4 hasn't been run, and this change reaches no passed case on the board, so the line should read Validation tasks: none. #1250 C4 and C3 can be mentioned in prose as cases to walk once they run.
AI disclosure: review by claude-opus-5-5 in Claude Code via T3 Code (/silo code-review).
| {name: "accessible library", requested: []int{3}, allowed: []int{3, 4}}, | ||
| {name: "unrestricted viewer, nonexistent library", requested: []int{999}}, |
There was a problem hiding this comment.
Test gap (medium). Both rows that expect results bind a value equal to tc.requested: [3] ∩ [3, 4] is [3], and an unrestricted [999] stays [999]. So this test can't tell whether buildPreviewPagePlan binds the effective scope or the raw def.LibraryIDs.
If one of the three uses of libraryIDs in buildPreviewPagePlan (query_executor.go:331, :346, :392) went back to def.LibraryIDs, a restricted viewer with no library_id would get no library predicate from the plan. Every test here and in TestEffectiveLibraryScope would still pass.
Repair: add a wantBound []int field and two rows. No request with allowed [3, 4] should bind [3, 4], and requested [1, 3] with allowed [3] should bind [3].
There was a problem hiding this comment.
Added a wantBound field with the two rows: no request with allowed [3, 4] binds [3, 4], and requested [1, 3] with allowed [3] binds [3]. Pointing the plan back at def.LibraryIDs now fails both rows in every scope (963ffd1).
| // Sort expression only: the relation above already applied the access | ||
| // predicate, including an empty effective library scope. |
There was a problem hiding this comment.
The comment overstates the guarantee (low). The relation reads def.LibraryIDs only when def.Groups is non-empty. Without groups, the empty-scope case is safe only because catalogSearchAccess has already narrowed AllowedLibraryIDs and returned early when nothing was left. A future caller that passed LibraryIDs: [1] with AllowedLibraryIDs: [3] and no groups would get library 3 results, and the discarded empty wouldn't flag it. No current caller does this.
Repair: state the precondition in the comment.
| // Sort expression only: the relation above already applied the access | |
| // predicate, including an empty effective library scope. | |
| // Sort expression only. Callers pass access already narrowed to the | |
| // requested libraries (catalogSearchAccess returns early when that is | |
| // empty), so the relation above enforces the library scope. |
| // set means the viewer is unrestricted. empty reports that a scope was | ||
| // requested or imposed but no library survived, so the caller must match | ||
| // nothing: an empty ID list must never be read as "no library filter". | ||
| func effectiveLibraryScope(requested, allowed []int) (ids []int, empty bool) { |
There was a problem hiding this comment.
Duplicate helper (low, needs your call). effectiveCatalogLibraryIDs (catalog_resolver.go:2484) already computes requested ∩ allowed with empty meaning match nothing, and it also drops disabled libraries. intersectOptionalInts (recent_tv.go:974) is a third copy of the nil-means-unrestricted rule.
Results agree today, because buildLibraryScopeJoin applies the disabled-library predicate separately, so this isn't a bug. The cost is that the next fail-closed fix can land in one helper and miss the others, which is how this bug got in.
Repair: build this helper on effectiveCatalogLibraryIDs, or move the rule onto AccessFilter so sections and jellycompat can use it too. A follow-up is fine.
There was a problem hiding this comment.
Fixed in ed0018c: effectiveLibraryScope is now a one-line call to effectiveCatalogLibraryIDs with only the allowlist, because its callers exclude disabled libraries in their own clause. The existing table test passes unchanged, so the requested-and-allowed rule has one implementation. intersectOptionalInts in recent_tv.go is outside this diff and serves sections, so I left it. Moving the rule onto AccessFilter for sections and jellycompat fits better in a follow-up.
| argIdx += len(libScopeArgs) | ||
| } else if access.AllowedLibraryIDs != nil && len(access.AllowedLibraryIDs) == 0 { | ||
| } | ||
| if libraryScopeEmpty { |
There was a problem hiding this comment.
Efficiency (low, unmeasured). When libraryScopeEmpty is true, the result is known before any SQL runs, but the executor still builds the plan and makes a Postgres round trip, plus a count query when offset > 0. Postgres should fold 1 = 0 into a one-time filter, so the cost is probably small; I didn't measure it. The resolver's browse paths and singleEpisodeCatalogLibraryID return early instead.
Optional repair: carry an empty flag on the plan and return an empty page from PreviewPage and PreviewCursorPage before querying. Keeping 1 = 0 as a backstop still makes sense.
There was a problem hiding this comment.
Leaving this as is. The empty case only happens when a restricted viewer asks for a library outside its access, and Postgres folds 1 = 0 into a one-time filter, so an early-return path in both page methods would add code for a rare request with little saving.
| if len(libraryIDs) == 0 { | ||
| if access.AllowedLibraryIDs != nil { | ||
| return 0, true, true | ||
| } | ||
| return 0, false, false | ||
| } |
There was a problem hiding this comment.
Nit. After the empty return above, this branch returns the same tuple as the len(libraryIDs) != 1 check below, so it can go.
| if len(libraryIDs) == 0 { | |
| if access.AllowedLibraryIDs != nil { | |
| return 0, true, true | |
| } | |
| return 0, false, false | |
| } |
The plan test only checked scopes equal to the raw request, so it could not tell whether the plan binds the effective scope. Add a restricted viewer with no request and a partly accessible request. Also state the search sort path's precondition in its comment and drop a branch in singleEpisodeCatalogLibraryID that the next check already covers.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
…raryIDs Keep one implementation of the requested-and-allowed library rule so a later fail-closed fix cannot land in one copy and miss the other.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
From the review summary:
|
… libraries miss its own A live library collection whose saved library_ids don't overlap the collection's libraries widened to every library the viewer can see, because the empty intersection was written back as no library scope. All three read paths (offset, base items, cursor) now return an empty result instead.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Update on the review summary: the smart-collection case is now fixed here instead of in a follow-up (c465a7e). |
|
Silo's pull request guidance changed today (#2016). A PR that changes what a user sees now needs before-and-after evidence in its Evidence section, and a PR with no visible change says Missing here: Before-and-after v2 catalog response excerpts of the same restricted-viewer request with an inaccessible library_id, and before-and-after captures of the affected smart collection. The rules are in Show visible changes, and the PR template shows the Evidence section layout. I've converted this PR to draft for now. Mark it ready for review once the Evidence section is filled in. Generated by Claude Code |
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
…mpty main doesn't compile at ca4f71b: Silo-Server#1953 added a two-value return to loadCollectionSource after Silo-Server#1984 gave the function a third result, the collection title. Return the title with no items, the same as the other paths in the function, so the Go jobs can build. This is the one-line fix main needs. It isn't part of the Cast & Crew change and can be dropped once main has its own fix.
…2018) * fix(catalog): return the collection title when its library scope is empty main doesn't compile at ca4f71b: #1953 added a two-value return to loadCollectionSource after #1984 gave the function a third result, the collection title. Return the title with no items, the same as the other paths in the function, so the Go jobs can build. This is the one-line fix main needs. It isn't part of the Cast & Crew change and can be dropped once main has its own fix. (cherry picked from commit f9cb264) * feat(people): add a Creator credit for series creators Silo had no credit type for a series' creators, so a plugin sending "Creator" had it stored as Producer. Add PersonKindCreator, map "Creator" from plugins and crew jobs, and have the series "Created by" line prefer Creator credits, falling back to Director credits. Movies and episodes keep leading with directors, so a series' creators don't appear as "Directed by" on its episodes. * test(models): name the Creator string once in its test Changed-line lint (goconst) counted the literal three times across the models package. * feat(people): list every creator in a series' Crew section The hero line names a series' first two creators, and the Crew section only listed Directors, Writers and Producers, so a third creator didn't appear anywhere on the series page. CrewList now takes the jobs to list, and the series page passes Creator ahead of the usual three, linking each creator to their person page like the rest of the crew. Season, episode and movie pages keep the default list, so a series' creators don't show up on them. * docs(web): document the CrewList component
Conflict resolution: - internal/userdb: main took SQLite schema v30 for the profile PIN revision (#2020). The login-wide sharing migration moves to v31, so a store already at main's v30 still runs it. - internal/catalog, internal/sections: main's fail-closed library scope (#1953, #2005, #2006) and this branch fixed the same empty-scope bug. The executor and section fetcher keep main's AccessFilter.LibraryScope; library collections keep this branch's ResolveLibraryCollectionMembership, which already returns nothing when the saved libraries miss the collection's own. main's scope test now exercises that resolver. narrowLibraryScope no longer needs the helper main removed. - internal/policy: main's hidden-library output (#2058) and this branch's ContentAccessOnly input both declared `hidden`; the input side is renamed. - Home sections (#2043): the admin per-profile card keeps main's row list but saves with this branch's override builder and a baseline, so like Settings > Home Screen it stores only what changed and untouched rows keep following the server. main's duplicate lib/sectionOverrides.ts is dropped; EditableSectionRows stays for that card and labels rows with rowKindLabel. Settings > Home Screen keeps this branch's page. - apiv2: keep both sides' services and fixtures; the admin profile section settings fixture gains default_title. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
* feat: show a combined Cast & Crew row with sharper headshots Movie and series detail pages now show one "Cast & Crew" row instead of a Cast carousel plus a separate Crew list. The director (or series creator) comes first, then up to three writers, then the top 12 billed cast, each group split by a thin divider with a small vertical label. Every card is the same size, and a writer-director only appears once. Season and episode pages are unchanged. Person photos requested without an explicit image size now ask plugins for the large variant instead of featured. The TMDB plugin maps featured to w185, which is soft on a cast card on a high-density screen; large maps to h632. Stored keys are still presigned untouched, and explicit image_size requests keep their existing mapping. * fix(catalog): return the collection title when its library scope is empty main doesn't compile at ca4f71b: #1953 added a two-value return to loadCollectionSource after #1984 gave the function a third result, the collection title. Return the title with no items, the same as the other paths in the function, so the Go jobs can build. This is the one-line fix main needs. It isn't part of the Cast & Crew change and can be dropped once main has its own fix. * feat(web): lead a series' Cast & Crew row with its Creator credits Prefer Creator credits for the series lead slot and fall back to Director credits when a series has none, so the row picks up creators once the server stores them (#2018) without changing series that only have directors. * perf(web): build the Cast & Crew groups once per render The movie and series pages called buildCrewGroups twice per render, once for the visibility check and once for the row, and the second call's new array made CastCarousel rebuild its sections every render. Memoise the groups on the item's crew and reuse them for both. * fix(web): caption series directors as directors and keep uncapped writers When a series has no Creator credits its Director credits fill the lead slot, but they were still captioned "Creator". Take the caption from the credits used. The writer group also skipped every lead credit, so a third director who also wrote showed nowhere; it now skips only the lead cards the row shows. * fix(web): show every series creator in the Cast & Crew row A series with three or more creators lost the third one to the two-card lead cap that is meant for directors. Creator credits now all get a card, still once per person, while a movie's directors and a series' fallback directors stay capped at two. The writer de-duplication follows the lead cards actually shown, so a creator who also wrote is never repeated.
Problem
Related issue: N/A
Validation tasks: none
A profile or account restricted to some libraries can read every other library by asking for it.
GET /api/v2/catalog?library_id=<library it can't access>returns that library's titles with full metadata and an exact total./api/v1/catalogdoes the same. A library ID that doesn't exist returns the whole catalog. This was reproduced with an account whose policy allows one library and with a profile that has library restrictions enabled. Rating and advisory limits still applied; only library access was bypassed. Search, facets, library sections and Jellyfin-compat browsing were not affected.The catalog query now matches nothing when the requested libraries and the viewer's allowed libraries have nothing in common.
Approach
buildPreviewPagePlanintersected the requested libraries with the allowed ones. When the intersection was empty, it built no library predicate, and its only fail-closed check looked at the allowed list instead of the intersection. One helper now computes the effective scope and reports when a scope was requested or imposed but nothing is left; the plan then adds1 = 0. Page and count queries share the plan, so totals are covered. The episode-catalog fast path and the search sort expression use the same helper. Allowed-library and disabled-library predicates are otherwise unchanged. The helper reuseseffectiveCatalogLibraryIDs, which the browse and search paths already use, so one implementation holds the rule.The same gap existed one layer up. A smart library collection whose saved
library_idsdon't overlap the collection's own libraries wrote the empty intersection back as "no library scope", so it widened to every library the viewer can see.scopeLibraryCollectionDefinitionreplacesintersectCatalogDefinitionLibrariesand reports the empty overlap, and the offset, base-item and cursor paths now return an empty result for it. That case never went past the viewer's allowlist; it returned the wrong collection contents. The legacy collection handler and Jellyfin compat already returned empty.Validation
library_id, on v2 and v1, and still get their own library's 1,000 items. An unrestricted profile still sees the requested library.scripts/ci/db-contracts.txtso CI runs it.library_idsname another, through offset paging, cursor paging and the base-item read, for an unrestricted and a restricted viewer. All return nothing; without the fix the unrestricted viewer got both libraries' items. It is also listed inscripts/ci/db-contracts.txt.go test ./internal/catalog/..., the access-related catalog DB tests,gofmt,make lint-changed: pass.make test-gowas not run locally; the full DB-backed catalog package timed out on the heavily loaded test machine.Evidence
Same request both times, sent as the Viewer profile (library access limited to TV and Mixed), asking for the Movies library it cannot open:
GET <server>/api/v2/catalog?library_id=1withX-Profile-Id: <Viewer>Before
{ "total": 10, "total_exact": true, "items": [ "Charade", "Detour", "Harbor Lights", "His Girl Friday", "Maple Street", "Night of the Living Dead", "Open Road", "The Pilot", "The General", "The Pilot Light" ] }After
{ "total": 0, "total_exact": true, "items": [] }library_id=99(no such library) gave the same 10 items before and 0 after.library_id=2(TV, which Viewer can open) returns Harbor Lights and Maple Street on both builds.Smart library collection "Movie Night" in the TV library, whose saved query names only the Movies library, opened by the admin from the TV library's Collections tab:
Before, the collection ignored its saved library and listed the TV library's series. After, it is empty.
Surface and build:
/api/v2/catalogand the web collection page; before 1555e52 (main at this PR's base), after 762b8bd (PR head). Test library with Movies, TV, Mixed and Audiobooks libraries and synthetic files; the Viewer profile has library restrictions on.Risks
library_idsdon't overlap its own libraries now shows as empty instead of listing every library. Collection create and update still don't cross-check the two fields.Checklist
AI Disclosure
Note
Fix catalog queries to fail closed when requested libraries are outside viewer access
effectiveLibraryScopein query_executor.go, which distinguishes an unrestricted scope from an empty effective one, andscopeLibraryCollectionDefinitionin catalog_resolver.go, which intersects saved smart-collection scopes with collection library scopes.Macroscope summarized 762b8bd.