Repository navigation
feat(auth): validate servers and restored sessions through v2 - #358
Conversation
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
|
Warning Review limit reachedNext included review available in 9 minutes. View limit detailsLimit 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. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (14)
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. Comment |
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. |
Code review summaryReviewed head: 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:
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 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 ( |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
e7cd7cc to
6665e5e
Compare
05cba3a to
05908e5
Compare
There was a problem hiding this comment.
💡 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() { |
There was a problem hiding this comment.
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 👍 / 👎.
6665e5e to
fa2ad8e
Compare
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]>
05908e5 to
5d7ac1b
Compare
There was a problem hiding this comment.
💡 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".
| default: | ||
| return .indeterminate |
There was a problem hiding this comment.
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 👍 / 👎.
Problem
Adding a server and validating a restored session on cold launch still used three v1 reads:
/api/v1/auth/setup(inAuthService.checkServerandRestoredSessionValidator.live),/api/v1/auth/me(SiloAPI.currentUser), and/api/v1/theme/brandingwith a/api/v1/healthfallback 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:
RestoredSessionValidatoronly understoodHTTPError. v2 errors arrive asAPIv2Error.problem/.httpStatus, so a 404 or 410 on the account read would have landed on.indeterminateand 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.
AuthService.checkServer) readsGET /api/v2/system/setupthroughAPIv2Client.setupStatus(explicit URL, public, ungated).AuthServicetakes the sharedSiloAPI.shared.apiV2Clientas an injectable dependency. A v1-only candidate fails withAPIv2Error.serverUpdateRequiredbefore anything is committed, andServerSetupViewModelalready shows the server-update copy for that (F5).RestoredSessionValidator.live(client:tokenStore:)) reads v2 setup and thenAPIv2Client.currentUser(GET /api/v2/account/me). The singlebindVerifiedAccountcall insidecurrentUseris kept, so validation also backfills the account ID for sessions installed without one. The token-first check (accessTokenReaderbefore any error classification) is unchanged.currentUserrefuses to send whileConnectionMonitor.isServerUpdateRequiredis 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 callsAuthService.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.APIv2Error.problemand.httpStatuswith the same status rules as before, applied toHTTPError.http. Transport, decoding and identity failures still arrive asHTTPErrorand are classified the same way as before.SiloAPI.currentUserdelegates toapiV2Client.currentUser()and maps the result toUserInfo(stringid,role == .admin). Its callers (settings, onboarding gate, diagnostics) are unchanged.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.serverNameis now required, which matches the contract.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.SetupStatus(replaced byAPIv2SetupStatus), the v1currentUserbody, the health fallback, and the unusedserverName/serverIdfields onHealthStatus.HealthStatusnow serves only the retainedConnectionMonitorprobe.Cold-launch outcomes (read-only surface; nothing here is a mutation):
.valid404 page not found) on setup or account, or a v1-only verdict that a re-probe confirms.serverRecovery(.serverUpdateRequired).validclient_upgrade_requiredon setup or account.serverRecovery(.appUpdateRequired).serverRecovery(.serverNotRecognized).indeterminate(local state used).needsLogin.indeterminateValidation
SiloTests) (full suite): PASS, 1608 tests, 2 skipped, 0 failures.SiloTVTests) (full suite): PASS, 1466 tests, 2 skipped, 0 failures.scripts/ci/check-no-api-v1.sh: ok. v1 matches drop inAuthService.swift,AuthModels.swift,RestoredSessionValidator.swift,ServerIdentity.swift,ServerNeedsSetupView.swift,SiloAPI.swiftand the touched tests. The allowlist is not edited, per the stack rules.iosApp/iosApp(withOwnerFence/sameCredentialIdentity): 60 before, 60 after.StubURLProtocol:RestoredSessionValidatorTests.testV2RepliesKeepRecoveryUpdateAndLoginOutcomescovers each row of the table above. It runs through the production composition with a realHTTPClientandTokenStore, and asserts the exact request paths (no v1, no fallback).testUpdateRequiredVerdictGatesAccountReadUntilRecheckClearsItruns 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.testUpdateRequiredVerdictIsRecheckedBeforeAccountReadandtestUpdateRequiredVerdictThatSurvivesRecheckSkipsAccountReadcover the same two outcomes at the validator boundary; the existing valid-session test checks that a v2 verdict triggers no re-probe.ServerIdentityResolverTestscovers the v2 branding name and the no-fallback cases.UpdateRequirementTestsserver-add cases now run over v2 setup only.DiagnosticsReviewFixesTestsadds the v2 5xx, 4xx and update-required cases.APIv2ContractStateTestsandHostedDiagnosticsAPITestspoint at the v2 routes and bodies.testCheckServerAndRefreshRecordTheContractVerdictalso checks thatrecheckActiveServerContract()records a probe answer.build ios,build tvos,build macosPASS; focusedtest ios(RestoredSessionValidatorTests,APIv2ContractStateTests,ServerIdentityResolverTests, 36 tests) andtest tvos(RestoredSessionValidatorTests,APIv2ContractStateTests, 29 tests) PASS. The full-suite numbers above predate that fix; the final-stack run below includes it.Risks and follow-ups
AuthService.swiftandRestoredSessionValidator.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 onmain. Expect a rebase conflict in those files.quietStatuses: [404], becauseAPIv2Client.setupStatushas no such parameter. A 404 on that read is now logged like any other failed request. There is no behavior change.APIv2Error.serverUpdateRequiredagainst a v1-only server. Settings and onboarding already swallow account-read errors, and diagnostics fails closed.AuthUserstays 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