carlos / platform Public

fix: claim page keymail origin fails closed; error page brand

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev 467916b992587330b8abe77e5d3ca6d181a40927 parent a42c868
8 files changed, +246 −43
  • internal/console/demo_claim_csp_test.go +30 −1
  • internal/console/demo_claim_page.go +40 −40
  • internal/console/demo_claim_resume_browser_test.go +1 −1
  • internal/console/demo_claim_resume_test.go +70 −0
  • internal/console/keymail.go +22 −0
  • internal/console/keymail_origin_test.go +48 −0
  • internal/console/static/demo_claim.js +7 −0
  • internal/console/testdata/demo_claim_resume_browser.mjs +28 −1

CI passed — run details

Intent

Human

<task-notification> <task-id>bpzjssn1n</task-id> <tool-use-id>toolu_01EfvnWKWtHaiB5PJJ8j4jtp</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/bpzjssn1n.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/dcpf; until [ -f $S/done ]; do sleep 20; done; tail -1 $S/log; cat $S/final.md" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>btynaa5v3</task-id> <tool-use-id>toolu_01YZjeXxTjt5UeLJP63HQvyr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/btynaa5v3.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/dcpf; until [ -f $S/luna.done ]; do sleep 10; done; cat $S/luna-final.md; until ! amadan ci status carlos/platform -branch demo-claim-page-fix 2&gt;&amp;1 | head -1 | grep -q 'running\|queued\|pending'; do sleep 60; done; amadan ci status carlos/platform -branch demo-claim-page-fix 2&gt;&amp;1 | head -2" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a12e7ee1661dffead</task-id> <tool-use-id>toolu_01SM7DebZ4M7SZ2SWi2S5qNp</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a12e7ee1661dffead.output</output-file> <status>completed</status> <summary>Agent "Review claim page fix (security)" 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># Review round 1 of 3: demo-claim-page-fix, tip a42c8685 **No P1s, two P2s and four P3s.** Under Stopping rule 1 the review stops here. Apply the P2s without reopening it. The Keymail origin fix changes security behaviour, so that small diff needs a check inside this budget. **How I checked:** I read the code and ran the focused tests. I also ran three throwaway tests through `go test -overlay`, so the worktree is unchanged and clean. **Sandbox block:** Chromium cannot start here (`socket() failed: Operation not permitted`). Both `TestDemoClaimSelectStepUpHeadless` and the older `TestDemoClaimBrowserHeadless` fail for that reason. I did not bypass the sandbox, so the browser evidence is Astra's log, `green-browser.log`, and not my own run. All the non-browser tests I ran passed. ## Findings **P2-1: `Origin()` does not fail closed on a malformed host** - **Where:** `internal/console/keymail.go:77-81`; used at `demo_claim_page.go:103` and `:48`. - **Scenario:** I ran the same parse logic on bad values, and these all pass through unchanged: - `https://*.example.com` - `https://*` - `https://keymail.dev;sandbox` (adds a CSP directive) - `https://a'b` - `https://a,b` - `https://:443` - **What is safe:** spaces, CR/LF, percent escapes, a missing scheme, `ftp://` and an empty value all give `""`. User info is dropped. - **Exposure:** the value only comes from `CONSOLE_KEYMAIL`, so there is no remote path. Gate item 1 is still not met, and `TestDemoClaimPageFormOrigin` has no negative cases. - **Fix:** require `u.Hostname()` to be DNS characters or a bracketed IPv6 address, and the port to be numeric or empty. Return `""` otherwise, and add a table test. - **Fault family:** a CSP source derived from config must be validated in one place. **P2-2: claim error pages show the wrong brand and look signed out** - **Where:** `internal/console/demo_claim_page.go:59`, `page{Brand: (&amp;Server{}).brandName()}`. - **Scenario:** with `consoleNameCfg` set, a signed-in person's 403 page showed "CARLOS console", not the deployment's name, and had no profile menu. The normal page was correct. On Carloku, every claim refusal (plan cap, wrong site, expired intent) would name the wrong product. - **Fix:** make the error a `Server` method that uses `s.brandName()`. Keep it signed-out if you prefer, but use the right brand. - **Fault family:** shared chrome must carry the deployment's identity. **P3 (follow-up list)** 1. **Browser test gating:** `demo_claim_resume_browser_test.go:15-22` skips only when Chromium or node is missing. Where Chromium exists but cannot start, as here, it fails with an unhandled `ECONNRESET`. The sibling test does the same, while the reports and banner browser tests use `CARLOS_DEMO_BROWSER_TESTS=1`. Family: test evidence. 2. **Wrong-demo test:** `otherFlow` (`demo_claim_resume_test.go:161-163`) swaps in another browser's cookie and does not do a real `POST /demo/claim/intent` between click and resume. Promote my passing scenario from section 2 into the suite. Family: confirmation bound to the flow. 3. **Leftover env var:** `DCPF_SCREENSHOTS` at `demo_claim_resume_browser_test.go:54` is named after a scratch directory. 4. **Double submit:** the button stays enabled during auto-submit. A second press gets a 401 "expired" page while the claim is running. The manual form already behaves this way, and a reload recovers. ## Security gate **1. CSP: pass, apart from P2-1** - `form-action` is `'self'` plus scheme and host from `k.base`, with nothing user-influenced (`demo_claim_page.go:46-52`, `keymail.go:81`). `StepUpURL` uses the same `k.base` (`keymail.go:159`). - The error page re-sets `form-action 'self'` (`:57`). My overlay test confirmed that on a real 403. - `default-src 'none'` stays, and the only addition is `style-src` with one hash. There is no new img, font or connect allowance. - The hash is exact and cannot drift at runtime: - The only template action in the styles is the static `fiesta_day` include. - It is computed from the rendered bytes at init (`:22-33`). - A data-dependent style would panic at init. - The chrome has no `style=`, `url(`, `@font-face`, `&lt;img&gt;` or `&lt;link&gt;`, so nothing is blocked. - `TestDemoClaimPageConsoleChrome` checks the hash in Go. Chromium reported zero CSP violations in Astra's log. **2. Resume cookie: pass** - **Who sets it:** only `stepup.go:469-472`, after a consumed `pending_actions` row with that path and POST. Rows are session-bound and burned on take (`stepup.go:238-246`). Sign-in, OAuth return and an existing session do not set it, and the `absent` case and `demo_claim_browser_test.go:158` cover that. - **Attributes:** HttpOnly, Secure, SameSite=Lax, Path=/demo/claim, 120 seconds (`demo_claim_selection.go:77`). - **HMAC:** the input is label plus `hashToken(session)` plus payload (`:39-43`), and no raw session token is included. The key is shared with email codes (`codeKey`), so the label is what separates them. Those inputs start with a hex hash and these start with the label, so they should not collide. I inferred the hex from the comment on `codeMAC` and did not trace the link hash's construction. The key is per-process, so a restart invalidates the cookie. - **Receipt:** - The check and delete are atomic under the mutex (`:100-109`), and the concurrent-GET test passes. - A restart loses it, which leaves the manual form. - Each entry needs a completed step-up. Expired entries are pruned on issue and there is one entry per session, so memory is bounded. - Every failure path clears the cookie and renders no marker. - **Cookie tossing or fixation:** a planted value fails the MAC or the digest check, because it is bound to the victim's session. The worst case is a lost hint and a manual form. Planting a flow cookie changes the nonce, which also fails closed. - **Fields carried:** only account, create and nonce. `SelectedAccount` comes from the person's eligible accounts, never from the cookie (`demo_claim_page.go:161-168`). - **Key scenario, a different demo started between click and resume: safe.** - The binding is the stashed nonce, `hash(flowCookie, session)`, compared at `demo_claim_selection.go:97` with the nonce from the current cookie. - The intent POST always rotates the flow cookie (`demo_claim_page.go:257-272`). - The one in-place rebind, `replaceDemoClaimBrowserFlow`, copies the same `demo_id`. - I ran this over real routes with two demos: click A, intent B, Keymail callback, then GET. The result was no marker, a manual form for B and zero ops. - If B lands after the marker rendered, the stale-nonce POST gets a 403 with zero ops. - **Cross-site GET:** it can only render the person's own confirmed selection for the same flow, and the POST is still same-origin. A fragment token takes the intent branch and never auto-submits. - **Plan Task 7:** GET stays render-only and a real POST claims. The click before step-up is the confirmation, which matches "selection is that confirmation". Finishing OAuth alone does nothing. **3. Gates on the re-post: pass** - `handleDemoClaimBrowserSelect` is unchanged. It runs admission, session, gate (nonce, CSRF, op check), flow, owner, membership, `requireFreshAuth`, proof, then reservation (`:391-461`). - GET changes only an in-memory receipt and a cookie clear, and the tests assert zero ops and zero proved flows. - `demo_claim.js` clears the fragment first and removes the marker before its single submit. - Fresh-auth failure sends the person back to a human gesture at Keymail or email, so it cannot loop unattended. No script, an invalid form or an exception leaves a visible form. - `resume` is unchanged for all other paths; the only diff is inside the `/demo/claim/select` branch. - Email step-up goes through the same `resume` (`emailsignin.go:652-657`), and the email subtest passes. **4. Chrome extraction: pass, but no test covers it** - There is no byte-identity test. I inlined both defines into the tip's `layout.html` and compared against main: 75,694 bytes, identical. That is a source comparison, not two rendered pages. - `server.go:523` parses `templates/*.html`, so the global set picks up the new file. - Signed-out shows only the brand link to `/`. Signed-in adds the address (already on the page), `/settings` and sign-out. There are no account fields or switcher. - In `icons_test.go`, the allowance is unchanged and the diff adds three negative cases. **5. Tests: mostly pass, with evidence gaps** - The router test uses real handlers and a stubbed Keymail over HTTP. The gate matrix takes a shortcut by calling `s.resume` directly, but `TestDemoClaimSelectStepUpRoundTrip` drives the whole path. - The browser test is real Chromium, and it skips if Chromium or node is missing. - **What CI proves:** nothing in `.amadan` installs Chromium, and the gate's `go test` line runs without `-v`, so a skip would be invisible. I could not see the workers. Assume CI proves the CSP string, cookie mechanics, gates and one reservation. - **What CI may not prove:** browser enforcement and the JS auto-submit may be local evidence only. - **Gap in the browser test:** loopback ports are same-site, while production is cross-site. A cross-site return, and any Keymail redirect to a third origin before its page renders, are unwitnessed. Do a real Keymail click-through on dev after the roll. **6. Visual: pass** - `light.png` and `dark.png` show the console header, purple accent and working dark mode, with no left-border stripe. - Only the account-picker state was captured. ## Also noted - The copy pass kept "Keeping your demo in the account you chose…" unchanged. - `census.log` was written at 18:40, before the final commit. The report says later changes stayed in excluded code, which I did not re-run. - Optional: the receipt and signed cookie overlap, and a server-side map alone could do the job. The implementer flagged this design as not explicitly approved. It is correct as built, so it is your or Paul's call, not a defect. ## Verdict **READY AFTER FIXES: tip a42c8685.** Apply P2-1 and P2-2, then run the targeted tests and re-check the census at the new tip. The P3s go on the branch's follow-up list.</result> <usage><subagent_tokens>161458</subagent_tokens><tool_uses>20</tool_uses><duration_ms>486115</duration_ms></usage> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="39e7acfa-a56a-470b-8ef5-70de5c57a6f2" message-id="390c82a6-e4c9-4d3f-b259-709cca7aeb91" source-agent-title="agent /start demo program controller"> From 39e7acfa, FYI: the dev stable freeze started at 18:58Z (G2 rerun executor 39f6160b). Canary stays free between drills, but before any canary move, your release agent must ask 39f6160b whether a drill is running, as well as asking 8a3d302. </paseo-system>

Attributed to this commit: 112 g CO₂e (5,776,838 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_csp_test.go b/internal/console/demo_claim_csp_test.go
index 7da3d7a60..9fb0cefc7 100644
--- a/internal/console/demo_claim_csp_test.go
+++ b/internal/console/demo_claim_csp_test.go
@@ -21,7 +21,7 @@ func TestDemoClaimPageFormOrigin(t *testing.T) {
}
}
w := httptest.NewRecorder()
- demoClaimBrowserError(w, 403, demoClaimWrongSite)
+ s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
if !strings.Contains(w.Header().Get("Content-Security-Policy"), "form-action 'self';") {
t.Fatal("error page widened form policy")
}
@@ -51,3 +51,32 @@ func TestDemoClaimPageConsoleChrome(t *testing.T) {
t.Error("unexpected script or font")
}
}
+
+func TestDemoClaimRefusalBrand(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ s.consoleNameCfg = "Claim test console"
+ b := newClaimBrowser(t, s, token)
+ b.login("claimant@example.com", MethodKeymail, true)
+ w := b.request("POST", "/demo/claim/select", url.Values{"nonce": {"stale"}, "csrf": {b.session}})
+ if w.Code != 403 {
+ t.Fatalf("refusal status = %d", w.Code)
+ }
+ if !strings.Contains(w.Body.String(), s.consoleNameCfg) || strings.Contains(w.Body.String(), "CARLOS console") {
+ t.Fatal("claim refusal did not use the deployment brand")
+ }
+ if strings.Contains(w.Body.String(), "claimant@example.com") || strings.Contains(w.Body.String(), "/logout") {
+ t.Fatal("claim refusal should retain signed-out chrome")
+ }
+}
+
+func TestDemoClaimPageRejectsUnsafeFormOrigin(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ for _, base := range []string{"https://*.example.com", "https://*", "https://keymail.dev;sandbox", "https://a'b", "https://a,b", "https://:443"} {
+ s.km = NewKeymail(base, s.cfg.Origin)
+ b := &claimBrowser{t: t, s: s}
+ w := b.request("GET", "/demo/claim", nil)
+ if !strings.Contains(w.Header().Get("Content-Security-Policy"), "form-action 'self';") {
+ t.Errorf("unsafe form origin for %q", base)
+ }
+ }
+}
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 519efc1aa..bddaa542e 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -53,10 +53,10 @@ func demoClaimPageHeaders(w http.ResponseWriter, keymailOrigin string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
}
-func demoClaimBrowserError(w http.ResponseWriter, status int, message string) {
+func (s *Server) demoClaimBrowserError(w http.ResponseWriter, status int, message string) {
demoClaimPageHeaders(w, "")
w.WriteHeader(status)
- _ = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", demoClaimPageData{Chrome: page{Brand: (&Server{}).brandName()}, Copy: demoClaimBrowserCopy(), Error: message})
+ _ = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", demoClaimPageData{Chrome: page{Brand: s.brandName()}, Copy: demoClaimBrowserCopy(), Error: message})
}
func setDemoClaimCookie(w http.ResponseWriter, raw string, expiry time.Time) {
@@ -83,14 +83,14 @@ func (s *Server) attachDemoClaimBrowser(w http.ResponseWriter, r *http.Request,
err = s.store.attachDemoClaimBrowser(r.Context(), raw, f)
}
if err != nil {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return false
}
expiry := f.ExpiresAt
if op, err := s.store.demoClaimOpForFlow(r.Context(), f.Hash); err == nil {
expiry = demoClaimResultExpiry(op)
} else if !errors.Is(err, sql.ErrNoRows) {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return false
}
setDemoClaimCookie(w, raw, expiry)
@@ -102,7 +102,7 @@ func (s *Server) attachDemoClaimBrowser(w http.ResponseWriter, r *http.Request,
func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
demoClaimPageHeaders(w, s.km.Origin())
if s.cfg.HostClaim || s.store.claimGated() {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
}
cookie := demoClaimCookie(r)
@@ -110,7 +110,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
var err error
cookie, err = randomToken()
if err != nil {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
}
setDemoClaimCookie(w, cookie, time.Now().Add(15*time.Minute))
@@ -135,7 +135,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
p.State = "aborted"
}
} else if !errors.Is(opErr, sql.ErrNoRows) {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
} else if f, ferr := s.store.demoClaimFlowByHash(r.Context(), hash, time.Now()); ferr == nil {
p.HasIntent = true
@@ -155,7 +155,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
var accounts []Account
accounts, err = s.store.AccountsFor(address)
if err != nil {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
}
for _, a := range accounts {
@@ -192,14 +192,14 @@ func (s *Server) demoClaimBrowserGate(w http.ResponseWriter, r *http.Request) bo
}
r.Body = http.MaxBytesReader(w, r.Body, 4096)
if r.ParseForm() != nil {
- demoClaimBrowserError(w, 400, demoClaimBadRequest)
+ s.demoClaimBrowserError(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) {
- demoClaimBrowserError(w, 403, demoClaimWrongSite)
+ s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
return false
}
// Intent uses the posted demo token and rotates the cookie. Other actions
@@ -207,10 +207,10 @@ func (s *Server) demoClaimBrowserGate(w http.ResponseWriter, r *http.Request) bo
hash, err := s.store.demoClaimBrowserHash(r.Context(), cookie, time.Now())
if err == nil && r.URL.Path != "/demo/claim/intent" {
if _, err = s.store.demoClaimOpForFlow(r.Context(), hash); err == nil {
- demoClaimBrowserError(w, 401, demoClaimIntentExpired)
+ s.demoClaimBrowserError(w, 401, demoClaimIntentExpired)
return false
} else if !errors.Is(err, sql.ErrNoRows) {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return false
}
}
@@ -219,11 +219,11 @@ func (s *Server) demoClaimBrowserGate(w http.ResponseWriter, r *http.Request) bo
func (s *Server) demoClaimBrowserAdmission(w http.ResponseWriter, r *http.Request) bool {
w.Header().Set("Cache-Control", "no-store")
if !s.demoClaimEnabled() {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return false
}
if !s.demoClaimOrigin(r) {
- demoClaimBrowserError(w, 403, demoClaimWrongSite)
+ s.demoClaimBrowserError(w, 403, demoClaimWrongSite)
return false
}
return true
@@ -235,7 +235,7 @@ func (s *Server) browserDemoClaimFlow(w http.ResponseWriter, r *http.Request) (c
f, err = s.store.demoClaimFlowByHash(r.Context(), hash, time.Now())
}
if err != nil {
- demoClaimBrowserError(w, 401, demoClaimIntentExpired)
+ s.demoClaimBrowserError(w, 401, demoClaimIntentExpired)
return claimFlow{}, false
}
return f, true
@@ -250,13 +250,13 @@ func (s *Server) handleDemoClaimBrowserIntent(w http.ResponseWriter, r *http.Req
return
}
if !s.limits.submit(s.clientIP(r)) {
- demoClaimBrowserError(w, 429, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 429, demoClaimUnavailable)
return
}
// Rotate instead of rebinding an existing cookie, so old forms fail closed.
raw, err := randomToken()
if err != nil {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
}
var f claimFlow
@@ -284,7 +284,7 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
return
}
if f.Person != "" {
- demoClaimBrowserError(w, 401, demoClaimBadProof)
+ s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
}
now := time.Now()
@@ -292,22 +292,22 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
if code := strings.TrimSpace(r.PostForm.Get("code")); code != "" {
c, ok := s.store.LiveEmailChallenge(ChallengeDemoClaim, f.Hash, now)
if !ok || c.Address != f.Address {
- demoClaimBrowserError(w, 401, demoClaimBadProof)
+ s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
}
done, ok := s.limits.reserveGuess(c.Address, ip)
if !ok {
- demoClaimBrowserError(w, 401, demoClaimBadProof)
+ s.demoClaimBrowserError(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 {
- demoClaimBrowserError(w, 401, demoClaimBadProof)
+ s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
}
if _, err := s.proveDemoClaim(r.Context(), f, MethodEmail, got.Address, ip, now); err != nil {
- demoClaimBrowserProofError(w, err)
+ s.demoClaimBrowserProofError(w, err)
return
}
s.finishSignin(w, r, got.Address, "", MethodEmail, "/demo/claim")
@@ -315,13 +315,13 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
}
address, ok := canonicalAddress(r.PostForm.Get("email"))
if !ok {
- demoClaimBrowserError(w, 400, demoClaimBadRequest)
+ s.demoClaimBrowserError(w, 400, demoClaimBadRequest)
return
}
underCap := s.limits.submit(ip)
keymail := s.keymailAddress(r.Context(), address, underCap)
if !keymail && !s.mailReady(r.Context()) {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
}
if !underCap {
@@ -374,7 +374,7 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
})
mu.Unlock()
if err != nil {
- demoClaimBrowserError(w, 401, demoClaimBadProof)
+ s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
}
if keymail {
@@ -409,7 +409,7 @@ func (s *Server) handleDemoClaimBrowserSelect(w http.ResponseWriter, r *http.Req
}
accounts, err := s.store.AccountsFor(person)
if err != nil {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
}
selected := r.PostForm.Get("accountId")
@@ -435,7 +435,7 @@ func (s *Server) handleDemoClaimBrowserSelect(w http.ResponseWriter, r *http.Req
}
f, err = s.proveDemoClaim(r.Context(), f, method, subject, s.clientIP(r), time.Now())
if err != nil {
- demoClaimBrowserProofError(w, err)
+ s.demoClaimBrowserProofError(w, err)
return
}
if f.Person != person {
@@ -445,7 +445,7 @@ func (s *Server) handleDemoClaimBrowserSelect(w http.ResponseWriter, r *http.Req
}
acct, choices, err := s.chooseDemoClaimAccountForBrowser(r.Context(), f, selected, len(accounts) == 0)
if err != nil {
- demoClaimBrowserAccountError(w, r, err)
+ s.demoClaimBrowserAccountError(w, r, err)
return
}
// A concurrent membership addition requires another explicit selection.
@@ -455,12 +455,12 @@ func (s *Server) handleDemoClaimBrowserSelect(w http.ResponseWriter, r *http.Req
}
rq, ref := s.newAppRegionReq(r, "", "")
if ref != nil {
- demoClaimBrowserError(w, ref.Status, ref.Msg)
+ s.demoClaimBrowserError(w, ref.Status, ref.Msg)
return
}
op, err := s.reserveDemoClaim(r.Context(), f, acct, rq)
if err != nil {
- demoClaimBrowserAccountError(w, r, err)
+ s.demoClaimBrowserAccountError(w, r, err)
return
}
setDemoClaimCookie(w, demoClaimCookie(r), demoClaimResultExpiry(op))
@@ -504,28 +504,28 @@ func demoClaimBrowserCopy() map[string]string {
func demoClaimCanCreate(a Account) bool { return a.Role == RoleOwner || a.Role == RoleMember }
-func demoClaimBrowserProofError(w http.ResponseWriter, err error) {
+func (s *Server) demoClaimBrowserProofError(w http.ResponseWriter, err error) {
if errors.Is(err, errDemoClaimSignupBusy) {
- demoClaimBrowserError(w, 429, demoClaimSignupBusy)
+ s.demoClaimBrowserError(w, 429, demoClaimSignupBusy)
return
}
- demoClaimBrowserError(w, 401, demoClaimBadProof)
+ s.demoClaimBrowserError(w, 401, demoClaimBadProof)
}
-func demoClaimBrowserAccountError(w http.ResponseWriter, r *http.Request, err error) {
+func (s *Server) demoClaimBrowserAccountError(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, ErrDemoToken):
- demoClaimBrowserError(w, 401, demoClaimIntentExpired)
+ s.demoClaimBrowserError(w, 401, demoClaimIntentExpired)
case errors.Is(err, errDemoClaimAccount):
http.NotFound(w, r)
case isPlanCap(err):
- demoClaimBrowserError(w, 409, demoClaimAccountCap)
+ s.demoClaimBrowserError(w, 409, demoClaimAccountCap)
case errors.Is(err, errDemoClaimPlacement):
- demoClaimBrowserError(w, 409, demoClaimPlacement)
+ s.demoClaimBrowserError(w, 409, demoClaimPlacement)
case errors.Is(err, ErrDemoBusy):
- demoClaimBrowserError(w, 409, demoClaimPending)
+ s.demoClaimBrowserError(w, 409, demoClaimPending)
default:
- demoClaimBrowserError(w, 503, demoClaimReserveFailed)
+ s.demoClaimBrowserError(w, 503, demoClaimReserveFailed)
}
}
@@ -533,7 +533,7 @@ func (s *Server) continueDemoClaimKeymail(w http.ResponseWriter, r *http.Request
// Discovery is not proof; the OAuth session supplies the actual identity.
flow := s.requestFlow(r)
if flow == "" {
- demoClaimBrowserError(w, 503, demoClaimUnavailable)
+ s.demoClaimBrowserError(w, 503, demoClaimUnavailable)
return
}
s.continueKeymailSignin(w, r, flow, "/demo/claim")
diff --git a/internal/console/demo_claim_resume_browser_test.go b/internal/console/demo_claim_resume_browser_test.go
index 6dd6f44fc..e719702f5 100644
--- a/internal/console/demo_claim_resume_browser_test.go
+++ b/internal/console/demo_claim_resume_browser_test.go
@@ -51,7 +51,7 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
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"))
+ cmd := exec.CommandContext(ctx, node, "testdata/demo_claim_resume_browser.mjs", chromium, t.TempDir(), ts.URL, b.session, b.cookie, a.Sqid, os.Getenv("CARLOS_DEMO_CLAIM_SCREENSHOTS"))
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("headless: %v %s", err, output)
diff --git a/internal/console/demo_claim_resume_test.go b/internal/console/demo_claim_resume_test.go
index ed0a1f9de..55f2c8ab3 100644
--- a/internal/console/demo_claim_resume_test.go
+++ b/internal/console/demo_claim_resume_test.go
@@ -135,6 +135,76 @@ func claimResumeSelection(t *testing.T, b *claimBrowser, form url.Values) *http.
return nil
}
+func TestDemoClaimSelectStepUpWrongDemo(t *testing.T) {
+ for _, afterMarker := range []bool{false, true} {
+ name := "beforeCallback"
+ if afterMarker {
+ name = "afterMarker"
+ }
+ t.Run(name, func(t *testing.T) {
+ s, _, tokenA := claimTestServer(t)
+ claimStepUpStub(t, s)
+ inB := demoTestAdmission(t, s.cfg.Demo)
+ if _, err := s.store.ReserveDemo(t.Context(), inB); err != nil {
+ t.Fatal(err)
+ }
+ b := newClaimBrowser(t, s, tokenA)
+ b.login("claimant@example.com", MethodKeymail, false)
+ a := claimAccount(t, s, 501, "claimant@example.com", RoleOwner)
+ b.request("GET", "/demo/claim", nil)
+ staleNonce := b.nonce
+ w := b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}})
+ if w.Code != 303 || claimBrowserCount(t, s, "pending_actions") != 1 || claimBrowserCount(t, s, "demo_claim_ops") != 0 {
+ t.Fatalf("demo A did not stop at step-up: %d", w.Code)
+ }
+ callback := w.Header().Get("Location")
+ finish := func() {
+ t.Helper()
+ w := claimFinishKeymail(t, b, callback)
+ if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" || claimBrowserCount(t, s, "pending_actions") != 0 {
+ t.Fatalf("step-up callback: %d %s", w.Code, w.Header().Get("Location"))
+ }
+ }
+ if afterMarker {
+ finish()
+ w := b.request("GET", "/demo/claim", nil)
+ if !strings.Contains(w.Body.String(), "data-auto-submit") {
+ t.Fatal("demo A selection did not render its marker")
+ }
+ staleNonce = b.nonce
+ }
+ if w := b.post("/demo/claim/intent", url.Values{"claimToken": {inB.Identity.Token}}); w.Code != 303 {
+ t.Fatalf("demo B intent: %d %s", w.Code, w.Body)
+ }
+ if !afterMarker {
+ finish()
+ }
+ w = b.request("GET", "/demo/claim", nil)
+ if w.Code != 200 || strings.Contains(w.Body.String(), "data-auto-submit") || !strings.Contains(w.Body.String(), `action="/demo/claim/select"`) {
+ t.Fatal("demo B must retain the manual form without an auto-submit marker")
+ }
+ hash, err := s.store.demoClaimBrowserHash(t.Context(), b.cookie, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ flow, err := s.store.demoClaimFlowByHash(t.Context(), hash, time.Now())
+ demoB, lookupErr := s.store.LookupDemoToken(t.Context(), inB.Identity.Token)
+ if err != nil || lookupErr != nil || flow.DemoID != demoB.ID || b.nonce == staleNonce {
+ t.Fatalf("manual form is not bound to demo B: %+v %v %v", flow, err, lookupErr)
+ }
+ if claimBrowserCount(t, s, "demo_claim_ops") != 0 {
+ t.Fatal("switching demos or rendering reserved a claim")
+ }
+ if afterMarker {
+ w = b.request("POST", "/demo/claim/select", url.Values{"accountId": {a.Sqid}, "nonce": {staleNonce}, "csrf": {b.session}})
+ if w.Code != 403 || !strings.Contains(w.Body.String(), demoClaimWrongSite) || claimBrowserCount(t, s, "demo_claim_ops") != 0 {
+ t.Fatalf("stale demo A form was not refused: %d", w.Code)
+ }
+ }
+ })
+ }
+}
+
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) {
diff --git a/internal/console/keymail.go b/internal/console/keymail.go
index 6190a43a6..5aa2e17fc 100644
--- a/internal/console/keymail.go
+++ b/internal/console/keymail.go
@@ -27,6 +27,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/netip"
"net/url"
"strconv"
"strings"
@@ -78,6 +79,27 @@ func (k *Keymail) Origin() string {
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
return ""
}
+ host := u.Hostname()
+ if host == "" {
+ return ""
+ }
+ if strings.HasPrefix(u.Host, "[") {
+ ip, err := netip.ParseAddr(host)
+ if err != nil || !ip.Is6() || ip.Zone() != "" {
+ return ""
+ }
+ } else {
+ for _, c := range host {
+ if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '.') {
+ return ""
+ }
+ }
+ }
+ for _, c := range u.Port() {
+ if c < '0' || c > '9' {
+ return ""
+ }
+ }
return u.Scheme + "://" + u.Host
}
diff --git a/internal/console/keymail_origin_test.go b/internal/console/keymail_origin_test.go
new file mode 100644
index 000000000..0d66f5d6a
--- /dev/null
+++ b/internal/console/keymail_origin_test.go
@@ -0,0 +1,48 @@
+package console
+
+import "testing"
+
+func TestKeymailOrigin(t *testing.T) {
+ for _, tt := range []struct{ base, want string }{
+ {"https://keymail.dev", "https://keymail.dev"},
+ {"http://127.0.0.1:12345", "http://127.0.0.1:12345"},
+ {"https://mail-2.example.com:8443/path?q=1#fragment", "https://mail-2.example.com:8443"},
+ {"https://KEYMAIL.dev.", "https://KEYMAIL.dev."},
+ {"http://[::1]:12345", "http://[::1]:12345"},
+ {"https://[2001:db8::1]", "https://[2001:db8::1]"},
+ {"https://keymail.dev:", "https://keymail.dev:"},
+ {"https://*.example.com", ""},
+ {"https://*", ""},
+ {"https://keymail.dev;sandbox", ""},
+ {"https://a'b", ""},
+ {"https://a,b", ""},
+ {"https://:443", ""},
+ {"https://mail_example.com", ""},
+ {"https://[keymail.dev]", ""},
+ {"https://[127.0.0.1]", ""},
+ {"https://::1", ""},
+ {"https://[fe80::1%25eth0]", ""},
+ {"https://keymail.dev:port", ""},
+ {"https://keymail.dev:*", ""},
+ {"https://keymail.dev:12;script-src", ""},
+ {"https://keymail.dev:12:34", ""},
+ {"https://keymail.dev bad", ""},
+ {"https://keymail.dev\r\nX-Test: bad", ""},
+ {"https://%2a.example.com", ""},
+ {"https://[::1", ""},
+ {"https:///path", ""},
+ {"//keymail.dev", ""},
+ {"ftp://keymail.dev", ""},
+ {"javascript:alert(1)", ""},
+ {"", ""},
+ } {
+ t.Run(tt.base, func(t *testing.T) {
+ if got := NewKeymail(tt.base, "").Origin(); got != tt.want {
+ t.Errorf("Origin() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+ if got := (*Keymail)(nil).Origin(); got != "" {
+ t.Errorf("nil Origin() = %q", got)
+ }
+}
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index 9d93bf190..1fc375de6 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -2,6 +2,13 @@
"use strict";
let token = location.hash.slice(1);
history.replaceState(null, "", "/demo/claim");
+ for (const form of document.querySelectorAll("form")) {
+ form.addEventListener("submit", () => {
+ for (const button of form.querySelectorAll('button[type="submit"]')) {
+ button.disabled = true;
+ }
+ });
+ }
if (!token) {
const selection = document.querySelector("form[data-auto-submit]");
if (selection) {
diff --git a/internal/console/testdata/demo_claim_resume_browser.mjs b/internal/console/testdata/demo_claim_resume_browser.mjs
index fc4f80ead..37411e6a2 100644
--- a/internal/console/testdata/demo_claim_resume_browser.mjs
+++ b/internal/console/testdata/demo_claim_resume_browser.mjs
@@ -11,6 +11,7 @@ const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu',
let sequence = 0, buffered = '', session;
const pending = new Map();
let security = [];
+const submissions = [];
chrome.stdio[4].on('data', bytes => {
buffered += bytes.toString();
@@ -19,6 +20,7 @@ chrome.stdio[4].on('data', bytes => {
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);
+ if (message.method === 'Runtime.bindingCalled' && message.params.name === 'claimSubmitted') submissions.push(JSON.parse(message.params.payload));
const resolve = pending.get(message.id);
if (resolve) { pending.delete(message.id); resolve(message); }
}
@@ -52,12 +54,32 @@ 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('Runtime.enable');
await call('Log.enable');
await call('Network.enable');
+ await call('Runtime.addBinding', {name:'claimSubmitted'});
+ await call('Page.addScriptToEvaluateOnNewDocument', {source:`
+ window.addEventListener('submit', event => {
+ const form = event.target;
+ if (form.getAttribute('action') !== '/demo/claim/select') return;
+ claimSubmitted(JSON.stringify({
+ disabled:form.querySelector('button[type=submit]').disabled,
+ visible:form.getBoundingClientRect().height > 0,
+ auto:!document.getElementById('claim-resuming').hidden,
+ account:new FormData(form).get('accountId')
+ }));
+ });
+ `});
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('Network.setBlockedURLs', {urls:['*demo_claim.js*']});
+ await call('Page.navigate', {url:target+'/demo/claim'});
+ await until('document.readyState === "complete" && !!document.querySelector("select[name=accountId]")');
+ assert.equal(await evaluate('document.querySelector("button[type=submit]").disabled'),false,'script failure disabled the manual fallback');
+ assert.equal(await evaluate('document.querySelector("form").getBoundingClientRect().height > 0'),true,'script failure hid the form');
+ await call('Network.setBlockedURLs', {urls:[]});
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()`);
@@ -66,6 +88,7 @@ try {
assert.equal(await evaluate('location.origin'), target);
process.stdout.write('before: Chromium blocked the cross-port Keymail redirect\n');
security = [];
+ submissions.length = 0;
await call('Page.navigate', {url:target+'/demo/claim'});
await until('!!document.querySelector("select[name=accountId]")');
await evaluate(`document.querySelector('select').value = ${JSON.stringify(account)}`);
@@ -78,11 +101,15 @@ try {
await writeFile(screenshots+'/'+scheme+'.png',Buffer.from(shot.data,'base64'));
}
}
- await evaluate(`document.querySelector('form[action="/demo/claim/select"]').requestSubmit()`);
+ await evaluate(`const button = document.querySelector('form[action="/demo/claim/select"] button'); button.click(); button.click()`);
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));
+ assert.deepEqual(submissions, [
+ {disabled:true,visible:true,auto:false,account},
+ {disabled:true,visible:true,auto:true,account}
+ ],'manual and automatic submissions must disable the button, retain the form and preserve the selected account');
process.stdout.write('after: redirect, callback, JS auto-submit, claiming state; no CSP violations\n');
} finally {
clearTimeout(timer);