Skip to content

feat(auth): validate servers and restored sessions through v2 - #358

Merged
Quick104 merged 2 commits into
mainfrom
apiv2-stack/10-validate-servers-through-v2
Sep 23, 2026
Merged

Quick104 merged 2 commits into
mainfrom
apiv2-stack/10-validate-servers-through-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

Adding a server and validating a restored session on cold launch still used three v1 reads: /api/v1/auth/setup (in AuthService.checkServer and RestoredSessionValidator.live), /api/v1/auth/me (SiloAPI.currentUser), and /api/v1/theme/branding with a /api/v1/health fallback for the server name (ServerIdentityResolver.fetchServerName). Against a 1.0 server, these v1 routes are tombstoned.

Moving the account read to v2 also exposed a gap: RestoredSessionValidator only understood HTTPError. v2 errors arrive as APIv2Error.problem / .httpStatus, so a 404 or 410 on the account read would have landed on .indeterminate and silently skipped the recovery and update screens (claim A6).

Solution

Inventory rows 5, 6, 7 and 8 move to v2. Row 9 (the health fallback) is deleted per D8.

  • Server add (AuthService.checkServer) reads GET /api/v2/system/setup through APIv2Client.setupStatus (explicit URL, public, ungated). AuthService takes the shared SiloAPI.shared.apiV2Client as an injectable dependency. A v1-only candidate fails with APIv2Error.serverUpdateRequired before anything is committed, and ServerSetupViewModel already shows the server-update copy for that (F5).
  • Cold-launch validation (RestoredSessionValidator.live(client:tokenStore:)) reads v2 setup and then APIv2Client.currentUser (GET /api/v2/account/me). The single bindVerifiedAccount call inside currentUser is kept, so validation also backfills the account ID for sessions installed without one. The token-first check (accessTokenReader before any error classification) is unchanged.
  • Re-probe before the gated account read. currentUser refuses to send while ConnectionMonitor.isServerUpdateRequired is set, and that verdict only changes on a new probe. When the v2 setup read succeeds but the verdict still says v1-only (the server was updated in place while the recovery screen was up), the validator first calls AuthService.recheckActiveServerContract(), which runs the usual contract probe for the active server under the same generation and active-server rules. If the probe answers v2, the account read goes ahead, so "Try again" leaves the update screen. If it still answers v1-only or fails, the validator returns update-required without sending the account read.
  • Error classification in the validator now handles APIv2Error.problem and .httpStatus with the same status rules as before, applied to HTTPError.http. Transport, decoding and identity failures still arrive as HTTPError and are classified the same way as before.
  • SiloAPI.currentUser delegates to apiV2Client.currentUser() and maps the result to UserInfo (string id, role == .admin). Its callers (settings, onboarding gate, diagnostics) are unchanged.
  • Server name comes from GET /api/v2/theme/branding (ServerIdentity.brandingPath). A blank name, a failure, or a v1-only server's legacy 404 returns nil and keeps the stored name. Nothing falls back to health. ServerBrandingStatus.serverName is now required, which matches the contract.
  • Diagnostics capture fallback (DiagnosticsCoordinator.isTransientCaptureFallbackFailure) treats a v2 5xx from the account read as transient. It did the same for the v1 read, so persistent captures still fall back to the last-known snapshot during a server outage. 4xx and update-required answers fail closed, as before.
  • Deleted: v1 SetupStatus (replaced by APIv2SetupStatus), the v1 currentUser body, the health fallback, and the unused serverName/serverId fields on HealthStatus. HealthStatus now serves only the retained ConnectionMonitor probe.

Cold-launch outcomes (read-only surface; nothing here is a mutation):

Reply Result Session
setup 200, account 200 .valid kept
legacy 404 (404 page not found) on setup or account, or a v1-only verdict that a re-probe confirms .serverRecovery(.serverUpdateRequired) kept
setup 200 with a v1-only verdict that the re-probe clears, account 200 .valid kept
410 client_upgrade_required on setup or account .serverRecovery(.appUpdateRequired) kept
problem 404 or a proxy 404 .serverRecovery(.serverNotRecognized) kept
408/429/5xx, transport failure, cancellation .indeterminate (local state used) kept
account 401, refresh rejected (token removed) .needsLogin removed by the existing refresh policy
account 401, refresh unavailable (token still present) .indeterminate kept

Validation

  • iOS, tvOS and macOS builds: all PASS.
  • iOS tests (SiloTests) (full suite): PASS, 1608 tests, 2 skipped, 0 failures.
  • tvOS tests (SiloTVTests) (full suite): PASS, 1466 tests, 2 skipped, 0 failures.
  • scripts/ci/check-no-api-v1.sh: ok. v1 matches drop in AuthService.swift, AuthModels.swift, RestoredSessionValidator.swift, ServerIdentity.swift, ServerNeedsSetupView.swift, SiloAPI.swift and the touched tests. The allowlist is not edited, per the stack rules.
  • Ownership fence lines in iosApp/iosApp (withOwnerFence/sameCredentialIdentity): 60 before, 60 after.
  • New and updated tests, all using StubURLProtocol:
    • RestoredSessionValidatorTests.testV2RepliesKeepRecoveryUpdateAndLoginOutcomes covers each row of the table above. It runs through the production composition with a real HTTPClient and TokenStore, and asserts the exact request paths (no v1, no fallback).
    • testUpdateRequiredVerdictGatesAccountReadUntilRecheckClearsIt runs the production composition with a v1-only verdict: when the re-probe confirms it, only the setup read is sent and the result is update-required; when the re-probe clears it, the account read is sent and the result is .valid.
    • testUpdateRequiredVerdictIsRecheckedBeforeAccountRead and testUpdateRequiredVerdictThatSurvivesRecheckSkipsAccountRead cover the same two outcomes at the validator boundary; the existing valid-session test checks that a v2 verdict triggers no re-probe.
    • ServerIdentityResolverTests covers the v2 branding name and the no-fallback cases.
    • UpdateRequirementTests server-add cases now run over v2 setup only.
    • DiagnosticsReviewFixesTests adds the v2 5xx, 4xx and update-required cases.
    • APIv2ContractStateTests and HostedDiagnosticsAPITests point at the v2 routes and bodies. testCheckServerAndRefreshRecordTheContractVerdict also checks that recheckActiveServerContract() records a probe answer.
  • After the re-probe fix: build ios, build tvos, build macos PASS; focused test ios (RestoredSessionValidatorTests, APIv2ContractStateTests, ServerIdentityResolverTests, 36 tests) and test tvos (RestoredSessionValidatorTests, APIv2ContractStateTests, 29 tests) PASS. The full-suite numbers above predate that fix; the final-stack run below includes it.
  • Not run: the plan's manual checks. These are adding a v1-only server, a bridge server and an unreachable host; cold-launching a revoked session; and watching the tvOS sign-in flow (TV client sign-in & onboarding — iOS #326, TV client sign-in & onboarding — tvOS #327).
  • Final stack: with all 50 PRs applied, the full iOS suite (1981 tests) and tvOS suite (1792 tests) passed with 0 failures, the macOS build passed, and the v1 path guard passed. Every branch in the stack, this one included, builds on its own.

Risks and follow-ups

  • Conflict with open PR feat(watch-party): add iOS and tvOS rooms and synchronized playback #347 (watch party). It touches AuthService.swift and RestoredSessionValidator.swift. The plan lists feat(watch-party): add iOS and tvOS rooms and synchronized playback #347 as a dependency, but it has not merged, so this PR builds on main. Expect a rebase conflict in those files.
  • The cold-launch setup probe no longer passes quietStatuses: [404], because APIv2Client.setupStatus has no such parameter. A 404 on that read is now logged like any other failed request. There is no behavior change.
  • The account read is now gated on the recorded v1-only verdict. Settings, the onboarding gate and diagnostics read APIv2Error.serverUpdateRequired against a v1-only server. Settings and onboarding already swallow account-read errors, and diagnostics fails closed.
  • AuthUser stays because the v1 login and device-login responses still decode it. W5-A removes it.

AI disclosure

Code and description written by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.


Part 10 of 50 in the Apple API v2 stack. Base: apiv2-stack/09-unauthenticated-health-probe. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 9 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 61789fdc-75bb-4a7b-98e3-a52908ac107a

📥 Commits

Reviewing files that changed from the base of the PR and between 00dba12 and 5d7ac1b.

📒 Files selected for processing (14)
  • iosApp/Tests/APIv2ContractStateTests.swift
  • iosApp/Tests/DiagnosticsReviewFixesTests.swift
  • iosApp/Tests/HostedDiagnosticsAPITests.swift
  • iosApp/Tests/RestoredSessionValidatorTests.swift
  • iosApp/Tests/ServerIdentityResolverTests.swift
  • iosApp/Tests/UpdateRequirementTests.swift
  • iosApp/iosApp/Networking/ServerIdentity.swift
  • iosApp/iosApp/Networking/SiloAPI.swift
  • iosApp/iosApp/Screens/Auth/AuthModels.swift
  • iosApp/iosApp/Screens/Auth/AuthService.swift
  • iosApp/iosApp/Screens/Auth/RestoredSessionValidator.swift
  • iosApp/iosApp/Screens/Auth/ServerNeedsSetupView.swift
  • iosApp/iosApp/Screens/Auth/ServerSetupViewModel.swift
  • iosApp/iosApp/Shared/Diagnostics/DiagnosticsCoordinator.swift

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 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-09-23T13:37:30.395871Z 5d7ac1b 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.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: 05cba3a4 (apiv2-stack/10-validate-servers-through-v2).

Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration.

Verified findings, all fixed on this branch:

  • major: After an in-place server upgrade, "Try again" on the update-required screen still says the server needs updating

Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no /api/v1 request from the new builds except the retained health probe.

Remaining: no open verified findings. Merge in stack order.

Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack.

Review by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 05cba3a40a

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

serverURL: normalized,
path: "/api/v1/auth/setup"
)
let status = try await apiV2Client.setupStatus(serverURL: normalized)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject candidates that fail the v2 contract probe

When a bridge or partially routed candidate serves /api/v2/system/setup but its authoritative /api/v2/system/info probe returns the legacy 404, this call succeeds, the registry is committed and switched, and only afterward recordContractVerdict marks the server update-required. ServerSetupViewModel therefore routes the user to login even though subsequent v2 operations are gated. Check the candidate's contract verdict and reject .updateServer before addOrUpdate rather than treating setup alone as proof of a usable v2 server.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/09-unauthenticated-health-probe branch from e7cd7cc to 6665e5e Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/10-validate-servers-through-v2 branch from 05cba3a to 05908e5 Compare September 23, 2026 13:19

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 05908e539d

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// the recovery screen is up), so probe again before trusting it.
// A failed probe leaves the verdict, and the gate would refuse the
// read anyway, so answer update-required without sending it.
if await isServerUpdateRequired() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Probe unknown contracts before accepting restored sessions

On a cold process launch, ConnectionMonitor.contractStatus starts as .unknown, so this condition skips the authoritative /api/v2/system/info probe and proceeds directly from setup to the account read. A partially routed server that serves /api/v2/system/setup and /api/v2/account/me but whose contract probe still returns the legacy 404 is therefore accepted as .valid; the concurrent branding refresh is not guaranteed to finish first. Recheck when the verdict is unknown as well as update-required, and reject a confirmed .updateServer result before authenticating the restored session.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/09-unauthenticated-health-probe branch from 6665e5e to fa2ad8e Compare September 23, 2026 13:31
Base automatically changed from apiv2-stack/09-unauthenticated-health-probe to main September 23, 2026 13:31
Quick104 and others added 2 commits September 23, 2026 09:31
Adding a server, cold-launch session validation, and the account read
still used /api/v1/auth/setup, /api/v1/auth/me and
/api/v1/theme/branding, with a /api/v1/health fallback for the server
name. The restored-session validator only understood HTTPError, so once
the account read moved to v2, a 404 or 410 would have fallen through to
"indeterminate" and hidden the recovery and update screens.

Server add and the validator now read GET /api/v2/system/setup, the
account read goes through APIv2Client.currentUser (GET
/api/v2/account/me, which also binds the verified account ID), and the
server name comes from GET /api/v2/theme/branding. The health fallback
is gone (D8): v2 branding always carries server_name, and a v1-only
server is update-required anyway. The validator classifies
APIv2Error.problem and .httpStatus by status, so a 404 keeps the
"server not recognized" recovery, a legacy 404 or the v1-only verdict
shows the server-update copy, a 410 client_upgrade_required shows the
app-update copy, and a revoked session still ends in needsLogin through
the token-first check. The diagnostics capture fallback also treats a
v2 5xx on the account read as transient, as it did for v1.

The v1 SetupStatus model and the unused health identity fields are
deleted.

Stack-PR: W1-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
After an admin updated a v1-only server in place, "Try again" on the
update-required screen still said the server needed updating. The v2
setup read succeeded, but APIv2Client.currentUser refused to send
because ConnectionMonitor still held the old verdict, and nothing on the
recovery screen re-ran the contract probe.

When the setup read succeeds while the active server's verdict is
update-required, the validator now calls
AuthService.recheckActiveServerContract(), which runs the usual contract
probe under the same generation and active-server rules. A v2 answer
lets the account read go ahead; a v1-only or failed probe returns
update-required without sending it.

Stack-PR: W1-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/10-validate-servers-through-v2 branch from 05908e5 to 5d7ac1b Compare September 23, 2026 13:32
@Quick104
Quick104 merged commit e39d74c into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/10-validate-servers-through-v2 branch September 23, 2026 13:32

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5d7ac1b35a

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +200 to 201
default:
return .indeterminate

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fail closed on verified account-ID mismatches

When /api/v2/account/me returns an ID different from the canonical session's account ID, APIv2Client.currentUser() throws AccountSessionPersistenceError.invalidIdentity from bindVerifiedAccount, but this default branch converts it to .indeterminate. Callers explicitly retain the locally authenticated state for that result, so cached data from the previous account can remain visible even after the server authoritatively identifies the token as another account; handle this mismatch as a terminal identity/session failure rather than an offline fallback.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant