Skip to content

fix(auth): check scoped API keys against the path the router serves - #3307

Merged
Quick104 merged 1 commit into
mainfrom
fix/api-key-scope-encoded-paths
Oct 31, 2026
Merged

Quick104 merged 1 commit into
mainfrom
fix/api-key-scope-encoded-paths

Conversation

@Quick104

@Quick104 Quick104 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #1190 C2

A scoped API key could reach routes outside its scopes by spelling the path in a way the scope check and the router read differently. The scope check decoded and cleaned the path, but chi routes on the escaped path when there is one and never cleans it. For example, an admin:users key sending PUT /api/v1/admin/settings/..%2Fusers%2F1 passed the check as /api/v1/admin/users/1, and chi then ran the admin settings handler, which saved a setting named ..%2Fusers%2F1. The same trick works on /api/v2, and with literal .. segments when a request reaches the API router directly. It affects servers where an administrator has issued scoped keys to integrations: admin-only routes still required the owner to be an administrator, but the key was not held to the routes its scopes list.

This change checks scoped keys against the path chi routes, and refuses with 403 any path where the two could differ.

Approach

apiKeyScopesAllow now matches the allowlist against r.URL.Path only when r.URL.RawPath is empty and the path is already clean (no . or .. segments, doubled slashes or trailing slash). In that case the string the allowlist reads is the string chi routes on. Any other spelling is refused, not normalized. Remote-playback sessions already followed this rule, so the check is now one helper used by both. Remote-playback behavior is unchanged.

Unscoped keys and login sessions are unchanged. Legitimate scoped-key paths don't need escaping: the allowlisted routes take numeric user and access-group IDs and UUID playback session IDs, and query strings (such as ?identity= with an encoded @) don't affect the check. docs/api-keys-api.md now states the rule. jellycompat, plugin routes and media grants already refuse scoped keys outright, so they need no change. The Apple and Android apps don't use API keys, so neither app needs a follow-up. The user manual leaves scope details to docs/api-keys-api.md and already lists a key's scopes as a reason for 403, so it needs no issue.

The settings handlers still accept unknown setting keys. That is separate defense in depth and is not part of this change.

Validation

  • Middleware tests: new table rows for encoded and unclean spellings, and a test that sends requests through http.ServeMux, a chi router and RequireAuth and checks which handler ran. Both fail on the parent commit (the settings handler is reached with 200) and pass with the change.
  • Full API router against a disposable, migrated PostgreSQL database with real scoped keys (not committed): before the change, PUT /api/v1/admin/settings/..%2Fusers%2F1 returned 200 and wrote the row. After the change it returns 403, as do the v2 and .. variants. In-scope v1 and v2 user reads, the encoded identity query and a UUID session terminate behave the same before and after.
  • go build ./..., gofmt -l ., go vet ./..., make lint-changed, make lint-router-recovery: pass
  • make test-go: failures in internal/httpstream, internal/jellycompat, internal/metadata/nfo, internal/playback, internal/scanner and internal/subtitles/subsync on the macOS machine used (case-insensitive filesystem, timing, real FFmpeg and media-tool cases). Only jellycompat depends on the changed package, and its two failures also fail with the base middleware. All other packages pass.
  • Web gate (pnpm install --frozen-lockfile, lint, format:check, build, budget:check, make test-web): install, lint, build and budget pass. format:check failed on src/pages/ItemDetail/detailLayout.css, which fix(web): format detailLayout.css so the Prettier check passes #3306 has since fixed on main, and four make test-web files fail. This change touches no web files, so both come from the base.
  • Generated contracts and hygiene targets from CONTRIBUTING: pass, except make verify-route-inventory, which could not type-check cgo files in internal/imageutil and internal/netadmin on this machine, and make verify-prometheus-rules, which did not run because the image pull failed on DNS.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3307/

API response excerpts for the same requests on the full router, with an admin:users key:

Request Before After
PUT /api/v1/admin/settings/..%2Fusers%2F1 200 {"key":"..%2Fusers%2F1","value":"probe"} 403 API key scopes do not permit this route
GET /api/v2/settings/values/..%2F..%2Fadmin%2Fusers%2F1 422 (passed auth) 403 permission_denied
GET /api/v1/admin/settings/../users/1 404 (passed auth) 403
GET /api/v2/admin/users/1 200 200

Surface and build: native API (/api/v1 and /api/v2) on the full API router built locally. Before: 271a4c87d, whose auth middleware and v2 gates are identical to this PR's base 5a205566a. After: 783036af8, this PR's head.

Risks

A scoped-key integration that sends a trailing slash, a doubled slash or an unnecessary percent-escape on an allowlisted route now gets 403 where the scope check used to pass. chi wouldn't have served the trailing- or doubled-slash forms as the allowlisted route anyway. No first-party client uses scoped keys. Validation task #1190 C2 passed on build 807 · d4e35ba9. This is a major change to its authorization path: encoded or unclean spellings that could bypass scopes now return 403. The change preserves C2's requirement that forbidden operations are denied, but the earlier pass does not cover this path. After merge and publication in a build, C2 needs re-validation of plain allowed and forbidden routes, an ambiguous path, and rotated/revoked credentials. If the task is Done, it should return to Ready with the validation hand-off.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: T3 Code, Claude Agent and Codex harnesses
  • Tool(s): Claude Code, GitHub CLI
  • Model(s): claude-opus-5-5; gpt-6.1-sol (validation impact text only)
  • Involvement: Fully AI-generated; not yet human verified (awaiting maintainer review)
  • Adversarial review: A separate claude-opus-5-5 agent (T3 Code, Claude Agent harness, high effort) reviewed the commit read-only in its own checkout. It checked whether the scope check and chi could still disagree on any path spelling, whether legitimate scoped-key requests are refused, the remote-playback refactor, and the tests. It found no blocking issue. Its findings, all fixed: the docs overstated which escapes are refused, a code comment was stale, and one test row passed without the fix and two overlapped the router test.

🤖 Generated with Claude Code

A scoped API key was checked against the decoded, cleaned request path,
while chi routes on the escaped path when one is set and never cleans it.
An encoded-slash or dot-segment spelling could therefore pass the scope
check as an allowlisted route and reach a different handler. Scoped keys
are now refused any path that is escaped or not already clean, the same
rule remote-playback sessions already follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 31, 2026
@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 ❌

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-31T14:25:40.339485Z 783036a PR opened
🔒 Security Review ✅ Completed 2026-10-31T14:26:59.903418Z 783036a PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@macroscopeapp

macroscopeapp Bot commented Oct 31, 2026

Copy link
Copy Markdown

The scoped-key API behavior is visible: ambiguous or encoded paths now return 403 instead of reaching an API route. The response table covers this behavior, but does not identify the build or commits used for the before and after responses; please name the API surface and the before/after commit or build. Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@coderabbitai

coderabbitai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 724155c9-c307-436e-aed1-9dc82298a61e
Commits

Reviewing files that changed from the base of the PR and between 35135c6 and 783036a.

Files selected for processing: 4
  • docs/api-keys-api.md
  • internal/api/middleware/api_key_scopes.go
  • internal/api/middleware/api_key_scopes_test.go
  • internal/api/middleware/remote_playback.go

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

Walkthrough

Scoped API-key requests now require a nonempty, clean URL path with no RawPath before scope-route matching. Remote playback applies the same path check before allowlist matching. Tests cover ambiguous path forms, chi routing, and unscoped-key access. The API-key documentation describes the resulting 403 responses.

Changes: Scoped and remote-playback path admission

Layer / File(s) Summary
Validate paths before allowlist matching
internal/api/middleware/api_key_scopes.go, internal/api/middleware/remote_playback.go, internal/api/middleware/api_key_scopes_test.go, docs/api-keys-api.md
Scoped-key requests require an unambiguous path before scope-route matching; unscoped keys remain allowed. Remote playback applies the same path check before allowlist matching. Tests cover ambiguous paths and chi routing. The documentation lists path forms that receive 403 responses.

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Bug fix

Possibly related PRs

Suggested labels: bug, documentation, go, api-v2, impact: security, priority: P1, size/M, needs-review

Suggested reviewers: rhainland

Merge Risk: Minimal · up to 78303

No actionable merge-blocking issue was established. Scoped keys and remote-playback sessions reject ambiguous paths while the intended unscoped-key behavior remains unchanged.

Security architecture risk: Low · up to 78303

The change restricts ambiguous requests rather than granting additional access. No introduced security defect was identified. Remaining uncertainty concerns production request transformations and compatibility with clients that send noncanonical paths.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The relevant attacker holds a scoped API key and controls the request method and path. For an administrator-owned key, interpretation disagreement could cross from permitted account-management routes into administrative settings on the same server. Owner-role enforcement remains a separate limiting boundary; this PR narrows that exposure rather than adding authority.

Security Findings and Attack Paths

  • inferred — The reported attack uses encoded separators or dot segments so authorization judges a normalized users route while dispatch selects a settings route. The head rejects those spellings before allowlist matching. Regression source asserts 403 and no handler reachability through a root mux and through direct chi dispatch; these assertions were inspected, not executed. No introduced or worsened attack path was established.

Trust Boundaries and Controls

  • observed — Current-authority revalidation continues to check captured credential identity, current key scopes, live session authority, bound profile, and enabled owner state. Its production progress callers construct operation paths. The new helper does not introduce a new credential source or replace captured identity.

Resilience and Maintainability Implications

  • inferred — The changed admission step adds no persistent reservation or multi-step state transition. Rejected paths terminate before narrowing mutations, and successful authentication uses request-local claims. Existing revocation and expiry checks remain unchanged. No new partial-failure or retry path that widens authority was identified; concurrent execution was not experimentally validated.
Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title names the main change: scoped API key checks now use the path chi routes on, so escaped or unclean paths are refused. It matches the changeset in the middleware and its tests, and the fix(au…
Docstring Coverage Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
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.
Description check Passed The description directly explains the scoped API-key path authorization issue, the implementation, affected behavior, tests, validation results, and risks. It is clearly related to the changeset.
Full details: Title check

Explanation

The title names the main change: scoped API key checks now use the path chi routes on, so escaped or unclean paths are refused. It matches the changeset in the middleware and its tests, and the fix(auth) prefix follows the usual convention. The title is 67 characters, which is acceptable.

Full details: Docstring Coverage

Explanation

Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 3 files. (1 skipped: 1 unsupported.)

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

@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 31, 2026
@Quick104

Copy link
Copy Markdown
Contributor Author

Added a "Surface and build" line under Evidence: the native API (/api/v1 and /api/v2) on the full API router, before at 271a4c87d (same auth middleware and v2 gates as the base 5a205566a) and after at 783036af8, this PR's head.

🤖 T3 Code / Claude Agent (claude-opus-5-5)

@coderabbitai coderabbitai Bot added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase documentation Improvements or additions to documentation needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. priority: P1 Core-path bug; painful workaround — next after P0 labels Oct 31, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 31, 2026

Copy link
Copy Markdown

Major change — #1190 C2 (Server; build 807 · d4e35ba9): This changes scoped-key authorization outcomes for encoded or unclean request paths: the middleware now rejects them before routing. The PR must explain why this previously validated behavior changes; its Problem/Approach gives the path-confusion rationale. C2 needs re-validation after merge, including plain allowed/forbidden routes and an ambiguous path. Validation tasks: changes #1190 C2 is accurate.

Suggested fix: No code diff; record the post-merge C2 re-validation.

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

Posted via Macroscope — v1 validation impact

@Quick104

Copy link
Copy Markdown
Contributor Author

Recorded #1190 C2 as a major authorization change in the PR's Risks. The new 403 closes the scope bypass and preserves C2's allowed/forbidden-operation criterion; its earlier pass on build 807 does not cover this path.

After merge and a published build, C2 needs re-validation of plain allowed and forbidden routes, an ambiguous path, and rotation/revocation. A Done task should return to Ready with that hand-off.

🤖 T3 Code / Codex (gpt-6.1-sol)

@Quick104
Quick104 merged commit 98c6aaa into main Oct 31, 2026
22 checks passed
@Quick104
Quick104 deleted the fix/api-key-scope-encoded-paths branch October 31, 2026 15:25
@Quick104 Quick104 mentioned this pull request Oct 31, 2026
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase bug Something isn't working documentation Improvements or additions to documentation go Pull requests that update go code impact: security Auth, privacy, or permission boundary needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. priority: P0 Fix/merge first: data-loss, security, or widespread breakage priority: P1 Core-path bug; painful workaround — next after P0 size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant