carlos / platform Public

console: a failed step-up setup clears retirement; a replay needs retirement to still hold (plans 6b task 13 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0e3ed732a9811e7896da9fc6715ceede4126441f parent 223ce67
5 files changed, +122 −30
  • internal/console/billingpage_copy.go +3 −0
  • internal/console/billingretire.go +30 −13
  • internal/console/billingretire_test.go +51 −0
  • internal/console/emailsignin.go +9 −7
  • internal/console/stepup.go +29 −10
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index 42d88b84b..c14e1a4aa 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -60,6 +60,9 @@ var billingCopy = map[string]string{
"delete.pending": "A change is still being confirmed or paid for. Finish it first.",
"delete.checkout": "A payment for this account is finishing. Try again in a few minutes.",
"delete.unverified": "We couldn't check every subscription for this account. Try again later, or ask an operator.",
+ // Fix round 1's draft: a confirmed deletion whose retirement ended while
+ // the owner signed in again.
+ "delete.retry": "Nothing was deleted. Try deleting the account again.",
// The page (Task 8).
"page.title": "Billing",
diff --git a/internal/console/billingretire.go b/internal/console/billingretire.go
index a8af7b6e2..c44529228 100644
--- a/internal/console/billingretire.go
+++ b/internal/console/billingretire.go
@@ -27,6 +27,7 @@ var (
errDeleteCheckout = billingRefusal{Key: "delete.checkout"}
errDeleteUnverified = billingRefusal{Key: "delete.unverified"}
errDeleteCollecting = billingRefusal{Key: "delete.collecting"}
+ errDeleteRetry = billingRefusal{Key: "delete.retry"}
)
// retireRenewingRefusal is delete.renewing: a live subscription renews at
@@ -160,11 +161,15 @@ func (s *Server) retireGateLocked(h billingHold, ctx context.Context, acct *Acco
// it has written the response.
//
// With a fresh sign-in proof, one hold covers the retirement mark, the gate
-// and the deletion. The step-up's replay arrives this way too, and finds the
-// mark its first run set. Without one, the gate runs first under the mark
-// (so a refusal never costs a sign-in), the hold is released, and the
-// request is stashed for the step-up; the account stays retiring until the
-// replay, which runs the gate again, or until the mark goes stale.
+// and the deletion. Without one, the gate runs first under the mark (so a
+// refusal never costs a sign-in), the hold is released, and the request is
+// stashed for the step-up; the account stays retiring until the replay, or
+// until the mark goes stale. A step-up that cannot start parks nothing, so
+// the mark is cleared at once. The replay (resume, marked on its context by
+// the server) needs the mark its first run set to still hold: if it has
+// ended (a refused attempt, a failed step-up, staleness), the replay is
+// refused before the gate and nothing is deleted. It then runs the gate
+// again.
func (s *Server) retireForDeletion(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account) (release func(), ok bool) {
settings := "/a/" + acct.Sqid + "/settings"
refuse := func(err error) {
@@ -181,7 +186,7 @@ func (s *Server) retireForDeletion(w http.ResponseWriter, r *http.Request, addr,
now := time.Now()
h, release := s.holdBilling(acct.Sqid)
if fresh {
- if err := s.retireLocked(h, ctx, acct, addr, now); err != nil {
+ if err := s.retireLocked(h, ctx, acct, addr, stepUpReplay(r), now); err != nil {
release()
refuse(err)
return nil, false
@@ -200,12 +205,20 @@ func (s *Server) retireForDeletion(w http.ResponseWriter, r *http.Request, addr,
return nil, false
}
release()
- if !s.requireFreshAuth(w, r, addr, raw) {
+ fresh, suspended := s.stepUpGate(w, r, addr, raw)
+ if !fresh {
+ if !suspended {
+ // Nothing is pending: the account must not stay retiring.
+ h, release = s.holdBilling(acct.Sqid)
+ s.endRetirement(acct)
+ release()
+ }
return nil, false
}
- // A proof that became fresh meanwhile: the replay's path, now.
+ // A proof that became fresh meanwhile: the mark this request set must
+ // still hold, as for a replay.
h, release = s.holdBilling(acct.Sqid)
- if err := s.retireLocked(h, ctx, acct, addr, time.Now()); err != nil {
+ if err := s.retireLocked(h, ctx, acct, addr, true, time.Now()); err != nil {
release()
refuse(err)
return nil, false
@@ -213,14 +226,18 @@ func (s *Server) retireForDeletion(w http.ResponseWriter, r *http.Request, addr,
return release, true
}
-// retireLocked is the gate with a fresh sign-in proof: the account is
-// marked retiring if it is not already (the replay finds the mark its first
-// run set), then the gate runs. A refusal clears the mark.
-func (s *Server) retireLocked(h billingHold, ctx context.Context, acct *Account, addr string, now time.Time) error {
+// retireLocked is the gate with a fresh sign-in proof. A replay (replay
+// true) needs the retirement mark to still hold, else errDeleteRetry before
+// any provider request; a first request marks the account itself. Then the
+// gate runs; a refusal clears the mark.
+func (s *Server) retireLocked(h billingHold, ctx context.Context, acct *Account, addr string, replay bool, now time.Time) error {
retiring, err := s.store.BillingRetiring(acct.ID, now)
if err != nil {
return err
}
+ if replay && !retiring {
+ return errDeleteRetry
+ }
if !retiring {
if err := s.store.BeginBillingRetirement(acct.ID, addr, now); err != nil {
return err
diff --git a/internal/console/billingretire_test.go b/internal/console/billingretire_test.go
index ea9076c18..da9d24e70 100644
--- a/internal/console/billingretire_test.go
+++ b/internal/console/billingretire_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "html"
"net/http"
"net/url"
"strings"
@@ -500,3 +501,53 @@ func TestRetiringRefusesSeatPaths(t *testing.T) {
}
wantCounts(t, o.counts(), map[string]int{})
}
+
+// ---- fix round 1: the mark's lifecycle around the sign-in step ---------------
+
+// A step-up that cannot start (Keymail cannot re-authenticate) parks no
+// deletion, so the retirement mark the gate set is cleared at once and the
+// account can be changed straight away.
+func TestStepUpSetupFailureClearsRetirement(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ o.fk.mu.Lock()
+ o.fk.reauth = false
+ o.fk.mu.Unlock()
+ status, loc, body := postForm(t, o.owner, o.ts.URL+"/a/"+o.acct.Sqid+"/delete",
+ url.Values{"csrf": {o.csrf}, "confirm": {o.acct.Name}})
+ if status != http.StatusServiceUnavailable || !strings.Contains(body, html.EscapeString("can't be asked right now")) {
+ t.Fatalf("delete with step-up unavailable = %d %q\n%s", status, loc, body)
+ }
+ o.wantKept(t)
+ var stashed int
+ o.st.db.QueryRow(`SELECT COUNT(*) FROM pending_actions`).Scan(&stashed)
+ if stashed != 0 {
+ t.Fatalf("%d pending actions parked", stashed)
+ }
+ o.reset()
+ o.wantFlash(t, o.renewal(t, "resume"), "ok", billingCopy["renewal.resumed"])
+ if o.sub("sub_1").CancelAtPeriodEnd {
+ t.Fatal("renewal did not resume")
+ }
+}
+
+// A replay needs the retirement its first run set to still hold: cleared in
+// between, the replay is refused before the gate and nothing is deleted. A
+// first request that already has a fresh proof still marks the account
+// itself (TestDeleteAfterCompletedPurchaseAndStop).
+func TestReplayNeedsRetirementToHold(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ loc := o.deleteStashed(t)
+ if err := o.st.EndBillingRetirement(o.acct.ID); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ status, rloc, body := completeStepUp(t, o.consoleFixture, o.owner, loc)
+ if status != http.StatusSeeOther || rloc != o.settingsPath() {
+ t.Fatalf("replay = %d %q\n%s", status, rloc, body)
+ }
+ if kind, msg := o.jarFlash(t); kind != "err" || msg == "" || msg != billingCopy["delete.retry"] {
+ t.Fatalf("flash = %s:%q, want delete.retry", kind, msg)
+ }
+ wantCounts(t, o.counts(), map[string]int{})
+ o.wantKept(t)
+}
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index 3c42c4286..36f979e73 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -437,25 +437,26 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) {
// that action, and show "Confirm it's you". With no mailer ready it fails
// closed, holding nothing. Over the send limit, a session that already has a
// live step-up challenge sees that one's page again (the earlier email still
-// works); any other fails closed.
-func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw string, now time.Time) {
+// works); any other fails closed. It answers whether this request was held
+// (suspended): only then can a step-up resume it.
+func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw string, now time.Time) (suspended bool) {
if !s.mailReady(r.Context()) {
log.Printf("console: step-up for %s: the console mailer is not ready", addr)
s.renderMessage(w, r, http.StatusServiceUnavailable, "Error", stepUpHoldFailed)
- return
+ return false
}
if !s.limits.stepUpSend(addr) {
if c, ok := s.liveStepUp(raw, now); ok {
s.renderStepUp(w, r, c.Address, "")
- return
+ return false
}
log.Printf("console: step-up email to %s over its limits; not sent", addr)
s.renderMessage(w, r, http.StatusServiceUnavailable, "Error", stepUpHoldFailed)
- return
+ return false
}
pending, ok := s.stashRequest(w, r, addr, raw, now)
if !ok {
- return
+ return false
}
// It replaces this session's earlier step-up challenge, if any.
link, code, err := s.store.CreateEmailChallenge(EmailChallenge{
@@ -468,7 +469,7 @@ func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw s
if err != nil {
log.Printf("console: step-up challenge for %s: %v", addr, err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the confirmation. Please try again.")
- return
+ return false
}
console := s.consoleName()
s.sendChallengeAsync(addr,
@@ -476,6 +477,7 @@ func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw s
copyText("email.stepup.body", "console", console, "address", addr,
"link", s.cfg.Origin+"/auth/email/link?t="+link, "code", code))
s.renderStepUp(w, r, addr, "")
+ return true
}
// stepUpFor reports whether c is a step-up challenge made for the session raw.
diff --git a/internal/console/stepup.go b/internal/console/stepup.go
index 725583ce8..2c960ea53 100644
--- a/internal/console/stepup.go
+++ b/internal/console/stepup.go
@@ -263,16 +263,25 @@ FROM pending_actions WHERE token_hash = ?`, hash).
// 404 rather than a redirect that confirms the account exists, and a
// cross-site POST must be refused before it can park a pending action.
func (s *Server) requireFreshAuth(w http.ResponseWriter, r *http.Request, addr, raw string) bool {
+ fresh, _ := s.stepUpGate(w, r, addr, raw)
+ return fresh
+}
+
+// stepUpGate is requireFreshAuth that also says, when it returns false,
+// whether the request was parked for a step-up that can resume it
+// (suspended) or nothing is pending because the step-up could not start
+// (Keymail unreachable or unable, a confirmation that could not be minted
+// or sent, a stash that failed). Either way the response is written.
+func (s *Server) stepUpGate(w http.ResponseWriter, r *http.Request, addr, raw string) (fresh, suspended bool) {
now := time.Now()
if s.store.FreshStepUp(raw, addr, now, StepUpWindow) {
- return true
+ return true, false
}
// A session that signed in by email re-confirms by email (spec 6). Only
// that method does: a Keymail session, or one whose method cannot be
// read, takes the passkey path below and never an email instead.
if _, method, ok := s.store.SessionInfo(raw, now); ok && method == MethodEmail {
- s.emailStepUp(w, r, addr, raw, now)
- return false
+ return false, s.emailStepUp(w, r, addr, raw, now)
}
// Ask the identity provider whether it can do this at all before sending a
// human off to try. Unreachable and "no" are the same answer here — see
@@ -283,29 +292,29 @@ func (s *Server) requireFreshAuth(w http.ResponseWriter, r *http.Request, addr,
case err != nil:
log.Printf("console: step-up capability check: %v", err)
s.renderMessage(w, r, http.StatusServiceUnavailable, "Can't confirm it's you", stepUpUnavailable)
- return false
+ return false, false
case !supported:
log.Printf("console: step-up refused: %s does not advertise re-authentication", s.cfg.Keymail)
s.renderMessage(w, r, http.StatusServiceUnavailable, "Can't confirm it's you", stepUpUnavailable)
- return false
+ return false, false
}
state, err := NewVerifier()
if err != nil {
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the confirmation. Please try again.")
- return false
+ return false, false
}
verifier, err := NewVerifier()
if err != nil {
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the confirmation. Please try again.")
- return false
+ return false, false
}
pending, ok := s.stashRequest(w, r, addr, raw, now)
if !ok {
- return false
+ return false, false
}
s.setCookie(w, stepUpCookie, state+"."+verifier+"."+pending, int(stepUpFlowTTL.Seconds()))
http.Redirect(w, r, s.km.StepUpURL(state, ChallengeS256(verifier), StepUpWindow), http.StatusSeeOther)
- return false
+ return false, true
}
// stashRequest parks the request the gate interrupted (StashPendingAction)
@@ -427,6 +436,16 @@ func (s *Server) handleStepUpCallback(w http.ResponseWriter, r *http.Request) {
s.resume(w, r, pending)
}
+// stepUpReplayKey marks a request's context as the replay of a held POST
+// (resume). Only the server sets it: a browser cannot send a context.
+type stepUpReplayKey struct{}
+
+// stepUpReplay is whether r is resume's replay of a held POST.
+func stepUpReplay(r *http.Request) bool {
+ v, _ := r.Context().Value(stepUpReplayKey{}).(bool)
+ return v
+}
+
// resume re-runs the held POST through the console's own router, so it meets
// every gate it would have met the first time — session, CSRF, membership,
// ownership, and the step-up gate that now passes. Re-dispatching rather than
@@ -449,7 +468,7 @@ func (s *Server) resume(w http.ResponseWriter, r *http.Request, p *pendingAction
// the token it satisfies it with is this browser's own, read from its
// cookie, not something recovered from storage.
form.Set("csrf", raw)
- req, err := http.NewRequestWithContext(r.Context(), p.Method, p.Path, strings.NewReader(form.Encode()))
+ req, err := http.NewRequestWithContext(context.WithValue(r.Context(), stepUpReplayKey{}, true), p.Method, p.Path, strings.NewReader(form.Encode()))
if err != nil {
log.Printf("console: resume %s %s: %v", p.Method, p.Path, err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not resume that action. Please try it again.")