Repository navigation
fix(auth): refresh sessions through /api/v2/auth/refresh - #356
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.
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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 ( |
f348ff0 to
5dc5b35
Compare
8a9ba4d to
0def986
Compare
5dc5b35 to
28244ca
Compare
Every token refresh still went to POST /api/v1/auth/refresh: the ordinary refresh flight, the scoped (captured-identity and temporary remote playback) flight, and the URL check before a scoped refresh. A 1.0 server retires that route, so an expired access token could never be renewed. The refresh also had no answer for a version mismatch: a legacy 404 or a 410 client_upgrade_required fell through to the original 401. All three sites now use HTTPClient.refreshPath, /api/v2/auth/refresh. The request body and the token response are unchanged, and v1 and v2 rotate the same token family on the server, so saved sessions carry over. The failure classifier stays 400/401/403, matching Android. A 422 (a body the contract refused; neither path sends a blank token) keeps the tokens. A refresh answered with 410 client_upgrade_required or with the legacy 404 is an update requirement: the tokens stay, the requests waiting on that refresh flight throw the UpdateRequirement instead of their 401 (so error screens show the update copy), and a legacy 404 also records the server-update verdict in ConnectionMonitor so APIv2Client refuses further calls. Test stubs that served the v1 refresh route now serve the v2 one. Stack-PR: W1-A Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
0def986 to
d31bdc5
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d31bdc5566
ℹ️ 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".
| if inFlightRefreshes[key]?.id == flightId { | ||
| inFlightRefreshes.removeValue(forKey: key) | ||
| } | ||
| if let requirement { throw requirement } |
There was a problem hiding this comment.
Revalidate the request identity before throwing refresh results
If cancelInFlightRequests() runs after the refresh task produces an UpdateRequirement but before this actor resumes, it increments requestDispatchRevision and removes/cancels the flight, yet this line still throws the completed result unconditionally. An old server's 404 or 410 can therefore surface as an update prompt after the user has switched servers; the existing-flight and scoped-refresh branches have the same issue. Recheck the dispatch revision/block state before propagating the requirement.
Useful? React with 👍 / 👎.
Problem
Every token refresh still posts to
/api/v1/auth/refresh. The URL is hard-coded in three places inHTTPClient(inventory rows 1, 2 and 130):performRefresh)performScopedRefresh)refreshScopedTokens)A 1.0 server answers every
/api/v1route except health with410 client_upgrade_required, so an expired access token could never be renewed. A version mismatch on refresh also fell through to the request's original 401. The user saw a generic error instead of the update message F5 introduced.Solution
All three sites now use one constant,
HTTPClient.refreshPath = "/api/v2/auth/refresh"(refreshSession). The request body{refresh_token}and theRefreshedTokensresponse{access_token, refresh_token, expires_in}match the existingRefreshRequest/RefreshResponse. The server runs v1 and v2 refresh through the sameSessions.Refresh(router.go:2188), so tokens issued through v1 keep rotating in the same family and saved sessions carry over.refreshSessionisx-silo-class: public.isPublicAuthPathalready matches the/auth/refreshsuffix, so the request carries no bearer or profile headers and cannot recurse into refresh. Refresh fires on a 401, or on the media-header path (mediaRequestHeaders) when the access token is expired or close to expiry.Failure classification (claim A2 in
plan-workflow.json):malformed_request), 401 (session_expired,invalid_token) and 403 still end the session. The rule matches Android (AuthInterceptorImpl.kt).refresh_token,minLength:1/maxLength:4096). Both refresh paths already refuse to send a blank token, so a 422 means the client and the contract disagree, not that the credential was rejected. Signing the user out for a client bug would be worse than keeping the original 401. This is documented onshouldInvalidateSessionAfterRefreshFailure.Update required on refresh (F5 classification). Before the terminal check, a new
UpdateRequirement(v2StatusCode:body:)classifies the refresh answer:410withclient_upgrade_required, as a problem document or the v1 error envelope, becomes.app.404with exactly Go's404 page not foundbody (APIv2Probe.isLegacyNotFound) becomes.server. On a known/api/v2route, that body proves a v1-only server answered.In both cases the tokens stay and no session-expiry notification is posted. The refresh flight now returns
UpdateRequirement?instead of an unusedBool. The owner, joiners, and the expired or challenged media-header path throw theUpdateRequirementinstead of their 401. The background proactive media refresh (startProactiveMediaRefresh) drops it withtry?and backs off for 10 seconds.UpdateRequirementnow conforms toLocalizedError, soErrorState,RestoredSessionValidatorandlocalizedDescriptionshow the existing update copy. A.serveranswer also records the update-required verdict for that server throughConnectionMonitor.noteContractProbe(.updateServer, …). The flight writes that verdict itself, so it is recorded even when the proactive media refresh drops the error. After that,APIv2Client.gate()refuses further calls with the server-update message. The existing foreground and recovery re-probes can clear the verdict.Tests:
RefreshSessionV2Tests(new, onStubURLProtocol) exercises both the ordinary and scoped paths. Every test stub that served/api/v1/auth/refreshnow serves the v2 route:SettingValuesAPITests,MediaRequestAuthorizationTests,MediaAuthorizationPlaybackTests, theStubURLProtocolusage comment, the refresh-route cases inHTTPClientDiagnosticsClassificationTests, and the negative refresh-URL cases inPlaybackMediaAuthorizationTests. The twoAuthTokenModelscomments name the v2 route.Failure outcomes for the refresh mutation (
x-silo-retry-safety: domain_identity; never auto-replayed):saveRefreshedTokens(replacing:)), then retry the original request once under the re-captured identity.invalidateRejectedRefresh), post the session-expiry notification, and surface the original 401.client_upgrade_required/ legacy 404UpdateRequirement(.app/.server)..serveralso records the server-update verdict.Validation
scripts/ci/check-no-api-v1.sh:check-no-api-v1: ok. No/api/v1/auth/refreshliteral remains in the app or tests.RefreshSessionV2Tests. Each runs on both the ordinary and the scoped request path:POST /api/v2/auth/refreshwith body{"refresh_token":…}and noAuthorizationorX-Profile-Id. The request is retried once with the rotated bearer, and both tokens rotate.session_expired, 401invalid_tokenand 403 clear both tokens and post exactly one expiry. 422, a 410playback_session_ended, 429 and 503 keep both tokens and post none. The request surfaces its original 401 in every row.client_upgrade_required, as a problem document or the v1 envelope, surfaces.appwith "Update Silo to keep using this server." Tokens are kept and no expiry is posted.404 page not foundsurfaces.server,ErrorStateshows the server-update copy,ConnectionMonitor.isServerUpdateRequiredbecomes true, and tokens are kept.Risks and follow-ups
/api/v2/auth/refresh. Once the access token expires, the app shows the server-update message and records the update-required verdict instead of renewing the session. Saved credentials are not removed. This follows the no-v1-fallback rule (I13) and D7.UpdateRequirementinstead ofHTTPError.http(401)when the refresh proves a version mismatch. Callers that match onHTTPErrortreat it as a generic error. The update-aware surfaces (ErrorState,RestoredSessionValidator, server setup) already classify it.noteContractProbe, which starts a new probe generation for that server. An in-flight system-info probe for the same server is then dropped, and the refresh's verdict stands until the next re-probe.84ed9e596does not sendclient_upgrade_requiredyet. The 410 handling is covered only by stubbed replies.HTTPClient.swifthunks. The plan expects this PR to be able to land first, but a textual conflict is still possible.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 8 of 50 in the Apple API v2 stack. Base:
apiv2-stack/07-explain-v1-only-servers. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code