fix: isolate moved-notice faults from the demo stream
Keep serving, retirement and claim delivery running after moved snapshot faults. Consume rejected generations and back off transport retries. Cache signed notices and send them only on connect or change, validate domains before reservation, and advertise moved support from the configured edge.
internal/console/apidemobox.go+23 −4internal/console/demo_claim_moved.go+31 −3internal/console/demo_claim_moved_test.go+162 −2internal/console/demo_claim_seed_test.go+1 −1internal/console/demo_claim_target.go+4 −0internal/console/demo_retirement_http_test.go+11 −4internal/console/server.go+1 −0internal/edge/demo_moved.go+7 −0internal/edge/demo_moved_test.go+27 −0internal/host/agent.go+10 −9internal/host/demo_claim_executor_test.go+30 −2internal/host/demo_jobs.go+7 −1internal/host/demo_moved.go+13 −7internal/host/demo_moved_test.go+104 −0internal/host/demo_retirement_stream_test.go+39 −1internal/status/snapshot.go+6 −1internal/status/snapshot_test.go+16 −1
CI failed — run details
Intent
<task-notification> <task-id>byt6k52uq</task-id> <tool-use-id>toolu_01CFH2QT3zeXRsAVdmQch6qM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/byt6k52uq.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t6.done ]; do sleep 30; done; tail -1 $S/t6.log" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a85016b7f9dc86db4</task-id> <tool-use-id>toolu_01NVk48FUnUPNzLLfkuFxgXU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/a85016b7f9dc86db4.output</output-file> <status>completed</status> <summary>Agent "Review Task 6 (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: ✅**, with two delivery-robustness gaps (P2s below). - **Risk 1, ordering (✅).** `ServeHTTP` calls `handleDemoRequest` first (internal/edge/edge.go:1903). The moved check is the first statement there (internal/edge/demo.go:104-107), ahead of route lookup, refusal, cache (edge.go:2623), caps, upgrade and activation. The merged `demoMovedPage` hook now calls `serveDemoMoved` instead of a second hook. Plain HTTP also checks it before redirecting. The old-cache, no-route and pending-route tests drive the real `ServeHTTP`. - **Risk 2, target and response (✅).** - The source must be exactly one label under `Demo.Domain` (`demoHost` plus `MovedDomains`). The target must be exactly app.account under `AppsDomain`. - The console rechecks `TargetHost == apexHost(target_sqid, app)` at commit and again when signing. The edge rechecks the domains on load. - The link is `https://` plus the host, through `html/template`. - GET returns 200 with HTML, HEAD returns headers only, and every other method gets 410 with no forwarding. Headers are no-store, no-referrer, nosniff, and a CSP of `default-src 'none'` with `form-action 'none'` and sandbox. - The page sets no redirect, cookie or token and wakes nothing. - **Risk 3, expiry (✅).** Each request checks `now >= ExpiresAt`. Pruning deletes only `demo_moved_notices` rows past expiry, and the host tombstone is untouched. The snapshot query reads notices, ops and commits but never `apps` or the source's serving state. - **Risk 4, delivery (✅ on the happy path).** - The notice key has one change scope (internal/release/changeindex.go:56). It is read at startup and when its generation changes, inside the existing `fastTick`, with no new ticker. - The registry stores the snapshot as a separate CAS row, and the edge re-verifies those bytes on every Reload. - Demo-fleet boxes get the snapshot over the existing stream. - **Risk 5, capacity (✅).** Capacity is reserved in the reservation writer transaction and rechecked inside the commit transaction, counting envelope and base64 size. A live notice may not change or disappear (`MovedMonotonic`). The signing separator is exactly `carlos demo moved v1\n`. - **Risk 6, Task 5 follow-ups (✅).** `hold_ready` is now written before `NotifyDemoBox` (demo_claim_transfer.go:313-320). The retry backoff resets when a pass shrinks the outbox, and a retirement ack sets `retry_at=0` and signals the job loop. Lock order stays op lock then app lock, matching every other acquisition I found. Nothing new polls. - **Root census (no findings).** I found no new root reads. Root opens the registry through the remote child, which only gains an additive `CREATE TABLE` and a fingerprint term. The registry's `DemoMoved` and `CompareDemoMoved` refuse remote use. The new `release.BumpChangeIndex` writes only `control/changes.json`. - **⚠️ Not verified from the diff.** - That every production edge sets `staticPub` (it comes from `CARLOS_RELEASE_PUBKEY` plus the bucket, edge.go:4815-4836) in the same configurations where the agent advertises `demo-moved-v1`. - The full body of internal/host/demo_moved_test.go. - I ran no tests. 2) **Findings** **P2-1. A moved-snapshot fault tears down the whole demo stream.** Fault family: failure isolation. An advisory notice is gating the serving, retirement and claim channel. - **Box side.** internal/host/demo_jobs.go (diff ~1793-1797): `if err := installDemoMoved(...); err != nil { return err }` ends `Connect`. - **Console side.** internal/console/apidemobox.go:218-226: `sendDemoPending` returns the `demoMovedSnapshot` error before `sendDemoServing` and the retirement replay. Any snapshot error therefore closes every capable peer's stream. - **Triggers:** - The console DB is restored to an earlier point, losing a committed live notice. Every box's `MovedMonotonic` check then fails until that notice's original expiry, up to 24 h. - The console clock runs ahead of a box at a notice's expiry boundary. - The persisted snapshot was signed by a previous key. - A CAS race with the same box's fast-tick reader. - An `AppsDomain` or `Demo.Domain` config change makes one row fail `apexHost`/`MovedDomains`, which fails the whole snapshot. - **Failure scenario.** The console replays the snapshot first on every connect and on every 10 s heartbeat wake, so the stream reconnects in a loop. Serving control lapses and demo traffic on that box fails closed. Retirement receipts and claim work stop for up to 24 h, or indefinitely after a key rotation. - **Fix:** - On the box, log the install error, keep the prior verified mapping and continue reading the stream. - On the console, log and skip the moved frame when building the snapshot fails, and let the outbox `moved` step carry the retry. **P2-2. A permanent install failure turns the normal-edge reader into a 2-second bucket poll.** Fault family: request cost ("no new per-box polling"). - **Evidence.** In `demoMovedReader.pass` (internal/host/demo_moved.go), the generation is consumed only on success. Any install error leaves it pending, so every `fastTick` (`fastTickEvery = 2s`, agent.go:2579) issues another `Get` of control/demo-moved.json. - **Failure scenario.** Use the P2-1 triggers. A console restore makes every box GET every 2 s, about 43k GETs per box per day, until the lost notice expires. A key rotation or corrupt persisted bytes make it last forever. - **Fix.** Consume the generation on a verify, monotonic or CAS failure, keeping the prior mapping and logging once. Retry only transport errors, with backoff or at the existing backstop. **P3s** - **P3-1. The full snapshot is re-signed and re-sent on every heartbeat.** apidemobox.go:181 wakes the peer on each 10 s heartbeat, and :196 then sets `replayRetirements=true`. Each wake re-queries up to 10,000 rows, signs up to 1 MiB with Ed25519, sends about 1.4 MiB per peer, and the 2 GB box re-verifies it. Fix: cache the signed bytes until notices change, and send on connect or change only. Family: CPU and bandwidth cost, not object-store cost. - **P3-2. The target-domain check happens only at commit, after the copy.** The `apexHost`/`MovedDomains` check sits at demo_claim_transfer.go:~656. `reserveDemoClaimRows` only runs `MovedFits` (DNS shape), so a mismatched target freezes and copies the source, then aborts. Fix: also check at reservation, before freeze. - **P3-3. The box-status half of the capability gate checks only freshness.** status/snapshot.go:1177 always advertises `demo-moved-v1`, so that half of `demoClaimMovedReady` only proves the status is fresh; the edges-file capability is the real gate. That capability also ignores the edge's own `staticPub`, `Demo.Domain` and `AppsDomain`. An edge missing these advertises the capability and then drops every snapshot. Fix: also require them when advertising. - **P3-4. The registry fingerprint hashes the whole snapshot.** It hex-hashes up to 1 MiB of snapshot bytes on every fingerprint pass (registry.go:~4233, ~4526). Fix: hash a stored digest instead. 3) **Strengths** - The notice table is independent of `apps` and source purge, and only open destinations are published. - Capacity reservation sits inside the same writer transaction as the app reservation, with a recheck at commit. - `MovedMonotonic` is enforced in both host and edge, and the edge re-verifies on restart. - The tests are strong: a real primed cache, activator-silence checks, escaping, a wrong signing context, and a stream frame larger than the old limit. - The Task 5 follow-ups are minimal and keep the lock order. 4) **Verdict: READY AFTER FIXES** (P2-1, P2-2). Inputs read: - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/.superpowers/sdd/2026-11-04-agent-start-demo-3-claim/task-6-brief.md - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/.superpowers/sdd/2026-11-04-agent-start-demo-3-claim/task-6-report.md - /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-3/.superpowers/sdd/2026-11-04-agent-start-demo-3-claim/review-8f2b67d5..3f29819e.diff</result> <usage><subagent_tokens>136554</subagent_tokens><tool_uses>29</tool_uses><duration_ms>334730</duration_ms></usage> </task-notification>
Attributed to this commit: 11.5 g CO₂e (1,348,475 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/apidemobox.go b/internal/console/apidemobox.go| index 848b97064..6a267ba89 100644 |
| --- a/internal/console/apidemobox.go |
| +++ b/internal/console/apidemobox.go |
| @@ -1,9 +1,11 @@ |
| package console |
| import ( |
| + "bytes" |
| "context" |
| "errors" |
| "io" |
| + "log" |
| "net/http" |
| "os" |
| "sort" |
| @@ -21,6 +23,8 @@ import ( |
| const demoBuildStreamPath = "/api/box/demo-builds" |
| type demoPeer struct { |
| + movedWire []byte |
| + movedError string |
| serving *demo.ServingControl |
| issued []demo.ServingControl |
| servingAck int64 |
| @@ -206,6 +210,7 @@ func (s *Server) sendDemoPending(ctx context.Context, p *demoPeer, replayRetirem |
| ok := s.demoPeerOK(p) |
| hint := p.reconcile |
| ready := p.ready |
| + movedWire, movedError := p.movedWire, p.movedError |
| p.reconcile = false |
| s.demoJobs.mu.Unlock() |
| if !ok { |
| @@ -218,10 +223,24 @@ func (s *Server) sendDemoPending(ctx context.Context, p *demoPeer, replayRetirem |
| if replayRetirements && ready.MovedCapability == democlaim.MovedCapability { |
| wire, err := s.demoMovedSnapshot(ctx) |
| if err != nil { |
| - return err |
| - } |
| - if err = send(demobuild.StreamMessage{Moved: wire}); err != nil { |
| - return err |
| + if message := err.Error(); message != movedError { |
| + log.Printf("console: demo moved snapshot: %s", message) |
| + s.demoJobs.mu.Lock() |
| + p.movedError = message |
| + s.demoJobs.mu.Unlock() |
| + } |
| + } else { |
| + s.demoJobs.mu.Lock() |
| + p.movedError = "" |
| + s.demoJobs.mu.Unlock() |
| + if !bytes.Equal(movedWire, wire) { |
| + if err = send(demobuild.StreamMessage{Moved: wire}); err != nil { |
| + return err |
| + } |
| + s.demoJobs.mu.Lock() |
| + p.movedWire = wire |
| + s.demoJobs.mu.Unlock() |
| + } |
| } |
| } |
| controlled, err := s.sendDemoServing(ctx, p) |
diff --git a/internal/console/demo_claim_moved.go b/internal/console/demo_claim_moved.go| index 8390a8c42..0f16b7b9b 100644 |
| --- a/internal/console/demo_claim_moved.go |
| +++ b/internal/console/demo_claim_moved.go |
| @@ -3,10 +3,13 @@ package console |
| import ( |
| "bytes" |
| "context" |
| + "crypto/sha256" |
| "database/sql" |
| "errors" |
| + "log" |
| "os" |
| "slices" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/democlaim" |
| @@ -14,6 +17,14 @@ import ( |
| "github.com/carlosframework/platform/internal/status" |
| ) |
| +type demoMovedCache struct { |
| + mu sync.Mutex |
| + notices []democlaim.Moved |
| + key [32]byte |
| + wire []byte |
| + rejected map[string]bool |
| +} |
| + |
| func (s *Server) demoClaimMovedReady(ctx context.Context) error { |
| snap, err := s.liveEdges(ctx) |
| if err != nil || !snap.EvidenceComplete() || len(snap.Files) == 0 { |
| @@ -78,6 +89,10 @@ func reserveDemoMovedCapacity(ctx context.Context, tx *sql.Tx, candidate *democl |
| // This source does not join apps or depend on source serving membership. |
| // Open must have completed before any member of the snapshot is published. |
| func (s *Server) demoMovedSnapshot(ctx context.Context) ([]byte, error) { |
| + s.demoMoved.mu.Lock() |
| + defer s.demoMoved.mu.Unlock() |
| + rejected := map[string]bool{} |
| + defer func() { s.demoMoved.rejected = rejected }() |
| rows, err := s.store.db.QueryContext(ctx, `SELECT n.demo_id,n.host,n.target_host,n.expires_at,o.target_sqid,o.app |
| FROM demo_moved_notices n JOIN demo_claim_ops o ON o.demo_id=n.demo_id |
| JOIN demo_claim_commits c ON c.operation_id=o.id |
| @@ -93,8 +108,12 @@ func (s *Server) demoMovedSnapshot(ctx context.Context) ([]byte, error) { |
| if err = rows.Scan(&r.DemoID, &r.Host, &r.TargetHost, &r.ExpiresAt, &acct, &app); err != nil { |
| return nil, err |
| } |
| - if r.TargetHost != s.apexHost(acct, app) || !democlaim.MovedDomains(r, s.cfg.Demo.Domain, s.cfg.AppsDomain) { |
| - return nil, democlaim.ErrMoved |
| + if r.TargetHost != s.apexHost(acct, app) || !democlaim.MovedDomains(r, s.cfg.Demo.Domain, s.cfg.AppsDomain) || !democlaim.MovedFits([]democlaim.Moved{r}) { |
| + rejected[r.DemoID] = true |
| + if !s.demoMoved.rejected[r.DemoID] { |
| + log.Printf("console: demo moved: skipping invalid notice %s", r.DemoID) |
| + } |
| + continue |
| } |
| notices = append(notices, r) |
| if len(notices) > democlaim.MaxMovedEntries { |
| @@ -104,7 +123,16 @@ func (s *Server) demoMovedSnapshot(ctx context.Context) ([]byte, error) { |
| if err = rows.Err(); err != nil { |
| return nil, err |
| } |
| - return democlaim.SignMoved(s.cfg.Key, notices) |
| + key := sha256.Sum256(s.cfg.Key) |
| + if s.demoMoved.wire != nil && s.demoMoved.key == key && slices.Equal(s.demoMoved.notices, notices) { |
| + return s.demoMoved.wire, nil |
| + } |
| + wire, err := democlaim.SignMoved(s.cfg.Key, notices) |
| + if err != nil { |
| + return nil, err |
| + } |
| + s.demoMoved.notices, s.demoMoved.key, s.demoMoved.wire = notices, key, wire |
| + return wire, nil |
| } |
| func (s *Server) publishDemoMoved(ctx context.Context) error { |
| defer s.acctLocks.lock("demo-moved-publication")() |
diff --git a/internal/console/demo_claim_moved_test.go b/internal/console/demo_claim_moved_test.go| index 555949020..6765f50e6 100644 |
| --- a/internal/console/demo_claim_moved_test.go |
| +++ b/internal/console/demo_claim_moved_test.go |
| @@ -6,11 +6,15 @@ import ( |
| "encoding/binary" |
| "errors" |
| "fmt" |
| + "net/http/httptest" |
| "strings" |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| "github.com/carlosframework/platform/internal/democlaim" |
| + "github.com/carlosframework/platform/internal/interactive" |
| + "golang.org/x/net/websocket" |
| ) |
| func TestDemoMovedPublication(t *testing.T) { |
| @@ -48,8 +52,13 @@ func TestDemoMovedPublication(t *testing.T) { |
| if _, err = s.store.db.Exec(`UPDATE demo_moved_notices SET target_host=? WHERE demo_id=?`, target, op.DemoID); err != nil { |
| t.Fatal(err) |
| } |
| - if _, err = s.demoMovedSnapshot(t.Context()); err == nil { |
| - t.Fatal("published destination not derived from committed app", target) |
| + wire, err = s.demoMovedSnapshot(t.Context()) |
| + if err != nil { |
| + t.Fatal("bad row failed the snapshot", err) |
| + } |
| + rows, err = democlaim.VerifyMoved(s.cfg.ReleasePub, wire) |
| + if err != nil || len(rows) != 0 { |
| + t.Fatal("published destination not derived from committed app", target, rows, err) |
| } |
| } |
| if _, err = s.store.db.Exec(`UPDATE demo_moved_notices SET target_host=? WHERE demo_id=?`, op.Target.Host, op.DemoID); err != nil { |
| @@ -231,3 +240,154 @@ func TestDemoMovedRetirementAckWakes(t *testing.T) { |
| t.Fatal("ack did not wake", p.RetryAt, err) |
| } |
| } |
| + |
| +func TestDemoMovedSnapshotCache(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimAdvance(t, s, op) |
| + first, err := s.demoMovedSnapshot(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for range 10 { |
| + next, err := s.demoMovedSnapshot(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if &first[0] != &next[0] { |
| + t.Fatal("unchanged snapshot signed again instead of reusing cached bytes") |
| + } |
| + } |
| + if _, err = s.store.db.Exec(`UPDATE demo_moved_notices SET expires_at=1`); err != nil { |
| + t.Fatal(err) |
| + } |
| + next, err := s.demoMovedSnapshot(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := democlaim.VerifyMoved(s.cfg.ReleasePub, next) |
| + if err != nil || len(rows) != 0 { |
| + t.Fatal("expiry did not invalidate cache", err) |
| + } |
| +} |
| + |
| +func TestDemoMovedPendingIsolationAndHeartbeat(t *testing.T) { |
| + for _, fault := range []bool{false, true} { |
| + t.Run(fmt.Sprint(fault), func(t *testing.T) { |
| + s, op, _ := claimTransferFixture(t) |
| + claimAdvance(t, s, op) |
| + if fault { |
| + if _, err := s.store.db.Exec(`ALTER TABLE demo_moved_notices RENAME TO unavailable_notices`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + template := s.demoJobs.peers["box"] |
| + result := make(chan error, 1) |
| + server := httptest.NewServer(interactive.NewServer(func(ws *websocket.Conn) { |
| + defer ws.Close() |
| + p := *template |
| + p.ws = ws |
| + s.demoJobs.mu.Lock() |
| + s.demoJobs.peers["box"] = &p |
| + s.demoJobs.mu.Unlock() |
| + for range 6 { |
| + p.ready.ServingProbe++ |
| + if err := s.sendDemoPending(t.Context(), &p, true); err != nil { |
| + result <- err |
| + return |
| + } |
| + } |
| + result <- nil |
| + })) |
| + defer server.Close() |
| + for connection := 0; connection < 2; connection++ { |
| + target, _ := interactive.WebSocketURL(server.URL) |
| + ws, err := interactive.DialFrame(t.Context(), target, server.URL, nil, democlaim.MaxMovedWire*2) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ws.Close() |
| + _ = ws.SetReadDeadline(time.Now().Add(3 * time.Second)) |
| + moved, serving, claims := 0, 0, 0 |
| + for { |
| + var msg demobuild.StreamMessage |
| + if websocket.JSON.Receive(ws, &msg) != nil { |
| + break |
| + } |
| + if len(msg.Moved) > 0 { |
| + moved++ |
| + } |
| + if msg.Serving != nil { |
| + serving++ |
| + } |
| + if len(msg.Claim) > 0 { |
| + claims++ |
| + } |
| + } |
| + if err = <-result; err != nil { |
| + t.Fatalf("moved fault stopped stream: %v", err) |
| + } |
| + want := 1 |
| + if fault { |
| + want = 0 |
| + } |
| + if moved != want || serving != 6 || claims != 6 { |
| + t.Fatalf("moved=%d serving=%d claims=%d", moved, serving, claims) |
| + } |
| + ws.Close() |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoMovedDomainBeforeReservation(t *testing.T) { |
| + for _, fault := range []string{"demo-domain", "apps-domain"} { |
| + t.Run(fault, func(t *testing.T) { |
| + s, _, token := claimTestServer(t) |
| + f, _ := claimProved(t, s, token, "shop@example.com") |
| + acct := claimAccount(t, s, 501, f.Person, RoleOwner) |
| + if fault == "demo-domain" { |
| + s.cfg.Demo.Domain = "other.example.com" |
| + } else { |
| + s.cfg.AppsDomain = "bad_domain.example.com" |
| + } |
| + _, err := s.reserveDemoClaim(t.Context(), f, acct, regionReq{}) |
| + if !errors.Is(err, democlaim.ErrMoved) { |
| + t.Fatalf("reservation did not refuse moved domain: %v", err) |
| + } |
| + var n int |
| + if err = s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_ops`).Scan(&n); err != nil || n != 0 { |
| + t.Fatal("reserved before domain check", n, err) |
| + } |
| + apps, err := s.store.AppsIn(acct.ID) |
| + if err != nil || len(apps) != 0 { |
| + t.Fatal("destination created before domain check", apps, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoMovedSnapshotSkipsBadRow(t *testing.T) { |
| + s, op, data := claimTransferFixture(t) |
| + claimToVerify(t, s, op, data) |
| + claimAdvance(t, s, op) |
| + // A second committed operation has a corrupt notice; the first stays publishable. |
| + _, err := s.store.db.Exec(`INSERT INTO demo_claim_ops SELECT 'other-op','',?,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 FROM demo_claim_ops WHERE id=?`, "AAAAAAAAAAAAAAAAAAAAAA", op.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.db.Exec(`INSERT INTO demo_claim_commits VALUES('other-op',?,?)`, "AAAAAAAAAAAAAAAAAAAAAA", time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = s.store.db.Exec(`INSERT INTO demo_moved_notices VALUES(?,?,?,?)`, "AAAAAAAAAAAAAAAAAAAAAA", "other."+s.cfg.Demo.Domain, "https://evil.example", op.SourceExpiresAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + wire, err := s.demoMovedSnapshot(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := democlaim.VerifyMoved(s.cfg.ReleasePub, wire) |
| + if err != nil || len(rows) != 1 || rows[0].DemoID != op.DemoID { |
| + t.Fatalf("bad row suppressed healthy notice: %+v %v", rows, err) |
| + } |
| +} |
diff --git a/internal/console/demo_claim_seed_test.go b/internal/console/demo_claim_seed_test.go| index 9cf67efac..564438f57 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{Release: "v1.0.0", Platform: "linux-arm64", Layout: &status.LayoutReport{Mode: "nested"}}, time.Now()) |
| + b := status.CollectBox(nil, status.Probes{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) |
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go| index f0a642e39..4575a0e41 100644 |
| --- a/internal/console/demo_claim_target.go |
| +++ b/internal/console/demo_claim_target.go |
| @@ -13,6 +13,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/democlaim" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/seeds" |
| ) |
| @@ -181,6 +182,9 @@ func (s *Server) reserveDemoClaim(ctx context.Context, f claimFlow, acct *Accoun |
| } else if present { |
| return claimOp{}, ErrDemoNameTaken |
| } |
| + if !democlaim.MovedDomains(democlaim.Moved{Host: d.Host, TargetHost: host}, s.cfg.Demo.Domain, s.cfg.AppsDomain) { |
| + return claimOp{}, democlaim.ErrMoved |
| + } |
| 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. |
diff --git a/internal/console/demo_retirement_http_test.go b/internal/console/demo_retirement_http_test.go| index 7fad96f23..a9c592ea4 100644 |
| --- a/internal/console/demo_retirement_http_test.go |
| +++ b/internal/console/demo_retirement_http_test.go |
| @@ -12,12 +12,13 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/democlaim" |
| "github.com/carlosframework/platform/internal/interactive" |
| "golang.org/x/net/websocket" |
| ) |
| func TestDemoOfflineRetirementHTTP(t *testing.T) { |
| - for _, mode := range []string{"ready", "admission-off", "builder-not-ready"} { |
| + for _, mode := range []string{"ready", "admission-off", "builder-not-ready", "moved-fault"} { |
| t.Run(mode, func(t *testing.T) { |
| s, d, _, _ := demoPublishFixture(t) |
| life, _ := s.store.AppLife(d.AccountID, d.App) |
| @@ -50,6 +51,12 @@ func TestDemoOfflineRetirementHTTP(t *testing.T) { |
| if mode == "builder-not-ready" { |
| ready = demobuild.WorkerReady{} |
| } |
| + if mode == "moved-fault" { |
| + ready.MovedCapability = democlaim.MovedCapability |
| + if _, err := s.store.db.Exec(`ALTER TABLE demo_moved_notices RENAME TO unavailable_notices`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| server := httptest.NewServer(s.mux) |
| defer server.Close() |
| defer s.closeDemoPeers() |
| @@ -95,7 +102,7 @@ func TestDemoOfflineRetirementHTTP(t *testing.T) { |
| ws.Close() |
| t.Fatal("expected hint after retirement") |
| } |
| - if mode == "ready" { |
| + if mode == "ready" || mode == "moved-fault" { |
| if err := websocket.JSON.Receive(ws, &after); err != nil { |
| ws.Close() |
| t.Fatal(err) |
| @@ -106,7 +113,7 @@ func TestDemoOfflineRetirementHTTP(t *testing.T) { |
| t.Fatalf("queued job did not follow retirement: %v", err) |
| } |
| } |
| - if mode != "ready" { |
| + if mode != "ready" && mode != "moved-fault" { |
| ws.SetReadDeadline(time.Now().Add(50 * time.Millisecond)) |
| var extra demobuild.StreamMessage |
| if err := websocket.JSON.Receive(ws, &extra); err == nil { |
| @@ -120,7 +127,7 @@ func TestDemoOfflineRetirementHTTP(t *testing.T) { |
| first.Close() |
| second := connect() |
| defer second.Close() |
| - if mode == "ready" { |
| + if mode == "ready" || mode == "moved-fault" { |
| // The existing ten-second heartbeat must keep jobs flowing without |
| // replaying a delivered retirement. Connect and wake still replay it. |
| second.SetReadDeadline(time.Now().Add(12 * time.Second)) |
diff --git a/internal/console/server.go b/internal/console/server.go| index 8d79de426..0bb740ecf 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1007,6 +1007,7 @@ type Server struct { |
| demoStopMu sync.Mutex |
| demoStopDeadlines map[int64]time.Time |
| demoJobs demoJobHub |
| + demoMoved demoMovedCache |
| managed managedConfigState |
| managedWorker managedWorkerState |
| managedExtra managedExtraChecks |
diff --git a/internal/edge/demo_moved.go b/internal/edge/demo_moved.go| index 23e6ff28d..dcdd2aa2d 100644 |
| --- a/internal/edge/demo_moved.go |
| +++ b/internal/edge/demo_moved.go |
| @@ -1,15 +1,22 @@ |
| package edge |
| import ( |
| + "crypto/ed25519" |
| "html/template" |
| "net/http" |
| "time" |
| + "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/democlaim" |
| ) |
| var movedPage = template.Must(template.New("moved").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>{{.Title}}</title></head><body><main><h1>{{.Title}}</h1><p>{{.Body}}</p><p><a href="https://{{.Host}}" rel="noreferrer">{{.Link}}</a></p></main></body></html>`)) |
| +// DemoMovedReady reports whether this edge can verify and serve moved notices. |
| +func (e *Edge) DemoMovedReady() bool { |
| + return e != nil && len(e.staticPub) == ed25519.PublicKeySize && demo.ValidDomain(e.demo.Domain) && demo.ValidDomain(e.appsDomain) |
| +} |
| + |
| func (e *Edge) loadDemoMoved() { |
| wire, err := e.reg.DemoMoved() |
| if err != nil || len(wire) == 0 { |
diff --git a/internal/edge/demo_moved_test.go b/internal/edge/demo_moved_test.go| index 5bea49cce..ffa2f7a02 100644 |
| --- a/internal/edge/demo_moved_test.go |
| +++ b/internal/edge/demo_moved_test.go |
| @@ -160,3 +160,30 @@ func TestDemoMovedRevalidatesRegistry(t *testing.T) { |
| t.Fatal("ordinary host intercepted") |
| } |
| } |
| + |
| +func TestDemoMovedCapabilityConfiguration(t *testing.T) { |
| + key := ed25519.NewKeyFromSeed(make([]byte, 32)).Public().(ed25519.PublicKey) |
| + for _, missing := range []string{"none", "key", "short-key", "demo-domain", "apps-domain"} { |
| + t.Run(missing, func(t *testing.T) { |
| + e := &Edge{staticPub: key, appsDomain: "apps.example.com"} |
| + e.demo.Domain = "demos.example.com" |
| + switch missing { |
| + case "key": |
| + e.staticPub = nil |
| + case "short-key": |
| + e.staticPub = []byte{1} |
| + case "demo-domain": |
| + e.demo.Domain = "" |
| + case "apps-domain": |
| + e.appsDomain = "" |
| + } |
| + if got := e.DemoMovedReady(); got != (missing == "none") { |
| + t.Fatalf("configured=%v with missing %s", got, missing) |
| + } |
| + }) |
| + } |
| + var e *Edge |
| + if e.DemoMovedReady() { |
| + t.Fatal("absent edge advertised capability") |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 2a7d07888..7e2de4995 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1030,7 +1030,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // sees them (cfg.HostWrites.Enabled, set by configureWakeClaims). |
| buildStateClaims := cfg != nil && cfg.HostWrites.Enabled |
| collectBuildStates := func() (map[string]status.BuildStatePins, error) { return buildStatePins(reg, buildStateClaims) } |
| - go statusLoop(reg, svc, collectBuildStates, egressStatus, boxJudge) |
| + go statusLoop(reg, svc, collectBuildStates, egressStatus, boxJudge, func() bool { return demoEdge.Load().DemoMovedReady() }) |
| // The memory early-warning (memory-pressure spec §2.4): per box, gated |
| // by CARLOS_HOST_METRICS — one log line and nothing else where unset. |
| go memwatchLoop() |
| @@ -4599,7 +4599,7 @@ func upstreamStates() map[string][]status.UpstreamState { |
| // logging that every 5 minutes forever would bury the log in noise. Any |
| // OTHER acquire error (a real S3/credential problem) is logged, same as any |
| // other tick failure. |
| -func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func() (map[string]status.BuildStatePins, error), egressStatus egressStatusReader, judge *provision.LifetimeJudge) { |
| +func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func() (map[string]status.BuildStatePins, error), egressStatus egressStatusReader, judge *provision.LifetimeJudge, movedReady func() bool) { |
| // The status tick runs under the box's judge like every other pass. |
| ctx := provision.WithLifetimes(context.Background(), judge) |
| // bucket is read for the lease key alone (lease.Acquire below), which a |
| @@ -4715,13 +4715,14 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func |
| memTotal, memAvail := readMemBytes() |
| p := status.Probes{ |
| - MachineID: readMachineID(), |
| - InstanceID: cachedInstanceID(), |
| - Region: boxRegion, |
| - NameRegion: nameRegion, |
| - MemFrac: readMemFrac(), |
| - DiskFrac: readDiskFrac(), |
| - Listening: wrapListeningProbe(unitBackedSockets(routes), statusSocketProbe(routes, svc)), |
| + DemoMovedReady: movedReady(), |
| + MachineID: readMachineID(), |
| + InstanceID: cachedInstanceID(), |
| + Region: boxRegion, |
| + NameRegion: nameRegion, |
| + MemFrac: readMemFrac(), |
| + DiskFrac: readDiskFrac(), |
| + Listening: wrapListeningProbe(unitBackedSockets(routes), statusSocketProbe(routes, svc)), |
| // One systemctl call per 5-minute tick, asking the only question |
| // that catches an enabled-but-never-armed adoption timer — the |
| // flagship's silent no-adopt state, which nothing on any page |
diff --git a/internal/host/demo_claim_executor_test.go b/internal/host/demo_claim_executor_test.go| index 86e43b6f0..f7a87159a 100644 |
| --- a/internal/host/demo_claim_executor_test.go |
| +++ b/internal/host/demo_claim_executor_test.go |
| @@ -1,6 +1,7 @@ |
| package host |
| import ( |
| + "bytes" |
| "context" |
| "crypto/ed25519" |
| "crypto/rand" |
| @@ -347,12 +348,32 @@ func TestDemoClaimFreezeEntryGates(t *testing.T) { |
| } |
| } |
| -func TestDemoClaimFreezeStreamDelivery(t *testing.T) { |
| +func TestDemoClaimFreezeStreamDelivery(t *testing.T) { testDemoClaimStream(t) } |
| +func testDemoClaimStream(t *testing.T, movedFault ...string) { |
| f := newClaimFixture(t) |
| wire, _ := democlaim.SignWork(f.key, f.work) |
| + var moved []byte |
| + if len(movedFault) > 0 { |
| + prior, _ := democlaim.SignMoved(f.key, []democlaim.Moved{{DemoID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "shop.example.com", TargetHost: "shop.bab.apps.example.com", ExpiresAt: time.Now().Add(time.Hour).Unix()}}) |
| + if err := f.w.reg.CompareDemoMoved(nil, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer func() { |
| + got, err := f.w.reg.DemoMoved() |
| + if err != nil || !bytes.Equal(got, prior) { |
| + t.Error("moved fault replaced prior mapping", err) |
| + } |
| + }() |
| + moved = []byte(`{}`) |
| + if movedFault[0] == "monotonic" { |
| + moved, _ = democlaim.SignMoved(f.key, []democlaim.Moved{}) |
| + } |
| + } |
| acked := make(chan struct{}) |
| + streamDone := make(chan struct{}) |
| stream := interactive.NewServer(func(ws *websocket.Conn) { |
| defer ws.Close() |
| + defer close(streamDone) |
| var ready demobuild.WorkerReady |
| if err := websocket.JSON.Receive(ws, &ready); err != nil { |
| return |
| @@ -360,7 +381,7 @@ func TestDemoClaimFreezeStreamDelivery(t *testing.T) { |
| if ready.ClaimCapability != "" { |
| t.Error("snapshot door not wired") |
| } |
| - if err := websocket.JSON.Send(ws, demobuild.StreamMessage{Claim: wire}); err != nil { |
| + if err := websocket.JSON.Send(ws, demobuild.StreamMessage{Moved: moved, Claim: wire}); err != nil { |
| return |
| } |
| select { |
| @@ -391,6 +412,7 @@ func TestDemoClaimFreezeStreamDelivery(t *testing.T) { |
| ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) |
| defer cancel() |
| _ = f.w.Connect(ctx) |
| + <-streamDone |
| if f.stops != 1 { |
| t.Fatal("stream did not execute freeze") |
| } |
| @@ -576,3 +598,9 @@ func TestDemoClaimRecoveryFailureClearsCapability(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestDemoMovedFaultStillClaims(t *testing.T) { |
| + for _, fault := range []string{"signature", "monotonic"} { |
| + t.Run(fault, func(t *testing.T) { testDemoClaimStream(t, fault) }) |
| + } |
| +} |
diff --git a/internal/host/demo_jobs.go b/internal/host/demo_jobs.go| index 255b7b32e..e2137d678 100644 |
| --- a/internal/host/demo_jobs.go |
| +++ b/internal/host/demo_jobs.go |
| @@ -40,6 +40,7 @@ type demoRootBuilder interface { |
| } |
| type demoWorker struct { |
| + movedError string |
| claimMu sync.Mutex |
| claimActivator demoClaimActivator |
| claimFreeze func(context.Context, demo.Descriptor, string) error |
| @@ -533,7 +534,12 @@ func (w *demoWorker) Connect(ctx context.Context) error { |
| } |
| if len(msg.Moved) > 0 { |
| if err := installDemoMoved(w.reg, w.pub, msg.Moved, time.Now()); err != nil { |
| - return err |
| + if message := err.Error(); message != w.movedError { |
| + log.Printf("agent: demo moved: %s", message) |
| + w.movedError = message |
| + } |
| + } else { |
| + w.movedError = "" |
| } |
| } |
| if msg.Serving != nil { |
diff --git a/internal/host/demo_moved.go b/internal/host/demo_moved.go| index f1867fb6c..a2829ea19 100644 |
| --- a/internal/host/demo_moved.go |
| +++ b/internal/host/demo_moved.go |
| @@ -17,11 +17,12 @@ import ( |
| var armedDemoMovedReader atomic.Bool |
| // The existing tick owns this reader. Unchanged generations never age into |
| -// another bucket read; failed refreshes leave the generation unconsumed. |
| +// another bucket read. Only transport failures retry, at the shared backstop. |
| type demoMovedReader struct { |
| watch *release.ChangeWatch |
| generation uint64 |
| loaded bool |
| + retryAt time.Time |
| } |
| func newDemoMovedReader(w *release.ChangeWatch) *demoMovedReader { |
| @@ -38,18 +39,23 @@ func (d *demoMovedReader) pass(ctx context.Context, s release.Store, reg *regist |
| if !known || d.loaded && d.generation == gen { |
| return nil |
| } |
| + if now.Before(d.retryAt) { |
| + return nil |
| + } |
| wire, _, err := s.Get(ctx, democlaim.MovedKey) |
| if errors.Is(err, os.ErrNotExist) { |
| d.generation, d.loaded = gen, true |
| return nil |
| } |
| - if err == nil { |
| - err = installDemoMoved(reg, pub, wire, now) |
| - } |
| - if err == nil { |
| - d.generation, d.loaded = gen, true |
| + if err != nil { |
| + d.retryAt = now.Add(release.ChangeIndexBackstop) |
| + return err |
| } |
| - return err |
| + d.retryAt = time.Time{} |
| + // Verification, monotonicity and local CAS failures cannot be repaired by |
| + // fetching the same object again. Preserve the mapping and consume this view. |
| + d.generation, d.loaded = gen, true |
| + return installDemoMoved(reg, pub, wire, now) |
| } |
| func installDemoMoved(reg *registry.Registry, pub ed25519.PublicKey, wire []byte, now time.Time) error { |
| if reg == nil { |
diff --git a/internal/host/demo_moved_test.go b/internal/host/demo_moved_test.go| index 028dd14a8..3a3046aca 100644 |
| --- a/internal/host/demo_moved_test.go |
| +++ b/internal/host/demo_moved_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "crypto/ed25519" |
| "encoding/base64" |
| "encoding/binary" |
| + "errors" |
| "fmt" |
| "net/http/httptest" |
| "testing" |
| @@ -182,3 +183,106 @@ func TestDemoMovedDeliveryStream(t *testing.T) { |
| t.Fatal("fleet edge polled bucket") |
| } |
| } |
| + |
| +func TestDemoMovedInvalidGenerationConsumed(t *testing.T) { |
| + for _, fault := range []string{"signature", "monotonic", "previous-key"} { |
| + t.Run(fault, func(t *testing.T) { |
| + cs := newCICountingStore(t) |
| + watch := release.NewChangeWatch(cs) |
| + key := ed25519.NewKeyFromSeed(make([]byte, 32)) |
| + reg, err := registry.Open(t.TempDir() + "/registry.db") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + prior, _ := democlaim.SignMoved(key, []democlaim.Moved{{DemoID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "shop.demos.example.com", TargetHost: "shop.bab.apps.example.com", ExpiresAt: time.Now().Add(time.Hour).Unix()}}) |
| + if err = reg.CompareDemoMoved(nil, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + wire := []byte(`{}`) |
| + if fault != "signature" { |
| + wire, _ = democlaim.SignMoved(key, []democlaim.Moved{}) |
| + } |
| + pub := key.Public().(ed25519.PublicKey) |
| + if fault == "previous-key" { |
| + seed := make([]byte, 32) |
| + seed[0] = 1 |
| + next := ed25519.NewKeyFromSeed(seed) |
| + pub = next.Public().(ed25519.PublicKey) |
| + wire, _ = democlaim.SignMoved(next, []democlaim.Moved{}) |
| + } |
| + if _, err = cs.Put(t.Context(), democlaim.MovedKey, wire, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + pollWatch(t, watch) |
| + cs.reset() |
| + reader := newDemoMovedReader(watch) |
| + for i := range 20 { |
| + _ = reader.pass(t.Context(), cs, reg, pub, time.Now().Add(time.Duration(i)*2*time.Second)) |
| + } |
| + if n := cs.count("Get", democlaim.MovedKey); n != 1 { |
| + t.Fatalf("unchanged rejected generation: got %d GETs, want 1", n) |
| + } |
| + got, err := reg.DemoMoved() |
| + if err != nil || !bytes.Equal(got, prior) { |
| + t.Fatal("lost prior mapping", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type movedTransportStore struct { |
| + release.Store |
| + gets int |
| + fail bool |
| +} |
| + |
| +func (s *movedTransportStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + s.gets++ |
| + if s.fail { |
| + return nil, "", errors.New("transport unavailable") |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| +func TestDemoMovedTransportBackstop(t *testing.T) { |
| + cs := newCICountingStore(t) |
| + watch := release.NewChangeWatch(cs) |
| + key := ed25519.NewKeyFromSeed(make([]byte, 32)) |
| + wire, _ := democlaim.SignMoved(key, []democlaim.Moved{}) |
| + if _, err := cs.Put(t.Context(), democlaim.MovedKey, wire, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + pollWatch(t, watch) |
| + reg, err := registry.Open(t.TempDir() + "/registry.db") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + store := &movedTransportStore{Store: cs, fail: true} |
| + reader := newDemoMovedReader(watch) |
| + now := time.Now() |
| + if err = reader.pass(t.Context(), store, reg, key.Public().(ed25519.PublicKey), now); err == nil { |
| + t.Fatal("transport failure ignored") |
| + } |
| + store.fail = false |
| + for i := range 20 { |
| + if err = reader.pass(t.Context(), store, reg, key.Public().(ed25519.PublicKey), now.Add(time.Duration(i)*2*time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if store.gets != 1 { |
| + t.Fatalf("transport retried without backoff: %d", store.gets) |
| + } |
| + if err = reader.pass(t.Context(), store, reg, key.Public().(ed25519.PublicKey), now.Add(release.ChangeIndexBackstop)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if store.gets != 2 { |
| + t.Fatalf("transport did not retry at backstop: %d", store.gets) |
| + } |
| + for i := range 5 { |
| + _ = reader.pass(t.Context(), store, reg, key.Public().(ed25519.PublicKey), now.Add(time.Duration(i+1)*time.Hour)) |
| + } |
| + if store.gets != 2 { |
| + t.Fatal("successful generation reread") |
| + } |
| +} |
diff --git a/internal/host/demo_retirement_stream_test.go b/internal/host/demo_retirement_stream_test.go| index 6f8907c69..f63790daa 100644 |
| --- a/internal/host/demo_retirement_stream_test.go |
| +++ b/internal/host/demo_retirement_stream_test.go |
| @@ -1,6 +1,7 @@ |
| package host |
| import ( |
| + "bytes" |
| "context" |
| "crypto/ed25519" |
| "crypto/rand" |
| @@ -9,6 +10,7 @@ import ( |
| "github.com/carlosframework/platform/internal/activator" |
| "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/provision" |
| + "log" |
| "net/http" |
| "net/http/httptest" |
| "path/filepath" |
| @@ -20,6 +22,7 @@ import ( |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/democlaim" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/interactive" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -46,7 +49,7 @@ func TestDemoRetirementSlowStream(t *testing.T) { testDemoRetirementStream(t, tr |
| func TestDemoServingStreamRefusalStillRetires(t *testing.T) { |
| testDemoRetirementStream(t, true, false, true) |
| } |
| -func testDemoRetirementStream(t *testing.T, builderReady, slow, refusedControl bool) { |
| +func testDemoRetirementStream(t *testing.T, builderReady, slow, refusedControl bool, movedFault ...string) { |
| t.Setenv("CARLOS_DEMO_ACCOUNT", "shop") |
| t.Setenv("CARLOS_DEMO_FLEET", "demo") |
| t.Setenv("CARLOS_DEMO_DOMAIN", "example.com") |
| @@ -161,6 +164,23 @@ func testDemoRetirementStream(t *testing.T, builderReady, slow, refusedControl b |
| picked <- struct{}{} |
| return nil, errors.New("stop at pickup") |
| } |
| + var moved []byte |
| + if len(movedFault) > 0 { |
| + prior, _ := democlaim.SignMoved(key, []democlaim.Moved{{DemoID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "shop.example.com", TargetHost: "shop.bab.apps.example.com", ExpiresAt: time.Now().Add(time.Hour).Unix()}}) |
| + if err := reg.CompareDemoMoved(nil, prior); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer func() { |
| + got, err := reg.DemoMoved() |
| + if err != nil || !bytes.Equal(got, prior) { |
| + t.Error("moved fault replaced prior mapping", err) |
| + } |
| + }() |
| + moved = []byte(`{}`) |
| + if movedFault[0] == "monotonic" { |
| + moved, _ = democlaim.SignMoved(key, []democlaim.Moved{}) |
| + } |
| + } |
| server := httptest.NewServer(interactive.NewServer(func(ws *websocket.Conn) { |
| defer ws.Close() |
| var ready demobuild.WorkerReady |
| @@ -174,6 +194,9 @@ func testDemoRetirementStream(t *testing.T, builderReady, slow, refusedControl b |
| } |
| } |
| } |
| + if len(moved) > 0 { |
| + _ = websocket.JSON.Send(ws, demobuild.StreamMessage{Moved: moved}) |
| + } |
| if refusedControl { |
| // A rejected envelope and a missing initialized counter must not |
| // prevent the same message's retirement or later stream work. |
| @@ -318,3 +341,18 @@ func TestDemoConnectClearsReadiness(t *testing.T) { |
| t.Error("failed dial retained readiness") |
| } |
| } |
| + |
| +func TestDemoMovedFaultStillServesAndRetires(t *testing.T) { |
| + for _, fault := range []string{"signature", "monotonic"} { |
| + t.Run(fault, func(t *testing.T) { |
| + var logs bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(old) |
| + testDemoRetirementStream(t, true, false, false, fault) |
| + if n := strings.Count(logs.String(), "agent: demo moved: "); n != 1 { |
| + t.Fatalf("repeated fault across reconnect logged %d times, want 1", n) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go| index 221bb8473..dd48259a7 100644 |
| --- a/internal/status/snapshot.go |
| +++ b/internal/status/snapshot.go |
| @@ -42,6 +42,7 @@ import ( |
| // Probes carries everything CollectBox may not read from the registry — |
| // each nil means "unknown", and unknown publishes as null, never a guess. |
| type Probes struct { |
| + DemoMovedReady bool |
| ConsoleProcesses []ConsoleProcess |
| ActivationID string |
| ActivationComplete bool |
| @@ -1173,8 +1174,12 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| len(routeDBBytes) > 0 || p.Layout != nil || len(p.ConfigRefusals) > 0 || len(p.ReleaseRefusals) > 0 || len(p.ProofWaits) > 0 || p.Rollout != nil || p.ConfigGuard != "" || |
| p.Alerts != nil || p.GeoIP != nil || p.HeldStreams != nil || len(p.BuildStates) > 0 || p.BuildStatesErr != "" || |
| p.UpdateSettings != 0 || len(p.Updates) > 0 || len(p.Egress) > 0 || p.SizeCommittedMiB != nil { |
| + capabilities := []string{seeds.DemoClaimCapability} |
| + if p.DemoMovedReady { |
| + capabilities = append(capabilities, democlaim.MovedCapability) |
| + } |
| box.Metrics = &BoxMetrics{ |
| - Capabilities: []string{seeds.DemoClaimCapability, democlaim.MovedCapability}, |
| + Capabilities: capabilities, |
| ConsoleProcesses: p.ConsoleProcesses, |
| ActivationID: p.ActivationID, ActivationComplete: p.ActivationComplete, |
| Enrollment: p.Enrollment, |
diff --git a/internal/status/snapshot_test.go b/internal/status/snapshot_test.go| index 47bc03036..bac4a728c 100644 |
| --- a/internal/status/snapshot_test.go |
| +++ b/internal/status/snapshot_test.go |
| @@ -381,7 +381,7 @@ func TestCollectBoxCarriesAliasesRead(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if !strings.Contains(string(out), `"metrics":{"capabilities":["demo-claim-seed-v1","demo-moved-v1"],"aliases_read":true}`) { |
| + if !strings.Contains(string(out), `"metrics":{"capabilities":["demo-claim-seed-v1"],"aliases_read":true}`) { |
| t.Fatalf("json lacks the aliases_read-only metrics block: %s", out) |
| } |
| off := CollectBox(nil, Probes{Release: "v1"}, at) |
| @@ -412,3 +412,18 @@ func TestSnapshotCarriesHeldStreams(t *testing.T) { |
| t.Fatalf("nil HeldStreams published: %s", raw) |
| } |
| } |
| + |
| +func TestDemoMovedCapabilityConfigured(t *testing.T) { |
| + for _, ready := range []bool{false, true} { |
| + b := CollectBox(nil, Probes{Release: "test", DemoMovedReady: ready}, time.Now()) |
| + found := false |
| + for _, c := range b.Metrics.Capabilities { |
| + if c == "demo-moved-v1" { |
| + found = true |
| + } |
| + } |
| + if found != ready { |
| + t.Fatalf("ready=%v advertised=%v", ready, found) |
| + } |
| + } |
| +} |