carlos / platform Public

Bound spent demo token retention to 30 days

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev a92358ee0cf884dc01fdc8e8b3f7b050ba243acf parent ac40eb5
7 files changed, +173 −56
  • internal/console/apidemo.go +1 −1
  • internal/console/demo_claim_transfer.go +3 −2
  • internal/console/demo_expiry.go +5 −4
  • internal/console/demo_spent_token_test.go +145 −22
  • internal/console/demo_store.go +11 −20
  • internal/console/static/demo_claim.js +1 −1
  • internal/console/store_gate.go +7 −6

CI failed — run details

Intent

Human

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

Human

<task-notification> <task-id>aa105e0434c8649b8</task-id> <tool-use-id>toolu_01579PK1yyeoNuKXpN5duRzD</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/aa105e0434c8649b8.output</output-file> <status>completed</status> <summary>Agent "Opus review spent-link branch" 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>**Verdict: BLOCK.** The security side is sound. The block is for the retention change, which went beyond the brief and makes `demo_apps` grow without limit. I could not run the tests: the sandbox mounts `~/.cache/go-build` read-only, and I left `GOCACHE` at its default as the rules require. I created no scratch files. **1. Can a spent token authorise anything? No.** - `spentDemoTokenError` (`demo_store.go:365`) only ever returns errors, and `LookupDemoToken` returns an empty row with them. - `LookupDemoToken` has three callers: start (`demo_claim_auth.go:143`), intent (`demo_claim_page.go:272`) and Bearer update (`apidemo.go:379`). All three refuse with 401. - Verify, select and status do not use the token. - The three new errors wrap `ErrDemoToken`, and every check uses `errors.Is`. - Commit still requires `claim_token_hash IS NOT NULL` (`demo_claim_transfer.go:661`). **2. Leaks, enumeration, timing: none found.** - Every miss now runs the same second indexed query, so random guesses look alike. - A reason, including the new expiry branch (`demo_store.go:356`), is only reachable with the full token. - The constant-time compare after an SQL equality match adds nothing, but does no harm. **Findings, most severe first** 1. **Blocking. `demo_store.go:512` and `demo_claim_transfer.go:1083` keep rows forever.** - Every demo gets a spent hash when it is claimed or retired, so the cleanup now never deletes any `demo_apps` row. - A kept row holds demo id, the shared demo account id and sqid, app, name, host, fleet, assigned box, created_at, generation, state and purged_at. - The wipe still blanks IP, client and source hash, and deletes reports, jobs and caps. So it still removes the abuse data. What it no longer bounds is how much it keeps. - The person who claimed is not linked after cleanup: `apps.demo_claim_op` is cleared at finish (`:760`) and the claim operations are pruned. The receipts still keep "this host was kept" forever. - Host and name reuse do not change, because `demo_host_tombstones` already reserves them permanently. - Failure scenario: `demoOperatorView` (`demo_serving.go:282`) loads every `demo_apps` row and then runs several queries per row. The operator listing grows forever, gets slower, and lists every historical demo. - Fix: - Revert both cleanup changes. - Add a table `demo_spent_tokens(hash BLOB PRIMARY KEY CHECK(length(hash)=32), reason TEXT CHECK(reason IN('expired','operator','kept')), spent_at INTEGER) WITHOUT ROWID`. - Write to it in the same transaction: at commit with reason 'kept', and at retirement with `INSERT OR IGNORE` so the first reason wins and a 'claimed' retirement is a no-op. - Delete rows older than 30 days in `WipeDemoAbuse`. After that, the token falls back to invalid. - This drops the `ALTER` statements and the `demo_claim_commits` lookup. 2. **Medium. `apidemo.go:310`: the invalid-token message changed for API clients.** - Start and Bearer update now answer a bad token with "This link is wrong or incomplete…". Before, they said "This demo token is invalid or no longer available." - An agent pushing an update has no link, so the new wording misleads it. - Fix: for reason `invalid`, keep `demoCopy["DEMO-TOKEN"]` on the API and add only the `reason` field. Keep `demoClaimLinkBroken` for the browser page. 3. **Nit. `demo_store.go:87`:** the unique index should be partial (`WHERE spent_token_hash IS NOT NULL`). The current one is still safe: SQLite treats NULLs as distinct. **4. Reason derivation: correct.** - "Kept" relies on `demo_claim_commits`, which commit writes in the same transaction. A rollback undoes both, and nothing else deletes those rows except the cleanup now guarded by the spent hash. - A 'claimed' retirement stores '' and becomes "kept" through that check. - Repeat retirement keeps the first hash and reason. The update uses the old values, and its `state='anonymous'` filter makes a second retirement a no-op anyway. - The migration runs safely twice: a "duplicate column" error is ignored and the index uses `IF NOT EXISTS`. **5. Browser script and template: correct, with one nit.** - A body that is not JSON makes `response.json()` reject. That falls into `.catch`, which shows the generic message. - Text is set through `textContent`, and html/template escapes the data attributes. The CSP and the page head are unchanged. - Nit: a body of `null` works only because of `?.`. Guard it with `typeof result === "object"`. **6. Scope creep:** finding 1 is outside the brief. The brief assumed rows were already kept as tombstones, but before this commit they were deleted after seven days. Finding 2 also changes copy the brief did not ask to change.</result> <usage><subagent_tokens>82065</subagent_tokens><tool_uses>15</tool_uses><duration_ms>136593</duration_ms></usage> </task-notification>

Attributed to this commit: 8.32 g CO₂e (962,734 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-claim-spent-link, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go
index 2447d9547..6d817e23f 100644
--- a/internal/console/apidemo.go
+++ b/internal/console/apidemo.go
@@ -300,7 +300,7 @@ func demoTokenRefusal(err error) (reason, message string) {
case errors.Is(err, ErrDemoTakenDown):
return "taken-down", demoClaimTakenDown
default:
- return "invalid", demoClaimLinkBroken
+ return "invalid", demoCopy["DEMO-TOKEN"]
}
}
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go
index f4640f8f5..4e0a3afeb 100644
--- a/internal/console/demo_claim_transfer.go
+++ b/internal/console/demo_claim_transfer.go
@@ -677,7 +677,8 @@ func (s *Server) commitDemoClaim(ctx context.Context, op claimOp) error {
}{
{`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES(?,?,?)`, []any{op.ID, op.DemoID, time.Now().Unix()}},
{`UPDATE demo_claim_ops SET phase='committed' WHERE id=?`, []any{op.ID}},
- {`UPDATE demo_apps SET spent_token_hash=claim_token_hash,claim_token_hash=NULL WHERE demo_id=?`, []any{op.DemoID}},
+ {`INSERT INTO demo_spent_tokens(hash,reason,spent_at) SELECT claim_token_hash,'kept',? FROM demo_apps WHERE demo_id=? AND claim_token_hash IS NOT NULL`, []any{time.Now().Unix(), op.DemoID}},
+ {`UPDATE demo_apps SET claim_token_hash=NULL WHERE demo_id=?`, []any{op.DemoID}},
{`DELETE FROM demo_claim_flows WHERE demo_id=?`, []any{op.DemoID}},
{`INSERT INTO demo_moved_notices(demo_id,host,target_host,expires_at) VALUES(?,?,?,?)`, []any{op.DemoID, d.Host, op.Target.Host, op.SourceExpiresAt}},
{`INSERT INTO demo_claim_outbox(operation_id,step) VALUES(?,'open'),(?,'moved'),(?,'retire')`, []any{op.ID, op.ID, op.ID}},
@@ -1080,7 +1081,7 @@ func (s *Server) pruneDemoClaims(ctx context.Context, now time.Time) error {
{`UPDATE demo_claim_ops SET flow_hash='' WHERE source_expires_at<=? AND flow_hash!=''`, now.Add(-24 * time.Hour).Unix()},
{`DELETE FROM demo_claim_flows WHERE hash NOT IN (SELECT flow_hash FROM demo_claim_ops WHERE flow_hash!='') AND expires_at<=?`, now.Unix()},
{`DELETE FROM demo_claim_progress WHERE operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
- {`DELETE FROM demo_claim_commits WHERE NOT EXISTS(SELECT 1 FROM demo_apps d WHERE d.demo_id=demo_claim_commits.demo_id AND d.spent_token_hash IS NOT NULL) AND operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
+ {`DELETE FROM demo_claim_commits WHERE operation_id IN (SELECT o.id FROM demo_claim_ops o JOIN demo_apps d ON d.demo_id=o.demo_id WHERE o.phase IN ('done','aborted') AND d.purged_at>0 AND d.purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
{`DELETE FROM demo_claim_ops WHERE phase IN ('done','aborted') AND demo_id IN (SELECT demo_id FROM demo_apps WHERE purged_at>0 AND purged_at<=?)`, now.Add(-7 * 24 * time.Hour).Unix()},
} {
if _, err = tx.ExecContext(ctx, q.sql, q.arg); err != nil {
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go
index 18522e24f..fc7310e83 100644
--- a/internal/console/demo_expiry.go
+++ b/internal/console/demo_expiry.go
@@ -210,11 +210,12 @@ func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time,
if _, err = tx.ExecContext(ctx, `INSERT INTO demo_retirements(demo_id,wire,acknowledged,initialized_clean,fenced_at) VALUES(?,?,?,?,?)`, d.ID, r.Wire, d.AssignedBox == "", d.AssignedBox == "", r.FencedAt); err != nil {
return err
}
- spentReason := reason
- if reason == "claimed" {
- spentReason = ""
+ if reason != "claimed" {
+ if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO demo_spent_tokens(hash,reason,spent_at) SELECT claim_token_hash,?,? FROM demo_apps WHERE demo_id=? AND state='anonymous' AND claim_token_hash IS NOT NULL`, reason, now.Unix(), d.ID); err != nil {
+ return err
+ }
}
- if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET state='retiring',generation=generation+1,spent_token_hash=coalesce(spent_token_hash,claim_token_hash),spent_reason=CASE WHEN spent_token_hash IS NULL THEN ? ELSE spent_reason END,claim_token_hash=NULL,active_job_id='' WHERE demo_id=? AND state='anonymous'`, spentReason, d.ID); err != nil {
+ if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET state='retiring',generation=generation+1,claim_token_hash=NULL,active_job_id='' WHERE demo_id=? AND state='anonymous'`, d.ID); err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `UPDATE demo_jobs SET state='failed',publish_stage='retired' WHERE demo_id=?`, d.ID); err != nil {
diff --git a/internal/console/demo_spent_token_test.go b/internal/console/demo_spent_token_test.go
index 71272da28..b7417dcc8 100644
--- a/internal/console/demo_spent_token_test.go
+++ b/internal/console/demo_spent_token_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/sha256"
+ "database/sql"
"encoding/base64"
"encoding/json"
"errors"
@@ -64,7 +65,10 @@ func TestDemoSpentTokenSurfaces(t *testing.T) {
t.Fatal(err)
}
case "kept":
- if _, err := s.store.db.Exec(`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES('test',?,?); UPDATE demo_apps SET spent_token_hash=claim_token_hash,claim_token_hash=NULL WHERE demo_id=?`, d.ID, time.Now().Unix(), d.ID); err != nil {
+ if _, err := s.store.db.Exec(`INSERT INTO demo_spent_tokens(hash,reason,spent_at) SELECT claim_token_hash,'kept',? FROM demo_apps WHERE demo_id=?`, time.Now().Unix(), d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_apps SET claim_token_hash=NULL WHERE demo_id=?`, d.ID); err != nil {
t.Fatal(err)
}
case "invalid":
@@ -97,7 +101,7 @@ func TestDemoSpentTokenSurfaces(t *testing.T) {
t.Errorf("intent exposed more than reason: %v", got)
}
} else {
- messages := map[string]string{"expired": demoClaimExpired, "kept": demoClaimAlreadyKept, "taken-down": demoClaimTakenDown, "invalid": demoClaimLinkBroken}
+ messages := map[string]string{"expired": demoClaimExpired, "kept": demoClaimAlreadyKept, "taken-down": demoClaimTakenDown, "invalid": demoCopy["DEMO-TOKEN"]}
if got["error"] != messages[reason] {
t.Errorf("%s message: %q", surface, got["error"])
}
@@ -176,7 +180,7 @@ func TestDemoSpentTokenClearingPaths(t *testing.T) {
check := func() {
t.Helper()
var live, spent []byte
- if err := s.store.db.QueryRow(`SELECT claim_token_hash,spent_token_hash FROM demo_apps WHERE demo_id=?`, d.ID).Scan(&live, &spent); err != nil {
+ if err := s.store.db.QueryRow(`SELECT claim_token_hash,(SELECT hash FROM demo_spent_tokens WHERE hash=?) FROM demo_apps WHERE demo_id=?`, hash[:], d.ID).Scan(&live, &spent); err != nil {
t.Fatal(err)
}
if len(live) != 0 || !bytes.Equal(spent, hash[:]) {
@@ -205,21 +209,22 @@ func TestDemoSpentTokenClearingPaths(t *testing.T) {
if err != nil || purged.PurgedAt == 0 {
t.Fatalf("purge did not complete: %+v %v", purged, err)
}
- future := time.Now().Add(30 * 24 * time.Hour)
+ future := time.Now().Add(10 * 24 * time.Hour)
if err := s.pruneDemoClaims(t.Context(), future); err != nil {
t.Fatal(err)
}
if err := s.store.WipeDemoAbuse(t.Context(), future); err != nil {
t.Fatal(err)
}
- check()
- retained, err := s.store.demoByID(t.Context(), d.ID)
- if err != nil || retained.CreatingIP != "" || retained.Client != "" || retained.SourceSHA256 != ([32]byte{}) {
- t.Fatalf("abuse metadata retained: %+v %v", retained, err)
+ if _, err := s.store.LookupDemoToken(t.Context(), token); !errors.Is(err, map[string]error{"expired": ErrDemoExpired, "operator": ErrDemoTakenDown, "claimed": ErrDemoKept}[reason]) {
+ t.Fatalf("spent token reason lost after demo wipe: %v", err)
+ }
+ if _, err := s.store.demoByID(t.Context(), d.ID); !errors.Is(err, sql.ErrNoRows) {
+ t.Fatalf("purged demo row retained: %v", err)
}
if reason == "claimed" {
var commits, ops int
- if err := s.store.db.QueryRow(`SELECT (SELECT count(*) FROM demo_claim_commits WHERE demo_id=?),(SELECT count(*) FROM demo_claim_ops WHERE demo_id=?)`, d.ID, d.ID).Scan(&commits, &ops); err != nil || commits != 1 || ops != 0 {
+ if err := s.store.db.QueryRow(`SELECT (SELECT count(*) FROM demo_claim_commits WHERE demo_id=?),(SELECT count(*) FROM demo_claim_ops WHERE demo_id=?)`, d.ID, d.ID).Scan(&commits, &ops); err != nil || commits != 0 || ops != 0 {
t.Fatalf("durable commit or operation pruning: commits=%d ops=%d %v", commits, ops, err)
}
}
@@ -234,22 +239,20 @@ func TestDemoSpentTokenMigration(t *testing.T) {
if _, err := st.ReserveDemo(t.Context(), in); err != nil {
t.Fatal(err)
}
- for _, q := range []string{`DROP INDEX IF EXISTS demo_apps_spent_token`, `ALTER TABLE demo_apps DROP COLUMN spent_token_hash`, `ALTER TABLE demo_apps DROP COLUMN spent_reason`} {
- if _, err := st.db.Exec(q); err != nil && !strings.Contains(err.Error(), "no such column") {
- t.Fatal(err)
- }
+ if _, err := st.db.Exec(`DROP TABLE demo_spent_tokens`); err != nil {
+ t.Fatal(err)
}
for i := 0; i < 2; i++ {
if err := st.migrateDemo(); err != nil {
t.Fatal(err)
}
}
- var live, spent []byte
- var reason string
- if err := st.db.QueryRow(`SELECT claim_token_hash,spent_token_hash,spent_reason FROM demo_apps WHERE demo_id=?`, in.Identity.ID).Scan(&live, &spent, &reason); err != nil {
+ var live []byte
+ var spent int
+ if err := st.db.QueryRow(`SELECT claim_token_hash,(SELECT count(*) FROM demo_spent_tokens) FROM demo_apps WHERE demo_id=?`, in.Identity.ID).Scan(&live, &spent); err != nil {
t.Fatal(err)
}
- if !bytes.Equal(live, in.Identity.TokenHash[:]) || spent != nil || reason != "" {
+ if !bytes.Equal(live, in.Identity.TokenHash[:]) || spent != 0 {
t.Fatal("migration changed live credential")
}
if _, err := st.LookupDemoToken(t.Context(), in.Identity.Token); err != nil {
@@ -348,15 +351,135 @@ func TestDemoSpentTokenAtomicClearing(t *testing.T) {
if err := clear(); err == nil {
t.Fatal("missing injected failure")
}
- var live, spent []byte
- var spentReason string
- var receipts int
- if err := s.store.db.QueryRow(`SELECT claim_token_hash,spent_token_hash,spent_reason,(SELECT count(*) FROM demo_claim_commits WHERE demo_id=d.demo_id) FROM demo_apps d WHERE demo_id=?`, d.ID).Scan(&live, &spent, &spentReason, &receipts); err != nil {
+ var live []byte
+ var spent, receipts int
+ if err := s.store.db.QueryRow(`SELECT claim_token_hash,(SELECT count(*) FROM demo_spent_tokens),(SELECT count(*) FROM demo_claim_commits WHERE demo_id=d.demo_id) FROM demo_apps d WHERE demo_id=?`, d.ID).Scan(&live, &spent, &receipts); err != nil {
t.Fatal(err)
}
- if !bytes.Equal(live, before) || len(spent) != 0 || spentReason != "" || receipts != 0 {
+ if !bytes.Equal(live, before) || spent != 0 || receipts != 0 {
t.Fatal("partial credential spend survived rollback")
}
})
}
}
+
+func TestDemoSpentTokenRetention(t *testing.T) {
+ st, _ := demoTestStore(t)
+ now := time.Now().Truncate(time.Second)
+ for _, tc := range []struct {
+ name string
+ age time.Duration
+ want error
+ }{
+ {"older", demoSpentTokenRetention + time.Second, ErrDemoToken},
+ {"younger", demoSpentTokenRetention - time.Second, ErrDemoExpired},
+ {"boundary", demoSpentTokenRetention, ErrDemoExpired},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ token, err := randomToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := base64.RawURLEncoding.DecodeString(token)
+ hash := sha256.Sum256(raw)
+ if _, err := st.db.Exec(`INSERT INTO demo_spent_tokens(hash,reason,spent_at) VALUES(?,'expired',?)`, hash[:], now.Add(-tc.age).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.WipeDemoAbuse(t.Context(), now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.LookupDemoToken(t.Context(), token); err != tc.want {
+ t.Fatalf("lookup: %v; want %v", err, tc.want)
+ }
+ var n int
+ if err := st.db.QueryRow(`SELECT count(*) FROM demo_spent_tokens WHERE hash=?`, hash[:]).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ wantRows := 1
+ if tc.want == ErrDemoToken {
+ wantRows = 0
+ }
+ if n != wantRows {
+ t.Fatalf("retained %d rows; want %d", n, wantRows)
+ }
+ })
+ }
+}
+
+func TestDemoWipeDeletesPurgedRows(t *testing.T) {
+ for _, spent := range []bool{false, true} {
+ t.Run(map[bool]string{false: "unspent", true: "spent"}[spent], func(t *testing.T) {
+ st, _ := demoTestStore(t)
+ in := demoTestAdmission(t, demoTestConfig(t))
+ d, err := st.ReserveDemo(t.Context(), in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ purged := now.Add(-8 * 24 * time.Hour).Unix()
+ if spent {
+ if _, err := st.db.Exec(`INSERT INTO demo_spent_tokens(hash,reason,spent_at) SELECT claim_token_hash,'operator',? FROM demo_apps WHERE demo_id=?`, purged, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.db.Exec(`UPDATE demo_apps SET claim_token_hash=NULL WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := st.db.Exec(`UPDATE demo_apps SET state='retired',purged_at=? WHERE demo_id=?`, purged, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.db.Exec(`INSERT INTO demo_host_tombstones(host,demo_id,purged_at) VALUES(?,?,?)`, d.Host, d.ID, purged); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.WipeDemoAbuse(t.Context(), now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.demoByID(t.Context(), d.ID); !errors.Is(err, sql.ErrNoRows) {
+ t.Fatalf("purged row retained: %v", err)
+ }
+ var n int
+ if err := st.db.QueryRow(`SELECT count(*) FROM demo_host_tombstones WHERE demo_id=?`, d.ID).Scan(&n); err != nil || n != 1 {
+ t.Fatalf("tombstone lost: %d %v", n, err)
+ }
+ })
+ }
+}
+
+func TestDemoSpentTokenFirstReasonWins(t *testing.T) {
+ for _, retirement := range []string{"expired", "operator", "claimed"} {
+ t.Run(retirement, func(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ var hash []byte
+ if err := s.store.db.QueryRow(`SELECT claim_token_hash FROM demo_apps WHERE demo_id=?`, op.DemoID).Scan(&hash); err != nil {
+ t.Fatal(err)
+ }
+ claimToVerify(t, s, op, data)
+ // Leave retirement pending so the first retirement follows a committed claim.
+ if _, err := s.store.db.Exec(`CREATE TRIGGER defer_retirement BEFORE INSERT ON demo_retirements BEGIN SELECT RAISE(ABORT,'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil {
+ t.Fatal("missing retirement failure")
+ }
+ var before int64
+ var reason string
+ if err := s.store.db.QueryRow(`SELECT reason,spent_at FROM demo_spent_tokens WHERE hash=?`, hash).Scan(&reason, &before); err != nil || reason != "kept" {
+ t.Fatalf("commit reason: %q %v", reason, err)
+ }
+ if _, err := s.store.db.Exec(`DROP TRIGGER defer_retirement`); err != nil {
+ t.Fatal(err)
+ }
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.retireDemoLocked(t.Context(), d, time.Unix(op.SourceExpiresAt+1, 0), retirement); err != nil {
+ t.Fatal(err)
+ }
+ var after int64
+ if err := s.store.db.QueryRow(`SELECT reason,spent_at FROM demo_spent_tokens WHERE hash=?`, hash).Scan(&reason, &after); err != nil || reason != "kept" || after != before {
+ t.Fatalf("first reason overwritten: %q %d -> %d %v", reason, before, after, err)
+ }
+ })
+ }
+}
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go
index 75b157f1e..d23ac3021 100644
--- a/internal/console/demo_store.go
+++ b/internal/console/demo_store.go
@@ -16,6 +16,8 @@ import (
"github.com/carlosframework/platform/internal/demo"
)
+const demoSpentTokenRetention = 30 * 24 * time.Hour
+
var (
ErrDemoCreateLimit = errors.New("demo: create budget exhausted")
ErrDemoLiveLimit = errors.New("demo: live ceiling reached")
@@ -71,22 +73,12 @@ CREATE TABLE IF NOT EXISTS demo_apps (
purged_at INTEGER NOT NULL DEFAULT 0,
UNIQUE(account_id, app)
);
+CREATE TABLE IF NOT EXISTS demo_spent_tokens(hash BLOB PRIMARY KEY CHECK(length(hash)=32), reason TEXT NOT NULL CHECK(reason IN('expired','operator','kept')), spent_at INTEGER NOT NULL) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS demo_host_tombstones(host TEXT PRIMARY KEY, demo_id TEXT NOT NULL, purged_at INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS demo_retirements(demo_id TEXT PRIMARY KEY, wire BLOB NOT NULL, delivered INTEGER NOT NULL DEFAULT 0, acknowledged INTEGER NOT NULL DEFAULT 0, purging INTEGER NOT NULL DEFAULT 0, initialized_clean INTEGER NOT NULL DEFAULT 0, wait_logged_at INTEGER NOT NULL DEFAULT 0);`)
if err != nil {
return err
}
- for _, stmt := range []string{
- `ALTER TABLE demo_apps ADD COLUMN spent_token_hash BLOB CHECK(spent_token_hash IS NULL OR length(spent_token_hash)=32)`,
- `ALTER TABLE demo_apps ADD COLUMN spent_reason TEXT NOT NULL DEFAULT '' CHECK(spent_reason IN ('','expired','operator'))`,
- } {
- if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
- return err
- }
- }
- if _, err := s.db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS demo_apps_spent_token ON demo_apps(spent_token_hash)`); err != nil {
- return err
- }
salt := make([]byte, 32)
if _, err := rand.Read(salt); err != nil {
return err
@@ -365,10 +357,7 @@ func (s *Store) LookupDemoToken(ctx context.Context, token string) (DemoRow, err
func (s *Store) spentDemoTokenError(ctx context.Context, hash []byte) error {
var stored []byte
var reason string
- var committed bool
- err := s.db.QueryRowContext(ctx, `SELECT spent_token_hash,spent_reason,
- EXISTS(SELECT 1 FROM demo_claim_commits c WHERE c.demo_id=d.demo_id)
- FROM demo_apps d WHERE spent_token_hash=?`, hash).Scan(&stored, &reason, &committed)
+ err := s.db.QueryRowContext(ctx, `SELECT hash,reason FROM demo_spent_tokens WHERE hash=?`, hash).Scan(&stored, &reason)
if errors.Is(err, sql.ErrNoRows) {
return ErrDemoToken
}
@@ -378,10 +367,9 @@ func (s *Store) spentDemoTokenError(ctx context.Context, hash []byte) error {
if subtle.ConstantTimeCompare(hash, stored) != 1 {
return ErrDemoToken
}
- if committed {
- return ErrDemoKept
- }
switch reason {
+ case "kept":
+ return ErrDemoKept
case "expired":
return ErrDemoExpired
case "operator":
@@ -484,7 +472,7 @@ func (s *Server) withDemoLocked(ctx context.Context, id string, fn func(DemoRow,
}
// WipeDemoAbuse removes identifying metadata seven days after confirmed purge.
-// Abuse history lasts seven days; spent hashes and host tombstones are permanent.
+// Purged history lasts seven days; the minimal host tombstone is permanent.
// The existing expiry pass calls this even with admission disabled.
func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error {
tx, err := s.db.BeginTx(ctx, nil)
@@ -509,7 +497,10 @@ func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error {
if _, err = tx.ExecContext(ctx, `DELETE FROM demo_caps WHERE demo_id IN (`+expired+`)`, cutoff); err != nil {
return err
}
- if _, err = tx.ExecContext(ctx, `DELETE FROM demo_apps WHERE spent_token_hash IS NULL AND demo_id IN (`+expired+`)`, cutoff); err != nil {
+ if _, err = tx.ExecContext(ctx, `DELETE FROM demo_apps WHERE demo_id IN (`+expired+`)`, cutoff); err != nil {
+ return err
+ }
+ if _, err = tx.ExecContext(ctx, `DELETE FROM demo_spent_tokens WHERE spent_at<?`, now.Add(-demoSpentTokenRetention).Unix()); err != nil {
return err
}
return tx.Commit()
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index 601701da1..349a657c4 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -135,7 +135,7 @@
form.delete("claimToken");
if (!response.ok) {
const result = await response.json();
- showError(result?.reason);
+ showError(result && typeof result === "object" ? result.reason : undefined);
return;
}
location.replace("/demo/claim");
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index db80ec995..b8fa2fa4b 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -204,12 +204,13 @@ var claimSQLTables = map[string]claimSQLTable{
// Jobs carry demo identity and durable spool metadata; source outbox rows
// carry only a job ID. Neither is safe to write with an ordinary app permit.
// The opaque IDs below are refusal-only scopes, never matched to a permit.
- "demo_jobs": {App: "demo_id", Refuse: "anonymous demo jobs require claims mode off"},
- "demo_job_outbox": {App: "job_id", Refuse: "anonymous demo source outbox requires claims mode off"},
- "demo_apps": {Account: "account_id", App: "app", Refuse: "anonymous demos require claims mode off"},
- "demo_admissions": {NonApp: "anonymous attempt budget, keyed by salted IP hash and time; names no app"},
- "demo_settings": {NonApp: "deployment salt for anonymous admission; names no app"},
- "app_stars": {NonApp: "personal bookmarks keyed by account, address and app lifetime; grants no app authority"},
+ "demo_jobs": {App: "demo_id", Refuse: "anonymous demo jobs require claims mode off"},
+ "demo_job_outbox": {App: "job_id", Refuse: "anonymous demo source outbox requires claims mode off"},
+ "demo_apps": {Account: "account_id", App: "app", Refuse: "anonymous demos require claims mode off"},
+ "demo_admissions": {NonApp: "anonymous attempt budget, keyed by salted IP hash and time; names no app"},
+ "demo_spent_tokens": {NonApp: "spent credential hashes, refusal reasons and retention times only; names no app and grants no authority"},
+ "demo_settings": {NonApp: "deployment salt for anonymous admission; names no app"},
+ "app_stars": {NonApp: "personal bookmarks keyed by account, address and app lifetime; grants no app authority"},
// ---- app-scoped: gated ----
"apps": {Account: "account_id", App: "app", AppID: "app_id", Terminal: claimAppsTerminal},
// Legacy per-app grants carry no account column, so a permit for app