Repository navigation
fix(auth): check who may create an API key in the transaction that stores it - #3317
Conversation
…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 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:
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
No actionable comments were generated in the recent review.
|
| 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: 
4 · 
1
-
Failed checks: 1 warning Passed checks: 4 passedFull 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
|
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 · The current 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 |
Co-authored-by: GPT-6.1 Sol <[email protected]>
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:
|
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.mdsays 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.CreateAsActorlocks the acting account and the target account withFOR SHARE, in id order (the order ownership transfer and admin session revocation already use), runs the existingCheckOwnerTargeton the locked rows, and inserts the key before committing. Every write tousers.roleorusers.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-keysandPOST /api/v2/admin/api-keys) use it, and so doesPOST /api/v2/api-keys, where the caller is always the target and the check always passes.POST /api/v1/api-keysonly ever creates keys for the caller's own account and is unchanged. The check no longer depends on the handler'sOwnersfield 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 still403 owner_protectedon 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.mdgains 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
53145fd48stays 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). Thequeryattrrace step passes.make test-db-pinsandmake test-db-contractsagainst 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:checkpass.make test-webfails 29 tests in 4 files on this machine withlocalStorageundefined 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) andmake 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 from35135c626(before) and this branch at0a072627c, the same code before a rebase onto main (after), local disposable database. Before: a key created while the target's promotion is in progress returns201, survives the promotion, and passes an admin-only request. After: the same request returns403and the promoted account has no keys.Risks
APIKeyRepository.Createand takes account locks for audit rows. Whichever merges second needs to keep both behaviors and check lock order.Checklist
AI Disclosure
🤖 Generated with Claude Code
Note
Fix API key creation to check owner rules in the storage transaction
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.goHandleAdminCreateAPIKey) and the shared v2 path (CreateAdminAPIKey) now create keys through this actor-aware store method via the newcreateAsActorhelper in api_keys.goMacroscope summarized cc6698d.