Skip to content

fix(auth): refresh sessions through /api/v2/auth/refresh - #356

Merged
Quick104 merged 1 commit into
mainfrom
apiv2-stack/08-refresh-through-v2
Sep 23, 2026
Merged

Quick104 merged 1 commit into
mainfrom
apiv2-stack/08-refresh-through-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

Every token refresh still posts to /api/v1/auth/refresh. The URL is hard-coded in three places in HTTPClient (inventory rows 1, 2 and 130):

  • the ordinary refresh flight (performRefresh)
  • the scoped refresh flight for captured-identity and temporary remote-playback requests (performScopedRefresh)
  • the URL check before a scoped refresh (refreshScopedTokens)

A 1.0 server answers every /api/v1 route except health with 410 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 the RefreshedTokens response {access_token, refresh_token, expires_in} match the existing RefreshRequest/RefreshResponse. The server runs v1 and v2 refresh through the same Sessions.Refresh (router.go:2188), so tokens issued through v1 keep rotating in the same family and saved sessions carry over.

  • refreshSession is x-silo-class: public. isPublicAuthPath already matches the /auth/refresh suffix, 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):

    • 400 (malformed_request), 401 (session_expired, invalid_token) and 403 still end the session. The rule matches Android (AuthInterceptorImpl.kt).
    • 422 keeps the tokens. v2 sends 422 only when the body fails validation (a blank or over-long 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 on shouldInvalidateSessionAfterRefreshFailure.
    • 429, 5xx, transport errors and any other 410 keep the tokens, as before.
  • Update required on refresh (F5 classification). Before the terminal check, a new UpdateRequirement(v2StatusCode:body:) classifies the refresh answer:

    • 410 with client_upgrade_required, as a problem document or the v1 error envelope, becomes .app.
    • 404 with exactly Go's 404 page not found body (APIv2Probe.isLegacyNotFound) becomes .server. On a known /api/v2 route, 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 unused Bool. The owner, joiners, and the expired or challenged media-header path throw the UpdateRequirement instead of their 401. The background proactive media refresh (startProactiveMediaRefresh) drops it with try? and backs off for 10 seconds. UpdateRequirement now conforms to LocalizedError, so ErrorState, RestoredSessionValidator and localizedDescription show the existing update copy. A .server answer also records the update-required verdict for that server through ConnectionMonitor.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, on StubURLProtocol) exercises both the ordinary and scoped paths. Every test stub that served /api/v1/auth/refresh now serves the v2 route: SettingValuesAPITests, MediaRequestAuthorizationTests, MediaAuthorizationPlaybackTests, the StubURLProtocol usage comment, the refresh-route cases in HTTPClientDiagnosticsClassificationTests, and the negative refresh-URL cases in PlaybackMediaAuthorizationTests. The two AuthTokenModels comments name the v2 route.

Failure outcomes for the refresh mutation (x-silo-retry-safety: domain_identity; never auto-replayed):

Outcome Behavior
Definite success (2xx) Save the rotated pair under the captured owner fence (saveRefreshedTokens(replacing:)), then retry the original request once under the re-captured identity.
Definite failure: 400/401/403 Invalidate the captured credential (invalidateRejectedRefresh), post the session-expiry notification, and surface the original 401.
Definite failure: 410 client_upgrade_required / legacy 404 Keep the tokens and surface UpdateRequirement (.app / .server). .server also records the server-update verdict.
Definite failure: 422, 429, 5xx, other 4xx Keep the tokens and surface the original 401. A later 401 can refresh again.
Uncertain (transport error, no response) Keep the tokens, mark the server unreachable, and surface the original 401. The refresh is not replayed.

Validation

  • iOS, tvOS and macOS builds: all PASS.
  • iOS tests: PASS, 144 tests, 0 failures. Classes: RefreshSessionV2Tests, UpdateRequirementTests, SettingValuesAPITests, MediaRequestAuthorizationTests, MediaAuthorizationPlaybackTests, PlaybackMediaAuthorizationTests, HTTPClientDiagnosticsClassificationTests, RestoredSessionValidatorTests.
  • tvOS tests: PASS, 144 tests, 0 failures. Same classes.
  • iOS tests, second run: PASS, 31 tests, 0 failures. Classes: RemotePlaybackRoutingTests (iOS only), CredentialIdentityTests, AuthDeviceV2Tests.
  • scripts/ci/check-no-api-v1.sh: check-no-api-v1: ok. No /api/v1/auth/refresh literal remains in the app or tests.
  • New tests in RefreshSessionV2Tests. Each runs on both the ordinary and the scoped request path:
    • A 401 leads to POST /api/v2/auth/refresh with body {"refresh_token":…} and no Authorization or X-Profile-Id. The request is retried once with the rotated bearer, and both tokens rotate.
    • A classification table: 400, 401 session_expired, 401 invalid_token and 403 clear both tokens and post exactly one expiry. 422, a 410 playback_session_ended, 429 and 503 keep both tokens and post none. The request surfaces its original 401 in every row.
    • A 410 client_upgrade_required, as a problem document or the v1 envelope, surfaces .app with "Update Silo to keep using this server." Tokens are kept and no expiry is posted.
    • A legacy 404 page not found surfaces .server, ErrorState shows the server-update copy, ConnectionMonitor.isServerUpdateRequired becomes true, and tokens are kept.
    • An HTML 404 from another service is not update evidence: the original 401 surfaces and no verdict is recorded.
  • Not run: the plan's manual check (expire the access token on a bridge server on all three platforms).
  • 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

  • v1-only servers lose token refresh. A pre-v2 server has no /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.
  • A request that triggered a refresh now throws UpdateRequirement instead of HTTPError.http(401) when the refresh proves a version mismatch. Callers that match on HTTPError treat it as a generic error. The update-aware surfaces (ErrorState, RestoredSessionValidator, server setup) already classify it.
  • The refresh-triggered verdict goes through 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.
  • Server 84ed9e596 does not send client_upgrade_required yet. The 410 handling is covered only by stubbed replies.
  • Open PR feat(watch-party): add iOS and tvOS rooms and synchronized playback #347 touches different HTTPClient.swift hunks. 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

@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

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 44d08edc-ad4d-476d-8337-8829f9a1ed6a

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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:38:09.764448Z d31bdc5 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: 8a9ba4df (apiv2-stack/08-refresh-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:

  • minor: PR body says refresh fires only on a 401, but the media path also refreshes early and discards the new error

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).

@Quick104
Quick104 force-pushed the apiv2-stack/07-explain-v1-only-servers branch from f348ff0 to 5dc5b35 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/08-refresh-through-v2 branch from 8a9ba4d to 0def986 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/07-explain-v1-only-servers branch from 5dc5b35 to 28244ca Compare September 23, 2026 13:30
Base automatically changed from apiv2-stack/07-explain-v1-only-servers to main September 23, 2026 13:31
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]>
@Quick104
Quick104 force-pushed the apiv2-stack/08-refresh-through-v2 branch from 0def986 to d31bdc5 Compare September 23, 2026 13:31
@Quick104
Quick104 merged commit 178e9a0 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/08-refresh-through-v2 branch September 23, 2026 13:31

@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: 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 }

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 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 👍 / 👎.

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