Conversation
…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
force-pushed
the
fix/magic-link-code-and-redirect
branch
from
November 26, 2026 11:14
60dfbf1 to
9eb4501
Compare
This was referenced Nov 26, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
codefrom/verify_emailcould never be redeemedRoot cause. When a magic link starts from an
/authorizerequest, the login UI passes the authorizestatethroughmagic_link_login./verify_emailthen took the pre-generated code out of that state (using a rawstrings.Split(…, "@@")) and appended&code=to the redirect. But theSetState(code, …)call that stores the code state was commented out, so the code was never stored./oauth/token(GetAndRemoveState(code)) found nothing and returnedinvalid_grantevery time.Fix (
internal/http_handlers/verify_email.go). The handler now does whatlogin.go,session.goandsignup.goalready do:codestate.HasCode/codestate.DecodeAuthorizeinstead of the raw split.noncethrough asOIDCNoncetoCreateAuthToken.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/tokenenforces 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
statealone does not identify the browser./authorize(code flow) generates a random value withcrypto/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.authorizer-authorize-bindingcookie only when the request actually sends the browser to the login UI (/appor the signup page). A request answered from an existing session, aprompt=nonerenew, 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.SecurefollowsAppCookieSecure, 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/authorizeand/verify_emailto be reached on the same host (the--urlhost). On any other host the click still signs the user in, but no code is issued./verify_emailissues 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./verify_email.Set-Cookieon/authorize.Other conditions for issuing a code:
statemust point at a stored authorize state that carries a code.GetAndRemoveState. The code is single-use at/oauth/token.redirect_uri/authorizerecorded (RFC 6749 §4.1.2). If the targets differ, or the state recorded no redirect_uri, the user gets the session but no code.client_idand the request presents the matching binding cookie, the redirect is validated against that client, the same one/authorizechecked it against. In every other case it is validated against the deployment's own client, as before. So--redirect-urisexact matching still applies to everyone who did not run that/authorizerequest.state,nonceandcodeare query-escaped in the redirect.Bug 2: magic links failed when
--redirect-uriswas setRoot cause.
utils.GetEmailVerificationURLconcatenatedredirect_uriraw into the link. On top of that,magic_link_loginappended?roles=…&state=…&scope=…to the redirect URI itself. So/verify_emailreceivedredirect_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 withnet/url, so every value is escaped.magic_link_loginno longer changes the redirect URI. It stores and signs the URI exactly as the caller gave it, and sendsroles,stateandscopeas top-level link parameters. That is whereVerifyEmailHandleralready reads them. Links already sent by an older build still parse the same way they did before.niland get the escaping.GetInviteVerificationURLgets the same escaping.IsValidRedirectURIinmagic_link_loginandcheckClientRedirectURIin/verify_emailare both still enforced.Tests
internal/integration_tests/magic_link_authorize_flow_test.godrives 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 intest_helper.go) →/verify_email→/oauth/token.TestMagicLinkAuthorizeCodeIsRedeemable(same browser: verifier → 200; replay →invalid_grant; wrong or missing verifier refused)main(invalid_grant)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)TestMagicLinkWithExactRedirectURIs(plain URI; URI with its own query string)main(400 invalid redirect uri)TestMagicLinkRedirectValidatedAgainstAuthorizeClient(third-party client under--redirect-uris, initiating browser)TestMagicLinkThirdPartyRedirectNeedsBrowserBinding(another client's state with no binding cookie, or a non-matching one → 400 "invalid redirect uri"; matching cookie → 307)TestAuthorizeBindingCookieOnlyOnLoginDetour(detour sets the cookie;prompt=noneand session-answered/authorizedo not)TestMagicLinkAuthorizeCodeOnlyToAuthorizeRedirectmainTestVerifyEmailLegacyAuthorizeStateIssuesNoCode(a binding-less blob gives no code)TestMagicLinkWithoutAuthorizeContextIssuesNoCode,TestMagicLinkAuthorizeCodeWithheldByMFA(guards)TestVerifyEmailStillDeliversCodeForAuthorizeFlownow seeds the authorize state with a binding digest and presents the matching cookie. There are also unit tests forGetEmailVerificationURL/GetInviteVerificationURL, thecodestateround 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 ./...andgo vet ./...clean;make test(SQLite) exit 0, 46 packages ok, no failures;make lint0 issues;make smokePASS.No storage-layer changes.