console: reuse fresh claim sign-in for step-up authentication
Request a fresh Keymail gesture only for the exact demo claim return, and retain verified auth_time for the newly created session. Keep ordinary sign-in unchanged and share the existing timestamp check. Reject malformed auth cookies. Cover the claim path, stale proof, session and address binding, and record-write failure through the production router. Targeted console tests: 269 pass, one sandbox-only skip. Console vet and formatting checks pass.
5 files changed,
+314
−20
internal/console/demo_claim_signin_test.go+265 −0internal/console/emailsignin.go+13 −4internal/console/keymail.go+8 −4internal/console/server.go+21 −9internal/console/stepup.go+7 −3
CI cancelled — superseded by a newer push — run details
Intent
Attributed to this commit: 4.69 g CO₂e (445,944 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-claim-one-signin, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/demo_claim_signin_test.go b/internal/console/demo_claim_signin_test.go| new file mode 100644 |
| index 000000000..46bdd29ce |
| --- /dev/null |
| +++ b/internal/console/demo_claim_signin_test.go |
| @@ -0,0 +1,265 @@ |
| +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) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go| index fd23b755d..2908e67f9 100644 |
| --- a/internal/console/emailsignin.go |
| +++ b/internal/console/emailsignin.go |
| @@ -257,8 +257,13 @@ 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. |
| +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 +285,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 +322,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..e135588b3 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -3935,15 +3935,22 @@ 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)) |
| + if next == "/demo/claim" { |
| + 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) |
| } |
| // handleCallback finishes the ceremony: verify state, exchange the code |
| @@ -3962,9 +3969,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 +3984,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 +3996,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 |
| } |