console: one Keymail sign-in for a browser demo claim
A browser claim with a Keymail address asked for Keymail twice: the ordinary sign-in dropped auth_time and recorded no step-up, so the claim's select step sent the browser to Keymail again. The claim sign-in (next=/demo/claim exactly) now asks Keymail for a fresh gesture (prompt=login, max_age=300, sign-in callback) when Keymail advertises reauth, marks the server-set auth cookie, and records a step-up for the new session only if Keymail's auth_time is inside the step-up window (shared check with the step-up callback). Ordinary sign-ins never record one. Opus security review: approve; nits applied. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from demo-claim-one-signin into main. Co-Authored-By: claude <claude~paul@keymail.dev>
5 files changed,
+374
−20
internal/console/demo_claim_signin_test.go+303 −0internal/console/emailsignin.go+17 −4internal/console/keymail.go+8 −4internal/console/server.go+39 −9internal/console/stepup.go+7 −3
CI passed — run details
diff --git a/internal/console/demo_claim_signin_test.go b/internal/console/demo_claim_signin_test.go| new file mode 100644 |
| index 000000000..00ddb0de8 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_signin_test.go |
| @@ -0,0 +1,303 @@ |
| +package console |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func claimSigninFixture(t *testing.T) (*Server, *fakeKeymail, *claimBrowser) { |
| + t.Helper() |
| + seed, _, token := claimTestServer(t) |
| + fk := newFakeKeymail(t, "claimant@keymail.dev") |
| + cfg := seed.cfg |
| + cfg.Keymail = fk.srv.URL |
| + s, err := NewServer(cfg, seed.store) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.demoClaimTestEnabled = true |
| + return s, fk, newClaimBrowser(t, s, token) |
| +} |
| + |
| +func claimSigninStart(t *testing.T, b *claimBrowser) *httptest.ResponseRecorder { |
| + t.Helper() |
| + w := b.post("/demo/claim/prove", url.Values{"email": {"typed@" + b.s.km.Host()}}) |
| + if w.Code != 303 || w.Header().Get("Location") != "/auth/signin?next=%2Fdemo%2Fclaim" { |
| + t.Fatalf("claim discovery: %d %s", w.Code, w.Header().Get("Location")) |
| + } |
| + return b.request("GET", w.Header().Get("Location"), nil) |
| +} |
| + |
| +func claimSigninCallback(t *testing.T, b *claimBrowser, fk *fakeKeymail, start *httptest.ResponseRecorder, authTime time.Time, extraQuery string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + if start.Code != 303 { |
| + t.Fatalf("signin: %d %s", start.Code, start.Body) |
| + } |
| + u, err := url.Parse(start.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + q := u.Query() |
| + fk.mu.Lock() |
| + fk.challenge, fk.expectCode, fk.authTime = q.Get("code_challenge"), "claim-signin", authTime |
| + fk.mu.Unlock() |
| + w := b.request("GET", "/auth/callback?code=claim-signin&state="+url.QueryEscape(q.Get("state"))+extraQuery, nil) |
| + fk.mu.Lock() |
| + defer fk.mu.Unlock() |
| + if fk.stepUp { |
| + t.Error("sign-in exchange used the step-up redirect_uri") |
| + } |
| + return w |
| +} |
| + |
| +func TestDemoClaimSigninAuthorize(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + for _, next := range []string{"/demo/claim", "", "/auth/cli", "/demo/claim/", "/demo/claim?x=1", "/demo/claim#x", "//evil.example/demo/claim"} { |
| + t.Run(next, func(t *testing.T) { |
| + w := b.request("GET", "/auth/signin?next="+url.QueryEscape(next), nil) |
| + if w.Code != 303 { |
| + t.Fatalf("signin: %d", w.Code) |
| + } |
| + u, err := url.Parse(w.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := b.cookies[authCookie] |
| + parts := strings.Split(c.Value, ".") |
| + fresh := next == "/demo/claim" |
| + wantParts := 2 |
| + if fresh { |
| + wantParts = 3 |
| + } |
| + if len(parts) != wantParts || parts[0] == "" || parts[1] == "" || (fresh && parts[2] != "f") { |
| + t.Fatalf("auth cookie parts = %v", parts) |
| + } |
| + if !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.MaxAge != int(authFlowTTL.Seconds()) { |
| + t.Fatalf("auth cookie attributes: %+v", c) |
| + } |
| + want := url.Values{ |
| + "client_id": {s.cfg.Origin}, "redirect_uri": {s.cfg.Origin + "/auth/callback"}, |
| + "scope": {"identify send"}, "state": {parts[0]}, |
| + "code_challenge": {ChallengeS256(parts[1])}, "code_challenge_method": {"S256"}, |
| + } |
| + if fresh { |
| + want.Set("prompt", "login") |
| + want.Set("max_age", "300") |
| + } |
| + if !reflect.DeepEqual(u.Query(), want) || u.String() != fk.srv.URL+"/oauth/authorize?"+want.Encode() { |
| + t.Fatalf("authorize = %s, want %v", u, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSigninFreshness(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + age time.Duration |
| + zero, ordinary, wantFresh bool |
| + mapped, recordFailure bool |
| + }{ |
| + {name: "fresh", age: 9 * time.Second, wantFresh: true}, |
| + {name: "withinSkew", age: -stepUpSkew / 2, wantFresh: true}, |
| + {name: "missing", zero: true}, |
| + {name: "stale", age: StepUpWindow + time.Minute}, |
| + {name: "future", age: -stepUpSkew - time.Minute}, |
| + {name: "ordinaryWithFreshAuthTime", age: 9 * time.Second, ordinary: true}, |
| + {name: "mappedPerson", age: 9 * time.Second, mapped: true, wantFresh: true}, |
| + {name: "recordFailure", age: 9 * time.Second, recordFailure: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + person := "claimant@keymail.dev" |
| + if tc.mapped { |
| + person = "person@example.com" |
| + } |
| + other := &claimBrowser{t: t, s: s} |
| + other.login(person, MethodKeymail, false) |
| + if tc.mapped { |
| + if _, err := s.store.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, added_at) VALUES (?, ?, ?, ?)`, MethodKeymail, "claimant@keymail.dev", person, time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if tc.recordFailure { |
| + if _, err := s.store.db.Exec(`CREATE TRIGGER refuse_step_up BEFORE INSERT ON step_ups BEGIN SELECT RAISE(FAIL, 'test record failure'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + a := claimAccount(t, s, 501, person, RoleOwner) |
| + var start *httptest.ResponseRecorder |
| + if tc.ordinary { |
| + start = b.request("GET", "/auth/signin", nil) |
| + // A landing cookie and callback query cannot upgrade an ordinary ceremony. |
| + b.cookies[nextCookie] = &http.Cookie{Name: nextCookie, Value: "/demo/claim", Path: "/"} |
| + } else { |
| + start = claimSigninStart(t, b) |
| + } |
| + authTime := time.Now().Add(-tc.age).Truncate(time.Second) |
| + if tc.zero { |
| + authTime = time.Time{} |
| + } |
| + b.session = other.session |
| + w := claimSigninCallback(t, b, fk, start, authTime, "&next=%2Fdemo%2Fclaim") |
| + if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" || b.session == "" || b.session == other.session { |
| + t.Fatalf("callback: %d %s", w.Code, w.Body) |
| + } |
| + addr, method, ok := s.store.SessionInfo(b.session, time.Now()) |
| + if !ok || addr != person || method != MethodKeymail { |
| + t.Fatalf("session: %q %q %v", addr, method, ok) |
| + } |
| + wantRows := 0 |
| + if tc.wantFresh { |
| + wantRows = 1 |
| + } |
| + if got := claimBrowserCount(t, s, "step_ups"); got != wantRows { |
| + t.Fatalf("step-up rows = %d, want %d", got, wantRows) |
| + } |
| + if tc.wantFresh { |
| + var hash, address string |
| + var recordedAuth int64 |
| + if err := s.store.db.QueryRow(`SELECT session_hash,address,auth_time FROM step_ups`).Scan(&hash, &address, &recordedAuth); err != nil { |
| + t.Fatal(err) |
| + } |
| + if hash != hashToken(b.session) || address != addr || recordedAuth != authTime.Unix() { |
| + t.Fatalf("step-up row: %q %q %d", hash, address, recordedAuth) |
| + } |
| + if s.store.FreshStepUp(b.session, "typed@"+s.km.Host(), time.Now(), StepUpWindow) { |
| + t.Fatal("typed identity became fresh") |
| + } |
| + } |
| + if s.store.FreshStepUp(other.session, addr, time.Now(), StepUpWindow) { |
| + t.Fatal("another session became fresh") |
| + } |
| + if w = b.request("GET", "/demo/claim", nil); w.Code != 200 { |
| + t.Fatalf("claim page: %d", w.Code) |
| + } |
| + w = b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}) |
| + if w.Code != 303 { |
| + t.Fatalf("select: %d %s", w.Code, w.Body) |
| + } |
| + if tc.wantFresh { |
| + if w.Header().Get("Location") != "/demo/claim" || claimBrowserCount(t, s, "demo_claim_ops") != 1 || claimBrowserCount(t, s, "pending_actions") != 0 { |
| + t.Fatalf("select requested another gesture: %s", w.Header().Get("Location")) |
| + } |
| + } else { |
| + u, err := url.Parse(w.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasPrefix(u.String(), fk.srv.URL+"/oauth/authorize?") || u.Query().Get("redirect_uri") != s.cfg.Origin+"/auth/stepup/callback" || claimBrowserCount(t, s, "demo_claim_ops") != 0 || claimBrowserCount(t, s, "pending_actions") != 1 { |
| + t.Fatalf("select bypassed step-up: %s", u) |
| + } |
| + } |
| + fk.mu.Lock() |
| + exchanges := fk.exchanges |
| + fk.mu.Unlock() |
| + if exchanges != 1 { |
| + t.Fatalf("exchanges = %d, want 1", exchanges) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSigninMalformedCookie(t *testing.T) { |
| + for _, value := range []string{"state.verifier.x", "state.verifier.f.extra", ".verifier", "state.", ".verifier.f", "state..f", "state.verifier.", "state", "state.verifier.f."} { |
| + t.Run(value, func(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + b.cookies[authCookie] = &http.Cookie{Name: authCookie, Value: value, Path: "/"} |
| + w := b.request("GET", "/auth/callback?state=state&code=unused&next=%2Fdemo%2Fclaim", nil) |
| + if w.Code != 400 || !strings.Contains(w.Body.String(), "Sign-in flow mismatch") { |
| + t.Fatalf("callback: %d %s", w.Code, w.Body) |
| + } |
| + if b.session != "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatal("malformed cookie created proof") |
| + } |
| + fk.mu.Lock() |
| + exchanges := fk.exchanges |
| + fk.mu.Unlock() |
| + if exchanges != 0 { |
| + t.Fatal("malformed cookie reached exchange") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSigninMissingCookie(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + start := claimSigninStart(t, b) |
| + delete(b.cookies, authCookie) |
| + w := claimSigninCallback(t, b, fk, start, time.Now(), "&next=%2Fdemo%2Fclaim") |
| + if w.Code != 400 || !strings.Contains(w.Body.String(), "Sign-in flow expired") || b.session != "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatalf("callback without server cookie: %d", w.Code) |
| + } |
| + fk.mu.Lock() |
| + defer fk.mu.Unlock() |
| + if fk.exchanges != 0 { |
| + t.Fatal("callback without server cookie exchanged a code") |
| + } |
| +} |
| + |
| +func TestStepUpAuthTimeBoundaries(t *testing.T) { |
| + now := time.Unix(1800000000, 0) |
| + for _, tc := range []struct { |
| + name string |
| + authTime time.Time |
| + want bool |
| + }{ |
| + {"missing", time.Time{}, false}, |
| + {"now", now, true}, |
| + {"window", now.Add(-StepUpWindow), true}, |
| + {"outsideWindow", now.Add(-StepUpWindow - time.Nanosecond), false}, |
| + {"skew", now.Add(stepUpSkew), true}, |
| + {"outsideSkew", now.Add(stepUpSkew + time.Nanosecond), false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + if got := usableStepUpAuthTime(tc.authTime, now); got != tc.want { |
| + t.Fatalf("usableStepUpAuthTime = %v, want %v", got, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A Keymail that does not advertise re-authentication is never asked for a |
| +// fresh gesture: the claim gets the ordinary sign-in and records nothing. |
| +func TestDemoClaimSigninNoReauthFallsBack(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + fk.mu.Lock() |
| + fk.reauth = false |
| + fk.mu.Unlock() |
| + start := claimSigninStart(t, b) |
| + if parts := strings.Split(b.cookies[authCookie].Value, "."); len(parts) != 2 { |
| + t.Fatalf("auth cookie parts = %v, want the ordinary two", parts) |
| + } |
| + u, err := url.Parse(start.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if q := u.Query(); q.Has("prompt") || q.Has("max_age") { |
| + t.Fatalf("fresh gesture asked of a deployment without reauth: %s", u) |
| + } |
| + claimSigninCallback(t, b, fk, start, time.Now(), "") |
| + if b.session == "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatalf("session=%q step_ups=%d", b.session, claimBrowserCount(t, s, "step_ups")) |
| + } |
| +} |
| + |
| +// A later ordinary sign-in replaces the claim's marked cookie; the claim |
| +// ceremony's callback then fails the state check and records nothing. |
| +func TestDemoClaimSigninOverwrittenByOrdinary(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + start := claimSigninStart(t, b) |
| + if w := b.request("GET", "/auth/signin", nil); w.Code != 303 { |
| + t.Fatalf("ordinary signin: %d", w.Code) |
| + } |
| + w := claimSigninCallback(t, b, fk, start, time.Now(), "") |
| + if w.Code != 400 || !strings.Contains(w.Body.String(), "Sign-in flow mismatch") || b.session != "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatalf("stale claim callback: %d session=%q", w.Code, b.session) |
| + } |
| +} |
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go| index fd23b755d..28450fe32 100644 |
| --- a/internal/console/emailsignin.go |
| +++ b/internal/console/emailsignin.go |
| @@ -257,8 +257,17 @@ func safeNext(raw string) string { |
| // for minutes later. The current account is resolved (minted for a new user) |
| // before ordinary redirects. The exact claim return skips account landing; |
| // its explicit confirmation uses the claim person lock and account cap. |
| -func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, proved, keymailToken, method, next string) { |
| - person, ok := s.completeSigninSession(w, r, proved, keymailToken, method) |
| +// freshAuthTime carries the claim callback's validated Keymail gesture, if any. |
| +// Like an email sign-in's, the presence it records is not scoped to the claim: |
| +// for StepUpWindow it satisfies every step-up gated action of this new session, |
| +// exactly as a step-up just after sign-in would. A Keymail address mapped to |
| +// another person records against that person, the session's own address. |
| +func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, proved, keymailToken, method, next string, freshAuthTime ...time.Time) { |
| + var authTime time.Time |
| + if len(freshAuthTime) > 0 { |
| + authTime = freshAuthTime[0] |
| + } |
| + person, ok := s.completeSigninSession(w, r, proved, keymailToken, method, authTime) |
| if !ok { |
| return |
| } |
| @@ -280,7 +289,8 @@ func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, proved, ke |
| // completeSigninSession records identity and opens the browser session without |
| // choosing or creating an account. Landing policy belongs to the caller. |
| -func (s *Server) completeSigninSession(w http.ResponseWriter, r *http.Request, proved, keymailToken, method string) (string, bool) { |
| +// A zero authTime records no Keymail step-up; email proves presence at use. |
| +func (s *Server) completeSigninSession(w http.ResponseWriter, r *http.Request, proved, keymailToken, method string, authTime time.Time) (string, bool) { |
| fresh, err := s.store.PersonWouldBeNew(method, proved) |
| if err != nil { |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not record your account. Please try again.") |
| @@ -316,7 +326,10 @@ func (s *Server) completeSigninSession(w http.ResponseWriter, r *http.Request, p |
| s.setCookie(w, welcomeCookie, "1", 300) |
| } |
| if method == MethodEmail { |
| - if err := s.store.RecordStepUp(raw, person, now, now); err != nil { |
| + authTime = now |
| + } |
| + if !authTime.IsZero() { |
| + if err := s.store.RecordStepUp(raw, person, authTime, now); err != nil { |
| // Not fatal: the session is good, and the first sensitive action |
| // will ask for a fresh proof. |
| log.Printf("console: step-up record for %s: %v", person, err) |
diff --git a/internal/console/keymail.go b/internal/console/keymail.go| index 5aa2e17fc..860f8c65a 100644 |
| --- a/internal/console/keymail.go |
| +++ b/internal/console/keymail.go |
| @@ -146,8 +146,8 @@ func (k *Keymail) redirectURI() string { return k.origin + "/auth/callback" } |
| // stepUpRedirectURI is where a re-authentication lands. A separate route from |
| // the sign-in callback on purpose: a code minted for a step-up must not be |
| -// spendable as a sign-in, and a sign-in must never be able to satisfy a |
| -// step-up — the two flows never share a landing pad or a state cookie. |
| +// spendable as a sign-in. Claim sign-in can also request a fresh gesture, |
| +// but the two flows never share a landing pad or a state cookie. |
| func (k *Keymail) stepUpRedirectURI() string { return k.origin + "/auth/stepup/callback" } |
| // AuthorizeURL is where the browser goes to approve the console. |
| @@ -155,6 +155,11 @@ func (k *Keymail) AuthorizeURL(state, challenge string) string { |
| return k.authorizeURL(state, challenge, k.redirectURI(), 0) |
| } |
| +// FreshSigninURL requests a fresh gesture while keeping the sign-in callback. |
| +func (k *Keymail) FreshSigninURL(state, challenge string, window time.Duration) string { |
| + return k.authorizeURL(state, challenge, k.redirectURI(), window) |
| +} |
| + |
| // StepUpURL is the same ceremony with one extra demand: a FRESH authenticator |
| // gesture, however live the user's Keymail session is. `prompt=login` is the |
| // ask; `max_age` is the same ask spelled for an IdP that only understands |
| @@ -198,8 +203,7 @@ func (k *Keymail) SupportsStepUp(ctx context.Context) (bool, error) { |
| } |
| // Grant is one completed ceremony: who the user is, the console's access |
| -// token, and — for a step-up — when the authenticator gesture behind it |
| -// happened. |
| +// token, and when the authenticator gesture behind it happened, if proved. |
| type Grant struct { |
| Address string |
| Token string |
diff --git a/internal/console/server.go b/internal/console/server.go| index e794a6890..b4c3fdb82 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -3935,15 +3935,40 @@ func (s *Server) handleSignin(w http.ResponseWriter, r *http.Request) { |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the sign-in flow. Please try again.") |
| return |
| } |
| - s.setCookie(w, authCookie, state+"."+verifier, int(authFlowTTL.Seconds())) |
| + next := safeNext(r.URL.Query().Get("next")) |
| + auth := state + "." + verifier |
| + target := s.km.AuthorizeURL(state, ChallengeS256(verifier)) |
| + // The claim sign-in asks for a fresh gesture so the claim's own step-up |
| + // is satisfied by this one ceremony. Only a deployment that advertises |
| + // re-authentication is asked (as stepUpGate does); any other gets the |
| + // ordinary sign-in and the claim's step-up asks as before. The asking is |
| + // not the proof: handleCallback records presence only from a reported |
| + // auth_time inside the step-up window. |
| + if next == "/demo/claim" && s.claimSigninCanAskFresh(r) { |
| + auth += ".f" |
| + target = s.km.FreshSigninURL(state, ChallengeS256(verifier), StepUpWindow) |
| + } |
| + s.setCookie(w, authCookie, auth, int(authFlowTTL.Seconds())) |
| // Where to land afterwards. Only a safe local path is kept; a stale one |
| // from an earlier attempt must not leak into this one. |
| - if n := safeNext(r.URL.Query().Get("next")); n != "" { |
| - s.setCookie(w, nextCookie, n, int(authFlowTTL.Seconds())) |
| + if next != "" { |
| + s.setCookie(w, nextCookie, next, int(authFlowTTL.Seconds())) |
| } else { |
| s.clearCookie(w, nextCookie) |
| } |
| - http.Redirect(w, r, s.km.AuthorizeURL(state, ChallengeS256(verifier)), http.StatusSeeOther) |
| + http.Redirect(w, r, target, http.StatusSeeOther) |
| +} |
| + |
| +// claimSigninCanAskFresh is the capability check before a fresh-gesture |
| +// sign-in. An error or a "no" falls back to the ordinary sign-in. |
| +func (s *Server) claimSigninCanAskFresh(r *http.Request) bool { |
| + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) |
| + defer cancel() |
| + ok, err := s.km.SupportsStepUp(ctx) |
| + if err != nil { |
| + log.Printf("console: claim sign-in capability check: %v", err) |
| + } |
| + return err == nil && ok |
| } |
| // handleCallback finishes the ceremony: verify state, exchange the code |
| @@ -3962,9 +3987,10 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { |
| "This sign-in attempt is stale or was started elsewhere. Please start again.") |
| return |
| } |
| - state, verifier, ok := strings.Cut(c.Value, ".") |
| - if !ok || state == "" || |
| - subtle.ConstantTimeCompare([]byte(state), []byte(q.Get("state"))) != 1 { |
| + parts := strings.Split(c.Value, ".") |
| + fresh := len(parts) == 3 && parts[2] == "f" |
| + if (len(parts) != 2 && !fresh) || parts[0] == "" || parts[1] == "" || |
| + subtle.ConstantTimeCompare([]byte(parts[0]), []byte(q.Get("state"))) != 1 { |
| s.renderMessage(w, r, http.StatusBadRequest, "Sign-in flow mismatch", |
| "The sign-in response didn't match this browser's sign-in attempt. Please start again.") |
| return |
| @@ -3976,7 +4002,7 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| - address, token, err := s.km.Exchange(ctx, code, verifier) |
| + grant, err := s.km.ExchangeGrant(ctx, code, parts[1], false) |
| if err != nil { |
| log.Printf("console: token exchange: %v", err) |
| s.renderMessage(w, r, http.StatusBadGateway, "Sign-in failed", |
| @@ -3988,7 +4014,11 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) { |
| next = nc.Value |
| } |
| s.clearCookie(w, nextCookie) |
| - s.finishSignin(w, r, address, token, MethodKeymail, next) |
| + var authTime time.Time |
| + if fresh && usableStepUpAuthTime(grant.AuthTime, time.Now()) { |
| + authTime = grant.AuthTime |
| + } |
| + s.finishSignin(w, r, grant.Address, grant.Token, MethodKeymail, next, authTime) |
| } |
| // handleConfirm is the retired Apps-inbox confirmation link (spec 11): |
diff --git a/internal/console/stepup.go b/internal/console/stepup.go| index 8af605d43..9f589326f 100644 |
| --- a/internal/console/stepup.go |
| +++ b/internal/console/stepup.go |
| @@ -150,6 +150,11 @@ ON CONFLICT(session_hash) DO UPDATE SET |
| return err |
| } |
| +func usableStepUpAuthTime(authTime, now time.Time) bool { |
| + age := now.Sub(authTime) |
| + return !authTime.IsZero() && age >= -stepUpSkew && age <= StepUpWindow |
| +} |
| + |
| // FreshStepUp is the gate's one question. Both the session AND the address must |
| // match, and the gesture must be inside the window; anything else — no row, a |
| // stale row, a row belonging to another identity — is false. |
| @@ -414,9 +419,8 @@ func (s *Server) handleStepUpCallback(w http.ResponseWriter, r *http.Request) { |
| } |
| // Fail closed on a missing or stale auth_time. An IdP that did not report |
| // when the gesture happened has not proved that one did. |
| - age := now.Sub(grant.AuthTime) |
| - if grant.AuthTime.IsZero() || age > StepUpWindow || age < -stepUpSkew { |
| - log.Printf("console: step-up produced no usable auth_time (zero=%v age=%s)", grant.AuthTime.IsZero(), age) |
| + if !usableStepUpAuthTime(grant.AuthTime, now) { |
| + log.Printf("console: step-up produced no usable auth_time (zero=%v age=%s)", grant.AuthTime.IsZero(), now.Sub(grant.AuthTime)) |
| s.renderMessage(w, r, http.StatusForbidden, "Can't confirm it's you", stepUpUnavailable) |
| return |
| } |