carlos / platform Public

feat: reserve account capacity for demo claims

Choose exact verified memberships, reserve app and instance capacity atomically, and isolate pending destinations across ordinary and internal mutation doors. Wire proof and selection to reserved status and preserve retry identity.

Targeted claim, plan, app-create, SQL and lifecycle tests pass. Console vet and touched-file formatting checks pass. Capability activation and independent task review remain with the controller.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 0b407d30bd6e140c9f704506e0382f5cdfa0b37f parent 82f0cb0
22 files changed, +1,213 −90
  • internal/console/apiservices.go +6 −0
  • internal/console/claim_app_mutation.go +4 −0
  • internal/console/claim_invariant_test.go +1 −0
  • internal/console/claim_route_writes.go +4 −0
  • internal/console/claim_sql_auto.go +5 −0
  • internal/console/demo_claim_auth.go +54 −12
  • internal/console/demo_claim_auth_test.go +15 −7
  • internal/console/demo_claim_caps_test.go +111 −0
  • internal/console/demo_claim_copy.go +9 −0
  • internal/console/demo_claim_store.go +130 −1
  • internal/console/demo_claim_store_test.go +6 −6
  • internal/console/demo_claim_target.go +290 −0
  • internal/console/demo_claim_target_test.go +467 −0
  • internal/console/demo_domains.go +13 −0
  • internal/console/lifetimes_purge.go +6 −0
  • internal/console/lifetimes_store.go +4 −3
  • internal/console/plancaps.go +7 −3
  • internal/console/recordlock.go +5 −0
  • internal/console/server.go +68 −56
  • internal/console/settle.go +3 −0
  • internal/console/store.go +4 −2
  • internal/console/store_gate.go +1 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>bzxaabb6o</task-id> <tool-use-id>toolu_01QkDWSVAR9vQpNYMqtiGUsg</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/bzxaabb6o.output</output-file> <status>completed</status> <summary>Background command "amadan task set 564 -status Started &gt;/dev/null; echo "Task 1: dispatched BASE 00785917 (codex t1)" &gt;&gt; .superpowers/sdd/2026-11-04-agent-start-demo-3-claim/progress.md S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t1.done ]; do sleep 30; done; tail -2 $S/t1.log" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a6cf2a4b8b37a6fe0</task-id> <tool-use-id>toolu_01KL48CG2bvWpwKwJUCGxHkS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a6cf2a4b8b37a6fe0.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (Opus)" 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>1) **Spec compliance: ✅** - **Endpoints and gate.** All four agent routes are registered (apidemo.go:272-275). GET `/demo/claim` is unchanged. Every handler goes through `demoClaimGate` (demo_claim_auth.go:39). That gate sets no-store, refuses when the R5 switch `demoClaimEnabled()` is off (demo_claim_auth.go:17), then applies the origin check. - **Start order matches `handleContinue`.** The order is: submit cap, Keymail discovery, `mailReady`, then `signinSend` / `HoldEmailChallenge` (demo_claim_auth.go:136-184, compared against server.go:3813-3866). So the no-mailer 503 comes before any send-limit decision, and the public-lookup failure falls back to email through the shared `keymailAddress`. - **Shared limits.** Claims use the same `s.limits` methods as ordinary sign-in: `submit`, `signinSend`, `reserveGuess` and `newPerson`. The 5-wrong-codes-per-challenge burn comes from `TakeEmailCode`. - **Flow token storage and lifetime.** The flow token is a canonical 32-byte base64url value, and only `hashToken` of it is stored (demo_claim_store.go:31-35). Lifetime is `min(now+15m, life.ExpiresAt)` (demo_claim_store.go:93-97). A resend only reads the existing row, and its rebind check is in demo_claim_auth.go:126-129 and :172-174. - **Purpose binding.** `challengeBinding` adds `ChallengeDemoClaim` → `flow_hash` (emailsignin_store.go:103). `deleteBound`, `LiveEmailChallenge` and `HoldEmailChallenge` all filter on `purpose = ?`, and the code MAC binds to the row's link hash. A sign-in, step-up, other-flow or superseded code therefore cannot match. Ordinary `handleEmailCode` only reads `ChallengeSignIn`, so claim codes cannot reach `finishSignin`. - **Atomic consume.** `TakeEmailCode` / `TakeEmailLink` consume atomically. `proveDemoClaim` then does a conditional `UPDATE ... WHERE person=''`, rechecking generation, lifetime and expiry in SQL, under the flow lock and the demo lock (demo_claim_auth.go:240-298). Exactly one proof results. - **Email link.** GET only peeks and renders a page (demo_claim_auth.go:346). POST passes the existing nonce/cookie/sameOrigin check, then the claim's own scheme+host check, then dispatches by purpose before the `finishSignin` branch (emailsignin.go dispatch hunk). - **No credentials issued.** No session cookie, CLI token or grant is created. `apps.expires_at` is never written. The migration is additive (`CREATE TABLE/INDEX IF NOT EXISTS`). The new table is classified in `claimSQLTables` and in the mutation inventory. - **Strict JSON.** Body capped at 4 KiB, string-only exact keys, duplicates refused (including escaped spellings, since keys are decoded), trailing tokens refused. No cookies are read on agent endpoints, and no CORS headers are set. - **Extra files are justified.** store_gate.go, claim_invariant_test.go (required by the census classification) and demo_claim_copy.go (Ruling R8). - ⚠️ I did not run the tests. The report's RED/GREEN evidence is unverified by me; the reported test bodies match the assertions in the brief. 2) **Findings** No P1. No P2. **P3-1. Mail error logging lost for all email sign-in and step-up sends.** Fault family: operability, a shared-path side effect. - Evidence: emailsignin.go `sendChallengeAsync` changed `%v` to `(%T)`. - Failure scenario: every real SMTP or provider failure on ordinary sign-in and step-up now logs only a Go type. The trigger was a hypothetical mailer that echoes the message body. - Fix: keep the error text but redact. For example, have `sendChallengeAsync` take the code and link and `strings.ReplaceAll` them out of `err.Error()`. **P3-2. Users created by claim proof get no first-sign-in record.** Fault family: audit completeness. - Evidence: demo_claim_auth.go:266 discards `created` from `ResolveSignIn`, and calls neither `auditSignInRow` nor anything equivalent. A later ordinary sign-in sees `created=false` (signinmethods_store.go:104), so the first-sign-in audit and the welcome cookie (emailsignin.go:291) never happen for that person. - Fix: audit person creation at proof, or have Task 2 do it when it mints the account. **P3-3. New-person cap refusal tells the user to request another email.** Fault family: refusal accuracy. - Evidence: demo_claim_auth.go:263-265 → verify answers 401 `demoClaimBadProof` ("Request another email") after the code was already consumed. - Failure scenario: retrying hits the same cap. Ordinary sign-in answers 429 "signup busy" here instead. - Fix: a distinct 429 with its own copy constant. **P3-4. `demoClaimAccountChoice` branches on `r.URL.Path == "/api/demo/claims/select"`.** Fault family: fragile seam. - Evidence: demo_claim_auth.go:303. - Fix: Task 2 replaces this with an explicit parameter. **P3-5. `proveDemoClaim`'s UPDATE uses `time.Now()` twice instead of the `now` it was given.** Fault family: consistency. - Evidence: demo_claim_auth.go:279. - Not exploitable, since wall clock only moves forward. **P3-6. The `otherDemo` and `otherFlow` cases test against a held, unsent challenge.** Fault family: test strength. - Evidence: in the test, the second `claimStart` for the same address falls inside the 60 s gap, so the target challenge is held rather than sent. - The binding mechanism (link-hash MAC plus purpose/flow filter) is still what refuses the code. But a sent rival challenge is never exercised. - Fix: advance `s.limits.now` past the gap before the second start. **P3-7. Nothing deletes `demo_claim_flows` rows yet.** Fault family: retention. - The report says Task 5 owns this. Make sure it is on Task 5's checklist, because flows accumulate at up to 30 per IP per hour per demo until then. 3) **Strengths** - Both the store and the proof write recheck generation, lifetime, state, purge and the token hash inside SQL, not only under the lock. - The over-submit-cap path writes nothing and returns a decoy with an identical response shape. - `HoldEmailChallenge` reuse keeps a sent code valid after a throttled resend, and the tests cover this. - The link GET is cross-site tolerant and never spends. Link POST dispatches by purpose before anything sign-in related can run. - The tests include real store reopen, plaintext-in-SQL scans, the SQL gate refusal and a stale-binding matrix. 4) **Verdict: READY**</result> <usage><subagent_tokens>121496</subagent_tokens><tool_uses>17</tool_uses><duration_ms>244941</duration_ms></usage> </task-notification>

Attributed to this commit: 9.48 g CO₂e (1,058,958 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/apiservices.go b/internal/console/apiservices.go
index 820cf11ed..5500eddfb 100644
--- a/internal/console/apiservices.go
+++ b/internal/console/apiservices.go
@@ -243,6 +243,12 @@ func (s *Server) handleAPIServiceCreate(w http.ResponseWriter, r *http.Request)
return
}
}
+ if app != "" {
+ if ref := s.demoClaimMutationRefusal(r.Context(), acct.ID, app); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ }
actor := auditActor(p, acct)
// Not trimmed: the stored form is the typed form, and a padded scope is
// refused by the grammar rather than quietly repaired (teamscope.go).
diff --git a/internal/console/claim_app_mutation.go b/internal/console/claim_app_mutation.go
index 99cee3351..c8b71acfe 100644
--- a/internal/console/claim_app_mutation.go
+++ b/internal/console/claim_app_mutation.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "errors"
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/release"
@@ -23,6 +24,9 @@ import (
// PrepareRestore, CompleteRestore, RecoverMutation).
func claimAppCall[T any](s *Server, ctx context.Context, acct *Account, app, action string, call func(context.Context) (T, error)) (T, error) {
var result T
+ if ref := s.demoClaimMutationRefusal(ctx, acct.ID, app); ref != nil {
+ return result, errors.New(ref.Msg)
+ }
if !s.cfg.HostClaim {
return call(ctx)
}
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index a80f9400a..5dc118a5b 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -183,6 +183,7 @@ type claimWindow struct {
// every writer is reached. A new boundary method or gated table fails the
// coverage step until a door reaches it or a reason is written here.
var claimWriterReasons = map[string]string{
+ "sql/demo_claim_ops": "demo claim reservations refuse claims mode; TestDemoClaimReservationSQLGate proves writes are 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/claim_route_writes.go b/internal/console/claim_route_writes.go
index 6672552d9..f540d5008 100644
--- a/internal/console/claim_route_writes.go
+++ b/internal/console/claim_route_writes.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "errors"
"time"
"github.com/carlosframework/platform/internal/release"
@@ -20,6 +21,9 @@ import (
// write below it is checked against. A caller that already holds a permitted
// context for the same app joins it rather than opening a second operation.
func (s *Server) appMutation(ctx context.Context, acct *Account, app, action string, fn func(context.Context) error) error {
+ if ref := s.demoClaimMutationRefusal(ctx, acct.ID, app); ref != nil {
+ return errors.New(ref.Msg)
+ }
return release.WithAppMutation(ctx, s.cfg.Releases, acct.Sqid, app, action, fn)
}
diff --git a/internal/console/claim_sql_auto.go b/internal/console/claim_sql_auto.go
index 43c13ada5..56915f364 100644
--- a/internal/console/claim_sql_auto.go
+++ b/internal/console/claim_sql_auto.go
@@ -12,6 +12,11 @@ import (
// mutation methods. Direct db writes remain refused. A future Store method
// receives no adapter until its scope and route fixture are reviewed.
func (s *Store) withAutoAppSQL(ctx context.Context, accountID int64, app, action string, call func(*Store) error) error {
+ if app != "" {
+ if ref := s.demoClaimMutationRefusal(ctx, accountID, app); ref != nil {
+ return errors.New(ref.Msg)
+ }
+ }
if app == "" || s.gate == nil || s.bound != nil {
return call(s)
}
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go
index 603fb0049..cb0286fe1 100644
--- a/internal/console/demo_claim_auth.go
+++ b/internal/console/demo_claim_auth.go
@@ -3,7 +3,9 @@ package console
import (
"bytes"
"context"
+ "database/sql"
"encoding/json"
+ "errors"
"fmt"
"html"
"io"
@@ -228,10 +230,10 @@ func (s *Server) handleDemoClaimVerify(w http.ResponseWriter, r *http.Request) {
}
flow, err = s.proveDemoClaim(r.Context(), flow, MethodEmail, got.Address, ip, now)
if err != nil {
- jsonError(w, 401, demoClaimBadProof)
+ s.demoClaimProofError(w, err)
return
}
- s.demoClaimAccountChoice(w, r, flow, "")
+ s.demoClaimAccountChoice(w, r, flow, "", false)
}
// Only call after an atomic email take or authenticated browser proof. Reload
@@ -261,12 +263,15 @@ func (s *Server) proveDemoClaim(ctx context.Context, flow claimFlow, method, add
return err
}
if fresh && !s.limits.newPerson(ip) {
- return ErrDemoToken
+ return errDemoClaimSignupBusy
}
- resolved, _, err := s.store.ResolveSignIn(method, addr, now)
+ resolved, created, err := s.store.ResolveSignIn(method, addr, now)
if err != nil {
return err
}
+ if created {
+ s.auditSignInRow(resolved.Address, true)
+ }
tx, err := s.store.demoTx(ctx)
if err != nil {
return err
@@ -301,13 +306,43 @@ func (s *Server) proveDemoClaim(ctx context.Context, flow claimFlow, method, add
return proved, err
}
-// Task 2 replaces this single seam with membership choice and reservation.
-func (s *Server) demoClaimAccountChoice(w http.ResponseWriter, r *http.Request, flow claimFlow, accountID string) {
- if accountID != "" || r.URL.Path == "/api/demo/claims/select" {
- jsonError(w, 503, demoClaimUnavailable)
+func (s *Server) demoClaimProofError(w http.ResponseWriter, err error) {
+ if errors.Is(err, errDemoClaimSignupBusy) {
+ jsonError(w, 429, demoClaimSignupBusy)
+ return
+ }
+ jsonError(w, 401, demoClaimBadProof)
+}
+
+func (s *Server) demoClaimAccountChoice(w http.ResponseWriter, r *http.Request, flow claimFlow, accountID string, explicit bool) {
+ if explicit && accountID == "" {
+ http.NotFound(w, r)
+ return
+ }
+ acct, choices, err := s.chooseDemoClaimAccount(r.Context(), flow, accountID)
+ if err != nil {
+ s.demoClaimAccountError(w, r, err)
+ return
+ }
+ if acct == nil {
+ accounts := make([]map[string]string, 0, len(choices))
+ for _, a := range choices {
+ accounts = append(accounts, map[string]string{"id": a.Sqid, "name": a.Name, "role": a.Role})
+ }
+ demoClaimReply(w, 200, map[string]any{"state": "account_required", "accounts": accounts})
+ return
+ }
+ rq, ref := s.newAppRegionReq(r, "", "")
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ op, err := s.reserveDemoClaim(r.Context(), flow, acct, rq)
+ if err != nil {
+ s.demoClaimAccountError(w, r, err)
return
}
- demoClaimReply(w, 200, map[string]any{"state": "account_required"})
+ demoClaimReply(w, 202, map[string]any{"state": "claiming", "phase": op.Phase, "retryAfter": 2})
}
func (s *Server) handleDemoClaimSelect(w http.ResponseWriter, r *http.Request) {
@@ -323,7 +358,7 @@ func (s *Server) handleDemoClaimSelect(w http.ResponseWriter, r *http.Request) {
demoError(w, ErrDemoToken)
return
}
- s.demoClaimAccountChoice(w, r, flow, fields["accountId"])
+ s.demoClaimAccountChoice(w, r, flow, fields["accountId"], true)
}
func (s *Server) handleDemoClaimStatus(w http.ResponseWriter, r *http.Request) {
@@ -335,11 +370,18 @@ func (s *Server) handleDemoClaimStatus(w http.ResponseWriter, r *http.Request) {
demoError(w, ErrDemoToken)
return
}
- flow, err := s.store.demoClaimFlow(r.Context(), strings.TrimPrefix(auth, "Bearer "), time.Now())
+ flow, err := s.store.demoClaimStatusFlow(r.Context(), strings.TrimPrefix(auth, "Bearer "), time.Now())
if err != nil {
demoError(w, ErrDemoToken)
return
}
+ if op, err := s.store.demoClaimOpForFlow(r.Context(), flow.Hash); err == nil {
+ demoClaimReply(w, 202, map[string]any{"state": "claiming", "phase": op.Phase, "retryAfter": 2})
+ return
+ } else if !errors.Is(err, sql.ErrNoRows) {
+ jsonError(w, 503, demoClaimUnavailable)
+ return
+ }
state := "email_required"
if flow.Person != "" {
state = "account_required"
@@ -387,7 +429,7 @@ func (s *Server) demoClaimLink(w http.ResponseWriter, r *http.Request, link stri
return
}
if _, err = s.proveDemoClaim(r.Context(), flow, MethodEmail, c.Address, s.clientIP(r), now); err != nil {
- jsonError(w, 401, demoClaimBadProof)
+ s.demoClaimProofError(w, err)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
diff --git a/internal/console/demo_claim_auth_test.go b/internal/console/demo_claim_auth_test.go
index f0b858794..1975e085a 100644
--- a/internal/console/demo_claim_auth_test.go
+++ b/internal/console/demo_claim_auth_test.go
@@ -1,6 +1,8 @@
package console
import (
+ "crypto/ed25519"
+ "crypto/rand"
"encoding/json"
"fmt"
"net/http"
@@ -18,6 +20,12 @@ func claimTestServer(t *testing.T) (*Server, *fakeConsoleMail, string) {
t.Helper()
s := demoTestServer(t)
s.demoClaimTestEnabled = true
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.cfg.ReleasePub = pub
+ s.cfg.Key = priv
s.cfg.Origin = "https://console.example.com"
m := &fakeConsoleMail{ready: true}
s.consoleMail = m
@@ -144,7 +152,7 @@ func TestDemoClaimProofBinding(t *testing.T) {
wg.Add(1)
go func() {
defer wg.Done()
- if claimVerify(s, flow, code).Code == 200 {
+ if claimVerify(s, flow, code).Code == 202 {
successes.Add(1)
}
}()
@@ -223,7 +231,7 @@ func TestDemoClaimEmailPrivacy(t *testing.T) {
t.Fatalf("privacy %d %s", w.Code, w.Body)
}
}
- if claimVerify(s, flow, code).Code != 200 {
+ if claimVerify(s, flow, code).Code != 202 {
t.Fatal("throttled resend destroyed sent challenge")
}
t.Run("noMailer", func(t *testing.T) {
@@ -350,7 +358,7 @@ func TestDemoClaimSharedLimits(t *testing.T) {
done(false)
}
}
- if claimVerify(s, flow, code).Code == 200 {
+ if claimVerify(s, flow, code).Code == 202 {
t.Fatal("guess limit bypassed")
}
claimNoProof(t, s, flow)
@@ -474,15 +482,15 @@ func TestDemoClaimProofStatusAndSelection(t *testing.T) {
if w := status("Bearer " + flow); w.Code != 200 || !strings.Contains(w.Body.String(), "email_required") {
t.Fatalf("unproved status %d %s", w.Code, w.Body)
}
- if claimVerify(s, flow, code).Code != 200 {
+ if claimVerify(s, flow, code).Code != 202 {
t.Fatal("verify failed")
}
- if w := status("Bearer " + flow); w.Code != 200 || !strings.Contains(w.Body.String(), "account_required") || w.Header().Get("Cache-Control") != "no-store" {
+ if w := status("Bearer " + flow); w.Code != 202 || !strings.Contains(w.Body.String(), "claiming") || w.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("proved status %d %s", w.Code, w.Body)
}
w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": flow, "accountId": "shop"})
- if w.Code != 503 || !strings.Contains(w.Body.String(), "unavailable") {
- t.Fatalf("selection stub %d %s", w.Code, w.Body)
+ if w.Code != 404 {
+ t.Fatalf("foreign selection %d %s", w.Code, w.Body)
}
for _, path := range []string{"/api/demo/claims", "/api/demo/claims/verify", "/api/demo/claims/select", "/api/demo/claims/status"} {
s.demoClaimTestEnabled = false
diff --git a/internal/console/demo_claim_caps_test.go b/internal/console/demo_claim_caps_test.go
new file mode 100644
index 000000000..024bebc13
--- /dev/null
+++ b/internal/console/demo_claim_caps_test.go
@@ -0,0 +1,111 @@
+package console
+
+import (
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+func TestDemoClaimAccountRaceOrdinaryCreate(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ s.cfg.PlanCatalog = examplePlanCatalog(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ // Leave only two slots, so the claim and ordinary create cannot both fit.
+ if _, err := s.store.CreateAppIn(a.ID, "existing", f.Person, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() {
+ defer wg.Done()
+ if _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}); err != nil && !isPlanCap(err) {
+ t.Error(err)
+ }
+ }()
+ go func() {
+ defer wg.Done()
+ defer s.planLock(a)()
+ if err := s.checkCreateApp(t.Context(), a, "ordinary"); err == nil {
+ if _, err := s.store.CreateAppIn(a.ID, "ordinary", f.Person, time.Now()); err != nil {
+ t.Error(err)
+ }
+ }
+ }()
+ wg.Wait()
+ if n, err := s.runningThings(t.Context(), a); err != nil || n > 3 || n < 2 {
+ t.Fatalf("overbooked %d %v", n, err)
+ }
+}
+func TestDemoClaimReservationCaps(t *testing.T) {
+ for _, on := range []bool{false, true} {
+ t.Run(map[bool]string{true: "plansOn", false: "plansOff"}[on], func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ if on {
+ s.cfg.PlanCatalog = examplePlanCatalog(t)
+ }
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ for _, app := range []string{"one", "two"} {
+ if _, err := s.store.CreateAppIn(a.ID, app, f.Person, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if on {
+ if !isPlanCap(err) {
+ t.Fatalf("cap: %v", err)
+ }
+ if _, err := s.store.LookupDemoToken(t.Context(), token); err != nil {
+ t.Fatal(err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.cfg.Releases.Put(t.Context(), provision.RecordKey(a.Sqid, op.Target.App, op.Target.Host), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 4 {
+ t.Fatalf("record double count %d %v", n, err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE apps SET deleted_at=1 WHERE account_id=? AND app=?`, a.ID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 4 {
+ t.Fatalf("lost reservation on partial cleanup %d %v", n, err)
+ }
+ })
+ }
+}
+
+func TestDemoClaimAccountsFreeAccountAllowance(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ s.cfg.PlanCatalog = examplePlanCatalog(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a, _, err := s.chooseDemoClaimAccount(t.Context(), f, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !isPlanCap(s.checkNewFreeAccount(f.Person)) {
+ t.Fatal("personal account did not consume ordinary free allowance")
+ }
+ again, _, err := s.chooseDemoClaimAccount(t.Context(), f, "")
+ if err != nil || again.ID != a.ID {
+ t.Fatalf("selected another free account: %v %v", again, err)
+ }
+ // A refused exact choice cannot become an instruction to mint another account.
+ if _, _, err := s.chooseDemoClaimAccount(t.Context(), f, "missing"); err == nil {
+ t.Fatal("foreign selection accepted")
+ }
+ accounts, err := s.store.AccountsFor(f.Person)
+ if err != nil || len(accounts) != 1 {
+ t.Fatalf("extra allowance: %v %v", accounts, err)
+ }
+ if _, err := s.store.LookupDemoToken(t.Context(), token); err != nil {
+ t.Fatal("selection refusal consumed source", err)
+ }
+}
diff --git a/internal/console/demo_claim_copy.go b/internal/console/demo_claim_copy.go
index 5a8fad54b..a74ed60ea 100644
--- a/internal/console/demo_claim_copy.go
+++ b/internal/console/demo_claim_copy.go
@@ -1,6 +1,15 @@
package console
const (
+ // CLAIM-PROOF: new-person signup budget exhausted after proof consumption.
+ demoClaimSignupBusy = "Too many new accounts have been made from here in the last hour. Try again later."
+ // CLAIM-BUSY: pending destination mutation refusal.
+ demoClaimPending = "This app is being claimed. Try again when the claim finishes."
+ // CLAIM-PLACEMENT: unsupported normal placement.
+ demoClaimPlacement = "This demo cannot be kept in the selected region yet. The demo is still running."
+ // CLAIM-PLACEMENT: reservation or retry failure.
+ demoClaimReserveFailed = "The destination could not be prepared. Try again."
+
// CLAIM-PROOF: closed admission and unwired selection.
demoClaimUnavailable = "unavailable"
// CLAIM-PROOF: invalid request shape.
diff --git a/internal/console/demo_claim_store.go b/internal/console/demo_claim_store.go
index 38268fedb..396edc1ca 100644
--- a/internal/console/demo_claim_store.go
+++ b/internal/console/demo_claim_store.go
@@ -22,7 +22,16 @@ func (s *Store) migrateDemoClaims() error {
generation INTEGER NOT NULL, address TEXT NOT NULL,
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 INDEX IF NOT EXISTS demo_claim_flows_demo ON demo_claim_flows(demo_id);
+ 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,
+ version TEXT NOT NULL, artifact_sha256 TEXT NOT NULL, phase TEXT NOT NULL,
+ generation INTEGER NOT NULL, account_id INTEGER NOT NULL, target_sqid TEXT NOT NULL,
+ app TEXT NOT NULL, host TEXT NOT NULL, target_lifetime TEXT NOT NULL,
+ region TEXT NOT NULL, seed_id TEXT NOT NULL, deadline INTEGER NOT NULL, source_expires_at INTEGER NOT NULL);
+ CREATE UNIQUE INDEX IF NOT EXISTS demo_claim_flow_active ON demo_claim_ops(flow_hash) WHERE flow_hash != '';
+ CREATE UNIQUE INDEX IF NOT EXISTS demo_claim_active ON demo_claim_ops(demo_id) WHERE phase != 'aborted';`)
return err
}
@@ -96,3 +105,123 @@ func newDemoClaimFlow(raw, address string, d DemoRow, life AppLife, now time.Tim
f := claimFlow{Hash: hashToken(raw), DemoID: d.ID, Lifetime: life.Lifetime, Generation: d.Generation, Address: address, ExpiresAt: time.Unix(expires, 0)}
return f
}
+
+const demoClaimOpColumns = `id,flow_hash,demo_id,source_lifetime,source_box,person,version,artifact_sha256,phase,generation,account_id,target_sqid,app,host,target_lifetime,region,seed_id,deadline,source_expires_at`
+
+func scanDemoClaimOp(row interface{ Scan(...any) error }) (claimOp, error) {
+ var op claimOp
+ var deadline int64
+ err := row.Scan(&op.ID, &op.FlowHash, &op.DemoID, &op.SourceLifetime, &op.SourceBox, &op.Person, &op.Version, &op.ArtifactSHA256, &op.Phase, &op.Generation, &op.Target.AccountID, &op.Target.Sqid, &op.Target.App, &op.Target.Host, &op.Target.Lifetime, &op.Target.Region, &op.Target.SeedID, &deadline, &op.SourceExpiresAt)
+ op.Deadline = time.Unix(deadline, 0)
+ return op, err
+}
+func (s *Store) demoClaimOpForFlow(ctx context.Context, hash string) (claimOp, error) {
+ return scanDemoClaimOp(s.db.QueryRowContext(ctx, `SELECT `+demoClaimOpColumns+` FROM demo_claim_ops WHERE flow_hash=?`, hash))
+}
+
+// Writer-lock rechecks prevent a removed membership, expired flow or competing
+// claim from leaving either a partial app row or an uncharged destination.
+func (s *Store) reserveDemoClaimRows(ctx context.Context, f claimFlow, op claimOp, source string) (claimOp, error) {
+ tx, err := s.demoTx(ctx)
+ if err != nil {
+ return claimOp{}, err
+ }
+ defer tx.Rollback()
+ if !demoServingEnabled(ctx, tx) {
+ return claimOp{}, ErrDemoToken
+ }
+ var n int
+ err = tx.QueryRowContext(ctx, `SELECT count(*) FROM memberships m JOIN accounts a ON a.id=m.account_id
+ WHERE a.id=? AND a.sqid=? AND a.deleted_at=0 AND m.address=? AND m.role IN ('owner','member')`, op.Target.AccountID, op.Target.Sqid, op.Person).Scan(&n)
+ if err != nil {
+ return claimOp{}, err
+ }
+ if n != 1 {
+ return claimOp{}, errDemoClaimAccount
+ }
+ now := time.Now()
+ err = tx.QueryRowContext(ctx, `SELECT a.expires_at,d.assigned_box,d.generation FROM demo_claim_flows f JOIN demo_apps d ON d.demo_id=f.demo_id
+ JOIN apps a ON a.account_id=d.account_id AND a.app=d.app
+ WHERE f.hash=? AND f.person=? AND f.demo_id=? AND f.lifetime=? AND f.generation=? AND f.expires_at>?
+ AND a.demo_id=d.demo_id AND a.lifetime=f.lifetime AND d.generation=f.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 AND d.active_job_id=''`,
+ f.Hash, f.Person, f.DemoID, f.Lifetime, f.Generation, now.Unix(), now.Unix()).Scan(&op.SourceExpiresAt, &op.SourceBox, &op.Generation)
+ if errors.Is(err, sql.ErrNoRows) {
+ return claimOp{}, ErrDemoToken
+ }
+ if err != nil {
+ return claimOp{}, err
+ }
+ if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM demo_claim_ops WHERE demo_id=? AND phase!='aborted'`, f.DemoID).Scan(&n); err != nil {
+ return claimOp{}, err
+ }
+ if n != 0 {
+ return claimOp{}, ErrDemoBusy
+ }
+ op.Deadline = now.Add(5 * time.Minute)
+ if op.Deadline.Unix() > op.SourceExpiresAt {
+ op.Deadline = time.Unix(op.SourceExpiresAt, 0)
+ }
+ created, err := insertAppRow(tx, newAppRow{AccountID: op.Target.AccountID, App: op.Target.App, CreatedBy: op.Person, CreatedAt: now.Unix(), Region: op.Target.Region, RegionSource: source, DemoClaimOp: op.ID})
+ if err != nil {
+ return claimOp{}, err
+ }
+ if !created {
+ return claimOp{}, ErrDemoNameTaken
+ }
+ if err = tx.QueryRowContext(ctx, `SELECT lifetime FROM apps WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App).Scan(&op.Target.Lifetime); err != nil {
+ return claimOp{}, err
+ }
+ _, err = tx.ExecContext(ctx, `INSERT INTO demo_claim_ops (`+demoClaimOpColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, op.ID, op.FlowHash, op.DemoID, op.SourceLifetime, op.SourceBox, op.Person, op.Version, op.ArtifactSHA256, op.Phase, op.Generation, op.Target.AccountID, op.Target.Sqid, op.Target.App, op.Target.Host, op.Target.Lifetime, op.Target.Region, op.Target.SeedID, op.Deadline.Unix(), op.SourceExpiresAt)
+ if err != nil {
+ return claimOp{}, err
+ }
+ if err = tx.Commit(); err != nil {
+ return claimOp{}, err
+ }
+ return op, nil
+}
+
+// Only subtract things the caller's ordinary count actually included. A
+// missing/trashed app still reserves both slots until cleanup is confirmed.
+func (s *Store) demoClaimReservedThings(ctx context.Context, accountID int64, live map[string]bool, records map[string]bool) (int, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT app,host FROM demo_claim_ops WHERE account_id=? AND phase NOT IN ('done','aborted')`, accountID)
+ if err != nil {
+ return 0, err
+ }
+ defer rows.Close()
+ extra := 0
+ for rows.Next() {
+ var app, host string
+ if err := rows.Scan(&app, &host); err != nil {
+ return 0, err
+ }
+ extra += 2
+ if live[app] {
+ extra--
+ if records[app+"/"+host] {
+ extra--
+ }
+ }
+ }
+ return extra, rows.Err()
+}
+
+func (s *Store) demoClaimStatusFlow(ctx context.Context, raw string, now time.Time) (claimFlow, error) {
+ b, err := base64.RawURLEncoding.Strict().DecodeString(raw)
+ if err != nil || len(b) != 32 || base64.RawURLEncoding.EncodeToString(b) != raw || s.claimGated() {
+ return claimFlow{}, ErrDemoToken
+ }
+ hash := hashToken(raw)
+ op, err := s.demoClaimOpForFlow(ctx, hash)
+ if errors.Is(err, sql.ErrNoRows) {
+ return s.demoClaimFlowByHash(ctx, hash, now)
+ }
+ if err != nil {
+ return claimFlow{}, err
+ }
+ if now.Unix() >= op.SourceExpiresAt+int64((24*time.Hour).Seconds()) {
+ return claimFlow{}, ErrDemoToken
+ }
+ return claimFlow{Hash: hash, DemoID: op.DemoID, Lifetime: op.SourceLifetime, Generation: op.Generation, Person: op.Person}, nil
+}
diff --git a/internal/console/demo_claim_store_test.go b/internal/console/demo_claim_store_test.go
index a49f3dfc5..0f2e7da82 100644
--- a/internal/console/demo_claim_store_test.go
+++ b/internal/console/demo_claim_store_test.go
@@ -82,7 +82,7 @@ func TestDemoClaimCodeRestart(t *testing.T) {
claimStart(t, s, token, "shop@example.com", flow)
fresh, _ := claimMail(t, s, m)
w := claimVerify(s, flow, fresh)
- if w.Code != 200 {
+ if w.Code != 202 {
t.Fatalf("fresh resend %d %s", w.Code, w.Body)
}
if len(w.Result().Cookies()) != 0 {
@@ -167,7 +167,7 @@ func TestDemoClaimProofIdentity(t *testing.T) {
}
flow, _ := claimStart(t, s, token, " Shop@Example.COM ", "")
code, _ := claimMail(t, s, m)
- if w := claimVerify(s, flow, code); w.Code != 200 {
+ if w := claimVerify(s, flow, code); w.Code != 202 {
t.Fatalf("verify %d %s", w.Code, w.Body)
}
f, err := s.store.demoClaimFlow(t.Context(), flow, time.Now())
@@ -175,8 +175,8 @@ func TestDemoClaimProofIdentity(t *testing.T) {
t.Fatalf("resolved person %+v %v", f, err)
}
accounts, err := s.store.AccountsFor(f.Person)
- if err != nil || len(accounts) != 0 {
- t.Fatalf("minted account: %+v %v", accounts, err)
+ if err != nil || len(accounts) != 1 {
+ t.Fatalf("personal account: %+v %v", accounts, err)
}
})
t.Run("newPersonCap", func(t *testing.T) {
@@ -188,8 +188,8 @@ func TestDemoClaimProofIdentity(t *testing.T) {
}
flow, _ := claimStart(t, s, token, "shop@example.com", "")
code, _ := claimMail(t, s, m)
- if claimVerify(s, flow, code).Code == 200 {
- t.Fatal("new-person cap bypassed")
+ if w := claimVerify(s, flow, code); w.Code != 429 || !strings.Contains(w.Body.String(), demoClaimSignupBusy) {
+ t.Fatalf("new-person cap: %d %s", w.Code, w.Body)
}
claimNoProof(t, s, flow)
fresh, err := s.store.PersonWouldBeNew(MethodEmail, "shop@example.com")
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go
new file mode 100644
index 000000000..3e7436a24
--- /dev/null
+++ b/internal/console/demo_claim_target.go
@@ -0,0 +1,290 @@
+package console
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "sort"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+type claimTarget struct {
+ AccountID int64
+ Sqid, App, Host, Lifetime, Region, SeedID string
+}
+type claimOp struct {
+ ID, FlowHash, DemoID, SourceLifetime, SourceBox, Person, Version, ArtifactSHA256, Phase string
+ Generation int64
+ Target claimTarget
+ Deadline time.Time
+ SourceExpiresAt int64
+}
+
+var (
+ errDemoClaimAccount = errors.New("demo claim: account not found")
+ errDemoClaimSignupBusy = errors.New("demo claim: signup busy")
+ errDemoClaimPlacement = errors.New(demoClaimPlacement)
+)
+
+// 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) {
+ if !s.demoClaimEnabled() {
+ return nil, nil, errors.New(demoClaimUnavailable)
+ }
+ defer s.acctLocks.lock("person:" + f.Person)()
+ fresh, err := s.store.demoClaimFlowByHash(ctx, f.Hash, time.Now())
+ if err != nil || fresh.Person == "" || fresh.Person != f.Person {
+ return nil, nil, ErrDemoToken
+ }
+ accounts, err := s.store.AccountsFor(fresh.Person)
+ if err != nil {
+ return nil, nil, err
+ }
+ if selected != "" {
+ for _, a := range accounts {
+ if a.Sqid == selected {
+ return &a, nil, nil
+ }
+ }
+ return nil, nil, errDemoClaimAccount
+ }
+ switch len(accounts) {
+ case 0:
+ if err := s.checkNewFreeAccount(fresh.Person); err != nil {
+ return nil, nil, err
+ }
+ a, err := s.mintAccount(ctx, fresh.Person, fresh.Person)
+ return a, nil, err
+ case 1:
+ return &accounts[0], nil, nil
+ default:
+ return nil, accounts, nil
+ }
+}
+
+// Task 5 installs the worker, seed and edge capability floor here before freeze.
+func (s *Server) demoClaimCapabilitiesReady(context.Context) error { return nil }
+
+// Reservation writes only a fresh, private destination. Transfer and publication
+// are owned by the later coordinator. The account lock shares normal create caps.
+func (s *Server) reserveDemoClaim(ctx context.Context, f claimFlow, acct *Account, rq regionReq) (claimOp, error) {
+ if !s.demoClaimEnabled() {
+ return claimOp{}, errors.New(demoClaimUnavailable)
+ }
+ if acct == nil {
+ return claimOp{}, errDemoClaimAccount
+ }
+ defer s.lockAccount(acct.Sqid)()
+ // Selection is not authority: resolve membership again after taking the lock.
+ accounts, err := s.store.AccountsFor(f.Person)
+ if err != nil {
+ return claimOp{}, err
+ }
+ var current *Account
+ for _, a := range accounts {
+ if a.ID == acct.ID && a.Sqid == acct.Sqid {
+ current = &a
+ break
+ }
+ }
+ if current == nil {
+ return claimOp{}, errDemoClaimAccount
+ }
+ acct = current
+ if op, err := s.store.demoClaimOpForFlow(ctx, f.Hash); err == nil {
+ if op.Person != f.Person || op.Target.AccountID != acct.ID || op.DemoID != f.DemoID {
+ return claimOp{}, errDemoClaimAccount
+ }
+ return op, s.finishDemoClaimReservation(ctx, op)
+ } else if !errors.Is(err, sql.ErrNoRows) {
+ return claimOp{}, err
+ }
+ fresh, err := s.store.demoClaimFlowByHash(ctx, f.Hash, time.Now())
+ if err != nil || fresh.Person == "" || fresh.Person != f.Person {
+ return claimOp{}, ErrDemoToken
+ }
+ f = fresh
+ d, err := s.store.demoByID(ctx, f.DemoID)
+ if err != nil {
+ return claimOp{}, err
+ }
+ if d.ActiveJobID != "" {
+ return claimOp{}, ErrDemoBusy
+ }
+ if err = s.checkRunningThings(ctx, acct, 2); err != nil {
+ return claimOp{}, err
+ }
+ if rq.hasExplicit {
+ region, ref := s.validateExplicitRegion(ctx, rq.explicit)
+ if ref != nil {
+ return claimOp{}, errDemoClaimPlacement
+ }
+ rq.explicit = region
+ }
+ region, source := s.resolveNewAppRegion(ctx, rq, false)
+ // Never silently replace an incompatible normal placement with the home.
+ if region != s.cfg.Region || s.haRegion(region) || s.cfg.HostClaim || s.cfg.AppsDomain == "" {
+ return claimOp{}, errDemoClaimPlacement
+ }
+ if err = s.roomIn(ctx, region, ""); err != nil {
+ return claimOp{}, errDemoClaimPlacement
+ }
+ if err = s.demoClaimCapabilitiesReady(ctx); err != nil {
+ return claimOp{}, err
+ }
+ id, err := demobuild.NewJobID()
+ if err != nil {
+ return claimOp{}, err
+ }
+ seed, err := seeds.NewID()
+ if err != nil {
+ return claimOp{}, err
+ }
+ for attempt := 0; attempt <= 16; attempt++ {
+ name := d.Name
+ if attempt > 0 {
+ h := sha256.Sum256([]byte(fmt.Sprintf("%s%d", id, attempt)))
+ name = fmt.Sprintf("%s-%x", d.Name, h[:4])
+ }
+ // A sibling instance writer holds the same account/app/hostname order.
+ keys := [][2]string{{d.AccountSqid, d.App}, {acct.Sqid, name}}
+ sort.Slice(keys, func(i, j int) bool {
+ if keys[i][0] != keys[j][0] {
+ return keys[i][0] < keys[j][0]
+ }
+ return keys[i][1] < keys[j][1]
+ })
+ unlockA := s.lockApp(keys[0][0], keys[0][1])
+ unlockB := s.lockApp(keys[1][0], keys[1][1])
+ host := s.apexHost(acct.Sqid, name)
+ unlockHost := s.lockHostname(host)
+ op, err := func() (claimOp, error) {
+ outcome, _, _ := s.validateClaimAppName(ctx, acct, name, "", false, time.Time{})
+ switch outcome {
+ case claimOK:
+ case claimTaken, claimApexHeld:
+ return claimOp{}, ErrDemoNameTaken
+ default:
+ return claimOp{}, errors.New(demoClaimReserveFailed)
+ }
+ // A leftover policy is occupied state too. Select a fresh suffix so
+ // createClaimAppRow never needs an external clear before reservation.
+ if present, err := s.appPolicyPresent(ctx, acct, name); err != nil {
+ return claimOp{}, err
+ } else if present {
+ return claimOp{}, ErrDemoNameTaken
+ }
+ op := claimOp{ID: id, FlowHash: f.Hash, DemoID: f.DemoID, SourceLifetime: f.Lifetime, SourceBox: d.AssignedBox, Person: f.Person, Generation: f.Generation, Phase: "reserved", Target: claimTarget{AccountID: acct.ID, Sqid: acct.Sqid, App: name, Host: host, Region: region, SeedID: seed}}
+ // The current schema keeps published binary identity in release metadata.
+ // An unpublished demo leaves these empty; Task 5 must re-pin before freeze.
+ ptr, e := release.Channel(ctx, s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, "edge")
+ if e != nil && !errors.Is(e, os.ErrNotExist) {
+ return claimOp{}, e
+ }
+ if e == nil && ptr != nil && ptr.Version != "" {
+ m, e := release.GetManifest(ctx, s.cfg.Releases, d.AccountSqid, d.App, ptr.Version)
+ if e != nil {
+ return claimOp{}, e
+ }
+ op.Version = ptr.Version
+ op.ArtifactSHA256 = m.Artifacts["linux-arm64"].SHA256
+ }
+ created, e := s.createClaimAppRow(ctx, acct, name, func(st *Store) (bool, error) {
+ var e error
+ op, e = st.reserveDemoClaimRows(ctx, f, op, source)
+ return e == nil, e
+ })
+ if e != nil {
+ return claimOp{}, e
+ }
+ if !created {
+ return claimOp{}, ErrDemoNameTaken
+ }
+ return op, nil
+ }()
+ unlockHost()
+ unlockB()
+ unlockA()
+ if errors.Is(err, ErrDemoNameTaken) {
+ continue
+ }
+ if err != nil {
+ return claimOp{}, err
+ }
+ return op, s.finishDemoClaimReservation(ctx, op)
+ }
+ return claimOp{}, errors.New(demoClaimReserveFailed)
+}
+
+func (s *Server) finishDemoClaimReservation(ctx context.Context, op claimOp) error {
+ // The durable reservation and marker already exist. A failed external write
+ // retains both slots. Retrying writes the same default pipeline and target.
+ if op.Phase != "reserved" {
+ return nil
+ }
+ _, err := release.SetPipeline(withDemoClaimOperation(ctx, op.ID), s.cfg.Releases, s.cfg.Key, op.Target.Sqid, op.Target.App, release.DefaultPipelineChannels(), op.Person)
+ return err
+}
+
+type demoClaimOperationKey struct{}
+
+func withDemoClaimOperation(ctx context.Context, id string) context.Context {
+ return context.WithValue(ctx, demoClaimOperationKey{}, id)
+}
+
+func (s *Store) demoClaimMutationRefusal(ctx context.Context, accountID int64, app string) *doorRefusal {
+ var id string
+ err := s.db.QueryRowContext(ctx, `SELECT demo_claim_op FROM apps WHERE account_id=? AND app=?`, accountID, app).Scan(&id)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return &doorRefusal{Status: 503, Msg: demoClaimUnavailable}
+ }
+ if id != "" && ctx.Value(demoClaimOperationKey{}) != id {
+ return &doorRefusal{Status: 409, Msg: demoClaimPending}
+ }
+ return nil
+}
+func (s *Server) demoClaimMutationRefusal(ctx context.Context, accountID int64, app string) *doorRefusal {
+ return s.store.demoClaimMutationRefusal(ctx, accountID, app)
+}
+
+func (s *Server) demoClaimAccountError(w http.ResponseWriter, r *http.Request, err error) {
+ switch {
+ case errors.Is(err, errDemoClaimAccount):
+ http.NotFound(w, r)
+ case isPlanCap(err):
+ demoClaimReply(w, 409, map[string]string{"error": err.Error(), "code": "cap"})
+ case errors.Is(err, errDemoClaimPlacement):
+ jsonError(w, 409, demoClaimPlacement)
+ case errors.Is(err, ErrDemoBusy):
+ jsonError(w, 409, demoClaimPending)
+ default:
+ jsonError(w, 503, demoClaimReserveFailed)
+ }
+}
+
+// Lifecycle paths have a sqid rather than an account row. Resolve it before
+// applying the same pending marker check used at the authenticated doors.
+func (s *Server) demoClaimAppMutationError(ctx context.Context, sqid, app string) error {
+ acct, err := s.store.AccountBySqid(sqid)
+ if err != nil {
+ return err
+ }
+ if acct == nil {
+ return nil
+ }
+ if ref := s.demoClaimMutationRefusal(ctx, acct.ID, app); ref != nil {
+ return errors.New(ref.Msg)
+ }
+ return nil
+}
diff --git a/internal/console/demo_claim_target_test.go b/internal/console/demo_claim_target_test.go
new file mode 100644
index 000000000..e8f951454
--- /dev/null
+++ b/internal/console/demo_claim_target_test.go
@@ -0,0 +1,467 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func claimProved(t *testing.T, s *Server, token, person string) (claimFlow, string) {
+ t.Helper()
+ d, err := s.store.LookupDemoToken(t.Context(), token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ life, err := s.store.AppLife(d.AccountID, d.App)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := randomToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := s.store.createDemoClaimFlow(t.Context(), raw, person, d, *life, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err = s.proveDemoClaim(t.Context(), f, MethodEmail, person, "192.0.2.10", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return f, raw
+}
+func claimAccount(t *testing.T, s *Server, id int64, person, role string) *Account {
+ t.Helper()
+ sqid := domains.Sqid(id)
+ owner := person
+ if role != RoleOwner {
+ owner = "owner@example.com"
+ }
+ if err := s.store.CreateAccount(id, sqid, "shop", owner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if role != RoleOwner {
+ if err := s.store.AddMember(id, person, role, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return &Account{ID: id, Sqid: sqid, Name: "shop", Role: role}
+}
+func TestDemoClaimAccounts(t *testing.T) {
+ for _, n := range []int{0, 1, 2} {
+ t.Run(fmt.Sprint(n), func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ for i := 0; i < n; i++ {
+ claimAccount(t, s, int64(501+i), f.Person, RoleMember)
+ }
+ if n > 0 {
+ if err := s.store.SetLastAccount(f.Person, 501); err != nil {
+ t.Fatal(err)
+ }
+ }
+ a, choices, err := s.chooseDemoClaimAccount(t.Context(), f, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n == 2 {
+ if a != nil || len(choices) != 2 {
+ t.Fatalf("implicit choice: %v %v", a, choices)
+ }
+ for _, choice := range choices {
+ if apps, err := s.store.AppsIn(choice.ID); err != nil || len(apps) != 0 {
+ t.Fatalf("created before choice: %v %v", apps, err)
+ }
+ }
+ a, _, err = s.chooseDemoClaimAccount(t.Context(), f, choices[1].Sqid)
+ if err != nil || a == nil || a.ID != choices[1].ID {
+ t.Fatalf("exact choice: %v %v", a, err)
+ }
+ } else if a == nil {
+ t.Fatal("no account")
+ }
+ if n == 0 {
+ as, err := s.store.AccountsFor(f.Person)
+ if err != nil || len(as) != 1 || as[0].Name != f.Person {
+ t.Fatalf("personal accounts: %v %v", as, err)
+ }
+ }
+ })
+ }
+ t.Run("foreignDeletedAndNameIdentical404", func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, raw := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ claimAccount(t, s, 502, "other@example.com", RoleOwner)
+ if _, err := s.store.db.Exec(`UPDATE accounts SET deleted_at=1 WHERE id=?`, a.ID); err != nil {
+ t.Fatal(err)
+ }
+ var body string
+ for _, id := range []string{domains.Sqid(501), domains.Sqid(502), "missing", "shop", ""} {
+ w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": raw, "accountId": id})
+ if w.Code != 404 {
+ t.Fatalf("%q: %d %s", id, w.Code, w.Body)
+ }
+ if body != "" && body != w.Body.String() {
+ t.Fatal("account oracle")
+ }
+ body = w.Body.String()
+ }
+ })
+}
+func TestDemoClaimAccountRace(t *testing.T) {
+ t.Run("memberRemovedAfterProof", func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleMember)
+ if err := s.store.RemoveMember(a.ID, f.Person); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}); !errors.Is(err, errDemoClaimAccount) {
+ t.Fatalf("removed member: %v", err)
+ }
+ })
+ t.Run("duplicateClaimsSamePerson", func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ var wg sync.WaitGroup
+ for range 8 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if _, _, err := s.chooseDemoClaimAccount(t.Context(), f, ""); err != nil {
+ t.Error(err)
+ }
+ }()
+ }
+ wg.Wait()
+ as, err := s.store.AccountsFor(f.Person)
+ if err != nil || len(as) != 1 {
+ t.Fatalf("accounts: %v %v", as, err)
+ }
+ })
+ t.Run("sameDemoTwoPeople", func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ g, _ := claimProved(t, s, token, "other@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ b := claimAccount(t, s, 502, g.Person, RoleOwner)
+ var wg sync.WaitGroup
+ errs := make(chan error, 2)
+ for i, x := range []claimFlow{f, g} {
+ wg.Add(1)
+ go func(f claimFlow, a *Account) {
+ defer wg.Done()
+ _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ errs <- err
+ }(x, []*Account{a, b}[i])
+ }
+ wg.Wait()
+ close(errs)
+ successes := 0
+ for err := range errs {
+ if err == nil {
+ successes++
+ }
+ }
+ if successes != 1 {
+ t.Fatalf("reservations=%d", successes)
+ }
+ })
+}
+func TestDemoClaimReservation(t *testing.T) {
+ for _, role := range []string{RoleOwner, RoleMember} {
+ t.Run(role, func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, raw := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, role)
+ d, err := s.store.LookupDemoToken(t.Context(), token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Even an owner must not adopt a name with objects but no console row.
+ if _, err = s.cfg.Releases.Put(t.Context(), release.ManifestKey(a.Sqid, d.Name, "v1.0.0"), []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if op.Target.App == d.Name || !strings.HasPrefix(op.Target.App, d.Name+"-") {
+ t.Fatalf("adopted: %+v", op)
+ }
+ life, err := s.store.AppLife(a.ID, op.Target.App)
+ if err != nil || life == nil || life.ExpiresAt != 0 || life.DemoID != "" || life.Lifetime != op.Target.Lifetime {
+ t.Fatalf("life: %+v %v", life, err)
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 2 {
+ t.Fatalf("things=%d %v", n, err)
+ }
+ if op.Phase != "reserved" || op.Deadline.After(time.Now().Add(5*time.Minute)) || op.Generation != d.Generation {
+ t.Fatalf("op: %+v", op)
+ }
+ r := httptest.NewRequest("GET", "/api/demo/claims/status", nil)
+ r.Header.Set("Authorization", "Bearer "+raw)
+ w := httptest.NewRecorder()
+ s.mux.ServeHTTP(w, r)
+ if w.Code != 202 || !strings.Contains(w.Body.String(), `"phase":"reserved"`) {
+ t.Fatalf("status: %d %s", w.Code, w.Body)
+ }
+ if _, err := s.store.LookupDemoToken(t.Context(), token); err != nil {
+ t.Fatalf("source token: %v", err)
+ }
+ })
+ }
+ t.Run("placementRefusal", func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ s.cfg.AppRegions = true
+ s.cfg.HomeRegion = "ie"
+ s.cfg.SecretsPub = testKeyPub
+ historyActive(s)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ if _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{explicit: "uk", hasExplicit: true}); err == nil {
+ t.Fatal("cross-region accepted")
+ }
+ if _, err := s.store.LookupDemoToken(t.Context(), token); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 0 {
+ t.Fatalf("refused reservation: %d %v", n, err)
+ }
+ })
+}
+func TestDemoClaimTargetIsolation(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, action := range []string{"ship", "promote", "delete", "seed", "run", "service-token", "lifecycle"} {
+ t.Run(action, func(t *testing.T) {
+ called := false
+ err := s.appMutation(t.Context(), a, op.Target.App, action, func(context.Context) error { called = true; return nil })
+ if err == nil || called {
+ t.Fatalf("pending mutation admitted: %v", err)
+ }
+ })
+ }
+ if ref := s.demoMutationRefusal(a, op.Target.App); ref == nil || ref.Status != 409 {
+ t.Fatalf("ordinary doors: %+v", ref)
+ }
+ if err := s.appMutation(withDemoClaimOperation(t.Context(), op.ID), a, op.Target.App, "claim-transfer", func(context.Context) error { return nil }); err != nil {
+ t.Fatal(err)
+ }
+ again, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if err != nil || again.ID != op.ID || again.Target != op.Target {
+ t.Fatalf("retry: %+v %v", again, err)
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 2 {
+ t.Fatalf("double charged: %d %v", n, err)
+ }
+}
+
+func TestDemoClaimReservationSQLGate(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ if _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}); err != nil {
+ t.Fatal(err)
+ }
+ gated, err := OpenGated(claimDatabasePath(t, s.store))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer gated.Close()
+ seedGateApp(t, gated)
+ if err = gated.withClaimSQL(t.Context(), []claimSQLScope{gateScope}, allowAllClaimSQL, func(v *Store) error {
+ for _, q := range []string{`UPDATE demo_claim_ops SET phase='done'`, `DELETE FROM demo_claim_ops`, `INSERT INTO demo_claim_ops SELECT * FROM demo_claim_ops`} {
+ _, err := v.db.Exec(q)
+ requireDenied(t, q, err)
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if claimSQLTables["demo_claim_ops"].Refuse == "" || claimWriterReasons["sql/demo_claim_ops"] == "" {
+ t.Fatal("missing gate inventory")
+ }
+}
+
+type claimPipelineFailure struct {
+ release.Store
+ fail bool
+}
+
+func (f *claimPipelineFailure) Put(ctx context.Context, key string, b []byte, etag string) (string, error) {
+ if f.fail && strings.HasSuffix(key, "/pipeline.json") {
+ return "", errors.New("injected pipeline failure")
+ }
+ return f.Store.Put(ctx, key, b, etag)
+}
+func TestDemoClaimTargetIsolationPartialReservation(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, raw := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ bucket := &claimPipelineFailure{Store: s.cfg.Releases, fail: true}
+ s.cfg.Releases = bucket
+ if _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}); err == nil {
+ t.Fatal("expected external write failure")
+ }
+ op, err := s.store.demoClaimOpForFlow(t.Context(), f.Hash)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 2 {
+ t.Fatalf("failed request released reservation: %d %v", n, err)
+ }
+ if err := s.store.TrashAppRow(a.ID, op.Target.App, time.Now()); err == nil {
+ t.Fatal("SQL lifecycle bypass")
+ }
+ if err := s.withRecordLock(a.Sqid, op.Target.App, func() error { t.Fatal("record lifecycle bypass"); return nil }); err == nil {
+ t.Fatal("record writer allowed")
+ }
+ if ref := s.demoClaimMutationRefusal(withDemoClaimOperation(t.Context(), "wrong"), a.ID, op.Target.App); ref == nil {
+ t.Fatal("foreign op admitted")
+ }
+ bucket.fail = false
+ got, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if err != nil || got.ID != op.ID || got.Target != op.Target {
+ t.Fatalf("retry changed identity: %+v %v", got, err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_flows SET expires_at=1 WHERE hash=?`, f.Hash); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.demoClaimStatusFlow(t.Context(), raw, time.Now()); err != nil {
+ t.Fatal("status expired with proof", err)
+ }
+ if _, err := s.store.demoClaimStatusFlow(t.Context(), raw, time.Unix(op.SourceExpiresAt, 0).Add(24*time.Hour)); err == nil {
+ t.Fatal("status outlived retention")
+ }
+ if _, err := s.store.demoClaimFlow(t.Context(), raw, time.Now()); err == nil {
+ t.Fatal("expired selection allowed")
+ }
+}
+
+func TestDemoClaimTargetIsolationHTTP(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ s.cli = newCLILimits()
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range []Principal{{Kind: PrincipalUser, Address: f.Person}, {Kind: PrincipalService, AccountID: a.ID, App: op.Target.App, Name: "deployer"}} {
+ for _, method := range []string{"POST", "PUT", "DELETE"} {
+ r := httptest.NewRequest(method, "/api/cli/apps/target/app", nil)
+ r.SetPathValue("account", a.Sqid)
+ r.SetPathValue("app", op.Target.App)
+ r = r.WithContext(context.WithValue(r.Context(), cliRouteKey{}, p))
+ w := httptest.NewRecorder()
+ if _, _, _, ok := s.apiAccountApp(w, r); ok || w.Code != 409 || !strings.Contains(w.Body.String(), demoClaimPending) {
+ t.Fatalf("kind=%d method=%s: %d %s", p.Kind, method, w.Code, w.Body)
+ }
+ }
+ }
+ // Service mint names its app in the body, outside apiAccountApp's path gate.
+ r := httptest.NewRequest("POST", "/api/cli/services", strings.NewReader(fmt.Sprintf(`{"name":"deployer","role":"publish","app":%q}`, op.Target.App)))
+ r.SetPathValue("account", a.Sqid)
+ r.Header.Set("Content-Type", "application/json")
+ r = r.WithContext(context.WithValue(r.Context(), cliRouteKey{}, Principal{Kind: PrincipalUser, Address: f.Person}))
+ w := httptest.NewRecorder()
+ s.handleAPIServiceCreate(w, r)
+ if w.Code != 409 || !strings.Contains(w.Body.String(), demoClaimPending) {
+ t.Fatalf("service mint: %d %s", w.Code, w.Body)
+ }
+}
+func TestDemoClaimAccountsHTTPExactChoice(t *testing.T) {
+ s, m, token := claimTestServer(t)
+ person := "shop@example.com"
+ a := claimAccount(t, s, 501, person, RoleMember)
+ claimAccount(t, s, 502, person, RoleOwner)
+ raw, _ := claimStart(t, s, token, person, "")
+ code, _ := claimMail(t, s, m)
+ if w := claimVerify(s, raw, code); w.Code != 200 || !strings.Contains(w.Body.String(), `"accounts"`) {
+ t.Fatalf("picker: %d %s", w.Code, w.Body)
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 0 {
+ t.Fatalf("early app: %d %v", n, err)
+ }
+ if w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": raw, "accountId": a.Sqid}); w.Code != 202 || !strings.Contains(w.Body.String(), `"phase":"reserved"`) {
+ t.Fatalf("select: %d %s", w.Code, w.Body)
+ }
+ if rows := auditRowsOf(t, s.store, auditFirstSignin); len(rows) != 1 || rows[0].Address != person {
+ t.Fatalf("first-signin audit: %+v", rows)
+ }
+ var n int
+ if err := s.store.db.QueryRow(`SELECT count(*) FROM sessions`).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("session issued: %d %v", n, err)
+ }
+}
+
+func TestDemoClaimReservationStalePolicy(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ d, err := s.store.LookupDemoToken(t.Context(), token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := release.AppPolicyKey(a.Sqid, d.Name)
+ if _, err := s.cfg.Releases.Put(t.Context(), key, []byte("old-policy"), ""); err != nil {
+ t.Fatal(err)
+ }
+ op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if op.Target.App == d.Name {
+ t.Fatal("reused name with stale policy")
+ }
+ b, _, err := s.cfg.Releases.Get(t.Context(), key)
+ if err != nil || string(b) != "old-policy" {
+ t.Fatalf("cleared policy before reserving: %q %v", b, err)
+ }
+}
+
+func TestDemoClaimReservationFlowErasure(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, raw := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ if _, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}); err != nil {
+ t.Fatal(err)
+ }
+ in := demoTestAdmission(t, s.cfg.Demo)
+ if _, err := s.store.ReserveDemo(t.Context(), in); err != nil {
+ t.Fatal(err)
+ }
+ g, otherRaw := claimProved(t, s, in.Identity.Token, f.Person)
+ if _, err := s.reserveDemoClaim(t.Context(), g, a, regionReq{}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`DELETE FROM demo_claim_flows`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET flow_hash=''`); err != nil {
+ t.Fatal("cannot erase multiple expired capabilities", err)
+ }
+ for _, raw := range []string{raw, otherRaw} {
+ if _, err := s.store.demoClaimStatusFlow(t.Context(), raw, time.Now()); err == nil {
+ t.Fatal("erased capability still works")
+ }
+ }
+ if n, err := s.runningThings(t.Context(), a); err != nil || n != 4 {
+ t.Fatalf("erasing credential released reservations: %d %v", n, err)
+ }
+}
diff --git a/internal/console/demo_domains.go b/internal/console/demo_domains.go
index 7e4710be8..479e9bb97 100644
--- a/internal/console/demo_domains.go
+++ b/internal/console/demo_domains.go
@@ -18,6 +18,9 @@ func (s *Server) demoDomainReserved(host string) bool {
}
func (s *Server) demoMutationRefusal(acct *Account, app string) *doorRefusal {
+ if ref := s.demoClaimMutationRefusal(context.Background(), acct.ID, app); ref != nil {
+ return ref
+ }
life, err := s.store.AppLife(acct.ID, app)
if err != nil {
log.Printf("console: demo mutation %s/%s: app life: %v", acct.Sqid, app, err)
@@ -34,6 +37,16 @@ func (s *Server) demoMutationRefusal(acct *Account, app string) *doorRefusal {
type demoRecordCreateKey struct{}
func (s *Server) demoRecordReservation(ctx context.Context, rec provision.Record) error {
+ acct, err := s.store.AccountBySqid(rec.Account)
+ if err != nil {
+ return err
+ }
+ if acct != nil {
+ if ref := s.demoClaimMutationRefusal(ctx, acct.ID, rec.App); ref != nil {
+ return &hostsUsedError{*ref}
+ }
+ }
+
if !s.demoDomainReserved(rec.Host) {
return nil
}
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go
index 0c0aece65..0e535c9f9 100644
--- a/internal/console/lifetimes_purge.go
+++ b/internal/console/lifetimes_purge.go
@@ -38,6 +38,9 @@ import (
// error leaves the marker: errLifetimePending and errLifetimeSettling stop
// the purge for a later run, and every step is idempotent.
func (s *Server) purgeAppWithLifetimes(ctx context.Context, sqid, app string, want, now time.Time, keepMarker ...bool) error {
+ if err := s.demoClaimAppMutationError(ctx, sqid, app); err != nil {
+ return err
+ }
s.noteRecordDeletion(sqid, app, time.Now()) // the canary-retire guard's evidence, first
if err := release.PurgeAppGuards(ctx, s.cfg.Releases, s.cfg.ReleasePub, sqid, app, want, now); err != nil {
return err
@@ -188,6 +191,9 @@ type trashSweepState struct {
func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now time.Time) {
defer s.lockApp(a.Account, a.App)()
+ if err := s.demoClaimAppMutationError(ctx, a.Account, a.App); err != nil {
+ return
+ }
tomb, err := release.ReadAppTombstone(ctx, s.cfg.Releases, a.Account, a.App)
if err != nil || tomb == nil || now.Sub(tomb.DeletedAt) < release.TrashCooloff {
if err != nil {
diff --git a/internal/console/lifetimes_store.go b/internal/console/lifetimes_store.go
index beaf5af06..dcf3c690f 100644
--- a/internal/console/lifetimes_store.go
+++ b/internal/console/lifetimes_store.go
@@ -371,6 +371,7 @@ type appExecer interface {
// newAppRow is the data of one new apps row.
type newAppRow struct {
+ DemoClaimOp string
AccountID int64
App string
CreatedBy string
@@ -397,11 +398,11 @@ func insertAppRow(ex appExecer, r newAppRow) (bool, error) {
if r.UnclaimedEverywhere {
unclaimed = 1
}
- res, err := ex.Exec(`INSERT INTO apps (app, account_id, created_by, created_at, region, region_source, expires_at, lifetime)
-SELECT ?, ?, ?, ?, ?, ?, ?, ?
+ res, err := ex.Exec(`INSERT INTO apps (app, account_id, created_by, created_at, region, region_source, expires_at, lifetime, demo_claim_op)
+SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?
WHERE ? = 0 OR NOT EXISTS (SELECT 1 FROM apps WHERE app = ?)
ON CONFLICT(account_id, app) DO NOTHING`,
- r.App, r.AccountID, r.CreatedBy, r.CreatedAt, r.Region, r.RegionSource, r.ExpiresAt, id, unclaimed, r.App)
+ r.App, r.AccountID, r.CreatedBy, r.CreatedAt, r.Region, r.RegionSource, r.ExpiresAt, id, r.DemoClaimOp, unclaimed, r.App)
if err != nil {
return false, err
}
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go
index 8f2b71981..e00583fd3 100644
--- a/internal/console/plancaps.go
+++ b/internal/console/plancaps.go
@@ -72,7 +72,8 @@ func (s *Server) runningThings(ctx context.Context, acct *Account) (int, error)
liveSet[a] = true
}
if s.cfg.Releases == nil {
- return apps, nil
+ extra, err := s.store.demoClaimReservedThings(ctx, acct.ID, liveSet, nil)
+ return apps + extra, err
}
counted := slices.Sorted(maps.Keys(liveSet))
type listed struct {
@@ -86,6 +87,7 @@ func (s *Server) runningThings(ctx context.Context, acct *Account) (int, error)
})
known := map[string]bool{acct.Sqid: true}
instances := 0
+ records := map[string]bool{}
for i, app := range counted {
if lists[i].err != nil {
return 0, lists[i].err
@@ -93,12 +95,14 @@ func (s *Server) runningThings(ctx context.Context, acct *Account) (int, error)
// The same parse the whole-prefix count made, so a key is counted
// exactly when it was: a record of this app, one level down.
for _, k := range lists[i].keys {
- if _, keyApp, _, ok := provision.ParseRecordKey(k, known); ok && keyApp == app {
+ if _, keyApp, host, ok := provision.ParseRecordKey(k, known); ok && keyApp == app {
+ records[app+"/"+host] = true
instances++
}
}
}
- return apps + instances, nil
+ extra, err := s.store.demoClaimReservedThings(ctx, acct.ID, liveSet, records)
+ return apps + instances + extra, err
}
// checkRunningThings refuses when adding more running things would pass
diff --git a/internal/console/recordlock.go b/internal/console/recordlock.go
index a23e12f9c..354c4590f 100644
--- a/internal/console/recordlock.go
+++ b/internal/console/recordlock.go
@@ -1,5 +1,7 @@
package console
+import "context"
+
// Record writes and the canary retire (#407). The canary retire re-lists the
// app's records just before it deletes the channel pointer, and refuses if
// anything changed since its follower check (recordStamps). It holds the
@@ -17,5 +19,8 @@ package console
// body, so the record-write census still sees it there.
func (s *Server) withRecordLock(acct, app string, write func() error) error {
defer s.lockApp(acct, app)()
+ if err := s.demoClaimAppMutationError(context.Background(), acct, app); err != nil {
+ return err
+ }
return write()
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 5183e53c3..7351af17d 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -5351,6 +5351,71 @@ func (s *Server) claimNamePrefixes(ctx context.Context, acct *Account, name stri
return claimOK, adoptingExistingApp
}
+// validateClaimAppName shares the fresh-name checks across ordinary creates and demo claims.
+func (s *Server) validateClaimAppName(ctx context.Context, acct *Account, name, placement string, ownerClaim bool, expiresAt time.Time) (claimOutcome, bool, *apexHold) {
+ if s.cfg.Demo.Account != "" && acct.Sqid == s.cfg.Demo.Account || s.cfg.Demo.Fleet != "" && placement == "fleet/"+s.cfg.Demo.Fleet {
+ return claimReserved, false, nil
+ }
+ if !release.ValidApp(name) {
+ return claimInvalid, false, nil
+ }
+ // Reserved before any store write, same as an invalid name.
+ if reservedAppName(acct, name) {
+ return claimReserved, false, nil
+ }
+ temporary := !expiresAt.IsZero()
+ if release.IsTemporaryName(name) != temporary {
+ if temporary {
+ return claimInvalid, false, nil
+ }
+ return claimTemporaryReserved, false, nil
+ }
+ if temporary {
+ ownerClaim = false
+ }
+ // Taken means taken IN THIS ACCOUNT — app names are unique per account,
+ // never globally, so another account's "blog" is not a conflict.
+ if has, err := s.store.HasAppIn(acct.ID, name); err != nil {
+ log.Printf("console: claim check failed: account=%q app=%q op=%q err=%v", acct.Sqid, name, "HasAppIn", err)
+ return claimCheckFailed, false, nil
+ } else if has {
+ return claimTaken, false, nil
+ }
+ // The pre-accounts checks still apply to the OPS account, where every
+ // CLI-granted and pre-accounts app lives: a name with grants or bucket
+ // objects there stays claim-proof.
+ if acct.ID == OpsAccountID {
+ if has, err := s.store.HasOwners(name); err != nil {
+ log.Printf("console: claim check failed: account=%q app=%q op=%q err=%v", acct.Sqid, name, "HasOwners", err)
+ return claimCheckFailed, false, nil
+ } else if has {
+ return claimTaken, false, nil
+ }
+ }
+ // The release-store deadline lives HERE, not in the doors, so both doors
+ // give the bucket the same ten seconds the browser form always has —
+ // and the database checks above stay outside it, as they always were.
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ // A name whose platform apex another app of the account already holds is
+ // not free either, whatever the tables say: the new app would never get
+ // its own URL (apex.go).
+ if hold, err := s.apexHolder(ctx, acct, name); err != nil {
+ if apexBucketFailure(err) {
+ return claimStoreFailed, false, nil
+ }
+ log.Printf("console: claim check failed: account=%q app=%q op=%q err=%v", acct.Sqid, name, "apexHolder", err)
+ return claimCheckFailed, false, nil
+ } else if hold != nil {
+ return claimApexHeld, false, hold
+ }
+ outcome, adoptingExistingApp := s.claimNamePrefixes(ctx, acct, name, ownerClaim)
+ if outcome != claimOK {
+ return outcome, false, nil
+ }
+ return claimOK, adoptingExistingApp, nil
+}
+
// claimAppWith claims an app name for acct — once, ever. A name is refused when
// the apps table has it, when ANY owner exists for it (CLI-granted apps stay
// claim-proof), or when the release store already holds anything under
@@ -5419,66 +5484,13 @@ func (s *Server) claimNamePrefixes(ctx context.Context, acct *Account, name stri
// §3, so any object under the prefix refuses), and inserts the row with its
// expiry in the same statement that claims the name.
func (s *Server) claimAppWith(ctx context.Context, acct *Account, name, addr, placement string, ownerClaim bool, rq regionReq, expiresAt time.Time) (outcome claimOutcome, placed string, held *apexHold) {
- if s.cfg.Demo.Account != "" && acct.Sqid == s.cfg.Demo.Account || s.cfg.Demo.Fleet != "" && placement == "fleet/"+s.cfg.Demo.Fleet {
- return claimReserved, "", nil
- }
- if !release.ValidApp(name) {
- return claimInvalid, "", nil
- }
- // Reserved before any store write, same as an invalid name.
- if reservedAppName(acct, name) {
- return claimReserved, "", nil
- }
- temporary := !expiresAt.IsZero()
- if release.IsTemporaryName(name) != temporary {
- if temporary {
- return claimInvalid, "", nil
- }
- return claimTemporaryReserved, "", nil
- }
- if temporary {
- ownerClaim = false
- }
- // Taken means taken IN THIS ACCOUNT — app names are unique per account,
- // never globally, so another account's "blog" is not a conflict.
- if has, err := s.store.HasAppIn(acct.ID, name); err != nil {
- log.Printf("console: claim check failed: account=%q app=%q op=%q err=%v", acct.Sqid, name, "HasAppIn", err)
- return claimCheckFailed, "", nil
- } else if has {
- return claimTaken, "", nil
- }
- // The pre-accounts checks still apply to the OPS account, where every
- // CLI-granted and pre-accounts app lives: a name with grants or bucket
- // objects there stays claim-proof.
- if acct.ID == OpsAccountID {
- if has, err := s.store.HasOwners(name); err != nil {
- log.Printf("console: claim check failed: account=%q app=%q op=%q err=%v", acct.Sqid, name, "HasOwners", err)
- return claimCheckFailed, "", nil
- } else if has {
- return claimTaken, "", nil
- }
- }
- // The release-store deadline lives HERE, not in the doors, so both doors
- // give the bucket the same ten seconds the browser form always has —
- // and the database checks above stay outside it, as they always were.
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
- // A name whose platform apex another app of the account already holds is
- // not free either, whatever the tables say: the new app would never get
- // its own URL (apex.go).
- if hold, err := s.apexHolder(ctx, acct, name); err != nil {
- if apexBucketFailure(err) {
- return claimStoreFailed, "", nil
- }
- log.Printf("console: claim check failed: account=%q app=%q op=%q err=%v", acct.Sqid, name, "apexHolder", err)
- return claimCheckFailed, "", nil
- } else if hold != nil {
- return claimApexHeld, "", hold
- }
- outcome, adoptingExistingApp := s.claimNamePrefixes(ctx, acct, name, ownerClaim)
+ outcome, adoptingExistingApp, held := s.validateClaimAppName(ctx, acct, name, placement, ownerClaim, expiresAt)
if outcome != claimOK {
- return outcome, "", nil
+ return outcome, "", held
}
+ temporary := !expiresAt.IsZero()
// Adopting an app whose objects already exist onto a placement is a move
// of its sealed values (spec §5.5): refused before the row is written,
// the same check carlos apps place makes. A create with no objects has
diff --git a/internal/console/settle.go b/internal/console/settle.go
index 4d05606ea..6f261d103 100644
--- a/internal/console/settle.go
+++ b/internal/console/settle.go
@@ -76,6 +76,9 @@ func (s *Server) doorEvidence(ctx context.Context) bool {
//
// An unreadable marker is an error and changes nothing.
func (s *Server) settleApp(ctx context.Context, accountID int64, sqid, app string, now time.Time, evidence evidenceFunc) error {
+ if ref := s.demoClaimMutationRefusal(ctx, accountID, app); ref != nil {
+ return fmt.Errorf("%s", ref.Msg)
+ }
if s.cfg.Releases == nil {
return nil
}
diff --git a/internal/console/store.go b/internal/console/store.go
index dbc43e972..ad99449b1 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -604,6 +604,7 @@ func (s *Store) migrate() error {
// time from whether the row was temporary then; nothing re-derives
// them.
`ALTER TABLE apps ADD COLUMN demo_id TEXT NOT NULL DEFAULT '';`,
+ `ALTER TABLE apps ADD COLUMN demo_claim_op TEXT NOT NULL DEFAULT '';`,
`ALTER TABLE apps ADD COLUMN expires_at INTEGER NOT NULL DEFAULT 0;`,
`ALTER TABLE apps ADD COLUMN restoring INTEGER NOT NULL DEFAULT 0;`,
`ALTER TABLE apps ADD COLUMN purge_after INTEGER NOT NULL DEFAULT 0;`,
@@ -825,6 +826,7 @@ func (s *Store) migrateAppsKey() error {
purge_for INTEGER NOT NULL DEFAULT 0,
lifetime TEXT NOT NULL DEFAULT '',
demo_id TEXT NOT NULL DEFAULT '',
+ demo_claim_op TEXT NOT NULL DEFAULT '',
PRIMARY KEY (account_id, app)
);`,
// The ALTERs above run before migrateAppsKey in migrate(), so
@@ -838,9 +840,9 @@ func (s *Store) migrateAppsKey() error {
// lifetime is carried across, and minted for a row that has none (the
// ALTER above adds it empty); randomblob(8) is 16 hex digits, the
// same form insertAppRow mints.
- `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, copies_configured, copies_dirty, expires_at, restoring, purge_after, purge_for, lifetime, demo_id)
+ `INSERT INTO apps_new (app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, copies_configured, copies_dirty, expires_at, restoring, purge_after, purge_for, lifetime, demo_id, demo_claim_op)
SELECT app, account_id, created_by, created_at, deleted_at, placement, control_plane, build_probe, region, region_source, region_set_at, copies_configured, copies_dirty, expires_at, restoring, purge_after, purge_for,
- CASE WHEN lifetime = '' THEN lower(hex(randomblob(8))) ELSE lifetime END, demo_id FROM apps;`,
+ CASE WHEN lifetime = '' THEN lower(hex(randomblob(8))) ELSE lifetime END, demo_id, demo_claim_op FROM apps;`,
`DROP TABLE apps;`,
`ALTER TABLE apps_new RENAME TO apps;`,
} {
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index bcf8944b4..540afd897 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -188,6 +188,7 @@ var claimAppsTerminal = map[string][]string{
// cannot silently ship ungated. There is deliberately no exemption class:
// audit and mail telemetry are app-scoped and are gated like the rest.
var claimSQLTables = map[string]claimSQLTable{
+ "demo_claim_ops": {Account: "account_id", App: "app", Refuse: "anonymous demo 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"},