Skip to content

fix(auth): check who may create an API key in the transaction that stores it - #3317

Merged
Quick104 merged 2 commits into
mainfrom
fix/api-key-issuance-promotion-lock
Oct 31, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/api-key-issuance-promotion-lock

Conversation

@Quick104

@Quick104 Quick104 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: changes #1190 C1; changes #1191 C1

An administrator who is not the server Owner can create API keys for ordinary accounts, but not for another administrator. That rule could be bypassed by timing. Key creation checked the target account first and stored the key in a separate statement. If the Owner promoted that account in between, the promotion deleted the account's existing keys, and the new key was stored afterwards and survived. The administrator was left with an unscoped key for a new administrator, which docs/admin-users-api.md says it may not have. Exploiting it needs the Owner to promote the account at the same moment, so it is hard to hit, but an administrator can retry key creation repeatedly while waiting for a promotion.

This change checks authority in the same transaction that stores the key. Deferred rollback has its own five-second timeout, independent of the request context.

Approach

APIKeyRepository.CreateAsActor locks the acting account and the target account with FOR SHARE, in id order (the order ownership transfer and admin session revocation already use), runs the existing CheckOwnerTarget on the locked rows, and inserts the key before committing. Every write to users.role or users.is_owner (admin account edits, provider role sync, ownership transfer, owner recovery) conflicts with that lock. Either the check sees a promotion or transfer that committed first, or a later promotion of the account deletes the new key along with the others, as it already does.

Both admin create routes (POST /api/v1/admin/api-keys and POST /api/v2/admin/api-keys) use it, and so does POST /api/v2/api-keys, where the caller is always the target and the check always passes. POST /api/v1/api-keys only ever creates keys for the caller's own account and is unchanged. The check no longer depends on the handler's Owners field being set. Responses don't change: the key is still shown once, storage is still hashed, scope validation is the same, and a refusal is still 403 owner_protected on v1 and the same problem on v2.

No client change is needed. The Apple and Android apps don't call the key routes. jellycompat has no key creation. The user manual doesn't describe this rule, so it needs no update. docs/admin-users-api.md gains one sentence on the new ordering.

On validation: this deliberately changes the path that serves admin key creation, the create step of #1190 C1 and #1191 C1 (Web admin creates keys through POST /api/v2/admin/api-keys). The published criterion is unchanged: only an admin creates keys, and a non-Owner admin can't create one for another admin or the Owner. Both cases passed on build 807, before the Owner rules existed, so after merge they need re-validation on a build that contains this change. #1190 C3 (secret shown only at creation) uses the same insert code and is covered by the existing database contract. #1190 C2 and #1191 C2 are unaffected.

Validation

  • Rollback fault probe through the real repository and pgx/PostgreSQL: cancel the caller and pause the database as rollback starts. Head 53145fd48 stays blocked until the database resumes; the updated code returns the expected refusal while the database remains paused. pgx can finish discarding the failed connection asynchronously; the pool works after the database resumes. This is a scratch probe, not a deployed-server test. The auth package, promotion-race database contract, changed-line lint and local-path check also pass after the cleanup change.

  • New database contract (listed in scripts/ci/db-contracts.txt) on v1 and v2: the Owner rules for key creation against the real database, and a non-Owner admin creating a key while a real promotion holds the account. On the parent commit it fails on both transports (key created, promoted account keeps it); with this change it passes, also over 10 repeated runs.

  • Existing API key database contracts (one-time secret, listing): pass.

  • go build ./..., gofmt -l ., go vet ./..., make lint-changed, make lint-router-recovery: clean.

  • make test-go (macOS): the touched packages pass. Five untouched packages fail on this machine, and they fail the same way built from the parent commit: internal/metadata/nfo, internal/scanner (case-variant file names on a case-insensitive filesystem), internal/subtitles/subsync (a non-UTF-8 file name), internal/jellycompat (Dolby Vision strip-route tests), internal/playback (real-FFmpeg remux test). The queryattr race step passes.

  • make test-db-pins and make test-db-contracts against a fresh migrated database: the new contract and the existing API key contracts pass. Four listed tests in untouched packages fail on this machine and fail the same way built from the parent commit: TestCollectionCollageReadsKeepActiveVariantsDB (database and host clocks differ by tens of milliseconds), TestScanIndexesFileWithNonUTF8Name, TestNotificationInboxCutoffReplayAndTies, TestImportRunReadsLargeSourcesWithinLimits.

  • Web: pnpm install --frozen-lockfile, lint (0 errors), format:check, build, budget:check pass. make test-web fails 29 tests in 4 files on this machine with localStorage undefined under the local Node; this branch changes no web files.

  • Generated contracts and hygiene: settings bindings, playback fixtures, migration ledger, scenario catalogs, offline routes, v2 OpenAPI, v2 contract, v2 fixtures, TestCommittedArtifactMatchesRouter, local paths, case collisions, actionlint, ShellCheck, size ratchet, bidi, migrations, and the v1 route freeze pass.

  • Not run here: make verify-route-inventory (its loader forces a Linux cgo build, which this macOS host can't type-check) and make verify-prometheus-rules (the image pull failed on DNS). This change adds no routes or rules; CI runs both.

Evidence

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

Surface and build: native API (POST /api/v2/admin/api-keys), servers built from 35135c626 (before) and this branch at 0a072627c, the same code before a rebase onto main (after), local disposable database. Before: a key created while the target's promotion is in progress returns 201, survives the promotion, and passes an admin-only request. After: the same request returns 403 and the promoted account has no keys.

Risks

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
  • Involvement: Fully AI-generated; not yet human verified. T3 Code / Codex (gpt-6.1-sol) addressed the automated rollback-timeout finding and ran the follow-up fault probe and checks.
  • Adversarial review: An independent Claude Opus 5.5 (claude-opus-5-5) review in a separate read-only checkout checked the locking against every role and owner writer, deadlock risk, issuance paths that might bypass the check, preserved behavior, and the tests. It found no blocking issues. As a result the new test now wires the handler as the router does, so it fails on the parent only because of the race; handler unit cases that only exercised a fake were removed; a possible cleanup hang in the test was fixed; and the docs wording and error wrapping were tightened.

🤖 Generated with Claude Code

Note

Fix API key creation to check owner rules in the storage transaction

  • Adds auth.APIKeyRepository.CreateAsActor, which locks the actor and target account rows (share locks, ID order) and runs the Owner-target check in the same transaction that inserts the key in api_key_repository.go
  • Both the v1 admin handler (HandleAdminCreateAPIKey) and the shared v2 path (CreateAdminAPIKey) now create keys through this actor-aware store method via the new createAsActor helper in api_keys.go
  • Key revocation and retiering keep the existing handler-level owner check; only creation moved into the store
  • Adds a database-backed race test that runs key creation while a promotion holds the target account lock, registered in the db-contract list
  • Behavioral Change: handler-level owner checks on creation are removed from owner_test.go; a target account not found during creation now surfaces as the insert error rather than a handler owner-check error

Macroscope summarized cc6698d.

…s the key

An administrator who is not the Owner may create API keys for ordinary
accounts but not for other administrators. The check read the target
account before a separate INSERT, so an Owner promotion that committed
between the two deleted the account's existing keys and left the new key
in place: the administrator kept an unscoped key for a new administrator.

APIKeyRepository.CreateAsActor locks the acting and target accounts with
FOR SHARE in id order, applies CheckOwnerTarget to the locked rows and
inserts the key in the same transaction. The v1 and v2 admin create
routes and v2 personal create use it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/L 200–499 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-31T15:31:03.942479Z 53145fd PR opened
🔒 Security Review ✅ Completed 2026-10-31T15:32:34.960000Z 53145fd 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.

@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
@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: d2f85297-e7f8-4f57-ad06-92bdb8f8e800
Commits

Reviewing files that changed from the base of the PR and between 53145fd and cc6698d.

Files selected for processing: 1
  • internal/auth/api_key_repository.go

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

Walkthrough

Admin API-key creation now checks owner rules for both the actor and target within a database transaction. The handlers use this actor-aware operation, and database-backed tests cover permitted creation, refusals, and a race with account promotion.

Changes: Owner-aware API key creation

Layer / File(s) Summary
Transactional actor-aware creation
internal/api/handlers/api_keys.go, internal/auth/api_key_repository.go, docs/admin-users-api.md
The store adds CreateAsActor. The repository locks actor and target account rows, checks owner rules, and inserts the key in one transaction. The API documentation describes ordering with promotions and ownership transfers.
Admin handler integration
internal/api/handlers/api_keys.go, internal/api/handlers/api_keys_test.go, internal/apiv2/api_key_scopes_test.go, internal/api/handlers/owner_test.go
Admin key-creation handlers delegate to actor-aware creation and handle owner errors. Test stores implement the added method. Existing owner-protection tests continue to cover deletion and tier updates.
Promotion race validation
internal/api/handlers/api_keys_owner_race_db_test.go, internal/api/handlers/api_keys_privacy_test.go, scripts/ci/db-contracts.txt
Database-backed tests exercise key-creation rules through v1 and v2, including creation racing with account promotion. The privacy-test schema adds account role and owner fields, and the database contract records the race scenario.

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

Possibly related PRs

  • Silo-Server/silo-server#2715: Changes API-key storage to verifier hashes and introduces the insertion path that this PR refactors and uses inside the owner-check transaction.
  • Silo-Server/silo-server#2306: Adds audit recording to API-key creation in the transaction; this PR adds another transactional creation path and shares the insertion helper.

Suggested reviewers: rhainland

Merge Risk: Minimal · up to cc669

No current-head defect was established in the actor-aware creation or handler integration, so this change is mergeable.

Security architecture risk: Low · up to cc669

The design strengthens credential issuance by keeping authorization and key storage under the same account locks. No introduced security regression was established. Remaining uncertainty concerns validation of concurrent and failure scenarios beyond the added promotion test.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The relevant exposure is a non-Owner administrator selecting an ordinary target and retaining a bearer that would gain administrator authority after promotion. The change confines issuance and the target-dependent authorization decision to one database transaction, coordinating with existing key revocation.

Security Findings and Attack Paths

  • inferred — The base permits a target check to precede promotion while key insertion follows promotion-side revocation. The head's conflicting account locks prevent that ordering within CreateAsActor. No introduced or worsened privileged-key attack path was established in the inspected flows.

Trust Boundaries and Controls

  • observed — The requester can select the target account but does not supply the acting identity: the helper obtains actorUserID from authenticated context. General caller admission remains a transport responsibility; CreateAsActor enforces the Owner/target relationship rather than independently requiring an administrator role.

Resilience and Maintainability Implications

  • observed — Creation returns errors from locking, scanning, authorization, insertion, and commit, and attempts rollback with a detached five-second cleanup context. Successful key material is returned only after commit. These controls avoid reporting successful issuance when the transaction has already failed.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main change: moving API-key authorization checks into the transaction that stores the key.
Description check Passed The description directly explains the race condition, transaction-based fix, affected API routes, tests, validation results, and risks. It is clearly related to the changeset.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 40.00% which is insufficient. 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 5 functions across 7 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

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

@coderabbitai coderabbitai Bot added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase documentation Improvements or additions to documentation evidence-required Needs before-and-after evidence before the Evidence check passes needs-review Needs maintainer review to resolve uncertain classification, scope, or changed evidence. labels Oct 31, 2026
Comment thread internal/auth/api_key_repository.go Resolved
@macroscopeapp

macroscopeapp Bot commented Oct 31, 2026

Copy link
Copy Markdown

Major validation impact: Server #1190 C1 and Web admin #1191 C1 both exercise API-key creation. #1190's relevant admin-route evidence is build 807 · d4e35ba9 (the build 940 check covers regular-user creation); #1191's Web admin evidence is build 807 · d4e35ba9. The v1 and v2 admin handlers now route creation through CreateAsActor, which locks both accounts and rechecks Owner authority before insertion; the Web admin sends POST /api/v2/admin/api-keys. The PR must explain why this validated behavior changes; its Validation section already describes the promotion race. Both cases need re-validation after merge on a build containing this change.

The current Validation tasks: changes #1190 C1; changes #1191 C1 line matches this impact.

Suggested fix: No diff — re-run both C1 cases after merge on a build containing this change.

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

Posted via Macroscope — v1 validation impact

@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 ❌

@Quick104
Quick104 merged commit 288f582 into main Oct 31, 2026
26 checks passed
@Quick104
Quick104 deleted the fix/api-key-issuance-promotion-lock branch October 31, 2026 17:35
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 evidence-required Needs before-and-after evidence before the Evidence check passes 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 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.

1 participant