Skip to content

fix(auth): bind tokens to their session's account and lock directory sign-ins - #3140

Merged
Quick104 merged 1 commit into
mainfrom
fix/sec-active-session-binding
Oct 27, 2026
Merged

Quick104 merged 1 commit into
mainfrom
fix/sec-active-session-binding

Conversation

@Quick104

@Quick104 Quick104 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #2920
Validation tasks: none

A login session could authenticate a token that names a different account, and a directory (LDAP) sign-in could leave a working session on an account an administrator had just disabled. An automated security scan found both, and a separate agent re-verified each against the code.

  • The per-request session check confirmed that an access token's session was active and that the session's account held the token's role. It never checked that the token's user ID was that account. Silo never issues such a token, but anyone holding the JWT signing secret could pair one account's ID with a live session of another account that has the same role, and the check would pass.
  • A password sign-in through a credentials plugin (LDAP) created its login session after account resolution had committed, without locking the account again. If an administrator disabled the account in that window, the new session kept working until its access token expired (8 hours by default). Local password sign-ins and OAuth sign-ins already lock and recheck the account before they open a session.

This change makes a session answer only for its own account, and opens directory sign-in sessions under the account lock.

Approach

SessionRepository.ActiveSession now takes the user ID the credential names and matches it in the same primary-key query, so the per-request check costs no extra statement. Because it is a parameter, every caller has to supply it: the auth middleware, direct-download links, Apple push display tokens, credential revalidation, the v1 events socket, the v2 socket validator, theme-song grants, the node media grant and plugin launch tokens each pass the user ID from the token or grant they already verified. Every token Silo issues names its session's own account, including impersonation tokens (which name the viewed account, the one that owns the session), device sign-in, remote-playback handoffs and refreshed tokens, so legitimate clients see no difference. A mismatched token gets the same 401 as a revoked session.

A directory sign-in now opens its session through OpenIdentitySession, the path OAuth completion and network sign-in already use. It locks the account, refuses a disabled one, locks the enabled installation and the linked identity, and inserts the session in that transaction. Disabling an account takes the same row lock and revokes the account's sessions in its own transaction, so either the disable revokes the new session or the sign-in sees the disabled account. Jellyfin and Audiobookshelf sign-ins through the directory still refuse an account that holds a temporary password, now checked under the lock as the local path does.

The request-time check still does not require users.enabled. The recorded contract scenario me.disabled_account pins a 200 for a disabled account's still-valid session on v1 and v2, and with this change no live session should outlive a disable, so tightening it is left as a separate contract decision.

#2920 stays open: a directory sign-in that overlaps a plain Sign out everywhere (no disable, unlink or password change) can still finish after the sign-out and keep its session. That matches what local password sign-ins do today.

Validation

  • Regression tests against a migrated Postgres: the session repository refuses another account's session under a different user ID, and a directory sign-in whose account is disabled after resolution fails with no live session. Both fail with the fixes reverted.
  • Admin impersonation (Admin impersonation — Server #1199 C1, C2, validated) goes through the changed check. Its tokens name the viewed account, which owns the session, and the impersonation tests and scenarios pass unchanged.
  • Focused packages (internal/auth with DB tests, internal/api/middleware, internal/api/handlers, internal/api, internal/apiv2, internal/proxy): pass. One handlers test with a fixed one-second wait timed out once while the machine was loaded and passes alone; it does not reach the session check.
  • Scenario executor, full live run (real router, fixture tokens for admins, members, a disabled account, impersonation, device sign-in and remote handoff): 1862 subtests pass, including every session, refresh, impersonation and device sign-in scenario. 82 assertions fail on catalog drift (new response fields, a changed header, an unknown placeholder) and on features this local setup leaves unconfigured (invitation links, avatar storage). None is at the auth gate: no request got an unexpected 401. CI runs only the public subset, and this run was not compared against main.
  • make test-go: passes except five packages with known local failures on macOS (case-insensitive file system, non-UTF-8 file names, a Dolby Vision PlaybackInfo case, a real-FFmpeg timeout). None touches the changed code.
  • go build, gofmt, go vet, make lint-changed, make lint-router-recovery: pass.

Evidence

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

No screen changes. Two responses change. An access token whose user ID is not its session's account, which Silo never issues, now gets the 401 a revoked session gets. A directory sign-in that races an administrator disabling the account now gets the disabled-account refusal instead of a session. Neither shows on a client screen. The evidence page has the test output.

Risks

Core authentication: every authenticated request goes through the changed query. The added predicate is on the row already fetched by primary key. A third-party tool that minted its own tokens with the server's secret and mismatched user and session IDs would stop working; Silo does not support that.

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 Code)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated; no human has reviewed the diff yet
  • Adversarial review: automated security scan finding, independently re-verified against the code by a separate agent before the fix.

🤖 Generated with Claude Code

Note

Bind login sessions and tokens to their account and lock directory sign-ins

  • SessionRepository.ActiveSession in session.go now takes a user ID and reports a session as active only for its owning account; all middleware, handler, and proxy session checks pass the token or grant's user ID
  • Non-local provider sign-in in service.go now goes through OpenIdentitySession, which rechecks the account and linked identity under locks before creating the session, so a disable or unlink between steps refuses sign-in
  • Adds a flag on IdentitySession to refuse sign-in when the account requires a password change
  • Adds a database test in credentials_link_db_test.go asserting a disabled account gets ErrUserDisabled and no live session
  • Documents the directory sign-in sequence in external-sign-in.md
  • Behavioral Change: a token or grant whose session belongs to a different user is now rejected as invalid across all auth paths (RequireAuth, RevalidateCurrent, socket validators, theme-song grants, direct-download links, plugin access, Apple push display, media grants); check ActiveSession callers and their userID arguments

Macroscope summarized fc268dc.

…sign-ins

The per-request session check confirmed that a token's session was active
and that the session's account held the token's role, but not that the
token's user ID was that account. ActiveSession now takes the user ID the
credential names and matches it in the same primary-key query; every
caller passes the ID from the token or grant it already verified.

A credentials-plugin (LDAP) sign-in inserted its login session after
account resolution committed, without locking the account again, so an
account disabled in that window kept a working session until its access
token expired. It now opens the session through OpenIdentitySession, under
the account, installation and identity locks an OAuth sign-in takes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 27, 2026
@silo-kody

silo-kody Bot commented Oct 27, 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 27, 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 36 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: 5e7f6e10-3cfa-43ba-a2dd-c71753f59adc
Commits

Reviewing files that changed from the base of the PR and between 073a5c4 and fc268dc.

Files selected for processing: 20
  • docs/architecture/external-sign-in.md
  • internal/api/handlers/events_socket_v2.go
  • internal/api/handlers/events_socket_v2_test.go
  • internal/api/handlers/events_ws.go
  • internal/api/handlers/events_ws_session_check_test.go
  • internal/api/handlers/theme_songs.go
  • internal/api/middleware/apple_push_display.go
  • internal/api/middleware/apple_push_display_test.go
  • internal/api/middleware/auth.go
  • internal/api/middleware/current_authority.go
  • internal/api/middleware/direct_download_link.go
  • internal/api/router.go
  • internal/api/router_v2_plugin_settings_test.go
  • internal/apiv2/parity_test.go
  • internal/auth/credentials_link_db_test.go
  • internal/auth/login_sessions_db_test.go
  • internal/auth/service.go
  • internal/auth/session.go
  • internal/proxy/mediagrant.go
  • internal/proxy/mediagrant_test.go
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 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-27T02:32:27.622180Z fc268dc PR opened
🔒 Security Review ✅ Completed 2026-10-27T02:34:19.858216Z fc268dc 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 27, 2026

Copy link
Copy Markdown

The change is visible in two authentication outcomes, but the linked evidence is described as test output rather than before-and-after API responses. Please add excerpts for:

  • A request using a token whose user ID does not match its session: previously accepted versus now rejected with 401.
  • A directory sign-in racing an account disable: previously opening a session versus now returning the disabled-account refusal.

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 27, 2026
Comment thread internal/auth/service.go
Comment on lines +828 to +834
pair, err := s.OpenIdentitySession(ctx, nil, IdentitySession{
UserID: user.ID,
IdentityID: identityID,
DeviceName: deviceName,
IP: ip,
RefusePasswordChange: refusePasswordChange,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug critical

Authentication failure in internal/auth/service.go occurs because non-local providers registered through RegisterProvider always enter OpenIdentitySession, but only the *PluginProvider authentication branch populates identityID; an AuthProvider that successfully returns a user therefore reaches lockOAuthIdentity with identityID == 0 and receives ErrNotPermitted instead of a session. Restrict identity-backed session opening to providers that supplied a plugin identity, and preserve an account-locked session path for other registered providers.

Prompt for LLM

File internal/auth/service.go:

Line 828 to 834:

Authentication failure in internal/auth/service.go occurs because non-local providers registered through RegisterProvider always enter OpenIdentitySession, but only the *PluginProvider authentication branch populates identityID; an AuthProvider that successfully returns a user therefore reaches lockOAuthIdentity with identityID == 0 and receives ErrNotPermitted instead of a session. Restrict identity-backed session opening to providers that supplied a plugin identity, and preserve an account-locked session path for other registered providers.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No current deployment hits this. In production the only password providers are the local provider, handled by the branch above, and the *PluginProvider instances that authProviderRegistry builds, so identityID is always set when this line runs. deps.AuthProviders is set only by the scenario executor (internal/scenariocatalog/executor/env.go), and its rejectingProvider refuses every login before a session is opened. A non-plugin provider added later would get ErrNotPermitted here. That fails closed: it refuses the sign-in instead of opening a session outside the account lock, which is the race this PR closes. If such a provider is ever added, it should get its own identity row rather than reuse the unlocked sessions.Create path.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Given the provider wiring you described, this is not a current authentication regression, and the critical severity is unwarranted. The finding identified a hypothetical successful non-plugin provider, not a reachable production sign-in path.

My recommendation to preserve a separate session-opening path was unnecessary for this PR. Keeping identity-backed session creation ensures the account-locking protection remains intact; an unsupported provider failing closed is not a reason to bypass it.

A future successful non-plugin provider should explicitly integrate with the identity-backed flow. That is future integration work, not a blocker for this security fix.

@Quick104

Copy link
Copy Markdown
Contributor Author

Both changes are covered in the Evidence section. A token whose user ID differs from its session's account now gets the revoked-session 401. A directory sign-in racing a disable now gets the disabled-account refusal. The evidence page has the output of the regression tests that drive both cases, failing on the unfixed code and passing on this branch. A live before-and-after response would need a forged token or a timed race, and the tests already show the same thing.

@Quick104
Quick104 merged commit d8d053f into main Oct 27, 2026
37 of 39 checks passed
@Quick104
Quick104 deleted the fix/sec-active-session-binding branch October 27, 2026 02:55
Brady3035 added a commit to Brady3035/silo-server that referenced this pull request Oct 28, 2026
Resolve the conflict in internal/api/router.go by keeping this branch's
removal of resolveOptionalPluginAccess(User); caller resolution lives in
internal/api/plugin_access.go. Port Silo-Server#3140's ActiveSession signature
(session id plus user id) to the plugin session checker and its test fake.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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/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