Skip to content

fix(auth): read accounts that have no email, username, or password hash - #3392

Merged
Quick104 merged 4 commits into
mainfrom
fix/login-without-email-or-username
Nov 2, 2026
Merged

Quick104 merged 4 commits into
mainfrom
fix/login-without-email-or-username

Conversation

@Quick104

@Quick104 Quick104 commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

users.email, users.username and users.password_hash are nullable, but
several queries read them into plain Go strings. An account with any of them
empty makes those reads fail with cannot scan NULL into *string. On main that breaks the admin API
key list and the password reset flow for such an account, and the same
pattern sits in the owner, plugin identity, audiobook credential, and history
import queries. This change reads those columns as nullable everywhere they are selected.

Approach

  • auth reads email, username and password hash with nullable scan targets
    and treats NULL as empty. An empty password hash matches no password, as
    before.
  • The other queries that select users.username wrap it in COALESCE:
    admin API key listings, the owner check, plugin identity lookup, audiobook
    credential validation, history import admin, and password reset lookup.
  • Password reset signed the user in with their username. For an account with
    only an email, it now uses the email, which sign-in already accepts. If that
    sign-in resolves to a different account (an older account whose username
    equals this email), the reset revokes the new session and returns no tokens;
    the person signs in normally instead.

Validation

  • Go build, go vet, and changed-line lint: pass.
  • The database test that creates accounts with no email, no username, and no
    password hash and reads them through the affected queries passes against
    PostgreSQL 18.
  • The owner query change has no dedicated test; it is a one-line COALESCE.

Evidence

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

Risks

Password reset for an account without a username now signs in with the email
instead of failing. No change for accounts that have a username.

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 with Claude Code
  • Tool(s): Claude Code with subagents; OpenAI Codex CLI for independent review
  • Model(s): claude-opus-5-5; gpt-6.1-sol (review)
  • Involvement: Fully AI-generated. The maintainer tested the backups work it came from on a development server; the diff awaits human review.
  • Adversarial review: gpt-6.1-sol reviewed the backups work read-only in repeated rounds; every finding was fixed or answered before this branch was cut.

🤖 Generated with Claude Code

Note

Fix auth account reads failing on NULL email, username, or password hash

  • Adds a userLogin scan type with nullable string pointers in repository.go; scanUser and scanUsers map NULL email, username, and password hash to empty strings.
  • Coalesces NULL usernames to empty strings in account queries across API key listings, SiloCredValidator.ResolveUsername, UserRepository.SetOwner, password-reset lookup, history-import enrichment, and PgUserIdentityLookup.LookupIdentity.
  • Password-reset completion now signs in email-only accounts using the email, verifies the login belongs to the reset account, and revokes a mismatched session via a 5-second detached context before returning ErrSessionStart.
  • Adds a database-backed test, TestUserWithoutEmailOrUsernameDB, registered in db-contracts.txt.
  • Behavioral Change: sessionStarter in service.go gains a Logout method; implementations must now support session revocation by ID.

Macroscope summarized 0cbe850.

users.email and users.username are both nullable, and an account can have
only one of them; users.password_hash is nullable too. Reading such an
account failed while scanning NULL into a string, in the account reads, the
admin API key listings, owner recovery, plugin identity lookups, the
Audiobookshelf token check, history-import mappings, and password reset.
NULL now reads as empty, which no password matches, and a completed
password reset signs in with the email when the account has no username.

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 Nov 2, 2026
@silo-kody

silo-kody Bot commented Nov 2, 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 Nov 2, 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-11-02T01:40:58.946439Z 61b21b5 New commits
🔒 Security Review ✅ Completed 2026-11-02T01:42:43.647720Z 61b21b5 New commits
ℹ️ 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.

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

Authentication and related account lookups now handle nullable account fields. Password reset completion uses email when the username is empty and checks that the signed-in account matches the reset account.

Changes: Account field handling

Layer / File(s) Summary
Nullable account reads
internal/auth/repository.go, internal/auth/repository_login_test.go, scripts/ci/db-contracts.txt, internal/auth/api_key_metadata.go, internal/auth/owner.go, internal/audiobooks/cred_validator.go, internal/historyimport/repo_admin.go, internal/plugins/user_identity_lookup.go, internal/passwordreset/repository.go
Authentication scans map null email, username, and password hash values to empty strings. Related lookup queries handle null usernames, and the owner query maps a null comparison to false. The database test checks users with missing email or username and is included in the database-contract runner.
Password reset login validation
internal/passwordreset/service.go, internal/passwordreset/service_test.go
Password reset completion uses email when the username is empty. It rejects a missing or mismatched logged-in user and logs out a returned session when necessary. Tests cover sign-in to a different account.

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

Change: Bug fix

Possibly related issues

Suggested reviewers: rhainland

Merge Risk: Minimal · up to 0cbe8

The PR is mergeable; consider adding the missing PasswordHash assertion to complete the stated nullable-field coverage.

Security architecture risk: Low · up to 0cbe8

The flow checks that sign-in belongs to the reset account and withholds tokens on failure. Failed cleanup can leave an unrevoked session record, but the reviewed paths do not disclose its credentials or establish new cross-account access.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new path primarily affects username-less accounts completing a valid reset. A legacy collision can additionally create a session for the colliding account only if that account accepts the supplied password; the reset caller receives neither that session's tokens nor the other account's user result.

Security Findings and Attack Paths

  • inferred — The reviewed collision path does not establish cross-account credential disclosure. Even if cleanup fails, Complete discards the token pair, and the inspected refresh path requires a valid signed refresh token rather than a session identifier alone.

Trust Boundaries and Controls

  • observed — The caller supplies a reset token and new password, while the login identifier comes from the reset account's stored fields. Session identifiers are generated as random UUIDs; active-session checks bind the session to its account and enforce revocation and expiry.

Resilience and Maintainability Implications

  • observed — The service test covers mismatch rejection and successful logout. It does not inject logout failure or exercise concurrent completion; recovery conclusions for those cases rely on the transaction and cleanup source paths.

Hardening Proposals

  • proposed — Consider binding post-reset authentication to the expected account ID before persisting a session, while retaining existing credential and account-state checks. This would avoid compensating cleanup for legacy identifier collisions.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 60.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 names the main change: auth reads of accounts with NULL email, username, or password hash. It follows the conventional-commit form and matches the raw summary and PR objectives. The title is…
Description check Passed The description states the problem (nullable users.email, users.username, and users.password_hash read into plain Go strings), the approach (nullable scan targets, COALESCE in affected queries, passwo…
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: Title check

Explanation

The title names the main change: auth reads of accounts with NULL email, username, or password hash. It follows the conventional-commit form and matches the raw summary and PR objectives. The title is 71 characters, which is within a normal limit.

Full details: Description check

Explanation

The description states the problem (nullable users.email, users.username, and users.password_hash read into plain Go strings), the approach (nullable scan targets, COALESCE in affected queries, password-reset sign-in change), validation steps, and risks. It is clearly related to the changeset described in the raw summary.

Full details: Docstring Coverage

Explanation

Docstring coverage is 60.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 10 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

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code impact: usability Core flow broken or severely blocked priority: P2 Limited scope, workaround exists, or polish labels Nov 2, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Nitpick comments: 1
internal/auth/repository_login_test.go: 1

20-87: Trivial · Maintainability & Code Quality · Quick win

Assert the returned user fields in the List check.

The List check only counts the two fixture IDs. It does not compare Username or Email. A wrong field mapping in the List row scan would still pass this test. UserRepository.List returns scanUsers(rows), so that scan decides the returned fields. No other test in the repository calls UserRepository.List. The test's doc comment says account reads return missing values as empty, but only GetByID checks those values.

The suggested fix removes the only slices.Contains call in the file. Remove the "slices" import as well, or the file will not compile.

Suggested fix
 import (
 	"context"
 	"os"
-	"slices"
 	"strconv"
 	"testing"
 	"time"
-	for id, want := range map[int][2]string{noEmail: {name, ""}, noUsername: {"", mail}} {
+	wantByID := map[int][2]string{noEmail: {name, ""}, noUsername: {"", mail}}
+	for id, want := range wantByID {
 		u, err := users.GetByID(ctx, id)
 		if err != nil || u.Username != want[0] || u.Email != want[1] {
 			t.Fatalf("GetByID(%d) = %+v, %v; want username %q, email %q", id, u, err, want[0], want[1])
 		}
 	}
 	all, err := users.List(ctx)
 	if err != nil {
 		t.Fatal(err)
 	}
 	listed := 0
 	for _, u := range all {
-		if slices.Contains(ids, u.ID) {
-			listed++
+		want, ok := wantByID[u.ID]
+		if !ok {
+			continue
+		}
+		listed++
+		if u.Username != want[0] || u.Email != want[1] {
+			t.Fatalf("List user %d = username %q, email %q; want username %q, email %q", u.ID, u.Username, u.Email, want[0], want[1])
 		}
 	}
-	if listed != 2 {
+	if listed != len(wantByID) {
 		t.Fatalf("List returned %d of the two accounts", listed)
 	}

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: c6117c1b-cbe6-4120-a69a-ef879728e3c1
Commits

Reviewing files that changed from the base of the PR and between 7e0765b and 0e50c43.

Files selected for processing: 10
  • internal/audiobooks/cred_validator.go
  • internal/auth/api_key_metadata.go
  • internal/auth/owner.go
  • internal/auth/repository.go
  • internal/auth/repository_login_test.go
  • internal/historyimport/repo_admin.go
  • internal/passwordreset/repository.go
  • internal/passwordreset/service.go
  • internal/plugins/user_identity_lookup.go
  • scripts/ci/db-contracts.txt

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

Comment thread internal/passwordreset/service.go Resolved
Quick104 and others added 2 commits November 1, 2026 20:37
When an account has no username, the reset signs in with its email. An
email can still be another account's username when both predate the
single identity space, so sign-in could resolve to that account. Revoke
the session and report ErrSessionStart instead of returning it.

Also check the username and email that List returns in the DB test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 2, 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 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

The review-body nitpick on internal/auth/repository_login_test.go is fixed in 61b21b5: the List check now compares each account's username and email, not just the count.

🤖 Claude Code (claude-opus-5-5)

Comment thread internal/passwordreset/service.go Resolved
Comment thread internal/passwordreset/service.go Resolved
…aves

The revocation runs after the session exists, so a cancelled request
must not skip it. Detach it from request cancellation with a 5 second
bound, as the auth session cleanup does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-kody

silo-kody Bot commented Nov 2, 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 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nitpick comments: 2
internal/passwordreset/service_test.go: 2

346-358: Trivial · Functional Correctness · Quick win

Assert the session ID passed to Logout.

The mismatch test only checks that one logout call occurred. It would pass if Logout received an incorrect session ID instead of the SessionID returned by Login.

Suggested fix
-	if !errors.Is(err, ErrSessionStart) || pair != nil || user == nil || user.ID != 5 || len(loggedOut) != 1 {
+	if !errors.Is(err, ErrSessionStart) || pair != nil || user == nil || user.ID != 5 || len(loggedOut) != 1 || loggedOut[0] != "sess" {

98-120: Trivial · Functional Correctness · Quick win

Exercise the username-empty email fallback.

TestCompleteValidatesFirstAndReportsCommittedReset only uses Username: "alice", and fakeSessions.Login discards the identifier. A regression in the email fallback can therefore pass the test. Add a case with an empty username and non-empty email, and capture the identifier passed to Login.

Suggested fix
 type fakeSessions struct {
 	err error
 	// userID is the account sign-in resolves to; 0 means 5.
 	userID    int
 	loggedOut *[]string
+	loginName *string
 }
 
-func (f fakeSessions) Login(context.Context, string, string, string, string) (*auth.TokenPair, *models.User, error) {
+func (f fakeSessions) Login(_ context.Context, loginName, _ string, _, _ string) (*auth.TokenPair, *models.User, error) {
 	if f.err != nil {
 		return nil, nil, f.err
 	}
+	if f.loginName != nil {
+		*f.loginName = loginName
+	}
 	id := f.userID

Add a Complete case that sets repo.user to &models.User{ID: 5, Email: "[email protected]"}, configures loginName, and asserts that loginName == "[email protected]".


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: 8fc26039-f8e8-4760-b971-ad6c9551fe24
Commits

Reviewing files that changed from the base of the PR and between 0e50c43 and 61b21b5.

Files selected for processing: 4
  • internal/auth/repository_login_test.go
  • internal/passwordreset/service.go
  • internal/passwordreset/service_test.go
  • scripts/ci/db-contracts.txt

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nitpick comments: 1
internal/auth/repository_login_test.go: 1

42-72: Trivial · Maintainability & Code Quality · Quick win

Assert PasswordHash in the nullable-field test.

TestUserWithoutEmailOrUsernameDB inserts both accounts without a password hash, so password_hash is NULL for both rows. The GetByID and List checks compare only Username and Email. A change that returns a non-empty PasswordHash for these rows would still pass. The PR description says this test covers accounts with a missing password hash, so the assertion closes a gap in that stated coverage.

Suggested fix
-		if err != nil || u.Username != want[0] || u.Email != want[1] {
+		if err != nil || u.Username != want[0] || u.Email != want[1] || u.PasswordHash != "" {
-		if u.Username != want[0] || u.Email != want[1] {
+		if u.Username != want[0] || u.Email != want[1] || u.PasswordHash != "" {

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: 7f2df2c0-4e33-4d55-9bd1-89b1d00d42ce
Commits

Reviewing files that changed from the base of the PR and between 61b21b5 and 0cbe850.

Files selected for processing: 1
  • internal/passwordreset/service.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.

@Quick104
Quick104 merged commit c2cd384 into main Nov 2, 2026
34 checks passed
@Quick104
Quick104 deleted the fix/login-without-email-or-username branch November 2, 2026 03:06
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: usability Core flow broken or severely blocked priority: P2 Limited scope, workaround exists, or polish 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