Skip to content

fix(audiobooks): scope login envelope libraries to the authenticated profile - #2793

Merged
Quick104 merged 2 commits into
mainfrom
fix/abs-login-envelope-library-scope
Oct 31, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/abs-login-envelope-library-scope

Conversation

@Quick104

@Quick104 Quick104 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Audiobookshelf login and refresh envelopes could list library IDs, names and default-library metadata outside the authenticated profile's resolved scope. The shared builder also discarded access-resolution errors. This change resolves metadata scope from the explicit authenticated account and profile.

Closes #2792
Related issue: N/A
Validation tasks: none of the passed cases are affected; partly unblocks #1247 C2 (not run yet; #2795 covers the remaining ABS scope gaps).

Approach

Reuse the existing access resolver and library predicates for login, refresh and authorize. A resolution error skips the library lookup; a listing error discards partial results. Both retain the existing empty-list/virtual-default response.

Nil and empty allowlists, disabled libraries and source-authorized scope keep their meanings. Response status, cookies and token issuance, persistence and refresh ordering are unchanged. The repair concerns library metadata; no item or media-access impact was established. Inspected native Apple, Android, web and Jellyfin source needs no change, and the manual already describes the intended behavior.

Validation

  • go test ./internal/audiobooks/... passes against a migrated test database, except TestRecordOutcomeClearsTheParkedRetry, which also fails on a fresh database on main. make lint-changed and go vet are clean.
  • Builder tests cover unrestricted, empty, subset, disabled-library and account scope, resolver and listing errors, and the legacy fallback. TestTokenHandlers_ScopeLibrariesToAuthenticatedProfile drives /login, /auth/refresh and /authorize for a profile allowed one of two libraries; with the profile ID dropped from the login and refresh calls, those subtests fail.
  • DB-backed check through the mounted ABS router, with the production credential validator, token store, library query and access adapter on a throwaway database: before the change, a Kid profile restricted to "Kids Books" got both libraries and "Adult Books" as its default on login and refresh; after, it gets only "Kids Books". No ABS client app was run.

Evidence

Before-and-after /login and /auth/refresh responses from the DB-backed check, with the setup and test results.

Evidence: https://evidence.siloserver.org/r/silo-server/issue-2792/

Risks

ABS clients get an empty library list, with the virtual default library, when scope resolution or the library query fails; that response shape already existed for an empty listing, and the failure is now logged at Warn. The live check used the legacy scope resolver rather than the policy-system resolver integrated mode uses; this PR changes neither. No ABS client app was run.

Follow-ups

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: T3 Code, Codex harness and Claude Code.
  • Tool(s): Codex implementation; T3 delegate_task for isolated Claude reviews; Modern Go Guidelines CLI.
  • Model(s): gpt-6.1-sol; claude-opus-5-5.
  • Involvement: AI-assisted; implementation and review performed by the listed agents, human verification pending.
  • Adversarial review: claude-opus-5-5 reviewed the approach, three groups of code-review angles and an independent sweep at 5b2b6dcc1. The approach review required explicit identity/context, compile adaptations and auth-fixture exclusions; all were adopted. The code rounds reported no actionable findings within their source and saved-evidence coverage. No reviewer subdelegation was used; effective backend effort was unverified. The isolated background PR review at the same head also reported no actionable findings and posted nothing. A later /silo review (Claude Code, claude-opus-5-5, with gpt-6.1-sol through the Codex CLI) found two low-severity issues, both fixed in 8c0d24320 (Warn-level failure logging, handler-level tests), and filed the pre-existing gaps as [bug] Audiobookshelf collections, playlists and session detail ignore the profile's library scope #2795.

Note

Fix abs.Handler.loginEnvelope to scope libraries to the authenticated profile

  • The login envelope now receives an explicit ctxAuth principal from all three callers: completeLogin, handleABSAuthorize, and handleRefresh (which builds it from validated refresh token claims).
  • Library list and default library ID come from the resolved access scope of that principal, ignoring conflicting principal data in ambient context. Without an AccessResolver, a legacy filter with the parsed user and profile IDs is used.
  • Behavioral Change: if scope resolution or library listing fails, the envelope returns an empty library list with the virtual library as default, and logs a warning with user, profile, and error — previously partial listings could be returned. See login.go and tests in login_scope_test.go.

Macroscope summarized 177370e.

@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 20, 2026
@silo-kody

silo-kody Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9bcc08c4-c18b-4e12-9221-5a797bc53cb3
📥 Commits

Reviewing files that changed from the base of the PR and between 5b2b6dc and 8c0d243.

📒 Files selected for processing: 2
  • internal/audiobooks/abs/login.go
  • internal/audiobooks/abs/login_scope_test.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.

Walkthrough

The shared Audiobookshelf login response builder now receives request context and an authenticated principal. It resolves library access from that principal and omits library metadata when resolution or listing fails. Login, authorize, and refresh use this path. Tests cover scoped, fallback, and error cases.

Changes: Audiobookshelf Login Envelope Scope

Layer / File(s) Summary
Resolve library metadata from the authenticated principal
internal/audiobooks/abs/login.go
The response builder accepts context and a principal, resolves access, and loads library metadata. Login, authorize, and refresh pass the principal to the builder.
Validate scoped metadata and failure behavior
internal/audiobooks/abs/login_envelope_test.go, internal/audiobooks/abs/login_scope_test.go
Tests cover explicit principal propagation, resolved filters, scoped library metadata, resolver fallback, and metadata omission after errors.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: pukabyte, pfuenzle

Merge Risk: Minimal · up to 8c0d2

No actionable library-scope issue remains in the reviewed changes; the PR is mergeable after normal checks.

Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly and concisely states the main change: scoping Audiobookshelf login-envelope libraries to the authenticated profile.
Linked Issues check Passed [#2792] requires library IDs, names, and default-library metadata to use the authenticated account and profile scope. loginEnvelope now receives ctxAuth, calls accessFilterForAuth with the expli…
Out of Scope Changes check Passed The changed production code updates the shared login, refresh, and authorize envelope path and its error handling. The changed tests verify principal forwarding, scope behavior, error behavior, and re…
Description check Passed The pull request description directly explains the Audiobookshelf library-scope changes, affected login, refresh, and authorize flows, error handling, tests, validation, and risks.
Full details: Linked Issues check

Explanation

[#2792] requires library IDs, names, and default-library metadata to use the authenticated account and profile scope. loginEnvelope now receives ctxAuth, calls accessFilterForAuth with the explicit principal, and skips listing when resolution fails. It clears partial results when listing fails. The existing virtual default remains for an empty result. Tests cover unrestricted, empty, restricted, disabled, account, resolver-error, listing-error, and legacy cases. Handler tests cover login, refresh, and authorize profile scoping.

Full details: Out of Scope Changes check

Explanation

The changed production code updates the shared login, refresh, and authorize envelope path and its error handling. The changed tests verify principal forwarding, scope behavior, error behavior, and response metadata. These changes support [#2792]. No item access, media access, token issuance, cookie, persistence, or unrelated feature change is shown in the supplied change summary.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
Fix failing CI checks
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@macroscopeapp

macroscopeapp Bot commented Oct 20, 2026

Copy link
Copy Markdown

The ABS /login, /auth/refresh, and /authorize responses now scope libraries and user.defaultLibraryId to the authenticated profile. The linked evidence is described as source/offline-only and lacks before-and-after API response excerpts for these envelopes; add redacted excerpts showing the changed fields for a profile-scoped principal. Suggested fix: include those excerpts on the evidence page.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: security Auth, privacy, or permission boundary priority: P0 Fix/merge first: data-loss, security, or widespread breakage labels Oct 20, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 20, 2026

Copy link
Copy Markdown

The Validation tasks: entry should name the pending Audiobookshelf compatibility checks. #1247 C1 covers authentication, browsing, and playback; C2 checks profile and library restrictions. The changed login/refresh/authorize envelope affects library metadata in those flows. Both cases are Not run, so there is no earlier recorded result to invalidate or unblock; include this metadata check when they are run.

Suggested line: Validation tasks: changes #1247 C1, C2

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Review of 5b2b6dc. The fix is correct: /login and /auth/refresh run outside bearerAuth, so the old builder found no principal in the request context and listed every enabled audiobook library. Passing the validated principal into loginEnvelope fixes that on all three paths, and the profile is the one the credentials picked (username#profile, or the account's primary when none is named), the same profile the issued token carries.

Two low-severity findings, both on lines this PR adds. I'm fixing both in a commit on this branch, so there's no need to change them yourself.

Other ABS endpoints have similar gaps that predate this PR: collection entries carry the server's first library ID, three helpers ignore a scope-resolution error and fall back to an unrestricted filter, and listening-session detail checks the account but not the profile. They are filed as #2795 and will get their own PR.

AI disclosure: reviewed with Claude Code (claude-opus-5-5), with an independent review by gpt-6.1-sol through the Codex CLI.

Comment thread internal/audiobooks/abs/login.go Resolved
@silo-triage silo-triage Bot added size/L 200–499 added + deleted lines (all files); change volume, not priority. and removed size/M 50–199 added + deleted lines (all files); change volume, not priority. labels Oct 20, 2026
@silo-kody

silo-kody Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104

Quick104 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

/silo review summary

Reviewed head: 8c0d24320 (my review covered 5b2b6dc; 8c0d24320 adds my fixes).

Fit: 9/10 · Readiness: 9/10 — ready (assuming CI is green)

The fix belongs where it is. /login and /auth/refresh run outside the bearer middleware, so the shared envelope builder had no principal and listed every enabled audiobook library. Passing the principal the handler just validated reuses the existing access resolver and library predicate instead of adding a second path. The profile is the one the sign-in selected (username#profile, or the primary profile), and it is the same profile the issued tokens carry. The Audiobookshelf endpoint is a beta surface, and this is a bounded security fix to it.

Addressed findings

Both were low severity, introduced by this PR, and fixed in 8c0d24320:

  • A failed scope lookup was logged only at Debug and without the error, so an empty library list after a database error left no trace at the default log level. It now logs at Warn with the error and the user and profile IDs.
  • The tests called the builder directly. Since the original bug was in the handler wiring, a handler that dropped the profile ID would still have passed. New handler-level tests cover /login, /auth/refresh and /authorize.

Verification

  • A DB-backed check ran through the mounted ABS router with the production credential validator, token store, library query and access adapter, on a throwaway database. On base, a Kid profile limited to "Kids Books" got both libraries, with "Adult Books" as its default, on login and on refresh. On this branch it gets only "Kids Books". The check used the legacy scope resolver rather than the policy-system resolver integrated mode uses; this PR changes neither.
  • go test ./internal/audiobooks/... passes with a test database, except TestRecordOutcomeClearsTheParkedRetry, which fails the same way on main. make lint-changed and go vet are clean.
  • No ABS client app was run.
  • ci / Go test was red on 5b2b6dc only from TestAdminDefaultChangeReachesEveryViewer, which fails on main too ([bug] Administrator default changes no longer reach any events socket #2748).

Remaining issues

None in this PR. The independent review and the altitude pass found older gaps of the same kind in other ABS handlers. Collection entries carry the server's first library ID. Three helpers ignore a scope-resolution error and fall back to an unrestricted filter. Listening-session detail checks the account but not the profile. These predate this PR. They are filed as #2795 and fixed separately in #2799. Whether collections and playlists should hide out-of-scope members entirely is a product question, and #2795 notes it.

Validated features

No passed validation case reaches this code. The Audiobookshelf compatibility task #1247 has not been run yet. Its C2 (restrictions match native enforcement) gets closer to passing with this PR, and #2795 covers the rest. The PR body's Validation tasks: line now says this.

User manual

The manual's Audiobookshelf page doesn't describe which libraries a sign-in lists, and this change makes the endpoint follow the profile restrictions the manual already describes. No docs issue is needed for this PR.

Apple / Android parity

No change is needed. Native Apple, Android and web clients use the v1/v2 API, and jellycompat's sign-in response has no library list.

Review method

Claude Code (claude-opus-5-5) ran three finder passes and a validation-impact pass at medium level. gpt-6.1-sol ran one independent round through the Codex CLI. Every finding was checked against the source.

Quick104 and others added 2 commits October 31, 2026 00:04
Log a failed library-scope lookup in the ABS login envelope at Warn with
the error and principal, so an empty library list after a resolver or
database failure is visible at the default log level.

Add handler-level tests for /login, /auth/refresh and /authorize that
give a restricted profile one of two libraries and check the response
lists only that one. The builder tests alone would still pass if a
handler dropped the profile ID.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Quick104
Quick104 force-pushed the fix/abs-login-envelope-library-scope branch from 8c0d243 to 177370e Compare October 31, 2026 04:06
@silo-kody

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@macroscopeapp

macroscopeapp Bot commented Oct 31, 2026

Copy link
Copy Markdown

The Evidence section describes before-and-after /login and /auth/refresh responses, but not the changed /authorize response. Include a before-and-after /authorize comparison for the same profile, showing libraries, userDefaultLibraryId, and user.defaultLibraryId, on the linked evidence page.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@Quick104
Quick104 merged commit 336bfd0 into main Oct 31, 2026
14 checks passed
@Quick104
Quick104 deleted the fix/abs-login-envelope-library-scope branch October 31, 2026 04:09
Quick104 added a commit that referenced this pull request Oct 31, 2026
…3302)

#2919 made the token store refuse tokens issued with no source credential,
and #2793 added a login test whose principal carries none. Each passed CI
alone; together they fail `go test` on main.

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code impact: security Auth, privacy, or permission boundary priority: P0 Fix/merge first: data-loss, security, or widespread breakage size/L 200–499 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] Audiobookshelf response metadata needs explicit profile library scope

1 participant