Skip to content

fix(passwordreset): recheck admin authority when storing a reset link - #3313

Merged
Quick104 merged 1 commit into
mainfrom
fix/password-reset-locked-authorization
Oct 31, 2026
Merged

Quick104 merged 1 commit into
mainfrom
fix/password-reset-locked-authorization

Conversation

@Quick104

@Quick104 Quick104 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

A non-Owner administrator could end up with a working password reset link for another administrator's account. Only the server Owner may reset another admin's password, and a scoped API key may not reset any admin's. The reset endpoint checked those rules against the account as it was read at the start of the request, then stored the link later in a separate statement. If the Owner promoted the account to admin in between, the promotion deleted the account's reset links first, and the link stored afterwards still worked. Whoever held it could set the new admin's password.

The same gap let a scoped API key get a link for an account promoted mid-request, and let an Owner who handed ownership away mid-request finish issuing a link for another admin.

Approach

Repository.Issue now runs in one transaction. It locks the issuing account and the target account in id order, the order ownership transfers use. It reruns auth.CheckOwnerTarget and the scoped-key rule on the locked rows, then stores the link. If a promotion or ownership move commits first, issuance sees it and refuses. If a promotion commits afterwards, it deletes the new link, as it already did.

  • Lock modes: The target is locked FOR NO KEY UPDATE as before. The issuer is locked FOR KEY SHARE, which waits for ownership moves (they take FOR UPDATE) but not for access-group updates, which lock many accounts in no fixed order. Review reproduced a deadlock with access-group updates when the issuer was locked as strongly as the target.
  • Error shape: The handler keeps its early checks, so the error order and wire shape are unchanged. A refusal found under the lock returns the same 403 as the early check: owner_protected (permission_denied on v2) for the Owner rules, and insufficient_scope for a scoped key.
  • Unchanged: Self-service reset (IssueUnlessRecent), its one-hour TTL, five-minute cooldown, and the protection of admin-issued links are untouched.
  • Docs: docs/architecture/password-resets.md records the invariant.

Surfaces: only POST /api/v2/admin/users/{id}/password-reset changes behavior, and only when an account changes role or ownership during the request. No /api/v1 route issues reset links, and jellycompat has no reset-link surface. The wire shape and error codes do not change, so the web, Apple and Android clients need no change. The user manual already says only the Owner can reset another admin, so it needs no update.

#2306 also turns Repository.Issue into a transaction, to write audit rows. The two will conflict textually; the audit insert belongs after this change's authority check, inside the same transaction.

Validated cases: User management (#1196, #1197) and API keys C2 (#1190) cover admin authority and key scopes. They passed on builds made before reset links and the Owner rules existed, so those passes never exercised this path and stay valid.

Validation

  • Regression tests on PostgreSQL 18 (disposable, fully migrated). The new tests hold the real promotion code (MutateAdminAccount), or an ownership move, with the account locked, wait until issuance is blocked on it, then let it commit. Results:
    • Against the original single-statement Issue, the non-Owner admin and scoped-key cases fail: issuance returns no error and the link resolves.
    • With the issuer lock removed, the ownership-move test fails.
    • With this change, all of them pass, also under -race with -count=3.
  • A one-off probe, not committed because it needs a wall-clock timeout, showed that an open update of the issuer's row blocked issuance under the earlier lock and does not now.
  • go build ./..., gofmt -l ., go vet ./..., make lint-changed (0 issues), make lint-router-recovery: pass.
  • make test-db-contracts: all five password-reset contracts pass, including the two new ones. Two unrelated contracts fail locally: TestScanIndexesFileWithNonUTF8Name (the macOS filesystem rejects non-UTF-8 names) and TestNotificationInboxCutoffReplayAndTies, which appears to hit the same database-versus-host clock skew.
  • make test-db-pins: one unrelated failure, TestCollectionCollageReadsKeepActiveVariantsDB. It compares the database clock with the host clock, and the local Docker VM clock ran about 55 ms behind.
  • make test-go: failures only in packages that do not import the changed code (internal/jellycompat, internal/metadata/nfo, internal/playback, internal/scanner, internal/subtitles/subsync). They are case-variant filename, non-UTF-8 filename and real-FFmpeg tests that depend on the local macOS filesystem and media tooling. internal/passwordreset, internal/api/handlers and internal/apiv2 pass.
  • Web gate: install, lint, format check, build and budget check pass. make test-web has 30 failures in 5 files (auth refresh, request deadline, player context, admin collections); this branch changes no web code.
  • Every verify-* target and the committed apiv2 artifact test pass, except two. verify-route-inventory could not type-check the cgo files on macOS (could not import C), so it did not compare routes; this branch changes no routes. verify-prometheus-rules did not run because pulling prom/prometheus:v3.5.0 failed with a Docker DNS timeout.

Evidence

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

No screen changes. The only behavior change is the refusal in the race window described above.

Risks

  • Issuing a reset link now takes a share lock on the issuing admin's own row for the length of a short transaction. It waits only for an ownership move.
  • The locked check covers the same rules as the handler (Owner rules and scoped keys). It does not recheck that the issuer is still an enabled admin; the route middleware checks that when the request arrives, as before.

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 harness
  • Tool(s): Claude Code, GitHub CLI
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated; no human has reviewed it yet
  • Adversarial review: an independent read-only review by a separate Claude Agent session (claude-opus-5-5, high effort) tried to break the change. It found that locking the issuer FOR NO KEY UPDATE could deadlock with access-group updates (reproduced; fixed by the FOR KEY SHARE issuer lock), that no test covered the issuer lock (added the ownership-move test), and one inaccurate comment (fixed). It also noted two older gaps outside this change: a deleted or demoted issuer is not refused under the lock, and moveOwnership keeps reset links the former Owner issued.

🤖 Generated with Claude Code

Note

Recheck admin authority transactionally when storing password reset links

Repository issuance now re-verifies owner-target and scoped-key/admin authorization inside the same transaction that stores the link, using locked account state, so concurrent promotions or ownership moves are judged after the lock is acquired.

  • Adds passwordreset.Issuer and ErrScopedKeyAdmin; Repository.Issue locks the target (FOR NO KEY UPDATE) and issuer (FOR KEY SHARE) in sorted ID order, then inserts or replaces the link only if the target still matches.
  • The handler passes scoped-key status through IssueInput and maps ErrScopedKeyAdmin to the existing insufficient_scope API error in password_resets.go.
  • Adds concurrency DB tests for promotion and ownership-move serialization in repository_db_test.go, plus docs in password-resets.md.
  • Behavioral Change: Repository.Issue's issuer argument changed from an *account.ID pointer to Issuer; out-of-tree implementations of the passwordreset.repository interface must be updated.

Macroscope summarized 2ac0a30.

IssuePasswordReset checked the Owner rules and the scoped-key rule
against an account read before the link was stored. If the Owner
promoted the account in between, the promotion deleted the account's
reset links first and a non-Owner admin, or a scoped key, still
received a working link for the new admin.

Repository.Issue now locks the issuer (FOR KEY SHARE) and the account
(FOR NO KEY UPDATE) in id order, as ownership transfers do, reruns
auth.CheckOwnerTarget and the scoped-key rule on the locked rows, and
stores the link in the same transaction. A promotion or ownership move
that commits first is refused; a promotion that commits later deletes
the link as before. The issuer's weaker lock still waits for ownership
moves but not for access-group updates, which lock rows in no fixed
order. The handler keeps its early checks and maps the locked refusals
to the same 403 problems.

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 ❌

@coderabbitai

coderabbitai Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 7 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

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: b76e05c3-6198-4cfc-964c-beb5c8a8a373
Commits

Reviewing files that changed from the base of the PR and between 35135c6 and 2ac0a30.

Files selected for processing: 7
  • docs/architecture/password-resets.md
  • internal/api/handlers/password_resets.go
  • internal/passwordreset/repository.go
  • internal/passwordreset/repository_db_test.go
  • internal/passwordreset/service.go
  • internal/passwordreset/service_test.go
  • scripts/ci/db-contracts.txt
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@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:53:19.205429Z 2ac0a30 PR opened
🔒 Security Review ✅ Completed 2026-10-31T14:54:42.696625Z 2ac0a30 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 admin password-reset API now refuses issuance when the target's role or ownership changes during the request (internal/api/handlers/password_resets.go); the Evidence section says “publishing; link follows” but provides no link or captures. Add the evidence-page URL or before-and-after response excerpts for the same POST /api/v2/admin/users/{id}/password-reset race, showing the success-versus-403 outcome.

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

This comment has been minimized.

@Quick104
Quick104 merged commit b240158 into main Oct 31, 2026
22 checks passed
@Quick104
Quick104 deleted the fix/password-reset-locked-authorization branch October 31, 2026 20:30
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.

1 participant