Registry Mirror
Skip to content

Conversation

@lakhansamani

@lakhansamani lakhansamani commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Refs #406

Issue #406 is a docs question about magic links. Answering it turned up two bugs in the magic-link / email-verification flow. This PR fixes both. Once it ships, the magic-link "current limitations" section in authorizerdev/docs#105 can be removed.

Bug 1: the code from /verify_email could never be redeemed

Root cause. When a magic link starts from an /authorize request, the login UI passes the authorize state through magic_link_login. /verify_email then took the pre-generated code out of that state (using a raw strings.Split(…, "@@")) and appended &code= to the redirect. But the SetState(code, …) call that stores the code state was commented out, so the code was never stored. /oauth/token (GetAndRemoveState(code)) found nothing and returned invalid_grant every time.

Fix (internal/http_handlers/verify_email.go). The handler now does what login.go, session.go and signup.go already do:

  • It decodes the authorize state with codestate.HasCode / codestate.DecodeAuthorize instead of the raw split.
  • It passes the authorize nonce through as OIDCNonce to CreateAuthToken.
  • It stores codestate.EncodeCode(codestate.Code{Challenge, Session: authToken.FingerPrintHash, Nonce, RedirectURI, Resource, ClientID}) under the code. It uses the same store and TTL as the other code paths, so /oauth/token enforces PKCE, the client and redirect_uri bindings, and single use exactly as it does for login codes. If storing fails, the request fails; the handler no longer redirects with a dead code.

The authorize request is bound to the browser that started it before a magic link can issue a code. Every other way back from the login-UI detour authenticates the browser itself: a password, an existing session, or a social callback checked against the OAuth state cookie. A magic-link request is unauthenticated, and the link is clicked wherever the mailbox owner opens it, so the state alone does not identify the browser.

  • /authorize (code flow) generates a random value with crypto/rand.Text(). It stores that value's digest (crypto.HashSessionValue) in the authorize state as a new trailing field, codestate.Authorize.BrowserBinding. The field is appended, so older blobs still decode.
  • The value goes into an authorizer-authorize-binding cookie only when the request actually sends the browser to the login UI (/app or the signup page). A request answered from an existing session, a prompt=none renew, or a web_message response leaves any pending binding alone, so a second tab or a silent renew does not break a magic link still in flight.
  • Cookie attributes: HttpOnly, Secure follows AppCookieSecure, host-only, 15-minute max-age. It is always SameSite=Lax: clicking a link from a mail client is a top-level cross-site GET, and Strict would strip the cookie. A cookie unit test guards these attributes. Because the cookie is host-only, magic-link codes require /authorize and /verify_email to be reached on the same host (the --url host). On any other host the click still signs the user in, but no code is issued.
  • /verify_email issues a code only when the request carries a cookie whose digest matches, compared in constant time. Without a match, the click still signs the user in with the session cookie, but no code is issued. The cookie is cleared once a code is issued.
  • Authorize states written before this change carry no binding, so they never yield a code from /verify_email.
  • Login, session, signup and social completion paths do not change. The new cookie is just one more Set-Cookie on /authorize.

Other conditions for issuing a code:

  • No authorize context, no code. state must point at a stored authorize state that carries a code.
  • The MFA gate runs first. A withheld session returns before the authorize state is touched, and the state survives so the flow can resume after MFA.
  • Single use. The authorize state is consumed with GetAndRemoveState. The code is single-use at /oauth/token.
  • The code only goes to the redirect_uri /authorize recorded (RFC 6749 §4.1.2). If the targets differ, or the state recorded no redirect_uri, the user gets the session but no code.
  • The redirect is checked against the authorize request's client, but only for the initiating browser. When the link's authorize state carries a client_id and the request presents the matching binding cookie, the redirect is validated against that client, the same one /authorize checked it against. In every other case it is validated against the deployment's own client, as before. So --redirect-uris exact matching still applies to everyone who did not run that /authorize request.
  • state, nonce and code are query-escaped in the redirect.

Bug 2: magic links failed when --redirect-uris was set

Root cause. utils.GetEmailVerificationURL concatenated redirect_uri raw into the link. On top of that, magic_link_login appended ?roles=…&state=…&scope=… to the redirect URI itself. So /verify_email received redirect_uri=<uri>?roles=…, which never exactly matched a registered URI, and returned 400 "invalid redirect uri". A redirect URI with its own query string was also cut short.

Fix.

  • GetEmailVerificationURL(token, hostname, redirectURI, extra url.Values) now builds the link with net/url, so every value is escaped.
  • magic_link_login no longer changes the redirect URI. It stores and signs the URI exactly as the caller gave it, and sends roles, state and scope as top-level link parameters. That is where VerifyEmailHandler already reads them. Links already sent by an older build still parse the same way they did before.
  • The other callers (signup verification, resend, update email, admin update user) pass nil and get the escaping. GetInviteVerificationURL gets the same escaping.
  • IsValidRedirectURI in magic_link_login and checkClientRedirectURI in /verify_email are both still enforced.

Tests

internal/integration_tests/magic_link_authorize_flow_test.go drives the real flow: /authorize (PKCE S256, no session) → magic_link_login → the link from the actually sent email (a test-only recorder wraps the email provider in test_helper.go) → /verify_email → /oauth/token.

Test Result before Result with this PR
TestMagicLinkAuthorizeCodeIsRedeemable (same browser: verifier → 200; replay → invalid_grant; wrong or missing verifier refused) FAIL on main (invalid_grant) PASS
TestMagicLinkAuthorizeCodeRequiresInitiatingBrowser (link clicked without the binding cookie, or with another request's binding → no code, and neither the redirect code nor the login-UI code can be redeemed; the initiating browser gets a code redeemable once) FAIL on this PR's first revision PASS
TestMagicLinkWithExactRedirectURIs (plain URI; URI with its own query string) FAIL on main (400 invalid redirect uri) PASS
TestMagicLinkRedirectValidatedAgainstAuthorizeClient (third-party client under --redirect-uris, initiating browser) FAIL (400) PASS
TestMagicLinkThirdPartyRedirectNeedsBrowserBinding (another client's state with no binding cookie, or a non-matching one → 400 "invalid redirect uri"; matching cookie → 307) FAIL on this PR's second revision (307 to the other client's URI) PASS
TestAuthorizeBindingCookieOnlyOnLoginDetour (detour sets the cookie; prompt=none and session-answered /authorize do not) FAIL on this PR's second revision PASS
TestMagicLinkAuthorizeCodeOnlyToAuthorizeRedirect FAIL on main PASS
TestVerifyEmailLegacyAuthorizeStateIssuesNoCode (a binding-less blob gives no code) n/a PASS
TestMagicLinkWithoutAuthorizeContextIssuesNoCode, TestMagicLinkAuthorizeCodeWithheldByMFA (guards) pass PASS

TestVerifyEmailStillDeliversCodeForAuthorizeFlow now seeds the authorize state with a binding digest and presents the matching cookie. There are also unit tests for GetEmailVerificationURL / GetInviteVerificationURL, the codestate round trip with the new field (including a legacy blob), and the binding cookie's shape.

Verification, run locally on this branch (current with origin/main): go build ./... and go vet ./... clean; make test (SQLite) exit 0, 46 packages ok, no failures; make lint 0 issues; make smoke PASS.

No storage-layer changes.

…e exact redirect URIs

/verify_email put the /authorize code in the redirect but never stored its
code state (the SetState was commented out), so /oauth/token always returned
invalid_grant. It now decodes the authorize state with codestate and persists
codestate.EncodeCode bound to the PKCE challenge, session fingerprint, nonce,
redirect_uri, resource and client id, exactly like login/session/signup. The
authorize state is consumed atomically, only after the MFA gate passes, and a
code is only issued to the redirect_uri /authorize recorded.

GetEmailVerificationURL concatenated redirect_uri raw and magic_link_login
appended roles/state/scope to the redirect URI itself, so /verify_email saw a
redirect_uri that never exactly matched --redirect-uris. The link is now built
with net/url, and roles/state/scope are top-level link params (where the
handler already reads them). Invite links get the same escaping.

Refs #406
… before issuing a code

/authorize now sets an HttpOnly, SameSite=Lax, host-only binding cookie and
stores its digest in the authorize state (codestate.Authorize.BrowserBinding,
appended field). /verify_email issues a code only when the clicking browser
presents the matching cookie; otherwise it still establishes the session but
issues no code. States without a binding (older builds) never yield a code.

Also: refuse a code when the authorize state recorded no redirect_uri,
validate the redirect against the authorize request's client_id when present,
and correct a comment about signup verification threading state.

Refs #406
…; set binding cookie only on login detour

/verify_email validated the redirect against the client_id of whatever
authorize state the link named. That state is caller-supplied, so it now
does so only when the request presents the matching browser-binding cookie;
otherwise it validates against the deployment's own client as before.

/authorize set the binding cookie on every code-flow request, so a
session-answered request or prompt=none renew overwrote a pending
magic-link binding. The cookie is now set only when handleResponse sends the
browser to the login UI.

Refs #406
@lakhansamani
lakhansamani force-pushed the fix/magic-link-code-and-redirect branch from 60dfbf1 to 9eb4501 Compare November 26, 2026 11:14
@lakhansamani
lakhansamani merged commit ce651b8 into main Nov 26, 2026
4 checks passed
@lakhansamani
lakhansamani deleted the fix/magic-link-code-and-redirect branch November 26, 2026 11:24
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