Skip to content

Stop the redirect check before the cross-origin destination - #213

Merged
mbarta merged 8 commits into
mainfrom
security/verification-fetch-no-credential-redirect
Nov 3, 2026
Merged

mbarta merged 8 commits into
mainfrom
security/verification-fetch-no-credential-redirect

Conversation

@jeremy

@jeremy jeremy commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

What

The redirect check in HttpRepository no longer requests the cross-origin destination. It follows same-origin hops by hand and returns the first cross-origin Location without requesting it. Then Session proposes that location as a cross-origin redirect visit.

Why

When Turbo's fetch hits a cross-origin redirect, the browser blocks it, and Turbo calls visitRequestFailedWithNonHttpStatusCode. Native then fetches the location again to find out where the redirect goes.

Since #211, that fetch only sends each host its own cookies, so cookies don't leak to the destination anymore. But the fetch still followed the whole chain, so the destination got a request from native before the WebView visited it. That's a problem when the destination URL carries a single-use token, like an OAuth or SAML handoff. Native's request uses up the token, and then the WebView's visit fails.

The fetch can't stop at the first hop, though. The usual chain is /account → /login → https://idp.example/auth: the browser follows the same-origin hops itself and only stops at the cross-origin one. A check that read just the first Location would see /login as same-origin and show an error screen instead of the IdP.

How

  • Same-origin hops: HttpRepository.fetchCrossOriginRedirect follows them with redirects turned off on the client, up to 20 hops (OkHttp's own limit). Each hop gets its own host's cookies from WebViewCookieJar.
  • Cross-origin redirect: the fetch returns the first Location with a different scheme, host or port, without requesting it.
  • Dead ends: a response that isn't a redirect, a redirect loop longer than 20 hops, an empty Location or a non-http Location (javascript:, intent:) returns null, and the visit fails with the usual error.
  • Session: Session reads the returned location directly. It no longer requires a 2xx at the end of the chain, because the fetch never requests the destination.

Behavior changes

  • Origin comparison: the check now compares the full origin, not just the host. So https://app → http://app and https://app → https://app:8443 now count as cross-origin redirects. navigator.route() checks those locations against the origin trust policy, so an untrusted origin opens in a browser tab, not in the app.
  • Error case: a same-origin chain that ends in a response still fails the visit, the same as before.

Testing

HttpRepositoryTest (MockWebServer) covers:

  • a cross-origin redirect, whose destination server gets no requests
  • a same-origin hop followed by a cross-origin redirect, with the session cookie sent on the same-origin hop
  • a same-origin chain that ends in a response, including a relative Location
  • a redirect loop, which stops after 20 requests
  • an empty Location and a javascript: location
  • connection reuse, which shows each response gets closed

SessionTest covers the multi-hop case end to end: a same-origin hop, then a cross-origin redirect, proposes the cross-origin visit.

With the hop limit set to 1, which is first-hop-only behavior, the 5 multi-hop tests fail. :core:testDebugUnitTest passes (208 tests).

🤖 Generated with Claude Code

@jeremy
jeremy requested review from jayohms and mbarta August 27, 2026 18:33
@jeremy
jeremy changed the base branch from main to host-scoped-webview-cookies August 28, 2026 07:10
@jeremy
jeremy force-pushed the security/verification-fetch-no-credential-redirect branch from f7f5403 to fcd94e8 Compare August 28, 2026 07:10
@rosa

rosa commented Sep 9, 2026

Copy link
Copy Markdown
Member

🤖 Review pass on this branch, run by an agent on Rosa's account. Two commits pushed on top of yours; everything else below is left for you to decide.

Base branch

host-scoped-webview-cookies still exists, hasn't moved since Aug 20, and is still the head of open #211. main hasn't moved since Jul 27. This branch was already sitting exactly on its base (0 behind), so no rebase was needed and I left the base alone.

Retargeting to main would be wrong today. This diff is written against the post-#211 HttpRepository (no manually-set Cookie header), and both HttpRepositoryTest and BaseRepositoryTest depend on WebViewCookieJar. #211 is also the broader fix — it covers OfflineHttpRepository and OfflinePreCacheRequest, which this PR doesn't touch. turbo-android already merged its twin of #211 (#356, Aug 19), so the sequence worth agreeing on is #211, then this, then #215.

Credentials on a redirect, every hop

With followRedirects(false) there is exactly one hop by construction, so "every hop" holds trivially — the real question is whether anything else can still egress to the destination. Traced against okhttp 5.3.2 and I couldn't find a path:

  • RetryAndFollowUpInterceptor.buildRedirectRequest returns null on its first statement when followRedirects is false, and all six 3xx codes go through it.
  • authenticator / proxyAuthenticator are Authenticator.NONE — never set in HotwireHttpClient, and newBuilder() inherits them unchanged.
  • 408 / 421 / 503 follow-ups re-issue the same request URL.
  • BridgeInterceptor sets Cookie from cookieJar.loadForRequest(url) for the one URL actually being sent.
  • The cache and the BASIC logging interceptor produce no egress.

newBuilder() sharing is clean: same connection pool, dispatcher, cache and interceptors, and the shared client isn't mutated, so PathConfigurationRepository and OfflineHttpRepository keep following redirects exactly as before.

Hostile Location values are safe too. HttpUrl.resolve returns null for javascript:, intent:, data:, file:, market: and for a tab-injected URL, so none of them can reach navigator.route() — redirectFrom returns null and the visit just fails. //evil.com, ///evil.com, /\evil.com and https://app.example.com@evil.com all resolve the way Chromium's parser resolves them and come out cross-origin.

Pushed

  • Trim the comments to what a reader of the current code needs.
  • Add an off-host redirect test. Worth knowing why: both MockWebServer instances bind the same loopback host, so does not forward credentials to a cross-origin redirect destination differs from the first-party origin only by port. It passes solely because of the port term this PR adds, and there was no cross-host case anywhere in the suite — the shape actually reported. The new case uses an absolute off-host Location, which needs no second server precisely because the redirect isn't followed.

./gradlew :core:testDebugUnitTest — 23 classes, 155 tests, green.

Worth deciding before merge

1. Multi-hop is the regression to weigh. redirectFrom reads the first Location only, so first-party → same-origin → cross-origin reports isCrossOrigin = false and Session falls through to visitRequestFailedWithStatusCode(WebError.Unknown), an error screen. The description calls this failing closed, which is accurate, but it's worth being explicit that this is the SSO shape (/dashboard → /session/refresh → IdP) and that the browser reaches this bridge call because fetch followed the same-origin hops itself and only tripped CORS at the cross-origin one. A bounded loop that follows same-origin hops and stops before sending on the first cross-origin Location would keep both the property and the feature — the cookie jar already keys per hop URL, so a same-origin hop carries nothing a same-origin request wouldn't.

2. HttpRequestResult.response no longer has a production reader. Session reads only result.redirect. The response is never closed, and against Rails (redirect_to always emits a body) an unread 302 body holds a pooled connection until finalization, plus an OkHttp leaked-connection log line. It leaks identically on main today so it isn't a regression, but this PR removes the last reason to hold it: execute().use { redirectFrom(it) } and dropping response from the result would close it.

3. The origin comparison widens behaviour as well as tightening it. https://app → http://app and https://app → https://app:8443 used to read same-origin (error screen) and now read cross-origin, which means pop() + route(location). Correct by the web's definition of origin, but the downgrade row means the library now proposes a cleartext navigation where it previously refused. Worth a line in the description.

4. Nits. An empty Location header is non-null and resolve("") returns the request URL, so you get HttpRedirect(location = <the original URL>, isCrossOrigin = false) — inert today because only isCrossOrigin is read, but .takeIf { it.isNotEmpty() } would make it honest. And followSslRedirects(false) is dead code: buildRedirectRequest returns on !followRedirects before it's ever consulted.

5. The description and commit message describe the pre-#211 code ("attached the WebView's cookies as a static Cookie header and issued the request with a redirect-following client"). On this base that isn't what the fetch does any more. I left your commit message alone.

6. #215 overlaps. It adds dev.hotwire.core.security.Origins.hasSameOriginAs — a duplicate of the private isSameOriginAs here — and converts visitRequestFailedWithNonHttpStatusCode from @JavascriptInterface to an internal fun dispatched from a WebMessageListener, which is a textual conflict with this diff in the same method.

One nice side effect nobody claimed: SessionTest (130-150) used to reach the live internet — the old code followed the enqueued 301 → https://example.com/ off the mock server out to the real host, and the assertion held only because example.com answers 2xx. Reading Location directly makes it hermetic. It passes unchanged.

@mbarta

mbarta commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

Thanks, looks good but I'll re-build the changes on #215 when it's merged.

@mbarta
mbarta force-pushed the security/verification-fetch-no-credential-redirect branch from 7791f59 to d2e3ff8 Compare September 23, 2026 13:52
@mbarta
mbarta removed this pull request from stack #214 September 23, 2026 13:55
@mbarta
mbarta added this pull request to stack #219 September 23, 2026 13:55
@mbarta
mbarta force-pushed the security/verification-fetch-no-credential-redirect branch from 0a7efdb to 037e768 Compare November 3, 2026 10:48
Copilot AI balanced review requested due to automatic review settings November 3, 2026 10:48

Copilot AI 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.

🟢 Approval recommended

No active review issues remain for the redirect-verification change.

No open issues 🎉

What changed in this PR

This PR prevents the native redirect-verification fetch from forwarding credentials to redirect destinations by inspecting the first redirect response without following it.

Changes:

  • Disables redirect following, resolves Location headers, compares full origins, and closes verification responses.
  • Updates Session to handle cross-origin redirects without requiring a successful final response.
  • Adds tests for credential containment, origin detection, relative locations, non-redirect responses, and connection reuse.
File Description
core/​src/​test/​kotlin/​dev/​hotwire/​core/​turbo/​http/​HttpRepositoryTest.kt Adds redirect-verification and response-cleanup tests.
core/​src/​test/​kotlin/​dev/​hotwire/​core/​turbo/​BaseRepositoryTest.kt Configures the test client with WebView cookies.
core/​src/​main/​kotlin/​dev/​hotwire/​core/​turbo/​session/​Session.kt Consumes redirect metadata directly when handling failed visits.
core/​src/​main/​kotlin/​dev/​hotwire/​core/​turbo/​http/​HttpRepository.kt Inspects redirects without following them and returns full-origin comparison results.

Review effort: Balanced

Base automatically changed from host-scoped-webview-cookies to main November 3, 2026 14:57
jeremy and others added 7 commits November 3, 2026 15:57
The native redirect-verification fetch attached the WebView's cookies as
a static Cookie header and issued the request with a redirect-following
client. On a cross-origin redirect, OkHttp forwards that caller-set
Cookie header to the destination (it drops Authorization on a host
change, but not a caller-set Cookie), delivering first-party cookies to
a different origin.

The fetch only needs to detect a cross-origin redirect, not follow it
with credentials. Disable redirect following on the verification client
and resolve the destination from the Location header, comparing the full
origin (scheme, host, and port) so a scheme downgrade or port change
counts as cross-origin. No credential-bearing request is ever sent to a
redirect destination.

Session.visitRequestFailedWithNonHttpStatusCode no longer gates on
response.isSuccessful (which only held when redirects were followed to a
2xx); detecting the cross-origin redirect response is sufficient to
propose the cross-origin redirect visit.

Adds HttpRepositoryTest (MockWebServer) covering the no-leak invariant,
cross/same-origin detection, and relative Location resolution.
Keep the reason the fetch doesn't follow redirects and drop the rest:
the same-origin comparison reads off its own body, and the guarantee it
supports is stated once where the client is built.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyPGJuffiyfWW9113PNxHG
Both MockWebServer instances bind the same loopback host, so the
existing cross-origin case differs from the first-party origin only by
port and exercises just the port term of the origin comparison. Add a
case with an absolute off-host Location, which needs no second server
precisely because the redirect isn't followed.

Also trim the test's comments, keeping the two that say why a request
count is asserted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DyPGJuffiyfWW9113PNxHG
Use the shared origin comparison from the trust policy instead of a
private HttpUrl extension. Both compare scheme, host, and effective
port, and an HttpUrl is always http(s), so the result is unchanged.
The response was never closed, so a redirect with a body kept its
connection out of the pool. Session no longer reads the response now
that the fetch doesn't follow redirects, so return the redirect and
close the response with use.
The timeouts can't change, and a lazily built client would also see
the cache. What an eager field would miss is the caching client
Session installs after constructing this repository.
@mbarta
mbarta force-pushed the security/verification-fetch-no-credential-redirect branch from 037e768 to b1bfaa5 Compare November 3, 2026 14:57
The verification fetch only read the first Location, so a chain like
/account -> /login -> https://idp.example/auth looked same-origin and the
visit failed with an error. That's the chain Turbo hands to native: the
browser's fetch follows the same-origin hops itself and only stops at the
cross-origin one.

The fetch now follows same-origin hops by hand, up to 20 like OkHttp, and
returns the first cross-origin Location without requesting it. An empty
or non-http Location ends the check. HttpRepository returns that location
directly, since Session never read anything else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mbarta mbarta changed the title Don't forward credentials when the verification fetch encounters a cross-origin redirect Stop the redirect check before the cross-origin destination Nov 3, 2026
@mbarta
mbarta merged commit f79fc42 into main Nov 3, 2026
1 check passed
@mbarta
mbarta deleted the security/verification-fetch-no-credential-redirect branch November 3, 2026 15:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

4 participants