Skip to content

fix(audiobooks): enforce download privilege on ABS-compat download routes - #234

Closed
Quick104 wants to merge 2 commits into
mainfrom
fix/issue-141-abs-download-privilege
Closed

Quick104 wants to merge 2 commits into
mainfrom
fix/issue-141-abs-download-privilege

Conversation

@Quick104

@Quick104 Quick104 commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The Audiobookshelf-compat API ignored Silo's per-account download
privilege (users.download_allowed / models.User.DownloadAllowed).
A non-admin user with downloads disabled could still download complete
audiobook files through the compat listener.

Reproduced on origin/main with a unit test driving handleFileStream
for a user whose download privilege is denied: the handler returned
200 and served the audio bytes, because it checked auth + library
access but never consulted DownloadAllowed. The native download
path enforces this correctly (internal/download/service.go →
ErrDownloadNotAllowed); the ABS layer simply never wired the check in.
Separately, the ABS login envelope hardcoded "download": true, so
clients rendered the offline-save UI unconditionally.

Approach

Add a narrow abs.DownloadPolicy dependency and enforce it on every ABS
surface that serves raw audiobook bytes for offline save — keeping the
privilege decision out of the catalog access filter (which governs
visibility, not download authorization) and instead mirroring the
native download service, which loads the user and checks
DownloadAllowed. The production resolver (ABSDownloadPolicy) reuses
the same user repository already wired for the ABS access resolver,
so no new plumbing is introduced and the user lookup lives in one place.

Surfaces gated:

  • handleFileStream (/items/{id}/file/{ino} and the /download
    variant): 403 when the account may not download. Both variants are
    hard-gated; the gate runs before ino resolution, so the raw-index
    fallback is covered too.
  • Login envelope: advertises the real download permission so
    compliant clients hide the offline-save UI for restricted users.
  • RSS feed download surface (found by the adversarial review — see
    below): feed creation (handleOpenItemFeed) is denied with 403,
    and the public handlePublicFeed / handlePublicFeedFile routes
    re-check the feed owner's current privilege and fail closed
    (404, hiding the feed) so existing feeds stop serving once a user's
    permission is revoked.

All checks fail closed: a resolver error denies rather than serving.
The DownloadPolicy is nil only in non-production wiring (tests), where
the handler preserves its prior allow-everything behavior; main.go
always wires a real resolver.

Playback is intentionally unaffected. ABS streaming uses
session-scoped public-track URLs (/public/session/{sid}/track/{idx},
see play_response.go), not the /file route, so restricted users can
still stream — only downloads are gated, matching the issue's scope. The
other hardcoded permission flags (update/delete/upload/
accessExplicitContent) are left true with a comment: the compat
layer does not implement those mutations, so deriving them is out of
scope for this single-concern PR.

Verification

Commands run from the worktree with GOWORK=off and a stubbed
web/dist (worktree build quirks):

  • go build ./internal/... ./cmd/... — clean.
  • go test ./internal/audiobooks/... ./internal/access/... — all pass,
    including new tests:
    • file route returns 403 when download disabled (bare + /download),
      200 when enabled, fails closed on resolver error, allows with nil
      policy;
    • login envelope download reflects the resolver (allowed/denied);
    • ABSDownloadPolicy reports the user's privilege and errors on a bad
      id / load failure;
    • RSS feed creation denied (403) when download disabled; public feed
      XML + enclosure fail closed (404) after owner revocation / on
      resolver error.
  • golangci-lint v2 run --new-from-rev=origin/main — no findings
    introduced by this diff (the repo's pre-existing goconst/misspell/
    unused noise is unrelated and excluded by CI).
  • make verify-local-paths — clean.

Adversarial review

Codex adversarial-review --base main, two iterations:

  1. needs-attention [high]: the /file gate was bypassable via the
    ABS RSS feed routes — a restricted user could mint a public feed and
    download bytes through the unauthenticated /feed/{slug}/file/{ino}
    enclosure. Fixed by gating feed creation and failing the public
    feed routes closed on the owner's privilege (with regression tests).
  2. approve — no material findings. Confirmed the RSS bypass is
    closed, the ABS ebook file route is still a 404 stub, and native
    ebook read + public-track streaming are correctly outside the scoped
    download surface.

Risks & follow-up

  • Low risk: additive dependency + early-return guards; streaming and all
    non-download ABS flows are untouched.
  • silo-android / silo-apple: no API contract change — download
    under the login permissions block already existed and merely reports
    its real value now. Compliant ABS clients will hide the offline-save UI
    for restricted users; clients that ignore the flag are still hard-gated
    server-side (403). No client change is required, but client teams may
    wish to confirm their UI honors permissions.download.
  • No UI changes in this repo (admin web UI untouched), so no screenshots.

Closes #141

AI-use disclosure

Implemented by Claude Code (issue-to-pr skill) with human oversight.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added download-access checks for ABS content, including file streaming, public feeds, and enclosure links.
    • Download permission is now reflected in the login response for compatible clients.
  • Bug Fixes

    • Restricted downloads now fail closed, returning 403 Forbidden or 404 Not Found as appropriate.
    • Users with revoked download access can no longer mint or use public feed links for protected content.
  • Tests

    • Added coverage for allowed, denied, and error cases across download and feed access flows.

Quick104 and others added 2 commits June 26, 2026 18:35
The Audiobookshelf-compat layer ignored the per-account download
privilege (models.User.DownloadAllowed). Restricted users could both see
the offline-save UI in ABS clients and successfully download audiobook
files via GET /api/items/{id}/file/{ino}[/download].

Two independent gaps are closed:

1. handleFileStream now consults a new abs.DownloadPolicy dependency and
   returns 403 when the account may not download. Both /file/{ino} and
   the /download variant are gated; the check fails closed on a resolver
   error. Streaming is unaffected — ABS playback uses session-scoped
   public-track URLs, not the file route.

2. The login envelope advertises the real "download" permission instead
   of a hardcoded true, so compliant clients hide the offline-save UI for
   restricted users. The other hardcoded flags (update/delete/upload/
   accessExplicitContent) are left as-is with a comment: the compat layer
   does not implement those mutations, so deriving them is out of scope.

ABSDownloadPolicy mirrors the native download service
(internal/download/service.go): it loads the user by ID and reports
DownloadAllowed, keeping the privilege decision in one place rather than
re-deriving it from the access filter. It reuses the same user repository
already wired for the ABS access resolver, so no new plumbing is added.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…lege

Adversarial review found that the /file/{ino} download gate was
bypassable through the ABS RSS feed routes: any authenticated user with
item access could POST /api/feeds/item/{itemId}/open to mint a public
feed, then GET the unauthenticated /feed/{slug}/file/{ino} enclosure to
download the audiobook bytes — defeating the new handleFileStream gate.

Close it with two defense layers, both reusing the DownloadPolicy:

- handleOpenItemFeed now returns 403 when the account may not download,
  so a restricted user cannot create a public-download feed in the first
  place (the gate point the issue called out).
- handlePublicFeed and handlePublicFeedFile re-check the feed OWNER's
  current download privilege and fail closed (404, hiding the feed) when
  it is revoked or the resolver errors — so feeds created while permitted
  stop serving once permission is withdrawn, mirroring the native
  download service's re-check-on-serve behavior.

Adds regression tests covering feed creation denial, the happy path, and
fail-closed XML + enclosure serving after revocation / on resolver error.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The ABS compat layer now threads a download policy through construction and uses it to gate file, login, and RSS feed routes. The login payload reflects the computed permission, and tests cover allowed, denied, nil-policy, and error cases.

Changes

ABS download privilege enforcement

Layer / File(s) Summary
Policy adapter
internal/audiobooks/access_resolver.go, internal/audiobooks/access_resolver_test.go
ABSDownloadPolicy resolves user.DownloadAllowed through access.UserRepository, and tests cover privilege, invalid IDs, repository errors, and nil-repo behavior.
Policy wiring
internal/audiobooks/abs/handler.go, internal/audiobooks/service.go, cmd/silo/main.go
DownloadPolicy is added to ABS dependencies, passed through handler construction, and set in the silo ABS handler wiring.
File and login checks
internal/audiobooks/abs/file_handler.go, internal/audiobooks/abs/login.go, internal/audiobooks/abs/file_handler_download_test.go
handleFileStream now rejects disallowed downloads, loginEnvelope returns the computed download flag, and tests cover the file-stream and login behaviors.
RSS feed checks
internal/audiobooks/abs/rss_feeds_handler.go, internal/audiobooks/abs/rss_feeds_download_test.go
Feed creation and public feed/file serving now check download permission, and tests cover allowed, denied, revoked, and error cases.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant handleFileStream
  participant ABSDownloadPolicy
  participant access.UserRepository

  Client->>handleFileStream: request file or /download route
  handleFileStream->>ABSDownloadPolicy: DownloadAllowed(ctx, userID)
  ABSDownloadPolicy->>access.UserRepository: GetByID(userID)
  access.UserRepository-->>ABSDownloadPolicy: user or error
  ABSDownloadPolicy-->>handleFileStream: allowed / denied / error
  handleFileStream-->>Client: 403 or file bytes
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: enforcing ABS download privilege on compat download routes.
Linked Issues check ✅ Passed The PR blocks restricted file downloads, updates login permissions, preserves playback, and adds RSS feed safeguards as required by #141.
Out of Scope Changes check ✅ Passed The changes stay focused on ABS download enforcement and related tests/wiring; no unrelated code paths stand out.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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 fix/issue-141-abs-download-privilege

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

@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

🤖 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/audiobooks/access_resolver.go`:
- Around line 62-78: The nil-handling in NewABSDownloadPolicy and
DownloadAllowed is inconsistent with the handler’s expectations: a typed-nil
*ABSDownloadPolicy still bypasses the abs.Handler DownloadPolicy == nil check,
so the allow-by-nil behavior currently depends on the p == nil guard inside
DownloadAllowed. Update the implementation so the nil path is authoritative and
explicit—either return the policy as the interface type that abs.Handler checks,
or adjust NewABSDownloadPolicy/DownloadAllowed and its comment to reflect that a
nil receiver is handled inside DownloadAllowed.
🪄 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: bbe25ed4-942a-4d87-8db6-675828e8de6e

📥 Commits

Reviewing files that changed from the base of the PR and between 41a1fc8 and 0ca6067.

📒 Files selected for processing (10)
  • cmd/silo/main.go
  • internal/audiobooks/abs/file_handler.go
  • internal/audiobooks/abs/file_handler_download_test.go
  • internal/audiobooks/abs/handler.go
  • internal/audiobooks/abs/login.go
  • internal/audiobooks/abs/rss_feeds_download_test.go
  • internal/audiobooks/abs/rss_feeds_handler.go
  • internal/audiobooks/access_resolver.go
  • internal/audiobooks/access_resolver_test.go
  • internal/audiobooks/service.go

Comment on lines +62 to +78
// NewABSDownloadPolicy constructs the download-privilege resolver. Returns nil
// when no user repository is available; abs.Handler treats a nil policy as
// "allow", so callers must wire a real repository to enforce the gate.
func NewABSDownloadPolicy(users access.UserRepository) *ABSDownloadPolicy {
if users == nil {
return nil
}
return &ABSDownloadPolicy{users: users}
}

// DownloadAllowed loads the account by its numeric ABS user ID and reports its
// download privilege. A malformed ID or a load failure returns an error, which
// the caller fails closed on (denying the download).
func (p *ABSDownloadPolicy) DownloadAllowed(ctx context.Context, userID string) (bool, error) {
if p == nil || p.users == nil {
return true, nil
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect how NewABSDownloadPolicy result is assigned and how downloadAllowed checks nil.
rg -nP -C3 'NewABSDownloadPolicy' 
rg -nP -C3 'DownloadPolicy\s*==\s*nil' internal/audiobooks/abs/
ast-grep run --pattern 'DownloadPolicy: $_' --lang go cmd/silo/main.go

Repository: Silo-Server/silo-server

Length of output: 161


Clarify the nil handling here

NewABSDownloadPolicy(nil) returns a typed-nil *ABSDownloadPolicy, so storing it in abs.DownloadPolicy won’t trip the handler’s DownloadPolicy == nil check. The allow-by-nil behavior still comes from DownloadAllowed’s p == nil guard, so either update the comment to match that or return the interface type if you want the handler-level nil check to be authoritative.

🤖 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/audiobooks/access_resolver.go` around lines 62 - 78, The
nil-handling in NewABSDownloadPolicy and DownloadAllowed is inconsistent with
the handler’s expectations: a typed-nil *ABSDownloadPolicy still bypasses the
abs.Handler DownloadPolicy == nil check, so the allow-by-nil behavior currently
depends on the p == nil guard inside DownloadAllowed. Update the implementation
so the nil path is authoritative and explicit—either return the policy as the
interface type that abs.Handler checks, or adjust
NewABSDownloadPolicy/DownloadAllowed and its comment to reflect that a nil
receiver is handled inside DownloadAllowed.

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.

ABS compat: download privilege (download_allowed) not enforced — restricted users can download audiobooks

1 participant