carlos / platform Public

fix: register demo claim console paths with the repo guards

Account mint inventory, account lock on claim seed creation, authority
census entry for the snapshot open, nil-safe claim marker guards, policy
holding checked before mutation admission, and an exact same-origin
allowance for the claim page script.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev e75b0b899404012145875e701ca8e593bb313c87 parent 1b764ad
10 files changed, +128 −8
  • internal/console/apipolicy.go +8 −0
  • internal/console/claim_authority_census_test.go +6 −0
  • internal/console/demo_claim_seed.go +1 −0
  • internal/console/demo_claim_seed_test.go +32 −1
  • internal/console/demo_claim_target.go +10 −0
  • internal/console/demo_claim_target_test.go +36 −0
  • internal/console/icons_test.go +27 −3
  • internal/console/recordcreators_guard_test.go +4 −2
  • internal/console/testdata/claim-authority-sites.txt +1 −0
  • internal/domains/reserved_test.go +3 −2

Intent

Human

<task-notification> <task-id>bc56mm91k</task-id> <tool-use-id>toolu_01ABff85tUN3tZJoUhxQYaUU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/bc56mm91k.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t8.done ]; do sleep 30; done; tail -1 $S/t8.log" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>b2005042h</task-id> <tool-use-id>toolu_01G21VBHSQhhgwaz983L1NXo</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/b2005042h.output</output-file> <status>completed</status> <summary>Background command "until amadan ci status carlos/platform -branch agent-start-demo-3 2&gt;&amp;1 | head -1 | grep -qv 'running'; do sleep 60; done; amadan ci status carlos/platform -branch agent-start-demo-3 2&gt;&amp;1 | head -5" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>afb2c3ded52d1583d</task-id> <tool-use-id>toolu_01Swt8Jrp3uHdW67VibdVs9b</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/afb2c3ded52d1583d.output</output-file> <status>completed</status> <summary>Agent "Census review agent-start-demo-3" 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>## Census verdict: agent-start-demo-3 at tip 1b764ad6 **Overall: APPROVED.** I found nothing to reject: no P1 and no P2. Four P3s go on the branch's follow-up list and do not start a round. The focused census test passes with the overlay: `nice go test ./internal/provision -run 'TestPlan14RootReadCensus|TestCensus' -count=1` gave `ok … 14.3s`. The first run inside the sandbox failed only because it could not write the default Go cache. I reran it outside the sandbox with the same cache. The worktree is still clean. **Who runs what.** Only `carlos-instance-control.service` (instancectl, and the demobuild worker inside it) runs as root. The agent, edge, activator, provision and registry code runs as user `carlos`. The one production `provision.Reconcile` call is `internal/host/agent.go:2087`. Registry reads by root go through the existing `HostDemo` wiring, which this branch does not change. ### Units with a recorded disposition (body / sites) | unit | verdict | evidence | |---|---|---| | activator/seedplace.go `ExecBackend.SeedPlaced` | APPROVE | Agent side. A demo-claim seed at `placed` re-runs the replica sync; this only tightens. | | demobuild/worker.go `NewWorker` | APPROVE | `snapshotPoisoned: true` at construction and `available()` now also requires `!snapshotPoisoned`. Fails closed. No new read. | | edge/demo.go `handleDemoRequest`, `redirectDemoRequest` | APPROVE | Edge (carlos). Serves a notice only from `VerifyMoved`-verified rows, checked against `MovedDomains`, before route lookup (`edge/demo_moved.go:20-46`). | | edge/edge.go `Edge.Reload` | APPROVE | Adds `loadDemoMoved()`: a signed, verified blob read from the edge's own registry. | | host/agent.go `fastConvergeLoop`, `fastTick`, `runAgent`, `statusLoop` | APPROVE | Agent only. Adds the moved reader on the existing watch, wires the claim client and a capability flag. `convergeAdopted` tightens: held rows are skipped. | | host/demo_serving.go `demoHeartbeat`, `demoServingAllowed` | APPROVE | Capability strings, and a `claimHeld` refusal added (tightening). | | host/seedwiring.go `wireSeedPlacement` | APPROVE | Adds `OnDemoClaimSeedWake`, a record recheck (`seedwiring.go:264-279`). | | units/carlos-instance-control.service `external` | APPROVE | Only adds `StateDirectory=carlos-demo-snapshots` with mode 0700, which is root-only. See P3-1. | | instancectl/server.go `runWithClaim`, `type Server` | APPROVE | Supervisor built only when `DemoBox`. Three POST routes added. No path field anywhere in the requests. | | provision/seed.go `SeedAbortBecause` | APPROVE | Applies the import's run and interactive refusals to demo-claim seeds (tightening). | | provision/seedreconcile.go `journalPass` | APPROVE | Skips any journal whose record is a demo claim (`seedreconcile.go:420-424`). | | status/snapshot.go `CollectBox` | APPROVE | Capability list only. | | activator/seedplace.go `seededRestore` (+Route) | APPROVE | A claim seed that is not ready fails, and an uncommitted one needs `OnDemoClaimSeedWake` (`seedplace.go:110-123`). | | host/demo_cleanup.go `retireDemo` (+HoldOp, Host) | APPROVE | `HandHold` only from a `demo-claim/` hold, after the signed retirement and tombstone checks. The root purge preconditions (`instancectl/demo_cleanup.go:78-92`) are unchanged and never checked expiry. | | instancectl/demo_cleanup.go `purgeDemoWithJobs` (−ReadDir) | APPROVE | Pure extraction into `stopDemoUnits` (`demo_cleanup.go:165-240`). Same derived unit set, stop calls and cgroup-empty proofs, and the same removals afterwards. | | provision/seedreconcile.go `seedAction` (+ImportGate, Route) | APPROVE | Agent. Only adds skip and abort paths (`seedreconcile.go:102-126`). | | registry/registry.go `Registry.migrate` (+Exec, sql) | APPROVE | Fixed DDL for a one-row table. Runs as carlos or the registry child. See P3-2 on the claim wording. | ### New and reads-changed dispositions (all accepted-legacy unless noted) | unit | verdict | evidence | |---|---|---| | democlaim/snapshot.go `checkWALBounds`, `contextReader.Read`, `copySnapshotFile`, `finishSnapshot` | APPROVE | Helper only: `finishSnapshot` refuses euid 0 (`snapshot.go:82`). Its only production caller is `RunSnapshotWorkerIn`. | | democlaim/source_linux.go `Source.open`, `VerifyUnchanged` | APPROVE | openat2 with `RESOLVE_BENEATH\|NO_SYMLINKS\|NO_MAGICLINKS` and `O_NONBLOCK`; the file must be regular with nlink==1 and size ≤ 256 MiB (`source_linux.go:64-79`). Callers: root reading `/work` after the reap, and the agent reading the `NestedDBPath`-pinned DB (`host/demo_claim_snapshot.go:26-29`). | | democlaim/worker.go `RunSnapshotWorkerIn` | APPROVE | Refuses euid 0. Fixed `/work` path. `main.go` refuses any arguments. | | host/demo_claim.go `pickupDemoClaimHTTP` | APPROVE | Agent. Bounded `ReadAll`, strict decode, signature check. | | host/demo_claim_executor.go `abortDemoClaim`, `checkDemoClaimHeld`, `claimDemo`, `claimRoute`, `holdDemoClaim`, `restoreDemoClaimHolds` | APPROVE | Agent-side registry reads and hold changes. Holds are restored only for valid job IDs on this box's fleet (`:320-329`). | | host/demo_claim_snapshot.go `wireDemoClaimSnapshot` | APPROVE | Reads `rt.DBPath` only to compare it with `NestedDBPath`; the derived path is what gets opened (`:26-30`). | | host/demo_serving.go `demoJobAllowed` | APPROVE | Adds a held-row refusal. | | host/seedwiring.go `claimSeedWakeHook` | APPROVE | Equality checks against the judged record. | | units/carlos-demo-snapshot@.service `external` | APPROVE | DynamicUser, no capabilities, `NoNewPrivileges`, private network/PIDs/IPC/devices, `TemporaryFileSystem` read-only over /data, /run, /var, /opt, /etc, /tmp. Only `/work` (the per-operation mount) is writable. Runs the fixed binary read-only. Memory, time and file-size limits. `checkUnit` checks the effective properties before every start (`demo_snapshot_disk.go:121-186`). Bootstrap installs every embedded unit (`bootstrap.go:551-559`, `703`). | | instancectl/demo_claim.go `handleDemoFreeze`, `freezeDemoLocal` | APPROVE | Request ≤ 16 KiB, strict, carrying only a descriptor and a `ValidJobID`. Host passes `ValidHostShape` and `ValidateBinding`. Registry values are equality checks only, under `lockDemo`. The paths are the cgroup parent plus `InstanceID(host)`. Root opens no DB and removes nothing, so this is strictly less than the existing purge. | | instancectl/demo_cleanup.go `stopDemoUnits` | APPROVE | `ReadDir` of ExeRoot and DropInDir (root-owned) moved out of purge, keeping only canonical keys of this host. | | instancectl/demo_snapshot.go `handleDemoSnapshot`, `exportDemoSnapshot`, `handleDemoSnapshotClose`, `snapshotHeld` | APPROVE | Multipart must be exactly metadata, db, wal, each with a single header (`:83-93`). Metadata ≤ 4 KiB; IDs pass `ValidJobID`; sizes ≤ 256 MiB; `io.CopyN` plus an EOF check (`:206-232`). `Statfs` is on the fixed `demoSnapshotRoot`. Output files are fixed names created `O_EXCL` beneath the work dir. The hold is checked three times (`:154`, `:237`, `:256`). | | instancectl/demo_snapshot.go `result` | APPROVE | Runs only after `stop()` has proved the unit inactive and its cgroup empty (`:246`). `result.json` is opened through `OpenBeneath` (regular file, no symlinks, `O_NONBLOCK`) and read ≤ 1025 bytes. `snapshot.db` goes through `OpenSource` (nlink==1, regular), hashed ≤ 256 MiB + 1, then `VerifyUnchanged` (`:433-466`). The helper can plant no FIFO, symlink or device (`nodev` mount, no `CAP_MKNOD`). A hard link can only point inside the fresh image, and nlink==1 blocks it for the DB. Nothing is left running to block on. | | instancectl/demo_snapshot.go `reap`, `checkReadiness` | APPROVE | Unit names and directory entries must be `ValidJobID`, or it fails closed. The root dir is 0700 and root-owned (checked at `:569`). `RemoveAll` goes through `os.Root`, only after the stop, the unmount and a `mountinfo` absence proof (`:407-432`). | | instancectl/demo_snapshot_client.go `demoSnapshotBody.Read` | APPROVE | Agent-side client stream. | | instancectl/demo_snapshot_disk.go `checkUnit` | APPROVE | Data literal and exact comparisons. | | instancectl/demo_snapshot_linux.go `emptyCgroup`, `snapshotDiskUnmounted`, `verifySnapshotDisk` | APPROVE | Paths derived from the cgroup root plus a validated unit name. Reads the process's own `/proc/self/mountinfo`. `verifySnapshotDisk` requires a different device, ext4, bounded size, and nodev, nosuid, noexec. | | (prepareDisk, mount unit, reached from exportDemoSnapshot) | APPROVE | Pinned to `demoSnapshotRoot` and `/run/systemd/system`. `What`/`Where` come only from the validated ID; unit names use systemd escaping (`-` becomes `\x2d`). mkfs gets fixed arguments on a root-created, fallocated image. The unit file is created `O_EXCL` (`demo_snapshot_disk.go:28-91`). | | provision/demo_claim_seed.go `validateDemoClaimSeed`, `demoClaimSeedRow`, `abortDemoClaimSeed` | APPROVE | Agent. Abort removes only at the derived `NestedDBPath` (`:150-157`). | | provision/demo_claim_seed.go `removeDemoClaimOrphan` | APPROVE | Agent (carlos) only; root never runs `Reconcile`. A demo-claim row's `DBPath` is always derived: the seed requires `DerivesPaths` (`:30`) and `RouteFor` sets `DefaultDBPath`. No tenant or app input reaches it. Only the agent can write such a row, and the agent is the actor. See P3-3. | | registry/demo_claim_seed.go `CompareSeedGate`, `CreateSeedRoute`, `DeleteSeedRoute` | APPROVE | Compare-and-swap SQL on the full identity. | | registry/registry.go `DemoMoved`, `CompareDemoMoved`, `Fingerprint`, `SnapshotFingerprint` | APPROVE | One-row blob, ≤ 1 MiB on write, verified by every reader. See P3-2. | | reads: activator `doWakeOnce`, edge `importGateAdmit`, host `convergeAdopted`, provision `AssertDemoRoute`, `Reconcile`, `RouteFor` (authority C,E3) | APPROVE | All refusal-adding or agent-side. `RouteFor` derives `HoldOp` and `Status` from the console-owned `DemoClaim`. `demoFixedForWrite` stops ordinary writers changing it, and `ValidJobID` is enforced. Root uses those fields only as equality gates for actions the agent can already request. | ### Envelopes `.`, `internal/activator`, `internal/demo`, `internal/demobuild`, `internal/democlaim`, `internal/edge`, `internal/host`, `internal/host/units`, `internal/instancectl`, `internal/provision`, `internal/registry`, `internal/release`, `internal/seeds`, `internal/status`: **APPROVE**, all 14. I read every changed non-test production file the card names. The notable points: - `main.go` adds the `__demo-snapshot` entry point, which accepts no arguments. - `demo.Config` gains a `CARLOS_DEMO_CLAIM` flag. - The demobuild retirement now accepts reason `claimed`. It is signed, and root purge never checked expiry. - `release` adds the `control/demo-moved.json` scope. - `seeds` raises the protocol to 2 and parses the claim ID strictly. No change lets root open, follow, run or query anything new from a path or input a tenant, app or agent can name. No check root relies on is weakened. ### Findings (P3 only; follow-up list, no round) 1. **Stale comment.** `internal/host/units/carlos-instance-control.service:33-34` says nothing but the per-generation drop-in is written to `/run/systemd/system`. Root now also writes `&lt;escaped&gt;.mount` units there (`demo_snapshot_disk.go:58-59`). Fix: update the comment. Invariant: the root write set of `/run/systemd/system`. 2. **Claim text is wrong.** The claims for `Registry.migrate`, `CompareDemoMoved`, `Fingerprint` and `SnapshotFingerprint` describe a "monotonic generation" or "increment a local generation". The code has no generation column: the table is `(id, wire)` and the fingerprints hash the wire bytes. Fix: correct those claim lines on the next `census-propose` rerun. Invariant: census basis accuracy. 3. **Weaker path check than the existing pattern.** `removeDemoClaimOrphan` (`demo_claim_seed.go:201`, `245-250`) checks `row.DBPath` only with `NestedPaths`. That check is an OR over DBPath and Socket prefixes. The existing import rollback pins `rt.DBPath == NestedDBPath(cfg.DataDir, j.Host)` (`seedrollback.go:79-80`). This is agent-only, and the row is derived by the agent, so it is not a root finding. Fix: add `row.DBPath == NestedDBPath(cfg.DataDir, row.Host)` to the guard at `:201` for parity. Invariant: seed removal touches only the derived nested DB. 4. **Dead code.** `democlaim.ExportSQLite` (`snapshot.go:37-78`) has no production caller. It refuses root, so it is harmless. Remove it or mark it test-only. One deployment note, not a census issue: `ensureSystemUnits`' list (`systemunits.go:36`) does not include `carlos-demo-snapshot@.service`. Only bootstrap's sweep of all embedded units installs it, plus whatever the private roll script copies, which I could not check. On a box without the template, `checkReadiness` fails, so claims are refused rather than run unconfined. Confirm the roll script installs it before claims are switched on. **Verdict: APPROVED** (reviewer: Opus, other family than Astra; tip 1b764ad6).</result> <usage><subagent_tokens>201774</subagent_tokens><tool_uses>49</tool_uses><duration_ms>389400</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a95b29099847e37ad</task-id> <tool-use-id>toolu_01Wm7do2d3nh2m8pz4pbseqB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a95b29099847e37ad.output</output-file> <status>completed</status> <summary>Agent "Whole-branch review (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>**Verdict: READY AFTER FIXES.** There are no P1s and two P2s. Both P2s come from Task 8's new wiring and both are cheap to fix. I confirmed each one by running a throwaway test through `go test -overlay` from `$TMPDIR`. Nothing in the worktree was edited, and the tree is clean. ## Tests run (focused, `nice`, default Go cache) - **All pass:** `TestDemoClaimEmailToPermanent`, `FailureKeepsDemo`, `OffCompatibility`, `Readiness`, `ReadinessCache`, `ReadinessDeadline`, `RecoveryRoutes`, `Config`, `AvailabilityResponse`, `CommitRecovery`, `AccountRace`, `ProofBinding`, `BrowserIdentity`, `Transfer`, `ExpiryRace`, `Retirement`, `RequestCost*`, `SnapshotWAL` (democlaim), `FreezeRecovery` (instancectl) and `TestDemoMovedPrecedesCache` (edge). - **One caveat:** `TestDemoClaimEmailToPermanent` fails inside the bubblewrap sandbox because creating the Unix socket is blocked ("operation not permitted"). It passes outside the sandbox. CI should not hit this. - **Review Focus 1-5:** every item has its owning test, and all of them pass. ## P1 None. ## P2 **P2-1. With admission off, the job loop now wakes every second and logs each time for any `ready` demo job.** - **Fault family:** admission switch vs recovery-loop scheduling (cost/noise). - **Cause:** Task 8 lets `RunDemoJobs` run when only the demo account/fleet/domain settings are present (`internal/console/demo_jobs.go:459`, `cmd/console/main.go:715`). The loop still calls `publishReadyDemos` (`demo_jobs.go:472`) and schedules `ready` jobs at now+1s (`:485`). `publishDemo` and `finishDemoPublish` both return `errDemoJob` when admission is off (`demo_publish.go:48`, `:333`), so the job never leaves `ready`. - **Failure scenario:** a worker result lands after the console restarts with `CARLOS_DEMO_APPS` unset (the README's documented post-smoke state). The overlay witness logged 5 "demo publication" lines in 3.5 s. That continues until the demo expires, up to about 86k lines a day per job. Before Task 8 this loop did not run with admission off. - **Fix:** in `RunDemoJobs`, only call `publishReadyDemos` and the `demo_jobs` deadline query when `s.cfg.Demo.Enabled`. Keep `ReconcileDemoClaims` and the claim timer running. Add a `ready`-job case to `TestDemoClaimOffCompatibility/admissionOffIdle`. **P2-2. An aborting claim waiting for the destination to stop reads the store every 2 s with no backoff, for as long as it waits.** - **Fault family:** request cost. The plan says idle claims cause zero extra store requests. This is the same family as Task 5's P2-3, whose fix covered committed waits and the cleanup=1 abort wait but missed this sub-state. - **Cause:** `ReconcileDemoClaims` picks up aborting ops with `p.cleanup=0` (`demo_claim_transfer.go:892`). `continueDemoClaimAbort`, via `abortDemoClaimSeed`/`requestDemoClaimSeedAbort` (`:806`), reads the destination record. The retry update (`:937`) only applies doubling backoff to `committed`; everything else retries at 2 s. - **Failure scenario:** the destination box is offline when the claim aborts. The overlay witness showed 1 GET per tick after the abort, with cleanup=false. That is about 43k GETs a day per stuck op. Because cleanup stays 0, `retireDemoLocked` keeps returning `ErrDemoBusy`, so the wait does not end at source expiry either. - **Fix:** - Apply the committed backoff (2 s doubling, capped at 5 min) to `phase='aborting' AND cleanup=0`. - Reset `retry_delay`/`retry_at` when the seed state changes, or on the target app's change scope. - Extend `TestDemoClaimRequestCostAbortWait` with a seed that has not yet been rolled back. ## P3 (follow-ups) 1. **Mislabelled readiness case.** `TestDemoClaimReadiness` "placement" sets `HostClaim=true` (`demo_claim_ready_test.go:59-60`), which stops at `demo_claim_ready.go:17`. It never reaches the linux-arm64 placement check in `demoClaimSeedReady`. Add a case for a non-arm64 box in the home region. (Test coverage.) 2. **Readiness blocks and flaps.** `demoClaimReady` holds its cache mutex for the whole 10 s check, so concurrent create responses and claim handlers wait behind it. A single transient failure is cached for 45 s, and during that time every `reserved` op aborts with "disabled" (`demo_claim_transfer.go:102`). That is safe, because it refuses before freeze, but it is noisy. (Availability.) 3. **Missing baseline in the off-compatibility test.** `TestDemoClaimOffCompatibility` does not contain the plan's "ordinary email/seed/import/apps =&gt; baseline" leg. Task 8 covered it by running the existing tests separately. 4. **Lock order.** `commitDemoClaim` locks only the target account, not the demo holding account (the plan says sorted account locks). It is safe today because the source app lock is held and the op lock is consistently outermost. I checked the commit, finish, abort, pin, hold, retirement-ack and expiry paths. 5. **Intent exemption is path-based.** The R13 exemption checks `r.URL.Path != "/demo/claim/intent"` (`demo_claim_page.go:175`); the controller already noted this. Also, rotating the cookie for demo B drops that browser's status view of demo A. ## Integration checks that hold - **Identities agree across tasks:** the op ID serves as work ID, hold ID, seed `ClaimID` and verify-token HMAC input. The moved row carries the source host, `apexHost` target and `SourceExpiresAt`. - **Commit:** a single transaction rechecks membership, caps (`checkRunningThings(...,0)`), hold ack, snapshot, lifetime and generation. It clears the token hash, deletes the flows and enqueues open/moved/retire. - **No source resume after commit:** clearing the hold requires `aborting` with cleanup=1. - **Expiry vs uncommitted claims:** expiry cannot retire an uncommitted source until destination cleanup (`retireDemoLocked` pending check). - **Expiry and the moved page:** the original expiry is never extended, and the moved notice expires at it. - **Invalid moved rows are skipped,** so publication still completes and nothing strands a committed claim. - **R5a holds:** only start/verify/select, browser proof/select/link, and the not-yet-frozen reserved/freezing phases check `demoClaimEnabled`. Status, box pickup/snapshot/ack, abort, committed recovery, retirement-ack and moved notices do not, and their routes register under the account/fleet/domain settings alone. - **Switch parsing and availability:** `CARLOS_DEMO_CLAIM` accepts only unset or "1". `claimAvailable` comes from `demoClaimEnabled()`. - **Dev witnesses:** both `DevAcceptance` entry points skip without `CARLOS_DEMO_CLAIM_DEV_WITNESS=1` (R6). - **The e2e test drives the real coordinator:** real handlers, `advanceDemoClaim`, the real exporter on an actual WAL, and an HTTP snapshot. Only root stop and seed placement/first replica are faked. - **README:** the operator and API notes match the code. ## Triage of deferred minors and P3s **Must fix before merge:** none. **Already fixed on the branch:** - T1 P3-2 (audit via `auditSignInRow`). - T1 P3-3 (429 `errDemoClaimSignupBusy`). - T1 P3-4 (explicit choice parameter). - T1 P3-7 / T5 moved-notice pruning (`pruneDemoClaims`). - T3 carried P3-4 (console checks digest, size and integrity in `acceptDemoClaimSnapshotLocked`). - T4 seeds floor minimum 2 (README activation step). - T5 overwrite of the stored abort reason (now uses CASE to keep it). - T5 notify ordering (the box is notified after `hold_ready` is written). - T5 committed backoff reset (on outbox progress and retirement ack). **Can stay as follow-ups:** - T1 P3-1, P3-5, P3-6. - T2 P3-4, P3-5, P3-6, P3-7. - T3 P3-a, P3-b, R11, and agent cancels its own POST. - T4 P3-1 orphan purge, P3-2, P3-4, P3-5. - T6 non-monotonic snapshot after a domain change, SQLite busy using up a generation, `SignMoved` failing on duplicates or overflow (guarded at reservation), and P3-4 fingerprint cost. - T7 path-based intent exemption. None of these lets two apps be writable at once or strands a committed claim. The open T3/T4 items are covered by the post-merge dev witness (R6). **Verdict: READY AFTER FIXES** (P2-1, P2-2).</result> <usage><subagent_tokens>193451</subagent_tokens><tool_uses>51</tool_uses><duration_ms>514072</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bmt7dr0ge</task-id> <tool-use-id>toolu_01DyvPQGvZBLhk7yFb8Ayhj1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/bmt7dr0ge.output</output-file> <status>killed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/cifix.done ]; do sleep 60; done; tail -1 $S/cifix.log" was stopped after reaching its background time limit</summary> <note>If the work in progress still needs it, start it again with `run_in_background` and a longer `timeout`. If it already had the longest `timeout` allowed, do not restart it. Either way, report that it was stopped.</note> </task-notification>

Human

<paseo-system version="1" kind="agent-message" source-agent-id="39e7acfa-a56a-470b-8ef5-70de5c57a6f2" message-id="09a353a3-2286-4620-b3dc-88e91723d2a4" source-agent-title="agent /start demo program controller"> From 39e7acfa: the CI-fix Codex run has spent almost 4 hours running full package suites locally, one after another (host, then console). Our rule is targeted tests locally and CI as the full gate. Please stop it now: kill that codex run (its edits stay in the worktree), check the diff yourself, commit in small commits (codex author), push, and let amadan CI run on the tip. If CI fails, give Astra only the failing tests to fix, with targeted runs. Then do the final review fix wave the same way. Send me the merge sha when it lands. </paseo-system>

diff --git a/internal/console/apipolicy.go b/internal/console/apipolicy.go
index ef9264293..d1e504df6 100644
--- a/internal/console/apipolicy.go
+++ b/internal/console/apipolicy.go
@@ -556,6 +556,14 @@ func (s *Server) handleAPIPolicyPut(w http.ResponseWriter, r *http.Request) {
ran bool
)
errRefused := errors.New("console: app policy: refused")
+ // Check the holding before mutation admission reads SQL. A lapsed
+ // writer must retain the lease refusal even if its request expired.
+ _, done, ref := s.policyAttempt(ctx, hold)
+ done()
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
err = s.appMutation(ctx, acct, app, policyAuditAction, func(ctx context.Context) error {
ran = true
reply, refusal = s.writePolicy(ctx, acct, app, addr, hold, pol, next, etag, detail)
diff --git a/internal/console/claim_authority_census_test.go b/internal/console/claim_authority_census_test.go
index 1963bcaf7..bb5a0e38b 100644
--- a/internal/console/claim_authority_census_test.go
+++ b/internal/console/claim_authority_census_test.go
@@ -20,6 +20,12 @@ import (
// The plaintext is reused for that fleet's preparation/enrolment; it never
// reaches UserData or an app-scoped record. Covered by TestManagedFleetCredentials
// and TestManagedFleetCredentialsLostSealWrite.
+// publishDemoClaimSeed opens only the console-created private seed scratch
+// file handed over by acceptDemoClaimSnapshotLocked after size, digest and SQLite
+// checks. It rechecks regular-file shape, size and digest on the descriptor
+// and uploads to the durable operation's exact snapshot key. No request path
+// selects this file. TestDemoClaimFreshSeed and the snapshot refusal tests
+// cover this boundary; the open adds no root or bucket-constructor authority.
func claimAuthoritySites(t *testing.T) []string {
t.Helper()
selected := map[string]bool{
diff --git a/internal/console/demo_claim_seed.go b/internal/console/demo_claim_seed.go
index fbce95695..42d3db397 100644
--- a/internal/console/demo_claim_seed.go
+++ b/internal/console/demo_claim_seed.go
@@ -117,6 +117,7 @@ func (s *Server) createDemoClaimSeed(ctx context.Context, op claimOp) (*provisio
return nil, err
}
ctx = withDemoClaimOperation(ctx, op.ID)
+ defer s.lockAccount(op.Target.Sqid)()
defer s.lockApp(op.Target.Sqid, op.Target.App)()
defer s.lockHostname(op.Target.Host)()
fresh, err := s.demoClaimSeedOperation(ctx, op)
diff --git a/internal/console/demo_claim_seed_test.go b/internal/console/demo_claim_seed_test.go
index 564438f57..d3c402a08 100644
--- a/internal/console/demo_claim_seed_test.go
+++ b/internal/console/demo_claim_seed_test.go
@@ -78,7 +78,7 @@ func claimSeedReadyFixture(t *testing.T, s *Server, protocol int, capable bool,
if _, err := st.Put(t.Context(), key, raw, etag); err != nil {
t.Fatal(err)
}
- b := status.CollectBox(nil, status.Probes{DemoMovedReady: capable, Release: "v1.0.0", Platform: "linux-arm64", Layout: &status.LayoutReport{Mode: "nested"}}, time.Now())
+ b := status.CollectBox(nil, status.Probes{DemoClaimSeedReady: capable, DemoMovedReady: capable, Release: "v1.0.0", Platform: "linux-arm64", Layout: &status.LayoutReport{Mode: "nested"}}, time.Now())
b.Label = "box-a"
if err := status.WriteBox(t.Context(), st, b); err != nil {
t.Fatal(err)
@@ -266,3 +266,34 @@ func TestDemoClaimSeedCommitCleanup(t *testing.T) {
})
}
}
+
+func TestDemoClaimSeedWaitsForAccountLock(t *testing.T) {
+ s, op := claimSeedConsole(t)
+ unlock := s.lockAccount(op.Target.Sqid)
+ locked := true
+ defer func() {
+ if locked {
+ unlock()
+ }
+ }()
+ done := make(chan error, 1)
+ go func() { _, err := s.createDemoClaimSeed(t.Context(), op); done <- err }()
+ select {
+ case err := <-done:
+ t.Fatalf("seed creator passed a held account lock: %v", err)
+ case <-time.After(100 * time.Millisecond):
+ }
+ if _, _, err := s.readRecord(t.Context(), op.Target.Sqid, op.Target.App, op.Target.Host); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("created a record before the account lock: %v", err)
+ }
+ unlock()
+ locked = false
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("seed creator stayed blocked after account unlock")
+ }
+}
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go
index 579f953f3..ac691107b 100644
--- a/internal/console/demo_claim_target.go
+++ b/internal/console/demo_claim_target.go
@@ -256,6 +256,13 @@ func withDemoClaimOperation(ctx context.Context, id string) context.Context {
}
func (s *Store) demoClaimMutationRefusal(ctx context.Context, accountID int64, app string) *doorRefusal {
+ // A server without a SQL store has no pending claim destinations.
+ if s == nil {
+ return nil
+ }
+ if s.db == nil {
+ return &doorRefusal{Status: 503, Msg: demoClaimUnavailable}
+ }
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) {
@@ -293,6 +300,9 @@ func (s *Server) demoClaimAccountError(w http.ResponseWriter, r *http.Request, e
// 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 {
+ if s.store == nil {
+ return nil
+ }
acct, err := s.store.AccountBySqid(sqid)
if err != nil {
return err
diff --git a/internal/console/demo_claim_target_test.go b/internal/console/demo_claim_target_test.go
index c805ed5c6..fa1a46777 100644
--- a/internal/console/demo_claim_target_test.go
+++ b/internal/console/demo_claim_target_test.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "encoding/json"
"errors"
"fmt"
"net/http/httptest"
@@ -525,3 +526,38 @@ func TestDemoClaimReservationFlowErasure(t *testing.T) {
t.Fatalf("erasing credential released reservations: %d %v", n, err)
}
}
+
+func TestDemoClaimMutationGuardMissingAndBrokenStore(t *testing.T) {
+ var absent *Store
+ if ref := absent.demoClaimMutationRefusal(t.Context(), 1, "shop"); ref != nil {
+ t.Fatal("a server without a store cannot own a claim destination")
+ }
+ s, _, _ := claimTestServer(t)
+ if err := s.store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if ref := s.demoClaimMutationRefusal(t.Context(), 1, "shop"); ref == nil || ref.Status != 503 {
+ t.Fatalf("an unreadable claim marker must refuse: %+v", ref)
+ }
+}
+
+func TestDemoClaimAccountMintSkipsReservedSqid(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ // The next ID, 1168, encodes the reserved infrastructure label dev.
+ const precedingID = 1167
+ body, err := json.Marshal(domains.AccountManifest{ID: precedingID, Sqid: domains.Sqid(precedingID), Name: "shop", CreatedAt: time.Now()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.cfg.Releases.Put(t.Context(), domains.AccountManifestKey(domains.Sqid(precedingID)), body, ""); err != nil {
+ t.Fatal(err)
+ }
+ a, choices, err := s.chooseDemoClaimAccount(t.Context(), f, "")
+ if err != nil || a == nil {
+ t.Fatalf("mint: %v %v", a, err)
+ }
+ if len(choices) != 0 || a.ID != precedingID+2 || domains.IsReservedSqid(a.Sqid) {
+ t.Fatalf("claim minted reserved account: %+v choices=%v", a, choices)
+ }
+}
diff --git a/internal/console/icons_test.go b/internal/console/icons_test.go
index e626a31d6..61a8785f4 100644
--- a/internal/console/icons_test.go
+++ b/internal/console/icons_test.go
@@ -58,10 +58,11 @@ func TestSwitcherChromeIsInlineSVGNotTextGlyphs(t *testing.T) {
// inline and its icons inline, and that is the whole of it. Vendoring the
// icons is what keeps this true.
//
-// One template is allowed subresources: the operator shell (opshell.html)
+// The operator shell (opshell.html) is allowed subresources. It
// loads Rastrillo's stylesheets and scripts, and it loads them from this
// origin only, through the {{asset "..."}} template func (/static/{hash}/...).
-// sameOriginAssetTags is the exact shape it may use; nothing else passes.
+// sameOriginAssetTags is the exact shape it may use. The demo claim page
+// may load only its embedded demo_claim.js through the same asset helper.
func TestConsoleTemplatesFetchNothingOffOrigin(t *testing.T) {
err := fs.WalkDir(tmplFS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
@@ -83,7 +84,7 @@ func TestConsoleTemplatesFetchNothingOffOrigin(t *testing.T) {
// The allowance for opshell.html is narrow: a literal off-origin URL in the
// same tags still fails, as does an {{asset}} tag carrying a second,
-// URL-shaped attribute, and no other template gets the allowance at all.
+// URL-shaped attribute. No other template gets the shell's general asset allowance.
func TestConsoleTemplatesOffOriginCheckRefusesLiteralURLsInTheShell(t *testing.T) {
shell, err := tmplFS.ReadFile("templates/opshell.html")
if err != nil {
@@ -128,6 +129,9 @@ func offOriginFetches(path, src string) []string {
if path == "templates/opshell.html" {
src = sameOriginAssetTags.ReplaceAllString(src, "")
}
+ if path == "templates/demo_claim.html" {
+ src = strings.ReplaceAll(src, `<script src="{{asset "demo_claim.js"}}"></script>`, "")
+ }
var found []string
for _, bad := range banned {
if strings.Contains(src, bad) {
@@ -216,3 +220,23 @@ func TestVendoredIconsAreSelfContained(t *testing.T) {
}
}
}
+
+func TestDemoClaimTemplateRefusesOtherSubresources(t *testing.T) {
+ const path = "templates/demo_claim.html"
+ const allowed = `<script src="{{asset "demo_claim.js"}}"></script>`
+ if got := offOriginFetches(path, allowed); len(got) != 0 {
+ t.Fatal(got)
+ }
+ for _, tag := range []string{
+ `<script src="https://example.com/demo_claim.js"></script>`,
+ `<script src="//example.com/demo_claim.js"></script>`,
+ `<script src="{{asset "https://example.com/demo_claim.js"}}"></script>`,
+ `<script src="{{asset "demo_claim.js"}}" data-url="https://example.com"></script>`,
+ `<script src="{{asset "other.js"}}"></script>`,
+ `<img src="https://example.com/image.png">`,
+ } {
+ if got := offOriginFetches(path, allowed+tag); len(got) == 0 {
+ t.Errorf("allowed %s", tag)
+ }
+ }
+}
diff --git a/internal/console/recordcreators_guard_test.go b/internal/console/recordcreators_guard_test.go
index 883c92c73..c344685f6 100644
--- a/internal/console/recordcreators_guard_test.go
+++ b/internal/console/recordcreators_guard_test.go
@@ -32,8 +32,9 @@ func TestEveryInstanceRecordCreatorIsUnderTheAccountLock(t *testing.T) {
server + "createSeedRecord": 1,
},
server + "createRecordMarkedLocked": {
- server + "createRecordMarked": 1,
- server + "placeDemoLocked": 1, // publishDemo holds account, withDemoLocked app, placeDemoLocked hostname
+ server + "createDemoClaimSeed": 1, // account -> app -> hostname held inside the creator
+ server + "createRecordMarked": 1,
+ server + "placeDemoLocked": 1, // publishDemo holds account, withDemoLocked app, placeDemoLocked hostname
},
server + "placeDemoLocked": {
server + "publishDemo": 2, // account lock before either withDemoLocked step
@@ -51,6 +52,7 @@ func TestEveryInstanceRecordCreatorIsUnderTheAccountLock(t *testing.T) {
server + "createSeedRecord": 1,
},
server + "createRecordWithLifetimeLocked": {
+ server + "createDemoClaimSeed": 1, // same account -> app -> hostname hold
server + "placeDemoLocked": 1, // same account -> app -> hostname hold as the marked create
server + "createRecordWithLifetime": 1,
server + "attachFirstRouteLocked": 1, // Kind static, no escrow
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt
index ee25b6e1f..f54897ec6 100644
--- a/internal/console/testdata/claim-authority-sites.txt
+++ b/internal/console/testdata/claim-authority-sites.txt
@@ -158,3 +158,4 @@ managedhistory.go|managedCredentialsHeld|seal.Open(sealed)
managedhistory.go|openManagedEnrolCredentials|seal.Open(sealed)
hacapacity_observe.go|Get|os.Open(filepath.Join(s.directory, filepath.FromSlash(key)))
hacapacity_observe.go|dirPage|os.Open(filepath.Join(s.directory, filepath.FromSlash(prefix)))
+demo_claim_seed.go|publishDemoClaimSeed|os.Open(path)
diff --git a/internal/domains/reserved_test.go b/internal/domains/reserved_test.go
index 34f9e97db..b2b9049b5 100644
--- a/internal/domains/reserved_test.go
+++ b/internal/domains/reserved_test.go
@@ -290,8 +290,9 @@ func TestAccountCreationPathsCensus(t *testing.T) {
"internal/console/server.go", // Server.mintAccount: landing, /accounts/new, /auth/cli/accounts
},
"s.mintAccount(": {
- "internal/console/authcli.go", // POST /auth/cli/accounts
- "internal/console/server.go", // landing mint and POST /accounts/new
+ "internal/console/authcli.go", // POST /auth/cli/accounts
+ "internal/console/demo_claim_target.go", // person-locked mint via Server.mintAccount and domains.MintAccount
+ "internal/console/server.go", // landing mint and POST /accounts/new
},
".CreateAccount(": {"internal/console/server.go"}, // inside Server.mintAccount only
}