fix: resume confirmed demo claims after step-up
12 files changed,
+608
−8
internal/console/demo_claim_browser_test.go+1 −1internal/console/demo_claim_copy.go+3 −0internal/console/demo_claim_page.go+11 −1internal/console/demo_claim_page_test.go+17 −1internal/console/demo_claim_resume_browser_test.go+71 −0internal/console/demo_claim_resume_test.go+277 −0internal/console/demo_claim_selection.go+110 −0internal/console/server.go+1 −0internal/console/static/demo_claim.js+16 −1internal/console/stepup.go+5 −1internal/console/templates/demo_claim.html+4 −3internal/console/testdata/demo_claim_resume_browser.mjs+92 −0
CI passed — run details
Intent
Attributed to this commit: 43.7 g CO₂e (5,606,526 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-claim-page-fix, 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_browser_test.go b/internal/console/demo_claim_browser_test.go| index 10fd67854..6c923af4f 100644 |
| --- a/internal/console/demo_claim_browser_test.go |
| +++ b/internal/console/demo_claim_browser_test.go |
| @@ -155,7 +155,7 @@ func TestDemoClaimBrowserRecovery(t *testing.T) { |
| t.Fatalf("signin minted account: %v %v", as, err) |
| } |
| w = b.request("GET", "/demo/claim", nil) |
| - if w.Code != 200 || b.cookie != cookie || !strings.Contains(w.Body.String(), "actual@example.com") { |
| + if w.Code != 200 || b.cookie != cookie || !strings.Contains(w.Body.String(), "actual@example.com") || strings.Contains(w.Body.String(), "data-auto-submit") { |
| t.Fatal("intent lost") |
| } |
| }) |
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go| index 2ea655557..dcab12abe 100644 |
| --- a/internal/console/demo_claim_copy.go |
| +++ b/internal/console/demo_claim_copy.go |
| @@ -87,3 +87,6 @@ const ( |
| // CLAIM-ACCOUNT-CAP: plan cap refusal during browser reservation. |
| demoClaimAccountCap = "This account has reached its plan limit. Choose another account or free up capacity." |
| ) |
| + |
| +// CLAIM-RESUME-SUBMITTING: the previously confirmed selection is being posted. |
| +const demoClaimResuming = "Keeping your demo in the account you chose…" |
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go| index fe08da45c..519efc1aa 100644 |
| --- a/internal/console/demo_claim_page.go |
| +++ b/internal/console/demo_claim_page.go |
| @@ -33,6 +33,8 @@ var demoClaimStyleHash = func() string { |
| }() |
| type demoClaimPageData struct { |
| + AutoSubmit bool |
| + SelectedAccount string |
| Chrome page |
| Copy map[string]string |
| Nonce, CSRF, Address, State, AccountID, App, URL, Error string |
| @@ -115,6 +117,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) { |
| } |
| address, session, _ := s.session(r) |
| p := demoClaimPageData{Chrome: s.basePage(r), Copy: demoClaimBrowserCopy(), Nonce: demoClaimNonce(cookie, session), CSRF: session, Address: address, State: "missing"} |
| + selection, resume := s.takeDemoClaimSelection(w, r, session, p.Nonce) |
| s.chrome(&p.Chrome) |
| p.Copy["next"] = fmt.Sprintf(demoClaimCLINext, s.cfg.Origin) |
| hash, err := s.store.demoClaimBrowserHash(r.Context(), cookie, time.Now()) |
| @@ -157,9 +160,16 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) { |
| } |
| for _, a := range accounts { |
| if demoClaimCanCreate(a) { |
| + if resume && !selection.Create && selection.Account == a.Sqid { |
| + p.AutoSubmit = p.CanClaim |
| + p.SelectedAccount = a.Sqid |
| + } |
| p.Accounts = append(p.Accounts, a) |
| } |
| } |
| + if resume && selection.Create && len(accounts) == 0 { |
| + p.AutoSubmit = p.CanClaim |
| + } |
| if len(accounts) > 0 && len(p.Accounts) == 0 { |
| p.State, p.CanClaim = "no_accounts", false |
| } |
| @@ -489,7 +499,7 @@ func (s *Server) demoClaimSessionIdentity(raw, person string) (string, string, b |
| } |
| func demoClaimBrowserCopy() map[string]string { |
| - return map[string]string{"back": demoClaimBack, "noAccounts": demoClaimNoEligibleAccount, "title": demoClaimPageTitle, "missing": demoClaimIntentExpired, "failed": demoClaimExchangeFailed, "noscript": demoClaimNeedsScript, "identity": demoClaimIdentityLabel, "email": demoClaimEmailLabel, "continue": demoClaimEmailContinue, "code": demoClaimCodeLabel, "prove": demoClaimCodeConfirm, "sent": demoClaimEmailSent, "signin": demoClaimSignin, "account": demoClaimAccountLabel, "choose": demoClaimChooseAccount, "new": demoClaimNewAccount, "confirm": demoClaimConfirm, "working": demoClaimWorking, "reload": demoClaimReload, "complete": demoClaimComplete, "app": demoClaimAppLabel, "url": demoClaimURLLabel, "aborted": demoClaimAborted, "disabled": demoClaimUnavailable} |
| + return map[string]string{"resuming": demoClaimResuming, "back": demoClaimBack, "noAccounts": demoClaimNoEligibleAccount, "title": demoClaimPageTitle, "missing": demoClaimIntentExpired, "failed": demoClaimExchangeFailed, "noscript": demoClaimNeedsScript, "identity": demoClaimIdentityLabel, "email": demoClaimEmailLabel, "continue": demoClaimEmailContinue, "code": demoClaimCodeLabel, "prove": demoClaimCodeConfirm, "sent": demoClaimEmailSent, "signin": demoClaimSignin, "account": demoClaimAccountLabel, "choose": demoClaimChooseAccount, "new": demoClaimNewAccount, "confirm": demoClaimConfirm, "working": demoClaimWorking, "reload": demoClaimReload, "complete": demoClaimComplete, "app": demoClaimAppLabel, "url": demoClaimURLLabel, "aborted": demoClaimAborted, "disabled": demoClaimUnavailable} |
| } |
| func demoClaimCanCreate(a Account) bool { return a.Role == RoleOwner || a.Role == RoleMember } |
diff --git a/internal/console/demo_claim_page_test.go b/internal/console/demo_claim_page_test.go| index 31d7bb194..12d7cfb47 100644 |
| --- a/internal/console/demo_claim_page_test.go |
| +++ b/internal/console/demo_claim_page_test.go |
| @@ -21,6 +21,7 @@ type claimBrowser struct { |
| t *testing.T |
| s *Server |
| cookie, session, nonce string |
| + cookies map[string]*http.Cookie |
| } |
| func (b *claimBrowser) request(method, path string, form url.Values) *httptest.ResponseRecorder { |
| @@ -30,7 +31,12 @@ func (b *claimBrowser) request(method, path string, form url.Values) *httptest.R |
| if method == "POST" { |
| r.Header.Set("Origin", b.s.cfg.Origin) |
| } |
| - if b.cookie != "" { |
| + for _, c := range b.cookies { |
| + if strings.HasPrefix(r.URL.Path, c.Path) { |
| + r.AddCookie(c) |
| + } |
| + } |
| + if b.cookie != "" && strings.HasPrefix(r.URL.Path, "/demo/claim") { |
| r.AddCookie(&http.Cookie{Name: browserClaimCookieName, Value: b.cookie}) |
| } |
| if b.session != "" { |
| @@ -38,7 +44,17 @@ func (b *claimBrowser) request(method, path string, form url.Values) *httptest.R |
| } |
| w := httptest.NewRecorder() |
| b.s.mux.ServeHTTP(w, r) |
| + if b.cookies == nil { |
| + b.cookies = make(map[string]*http.Cookie) |
| + } |
| for _, c := range w.Result().Cookies() { |
| + if c.Name != browserClaimCookieName && c.Name != sessionCookie { |
| + if c.MaxAge < 0 { |
| + delete(b.cookies, c.Name) |
| + } else { |
| + b.cookies[c.Name] = c |
| + } |
| + } |
| if c.Name == browserClaimCookieName { |
| b.cookie = c.Value |
| } |
diff --git a/internal/console/demo_claim_resume_browser_test.go b/internal/console/demo_claim_resume_browser_test.go| new file mode 100644 |
| index 000000000..6dd6f44fc |
| --- /dev/null |
| +++ b/internal/console/demo_claim_resume_browser_test.go |
| @@ -0,0 +1,71 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDemoClaimSelectStepUpHeadless(t *testing.T) { |
| + chromium, err := exec.LookPath("chromium") |
| + if err != nil { |
| + t.Skip("no installed headless Chromium") |
| + } |
| + node, err := exec.LookPath("node") |
| + if err != nil { |
| + t.Skip("no installed node") |
| + } |
| + s, _, token := claimTestServer(t) |
| + fk := claimStepUpStub(t, s) |
| + s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic) |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if strings.HasPrefix(r.URL.Path, "/auth/") { |
| + if _, err := r.Cookie(browserClaimCookieName); err == nil { |
| + t.Error("claim cookie reached auth path") |
| + } |
| + } |
| + if r.URL.Query().Get("csp") == "before" { |
| + rec := httptest.NewRecorder() |
| + s.mux.ServeHTTP(rec, r) |
| + for k, v := range rec.Header() { |
| + w.Header()[k] = v |
| + } |
| + w.Header().Set("Content-Security-Policy", strings.ReplaceAll(w.Header().Get("Content-Security-Policy"), "form-action 'self' "+fk.srv.URL, "form-action 'self'")) |
| + w.WriteHeader(rec.Code) |
| + w.Write(rec.Body.Bytes()) |
| + return |
| + } |
| + s.mux.ServeHTTP(w, r) |
| + })) |
| + defer ts.Close() |
| + s.cfg.Origin = ts.URL |
| + s.km.origin = ts.URL |
| + b := newClaimBrowser(t, s, token) |
| + b.login("claimant@example.com", MethodKeymail, false) |
| + claimAccount(t, s, 501, "claimant@example.com", RoleOwner) |
| + a := claimAccount(t, s, 502, "claimant@example.com", RoleOwner) |
| + ctx, cancel := context.WithTimeout(t.Context(), 45*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, node, "testdata/demo_claim_resume_browser.mjs", chromium, t.TempDir(), ts.URL, b.session, b.cookie, a.Sqid, os.Getenv("DCPF_SCREENSHOTS")) |
| + output, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("headless: %v %s", err, output) |
| + } |
| + t.Log(strings.TrimSpace(string(output))) |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 1 { |
| + t.Fatal("JS did not reserve exactly one operation") |
| + } |
| + hash, err := s.store.demoClaimBrowserHash(t.Context(), b.cookie, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + op, err := s.store.demoClaimOpForFlow(t.Context(), hash) |
| + if err != nil || op.Target.Sqid != a.Sqid { |
| + t.Fatalf("wrong browser destination: %+v %v", op, err) |
| + } |
| +} |
diff --git a/internal/console/demo_claim_resume_test.go b/internal/console/demo_claim_resume_test.go| new file mode 100644 |
| index 000000000..ed0a1f9de |
| --- /dev/null |
| +++ b/internal/console/demo_claim_resume_test.go |
| @@ -0,0 +1,277 @@ |
| +package console |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The stub drives the browser redirect as well as the server-side exchange. |
| +func claimStepUpStub(t *testing.T, s *Server) *fakeKeymail { |
| + t.Helper() |
| + fk := newFakeKeymail(t, "claimant@example.com") |
| + original := fk.srv.Config.Handler |
| + fk.srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/oauth/authorize" { |
| + original.ServeHTTP(w, r) |
| + return |
| + } |
| + q := r.URL.Query() |
| + fk.mu.Lock() |
| + fk.challenge, fk.expectCode, fk.authTime = q.Get("code_challenge"), "claim-stepup", time.Now() |
| + fk.mu.Unlock() |
| + http.Redirect(w, r, q.Get("redirect_uri")+"?code=claim-stepup&state="+url.QueryEscape(q.Get("state")), 303) |
| + }) |
| + s.km = NewKeymail(fk.srv.URL, s.cfg.Origin) |
| + s.km.SetSigningKey(testSigningKey(t)) |
| + s.registerRoute("GET /auth/stepup/callback", s.handleStepUpCallback) |
| + s.registerRoute("POST /auth/email/stepup/code", s.handleStepUpEmailCode) |
| + return fk |
| +} |
| + |
| +func claimFinishKeymail(t *testing.T, b *claimBrowser, location string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + response, err := c.Get(location) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + response.Body.Close() |
| + if response.StatusCode != 303 { |
| + t.Fatalf("stub: %d", response.StatusCode) |
| + } |
| + callback, err := url.Parse(response.Header.Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.request("GET", callback.RequestURI(), nil) |
| +} |
| + |
| +func TestDemoClaimSelectStepUpRoundTrip(t *testing.T) { |
| + for _, method := range []string{MethodKeymail, MethodEmail} { |
| + t.Run(method, func(t *testing.T) { |
| + s, m, token := claimTestServer(t) |
| + fk := claimStepUpStub(t, s) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("claimant@example.com", method, false) |
| + claimAccount(t, s, 501, "claimant@example.com", RoleOwner) |
| + a := claimAccount(t, s, 502, "claimant@example.com", RoleOwner) |
| + page := b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(page.Header().Get("Content-Security-Policy"), "form-action 'self' "+fk.srv.URL+";") { |
| + t.Error("rendered page CSP does not allow the configured step-up origin") |
| + } |
| + w := b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}) |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 || claimBrowserCount(t, s, "pending_actions") != 1 { |
| + t.Fatal("select did not stop at step-up") |
| + } |
| + if method == MethodKeymail { |
| + if w.Code != 303 { |
| + t.Fatalf("step-up: %d %s", w.Code, w.Body) |
| + } |
| + w = claimFinishKeymail(t, b, w.Header().Get("Location")) |
| + } else { |
| + code, _ := claimMail(t, s, m) |
| + w = b.request("POST", "/auth/email/stepup/code", url.Values{"code": {code}}) |
| + } |
| + if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" { |
| + t.Fatalf("resume: %d %s", w.Code, w.Body) |
| + } |
| + if claimBrowserCount(t, s, "pending_actions") != 0 || claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("resume must consume stash without claiming") |
| + } |
| + w = b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(w.Body.String(), `data-auto-submit`) || !strings.Contains(w.Body.String(), `value="`+a.Sqid+`" selected`) { |
| + t.Fatalf("selected account was not resumed: %s", w.Body) |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("GET claimed") |
| + } |
| + if w = b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}); w.Code != 303 { |
| + t.Fatalf("auto POST: %d %s", w.Code, w.Body) |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 1 { |
| + t.Fatal("want exactly one reservation") |
| + } |
| + hash, err := s.store.demoClaimBrowserHash(t.Context(), b.cookie, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + op, err := s.store.demoClaimOpForFlow(t.Context(), hash) |
| + if err != nil || op.Target.Sqid != a.Sqid { |
| + t.Fatalf("wrong destination: %+v %v", op, err) |
| + } |
| + w = b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(w.Body.String(), demoClaimWorking) { |
| + t.Fatal("no claiming state") |
| + } |
| + b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}) |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 1 { |
| + t.Fatal("duplicate reservation") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func claimResumeSelection(t *testing.T, b *claimBrowser, form url.Values) *http.Cookie { |
| + t.Helper() |
| + form.Set("nonce", b.nonce) |
| + r := httptest.NewRequest("GET", "/auth/stepup/callback", nil) |
| + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: b.session}) |
| + w := httptest.NewRecorder() |
| + b.s.resume(w, r, &pendingAction{Method: "POST", Path: "/demo/claim/select", Form: form.Encode()}) |
| + for _, c := range w.Result().Cookies() { |
| + if c.Path == "/demo/claim" { |
| + if !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteLaxMode || c.MaxAge != 120 || strings.Contains(c.Value, b.session) { |
| + t.Fatalf("unsafe selection cookie: %+v", c) |
| + } |
| + b.cookies[c.Name] = c |
| + return c |
| + } |
| + } |
| + t.Fatal("resume did not set a selection cookie") |
| + return nil |
| +} |
| + |
| +func TestDemoClaimResumedSelectionGates(t *testing.T) { |
| + for _, which := range []string{"absent", "forged", "otherSession", "expired", "otherFlow", "removedAccount", "demotedAccount", "newMembership", "valid", "create", "csrf", "nonce", "staleAuth"} { |
| + t.Run(which, func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + fk := claimStepUpStub(t, s) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("claimant@example.com", MethodKeymail, true) |
| + form := url.Values{"create": {"1"}} |
| + if which != "create" && which != "newMembership" { |
| + a := claimAccount(t, s, 501, "claimant@example.com", RoleOwner) |
| + form = url.Values{"accountId": {a.Sqid}} |
| + } |
| + b.request("GET", "/demo/claim", nil) |
| + if which != "absent" { |
| + c := claimResumeSelection(t, b, form) |
| + switch which { |
| + case "forged": |
| + c.Value += "tampered" |
| + case "otherSession": |
| + b.login("claimant@example.com", MethodKeymail, true) |
| + b.cookies[c.Name] = c |
| + case "expired": |
| + c.Value = s.demoClaimSelectionValue(b.session, form, time.Now().Add(-3*time.Minute)) |
| + case "otherFlow": |
| + other := newClaimBrowser(t, s, token) |
| + b.cookie = other.cookie |
| + case "demotedAccount": |
| + if _, err := s.store.db.Exec(`UPDATE memberships SET role=? WHERE account_id=501`, "viewer"); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "newMembership": |
| + claimAccount(t, s, 502, "claimant@example.com", RoleOwner) |
| + case "removedAccount": |
| + // Preserve a different choice so the stale account cannot become create=1. |
| + claimAccount(t, s, 502, "claimant@example.com", RoleOwner) |
| + if _, err := s.store.db.Exec(`DELETE FROM memberships WHERE account_id=501`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + w := b.request("GET", "/demo/claim", nil) |
| + auto := strings.Contains(w.Body.String(), "data-auto-submit") |
| + want := which == "valid" || which == "create" || which == "csrf" || which == "nonce" || which == "staleAuth" |
| + if auto != want { |
| + t.Fatalf("auto-submit=%v want %v", auto, want) |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("GET reserved") |
| + } |
| + var proved int |
| + if err := s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_flows WHERE person!=''`).Scan(&proved); err != nil || proved != 0 { |
| + t.Fatal("GET proved identity", err) |
| + } |
| + if strings.Contains(b.request("GET", "/demo/claim", nil).Body.String(), "data-auto-submit") { |
| + t.Fatal("reload replayed selection after cookie clear") |
| + } |
| + switch which { |
| + case "create": |
| + if w := b.post("/demo/claim/select", form); w.Code != 303 || claimBrowserCount(t, s, "demo_claim_ops") != 1 { |
| + t.Fatalf("resumed create: %d %s", w.Code, w.Body) |
| + } |
| + case "csrf", "nonce": |
| + form.Set("nonce", b.nonce) |
| + form.Set("csrf", b.session) |
| + form.Del(which) |
| + if w := b.request("POST", "/demo/claim/select", form); w.Code != 403 { |
| + t.Fatalf("missing %s: %d", which, w.Code) |
| + } |
| + case "removedAccount", "demotedAccount", "newMembership": |
| + if w := b.post("/demo/claim/select", form); w.Code != 404 { |
| + t.Fatalf("removed account: %d", w.Code) |
| + } |
| + case "staleAuth": |
| + if err := s.store.ClearStepUp(b.session); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := b.post("/demo/claim/select", form) |
| + if w.Code != 303 || !strings.HasPrefix(w.Header().Get("Location"), fk.srv.URL) { |
| + t.Fatalf("stale auto POST skipped step-up: %d", w.Code) |
| + } |
| + if strings.Contains(b.request("GET", "/demo/claim", nil).Body.String(), "data-auto-submit") { |
| + t.Fatal("automatic retry loop") |
| + } |
| + if claimBrowserCount(t, s, "pending_actions") != 1 { |
| + t.Fatal("wrong repeated step-up count") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimResumedSelectionCopiedCookieReplay(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("claimant@example.com", MethodKeymail, true) |
| + a := claimAccount(t, s, 501, "claimant@example.com", RoleOwner) |
| + c := claimResumeSelection(t, b, url.Values{"accountId": {a.Sqid}}) |
| + if !strings.Contains(b.request("GET", "/demo/claim", nil).Body.String(), "data-auto-submit") { |
| + t.Fatal("first use did not resume") |
| + } |
| + b.cookies[c.Name] = c |
| + if strings.Contains(b.request("GET", "/demo/claim", nil).Body.String(), "data-auto-submit") { |
| + t.Fatal("copied cookie replayed after clear") |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("GET reserved") |
| + } |
| +} |
| + |
| +func TestDemoClaimResumedSelectionConcurrentGET(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("claimant@example.com", MethodKeymail, true) |
| + a := claimAccount(t, s, 501, "claimant@example.com", RoleOwner) |
| + c := claimResumeSelection(t, b, url.Values{"accountId": {a.Sqid}}) |
| + results := make(chan bool, 2) |
| + for i := 0; i < 2; i++ { |
| + go func() { |
| + r := httptest.NewRequest("GET", "/demo/claim", nil) |
| + r.AddCookie(c) |
| + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: b.session}) |
| + r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: b.cookie}) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + results <- strings.Contains(w.Body.String(), "data-auto-submit") |
| + }() |
| + } |
| + n := 0 |
| + for i := 0; i < 2; i++ { |
| + if <-results { |
| + n++ |
| + } |
| + } |
| + if n != 1 { |
| + t.Fatalf("concurrent GETs resumed %d times", n) |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("GET reserved") |
| + } |
| +} |
diff --git a/internal/console/demo_claim_selection.go b/internal/console/demo_claim_selection.go| new file mode 100644 |
| index 000000000..d246cbbd4 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_selection.go |
| @@ -0,0 +1,110 @@ |
| +package console |
| + |
| +import ( |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +const demoClaimSelectionCookie = "carlos_demo_claim_selection" |
| +const demoClaimSelectionTTL = 2 * time.Minute |
| + |
| +type demoClaimSelection struct { |
| + ID string `json:"id"` |
| + Account string `json:"account,omitempty"` |
| + Create bool `json:"create,omitempty"` |
| + Nonce string `json:"nonce"` |
| + Expires int64 `json:"expires"` |
| +} |
| + |
| +// A receipt is only a one-use rendering hint, never claim authority. Keep one |
| +// per session and prune expired entries on issuance; a restart loses the hint |
| +// and leaves the ordinary confirmation form. No durable state changes on GET. |
| +type demoClaimSelectionReceipts struct { |
| + mu sync.Mutex |
| + entries map[string]demoClaimSelectionReceipt |
| +} |
| + |
| +type demoClaimSelectionReceipt struct { |
| + digest string |
| + expires time.Time |
| +} |
| + |
| +func (s *Server) demoClaimSelectionMAC(session, payload string) []byte { |
| + mac := hmac.New(sha256.New, s.store.codeKey) |
| + mac.Write([]byte("demo-claim-selection:" + hashToken(session) + ":" + payload)) |
| + return mac.Sum(nil) |
| +} |
| + |
| +func (s *Server) demoClaimSelectionValue(session string, form url.Values, now time.Time) string { |
| + id, err := randomToken() |
| + if err != nil || len(s.store.codeKey) == 0 { |
| + return "" |
| + } |
| + selection := demoClaimSelection{ID: id, Account: form.Get("accountId"), Create: form.Get("create") == "1", Nonce: form.Get("nonce"), Expires: now.Add(demoClaimSelectionTTL).Unix()} |
| + if session == "" || selection.Nonce == "" || selection.Create != (selection.Account == "") { |
| + return "" |
| + } |
| + payload, _ := json.Marshal(selection) |
| + encoded := base64.RawURLEncoding.EncodeToString(payload) |
| + return encoded + "." + base64.RawURLEncoding.EncodeToString(s.demoClaimSelectionMAC(session, encoded)) |
| +} |
| + |
| +func (s *Server) setDemoClaimSelection(w http.ResponseWriter, session string, form url.Values) { |
| + now := time.Now() |
| + value := s.demoClaimSelectionValue(session, form, now) |
| + if value == "" { |
| + return |
| + } |
| + receipts := &s.demoClaimSelections |
| + receipts.mu.Lock() |
| + if receipts.entries == nil { |
| + receipts.entries = make(map[string]demoClaimSelectionReceipt) |
| + } |
| + for key, entry := range receipts.entries { |
| + if !entry.expires.After(now) { |
| + delete(receipts.entries, key) |
| + } |
| + } |
| + receipts.entries[hashToken(session)] = demoClaimSelectionReceipt{digest: hashToken(value), expires: now.Add(demoClaimSelectionTTL)} |
| + receipts.mu.Unlock() |
| + http.SetCookie(w, &http.Cookie{Name: demoClaimSelectionCookie, Value: value, Path: "/demo/claim", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 120, Expires: now.Add(demoClaimSelectionTTL)}) |
| +} |
| + |
| +func (s *Server) takeDemoClaimSelection(w http.ResponseWriter, r *http.Request, session, nonce string) (demoClaimSelection, bool) { |
| + c, err := r.Cookie(demoClaimSelectionCookie) |
| + if err != nil { |
| + return demoClaimSelection{}, false |
| + } |
| + http.SetCookie(w, &http.Cookie{Name: demoClaimSelectionCookie, Path: "/demo/claim", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: -1, Expires: time.Unix(1, 0)}) |
| + payload, signature, ok := strings.Cut(c.Value, ".") |
| + mac, err := base64.RawURLEncoding.DecodeString(signature) |
| + if !ok || err != nil || session == "" || !hmac.Equal(mac, s.demoClaimSelectionMAC(session, payload)) { |
| + return demoClaimSelection{}, false |
| + } |
| + raw, err := base64.RawURLEncoding.DecodeString(payload) |
| + var selection demoClaimSelection |
| + if err != nil || json.Unmarshal(raw, &selection) != nil { |
| + return demoClaimSelection{}, false |
| + } |
| + now := time.Now().Unix() |
| + if selection.Expires <= now || selection.Expires > now+int64(demoClaimSelectionTTL.Seconds()) || selection.Nonce != nonce || selection.Create != (selection.Account == "") { |
| + return demoClaimSelection{}, false |
| + } |
| + receipts := &s.demoClaimSelections |
| + receipts.mu.Lock() |
| + defer receipts.mu.Unlock() |
| + key := hashToken(session) |
| + receipt, ok := receipts.entries[key] |
| + if !ok || receipt.digest != hashToken(c.Value) || !receipt.expires.After(time.Now()) { |
| + return demoClaimSelection{}, false |
| + } |
| + delete(receipts.entries, key) |
| + return selection, true |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 101640147..e794a6890 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1259,6 +1259,7 @@ type Server struct { |
| limits emailLimits |
| // flowLocks serialise /auth/continue per sign-in flow (flowLock). |
| flowLocks [256]sync.Mutex |
| + demoClaimSelections demoClaimSelectionReceipts |
| demoClaimBoundary func(string) error // Test-only crash injection after durable boundaries. |
| demoClaimTestEnabled bool // Test-only readiness bypass. |
| // challengeSem bounds the sign-in and step-up sends in flight |
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js| index f25a17706..9d93bf190 100644 |
| --- a/internal/console/static/demo_claim.js |
| +++ b/internal/console/static/demo_claim.js |
| @@ -2,7 +2,22 @@ |
| "use strict"; |
| let token = location.hash.slice(1); |
| history.replaceState(null, "", "/demo/claim"); |
| - if (!token) return; |
| + if (!token) { |
| + const selection = document.querySelector("form[data-auto-submit]"); |
| + if (selection) { |
| + selection.removeAttribute("data-auto-submit"); |
| + const status = document.getElementById("claim-resuming"); |
| + try { |
| + if (selection.checkValidity()) { |
| + status.hidden = false; |
| + selection.requestSubmit(); |
| + } |
| + } catch (_) { |
| + status.hidden = true; |
| + } |
| + } |
| + return; |
| + } |
| const form = new URLSearchParams({ |
| claimToken: token, |
| nonce: document.querySelector('input[name="nonce"]').value, |
diff --git a/internal/console/stepup.go b/internal/console/stepup.go| index b0684c7a0..8af605d43 100644 |
| --- a/internal/console/stepup.go |
| +++ b/internal/console/stepup.go |
| @@ -464,8 +464,12 @@ func (s *Server) resume(w http.ResponseWriter, r *http.Request, p *pendingAction |
| return |
| } |
| // The claim-only cookie cannot reach /auth. Return to its path after |
| - // proof, where the person confirms with that cookie and a fresh nonce. |
| + // proof with the explicit selection already confirmed before step-up. |
| + // Only this consumed select stash can request a browser POST; OAuth alone cannot. |
| if p.Path == "/demo/claim/select" { |
| + if p.Method == http.MethodPost { |
| + s.setDemoClaimSelection(w, raw, form) |
| + } |
| http.Redirect(w, r, "/demo/claim", http.StatusSeeOther) |
| return |
| } |
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html| index 1c0df5855..93bc684a1 100644 |
| --- a/internal/console/templates/demo_claim.html |
| +++ b/internal/console/templates/demo_claim.html |
| @@ -28,15 +28,16 @@ |
| {{if and .HasIntent .CanClaim}} |
| {{if .Address}} |
| <p>{{.Copy.identity}} <strong>{{.Address}}</strong></p> |
| -<form method="post" action="/demo/claim/select"> |
| +<form method="post" action="/demo/claim/select"{{if .AutoSubmit}} data-auto-submit{{end}}> |
| <input type="hidden" name="nonce" value="{{.Nonce}}"><input type="hidden" name="csrf" value="{{.CSRF}}"> |
| {{if .Accounts}} |
| <label for="account">{{.Copy.account}}</label> |
| <select id="account" name="accountId" required> |
| -{{if gt (len .Accounts) 1}}<option value="" selected disabled>{{.Copy.choose}}</option>{{end}} |
| -{{range .Accounts}}<option value="{{.Sqid}}">{{.Name}} ({{.Sqid}})</option>{{end}} |
| +{{if gt (len .Accounts) 1}}<option value=""{{if not .SelectedAccount}} selected{{end}} disabled>{{.Copy.choose}}</option>{{end}} |
| +{{range .Accounts}}<option value="{{.Sqid}}"{{if eq .Sqid $.SelectedAccount}} selected{{end}}>{{.Name}} ({{.Sqid}})</option>{{end}} |
| </select> |
| {{else}}<p>{{.Copy.new}}</p><input type="hidden" name="create" value="1">{{end}} |
| +<p id="claim-resuming" role="status" hidden>{{.Copy.resuming}}</p> |
| <button type="submit">{{.Copy.confirm}}</button> |
| </form> |
| {{else}} |
diff --git a/internal/console/testdata/demo_claim_resume_browser.mjs b/internal/console/testdata/demo_claim_resume_browser.mjs| new file mode 100644 |
| index 000000000..fc4f80ead |
| --- /dev/null |
| +++ b/internal/console/testdata/demo_claim_resume_browser.mjs |
| @@ -0,0 +1,92 @@ |
| +import {spawn} from 'node:child_process'; |
| +import assert from 'node:assert/strict'; |
| +import {writeFile} from 'node:fs/promises'; |
| + |
| +const [binary, profile, target, sessionToken, flowCookie, account, screenshots] = process.argv.slice(2); |
| +const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu', |
| + '--disable-dev-shm-usage', '--disable-background-networking', '--disable-component-update', |
| + '--disable-default-apps', '--disable-extensions', '--disable-sync', '--no-proxy-server', |
| + '--no-first-run', '--no-default-browser-check', '--remote-debugging-pipe', |
| + '--user-data-dir=' + profile], {stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe']}); |
| +let sequence = 0, buffered = '', session; |
| +const pending = new Map(); |
| +let security = []; |
| + |
| +chrome.stdio[4].on('data', bytes => { |
| + buffered += bytes.toString(); |
| + let end; |
| + while ((end = buffered.indexOf('\0')) !== -1) { |
| + const message = JSON.parse(buffered.slice(0, end)); |
| + buffered = buffered.slice(end + 1); |
| + if (message.method === 'Log.entryAdded' && message.params.entry.source === 'security') security.push(message.params.entry.text); |
| + const resolve = pending.get(message.id); |
| + if (resolve) { pending.delete(message.id); resolve(message); } |
| + } |
| +}); |
| +async function call(method, params = {}, attached = true) { |
| + const id = ++sequence; |
| + const result = new Promise(resolve => pending.set(id, resolve)); |
| + chrome.stdio[3].write(JSON.stringify({id, method, params, ...(attached && session ? {sessionId:session} : {})}) + '\0'); |
| + const message = await result; |
| + assert.equal(message.error, undefined, JSON.stringify(message.error)); |
| + return message.result; |
| +} |
| +async function evaluate(expression) { |
| + const result = await call('Runtime.evaluate', {expression, returnByValue:true}); |
| + assert.equal(result.exceptionDetails, undefined); |
| + return result.result.value; |
| +} |
| +async function until(expression) { |
| + for (let i = 0; i < 150; i++) { |
| + if (await evaluate(expression)) return; |
| + await new Promise(resolve => setTimeout(resolve, 100)); |
| + } |
| + throw Error('browser_condition_timeout: ' + await evaluate('JSON.stringify({text:document.body.innerText,email:document.getElementById("email")?.value,focus:document.activeElement.tagName,valid:document.querySelector("form")?.checkValidity()})')); |
| +} |
| +async function key(key, code, number) { |
| + await call('Input.dispatchKeyEvent', {type:key === 'Enter' ? 'keyDown' : 'rawKeyDown', key, code, windowsVirtualKeyCode:number, ...(key === 'Enter' ? {text:'\r', unmodifiedText:'\r'} : {})}); |
| + await call('Input.dispatchKeyEvent', {type:'keyUp', key, code, windowsVirtualKeyCode:number}); |
| +} |
| +const timer = setTimeout(() => { chrome.kill('SIGKILL'); process.exitCode = 1; }, 35000); |
| +try { |
| + const created = await call('Target.createTarget', {url:'about:blank'}, false); |
| + session = (await call('Target.attachToTarget', {targetId:created.targetId, flatten:true}, false)).sessionId; |
| + await call('Page.enable'); |
| + await call('Log.enable'); |
| + await call('Network.enable'); |
| + await call('Network.setCookies', {cookies:[ |
| + {name:'carlos_console_session',value:sessionToken,url:target,path:'/',httpOnly:true,sameSite:'Lax'}, |
| + {name:'carlos_demo_claim_flow',value:flowCookie,url:target,path:'/demo/claim',httpOnly:true,secure:true,sameSite:'Lax'} |
| + ]}); |
| + await call('Page.navigate', {url:target+'/demo/claim?csp=before'}); |
| + await until('!!document.querySelector("select[name=accountId]")'); |
| + await evaluate(`document.querySelector('select').value = ${JSON.stringify(account)}; document.querySelector('form[action="/demo/claim/select"]').requestSubmit()`); |
| + for (let i=0; i<50 && !security.some(s=>s.includes('form-action')); i++) await new Promise(r=>setTimeout(r,100)); |
| + assert(security.some(s=>s.includes('form-action')), 'Chromium did not reproduce redirect CSP block: '+JSON.stringify(security)); |
| + assert.equal(await evaluate('location.origin'), target); |
| + process.stdout.write('before: Chromium blocked the cross-port Keymail redirect\n'); |
| + security = []; |
| + await call('Page.navigate', {url:target+'/demo/claim'}); |
| + await until('!!document.querySelector("select[name=accountId]")'); |
| + await evaluate(`document.querySelector('select').value = ${JSON.stringify(account)}`); |
| + assert.equal(await evaluate('document.querySelectorAll("script").length'),1); |
| + if (screenshots) { |
| + for (const scheme of ['light','dark']) { |
| + await call('Emulation.setEmulatedMedia',{features:[{name:'prefers-color-scheme',value:scheme}]}); |
| + await new Promise(r=>setTimeout(r,150)); |
| + const shot = await call('Page.captureScreenshot',{format:'png',captureBeyondViewport:true}); |
| + await writeFile(screenshots+'/'+scheme+'.png',Buffer.from(shot.data,'base64')); |
| + } |
| + } |
| + await evaluate(`document.querySelector('form[action="/demo/claim/select"]').requestSubmit()`); |
| + await until(`!!document.querySelector("p[role=status]") && !document.querySelector('form[action="/demo/claim/select"]')`); |
| + assert.equal(await evaluate('location.pathname'),'/demo/claim'); |
| + assert.equal(await evaluate('location.hash'),''); |
| + assert.equal(security.length,0,JSON.stringify(security)); |
| + process.stdout.write('after: redirect, callback, JS auto-submit, claiming state; no CSP violations\n'); |
| +} finally { |
| + clearTimeout(timer); |
| + const closed = new Promise(resolve => chrome.once('exit',resolve)); |
| + chrome.kill('SIGTERM'); |
| + await closed; |
| +} |