feat: finish demo claims in the console browser
Add claim-only browser cookies, fragment exchange, email proof and Keymail continuation. Require explicit account confirmation with CSRF, membership and fresh-auth gates, and preserve status when admission is off. Keep ordinary sign-in landing unchanged and use the shared claim account and reservation helpers. Cover browser recovery, identity binding, origin checks and keyboard operation with targeted tests and installed Chromium.
internal/console/apidemo.go+4 −4internal/console/claim_invariant_test.go+1 −0internal/console/demo_claim_auth.go+13 −6internal/console/demo_claim_browser_store.go+42 −0internal/console/demo_claim_browser_test.go+527 −0internal/console/demo_claim_copy.go+49 −0internal/console/demo_claim_page.go+402 −0internal/console/demo_claim_page_test.go+200 −0internal/console/demo_claim_store.go+3 −0internal/console/demo_claim_target.go+9 −0internal/console/emailsignin.go+31 −16internal/console/server.go+16 −6internal/console/static/demo_claim.js+30 −0internal/console/stepup.go+6 −0internal/console/store_gate.go+1 −0internal/console/templates/demo_claim.html+59 −0internal/console/testdata/demo_claim_browser.mjs+72 −0
CI failed — run details
Intent
<task-notification> <task-id>brtwgzgca</task-id> <tool-use-id>toolu_01GMQfYNARD3HiZaxcaYFzUS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/brtwgzgca.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t6fix.done ]; do sleep 30; done; tail -1 $S/t6fix.log" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a46fea76c2c0d19a5</task-id> <tool-use-id>toolu_01C1DeR1Up7jGpDzM8HjneoE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a46fea76c2c0d19a5.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 6 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>I'd call this **READY**. All five round-1 findings are fixed, and the fix diff adds no P1 or P2. It does add three P3 edge cases, listed below. I checked the code against the full diff (3f29819e..ee418de0). The targeted `TestDemoMoved|TestDemoOfflineRetirementHTTP` run passed for `internal/edge` and `internal/status`. It did not run for `internal/host` and `internal/console`: setup failed because the sandbox has a read-only entry in `~/.cache/go-build`, and I left `GOCACHE` alone as the house rules require. For those two packages I relied on the GREEN evidence in the report. All paths below are under `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/`. ## Round-1 findings - **P2-1, failure isolation: ADDRESSED.** - Box: `internal/host/demo_jobs.go:535-543` logs the error once (repeats are suppressed until a success) and keeps reading. `installDemoMoved` only writes after it has verified the snapshot and checked it is monotonic, so the prior mapping is untouched. - Console: `internal/console/apidemobox.go:223-245` logs and skips the moved frame. Serving, retirement and claim replay carry on. - Outbox retry is kept: `publishDemoMoved` still returns snapshot-build errors (`internal/console/demo_claim_moved.go:144-147`). - A bad row is skipped instead of failing the whole build (`demo_claim_moved.go:111-117`). - **P2-2, request cost: ADDRESSED.** `internal/host/demo_moved.go:42-58`. After any completed GET the generation is consumed before verify and install. Only a failed GET sets `retryAt = now + ChangeIndexBackstop` (30 min). A later, new generation is still picked up because `d.generation != gen` and a successful GET clears `retryAt`. A new generation that arrives during the 30-minute window waits for it, but the stream push still delivers it. - **P3-1, heartbeat re-sign: ADDRESSED.** - The console caches the signed bytes keyed on the eligible notices plus a SHA-256 of the signing key (`demo_claim_moved.go:126-135`). - Each connection records the last bytes it sent (`p.movedWire`) and sends only on connect or change (`apidemobox.go:236-244`). - **P3-2, domain check at reservation: ADDRESSED.** `internal/console/demo_claim_target.go:185-187` checks before the op is created. The commit-time check is still there. - **P3-3, honest capability: ADDRESSED.** - The edge reports ready only with a correctly sized static public key and valid `Demo.Domain` and `AppsDomain`, and it handles a nil receiver (`internal/edge/demo_moved.go:16-18`). - The host passes that through the status loop (`internal/host/agent.go:1033`, `:4718`), and `demo-moved-v1` is advertised only when the probe is true (`internal/status/snapshot.go:1177-1180`). - No startup race: `ready(e)` (`internal/edge/edge.go:4566`) runs after `enableStaticFromEnv` (`:4510`). ## Your specific questions - **Can a stale snapshot be sent from the cache?** No. ed25519 signing is deterministic, and the cache key covers the full notice list (which drops expired rows, since the query filters on `expires_at > now`) and the key hash. A notice change, an expiry or a key change always forces a fresh signature. The per-connection record is compared byte for byte, so any change is re-sent. - **Is a new generation picked up after a failed one is consumed?** Yes, as above. - **Any new root read?** No. The diff touches no root-binary code and adds no bucket reads. The new readiness probe is in-memory and the console cache is SQL only. ## New issues from the fix (all P3) 1. **P3: skipping a row can publish a snapshot that breaks monotonicity.** Family: failure isolation versus monotonicity, a new family the P2-1 fix opened (related to round-1 P2-1). - Reservation and commit now gate the domain, so a row only fails the check at publish time after it was valid when committed. That happens only after an operator changes the configured domains (`Demo.Domain` or `AppsDomain`). - When it does, `publishDemoMoved` puts a snapshot without that row. It is not a dead end, but it degrades in two ways: - Boxes holding the old snapshot reject every later one on the monotonic check (`internal/democlaim/moved.go:88`). They log once and keep the old mapping, so the dropped host's notice still serves there. But no newly claimed host's notice installs on those boxes until the dropped row expires. - New boxes never show a notice for the dropped host. Nothing ever re-adds it, because the outbox step succeeds. - Before the fix the build failed for everyone instead, so this is no worse in blocking terms. Two possible fixes: keep a skipped row if it is in the currently published snapshot, or refuse the Put when the new snapshot is not monotonic against `old` (`demo_claim_moved.go:148`) and let the outbox retry. 2. **P3: a transient local error can be treated as permanent.** Family: retry classification, the same family as round-1 P2-2. - In the box's `pass`, a SQLite busy or I/O error from `reg.DemoMoved` or `CompareDemoMoved` consumes the generation (`internal/host/demo_moved.go:56-58`). The console also marks those bytes as sent (`apidemobox.go:241-243`). - A valid snapshot is then ignored until the next change or stream reconnect. - A CAS conflict between the reader and the stream is harmless, because both get their bytes from the same console. Only real local I/O errors hit this. 3. **P3: one combination can still fail the whole build.** Each row passes its own check, but duplicate live hosts or a combined size over the limit make `SignMoved` fail for the whole set (`demo_claim_moved.go:119-121`, `:130`). In practice `reserveDemoMovedCapacity` (`demo_claim_moved.go:58-86`), which checks every live notice plus the candidate, guards against both at reservation and again at commit. Noted only. Minor: on an early error return, the `rejected` map is reset to a partial set (`demo_claim_moved.go:95`). The only effect is an extra log line. **Verdict: READY**</result> <usage><subagent_tokens>71873</subagent_tokens><tool_uses>18</tool_uses><duration_ms>166216</duration_ms></usage> </task-notification>
Attributed to this commit: 18.3 g CO₂e (2,233,689 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-3, 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/apidemo.go b/internal/console/apidemo.go| index f367c0899..1b75c1eea 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -276,10 +276,10 @@ func (s *Server) registerDemoRoutes() { |
| s.registerRoute("POST /api/box/demo-claims/{operationID}/pickup", s.handleDemoClaimPickup) |
| s.registerRoute("POST /api/box/demo-claims/{operationID}/snapshot", s.handleDemoClaimSnapshot) |
| s.registerRoute("POST /api/box/demo-claims/{operationID}/ack", s.handleDemoClaimAck) |
| - s.registerRoute("GET /demo/claim", func(w http.ResponseWriter, r *http.Request) { |
| - w.Header().Set("Cache-Control", "no-store") |
| - jsonError(w, http.StatusServiceUnavailable, demoCopy["DEMO-CLAIM-LATER"]) |
| - }) |
| + s.registerRoute("GET /demo/claim", s.handleDemoClaimPage) |
| + s.registerRoute("POST /demo/claim/intent", s.handleDemoClaimBrowserIntent) |
| + s.registerRoute("POST /demo/claim/prove", s.handleDemoClaimBrowserProof) |
| + s.registerRoute("POST /demo/claim/select", s.handleDemoClaimBrowserSelect) |
| } |
| func demoError(w http.ResponseWriter, err error) { |
| switch { |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index fbd34f00a..b19786d9b 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -189,6 +189,7 @@ var claimWriterReasons = map[string]string{ |
| "sql/demo_moved_notices": "demo claim coordination refuses claims mode; TestDemoClaimTransferSQLGate proves writes are denied", |
| "sql/demo_claim_ops": "demo claim reservations refuse claims mode; TestDemoClaimReservationSQLGate proves writes are denied", |
| + "sql/demo_claim_browsers": "browser claim credentials refuse claims mode; TestDemoClaimBrowserSQLGate proves every write is denied", |
| "sql/demo_claim_flows": "demo claim proof refuses claims mode; TestDemoClaimProofSQLGate proves every write is denied even with an app permit", |
| "sql/demo_reports": "demo reports refuse claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| "sql/demo_caps": "demo caps refuse claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied", |
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go| index c83c5dd46..ac45bf1f4 100644 |
| --- a/internal/console/demo_claim_auth.go |
| +++ b/internal/console/demo_claim_auth.go |
| @@ -255,7 +255,7 @@ func (s *Server) proveDemoClaim(ctx context.Context, flow claimFlow, method, add |
| if err != nil { |
| return err |
| } |
| - if f.DemoID != flow.DemoID || f.Lifetime != flow.Lifetime || f.Generation != flow.Generation || f.Address != addr || f.Person != "" { |
| + if f.DemoID != flow.DemoID || f.Lifetime != flow.Lifetime || f.Generation != flow.Generation || (f.Address != addr && !s.store.isDemoClaimBrowser(ctx, f.Hash)) || f.Person != "" { |
| return ErrDemoToken |
| } |
| fresh, err := s.store.PersonWouldBeNew(method, addr) |
| @@ -278,11 +278,11 @@ func (s *Server) proveDemoClaim(ctx context.Context, flow claimFlow, method, add |
| } |
| defer tx.Rollback() |
| // Recheck lifetime and generation in the write as well as under the lock. |
| - res, err := tx.ExecContext(ctx, `UPDATE demo_claim_flows SET person=?,method=? WHERE hash=? AND person='' AND expires_at>? |
| + res, err := tx.ExecContext(ctx, `UPDATE demo_claim_flows SET address=?,person=?,method=? WHERE hash=? AND person='' AND expires_at>? |
| AND EXISTS (SELECT 1 FROM demo_apps d JOIN apps a ON a.account_id=d.account_id AND a.app=d.app |
| WHERE d.demo_id=demo_claim_flows.demo_id AND a.demo_id=d.demo_id AND a.lifetime=demo_claim_flows.lifetime |
| AND d.generation=demo_claim_flows.generation AND a.expires_at>? AND a.deleted_at=0 AND a.restoring=0 AND d.state='anonymous' AND d.purged_at=0 AND d.claim_token_hash IS NOT NULL)`, |
| - resolved.Address, method, f.Hash, time.Now().Unix(), time.Now().Unix()) |
| + addr, resolved.Address, method, f.Hash, time.Now().Unix(), time.Now().Unix()) |
| if err != nil { |
| return err |
| } |
| @@ -299,7 +299,7 @@ func (s *Server) proveDemoClaim(ctx context.Context, flow claimFlow, method, add |
| if err = tx.Commit(); err != nil { |
| return err |
| } |
| - f.Person, f.Method = resolved.Address, method |
| + f.Address, f.Person, f.Method = addr, resolved.Address, method |
| proved = f |
| return nil |
| }) |
| @@ -415,7 +415,7 @@ func (s *Server) demoClaimLinkPage(w http.ResponseWriter, r *http.Request, link |
| } |
| s.setCookie(w, linkConfirmCookie, nonce, int(ConfirmationTTL.Seconds())) |
| w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| - w.Header().Set("Referrer-Policy", "no-referrer") |
| + w.Header().Set("Referrer-Policy", "origin") |
| w.Header().Set("Content-Security-Policy", "default-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'") |
| fmt.Fprintf(w, `<!doctype html><html lang="en"><meta charset="utf-8"><title>%s</title><h1>%s</h1><form method="post" action="/auth/email/link"><input type="hidden" name="t" value="%s"><input type="hidden" name="nonce" value="%s"><button>%s</button></form></html>`, html.EscapeString(demoClaimLinkTitle), html.EscapeString(demoClaimLinkTitle), html.EscapeString(link), html.EscapeString(nonce), html.EscapeString(demoClaimLinkButton)) |
| } |
| @@ -434,10 +434,17 @@ func (s *Server) demoClaimLink(w http.ResponseWriter, r *http.Request, link stri |
| jsonError(w, 401, demoClaimBadProof) |
| return |
| } |
| - if _, err = s.proveDemoClaim(r.Context(), flow, MethodEmail, c.Address, s.clientIP(r), now); err != nil { |
| + if flow, err = s.proveDemoClaim(r.Context(), flow, MethodEmail, c.Address, s.clientIP(r), now); err != nil { |
| s.demoClaimProofError(w, err) |
| return |
| } |
| + if s.store.isDemoClaimBrowser(r.Context(), flow.Hash) { |
| + if !s.attachDemoClaimBrowser(w, r, flow) { |
| + return |
| + } |
| + s.finishSignin(w, r, c.Address, "", MethodEmail, "/demo/claim") |
| + return |
| + } |
| w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| fmt.Fprintln(w, demoClaimLinkDone) |
| } |
diff --git a/internal/console/demo_claim_browser_store.go b/internal/console/demo_claim_browser_store.go| new file mode 100644 |
| index 000000000..a7383a961 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_browser_store.go |
| @@ -0,0 +1,42 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "time" |
| +) |
| + |
| +const demoClaimBrowserPurpose = "demo-claim-browser" |
| + |
| +// Browser credentials are independent of agent flow tokens. Only their hashes |
| +// are persisted, so even a cookie submitted to an agent door grants nothing. |
| +func (s *Store) attachDemoClaimBrowser(ctx context.Context, raw string, f claimFlow) error { |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_claim_browsers WHERE expires_at<=?`, time.Now().Unix()); err != nil { |
| + return err |
| + } |
| + _, err = tx.ExecContext(ctx, `INSERT INTO demo_claim_browsers(hash,flow_hash,purpose,expires_at) VALUES(?,?,?,?)`, hashToken(raw), f.Hash, demoClaimBrowserPurpose, f.ExpiresAt.Unix()) |
| + if err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| +func (s *Store) demoClaimBrowserHash(ctx context.Context, raw string, now time.Time) (string, error) { |
| + if s.claimGated() || raw == "" { |
| + return "", ErrDemoToken |
| + } |
| + var hash string |
| + err := s.db.QueryRowContext(ctx, `SELECT flow_hash FROM demo_claim_browsers WHERE hash=? AND purpose=? AND expires_at>?`, hashToken(raw), demoClaimBrowserPurpose, now.Unix()).Scan(&hash) |
| + if err != nil { |
| + return "", ErrDemoToken |
| + } |
| + return hash, nil |
| +} |
| +func (s *Store) isDemoClaimBrowser(ctx context.Context, hash string) bool { |
| + var n int |
| + err := s.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_browsers WHERE flow_hash=? AND purpose=?`, hash, demoClaimBrowserPurpose).Scan(&n) |
| + return err == nil && n > 0 |
| +} |
diff --git a/internal/console/demo_claim_browser_test.go b/internal/console/demo_claim_browser_test.go| new file mode 100644 |
| index 000000000..751156b68 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_browser_test.go |
| @@ -0,0 +1,527 @@ |
| +package console |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDemoClaimBrowserIdentity(t *testing.T) { |
| + t.Run("noSession", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + w := b.post("/demo/claim/select", nil) |
| + if w.Code != 303 || !strings.Contains(w.Header().Get("Location"), "next=") { |
| + t.Fatalf("signin: %d %s", w.Code, w.Header()) |
| + } |
| + }) |
| + t.Run("actualIdentityAndExplicitConfirmation", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("actual@example.com", MethodKeymail, true) |
| + a := claimAccount(t, s, 501, "actual@example.com", RoleOwner) |
| + w := b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(w.Body.String(), "actual@example.com") || !strings.Contains(w.Body.String(), a.Sqid) { |
| + t.Fatal("actual person and account missing") |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("GET claimed") |
| + } |
| + var n int |
| + s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_flows WHERE person!=''`).Scan(&n) |
| + if n != 0 { |
| + t.Fatal("GET proved") |
| + } |
| + }) |
| + t.Run("multipleAccounts", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("shop@example.com", MethodEmail, true) |
| + a := claimAccount(t, s, 501, "shop@example.com", RoleOwner) |
| + c := claimAccount(t, s, 502, "shop@example.com", RoleOwner) |
| + w := b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(w.Body.String(), a.Sqid) || !strings.Contains(w.Body.String(), c.Sqid) { |
| + t.Fatal("picker missing") |
| + } |
| + w = b.post("/demo/claim/select", nil) |
| + if w.Code != 404 { |
| + t.Fatalf("implicit multi-account selection: %d", w.Code) |
| + } |
| + }) |
| + t.Run("staleSessionFreshAuthLast", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("shop@example.com", MethodEmail, false) |
| + a := claimAccount(t, s, 501, "shop@example.com", RoleOwner) |
| + w := b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}) |
| + if w.Code == 404 || w.Code == 401 || claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatalf("stepup: %d %s", w.Code, w.Body.String()) |
| + } |
| + if claimBrowserCount(t, s, "pending_actions") != 1 { |
| + t.Fatal("no fresh auth request") |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoClaimBrowserCSRF(t *testing.T) { |
| + for _, which := range []string{"wrongOrigin", "missingNonce", "crossFlow", "missingSessionCSRF"} { |
| + t.Run(which, func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("shop@example.com", MethodEmail, true) |
| + nonce := b.nonce |
| + if which == "missingNonce" { |
| + nonce = "" |
| + } |
| + if which == "crossFlow" { |
| + other := newClaimBrowser(t, s, token) |
| + nonce = other.nonce |
| + } |
| + form := url.Values{"nonce": {nonce}, "csrf": {b.session}, "accountId": {"missing"}} |
| + if which == "missingSessionCSRF" { |
| + form.Del("csrf") |
| + } |
| + r := httptest.NewRequest("POST", "/demo/claim/select", strings.NewReader(form.Encode())) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", s.cfg.Origin) |
| + if which == "wrongOrigin" { |
| + r.Header.Set("Origin", "https://other.example.com") |
| + } |
| + r.AddCookie(&http.Cookie{Name: browserClaimCookieName, Value: b.cookie}) |
| + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: b.session}) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 403 { |
| + t.Fatalf("csrf: %d %s", w.Code, w.Body.String()) |
| + } |
| + }) |
| + } |
| + t.Run("membershipBeforeFreshAuth", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("shop@example.com", MethodEmail, false) |
| + w := b.post("/demo/claim/select", url.Values{"accountId": {"foreign"}}) |
| + if w.Code != 404 || w.Body.String() != "404 page not found\n" || claimBrowserCount(t, s, "pending_actions") != 0 { |
| + t.Fatalf("membership gate: %d %s", w.Code, w.Body.String()) |
| + } |
| + }) |
| + t.Run("externalNext", func(t *testing.T) { |
| + if safeNext("https://other.example.com/demo/claim") != "" { |
| + t.Fatal("external next allowed") |
| + } |
| + }) |
| + t.Run("emailedLinkGET", func(t *testing.T) { |
| + s, m, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + w := b.post("/demo/claim/prove", url.Values{"email": {"shop@example.com"}}) |
| + if w.Code != 303 { |
| + t.Fatalf("send: %d %s", w.Code, w.Body.String()) |
| + } |
| + _, link := claimMail(t, s, m) |
| + w = b.request("GET", "/auth/email/link?t="+link, nil) |
| + if w.Code != 200 { |
| + t.Fatalf("link GET: %d", w.Code) |
| + } |
| + if _, ok := s.store.PeekEmailLink(link, time.Now()); !ok { |
| + t.Fatal("GET consumed link") |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("GET claimed") |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoClaimBrowserRecovery(t *testing.T) { |
| + t.Run("returnFromOAuthSameIntent", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + cookie := b.cookie |
| + r := httptest.NewRequest("GET", "/auth/callback", nil) |
| + w := httptest.NewRecorder() |
| + s.finishSignin(w, r, "actual@example.com", "", MethodKeymail, "/demo/claim") |
| + if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" { |
| + t.Fatalf("return: %d", w.Code) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == sessionCookie { |
| + b.session = c.Value |
| + } |
| + } |
| + as, err := s.store.AccountsFor("actual@example.com") |
| + if err != nil || len(as) != 0 { |
| + 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") { |
| + t.Fatal("intent lost") |
| + } |
| + }) |
| + t.Run("expiredIntent", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_flows SET expires_at=1`); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := b.post("/demo/claim/prove", url.Values{"email": {"shop@example.com"}}) |
| + if w.Code != 401 { |
| + t.Fatalf("expired: %d %s", w.Code, w.Body.String()) |
| + } |
| + }) |
| + t.Run("committedTokenReuse", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + if _, err := s.store.db.Exec(`UPDATE demo_apps SET claim_token_hash=NULL`); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := b.post("/demo/claim/intent", url.Values{"claimToken": {token}}) |
| + if w.Code != 401 { |
| + t.Fatalf("reuse: %d", w.Code) |
| + } |
| + }) |
| + t.Run("disabledAdmission", func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + s.demoClaimTestEnabled = false |
| + for _, path := range []string{"intent", "prove", "select"} { |
| + w := b.post("/demo/claim/"+path, nil) |
| + if w.Code != 503 || !strings.Contains(w.Body.String(), "unavailable") { |
| + t.Fatalf("disabled %s: %d", path, w.Code) |
| + } |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoClaimBrowserEmailCompletion(t *testing.T) { |
| + for _, door := range []string{"code", "linkOtherBrowser"} { |
| + t.Run(door, func(t *testing.T) { |
| + s, m, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + if w := b.post("/demo/claim/prove", url.Values{"email": {"shop@example.com"}}); w.Code != 303 { |
| + t.Fatalf("send: %d %s", w.Code, w.Body.String()) |
| + } |
| + code, link := claimMail(t, s, m) |
| + if door == "code" { |
| + w := b.post("/demo/claim/prove", url.Values{"code": {code}}) |
| + if w.Code != 303 { |
| + t.Fatalf("code: %d %s", w.Code, w.Body.String()) |
| + } |
| + } else { |
| + other := &claimBrowser{t: t, s: s} |
| + w := other.request("GET", "/auth/email/link?t="+link, nil) |
| + var ck *http.Cookie |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == linkConfirmCookie { |
| + ck = c |
| + } |
| + } |
| + if ck == nil { |
| + t.Fatal("no link nonce") |
| + } |
| + r := httptest.NewRequest("POST", "/auth/email/link", strings.NewReader(url.Values{"t": {link}, "nonce": {ck.Value}}.Encode())) |
| + r.Header.Set("Origin", s.cfg.Origin) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.AddCookie(ck) |
| + w = httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" { |
| + t.Fatalf("link finish: %d %s", w.Code, w.Body.String()) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == browserClaimCookieName { |
| + other.cookie = c.Value |
| + } |
| + if c.Name == sessionCookie { |
| + other.session = c.Value |
| + } |
| + } |
| + if other.cookie == b.cookie || other.cookie == "" { |
| + t.Fatal("no independent browser credential") |
| + } |
| + h1, e1 := s.store.demoClaimBrowserHash(t.Context(), b.cookie, time.Now()) |
| + h2, e2 := s.store.demoClaimBrowserHash(t.Context(), other.cookie, time.Now()) |
| + if e1 != nil || e2 != nil || h1 != h2 { |
| + t.Fatal("other browser changed intent") |
| + } |
| + b = other |
| + } |
| + if b.session == "" { |
| + t.Fatal("no browser session") |
| + } |
| + if as, err := s.store.AccountsFor("shop@example.com"); err != nil || len(as) != 0 { |
| + t.Fatal("proof minted account") |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("proof claimed without confirmation") |
| + } |
| + w := b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(w.Body.String(), "shop@example.com") { |
| + t.Fatal("identity not shown") |
| + } |
| + if w = b.post("/demo/claim/select", url.Values{"create": {"1"}}); w.Code != 303 { |
| + t.Fatalf("confirm: %d %s", w.Code, w.Body.String()) |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 1 { |
| + t.Fatal("no reservation") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserSQLGate(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + gated, err := OpenGated(claimDatabasePath(t, s.store)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer gated.Close() |
| + seedGateApp(t, gated) |
| + err = gated.withClaimSQL(t.Context(), []claimSQLScope{gateScope}, allowAllClaimSQL, func(v *Store) error { |
| + for _, q := range []string{`INSERT INTO demo_claim_browsers(hash,flow_hash,purpose,expires_at) VALUES('other','flow','demo-claim-browser',1)`, `UPDATE demo_claim_browsers SET purpose='other'`, `DELETE FROM demo_claim_browsers`} { |
| + _, err := v.db.Exec(q) |
| + requireDenied(t, q, err) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = gated.demoClaimBrowserHash(t.Context(), b.cookie, time.Now()); err == nil { |
| + t.Fatal("gated cookie readable") |
| + } |
| + if claimWriterReasons["sql/demo_claim_browsers"] == "" { |
| + t.Fatal("missing writer inventory") |
| + } |
| + var stored string |
| + if err = s.store.db.QueryRow(`SELECT hash FROM demo_claim_browsers`).Scan(&stored); err != nil { |
| + t.Fatal(err) |
| + } |
| + if stored == b.cookie || stored != hashToken(b.cookie) { |
| + t.Fatal("raw cookie persisted") |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserStatus(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + raw, _ := randomToken() |
| + f := claimFlow{Hash: op.FlowHash, ExpiresAt: time.Now().Add(15 * time.Minute)} |
| + if err := s.store.attachDemoClaimBrowser(t.Context(), raw, f); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := &claimBrowser{t: t, s: s, cookie: raw} |
| + s.demoClaimTestEnabled = false |
| + for _, phase := range []string{"reserved", "committed", "done", "aborted"} { |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=? WHERE id=?`, phase, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + w := b.request("GET", "/demo/claim", nil) |
| + if w.Code != 200 { |
| + t.Fatalf("%s status: %d", phase, w.Code) |
| + } |
| + if phase == "done" && (!strings.Contains(w.Body.String(), op.Target.Host) || !strings.Contains(w.Body.String(), op.Target.App) || !strings.Contains(w.Body.String(), op.Target.Sqid) || !strings.Contains(w.Body.String(), "carlos login")) { |
| + t.Fatalf("result missing: %s", w.Body.String()) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserActualSubject(t *testing.T) { |
| + s, m, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.post("/demo/claim/prove", url.Values{"email": {"typed@example.com"}}) |
| + claimMail(t, s, m) |
| + b.login("actual@example.com", MethodKeymail, true) |
| + a := claimAccount(t, s, 501, "actual@example.com", RoleOwner) |
| + w := b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(w.Body.String(), "actual@example.com") || strings.Contains(w.Body.String(), "typed@example.com") { |
| + t.Fatal("typed address presented as identity") |
| + } |
| + w = b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}) |
| + if w.Code != 303 { |
| + t.Fatalf("select: %d %s", w.Code, w.Body.String()) |
| + } |
| + var person, method string |
| + if err := s.store.db.QueryRow(`SELECT person,method FROM demo_claim_flows`).Scan(&person, &method); err != nil { |
| + t.Fatal(err) |
| + } |
| + if person != "actual@example.com" || method != MethodKeymail { |
| + t.Fatalf("proof: %s %s", person, method) |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserStepUpReturn(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("shop@example.com", MethodEmail, true) |
| + r := httptest.NewRequest("GET", "/auth/stepup/callback", nil) |
| + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: b.session}) |
| + w := httptest.NewRecorder() |
| + s.resume(w, r, &pendingAction{Path: "/demo/claim/select", Method: "POST", Form: "accountId=foreign"}) |
| + if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" || claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatalf("stepup return: %d %s", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserKeymail(t *testing.T) { |
| + s, m, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + fk := newFakeKeymail(t, "actual@example.com") |
| + s.km = NewKeymail(fk.srv.URL, s.cfg.Origin) |
| + s.km.SetSigningKey(testSigningKey(t)) |
| + w := b.post("/demo/claim/prove", url.Values{"email": {"typed@127.0.0.1"}}) |
| + if w.Code != 303 || w.Header().Get("Location") != "/auth/signin?next=%2Fdemo%2Fclaim" { |
| + t.Fatalf("discovery: %d %s", w.Code, w.Body.String()) |
| + } |
| + if len(m.sentCopy()) != 0 { |
| + t.Fatal("Keymail discovery sent email") |
| + } |
| + r := httptest.NewRequest("GET", w.Header().Get("Location"), nil) |
| + w = httptest.NewRecorder() |
| + s.handleSignin(w, r) |
| + u, err := url.Parse(w.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fk.mu.Lock() |
| + fk.challenge = u.Query().Get("code_challenge") |
| + fk.expectCode = "browser-proof" |
| + fk.mu.Unlock() |
| + r = httptest.NewRequest("GET", "/auth/callback?state="+url.QueryEscape(u.Query().Get("state"))+"&code=browser-proof", nil) |
| + for _, c := range w.Result().Cookies() { |
| + r.AddCookie(c) |
| + } |
| + w = httptest.NewRecorder() |
| + s.handleCallback(w, r) |
| + if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" { |
| + t.Fatalf("OAuth: %d", w.Code) |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == sessionCookie { |
| + b.session = c.Value |
| + } |
| + } |
| + if b.session == "" { |
| + t.Fatal("OAuth session missing") |
| + } |
| + w = b.request("GET", "/demo/claim", nil) |
| + if !strings.Contains(w.Body.String(), "actual@example.com") || strings.Contains(w.Body.String(), "typed@") { |
| + t.Fatal("actual OAuth identity missing") |
| + } |
| + if as, err := s.store.AccountsFor("actual@example.com"); err != nil || len(as) != 0 { |
| + t.Fatal("OAuth minted an account") |
| + } |
| + fk.mu.Lock() |
| + fk.reauth = false |
| + fk.mu.Unlock() |
| + w = b.post("/demo/claim/select", url.Values{"create": {"1"}}) |
| + if w.Code != 503 || len(m.sentCopy()) != 0 || claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatalf("Keymail downgraded: %d", w.Code) |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserLinkedIdentity(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("person@example.com", MethodEmail, true) |
| + if _, err := s.store.db.Exec(`INSERT INTO sign_in_methods(kind,subject,address,added_at) VALUES('keymail','alias@example.com','person@example.com',?)`, time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.login("alias@example.com", MethodKeymail, true) |
| + a := claimAccount(t, s, 501, "person@example.com", RoleOwner) |
| + w := b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}) |
| + if w.Code != 303 { |
| + t.Fatalf("linked: %d %s", w.Code, w.Body.String()) |
| + } |
| + var person, address, method string |
| + if err := s.store.db.QueryRow(`SELECT person,address,method FROM demo_claim_flows`).Scan(&person, &address, &method); err != nil { |
| + t.Fatal(err) |
| + } |
| + if person != "person@example.com" || address != "alias@example.com" || method != MethodKeymail { |
| + t.Fatalf("identity: %s %s %s", person, address, method) |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserCreateIsExplicit(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("shop@example.com", MethodEmail, true) |
| + fraw, err := s.store.demoClaimBrowserHash(t.Context(), b.cookie, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := s.store.demoClaimFlowByHash(t.Context(), fraw, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err = s.proveDemoClaim(t.Context(), f, MethodEmail, "shop@example.com", "192.0.2.1", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + claimAccount(t, s, 501, "shop@example.com", RoleOwner) |
| + // Simulate a membership appearing after the browser's zero-account gate. |
| + if a, _, err := s.chooseDemoClaimAccountForBrowser(t.Context(), f, "", true); err == nil || a != nil { |
| + t.Fatal("create confirmation silently chose a concurrent membership") |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserRestart(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + b.login("shop@example.com", MethodEmail, true) |
| + before, err := s.store.demoClaimBrowserHash(t.Context(), b.cookie, time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + path := claimDatabasePath(t, s.store) |
| + if err = s.store.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + reopened, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reopened.Close() |
| + s.store = reopened |
| + after, err := s.store.demoClaimBrowserHash(t.Context(), b.cookie, time.Now()) |
| + if err != nil || before != after { |
| + t.Fatal("restart lost intent") |
| + } |
| + if w := b.request("GET", "/demo/claim", nil); w.Code != 200 || !strings.Contains(w.Body.String(), "shop@example.com") { |
| + t.Fatal("restart lost person") |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserDoorsCSRF(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := newClaimBrowser(t, s, token) |
| + for _, door := range []string{"intent", "prove", "select"} { |
| + b.login("shop@example.com", MethodEmail, true) |
| + for _, which := range []string{"nonce", "origin", "fetchSite"} { |
| + form := url.Values{"nonce": {b.nonce}, "csrf": {b.session}, "claimToken": {token}, "email": {"shop@example.com"}, "create": {"1"}} |
| + if which == "nonce" { |
| + form.Del("nonce") |
| + } |
| + r := httptest.NewRequest("POST", "/demo/claim/"+door, strings.NewReader(form.Encode())) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", s.cfg.Origin) |
| + if which == "origin" { |
| + r.Header.Set("Origin", "https://other.example.com") |
| + } |
| + if which == "fetchSite" { |
| + r.Header.Set("Sec-Fetch-Site", "cross-site") |
| + } |
| + r.AddCookie(&http.Cookie{Name: browserClaimCookieName, Value: b.cookie}) |
| + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: b.session}) |
| + w := httptest.NewRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 403 { |
| + t.Fatalf("%s/%s: %d", door, which, w.Code) |
| + } |
| + } |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("CSRF started claim") |
| + } |
| +} |
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go| index a74ed60ea..e6e8b5f1b 100644 |
| --- a/internal/console/demo_claim_copy.go |
| +++ b/internal/console/demo_claim_copy.go |
| @@ -29,3 +29,52 @@ const ( |
| // CLAIM-PROOF: confirmation after link redemption. |
| demoClaimLinkDone = "Email confirmed. Return to where you started to continue." |
| ) |
| + |
| +const ( |
| + // CLAIM-PROOF: browser page title. |
| + demoClaimPageTitle = "Keep your demo" |
| + // CLAIM-PROOF: absent or expired intent. |
| + demoClaimIntentExpired = "Open the claim link from your demo to start again." |
| + // CLAIM-PROOF: fragment exchange failure. |
| + demoClaimExchangeFailed = "The claim link could not be opened. Try again." |
| + // CLAIM-PROOF: no-script explanation. |
| + demoClaimNeedsScript = "JavaScript is needed to open the private claim link." |
| + // CLAIM-PROOF: identity confirmation. |
| + demoClaimIdentityLabel = "You are signed in as" |
| + // CLAIM-EMAIL: email field label. |
| + demoClaimEmailLabel = "Email address" |
| + // CLAIM-EMAIL: discovery action. |
| + demoClaimEmailContinue = "Continue" |
| + // CLAIM-EMAIL: code field label. |
| + demoClaimCodeLabel = "Email code" |
| + // CLAIM-EMAIL: code action. |
| + demoClaimCodeConfirm = "Confirm email" |
| + // CLAIM-EMAIL: browser email body; code and nonce-confirmed link. |
| + demoClaimBrowserEmailBody = "To keep your demo, enter this code where you started: %s\n\nOr confirm your email here: %s\n\nThis proof expires within 15 minutes. It signs you in so you can choose where to keep your demo.\n" |
| + // CLAIM-EMAIL: awaiting proof. |
| + demoClaimEmailSent = "Check your email for a code or confirmation link." |
| + // CLAIM-KEYMAIL: ordinary sign-in action. |
| + demoClaimSignin = "Sign in to continue" |
| + // CLAIM-ACCOUNT: account selector label. |
| + demoClaimAccountLabel = "Account" |
| + // CLAIM-ACCOUNT: empty picker choice. |
| + demoClaimChooseAccount = "Choose an account" |
| + // CLAIM-ACCOUNT: zero membership confirmation. |
| + demoClaimNewAccount = "Create a personal account and keep this demo in it. Your plan limits apply." |
| + // CLAIM-ACCOUNT: explicit claim action. |
| + demoClaimConfirm = "Keep this demo" |
| + // CLAIM-RESULT: in-progress status. |
| + demoClaimWorking = "Your demo is being copied. Reload this page to check its progress." |
| + // CLAIM-RESULT: reload action. |
| + demoClaimReload = "Check progress" |
| + // CLAIM-RESULT: completed claim. |
| + demoClaimComplete = "Your demo is now a permanent app." |
| + // CLAIM-RESULT: result app label. |
| + demoClaimAppLabel = "App" |
| + // CLAIM-RESULT: result URL label. |
| + demoClaimURLLabel = "Open app" |
| + // CLAIM-RESULT: next workflow. |
| + demoClaimCLINext = "To deploy changes, sign in with the CLI: carlos login" |
| + // CLAIM-RETIRED: unsuccessful operation. |
| + demoClaimAborted = "This claim did not finish. Open the original demo link to try again if the demo has not expired." |
| +) |
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go| new file mode 100644 |
| index 000000000..a8d8f0cd6 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_page.go |
| @@ -0,0 +1,402 @@ |
| +package console |
| + |
| +import ( |
| + "crypto/subtle" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "html/template" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "time" |
| +) |
| + |
| +const demoClaimBrowserCookie = "carlos_demo_claim_flow" |
| + |
| +var demoClaimPageTemplate = template.Must(template.New("demo_claim.html").Funcs(template.FuncMap{"asset": assetURL}).ParseFS(tmplFS, "templates/demo_claim.html")) |
| + |
| +func setDemoClaimCookie(w http.ResponseWriter, raw string, expiry time.Time) { |
| + age := int(time.Until(expiry).Seconds()) |
| + if age > 900 { |
| + age = 900 |
| + } |
| + if age < 1 { |
| + age = 1 |
| + } |
| + http.SetCookie(w, &http.Cookie{Name: demoClaimBrowserCookie, Value: raw, Path: "/demo/claim", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: age, Expires: expiry}) |
| +} |
| +func demoClaimCookie(r *http.Request) string { |
| + c, err := r.Cookie(demoClaimBrowserCookie) |
| + if err != nil { |
| + return "" |
| + } |
| + return c.Value |
| +} |
| +func demoClaimNonce(cookie, session string) string { |
| + return hashToken("demo-claim-csrf:" + cookie + ":" + session) |
| +} |
| + |
| +func (s *Server) attachDemoClaimBrowser(w http.ResponseWriter, r *http.Request, f claimFlow) bool { |
| + raw, err := randomToken() |
| + if err == nil { |
| + err = s.store.attachDemoClaimBrowser(r.Context(), raw, f) |
| + } |
| + if err != nil { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return false |
| + } |
| + setDemoClaimCookie(w, raw, f.ExpiresAt) |
| + return true |
| +} |
| + |
| +// A render may read existing work with admission off. It never proves identity, |
| +// chooses an account, or starts a reservation, including on OAuth return. |
| +func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "origin") |
| + w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'") |
| + if s.cfg.HostClaim || s.store.claimGated() { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + cookie := demoClaimCookie(r) |
| + if cookie == "" { |
| + var err error |
| + cookie, err = randomToken() |
| + if err != nil { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + setDemoClaimCookie(w, cookie, time.Now().Add(15*time.Minute)) |
| + } |
| + address, session, _ := s.session(r) |
| + p := struct { |
| + Copy map[string]string |
| + Nonce, CSRF, Address, State, AccountID, App, URL string |
| + Accounts []Account |
| + CanClaim, HasIntent, EmailPending bool |
| + }{Copy: demoClaimBrowserCopy(), Nonce: demoClaimNonce(cookie, session), CSRF: session, Address: address, State: "missing"} |
| + hash, err := s.store.demoClaimBrowserHash(r.Context(), cookie, time.Now()) |
| + if err == nil { |
| + if op, opErr := s.store.demoClaimOpForFlow(r.Context(), hash); opErr == nil { |
| + p.State = "claiming" |
| + if op.Phase == "done" { |
| + p.State = "claimed" |
| + p.AccountID = op.Target.Sqid |
| + p.App = op.Target.App |
| + p.URL = "https://" + op.Target.Host |
| + } |
| + if op.Phase == "aborted" { |
| + p.State = "aborted" |
| + } |
| + } else if !errors.Is(opErr, sql.ErrNoRows) { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } else if f, ferr := s.store.demoClaimFlowByHash(r.Context(), hash, time.Now()); ferr == nil { |
| + p.HasIntent = true |
| + p.State = "proof" |
| + p.CanClaim = s.demoClaimEnabled() |
| + if !p.CanClaim { |
| + p.State = "disabled" |
| + } |
| + _, p.EmailPending = s.store.LiveEmailChallenge(ChallengeDemoClaim, hash, time.Now()) |
| + if address != "" { |
| + // A different signed-in person cannot take over an already proved flow. |
| + if f.Person != "" && f.Person != address { |
| + p.State = "missing" |
| + p.HasIntent = false |
| + p.CanClaim = false |
| + } else { |
| + p.Accounts, err = s.store.AccountsFor(address) |
| + if err != nil { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + } |
| + } |
| + } |
| + } |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + if err = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", p); err != nil { |
| + return |
| + } |
| +} |
| + |
| +// The nonce is bound to both the private flow cookie and the current session. |
| +// Session CSRF is checked separately so ordinary fresh-auth replay cannot |
| +// substitute another browser or person. Body fields alone authorize nothing. |
| +func (s *Server) demoClaimBrowserGate(w http.ResponseWriter, r *http.Request) bool { |
| + if !s.demoClaimGate(w, r) { |
| + return false |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil { |
| + jsonError(w, 400, demoClaimBadRequest) |
| + return false |
| + } |
| + cookie := demoClaimCookie(r) |
| + _, session, _ := s.session(r) |
| + nonce := r.PostForm.Get("nonce") |
| + if cookie == "" || nonce == "" || subtle.ConstantTimeCompare([]byte(nonce), []byte(demoClaimNonce(cookie, session))) != 1 || (session != "" && subtle.ConstantTimeCompare([]byte(r.PostForm.Get("csrf")), []byte(session)) != 1) { |
| + jsonError(w, 403, demoClaimWrongSite) |
| + return false |
| + } |
| + return true |
| +} |
| +func (s *Server) browserDemoClaimFlow(w http.ResponseWriter, r *http.Request) (claimFlow, bool) { |
| + hash, err := s.store.demoClaimBrowserHash(r.Context(), demoClaimCookie(r), time.Now()) |
| + var f claimFlow |
| + if err == nil { |
| + f, err = s.store.demoClaimFlowByHash(r.Context(), hash, time.Now()) |
| + } |
| + if err != nil { |
| + jsonError(w, 401, demoClaimIntentExpired) |
| + return claimFlow{}, false |
| + } |
| + return f, true |
| +} |
| +func (s *Server) handleDemoClaimBrowserIntent(w http.ResponseWriter, r *http.Request) { |
| + if !s.demoClaimBrowserGate(w, r) { |
| + return |
| + } |
| + d, err := s.store.LookupDemoToken(r.Context(), r.PostForm.Get("claimToken")) |
| + if err != nil { |
| + demoError(w, ErrDemoToken) |
| + return |
| + } |
| + if !s.limits.submit(s.clientIP(r)) { |
| + jsonError(w, 429, demoClaimUnavailable) |
| + return |
| + } |
| + // Rotate instead of rebinding an existing cookie, so old forms fail closed. |
| + raw, err := randomToken() |
| + if err != nil { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + var f claimFlow |
| + err = s.withDemoLocked(r.Context(), d.ID, func(d DemoRow, life AppLife) error { |
| + var err error |
| + f, err = s.store.createDemoClaimFlow(r.Context(), raw, "", d, life, time.Now()) |
| + return err |
| + }) |
| + if err != nil { |
| + demoError(w, err) |
| + return |
| + } |
| + if !s.attachDemoClaimBrowser(w, r, f) { |
| + return |
| + } |
| + http.Redirect(w, r, "/demo/claim", http.StatusSeeOther) |
| +} |
| + |
| +func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Request) { |
| + if !s.demoClaimBrowserGate(w, r) { |
| + return |
| + } |
| + f, ok := s.browserDemoClaimFlow(w, r) |
| + if !ok { |
| + return |
| + } |
| + if f.Person != "" { |
| + jsonError(w, 401, demoClaimBadProof) |
| + return |
| + } |
| + now := time.Now() |
| + ip := s.clientIP(r) |
| + if code := strings.TrimSpace(r.PostForm.Get("code")); code != "" { |
| + c, ok := s.store.LiveEmailChallenge(ChallengeDemoClaim, f.Hash, now) |
| + if !ok || c.Address != f.Address { |
| + jsonError(w, 401, demoClaimBadProof) |
| + return |
| + } |
| + done, ok := s.limits.reserveGuess(c.Address, ip) |
| + if !ok { |
| + jsonError(w, 401, demoClaimBadProof) |
| + return |
| + } |
| + got, result := s.store.TakeEmailCode(c, code, now) |
| + done(result == CodeOK) |
| + if result != CodeOK || got.FlowHash != f.Hash || got.Purpose != ChallengeDemoClaim || got.Address != f.Address { |
| + jsonError(w, 401, demoClaimBadProof) |
| + return |
| + } |
| + if _, err := s.proveDemoClaim(r.Context(), f, MethodEmail, got.Address, ip, now); err != nil { |
| + s.demoClaimProofError(w, err) |
| + return |
| + } |
| + s.finishSignin(w, r, got.Address, "", MethodEmail, "/demo/claim") |
| + return |
| + } |
| + address, ok := canonicalAddress(r.PostForm.Get("email")) |
| + if !ok { |
| + jsonError(w, 400, demoClaimBadRequest) |
| + return |
| + } |
| + underCap := s.limits.submit(ip) |
| + if s.keymailAddress(r.Context(), address, underCap) { |
| + // Use the ordinary discovery and state/PKCE doors. The typed address is |
| + // never proof; the OAuth session's method subject wins at confirmation. |
| + s.continueKeymailSignin(w, r, s.requestFlow(r), "/demo/claim") |
| + return |
| + } |
| + if !s.mailReady(r.Context()) { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + if !underCap { |
| + http.Redirect(w, r, "/demo/claim", http.StatusSeeOther) |
| + return |
| + } |
| + mu := s.flowLock(f.Hash) |
| + mu.Lock() |
| + var link, code string |
| + sent := false |
| + err := func() error { |
| + fresh, err := s.store.demoClaimFlowByHash(r.Context(), f.Hash, now) |
| + if err != nil || fresh.Person != "" || (fresh.Address != "" && fresh.Address != address) { |
| + return ErrDemoToken |
| + } |
| + res, err := s.store.db.ExecContext(r.Context(), `UPDATE demo_claim_flows SET address=? WHERE hash=? AND person='' AND (address='' OR address=?)`, address, f.Hash, address) |
| + if err != nil { |
| + return err |
| + } |
| + n, err := res.RowsAffected() |
| + if err != nil { |
| + return err |
| + } |
| + if n != 1 { |
| + return ErrDemoToken |
| + } |
| + c := EmailChallenge{Purpose: ChallengeDemoClaim, FlowHash: f.Hash, Address: address, ExpiresAt: f.ExpiresAt} |
| + if !s.limits.signinSend(address, ip) { |
| + return s.store.HoldEmailChallenge(c, now) |
| + } |
| + link, code, err = s.store.CreateEmailChallenge(c, now) |
| + sent = err == nil |
| + return err |
| + }() |
| + mu.Unlock() |
| + if err != nil { |
| + jsonError(w, 401, demoClaimBadProof) |
| + return |
| + } |
| + if sent { |
| + s.sendChallengeAsync(address, demoClaimEmailSubject, fmt.Sprintf(demoClaimBrowserEmailBody, code, s.cfg.Origin+"/auth/email/link?t="+link)) |
| + } |
| + http.Redirect(w, r, "/demo/claim", http.StatusSeeOther) |
| +} |
| + |
| +func (s *Server) handleDemoClaimBrowserSelect(w http.ResponseWriter, r *http.Request) { |
| + if !s.demoClaimGate(w, r) { |
| + return |
| + } |
| + person, session, ok := s.session(r) |
| + if !ok { |
| + http.Redirect(w, r, "/?next="+url.QueryEscape("/demo/claim"), http.StatusSeeOther) |
| + return |
| + } |
| + if !s.demoClaimBrowserGate(w, r) { |
| + return |
| + } |
| + f, ok := s.browserDemoClaimFlow(w, r) |
| + if !ok { |
| + return |
| + } |
| + if f.Person != "" && f.Person != person { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + accounts, err := s.store.AccountsFor(person) |
| + if err != nil { |
| + jsonError(w, 503, demoClaimUnavailable) |
| + return |
| + } |
| + selected := r.PostForm.Get("accountId") |
| + member := false |
| + for _, a := range accounts { |
| + if a.Sqid == selected && (a.Role == RoleOwner || a.Role == RoleMember) { |
| + member = true |
| + } |
| + } |
| + if (!member && len(accounts) > 0) || (len(accounts) == 0 && (selected != "" || r.PostForm.Get("create") != "1")) { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + // Membership and all browser checks precede the fresh-auth redirect. |
| + if !s.requireFreshAuth(w, r, person, session) { |
| + return |
| + } |
| + if f.Person == "" { |
| + subject, method, ok := s.demoClaimSessionIdentity(session, person) |
| + if !ok { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + f, err = s.proveDemoClaim(r.Context(), f, method, subject, s.clientIP(r), time.Now()) |
| + if err != nil { |
| + s.demoClaimProofError(w, err) |
| + return |
| + } |
| + if f.Person != person { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + } |
| + acct, choices, err := s.chooseDemoClaimAccountForBrowser(r.Context(), f, selected, len(accounts) == 0) |
| + if err != nil { |
| + s.demoClaimAccountError(w, r, err) |
| + return |
| + } |
| + // A concurrent membership addition requires another explicit selection. |
| + if acct == nil || len(choices) > 0 { |
| + http.Redirect(w, r, "/demo/claim", http.StatusSeeOther) |
| + return |
| + } |
| + rq, ref := s.newAppRegionReq(r, "", "") |
| + if ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| + if _, err = s.reserveDemoClaim(r.Context(), f, acct, rq); err != nil { |
| + s.demoClaimAccountError(w, r, err) |
| + return |
| + } |
| + http.Redirect(w, r, "/demo/claim", http.StatusSeeOther) |
| +} |
| + |
| +// Resolve the exact method subject that authenticated this session, including |
| +// linked identities whose subject differs from the canonical person address. |
| +func (s *Server) demoClaimSessionIdentity(raw, person string) (string, string, bool) { |
| + address, method, ok := s.store.SessionInfo(raw, time.Now()) |
| + if !ok || address != person { |
| + return "", "", false |
| + } |
| + id, ok := s.store.SessionMethodID(raw, time.Now()) |
| + if !ok { |
| + return "", "", false |
| + } |
| + methods, err := s.store.SignInMethodsFor(person) |
| + if err != nil { |
| + return "", "", false |
| + } |
| + for _, m := range methods { |
| + if m.ID == id && m.Kind == method { |
| + return m.Subject, method, true |
| + } |
| + } |
| + // Older sessions did not retain method IDs. Only the exact same subject |
| + // may serve as the fallback, never another linked method. |
| + if id == 0 { |
| + m, found, err := s.store.LookupSignIn(method, person) |
| + if err == nil && found && m.Address == person { |
| + return person, method, true |
| + } |
| + } |
| + return "", "", false |
| +} |
| + |
| +func demoClaimBrowserCopy() map[string]string { |
| + return map[string]string{"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, "next": demoClaimCLINext, "aborted": demoClaimAborted, "disabled": demoClaimUnavailable} |
| +} |
diff --git a/internal/console/demo_claim_page_test.go b/internal/console/demo_claim_page_test.go| new file mode 100644 |
| index 000000000..40d021888 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_page_test.go |
| @@ -0,0 +1,200 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os/exec" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +const browserClaimCookieName = "carlos_demo_claim_flow" |
| + |
| +var browserNonceRE = regexp.MustCompile(`name="nonce" value="([^"]+)"`) |
| + |
| +type claimBrowser struct { |
| + t *testing.T |
| + s *Server |
| + cookie, session, nonce string |
| +} |
| + |
| +func (b *claimBrowser) request(method, path string, form url.Values) *httptest.ResponseRecorder { |
| + b.t.Helper() |
| + r := httptest.NewRequest(method, path, strings.NewReader(form.Encode())) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + if method == "POST" { |
| + r.Header.Set("Origin", b.s.cfg.Origin) |
| + } |
| + if b.cookie != "" { |
| + r.AddCookie(&http.Cookie{Name: browserClaimCookieName, Value: b.cookie}) |
| + } |
| + if b.session != "" { |
| + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: b.session}) |
| + } |
| + w := httptest.NewRecorder() |
| + b.s.mux.ServeHTTP(w, r) |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == browserClaimCookieName { |
| + b.cookie = c.Value |
| + } |
| + if c.Name == sessionCookie { |
| + b.session = c.Value |
| + } |
| + } |
| + if m := browserNonceRE.FindStringSubmatch(w.Body.String()); len(m) == 2 { |
| + b.nonce = m[1] |
| + } |
| + return w |
| +} |
| +func (b *claimBrowser) post(path string, form url.Values) *httptest.ResponseRecorder { |
| + if form == nil { |
| + form = url.Values{} |
| + } |
| + form.Set("nonce", b.nonce) |
| + form.Set("csrf", b.session) |
| + return b.request("POST", path, form) |
| +} |
| +func newClaimBrowser(t *testing.T, s *Server, token string) *claimBrowser { |
| + t.Helper() |
| + if _, pattern := s.mux.Handler(httptest.NewRequest("GET", "/auth/email/link", nil)); pattern == "" { |
| + s.registerRoute("GET /auth/email/link", s.handleEmailLinkPage) |
| + s.registerRoute("POST /auth/email/link", s.handleEmailLink) |
| + } |
| + b := &claimBrowser{t: t, s: s} |
| + if w := b.request("GET", "/demo/claim", nil); w.Code != 200 { |
| + t.Fatalf("page: %d %s", w.Code, w.Body.String()) |
| + } |
| + if w := b.post("/demo/claim/intent", url.Values{"claimToken": {token}}); w.Code != 303 { |
| + t.Fatalf("intent: %d %s", w.Code, w.Body.String()) |
| + } |
| + b.request("GET", "/demo/claim", nil) |
| + return b |
| +} |
| +func (b *claimBrowser) login(address, method string, fresh bool) { |
| + b.t.Helper() |
| + now := time.Now() |
| + m, _, err := b.s.store.ResolveSignIn(method, address, now) |
| + if err != nil { |
| + b.t.Fatal(err) |
| + } |
| + b.session, err = b.s.store.CreateSessionVia(m.Address, "", method, m.ID, now) |
| + if err != nil { |
| + b.t.Fatal(err) |
| + } |
| + if fresh { |
| + if err = b.s.store.RecordStepUp(b.session, m.Address, now, now); err != nil { |
| + b.t.Fatal(err) |
| + } |
| + } |
| + b.request("GET", "/demo/claim", nil) |
| +} |
| +func claimBrowserCount(t *testing.T, s *Server, table string) int { |
| + t.Helper() |
| + var n int |
| + if err := s.store.db.QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +func TestDemoClaimFragment(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + b := &claimBrowser{t: t, s: s} |
| + w := b.request("GET", "/demo/claim?claimToken="+token, nil) |
| + if w.Code != 200 { |
| + t.Fatalf("page: %d", w.Code) |
| + } |
| + if strings.Contains(w.Body.String(), token) || claimBrowserCount(t, s, "demo_claim_flows") != 0 || claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("scanner GET leaked or acted on token") |
| + } |
| + if w.Header().Get("Referrer-Policy") != "origin" || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatal("missing privacy headers") |
| + } |
| + if b.cookie == "" || b.nonce == "" { |
| + t.Fatal("no browser nonce") |
| + } |
| + for _, c := range w.Result().Cookies() { |
| + if c.Name == browserClaimCookieName && (!c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/demo/claim" || c.MaxAge > 900) { |
| + t.Fatalf("cookie: %+v", c) |
| + } |
| + } |
| + js, err := staticFS.ReadFile("static/demo_claim.js") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + script := string(js) |
| + clear := strings.Index(script, "history.replaceState") |
| + post := strings.Index(script, "fetch(") |
| + if clear < 0 || post < clear || !strings.Contains(script, "location.hash") || !strings.Contains(script, "claimToken") { |
| + t.Fatal("fragment must be cleared before POST exchange") |
| + } |
| + for _, bad := range []string{"localStorage", "sessionStorage", "sendBeacon", "console.log", "https://"} { |
| + if strings.Contains(script, bad) { |
| + t.Fatalf("unsafe script: %s", bad) |
| + } |
| + } |
| + if w = b.post("/demo/claim/intent", url.Values{"claimToken": {token}}); w.Code != 303 { |
| + t.Fatalf("exchange: %d %s", w.Code, w.Body.String()) |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("intent claimed") |
| + } |
| + if w = claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": b.cookie, "accountId": "anything"}); w.Code != 401 { |
| + t.Fatalf("browser cookie authorized agent API: %d", w.Code) |
| + } |
| +} |
| + |
| +func TestDemoClaimBrowserHeadless(t *testing.T) { |
| + chromium, err := exec.LookPath("chromium") |
| + if err != nil { |
| + t.Skip("no installed headless browser") |
| + } |
| + node, err := exec.LookPath("node") |
| + if err != nil { |
| + t.Skip("no installed node for browser protocol") |
| + } |
| + s, m, token := claimTestServer(t) |
| + s.registerRoute("GET /static/{hash}/{file...}", s.handleStatic) |
| + var mu sync.Mutex |
| + var leaked bool |
| + var exchange int |
| + var requests []string |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + mu.Lock() |
| + requests = append(requests, r.Method+" "+r.URL.Path) |
| + if strings.Contains(r.URL.String(), token) || strings.Contains(r.Header.Get("Referer"), token) { |
| + leaked = true |
| + } |
| + if r.Method == "POST" && r.URL.Path == "/demo/claim/intent" { |
| + exchange++ |
| + } |
| + mu.Unlock() |
| + s.mux.ServeHTTP(w, r) |
| + })) |
| + defer ts.Close() |
| + s.cfg.Origin = ts.URL |
| + ctx, cancel := context.WithTimeout(t.Context(), 40*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, node, "testdata/demo_claim_browser.mjs", chromium, t.TempDir(), ts.URL+"/demo/claim#"+token) |
| + output, err := cmd.CombinedOutput() |
| + if err != nil { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + t.Fatalf("headless: %v requests=%v %s", err, requests, output) |
| + } |
| + t.Log(strings.TrimSpace(string(output))) |
| + claimMail(t, s, m) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if leaked || exchange != 1 { |
| + t.Fatalf("browser transport: leaked=%v exchanges=%d", leaked, exchange) |
| + } |
| + if claimBrowserCount(t, s, "demo_claim_ops") != 0 { |
| + t.Fatal("keyboard discovery claimed") |
| + } |
| +} |
diff --git a/internal/console/demo_claim_store.go b/internal/console/demo_claim_store.go| index fa865d172..9367ce07d 100644 |
| --- a/internal/console/demo_claim_store.go |
| +++ b/internal/console/demo_claim_store.go |
| @@ -26,6 +26,9 @@ func (s *Store) migrateDemoClaims() error { |
| person TEXT NOT NULL DEFAULT '', method TEXT NOT NULL DEFAULT '', |
| expires_at INTEGER NOT NULL); |
| CREATE INDEX IF NOT EXISTS demo_claim_flows_demo ON demo_claim_flows(demo_id); |
| + CREATE TABLE IF NOT EXISTS demo_claim_browsers ( |
| + hash TEXT PRIMARY KEY, flow_hash TEXT NOT NULL, purpose TEXT NOT NULL, expires_at INTEGER NOT NULL); |
| + CREATE INDEX IF NOT EXISTS demo_claim_browsers_flow ON demo_claim_browsers(flow_hash); |
| CREATE TABLE IF NOT EXISTS demo_claim_ops ( |
| id TEXT PRIMARY KEY, flow_hash TEXT NOT NULL, demo_id TEXT NOT NULL, |
| source_lifetime TEXT NOT NULL, source_box TEXT NOT NULL, person TEXT NOT NULL, |
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go| index 4575a0e41..579f953f3 100644 |
| --- a/internal/console/demo_claim_target.go |
| +++ b/internal/console/demo_claim_target.go |
| @@ -38,6 +38,12 @@ var ( |
| // The person lock is always held, including without plans. MRU is not a choice. |
| func (s *Server) chooseDemoClaimAccount(ctx context.Context, f claimFlow, selected string) (*Account, []Account, error) { |
| + return s.chooseDemoClaimAccountForBrowser(ctx, f, selected, false) |
| +} |
| + |
| +// createOnly preserves the browser's explicit choice when a membership arrives |
| +// between rendering a new-account confirmation and taking the person lock. |
| +func (s *Server) chooseDemoClaimAccountForBrowser(ctx context.Context, f claimFlow, selected string, createOnly bool) (*Account, []Account, error) { |
| if !s.demoClaimEnabled() { |
| return nil, nil, errors.New(demoClaimUnavailable) |
| } |
| @@ -50,6 +56,9 @@ func (s *Server) chooseDemoClaimAccount(ctx context.Context, f claimFlow, select |
| if err != nil { |
| return nil, nil, err |
| } |
| + if createOnly && len(accounts) != 0 { |
| + return nil, nil, errDemoClaimAccount |
| + } |
| if selected != "" { |
| for _, a := range accounts { |
| if a.Sqid == selected { |
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go| index a73705ba5..fd23b755d 100644 |
| --- a/internal/console/emailsignin.go |
| +++ b/internal/console/emailsignin.go |
| @@ -255,34 +255,58 @@ func safeNext(raw string) string { |
| // remembers its method row, set the cookies, then land. An email sign-in also |
| // records a step-up at the moment of use, the same proof a step-up would ask |
| // for minutes later. The current account is resolved (minted for a new user) |
| -// before any redirect, so onboarding runs before next. |
| +// 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) |
| + if !ok { |
| + return |
| + } |
| + if n := safeNext(next); n != "" { |
| + if n == "/demo/claim" { |
| + http.Redirect(w, r, n, http.StatusSeeOther) |
| + return |
| + } |
| + if _, err := s.currentAccount(r.Context(), person); err != nil { |
| + log.Printf("console: landing for %s: %v", person, err) |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not open your account. Please try again.") |
| + return |
| + } |
| + http.Redirect(w, r, n, http.StatusSeeOther) |
| + return |
| + } |
| + s.redirectToCurrentAccount(w, r, person, http.StatusSeeOther) |
| +} |
| + |
| +// 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) { |
| 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.") |
| - return |
| + return "", false |
| } |
| if fresh && !s.limits.newPerson(s.clientIP(r)) { |
| s.renderMessage(w, r, http.StatusTooManyRequests, copyText("signup.busy_title"), copyText("signup.busy")) |
| - return |
| + return "", false |
| } |
| now := time.Now() |
| m, created, err := s.store.ResolveSignIn(method, proved, now) |
| if err != nil { |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not record your account. Please try again.") |
| - return |
| + return "", false |
| } |
| person := m.Address |
| if keymailToken != "" { |
| if err := s.store.SetGrantToken(proved, keymailToken, now); err != nil { |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not store your sign-in grant. Please try again.") |
| - return |
| + return "", false |
| } |
| } |
| raw, err := s.store.CreateSessionVia(person, keymailToken, method, m.ID, now) |
| if err != nil { |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not create your session. Please try again.") |
| - return |
| + return "", false |
| } |
| s.noteSeen(person, now) |
| s.auditSignInRow(person, created) |
| @@ -298,16 +322,7 @@ func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, proved, ke |
| log.Printf("console: step-up record for %s: %v", person, err) |
| } |
| } |
| - if n := safeNext(next); n != "" { |
| - if _, err := s.currentAccount(r.Context(), person); err != nil { |
| - log.Printf("console: landing for %s: %v", person, err) |
| - s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not open your account. Please try again.") |
| - return |
| - } |
| - http.Redirect(w, r, n, http.StatusSeeOther) |
| - return |
| - } |
| - s.redirectToCurrentAccount(w, r, person, http.StatusSeeOther) |
| + return person, true |
| } |
| // renderLinkExpired is the answer to an unknown, expired or spent link. |
diff --git a/internal/console/server.go b/internal/console/server.go| index 0bb740ecf..28b477ec9 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -3817,12 +3817,7 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) { |
| log.Printf("console: sign-in submissions from %s over the hourly cap; no lookup, no send", ip) |
| } |
| if s.keymailAddress(r.Context(), addr, underCap) { |
| - s.setFlow(w, flow) |
| - target := "/auth/signin" |
| - if next != "" { |
| - target += "?next=" + url.QueryEscape(next) |
| - } |
| - http.Redirect(w, r, target, http.StatusSeeOther) |
| + s.continueKeymailSignin(w, r, flow, next) |
| return |
| } |
| if !s.mailReady(r.Context()) { |
| @@ -3845,6 +3840,21 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) { |
| s.renderCheck(w, flow, addr, next) |
| } |
| +// continueKeymailSignin is shared by ordinary discovery and browser claims. |
| +// Neither the typed address nor the claim credential enters OAuth state. |
| +func (s *Server) continueKeymailSignin(w http.ResponseWriter, r *http.Request, flow, next string) { |
| + if flow == "" { |
| + jsonError(w, http.StatusServiceUnavailable, demoClaimUnavailable) |
| + return |
| + } |
| + s.setFlow(w, flow) |
| + target := "/auth/signin" |
| + if n := safeNext(next); n != "" { |
| + target += "?next=" + url.QueryEscape(n) |
| + } |
| + http.Redirect(w, r, target, http.StatusSeeOther) |
| +} |
| + |
| // signinChallenge is the front door's limits and challenge write for one |
| // flow, under that flow's lock, so overlapping submissions from one browser |
| // take turns. Accepted (under the submission cap and every send limit), it |
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js| new file mode 100644 |
| index 000000000..c8d058e02 |
| --- /dev/null |
| +++ b/internal/console/static/demo_claim.js |
| @@ -0,0 +1,30 @@ |
| +(() => { |
| + "use strict"; |
| + let token = location.hash.slice(1); |
| + history.replaceState(null, "", "/demo/claim"); |
| + if (!token) return; |
| + const form = new URLSearchParams({ |
| + claimToken: token, |
| + nonce: document.querySelector('input[name="nonce"]').value, |
| + csrf: document.querySelector('input[name="csrf"]').value |
| + }); |
| + token = ""; |
| + fetch("/demo/claim/intent", { |
| + method: "POST", |
| + credentials: "same-origin", |
| + mode: "same-origin", |
| + cache: "no-store", |
| + referrerPolicy: "no-referrer", |
| + body: form |
| + }).then(response => { |
| + form.delete("claimToken"); |
| + if (!response.ok) throw new Error(); |
| + location.replace("/demo/claim"); |
| + }).catch(() => { |
| + form.delete("claimToken"); |
| + const error = document.getElementById("claim-error"); |
| + error.textContent = document.getElementById("claim").dataset.failed; |
| + error.hidden = false; |
| + error.focus(); |
| + }); |
| +})(); |
diff --git a/internal/console/stepup.go b/internal/console/stepup.go| index 2c960ea53..b0684c7a0 100644 |
| --- a/internal/console/stepup.go |
| +++ b/internal/console/stepup.go |
| @@ -463,6 +463,12 @@ func (s *Server) resume(w http.ResponseWriter, r *http.Request, p *pendingAction |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not resume that action. Please try it again.") |
| 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. |
| + if p.Path == "/demo/claim/select" { |
| + http.Redirect(w, r, "/demo/claim", http.StatusSeeOther) |
| + return |
| + } |
| // Put back the one field the stash refuses to hold (see requireFreshAuth): |
| // the resumed request must satisfy the same CSRF check as any other, and |
| // the token it satisfies it with is this browser's own, read from its |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index fab603220..db80ec995 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -193,6 +193,7 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "demo_claim_outbox": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| "demo_moved_notices": {App: "demo_id", Refuse: "anonymous demo claims require claims mode off"}, |
| "demo_claim_ops": {Account: "account_id", App: "app", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_claim_browsers": {App: "flow_hash", Refuse: "anonymous demo browser claims require claims mode off"}, |
| "demo_claim_flows": {App: "demo_id", Refuse: "anonymous demo claim flows require claims mode off"}, |
| "demo_reports": {App: "demo_id", Refuse: "anonymous demo reports require claims mode off"}, |
| "demo_report_attempts": {NonApp: "deployment report attempt budget keyed by salted IP hash and time; names no app"}, |
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html| new file mode 100644 |
| index 000000000..3133516b0 |
| --- /dev/null |
| +++ b/internal/console/templates/demo_claim.html |
| @@ -0,0 +1,59 @@ |
| +<!doctype html> |
| +<html lang="en"> |
| +<head> |
| +<meta charset="utf-8"> |
| +<meta name="viewport" content="width=device-width, initial-scale=1"> |
| +<meta name="referrer" content="origin"> |
| +<title>{{.Copy.title}}</title> |
| +</head> |
| +<body> |
| +<main id="claim" data-failed="{{.Copy.failed}}"> |
| +<h1>{{.Copy.title}}</h1> |
| +<input type="hidden" name="nonce" value="{{.Nonce}}"> |
| +<input type="hidden" name="csrf" value="{{.CSRF}}"> |
| +<p id="claim-error" role="alert" tabindex="-1" hidden></p> |
| +{{if eq .State "missing"}}<p>{{.Copy.missing}}</p>{{end}} |
| +{{if eq .State "disabled"}}<p>{{.Copy.disabled}}</p>{{end}} |
| +{{if eq .State "claiming"}}<p role="status">{{.Copy.working}}</p><a href="/demo/claim">{{.Copy.reload}}</a>{{end}} |
| +{{if eq .State "aborted"}}<p>{{.Copy.aborted}}</p>{{end}} |
| +{{if eq .State "claimed"}} |
| +<p role="status">{{.Copy.complete}}</p> |
| +<dl><dt>{{.Copy.account}}</dt><dd>{{.AccountID}}</dd><dt>{{.Copy.app}}</dt><dd>{{.App}}</dd></dl> |
| +<p><a href="{{.URL}}" rel="noreferrer">{{.Copy.url}}</a></p><p>{{.Copy.next}}</p> |
| +{{end}} |
| +{{if and .HasIntent .CanClaim}} |
| +{{if .Address}} |
| +<p>{{.Copy.identity}} <strong>{{.Address}}</strong></p> |
| +<form method="post" action="/demo/claim/select"> |
| +<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}} |
| +</select> |
| +{{else}}<p>{{.Copy.new}}</p><input type="hidden" name="create" value="1">{{end}} |
| +<button type="submit">{{.Copy.confirm}}</button> |
| +</form> |
| +{{else}} |
| +<form method="post" action="/demo/claim/prove"> |
| +<input type="hidden" name="nonce" value="{{.Nonce}}"><input type="hidden" name="csrf" value="{{.CSRF}}"> |
| +<label for="email">{{.Copy.email}}</label><input id="email" name="email" type="email" autocomplete="email" required> |
| +<button type="submit">{{.Copy.continue}}</button> |
| +</form> |
| +{{if .EmailPending}} |
| +<p>{{.Copy.sent}}</p> |
| +<form method="post" action="/demo/claim/prove"> |
| +<input type="hidden" name="nonce" value="{{.Nonce}}"><input type="hidden" name="csrf" value="{{.CSRF}}"> |
| +<label for="code">{{.Copy.code}}</label><input id="code" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" required> |
| +<button type="submit">{{.Copy.prove}}</button> |
| +</form> |
| +{{end}} |
| +<p><a href="/?next=%2Fdemo%2Fclaim">{{.Copy.signin}}</a></p> |
| +{{end}} |
| +{{end}} |
| +<noscript><p>{{.Copy.noscript}}</p></noscript> |
| +</main> |
| +<script src="{{asset "demo_claim.js"}}"></script> |
| +</body> |
| +</html> |
diff --git a/internal/console/testdata/demo_claim_browser.mjs b/internal/console/testdata/demo_claim_browser.mjs| new file mode 100644 |
| index 000000000..aef4f283d |
| --- /dev/null |
| +++ b/internal/console/testdata/demo_claim_browser.mjs |
| @@ -0,0 +1,72 @@ |
| +import {spawn} from 'node:child_process'; |
| +import assert from 'node:assert/strict'; |
| + |
| +const [binary, profile, target] = 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(); |
| +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); |
| + 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; }, 25000); |
| +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('Page.navigate', {url:target}); |
| + await until('location.hash === "" && !!document.getElementById("email")'); |
| + const history = await call('Page.getNavigationHistory'); |
| + assert(history.entries.every(entry => !entry.url.includes('#') && !entry.url.includes('claimToken'))); |
| + assert(!String(await evaluate('document.referrer')).includes('#')); |
| + assert(!String(await evaluate('document.referrer')).includes('claimToken')); |
| + assert.equal(await evaluate('localStorage.length'), 0); |
| + for (let i=0; i<8 && await evaluate('document.activeElement.id') !== 'email'; i++) await key('Tab','Tab',9); |
| + assert.equal(await evaluate('document.activeElement.id'), 'email'); |
| + await call('Input.insertText', {text:'shop@example.com'}); |
| + await key('Tab','Tab',9); |
| + assert.equal(await evaluate('document.activeElement.tagName'), 'BUTTON'); |
| + await key('Enter','Enter',13); |
| + await until('!!document.getElementById("code")'); |
| + assert.equal(await evaluate('document.querySelector("label[for=code]") !== null'), true); |
| + process.stdout.write('fragment_cleared post_exchange keyboard_email_submit passed\n'); |
| +} finally { |
| + clearTimeout(timer); |
| + const closed = new Promise(resolve => chrome.once('exit', resolve)); |
| + chrome.kill('SIGTERM'); |
| + await closed; |
| +} |