carlos / platform Public

Merge origin/main into region-ha-g2-fixes

Preserve both census histories and regenerate the branch proposal last.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2d815ee9a8ee4fad146a3a675387bc57f561f562 parent 5a651b3parent 3ce8532
39 files changed, +2,056 −122
  • docs/superpowers/notes/census-demo-moved-capability-claims.md +9 −0
  • docs/superpowers/notes/census-demo-snapshot-unit-check-claims.md +6 −0
  • docs/superpowers/notes/census-proposal-demo-moved-capability.md +11 −0
  • docs/superpowers/notes/census-proposal-demo-snapshot-unit-check.md +29 −0
  • docs/superpowers/notes/census-proposal-region-ha-g2-fixes.md +1 −1
  • docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md +2 −0
  • internal/console/demo_claim_gate_causes_test.go +321 −0
  • internal/console/demo_claim_gates_test.go +392 −0
  • internal/console/demo_claim_ha_gate_test.go +100 −0
  • internal/console/demo_claim_moved.go +26 −8
  • internal/console/demo_claim_ready.go +90 −29
  • internal/console/demo_claim_ready_test.go +99 −0
  • internal/console/demo_claim_seed.go +51 −25
  • internal/console/demo_claim_target.go +1 −1
  • internal/console/demo_claim_transfer.go +20 −8
  • internal/console/hacapacity.go +31 −0
  • internal/console/hacapacity_observe.go +2 −0
  • internal/console/hostsused.go +30 −1
  • internal/console/hostsused_groupmember_test.go +224 −0
  • internal/console/seedfloor.go +9 −0
  • internal/console/server.go +1 −1
  • internal/democlaim/moved.go +14 −0
  • internal/democlaim/moved_test.go +30 −0
  • internal/democlaim/source_linux.go +33 −4
  • internal/democlaim/source_other.go +4 −3
  • internal/democlaim/source_worker_linux_test.go +166 −0
  • internal/democlaim/worker.go +1 −1
  • internal/edge/demo_moved.go +2 −2
  • internal/edge/demo_moved_test.go +76 −3
  • internal/host/demo_moved_test.go +29 −23
  • internal/host/edgesfile.go +11 −4
  • internal/instancectl/demo_snapshot_disk.go +3 −3
  • internal/instancectl/demo_snapshot_kernel_linux_test.go +97 −2
  • internal/instancectl/demo_snapshot_unit_test.go +51 −0
  • internal/instancectl/testdata/systemd257-snapshot-unit.txt +57 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +3 −1
  • internal/provision/testdata/plan14-root-reads-demo-moved-capability.tsv +5 −0
  • internal/provision/testdata/plan14-root-reads-demo-snapshot-unit-check.tsv +17 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-g2-fixes.tsv +2 −2

Intent

Human

<task-notification> <task-id>b091fk5h6</task-id> <tool-use-id>toolu_01VsmB3YVkHS47Bbyyusj8JU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/5555438b-7fa2-408d-b2c4-9fa87ea89332/tasks/b091fk5h6.output</output-file> <status>completed</status> <summary>Background command "Final F-A witness run 6" completed (exit code 0)</summary> </task-notification>

diff --git a/docs/superpowers/notes/census-demo-moved-capability-claims.md b/docs/superpowers/notes/census-demo-moved-capability-claims.md
new file mode 100644
index 000000000..e263cdda3
--- /dev/null
+++ b/docs/superpowers/notes/census-demo-moved-capability-claims.md
@@ -0,0 +1,9 @@
+# Demo moved capability claims. Base: 25ca6faf. Independent review pending; no review rounds run.
+# Census reports only three source envelopes, with no changed read units.
+# Unit notes below are comments because census-propose refuses claims for units outside its change list.
+# internal/host/edgesfile.go:edgesFileCapabilities Remove runtime moved capability from frozen startup capabilities. No new read.
+# internal/host/edgesfile.go:withDemoMovedCapability Recompute moved capability from the configured demo domain, read-mode change index, armed watch and armed reader on each publication pass. Reads existing process configuration and atomic readiness flags; no new filesystem, registry or network read.
+# internal/host/edgesfile.go:edgesFileLoop Call withDemoMovedCapability on each publication pass so late reader arming is advertised. Existing read sites and publication destination are unchanged.
+# internal/edge/demo_moved.go:Edge.DemoMovedReady Require the static release public key and valid demo domain without requiring edge apps-domain configuration. No new read.
+# internal/edge/demo_moved.go:Edge.loadDemoMoved Validate already signature-verified notices with MovedEdgeDomains. Existing registry read, release-key verification and monotonicity checks remain; no new read.
+# internal/democlaim/moved.go:MovedEdgeDomains Require an exact one-label source under the configured demo domain and a valid lowercase DNS target outside that domain with at least three labels. The release signature authorizes the target; console MovedDomains validation remains unchanged. No new read.
diff --git a/docs/superpowers/notes/census-demo-snapshot-unit-check-claims.md b/docs/superpowers/notes/census-demo-snapshot-unit-check-claims.md
new file mode 100644
index 000000000..85f4fce28
--- /dev/null
+++ b/docs/superpowers/notes/census-demo-snapshot-unit-check-claims.md
@@ -0,0 +1,6 @@
+internal/instancectl/demo_snapshot_disk.go:demoSnapshotSupervisor.checkUnit Accept an omitted EnvironmentFiles property as empty, as emitted by systemd 257; continue requesting it and reject every non-empty value. All other property checks remain unchanged. No read added; the existing systemctl query requests the same properties.
+internal/democlaim/source_linux.go:OpenSource Retain the existing instancefs directory open and openat2 flags for root and agent callers; move the file syscall from Source.open into this constructor's opener. No fallback is added. Shared validation still rejects unsafe names, nonregular files, multiple links and oversized DB plus WAL.
+internal/democlaim/source_linux.go:OpenWorkerSource Open only the worker's private directory with open O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC, then use the worker file opener and shared Source checks. The private command supplies /work; no root or agent caller switches to this constructor. New direct directory read replaces the worker's blocked openat2 path.
+internal/democlaim/source_linux.go:openWorkerFile Open a single component relative to the held private worker directory with openat O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOFOLLOW. Refuse empty, dot, dot-dot, slash, backslash and NUL names before the syscall. New direct file read is used only by OpenWorkerSource, including VerifyUnchanged.
+internal/democlaim/source_linux.go:Source.open Route the file open through the constructor-selected opener; retain identical Fstat, regular-file, nlink==1 and nonnegative-size checks. Root and agent still select openat2; the private worker selects openat. VerifyUnchanged uses this same seam with its existing inode, timestamps, size and link checks.
+internal/democlaim/worker.go:RunSnapshotWorkerIn Select OpenWorkerSource for fixed snapshot.db and optional snapshot.db-wal in private /work. Preserve root refusal, result-name reservation, timeout, VerifyUnchanged, checkpoint, integrity check, hashing and failed-result cleanup. No new path input or read is added here.
diff --git a/docs/superpowers/notes/census-proposal-demo-moved-capability.md b/docs/superpowers/notes/census-proposal-demo-moved-capability.md
new file mode 100644
index 000000000..ddd82c402
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-demo-moved-capability.md
@@ -0,0 +1,11 @@
+# Census approval: demo-moved-capability
+
+Ruling `census-ruling-demo-moved-capability`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/democlaim`, `internal/edge`, `internal/host`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939` → `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-demo-moved-capability.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-demo-snapshot-unit-check.md b/docs/superpowers/notes/census-proposal-demo-snapshot-unit-check.md
new file mode 100644
index 000000000..10e908894
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-demo-snapshot-unit-check.md
@@ -0,0 +1,29 @@
+# Census approval: demo-snapshot-unit-check
+
+Ruling `census-ruling-demo-snapshot-unit-check`. The independent reviewer approves or rejects every change below, 3 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/democlaim/worker.go` `RunSnapshotWorkerIn` | body | unchanged (1) | Select OpenWorkerSource for fixed snapshot.db and optional snapshot.db-wal in private /work. Preserve root refusal, result-name reservation, timeout, VerifyUnchanged, checkpoint, integrity check, hashing and failed-result cleanup. No new path input or read is added here. |
+| `internal/instancectl/demo_snapshot_disk.go` `demoSnapshotSupervisor.checkUnit` | body | unchanged (1) | Accept an omitted EnvironmentFiles property as empty, as emitted by systemd 257; continue requesting it and reject every non-empty value. All other property checks remain unchanged. No read added; the existing systemctl query requests the same properties. |
+| `internal/democlaim/source_linux.go` `Source.open` | sites | -file:Openat2 | Route the file open through the constructor-selected opener; retain identical Fstat, regular-file, nlink==1 and nonnegative-size checks. Root and agent still select openat2; the private worker selects openat. VerifyUnchanged uses this same seam with its existing inode, timestamps, size and link checks. |
+
+Envelopes re-pinned: `internal/democlaim`, `internal/instancectl`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/democlaim/worker.go` `RunSnapshotWorkerIn`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Open only fixed private helper files and write bounded snapshot metadata; caller-provided live source paths never reach SQLite as root. Census read-site delta: +file:OpenFile.
+- `internal/instancectl/demo_snapshot_disk.go` `demoSnapshotSupervisor.checkUnit`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Inspect the effective fixed systemd snapshot unit and require its declared isolation, resource and execution settings. Census read-site delta: +data-literal.
+- `internal/democlaim/source_linux.go` `Source.open`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Open DB and WAL beneath the retained source directory with openat2 no-follow/beneath constraints and enforce regular-file bounds. Census read-site delta: +file:Fstat, +file:Openat2.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/democlaim/source_linux.go:OpenSource`: reads +file:Openat2; written legacy, accepted-legacy, frozen
+- new `internal/democlaim/source_linux.go:OpenWorkerSource`: reads +file:Open; written legacy, accepted-legacy, frozen
+- new `internal/democlaim/source_linux.go:openWorkerFile`: reads +file:Openat; written legacy, accepted-legacy, frozen
+
+Seal: `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939` → `1e83ce23d7d1306e3963f802fecf8c914a2624726255e3bc30382104e568adde`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-demo-snapshot-unit-check.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-region-ha-g2-fixes.md b/docs/superpowers/notes/census-proposal-region-ha-g2-fixes.md
index c89880e40..c27ec00f0 100644
--- a/docs/superpowers/notes/census-proposal-region-ha-g2-fixes.md
+++ b/docs/superpowers/notes/census-proposal-region-ha-g2-fixes.md
@@ -141,6 +141,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- reads `internal/edge/wakeplacement.go:homeMap.dutySnapshot`: +registry:Pool ×2; keeps legacy, task accepted-legacy
- reads `internal/host/edgesfile.go:edgesFileWriteClaims`: +registry:Host, +registry:Pool; keeps authority, task F,J1
-Seal: `ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939` → `f4c2ef292f645dccbfa9b2b570074d1033b3be9fc2b4dc76e2f14aec1f8b94b7`.
+Seal: `1e83ce23d7d1306e3963f802fecf8c914a2624726255e3bc30382104e568adde` → `3c1d54d297da31d147cdb4e1ad4627f759c8cb8eae2db53cc92218db35e59c7b`.
Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-g2-fixes.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
index e72858822..e1103bb0b 100644
--- a/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
+++ b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md
@@ -56,6 +56,8 @@ Deleted history and noncurrent versions are not sources, because they are harmle
**A fleet created after completion is recorded at its first box (#519, 2026-11-02).** Activation records every fleet on its roster, so a fleet the history has not recorded was created since. No box of it existed before completion, so none holds its old data. Its first add-box, with the console serving, records the fleet as examined before it adds the box: its targets are its bucket, its boxes so far and the new box, and the new label is its first box (`first_box`). Its next add-box is N9 like any recorded fleet's, except its first-box label while no box of that label is active, which completes the enrollment. A box is never added before the record lands and never detached, so a write of the mode that errs, lands late or never lands is finished by the same add-box again (Paul's ruling on Astra r2; `TestNewFleetEnrollmentSimulation`). A bucket that a closed fleet also uses was never scanned: such a fleet is left unrecorded and completes offline, as before. **What this takes on trust (Paul, 2026-11-02, on Astra r1 P1 1):** the console never reads a fleet's bucket or boxes, so storage the owner names is examined as new, as anything they copy into an examined fleet's storage later would be. The first-box label stays completable after a detach, on the same terms. A registry restored to a snapshot from before activation is outside it too.
+**A group member that joins a region is not a target the history waits for (Paul's ruling on #421, 2026-11-06, option A).** S4's coverage check refuses every data-kind create in a region whose edges files name a box that completion did not record, because a box that joins from infra may carry old data on its disk. Each replacement in a region's Auto Scaling group mints a new `g-` reference, so before this ruling every replacement refused all data-kind creates in its region, legacy creates included, until the history was completed again offline. A group box cannot carry old data: it starts from the launch template with a root volume deleted on termination, `restore-box` refuses group boxes (durability §3.1 item 3), it runs no unit, platform or non-hibernating records (region HA §6.1), and it holds only copies of state in its region's data bucket. So the coverage check skips a box's `box:` target only when the current HA capacity observation proved the box a group member of that region: its edges file was read within the region's scope, its signed identity verified, its reference is `haGroupReference` of that identity's account and instance, no other file conflicts with it, the configuration does not pin its reference as a fixed box, and every edges file naming it is its own (key and `box_id` are its reference) (`provenGroupTarget`). The box's data bucket stays a checked target. A member the observation has not proved, or no observation, or a stale one, refuses as before. Nothing is written to the mode: the excused box never becomes a recorded target. **What this takes on trust:** a box whose host.env an operator deliberately switches to `CARLOS_BOX_REFERENCE=group` is treated as a group box. The proof needs a fresh edges file. A terminated member's file is deleted by the departure scan, and until it is, that file refuses as before.
+
## 3a. The activation window (accepted 2026-10-26)
A one-time maintenance window wraps the inventory. It closes round 3's P1: a marked allocation started before activation and still pending could otherwise publish over old data after `complete` (recovery's "our slot, absent record" branch, lifetimes_recovery.go:204).
diff --git a/internal/console/demo_claim_gate_causes_test.go b/internal/console/demo_claim_gate_causes_test.go
new file mode 100644
index 000000000..44e85bdb0
--- /dev/null
+++ b/internal/console/demo_claim_gate_causes_test.go
@@ -0,0 +1,321 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "log"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+type claimHungIndexStore struct{ release.Store }
+
+func (s claimHungIndexStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == release.ChangeIndexKey {
+ <-ctx.Done()
+ return nil, "", ctx.Err()
+ }
+ return s.Store.Get(ctx, key)
+}
+
+func TestDemoClaimReadinessDeadlineCause(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ s.cfg.Releases = claimHungIndexStore{s.cfg.Releases}
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
+ defer cancel()
+ gates, err := s.demoClaimReadinessGates(ctx)
+ if !errors.Is(ctx.Err(), context.DeadlineExceeded) || err == nil || err.Error() != demoClaimUnavailable {
+ t.Fatalf("changed deadline verdict: context=%v, verdict=%v", ctx.Err(), err)
+ }
+ if !slices.Contains(gates, "context") || !slices.Contains(gates, "change-index") {
+ t.Fatalf("missing deadline cause: %s", gates.names())
+ }
+}
+
+func claimGateFloor(t *testing.T, s *Server, min int, minRelease string) {
+ t.Helper()
+ _, tag, err := s.cfg.Releases.Get(t.Context(), seeds.FloorKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := json.Marshal(seeds.Floor{Min: min, MinRelease: minRelease})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.cfg.Releases.Put(t.Context(), seeds.FloorKey, raw, tag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDemoClaimReadinessSeedRefusalCauses(t *testing.T) {
+ for _, tc := range []struct {
+ name, gate string
+ change func(*testing.T, *Server)
+ }{
+ {"flat", "box-layout:box-a", func(t *testing.T, s *Server) {
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Layout.Mode = "flat" })
+ }},
+ {"missing-layout", "box-layout:box-a", func(t *testing.T, s *Server) {
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Layout = nil })
+ }},
+ {"claim-control", "box-claim-control:box-a", func(t *testing.T, s *Server) {
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.HostClaimEnabled = true })
+ }},
+ {"moves-state", "edge-moves-floor:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["moves_floor_state"] = "accepted" })
+ }},
+ {"moves-generation", "edge-moves-floor:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["moves_floor_generation"] = 1 })
+ }},
+ {"moves-unarmed-seeds", "edge-moves-floor:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) {
+ f["moves_floor_state"], f["seeds_floor_state"] = "accepted", "accepted"
+ })
+ }},
+ {"floor-protocol", "seed-floor-protocol", func(t *testing.T, s *Server) {
+ claimGateFloor(t, s, 3, "v1.0.0")
+ }},
+ {"floor-release-empty", "seed-floor-release", func(t *testing.T, s *Server) {
+ claimGateFloor(t, s, 2, "")
+ }},
+ {"floor-release-malformed", "seed-floor-release", func(t *testing.T, s *Server) {
+ claimGateFloor(t, s, 2, "invalid")
+ }},
+ {"no-region-edge", "seed-region-edges", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["placement"] = "other" })
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ tc.change(t, s)
+ if s.seedRegionReadyForEdges(t.Context(), s.cfg.Region, false, demoClaimEdge) == nil {
+ t.Fatal("fixture did not reach an existing seed refusal")
+ }
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ if err := s.demoClaimReady(t.Context()); err == nil || err.Error() != demoClaimUnavailable {
+ t.Fatalf("changed refusal: %v", err)
+ }
+ names := strings.Split(s.demoClaimAdmission.failures, ",")
+ if !slices.Contains(names, tc.gate) || !slices.Contains(names, "seed-region") {
+ t.Fatalf("missing cause or umbrella: %v", names)
+ }
+ if !strings.Contains(output.String(), "console: demo claim readiness: refusing: "+s.demoClaimAdmission.failures+"\n") {
+ t.Fatalf("missing diagnostic: %s", &output)
+ }
+ })
+ }
+}
+
+func TestDemoClaimReadinessSeedCauseChanges(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Layout.Mode = "flat" })
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ for _, want := range []string{"box-layout:box-a,seed-region", "box-claim-control:box-a,seed-region"} {
+ for range 2 {
+ s.demoClaimAdmission.expiresAt = time.Time{}
+ if s.demoClaimReady(t.Context()) == nil {
+ t.Fatal("admitted refusal")
+ }
+ }
+ if !strings.HasSuffix(output.String(), "console: demo claim readiness: refusing: "+want+"\n") {
+ t.Fatalf("missing changed cause: %s", &output)
+ }
+ claimGateBox(t, s, func(b *status.Box) {
+ b.Metrics.Layout.Mode, b.Metrics.HostClaimEnabled = "nested", true
+ })
+ }
+ if strings.Count(output.String(), "console: demo claim readiness: refusing:") != 2 {
+ t.Fatalf("want two diagnostic lines: %s", &output)
+ }
+}
+
+func TestDemoClaimSeedCauseChecksPreserveAcceptance(t *testing.T) {
+ for _, mode := range []string{"higher-protocol", "moves-with-accepted-seeds", "other-region", "named-pool"} {
+ t.Run(mode, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ switch mode {
+ case "higher-protocol":
+ claimGateFloor(t, s, 3, "v1.0.0")
+ claimGateEdge(t, s, func(f map[string]any) { f["seeds_protocol"] = 3 })
+ case "moves-with-accepted-seeds":
+ claimGateEdge(t, s, func(f map[string]any) {
+ f["moves_floor_state"], f["seeds_floor_state"], f["seeds_floor_generation"] = "refused", "accepted", 1
+ })
+ default:
+ fx := &consoleFixture{srv: s, rel: s.cfg.Releases}
+ seedReadyBox(t, fx, "box-b", "other", 2, "v1.0.0", "v1.0.0", "flat", true)
+ // Keep all shared readers capable, including a flat box outside the destination region.
+ boxes, err := status.LoadBoxes(t.Context(), s.cfg.Releases)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, b := range boxes {
+ if b.Label == "box-b" {
+ b.Metrics.Capabilities = append(b.Metrics.Capabilities, seeds.DemoClaimCapability)
+ if err := status.WriteBox(t.Context(), s.cfg.Releases, b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ key := "control/edges/box-b.json"
+ raw, tag, err := s.cfg.Releases.Get(t.Context(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f map[string]any
+ if err := json.Unmarshal(raw, &f); err != nil {
+ t.Fatal(err)
+ }
+ f["capabilities"] = []string{seeds.DemoClaimCapability}
+ f["moves_floor_state"] = "accepted"
+ if mode == "named-pool" {
+ f["placement"], f["serves_shared_pool"] = s.cfg.Region, false
+ }
+ raw, err = json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.cfg.Releases.Put(t.Context(), key, raw, tag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if ref := s.seedRegionReadyForEdges(t.Context(), s.cfg.Region, false, demoClaimEdge); ref != nil {
+ t.Fatalf("existing refusal: %+v", ref)
+ }
+ if gates := s.demoClaimSeedGates(t.Context(), s.cfg.Region); len(gates) != 0 {
+ t.Fatalf("new refusal: %s", gates.names())
+ }
+ })
+ }
+}
+
+func TestDemoClaimSeedHostClaimNilStore(t *testing.T) {
+ s := &Server{cfg: Config{HostClaim: true}}
+ gates := s.demoClaimSeedGates(t.Context(), "")
+ if !slices.Contains(gates, "host-claim") || gates.err() == nil {
+ t.Fatalf("missing host-claim refusal: %s", gates.names())
+ }
+}
+
+func TestDemoClaimReadinessEarlyRefusals(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ if err := s.demoClaimReady(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ counted := &demoCountingStore{Store: s.cfg.Releases}
+ s.cfg.Releases = counted
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ defer func() { s.store.gate = nil }()
+ for _, want := range []string{"demo-enabled", "host-claim", "claim-gated", "claim-gated,demo-enabled,host-claim"} {
+ s.cfg.Demo.Enabled = !strings.Contains(want, "demo-enabled")
+ s.cfg.HostClaim = strings.Contains(want, "host-claim")
+ s.store.gate = nil
+ if strings.Contains(want, "claim-gated") {
+ s.store.gate = &claimGate{}
+ }
+ output.Reset()
+ for i := range 3 {
+ if i == 2 {
+ s.demoClaimAdmission.expiresAt = time.Time{}
+ }
+ if err := s.demoClaimReady(t.Context()); err == nil || err.Error() != demoClaimUnavailable {
+ t.Fatalf("early refusal: %v", err)
+ }
+ }
+ if strings.Count(output.String(), "console: demo claim readiness: refusing:") != 1 ||
+ !strings.HasSuffix(output.String(), "refusing: "+want+"\n") {
+ t.Fatalf("early diagnostic: %s", &output)
+ }
+ }
+ if counted.requests() != 0 {
+ t.Fatalf("early refusal read deployment: %d", counted.requests())
+ }
+ s.cfg.Demo.Enabled, s.cfg.HostClaim, s.store.gate = true, false, nil
+ if err := s.demoClaimReady(t.Context()); err != nil {
+ t.Fatalf("stale prerequisite refusal: %v", err)
+ }
+ if !strings.HasSuffix(output.String(), "console: demo claim readiness: ready\n") {
+ t.Fatalf("missing recovery: %s", &output)
+ }
+}
+
+func TestDemoClaimTransferCapabilityCauseOnce(t *testing.T) {
+ for _, fault := range []string{"worker-peer", "box-layout:box-a,seed-region", "moved-edge:box-a"} {
+ t.Run(fault, func(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ switch fault {
+ case "worker-peer":
+ s.demoJobs.peers["box"].ready.ClaimCapability = ""
+ case "box-layout:box-a,seed-region":
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Layout.Mode = "flat" })
+ case "moved-edge:box-a":
+ claimGateEdge(t, s, func(f map[string]any) { f["capabilities"] = []string{seeds.DemoClaimCapability} })
+ }
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ claimAdvance(t, s, op)
+ claimAdvance(t, s, op)
+ p, err := s.claimProgress(t.Context(), op.ID)
+ if err != nil || p.Reason != "capability" {
+ t.Fatalf("abort reason: %+v %v", p, err)
+ }
+ if strings.Count(output.String(), "console: demo claim capability:") != 1 ||
+ !strings.Contains(output.String(), "console: demo claim capability: refusing: "+fault+"\n") {
+ t.Fatalf("abort diagnostic: %s", &output)
+ }
+ if strings.Contains(output.String(), op.ID) || strings.Contains(output.String(), op.Target.Host) {
+ t.Fatalf("operation identity leaked: %s", &output)
+ }
+ })
+ }
+}
+
+func TestDemoClaimTransferCapabilityCleanupRetry(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ s.demoJobs.peers["box"].ready.ClaimCapability = ""
+ store := s.cfg.Releases
+ s.cfg.Releases = &claimGateStore{Store: store, failGet: provision.RecordKey(op.Target.Sqid, op.Target.App, op.Target.Host)}
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ for range 2 {
+ if err := s.advanceDemoClaim(t.Context(), op.ID); !errors.Is(err, errClaimGateStore) {
+ t.Fatalf("expected cleanup failure: %v", err)
+ }
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil || fresh.Phase != "aborting" {
+ t.Fatalf("abort transition not persisted: %+v %v", fresh, err)
+ }
+ }
+ s.cfg.Releases = store
+ claimAdvance(t, s, op)
+ if strings.Count(output.String(), "console: demo claim capability: refusing: worker-peer\n") != 1 {
+ t.Fatalf("cleanup retry repeated diagnostic: %s", &output)
+ }
+}
diff --git a/internal/console/demo_claim_gates_test.go b/internal/console/demo_claim_gates_test.go
new file mode 100644
index 000000000..677504591
--- /dev/null
+++ b/internal/console/demo_claim_gates_test.go
@@ -0,0 +1,392 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "log"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+func claimGateEdge(t *testing.T, s *Server, edit func(map[string]any)) {
+ t.Helper()
+ key := "control/edges/box-a.json"
+ raw, tag, err := s.cfg.Releases.Get(t.Context(), key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f map[string]any
+ if err := json.Unmarshal(raw, &f); err != nil {
+ t.Fatal(err)
+ }
+ edit(f)
+ raw, err = json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.cfg.Releases.Put(t.Context(), key, raw, tag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func claimGateBox(t *testing.T, s *Server, edit func(*status.Box)) {
+ t.Helper()
+ boxes, err := status.LoadBoxes(t.Context(), s.cfg.Releases)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, b := range boxes {
+ if b.Label != "box-a" {
+ continue
+ }
+ edit(&b)
+ if err := status.WriteBox(t.Context(), s.cfg.Releases, b); err != nil {
+ t.Fatal(err)
+ }
+ return
+ }
+ t.Fatal("missing fixture box")
+}
+
+var errClaimGateStore = errors.New("private store error must not appear in readiness diagnostics")
+
+type claimGateStore struct {
+ release.Store
+ failGet, failList string
+ failListAt int32
+ lists atomic.Int32
+}
+
+func (s *claimGateStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == s.failGet {
+ return nil, "", errClaimGateStore
+ }
+ return s.Store.Get(ctx, key)
+}
+func (s *claimGateStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == s.failList {
+ n := s.lists.Add(1)
+ if s.failListAt == 0 || n == s.failListAt {
+ return nil, errClaimGateStore
+ }
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func TestDemoClaimReadinessGateNames(t *testing.T) {
+ cases := []struct {
+ name, gate string
+ change func(*testing.T, *Server)
+ }{
+ {"keymail", "keymail", func(t *testing.T, s *Server) { s.km = nil }},
+ {"keymail-host", "keymail", func(t *testing.T, s *Server) { s.km = NewKeymail("", s.cfg.Origin) }},
+ {"apps-domain", "apps-domain", func(t *testing.T, s *Server) { s.cfg.AppsDomain = "" }},
+ {"signing-key", "signing-key", func(t *testing.T, s *Server) { s.cfg.Key = nil }},
+ {"release-pub", "release-pub", func(t *testing.T, s *Server) { s.cfg.ReleasePub = nil }},
+ {"releases", "releases", func(t *testing.T, s *Server) { s.cfg.Releases = nil }},
+ {"seed-data", "seed-data", func(t *testing.T, s *Server) { s.cfg.SeedData = nil }},
+ {"leftover-check", "leftover-check", func(t *testing.T, s *Server) { s.cfg.HibernateBucket = "" }},
+ {"seed-stream", "seed-stream", func(t *testing.T, s *Server) { s.cfg.SeedData = &demoCountingStore{Store: s.cfg.SeedData} }},
+ {"record-watch", "record-watch", func(t *testing.T, s *Server) { s.recordView = nil }},
+ {"change-index", "change-index", func(t *testing.T, s *Server) {
+ s.cfg.Releases = &claimGateStore{Store: s.cfg.Releases, failGet: release.ChangeIndexKey}
+ }},
+ {"worker-peer", "worker-peer", func(t *testing.T, s *Server) { s.demoJobs.peers["box"].ready.ClaimCapability = "" }},
+ {"publish", "publish", func(t *testing.T, s *Server) { s.cfg.Bucket = "private-bucket"; s.cfg.PolicyLease = nil }},
+ {"ha-region", "ha-region", func(t *testing.T, s *Server) { s.cfg.HomeRegion = "home"; s.cfg.HARegions = []string{"home"} }},
+ {"seed-region", "seed-region", func(t *testing.T, s *Server) {
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Layout.Mode = "flat" })
+ }},
+ {"seed-floor", "seed-floor", func(t *testing.T, s *Server) {
+ if err := s.cfg.Releases.Delete(t.Context(), seeds.FloorKey); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {"seed-floor-old", "seed-floor", func(t *testing.T, s *Server) {
+ _, tag, _ := s.cfg.Releases.Get(t.Context(), seeds.FloorKey)
+ if _, err := s.cfg.Releases.Put(t.Context(), seeds.FloorKey, []byte(`{"min":1,"min_release":"v1.0.0"}`), tag); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {"edges-evidence", "edges-evidence", func(t *testing.T, s *Server) {
+ s.cfg.Releases = &claimGateStore{Store: s.cfg.Releases, failList: "control/edges/"}
+ }},
+ {"edge-capability", "edge-capability:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["capabilities"] = []string{democlaim.MovedCapability} })
+ }},
+ {"edge-protocol", "edge-protocol:box-a", func(t *testing.T, s *Server) { claimGateEdge(t, s, func(f map[string]any) { f["seeds_protocol"] = 1 }) }},
+ {"edge-floor", "edge-floor:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["seeds_floor_min_release"] = "v0.9.0" })
+ }},
+ {"edge-prev", "edge-prev:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["prev_seeds_allowed_for"] = "" })
+ }},
+ {"edge-floor-state", "edge-floor-state:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["seeds_floor_state"] = "refused"; f["seeds_floor_generation"] = 1 })
+ }},
+ {"no-shared-edges", "no-shared-edges", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["serves_shared_pool"] = false })
+ }},
+ {"box-status", "box-status:box-a", func(t *testing.T, s *Server) {
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Capabilities = []string{democlaim.MovedCapability} })
+ }},
+ {"box-status-read", "box-status", func(t *testing.T, s *Server) {
+ s.cfg.Releases = &claimGateStore{Store: s.cfg.Releases, failList: "status/boxes/"}
+ }},
+ {"box-platform", "box-platform:box-a", func(t *testing.T, s *Server) {
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Platform = "linux-amd64" })
+ }},
+ {"moved-box", "moved-box:box-a", func(t *testing.T, s *Server) {
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Capabilities = []string{seeds.DemoClaimCapability} })
+ }},
+ {"moved-edge", "moved-edge:box-a", func(t *testing.T, s *Server) {
+ claimGateEdge(t, s, func(f map[string]any) { f["capabilities"] = []string{seeds.DemoClaimCapability} })
+ }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ tc.change(t, s)
+ gates, err := s.demoClaimReadinessGates(t.Context())
+ if err == nil || err.Error() != demoClaimUnavailable {
+ t.Fatalf("caller error = %v", err)
+ }
+ if !slices.Contains(gates, tc.gate) {
+ t.Fatalf("missing %q in %q", tc.gate, gates.names())
+ }
+ })
+ }
+}
+
+func TestDemoClaimReadinessAllFailuresAndTransitions(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ km, key := s.km, s.cfg.Key
+ s.km, s.cfg.Key = nil, nil
+ claimSeedReadyFixture(t, s, 1, false, "")
+ claimGateBox(t, s, func(b *status.Box) { b.Metrics.Platform = "linux-amd64" })
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ check := func(ready bool) {
+ t.Helper()
+ err := s.demoClaimReady(t.Context())
+ if ready && err != nil || !ready && (err == nil || err.Error() != demoClaimUnavailable) {
+ t.Fatalf("readiness = %v", err)
+ }
+ }
+ check(false)
+ want := "console: demo claim readiness: refusing: box-platform:box-a,box-status:box-a,edge-capability:box-a,edge-prev:box-a,edge-protocol:box-a,keymail,moved-box:box-a,moved-edge:box-a,seed-floor-protocol,seed-region,signing-key"
+ if !strings.Contains(output.String(), want+"\n") {
+ t.Fatalf("missing complete sorted failures: %s", &output)
+ }
+ first := output.String()
+ check(false)
+ s.demoClaimAdmission.expiresAt = time.Time{}
+ check(false)
+ if output.String() != first {
+ t.Fatalf("repeat logged again: %s", &output)
+ }
+ s.km = km
+ s.demoClaimAdmission.expiresAt = time.Time{}
+ check(false)
+ if strings.Count(output.String(), "console: demo claim readiness: refusing:") != 2 {
+ t.Fatalf("changed set did not log: %s", &output)
+ }
+ s.cfg.Key = key
+ claimSeedReadyFixture(t, s, 2, true, "v1.0.0")
+ s.demoClaimAdmission.expiresAt = time.Time{}
+ check(true)
+ s.demoClaimAdmission.expiresAt = time.Time{}
+ check(true)
+ if strings.Count(output.String(), "console: demo claim readiness: ready") != 1 {
+ t.Fatalf("recovery: %s", &output)
+ }
+ s.km = nil
+ s.demoClaimAdmission.expiresAt = time.Time{}
+ check(false)
+ if !strings.HasSuffix(output.String(), "console: demo claim readiness: refusing: keymail\n") {
+ t.Fatalf("regression: %s", &output)
+ }
+}
+
+func TestDemoClaimReadinessOffNoReadsOrLogs(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ s.cfg.Demo.ClaimEnabled = false
+ store := &demoCountingStore{Store: s.cfg.Releases}
+ s.cfg.Releases = store
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ for range 3 {
+ if err := s.demoClaimReady(t.Context()); err == nil || err.Error() != demoClaimUnavailable {
+ t.Fatalf("off error: %v", err)
+ }
+ }
+ if store.gets.Load() != 0 || store.lists.Load() != 0 || output.Len() != 0 {
+ t.Fatalf("off read/log: %d/%d %s", store.gets.Load(), store.lists.Load(), &output)
+ }
+}
+
+func TestDemoClaimReadinessNilStoresKeepIndependentGates(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ s.cfg.Releases, s.cfg.SeedData, s.km = nil, nil, nil
+ s.demoJobs.peers["box"].ready.ClaimCapability = ""
+ gates, err := s.demoClaimReadinessGates(t.Context())
+ if err == nil || gates.names() != "keymail,releases,seed-data,worker-peer" {
+ t.Fatalf("nil stores: %q %v", gates.names(), err)
+ }
+}
+
+func TestDemoClaimReadinessCapabilitiesCompatibility(t *testing.T) {
+ for _, fault := range []string{"", "source", "seed", "moved", "moved-store"} {
+ t.Run(fault, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ op := claimOp{SourceBox: s.demoJobs.peers["box"].box(), Target: claimTarget{Region: s.cfg.Region}}
+ ctx := withReqMemo(t.Context())
+ switch fault {
+ case "source":
+ op.SourceBox = "missing"
+ case "seed":
+ claimGateEdge(t, s, func(f map[string]any) { f["seeds_protocol"] = 1 })
+ case "moved":
+ claimGateEdge(t, s, func(f map[string]any) { f["capabilities"] = []string{seeds.DemoClaimCapability} })
+ case "moved-store":
+ s.cfg.Releases = &claimGateStore{Store: s.cfg.Releases, failList: "status/boxes/", failListAt: 4}
+ }
+ err := s.demoClaimCapabilitiesReady(ctx, op)
+ switch fault {
+ case "":
+ if err != nil {
+ t.Fatal(err)
+ }
+ case "moved-store":
+ if !errors.Is(err, errClaimGateStore) {
+ t.Fatalf("lost moved storage error: %v", err)
+ }
+ default:
+ if err == nil || err.Error() != demoClaimUnavailable {
+ t.Fatalf("changed refusal: %v", err)
+ }
+ }
+ })
+ }
+}
+
+func TestDemoClaimReadinessRequestBudget(t *testing.T) {
+ for _, memo := range []bool{false, true} {
+ for _, failing := range []bool{false, true} {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ if failing {
+ s.km = nil
+ s.cfg.Key = nil
+ claimGateEdge(t, s, func(f map[string]any) { f["capabilities"] = []string{seeds.DemoClaimCapability} })
+ }
+ counted := &demoCountingStore{Store: s.cfg.Releases}
+ s.cfg.Releases = counted
+ ctx := t.Context()
+ if memo {
+ ctx = withReqMemo(ctx)
+ }
+ err := s.demoClaimReady(ctx)
+ if (err != nil) != failing {
+ t.Fatalf("readiness: %v", err)
+ }
+ // Measured against the original complete pass, with one edge and one box.
+ var gets, lists int32 = 12, 9
+ if memo {
+ gets, lists = 8, 5
+ }
+ if counted.gets.Load() != gets || counted.lists.Load() != lists {
+ t.Fatalf("memo=%v failing=%v: GET/LIST=%d/%d, want %d/%d", memo, failing, counted.gets.Load(), counted.lists.Load(), gets, lists)
+ }
+ for range 3 {
+ _ = s.demoClaimReady(t.Context())
+ }
+ if counted.gets.Load() != gets || counted.lists.Load() != lists || counted.puts.Load() != 0 {
+ t.Fatal("cache read or readiness write")
+ }
+ t.Logf("memo=%v failing=%v: %d GET, %d LIST; cache hits: zero", memo, failing, gets, lists)
+ }
+ }
+}
+
+func TestDemoClaimReadinessMultipleBoxes(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ claimGateEdge(t, s, func(f map[string]any) { f["prev_seeds_allowed_for"] = "" })
+ raw, _, err := s.cfg.Releases.Get(t.Context(), "control/edges/box-a.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f map[string]any
+ if err = json.Unmarshal(raw, &f); err != nil {
+ t.Fatal(err)
+ }
+ f["box"] = "dennis-stenciling"
+ f["eip"] = "192.0.2.11"
+ raw, err = json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.cfg.Releases.Put(t.Context(), "control/edges/dennis-stenciling.json", raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ boxes, err := status.LoadBoxes(t.Context(), s.cfg.Releases)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := boxes[0]
+ b.Label = "dennis-stenciling"
+ if err = status.WriteBox(t.Context(), s.cfg.Releases, b); err != nil {
+ t.Fatal(err)
+ }
+ gates, err := s.demoClaimReadinessGates(t.Context())
+ want := "edge-prev:box-a,edge-prev:dennis-stenciling,seed-region"
+ if err == nil || gates.names() != want || gates.names() != want {
+ t.Fatalf("multiple boxes: %q %v", gates.names(), err)
+ }
+}
+
+func TestDemoClaimSeedGatePrerequisites(t *testing.T) {
+ for _, which := range []string{"host-claim", "claim-gated", "seed-region"} {
+ t.Run(which, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ region := s.cfg.Region
+ switch which {
+ case "host-claim":
+ s.cfg.HostClaim = true
+ case "claim-gated":
+ s.store.gate = &claimGate{}
+ defer func() { s.store.gate = nil }()
+ case "seed-region":
+ region = "other"
+ }
+ gates := s.demoClaimSeedGates(t.Context(), region)
+ if !slices.Contains(gates, which) {
+ t.Fatalf("missing %q: %q", which, gates.names())
+ }
+ if err := s.demoClaimSeedReady(t.Context(), region); err == nil || err.Error() != demoClaimUnavailable {
+ t.Fatalf("seed refusal: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/console/demo_claim_ha_gate_test.go b/internal/console/demo_claim_ha_gate_test.go
new file mode 100644
index 000000000..ff56b1bd0
--- /dev/null
+++ b/internal/console/demo_claim_ha_gate_test.go
@@ -0,0 +1,100 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ lsfile "github.com/benbjohnson/litestream/file"
+)
+
+func TestDemoClaimReservationBornHA(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ ha bool
+ pools []string
+ invalid, refuse bool
+ }{
+ {name: "non-HA"},
+ {name: "region-wide", ha: true, refuse: true},
+ {name: "named-only", ha: true, pools: []string{"ha"}},
+ // The parser rejects this configuration; the predicate also refuses it
+ // if an in-memory scope ever contains the shared pool.
+ {name: "shared-pool", ha: true, pools: []string{""}, refuse: true},
+ {name: "invalid-scope", ha: true, pools: []string{"ha"}, invalid: true, refuse: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s, _, token := claimTestServer(t)
+ f, _ := claimProved(t, s, token, "shop@example.com")
+ a := claimAccount(t, s, 501, f.Person, RoleOwner)
+ claimActivationFixture(t, s)
+ s.cfg.HomeRegion = "ie"
+ if tc.ha {
+ s.cfg.HARegions = []string{"ie"}
+ }
+ s.haPools = map[string][]string{"ie": tc.pools}
+ s.haScopeInvalid = tc.invalid
+ gates, err := s.demoClaimReadinessGates(t.Context())
+ if slices.Contains(gates, "ha-region") != tc.refuse || (err != nil) != tc.refuse {
+ t.Fatalf("readiness HA gate: %q, %v; refuse=%v", gates.names(), err, tc.refuse)
+ }
+ if err := s.demoClaimSeedReady(t.Context(), s.cfg.Region); (err != nil) != tc.refuse {
+ t.Fatalf("seed HA gate: %v; refuse=%v", err, tc.refuse)
+ } else if err != nil && err.Error() != demoClaimUnavailable {
+ t.Fatalf("seed refusal changed: %v", err)
+ }
+ // Reach the placement gate even when readiness would refuse admission.
+ s.demoClaimTestEnabled = true
+ op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{})
+ if tc.refuse {
+ if !errors.Is(err, errDemoClaimPlacement) {
+ t.Fatalf("reservation refusal: %v", err)
+ }
+ var count int
+ if err = s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_ops`).Scan(&count); err != nil || count != 0 {
+ t.Fatalf("refused placement reserved an operation: %d %v", count, err)
+ }
+ apps, err := s.store.AppsIn(a.ID)
+ if err != nil || len(apps) != 0 {
+ t.Fatalf("refused placement created an app: %v %v", apps, err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ root := t.TempDir()
+ s.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) {
+ return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil
+ }
+ rec, err := s.createDemoClaimSeed(t.Context(), op)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rec.HA || rec.Pool != "" {
+ t.Fatalf("destination born HA or pooled: %+v", rec)
+ }
+ stored, _, err := s.readRecord(t.Context(), op.Target.Sqid, op.Target.App, op.Target.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if stored.HA || stored.Pool != "" {
+ t.Fatalf("stored destination born HA or pooled: %+v", stored)
+ }
+ })
+ }
+}
+
+func TestDemoClaimSeedHAPoolScopeParsing(t *testing.T) {
+ raw := strings.Replace(haTestConfig, `"aws_region":"eu-west-1"`, `"aws_region":"eu-west-1","ha_pools":[""]`, 1)
+ if _, err := parseHACapacityConfig(raw, []string{"ie"}, "ie"); err == nil {
+ t.Fatal("shared pool unexpectedly representable in HA config")
+ }
+ raw = strings.Replace(haTestConfig, `"aws_region":"eu-west-1"`, `"aws_region":"eu-west-1","ha_pools":["ha"]`, 1)
+ if _, err := parseHACapacityConfig(raw, []string{"ie"}, "ie"); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/console/demo_claim_moved.go b/internal/console/demo_claim_moved.go
index 0f16b7b9b..e803e94f1 100644
--- a/internal/console/demo_claim_moved.go
+++ b/internal/console/demo_claim_moved.go
@@ -26,13 +26,23 @@ type demoMovedCache struct {
}
func (s *Server) demoClaimMovedReady(ctx context.Context) error {
- snap, err := s.liveEdges(ctx)
- if err != nil || !snap.EvidenceComplete() || len(snap.Files) == 0 {
- return errors.New(demoClaimUnavailable)
+ _, err := s.demoClaimMovedGates(ctx)
+ return err
+}
+
+func (s *Server) demoClaimMovedGates(ctx context.Context) (demoClaimGates, error) {
+ var gates demoClaimGates
+ gates.check("releases", s.cfg.Releases != nil)
+ if s.cfg.Releases == nil {
+ return gates, gates.err()
}
+ snap, err := s.liveEdges(ctx)
+ gates.check("edges-evidence", err == nil && snap.EvidenceComplete() && len(snap.Files) != 0)
+ firstErr := gates.err()
boxes, err := status.LoadBoxes(ctx, s.cfg.Releases)
- if err != nil {
- return err
+ gates.check("box-status", err == nil)
+ if firstErr == nil {
+ firstErr = err
}
capable := map[string]bool{}
seen := map[string]bool{}
@@ -44,12 +54,20 @@ func (s *Server) demoClaimMovedReady(ctx context.Context) error {
seen[b.Label] = true
capable[b.Label] = !status.BoxStale(b, time.Now(), status.SnapshotPeriod) && b.Metrics != nil && slices.Contains(b.Metrics.Capabilities, democlaim.MovedCapability)
}
+ counted := 0
for _, f := range snap.Files {
- if !capable[f.Box] || !slices.Contains(f.Capabilities, democlaim.MovedCapability) {
- return errors.New(demoClaimUnavailable)
+ if !demoClaimEdge(f) {
+ continue
}
+ counted++
+ gates.check("moved-box:"+f.Box, capable[f.Box])
+ gates.check("moved-edge:"+f.Box, slices.Contains(f.Capabilities, democlaim.MovedCapability))
}
- return nil
+ gates.check("no-shared-edges", counted != 0)
+ if firstErr != nil {
+ return gates, firstErr
+ }
+ return gates, gates.err()
}
// Pending operations reserve their eventual wire size in the same writer
diff --git a/internal/console/demo_claim_ready.go b/internal/console/demo_claim_ready.go
index 0115f0fb4..d6e10cd40 100644
--- a/internal/console/demo_claim_ready.go
+++ b/internal/console/demo_claim_ready.go
@@ -4,52 +4,113 @@ import (
"context"
"crypto/ed25519"
"errors"
+ "log"
+ "slices"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/democlaim"
"github.com/carlosframework/platform/internal/release"
)
+type demoClaimAdmissionCache struct {
+ demoAdmissionCache
+ failures string
+ prerequisites string
+}
+
+type demoClaimGates []string
+
+func (g *demoClaimGates) check(name string, ready bool) {
+ if !ready {
+ *g = append(*g, name)
+ }
+}
+
+func (g demoClaimGates) names() string {
+ g = slices.Clone(g)
+ slices.Sort(g)
+ return strings.Join(slices.Compact(g), ",")
+}
+
+func (g demoClaimGates) err() error {
+ if len(g) != 0 {
+ return errors.New(demoClaimUnavailable)
+ }
+ return nil
+}
+
+// Older writers do not declare pool membership, so they still count.
+func demoClaimEdge(f edgesFilePlacementView) bool {
+ return f.ServesSharedPool == nil || *f.ServesSharedPool
+}
+
// Readiness shares one bounded verdict across callers, including failures.
// Switching off bypasses the cache and performs no deployment reads.
func (s *Server) demoClaimReady(ctx context.Context) error {
refuse := func() error { return errors.New(demoClaimUnavailable) }
- if !s.cfg.Demo.ClaimEnabled || !s.cfg.Demo.Enabled || s.cfg.HostClaim || s.store.claimGated() {
+ if !s.cfg.Demo.ClaimEnabled {
return refuse()
}
c := &s.demoClaimAdmission
c.mu.Lock()
defer c.mu.Unlock()
- if c.checked && time.Now().Before(c.expiresAt) {
+ var gates demoClaimGates
+ gates.check("demo-enabled", s.cfg.Demo.Enabled)
+ gates.check("host-claim", !s.cfg.HostClaim)
+ gates.check("claim-gated", s.store == nil || !s.store.claimGated())
+ prerequisites := gates.names()
+ if c.checked && prerequisites == c.prerequisites && time.Now().Before(c.expiresAt) {
return c.err
}
- ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
- defer cancel()
- c.err = s.checkDemoClaimReady(ctx)
+ err := gates.err()
+ if err == nil {
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
+ defer cancel()
+ gates, err = s.demoClaimReadinessGates(ctx)
+ }
+ failures := gates.names()
+ if failures != c.failures {
+ if failures == "" {
+ log.Printf("console: demo claim readiness: ready")
+ } else {
+ log.Printf("console: demo claim readiness: refusing: %s", failures)
+ }
+ }
+ c.failures = failures
+ c.prerequisites = prerequisites
+ c.err = err
c.checked = true
c.expiresAt = time.Now().Add(demoAdmissionTTL)
return c.err
}
func (s *Server) checkDemoClaimReady(ctx context.Context) error {
- refuse := func() error { return errors.New(demoClaimUnavailable) }
+ _, err := s.demoClaimReadinessGates(ctx)
+ return err
+}
+
+func (s *Server) demoClaimReadinessGates(ctx context.Context) (demoClaimGates, error) {
+ var gates demoClaimGates
// Readiness means the browser Keymail path can complete. Email-code starts
// are refused per request when no mailer is ready.
- if s.km == nil || s.km.Host() == "" || s.cfg.AppsDomain == "" ||
- len(s.cfg.Key) != ed25519.PrivateKeySize || len(s.cfg.ReleasePub) != ed25519.PublicKeySize ||
- s.cfg.Releases == nil || s.cfg.SeedData == nil || !s.leftoverCheckApplies(s.cfg.Region, "") {
- return refuse()
- }
- if _, ok := s.cfg.SeedData.(release.PutStreamer); !ok {
- return refuse()
+ gates.check("keymail", s.km != nil && s.km.Host() != "")
+ gates.check("apps-domain", s.cfg.AppsDomain != "")
+ gates.check("signing-key", len(s.cfg.Key) == ed25519.PrivateKeySize)
+ gates.check("release-pub", len(s.cfg.ReleasePub) == ed25519.PublicKeySize)
+ gates.check("releases", s.cfg.Releases != nil)
+ gates.check("seed-data", s.cfg.SeedData != nil)
+ gates.check("leftover-check", s.leftoverCheckApplies(s.cfg.Region, ""))
+ if s.cfg.SeedData != nil {
+ _, ok := s.cfg.SeedData.(release.PutStreamer)
+ gates.check("seed-stream", ok)
}
// Delivery uses the existing shared watch. Reading its index checks access
// without mutating control state or adding a watch per claim or per box.
- if s.recordView == nil || s.recordView.Watch() == nil {
- return refuse()
- }
- if _, tag, err := release.ReadChangeIndex(ctx, s.cfg.Releases); err != nil || tag == "" {
- return refuse()
+ gates.check("record-watch", s.recordView != nil && s.recordView.Watch() != nil)
+ if s.cfg.Releases != nil {
+ _, tag, err := release.ReadChangeIndex(ctx, s.cfg.Releases)
+ gates.check("change-index", err == nil && tag != "")
}
found := false
for _, p := range s.demoEligiblePeers() {
@@ -58,17 +119,17 @@ func (s *Server) checkDemoClaimReady(ctx context.Context) error {
break
}
}
- if !found {
- return refuse()
- }
- if err := s.demoPublishReady(ctx, ""); err != nil {
- return refuse()
+ gates.check("worker-peer", found)
+ gates.check("publish", s.demoPublishReady(ctx, "") == nil)
+ gates = append(gates, s.demoClaimSeedGates(ctx, s.cfg.Region)...)
+ if s.cfg.Releases != nil {
+ moved, _ := s.demoClaimMovedGates(ctx)
+ gates = append(gates, moved...)
}
- if err := s.demoClaimSeedReady(ctx, s.cfg.Region); err != nil {
- return refuse()
- }
- if err := s.demoClaimMovedReady(ctx); err != nil {
- return refuse()
+ if err := gates.err(); err != nil {
+ gates.check("context", ctx.Err() == nil)
+ return gates, err
}
- return ctx.Err()
+ gates.check("context", ctx.Err() == nil)
+ return gates, ctx.Err()
}
diff --git a/internal/console/demo_claim_ready_test.go b/internal/console/demo_claim_ready_test.go
index aa5bfda7f..86dc74d49 100644
--- a/internal/console/demo_claim_ready_test.go
+++ b/internal/console/demo_claim_ready_test.go
@@ -12,6 +12,7 @@ import (
"github.com/carlosframework/platform/internal/democlaim"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
)
func claimActivationFixture(t *testing.T, s *Server) {
@@ -208,3 +209,101 @@ func TestDemoClaimReadinessWithPurgedStrays(t *testing.T) {
})
}
}
+
+func TestDemoClaimReadinessSharedPool(t *testing.T) {
+ for _, tc := range []struct {
+ name, membership, fault string
+ seedReady, movedReady bool
+ }{
+ {"named edge without capabilities", "named", "capabilities", true, true},
+ {"named edge old protocol", "named", "protocol", true, true},
+ {"named edge old rollback", "named", "previous", true, true},
+ {"named edge unaccepted floor", "named", "floor", true, true},
+ {"named edge unready heartbeat", "named", "heartbeat", true, true},
+ {"shared edge without capabilities", "shared", "capabilities", false, false},
+ {"shared edge old protocol", "shared", "protocol", false, true},
+ {"shared edge old rollback", "shared", "previous", false, true},
+ {"shared edge unaccepted floor", "shared", "floor", false, true},
+ {"shared edge unready heartbeat", "shared", "heartbeat", false, false},
+ {"legacy edge without capabilities", "absent", "capabilities", false, false},
+ {"legacy edge ready", "absent", "", true, true},
+ {"shared edge ready", "shared", "", true, true},
+ {"only named edges", "only-named", "", false, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s, _, _ := claimTestServer(t)
+ claimActivationFixture(t, s)
+ ctx := t.Context()
+ key := "control/edges/box-a.json"
+ raw, tag, err := s.cfg.Releases.Get(ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var f map[string]any
+ if err = json.Unmarshal(raw, &f); err != nil {
+ t.Fatal(err)
+ }
+ f["serves_shared_pool"] = tc.membership != "only-named"
+ // Inbound acceptance does not decide whether an edge serves claims.
+ f["accepts_inbound"] = false
+ raw, err = json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.cfg.Releases.Put(ctx, key, raw, tag); err != nil {
+ t.Fatal(err)
+ }
+ if tc.membership != "only-named" {
+ f["box"] = "box-b"
+ f["eip"] = "192.0.2.11"
+ f["accepts_inbound"] = tc.membership == "named"
+ if tc.membership == "absent" {
+ delete(f, "serves_shared_pool")
+ } else {
+ f["serves_shared_pool"] = tc.membership == "shared"
+ }
+ switch tc.fault {
+ case "capabilities":
+ f["capabilities"] = []string{"lifetimes-1"}
+ case "protocol":
+ f["seeds_protocol"] = 1
+ case "previous":
+ f["prev_seeds_allowed_for"] = ""
+ case "floor":
+ f["seeds_floor_state"] = "refused"
+ f["seeds_floor_generation"] = 1
+ }
+ raw, err = json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.cfg.Releases.Put(ctx, "control/edges/box-b.json", raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ b := status.CollectBox(nil, status.Probes{DemoClaimSeedReady: tc.fault != "heartbeat", DemoMovedReady: tc.fault != "heartbeat", Release: "v1.0.0", Platform: "linux-arm64", Layout: &status.LayoutReport{Mode: "nested"}}, time.Now())
+ b.Label = "box-b"
+ if tc.fault == "heartbeat" {
+ b.Metrics.Platform = "linux-amd64"
+ b.Metrics.Layout.Mode = "flat"
+ }
+ if err = status.WriteBox(ctx, s.cfg.Releases, b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.demoClaimSeedReady(ctx, s.cfg.Region); (err == nil) != tc.seedReady {
+ t.Fatalf("seed readiness = %v, want ready %v", err, tc.seedReady)
+ }
+ if err := s.demoClaimMovedReady(ctx); (err == nil) != tc.movedReady {
+ t.Fatalf("moved readiness = %v, want ready %v", err, tc.movedReady)
+ }
+ if err := s.checkDemoClaimReady(ctx); (err == nil) != (tc.seedReady && tc.movedReady) {
+ t.Fatalf("claim readiness = %v", err)
+ }
+ if tc.membership == "named" && (tc.fault == "protocol" || tc.fault == "previous" || tc.fault == "floor" || tc.fault == "heartbeat") {
+ if s.seedRegionReady(ctx, s.cfg.Region, false) == nil {
+ t.Fatal("ordinary seed operation skipped an unready named-pool box")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/console/demo_claim_seed.go b/internal/console/demo_claim_seed.go
index 42d3db397..a4261e4db 100644
--- a/internal/console/demo_claim_seed.go
+++ b/internal/console/demo_claim_seed.go
@@ -34,32 +34,53 @@ func (s *Server) demoClaimVerifyToken(id string) (string, error) {
// Admission requires every ingress reader as well as every destination.
// Protocol 2's existing seeds floor excludes an older rollback binary.
func (s *Server) demoClaimSeedReady(ctx context.Context, region string) error {
- refuse := func() error { return errors.New(demoClaimUnavailable) }
- if s.cfg.HostClaim || s.store.claimGated() || s.cfg.Releases == nil || region != s.cfg.Region || s.haRegion(region) {
- return refuse()
- }
- if ref := s.seedRegionReady(ctx, region, false); ref != nil {
- return refuse()
- }
+ return s.demoClaimSeedGates(ctx, region).err()
+}
+
+func (s *Server) demoClaimSeedGates(ctx context.Context, region string) demoClaimGates {
+ var gates demoClaimGates
+ gates.check("host-claim", !s.cfg.HostClaim)
+ gates.check("claim-gated", s.store == nil || !s.store.claimGated())
+ gates.check("releases", s.cfg.Releases != nil)
+ gates.check("seed-region", region == s.cfg.Region)
+ gates.check("ha-region", !s.haCreate(region, ""))
+ if s.cfg.Releases == nil {
+ return gates
+ }
+ gates.check("seed-region", s.seedRegionReadyForEdges(ctx, region, false, demoClaimEdge) == nil)
floor, err := seeds.ReadFloor(ctx, s.cfg.Releases)
- if err != nil || floor == nil || floor.Min < seeds.DemoClaimProtocol {
- return refuse()
+ gates.check("seed-floor", err == nil && floor != nil && floor.Min >= seeds.DemoClaimProtocol)
+ if floor != nil {
+ ok, err := seeds.ReleaseAtOrAbove(floor.MinRelease, floor.MinRelease)
+ gates.check("seed-floor-release", ok && err == nil)
}
snap, err := s.liveEdges(ctx)
- if err != nil || !snap.EvidenceComplete() || len(snap.Files) == 0 {
- return refuse()
- }
+ gates.check("edges-evidence", err == nil && snap.EvidenceComplete() && len(snap.Files) != 0)
+ counted, inRegion := 0, 0
for _, f := range snap.Files {
- if !slices.Contains(f.Capabilities, seeds.DemoClaimCapability) || f.SeedsProtocol < seeds.DemoClaimProtocol ||
- f.SeedsFloorMinRelease != floor.MinRelease || (f.PrevRelease != "none" && f.PrevSeedsAllowedFor != floor.MinRelease) ||
- ((f.SeedsFloorState != "" || f.SeedsFloorGeneration != 0) && (f.SeedsFloorState != "accepted" || f.SeedsFloorGeneration == 0)) {
- return refuse()
+ if !demoClaimEdge(f) {
+ continue
+ }
+ counted++
+ if s.homeRegionIn(f.Placement) == s.homeRegionIn(region) {
+ inRegion++
+ if floor != nil {
+ gates.check("seed-floor-protocol", f.SeedsProtocol >= max(seeds.RequiredProtocol, floor.Min))
+ }
+ gates.check("edge-moves-floor:"+f.Box, (f.MovesFloorState == "" && f.MovesFloorGeneration == 0) || (f.SeedsFloorState == "accepted" && f.SeedsFloorGeneration != 0))
}
+ gates.check("edge-capability:"+f.Box, slices.Contains(f.Capabilities, seeds.DemoClaimCapability))
+ gates.check("edge-protocol:"+f.Box, f.SeedsProtocol >= seeds.DemoClaimProtocol)
+ if floor != nil {
+ gates.check("edge-floor:"+f.Box, f.SeedsFloorMinRelease == floor.MinRelease)
+ gates.check("edge-prev:"+f.Box, f.PrevRelease == "none" || f.PrevSeedsAllowedFor == floor.MinRelease)
+ }
+ gates.check("edge-floor-state:"+f.Box, (f.SeedsFloorState == "" && f.SeedsFloorGeneration == 0) || (f.SeedsFloorState == "accepted" && f.SeedsFloorGeneration != 0))
}
+ gates.check("no-shared-edges", counted != 0)
+ gates.check("seed-region-edges", inRegion != 0)
boxes, err := status.LoadBoxes(ctx, s.cfg.Releases)
- if err != nil {
- return refuse()
- }
+ gates.check("box-status", err == nil)
byLabel := map[string]status.Box{}
dup := map[string]bool{}
for _, b := range boxes {
@@ -69,15 +90,20 @@ func (s *Server) demoClaimSeedReady(ctx context.Context, region string) error {
byLabel[b.Label] = b
}
for _, f := range snap.Files {
- b, ok := byLabel[f.Box]
- if !ok || dup[f.Box] || status.BoxStale(b, time.Now(), status.SnapshotPeriod) || b.Metrics == nil || !slices.Contains(b.Metrics.Capabilities, seeds.DemoClaimCapability) {
- return refuse()
+ if !demoClaimEdge(f) {
+ continue
}
- if s.homeRegionIn(f.Placement) == s.homeRegionIn(region) && b.Metrics.Platform != "linux-arm64" {
- return refuse()
+ b, ok := byLabel[f.Box]
+ gates.check("box-status:"+f.Box, ok && !dup[f.Box] && !status.BoxStale(b, time.Now(), status.SnapshotPeriod) && b.Metrics != nil && slices.Contains(b.Metrics.Capabilities, seeds.DemoClaimCapability))
+ if s.homeRegionIn(f.Placement) == s.homeRegionIn(region) {
+ gates.check("box-layout:"+f.Box, b.Metrics != nil && b.Metrics.Layout != nil && b.Metrics.Layout.Mode == "nested")
+ if b.Metrics != nil {
+ gates.check("box-claim-control:"+f.Box, !b.Metrics.HostClaimEnabled)
+ gates.check("box-platform:"+f.Box, b.Metrics.Platform == "linux-arm64")
+ }
}
}
- return nil
+ return gates
}
// Call while holding the app lock. Stored identity, not a caller's target,
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go
index ac691107b..a9f1d0ec0 100644
--- a/internal/console/demo_claim_target.go
+++ b/internal/console/demo_claim_target.go
@@ -139,7 +139,7 @@ func (s *Server) reserveDemoClaim(ctx context.Context, f claimFlow, acct *Accoun
}
region, source := s.resolveNewAppRegion(ctx, rq, false)
// Never silently replace an incompatible normal placement with the home.
- if region != s.cfg.Region || s.haRegion(region) || s.cfg.HostClaim || s.cfg.AppsDomain == "" {
+ if region != s.cfg.Region || s.haCreate(region, "") || s.cfg.HostClaim || s.cfg.AppsDomain == "" {
return claimOp{}, errDemoClaimPlacement
}
if err = s.roomIn(ctx, region, ""); err != nil {
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go
index 5ddb19eba..e8d4074b0 100644
--- a/internal/console/demo_claim_transfer.go
+++ b/internal/console/demo_claim_transfer.go
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"errors"
"io"
+ "log"
"net/http"
"os"
"sort"
@@ -44,19 +45,27 @@ func (s *Server) claimBoundary(at string) error {
}
func (s *Server) demoClaimCapabilitiesReady(ctx context.Context, op claimOp) error {
+ _, err := s.demoClaimCapabilityGates(ctx, op)
+ return err
+}
+
+func (s *Server) demoClaimCapabilityGates(ctx context.Context, op claimOp) (demoClaimGates, error) {
+ var gates demoClaimGates
found := false
for _, p := range s.demoEligiblePeers() {
if p.box() == op.SourceBox && p.ready.ClaimCapability == democlaim.Capability && p.ready.MovedCapability == democlaim.MovedCapability {
found = true
}
}
- if !found {
- return errors.New(demoClaimUnavailable)
+ gates.check("worker-peer", found)
+ if err := gates.err(); err != nil {
+ return gates, err
}
- if err := s.demoClaimSeedReady(ctx, op.Target.Region); err != nil {
- return err
+ gates = s.demoClaimSeedGates(ctx, op.Target.Region)
+ if err := gates.err(); err != nil {
+ return gates, err
}
- return s.demoClaimMovedReady(ctx)
+ return s.demoClaimMovedGates(ctx)
}
// The operation mutex serializes pickup, upload, abort and recovery. It is
@@ -102,8 +111,8 @@ func (s *Server) advanceDemoClaimLocked(ctx context.Context, id string) error {
if !s.demoClaimEnabled() {
return s.beginDemoClaimAbort(ctx, op, "disabled")
}
- if err = s.demoClaimCapabilitiesReady(ctx, op); err != nil {
- return s.beginDemoClaimAbort(ctx, op, "capability")
+ if gates, err := s.demoClaimCapabilityGates(ctx, op); err != nil {
+ return s.beginDemoClaimAbort(ctx, op, "capability", gates...)
}
if err = s.pinDemoClaim(ctx, &op); err != nil {
return s.beginDemoClaimAbort(ctx, op, "source_unready")
@@ -773,7 +782,7 @@ func (s *Server) abortDemoClaimLocked(ctx context.Context, id, reason string) er
return s.beginDemoClaimAbort(ctx, op, reason)
})
}
-func (s *Server) beginDemoClaimAbort(ctx context.Context, op claimOp, reason string) error {
+func (s *Server) beginDemoClaimAbort(ctx context.Context, op claimOp, reason string, gates ...string) error {
if op.Phase == "committed" || op.Phase == "done" {
return ErrDemoToken
}
@@ -797,6 +806,9 @@ func (s *Server) beginDemoClaimAbort(ctx context.Context, op claimOp, reason str
if err = tx.Commit(); err != nil {
return err
}
+ if op.Phase == "reserved" && reason == "capability" {
+ log.Printf("console: demo claim capability: refusing: %s", demoClaimGates(gates).names())
+ }
op.Phase = "aborting"
return s.continueDemoClaimAbort(ctx, op)
}
diff --git a/internal/console/hacapacity.go b/internal/console/hacapacity.go
index c2fab489a..a0fd67e3a 100644
--- a/internal/console/hacapacity.go
+++ b/internal/console/hacapacity.go
@@ -204,6 +204,32 @@ func HADataStoreRegions(cfg Config) (map[string]HADataStore, error) {
return regions, nil
}
+// provenGroupMember reports whether this generation proved ref a box its
+// region's group launched, in region (the record-vocabulary placement code,
+// "" for the home): ref's edges file was read within region's scope, its
+// signed identity verified, ref is haGroupReference of that identity's
+// account and instance, and no other file conflicts with it. The hostname
+// history's coverage check excuses only such a box's box: target (Paul's
+// ruling on #421, 2026-11-06); the caller checks the observation is
+// available.
+func (o *HACapacityObservation) provenGroupMember(region, ref string) bool {
+ if o == nil || o.config == nil {
+ return false
+ }
+ if region == "" {
+ region = o.config.home
+ }
+ if _, pinned := o.config.FixedBoxes[ref]; pinned {
+ return false // the operator declared it fixed
+ }
+ for _, f := range o.files {
+ if f.ref == ref {
+ return f.group && f.region == region && !f.malformed && f.identityCode == "" && f.instance != ""
+ }
+ }
+ return false
+}
+
func haGroupReference(account, instance string) string {
sum := sha256.Sum256([]byte("carlos-box-ref-v1|" + account + "|" + instance))
return "g-" + hex.EncodeToString(sum[:])[:20]
@@ -248,6 +274,11 @@ type haCapacityFile struct {
instance string
report *status.Box
statusCode string
+ // region is the configured region whose scope admitted the file, and
+ // group that its signed identity derives its reference
+ // (haGroupReference): set by observe, read by provenGroupMember.
+ region string
+ group bool
}
// HACapacityObservation retains producer evidence. Its fields and collections
diff --git a/internal/console/hacapacity_observe.go b/internal/console/hacapacity_observe.go
index 819eb1969..714528b2a 100644
--- a/internal/console/hacapacity_observe.go
+++ b/internal/console/hacapacity_observe.go
@@ -424,6 +424,8 @@ func (o *haObserver) observe(ctx context.Context, start time.Time) *HACapacityOb
continue
}
f.instance = ev.Cloud.InstanceID
+ f.region = region
+ f.group = strings.HasPrefix(f.ref, "g-") && f.ref == haGroupReference(ev.Cloud.Account, f.instance)
instances[f.instance] = append(instances[f.instance], i)
if strings.HasPrefix(f.ref, "g-") && f.ref != haGroupReference(ev.Cloud.Account, f.instance) {
f.identityCode = "instance_conflict"
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index 184b03994..15133cf81 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -8,10 +8,12 @@ import (
"net/http"
"os"
"slices"
+ "strings"
"sync"
"time"
"github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/geo"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
@@ -221,7 +223,9 @@ func (s *Server) hostsTargetRefusal(ctx context.Context, region string) *doorRef
// region's target set is fixed once recorded). A box added to a fleet
// since is refused at its own door (addFleetBoxRecorded); a box that joins
// a region does so from infra, so a create there is refused here until
-// the history is completed again. Targets that cannot be read refuse (S5).
+// the history is completed again, unless the HA capacity observation
+// proved it a group member (provenGroupTarget; its data bucket is still
+// checked). Targets that cannot be read refuse (S5).
// It reads the edges files (one snapshot, which also names the place), or
// the registry for a fleet, once per data-kind create while the history is
// active.
@@ -258,6 +262,7 @@ func (s *Server) hostsCoverageRefusal(ctx context.Context, region string) *doorR
}
now, recorded = rosterRegions(snap)["region:"+region], st.RegionTargets
place = snapshotPlaceName(snap, region, s.homeRegionOut(region))
+ now = slices.DeleteFunc(now, func(t string) bool { return s.provenGroupTarget(snap, region, t) })
}
for _, t := range now {
if !slices.Contains(recorded, t) {
@@ -271,6 +276,30 @@ func (s *Server) hostsCoverageRefusal(ctx context.Context, region string) *doorR
return nil
}
+// provenGroupTarget reports whether t is the box: target of a box the
+// current HA capacity observation proved its region's group launched
+// (provenGroupMember): such a box is not a target the history waits for
+// (Paul's ruling on #421, 2026-11-06). Every replacement mints a new
+// reference, and a group box starts from the launch template with a fresh
+// disk, is never restored onto (durability §3.1 item 3), and holds only
+// copies of state in its region's data bucket, which stays a target
+// checked here. No observation, or one that is stale, proves nothing. Every
+// file in snap naming the box must be the box's own (its key and box_id
+// are its reference), so another file cannot hide behind a proven name.
+func (s *Server) provenGroupTarget(snap edgesSnapshot, region, t string) bool {
+ ref, ok := strings.CutPrefix(t, "box:")
+ if !ok || !edgesfile.IsGroupReference(ref) {
+ return false
+ }
+ for _, f := range snap.Files {
+ if f.Box == ref && (f.Key != edgesfile.Key(ref) || f.BoxID != ref) {
+ return false
+ }
+ }
+ obs, ok := s.HACapacity()
+ return ok && obs.provenGroupMember(region, ref)
+}
+
// snapshotPlaceName is a region's place name from the snapshot already
// read (placeOf's rule: the AWS region its boxes publish, else fallback),
// so the refusal costs no second read.
diff --git a/internal/console/hostsused_groupmember_test.go b/internal/console/hostsused_groupmember_test.go
new file mode 100644
index 000000000..440d9298f
--- /dev/null
+++ b/internal/console/hostsused_groupmember_test.go
@@ -0,0 +1,224 @@
+package console
+
+// A box its region's group launched is not a target the hostname history
+// waits for (Paul's ruling on #421, 2026-11-06, option A). Every
+// replacement mints a new g- reference, and before this ruling each one
+// refused every data-kind create in its region until the history was
+// completed again offline. A group box starts from the launch template
+// with a fresh disk, cannot be restored onto (durability §3.1 item 3) and
+// holds only copies of state in the region's data bucket, which stays a
+// checked target. So the coverage check excuses a box: target only when
+// the current HA capacity observation proved it a group member: its signed
+// identity verified and its reference haGroupReference of that identity.
+// Anything less is refused as before.
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const groupTestInstance = "i-0fedcba9876543210"
+
+// groupMemberCase is a console whose home region's history was completed
+// with one fixed box (leo) and the region's bucket, after which a group
+// member published its edges file.
+type groupMemberCase struct {
+ fx *consoleFixture
+ ref string
+ o *haObserver
+}
+
+func newGroupMemberCase(t *testing.T) groupMemberCase {
+ return newGroupMemberCaseFor(t, groupTestInstance)
+}
+
+func newGroupMemberCaseFor(t *testing.T, instance string) groupMemberCase {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ putHostsEdges(t, fx.rel, "leo", "", "test-data")
+ activeAsNow(t, fx.srv)
+ ref := haGroupReference(moveTestAccount, instance)
+ putMemberEdges(t, fx.rel, ref, "", "test-data")
+ return groupMemberCase{fx: fx, ref: ref}
+}
+
+// putMemberEdges is putHostsEdges for a group member, which publishes its
+// box_id (region HA spec 1 §5.1).
+func putMemberEdges(t *testing.T, st release.Store, ref, placement, bucket string) {
+ t.Helper()
+ body := `{"v":1,"box":"` + ref + `","box_id":"` + ref + `","eip":"192.0.2.1","region":"eu-west-1","placement":"` + placement + `","data_bucket":"` + bucket + `","hosts":{}}`
+ key := edgesFilePrefix + ref + ".json"
+ _, etag, _ := st.Get(context.Background(), key)
+ if _, err := st.Put(context.Background(), key, []byte(body), etag); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// observe publishes the member's evidence to the HA capacity observation's
+// store: its edges file (the golden publisher's body, under ref), a signed
+// identity for instance, and a fresh status; then observes at "at" and
+// installs the observer on the console.
+func (c *groupMemberCase) observe(t *testing.T, instance string, at time.Time, edit func(map[string]any)) {
+ t.Helper()
+ o, store, signer := haFixture(t)
+ now := time.Now().UTC()
+ haPut(t, store, edgesFilePrefix+"leo.json", haEdit(t, haGolden(t), func(m map[string]any) {
+ m["generation"] = now.Format(time.RFC3339Nano)
+ }))
+ haPut(t, store, edgesFilePrefix+c.ref+".json", haEdit(t, haGolden(t), func(m map[string]any) {
+ m["box"], m["box_id"] = c.ref, c.ref
+ m["box_role"], m["admitted"] = "booting", false
+ m["generation"] = now.Format(time.RFC3339Nano)
+ if edit != nil {
+ edit(m)
+ }
+ }))
+ _, raw := signer.Record(t, c.ref, moveTestAccount, "eu-west-1", instance)
+ haPut(t, store, boxid.Key(c.ref), raw)
+ haPut(t, store, haStatusPrefix+c.ref+".json", []byte(fmt.Sprintf(`{"label":%q,"generated_at":%q,"metrics":{"instance_id":%q}}`, c.ref, now.Format(time.RFC3339Nano), instance)))
+ o.current.Store(o.observe(context.Background(), at))
+ c.fx.srv.haCapacity.Store(o)
+ c.o = o
+}
+
+// proven fails the test unless the observation proved the member at home,
+// so a refusal subtest cannot pass for want of the proof it varies.
+func (c groupMemberCase) proven(t *testing.T) {
+ t.Helper()
+ if _, ok := c.fx.srv.HACapacity(); !ok || !c.o.current.Load().provenGroupMember("", c.ref) {
+ t.Fatal("the member was not proven at home: the case tests nothing")
+ }
+}
+
+func (c groupMemberCase) coverage(t *testing.T) *doorRefusal {
+ t.Helper()
+ return c.fx.srv.hostsCoverageRefusal(context.Background(), "")
+}
+
+func wantS4(t *testing.T, what string, ref *doorRefusal) {
+ t.Helper()
+ if ref == nil || ref.Status != http.StatusConflict {
+ t.Fatalf("%s: coverage = %+v, want 409 S4", what, ref)
+ }
+}
+
+// TestProvenGroupMemberJoinsRegion: a proven group member that joined the
+// home region after completion does not refuse creates there, and the
+// whole admission (gateDataCreate) passes.
+func TestProvenGroupMemberJoinsRegion(t *testing.T) {
+ c := newGroupMemberCase(t)
+ c.observe(t, groupTestInstance, time.Now().UTC(), nil)
+ if ref := c.coverage(t); ref != nil {
+ t.Fatalf("coverage with a proven group member = %+v, want admitted", ref)
+ }
+ if ref := c.fx.srv.gateDataCreate(context.Background(), "new.example.com", ""); ref != nil {
+ t.Fatalf("admission with a proven group member = %+v, want admitted", ref)
+ }
+}
+
+// TestUnprovenGroupMemberRefused: everything short of the proof refuses,
+// as before the ruling.
+func TestUnprovenGroupMemberRefused(t *testing.T) {
+ t.Run("no observation", func(t *testing.T) {
+ c := newGroupMemberCase(t)
+ wantS4(t, "no observation", c.coverage(t))
+ })
+ t.Run("stale observation", func(t *testing.T) {
+ c := newGroupMemberCase(t)
+ at := time.Now().UTC().Add(-haCapacityLifetime - time.Second)
+ c.observe(t, groupTestInstance, at, func(m map[string]any) { m["generation"] = at.Format(time.RFC3339Nano) })
+ if !c.o.current.Load().provenGroupMember("", c.ref) {
+ t.Fatal("the member was not proven when observed: the case tests nothing")
+ }
+ wantS4(t, "stale observation", c.coverage(t))
+ })
+ t.Run("reference not derived from its identity", func(t *testing.T) {
+ c := newGroupMemberCase(t)
+ c.observe(t, "i-0aaaaaaaaaaaaaaaa", time.Now().UTC(), nil)
+ wantS4(t, "a g- reference another instance's identity signs", c.coverage(t))
+ })
+ t.Run("proven in another region", func(t *testing.T) {
+ // Proven as a member of the home's group, but listed in de's
+ // edges: de's coverage does not take the home's proof.
+ c := newGroupMemberCase(t)
+ c.observe(t, groupTestInstance, time.Now().UTC(), nil)
+ if !c.o.current.Load().provenGroupMember("", c.ref) {
+ t.Fatal("the member was not proven at home: the case tests nothing")
+ }
+ putMemberEdges(t, c.fx.rel, c.ref, "de", "test-data")
+ wantS4(t, "a member proven in another region", c.fx.srv.hostsCoverageRefusal(context.Background(), "de"))
+ })
+ t.Run("a fixed box joins", func(t *testing.T) {
+ c := newGroupMemberCase(t)
+ c.observe(t, groupTestInstance, time.Now().UTC(), nil)
+ c.proven(t)
+ putHostsEdges(t, c.fx.rel, "late", "", "test-data")
+ wantS4(t, "a fixed box beside a proven member", c.coverage(t))
+ })
+ t.Run("a new data bucket", func(t *testing.T) {
+ c := newGroupMemberCase(t)
+ c.observe(t, groupTestInstance, time.Now().UTC(), nil)
+ c.proven(t)
+ putMemberEdges(t, c.fx.rel, c.ref, "", "other-data")
+ wantS4(t, "a proven member publishing a bucket never scanned", c.coverage(t))
+ })
+ t.Run("another file names the member", func(t *testing.T) {
+ // An edges file under another key whose body names the proven
+ // member must not hide behind its proof.
+ c := newGroupMemberCase(t)
+ c.observe(t, groupTestInstance, time.Now().UTC(), nil)
+ c.proven(t)
+ body := `{"v":1,"box":"` + c.ref + `","eip":"192.0.2.9","region":"eu-west-1","placement":"","hosts":{}}`
+ if _, err := c.fx.rel.Put(context.Background(), edgesFilePrefix+"old.json", []byte(body), ""); err != nil {
+ t.Fatal(err)
+ }
+ wantS4(t, "a second file naming the member", c.coverage(t))
+ })
+ t.Run("pinned as a fixed box", func(t *testing.T) {
+ c := newGroupMemberCase(t)
+ c.observe(t, groupTestInstance, time.Now().UTC(), nil)
+ c.proven(t)
+ c.o.config.FixedBoxes[c.ref] = haFixedBox{RegionCode: "ie", InstanceID: groupTestInstance}
+ wantS4(t, "a reference the configuration pins as fixed", c.coverage(t))
+ })
+ t.Run("an identity two boxes claim", func(t *testing.T) {
+ // The member's identity is leo's instance too: identity_duplicate.
+ c := newGroupMemberCaseFor(t, "i-0123456789abcdef0")
+ c.observe(t, "i-0123456789abcdef0", time.Now().UTC(), nil)
+ f := c.o.current.Load().files
+ for _, x := range f {
+ if x.ref == c.ref && (!x.group || x.identityCode != "identity_duplicate") {
+ t.Fatalf("the case tests nothing: %+v", x)
+ }
+ }
+ wantS4(t, "a member whose identity another box also claims", c.coverage(t))
+ })
+}
+
+// TestGroupMemberLeavesHistoryUnchanged: excusing a member writes nothing:
+// the mode's region targets are what completion recorded.
+func TestGroupMemberLeavesHistoryUnchanged(t *testing.T) {
+ c := newGroupMemberCase(t)
+ before, _, err := provision.ReadHostsState(context.Background(), c.fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ c.observe(t, groupTestInstance, time.Now().UTC(), nil)
+ if ref := c.coverage(t); ref != nil {
+ t.Fatalf("coverage = %+v", ref)
+ }
+ after, _, err := provision.ReadHostsState(context.Background(), c.fx.rel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fmt.Sprint(before.RegionTargets) != fmt.Sprint(after.RegionTargets) {
+ t.Fatalf("region targets changed: %v -> %v", before.RegionTargets, after.RegionTargets)
+ }
+}
diff --git a/internal/console/seedfloor.go b/internal/console/seedfloor.go
index 80a6b1668..a43197322 100644
--- a/internal/console/seedfloor.go
+++ b/internal/console/seedfloor.go
@@ -33,6 +33,12 @@ import (
// box whose own local floor is unreadable publishes "" for its floor, and
// must never be read as ready.
func (s *Server) seedRegionReady(ctx context.Context, region string, oneBox bool) *doorRefusal {
+ return s.seedRegionReadyForEdges(ctx, region, oneBox, nil)
+}
+
+// Demo claims only use shared-pool edges. Other seed operations pass nil and
+// retain the region-wide checks, including layout and host-claim readiness.
+func (s *Server) seedRegionReadyForEdges(ctx context.Context, region string, oneBox bool, include func(edgesFilePlacementView) bool) *doorRefusal {
region = s.homeRegionIn(region)
if s.cfg.HostClaim {
return seedClaimConsoleRefusal()
@@ -68,6 +74,9 @@ func (s *Server) seedRegionReady(ctx context.Context, region string, oneBox bool
}
var inRegion, below []string
for _, f := range snap.Files {
+ if include != nil && !include(f) {
+ continue
+ }
if s.homeRegionIn(f.Placement) != region {
continue
}
diff --git a/internal/console/server.go b/internal/console/server.go
index e1f9f3d77..101640147 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1007,7 +1007,7 @@ type Server struct {
demoTransport http.RoundTripper
demoAdmission demoAdmissionCache
- demoClaimAdmission demoAdmissionCache
+ demoClaimAdmission demoClaimAdmissionCache
demoStatus demoStatusLimiter
demoControlMu sync.RWMutex
demoStopMu sync.Mutex
diff --git a/internal/democlaim/moved.go b/internal/democlaim/moved.go
index feda4217d..bc5a20b62 100644
--- a/internal/democlaim/moved.go
+++ b/internal/democlaim/moved.go
@@ -105,3 +105,17 @@ func MovedDomains(r Moved, demoDomain, appsDomain string) bool {
target, ok := strings.CutSuffix(r.TargetHost, "."+appsDomain)
return ok && len(strings.Split(target, ".")) == 2 && demo.ValidDomain(r.TargetHost)
}
+
+// MovedEdgeDomains checks a signed notice without the console's apps-domain
+// configuration. The release signer authorizes the destination; it must be a
+// DNS name outside the demo domain with room for app and account labels.
+func MovedEdgeDomains(r Moved, demoDomain string) bool {
+ if !demo.ValidDomain(demoDomain) || !demo.ValidDomain(r.Host) || !demo.ValidDomain(r.TargetHost) {
+ return false
+ }
+ source, ok := strings.CutSuffix(r.Host, "."+demoDomain)
+ if !ok || source == "" || strings.Contains(source, ".") {
+ return false
+ }
+ return r.TargetHost != demoDomain && !strings.HasSuffix(r.TargetHost, "."+demoDomain) && strings.Count(r.TargetHost, ".") >= 2
+}
diff --git a/internal/democlaim/moved_test.go b/internal/democlaim/moved_test.go
index 771769eca..3a6af84ac 100644
--- a/internal/democlaim/moved_test.go
+++ b/internal/democlaim/moved_test.go
@@ -92,3 +92,33 @@ func TestDemoMovedLargeSnapshot(t *testing.T) {
t.Fatal("wrong signing context")
}
}
+
+func TestDemoMovedEdgeDomains(t *testing.T) {
+ for _, tc := range []struct {
+ name, source, target, domain string
+ want bool
+ }{
+ {"apps target", "shop.demos.example.com", "shop.bab.apps.example.com", "demos.example.com", true},
+ {"three labels", "shop.demos.example.com", "shop.bab.example", "demos.example.com", true},
+ {"suffix lookalike", "shop.demos.example.com", "shop.bab.notdemos.example.com", "demos.example.com", true},
+ {"demo target", "shop.demos.example.com", "other.demos.example.com", "demos.example.com", false},
+ {"nested demo target", "shop.demos.example.com", "other.bab.demos.example.com", "demos.example.com", false},
+ {"demo apex target", "shop.demos.example.com", "demos.example.com", "demos.example.com", false},
+ {"two labels", "shop.demos.example.com", "shop.example", "demos.example.com", false},
+ {"port", "shop.demos.example.com", "shop.bab.example:443", "demos.example.com", false},
+ {"path", "shop.demos.example.com", "shop.bab.example/path", "demos.example.com", false},
+ {"scheme", "shop.demos.example.com", "https://shop.bab.example", "demos.example.com", false},
+ {"uppercase", "shop.demos.example.com", "SHOP.bab.example", "demos.example.com", false},
+ {"source apex", "demos.example.com", "shop.bab.example", "demos.example.com", false},
+ {"deep source", "deep.shop.demos.example.com", "shop.bab.example", "demos.example.com", false},
+ {"foreign source", "shop.other.example.com", "shop.bab.example", "demos.example.com", false},
+ {"invalid source", "bad_name.demos.example.com", "shop.bab.example", "demos.example.com", false},
+ {"invalid domain", "shop.demos.example.com", "shop.bab.example", "", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := MovedEdgeDomains(Moved{Host: tc.source, TargetHost: tc.target}, tc.domain); got != tc.want {
+ t.Fatalf("MovedEdgeDomains = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/democlaim/source_linux.go b/internal/democlaim/source_linux.go
index f35c41c40..73987b310 100644
--- a/internal/democlaim/source_linux.go
+++ b/internal/democlaim/source_linux.go
@@ -20,17 +20,46 @@ type Source struct {
dir *os.File
base string
dbStat, walStat unix.Stat_t
+ openFile func(int, string) (int, error)
}
-func OpenSource(dir, base string) (s *Source, err error) {
+func OpenSource(dir, base string) (*Source, error) {
+ return openSource(dir, base, func(dir string) (*os.File, error) {
+ return instancefs.OpenDirBeneath(dir, ".")
+ }, func(fd int, name string) (int, error) {
+ return unix.Openat2(fd, name, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_CLOEXEC | unix.O_NONBLOCK, Resolve: unix.RESOLVE_BENEATH | unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
+ })
+}
+
+// OpenWorkerSource is only for fixed names in the worker's private /work.
+// DynamicUser's seccomp filter blocks openat2. A single component opened
+// with O_NOFOLLOW cannot escape the held directory or follow a symlink.
+func OpenWorkerSource(dir, base string) (*Source, error) {
+ return openSource(dir, base, func(dir string) (*os.File, error) {
+ fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, err
+ }
+ return os.NewFile(uintptr(fd), dir), nil
+ }, openWorkerFile)
+}
+
+func openWorkerFile(fd int, name string) (int, error) {
+ if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\\x00") {
+ return -1, ErrSnapshot
+ }
+ return unix.Openat(fd, name, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK|unix.O_NOFOLLOW, 0)
+}
+
+func openSource(dir, base string, openDir func(string) (*os.File, error), openFile func(int, string) (int, error)) (s *Source, err error) {
if !filepath.IsAbs(dir) || base == "" || base == "." || base == ".." || strings.ContainsAny(base, "/\\\x00") {
return nil, ErrSnapshot
}
- d, err := instancefs.OpenDirBeneath(dir, ".")
+ d, err := openDir(dir)
if err != nil {
return nil, err
}
- s = &Source{dir: d, base: base}
+ s = &Source{dir: d, base: base, openFile: openFile}
defer func() {
if err != nil {
s.Close()
@@ -63,7 +92,7 @@ func OpenSource(dir, base string) (s *Source, err error) {
func (s *Source) open(name string) (*os.File, unix.Stat_t, error) {
var st unix.Stat_t
- fd, err := unix.Openat2(int(s.dir.Fd()), name, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_CLOEXEC | unix.O_NONBLOCK, Resolve: unix.RESOLVE_BENEATH | unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
+ fd, err := s.openFile(int(s.dir.Fd()), name)
if err != nil {
return nil, st, err
}
diff --git a/internal/democlaim/source_other.go b/internal/democlaim/source_other.go
index a9ec1d708..d1086c883 100644
--- a/internal/democlaim/source_other.go
+++ b/internal/democlaim/source_other.go
@@ -12,6 +12,7 @@ type Source struct {
DBBytes, WALBytes int64
}
-func OpenSource(string, string) (*Source, error) { return nil, errors.ErrUnsupported }
-func (*Source) VerifyUnchanged() error { return errors.ErrUnsupported }
-func (*Source) Close() error { return nil }
+func OpenSource(string, string) (*Source, error) { return nil, errors.ErrUnsupported }
+func OpenWorkerSource(string, string) (*Source, error) { return nil, errors.ErrUnsupported }
+func (*Source) VerifyUnchanged() error { return errors.ErrUnsupported }
+func (*Source) Close() error { return nil }
diff --git a/internal/democlaim/source_worker_linux_test.go b/internal/democlaim/source_worker_linux_test.go
new file mode 100644
index 000000000..84516cfed
--- /dev/null
+++ b/internal/democlaim/source_worker_linux_test.go
@@ -0,0 +1,166 @@
+//go:build linux
+
+package democlaim
+
+import (
+ "bytes"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "golang.org/x/sys/unix"
+)
+
+func TestOpenWorkerSource(t *testing.T) {
+ t.Run("dbAndWAL", func(t *testing.T) {
+ dir := walFixture(t)
+ s, err := OpenWorkerSource(dir, "source.db")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ for _, entry := range []struct {
+ file *os.File
+ size int64
+ name string
+ }{{s.DB, s.DBBytes, "source.db"}, {s.WAL, s.WALBytes, "source.db-wal"}} {
+ if entry.file == nil || entry.size <= 0 {
+ t.Fatalf("missing %s", entry.name)
+ }
+ got, err := io.ReadAll(entry.file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, err := os.ReadFile(filepath.Join(dir, entry.name))
+ if err != nil || !bytes.Equal(got, want) || int64(len(got)) != entry.size {
+ t.Fatal("source bytes differ", entry.name, err)
+ }
+ }
+ if err = s.VerifyUnchanged(); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Truncate(filepath.Join(dir, "source.db-wal"), 0); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.VerifyUnchanged(); err == nil {
+ t.Fatal("changed WAL accepted")
+ }
+ })
+ for _, suffix := range []string{"", "-wal"} {
+ for _, fault := range []string{"symlink", "hardlink", "fifo", "directory", "oversize"} {
+ t.Run("source.db"+suffix+"/"+fault, func(t *testing.T) {
+ dir := t.TempDir()
+ must := func(err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ base := filepath.Join(dir, "source.db")
+ must(os.WriteFile(base, []byte("db"), 0600))
+ path := base + suffix
+ if suffix == "" {
+ must(os.Remove(path))
+ }
+ switch fault {
+ case "symlink":
+ must(os.WriteFile(path+".target", []byte("db"), 0600))
+ must(os.Symlink(path+".target", path))
+ case "hardlink":
+ must(os.WriteFile(path+".target", []byte("db"), 0600))
+ must(os.Link(path+".target", path))
+ case "fifo":
+ must(unix.Mkfifo(path, 0600))
+ case "directory":
+ must(os.Mkdir(path, 0700))
+ case "oversize":
+ must(os.WriteFile(path, []byte("db"), 0600))
+ must(os.Truncate(path, MaxSnapshotBytes+1))
+ }
+ if s, err := OpenWorkerSource(dir, "source.db"); err == nil {
+ s.Close()
+ t.Fatal("unsafe source accepted")
+ }
+ })
+ }
+ }
+ for _, name := range []string{"", ".", "..", "nested/source.db", "../source.db"} {
+ t.Run("name/"+name, func(t *testing.T) {
+ if s, err := OpenWorkerSource(t.TempDir(), name); err != ErrSnapshot {
+ if s != nil {
+ s.Close()
+ }
+ t.Fatal("unsafe name accepted", err)
+ }
+ if fd, err := openWorkerFile(-1, name); err != ErrSnapshot {
+ if fd >= 0 {
+ unix.Close(fd)
+ }
+ t.Fatal("worker file seam did not reject name", err)
+ }
+ })
+ }
+ t.Run("directorySymlink", func(t *testing.T) {
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(walFixture(t), link); err != nil {
+ t.Fatal(err)
+ }
+ if s, err := OpenWorkerSource(link, "source.db"); err == nil {
+ s.Close()
+ t.Fatal("directory symlink accepted")
+ }
+ })
+ t.Run("absentWAL", func(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "source.db"), []byte("db"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ s, err := OpenWorkerSource(dir, "source.db")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ if s.WAL != nil || s.WALBytes != 0 {
+ t.Fatal("absent WAL reported present")
+ }
+ if err = s.VerifyUnchanged(); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(dir, "source.db-wal"), []byte("wal"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.VerifyUnchanged(); err == nil {
+ t.Fatal("new WAL accepted")
+ }
+ })
+}
+
+func TestWorkerSourceDoesNotUseOpenat2(t *testing.T) {
+ f, err := parser.ParseFile(token.NewFileSet(), "source_linux.go", nil, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"OpenWorkerSource", "openWorkerFile"} {
+ found := false
+ for _, decl := range f.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Name.Name != name {
+ continue
+ }
+ found = true
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ if id, ok := n.(*ast.Ident); ok && (id.Name == "Openat2" || id.Name == "instancefs" || id.Name == "OpenSource") {
+ t.Errorf("%s references %s; the worker sandbox blocks openat2", name, id.Name)
+ }
+ return true
+ })
+ }
+ if !found {
+ t.Fatalf("worker open function %s missing", name)
+ }
+ }
+}
diff --git a/internal/democlaim/worker.go b/internal/democlaim/worker.go
index 66d63709b..186e96415 100644
--- a/internal/democlaim/worker.go
+++ b/internal/democlaim/worker.go
@@ -38,7 +38,7 @@ func RunSnapshotWorkerIn(ctx context.Context, dir string) (err error) {
_ = os.Remove(filepath.Join(dir, "result.json"))
}
}()
- source, err := OpenSource(dir, "snapshot.db")
+ source, err := OpenWorkerSource(dir, "snapshot.db")
if err != nil {
return err
}
diff --git a/internal/edge/demo_moved.go b/internal/edge/demo_moved.go
index dcdd2aa2d..a2197f026 100644
--- a/internal/edge/demo_moved.go
+++ b/internal/edge/demo_moved.go
@@ -14,7 +14,7 @@ var movedPage = template.Must(template.New("moved").Parse(`<!doctype html><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)
+ return e != nil && len(e.staticPub) == ed25519.PublicKeySize && demo.ValidDomain(e.demo.Domain)
}
func (e *Edge) loadDemoMoved() {
@@ -28,7 +28,7 @@ func (e *Edge) loadDemoMoved() {
}
next := make(map[string]democlaim.Moved, len(rows))
for _, r := range rows {
- if !democlaim.MovedDomains(r, e.demo.Domain, e.appsDomain) {
+ if !democlaim.MovedEdgeDomains(r, e.demo.Domain) {
return
}
next[r.Host] = r
diff --git a/internal/edge/demo_moved_test.go b/internal/edge/demo_moved_test.go
index ffa2f7a02..7faf62f72 100644
--- a/internal/edge/demo_moved_test.go
+++ b/internal/edge/demo_moved_test.go
@@ -3,6 +3,8 @@ package edge
import (
"bytes"
"crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
"net/http"
"net/http/httptest"
"strings"
@@ -16,7 +18,7 @@ import (
func movedEdgeFixture(t *testing.T, expiry int64) (*Edge, *registry.Registry) {
t.Helper()
t.Setenv("CARLOS_DEMO_DOMAIN", "demos.example.com")
- t.Setenv("PLATFORM_APPS_DOMAIN", "apps.example.com")
+ t.Setenv("PLATFORM_APPS_DOMAIN", "")
reg := openReg(t)
key := ed25519.NewKeyFromSeed(make([]byte, 32))
wire, err := democlaim.SignMoved(key, []democlaim.Moved{{DemoID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "shop.demos.example.com", TargetHost: "shop.bab.apps.example.com", ExpiresAt: expiry}})
@@ -163,7 +165,7 @@ func TestDemoMovedRevalidatesRegistry(t *testing.T) {
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"} {
+ for _, missing := range []string{"none", "key", "short-key", "demo-domain", "invalid-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"
@@ -174,10 +176,12 @@ func TestDemoMovedCapabilityConfiguration(t *testing.T) {
e.staticPub = []byte{1}
case "demo-domain":
e.demo.Domain = ""
+ case "invalid-demo-domain":
+ e.demo.Domain = "bad_domain.example.com"
case "apps-domain":
e.appsDomain = ""
}
- if got := e.DemoMovedReady(); got != (missing == "none") {
+ if got := e.DemoMovedReady(); got != (missing == "none" || missing == "apps-domain") {
t.Fatalf("configured=%v with missing %s", got, missing)
}
})
@@ -187,3 +191,72 @@ func TestDemoMovedCapabilityConfiguration(t *testing.T) {
t.Fatal("absent edge advertised capability")
}
}
+
+func TestDemoMovedSignedDomainsWithoutAppsDomain(t *testing.T) {
+ for _, tc := range []struct {
+ name, target, signature string
+ want bool
+ }{
+ {"valid", "shop.bab.apps.example.com", "valid", true},
+ {"demo target", "other.demos.example.com", "valid", false},
+ {"demo apex", "demos.example.com", "valid", false},
+ {"two labels", "shop.example", "valid", false},
+ {"port", "shop.bab.apps.example.com:443", "valid", false},
+ {"path", "shop.bab.apps.example.com/path", "valid", false},
+ {"scheme", "https://shop.bab.apps.example.com", "valid", false},
+ {"uppercase", "SHOP.bab.apps.example.com", "valid", false},
+ {"unsigned", "shop.bab.apps.example.com", "unsigned", false},
+ {"wrong key", "shop.bab.apps.example.com", "wrong", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("CARLOS_DEMO_DOMAIN", "demos.example.com")
+ t.Setenv("PLATFORM_APPS_DOMAIN", "")
+ key := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
+ row := democlaim.Moved{DemoID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "shop.demos.example.com", TargetHost: tc.target, ExpiresAt: time.Now().Add(time.Hour).Unix()}
+ // Sign the raw payload to exercise receiver validation even when the
+ // normal signer would refuse a malformed target.
+ payload, err := json.Marshal([]democlaim.Moved{row})
+ if err != nil {
+ t.Fatal(err)
+ }
+ encoded := base64.StdEncoding.EncodeToString(payload)
+ signer := key
+ if tc.signature == "wrong" {
+ seed := make([]byte, ed25519.SeedSize)
+ seed[0] = 1
+ signer = ed25519.NewKeyFromSeed(seed)
+ }
+ sig := base64.StdEncoding.EncodeToString(ed25519.Sign(signer, []byte("carlos demo moved v1\n"+encoded)))
+ if tc.signature == "unsigned" {
+ sig = ""
+ }
+ wire, err := json.Marshal(map[string]string{"payload": encoded, "sig": sig})
+ if err != nil {
+ t.Fatal(err)
+ }
+ reg := openReg(t)
+ if err = reg.CompareDemoMoved(nil, wire); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.staticPub = key.Public().(ed25519.PublicKey)
+ if e.appsDomain != "" || !e.DemoMovedReady() {
+ t.Fatal("moved reader requires apps-domain configuration")
+ }
+ if err = e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ if got := e.demoMovedPage(w, httptest.NewRequest("GET", "https://"+row.Host, nil), row.Host); got != tc.want {
+ t.Fatalf("served = %v, want %v", got, tc.want)
+ }
+ if tc.want && (w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `href="https://`+tc.target+`"`)) {
+ t.Fatalf("wrong notice: %d %s", w.Code, w.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/host/demo_moved_test.go b/internal/host/demo_moved_test.go
index 12089ed1d..545cc7c01 100644
--- a/internal/host/demo_moved_test.go
+++ b/internal/host/demo_moved_test.go
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"net/http/httptest"
+ "slices"
"testing"
"time"
@@ -99,22 +100,11 @@ func TestDemoMovedRequiresWatch(t *testing.T) {
oldReady := armedDemoMovedReader.Swap(false)
defer armedChangeWatch.Store(oldWatch)
defer armedDemoMovedReader.Store(oldReady)
- env := func(k string) string {
- if k == "CARLOS_DEMO_DOMAIN" {
- return "demo.example.com"
- }
- if k == "CARLOS_CHANGE_INDEX" {
- return "read"
- }
- return ""
- }
+ env := map[string]string{"CARLOS_DEMO_DOMAIN": "demo.example.com", "CARLOS_CHANGE_INDEX": "read"}
+ getenv := func(k string) string { return env[k] }
+ baseCaps := edgesFileCapabilities(getenv)
has := func() bool {
- for _, c := range edgesFileCapabilities(env) {
- if c == democlaim.MovedCapability {
- return true
- }
- }
- return false
+ return slices.Contains(withDemoMovedCapability(baseCaps, getenv), democlaim.MovedCapability)
}
if has() {
t.Fatal("unarmed capability")
@@ -125,18 +115,34 @@ func TestDemoMovedRequiresWatch(t *testing.T) {
}
armedDemoMovedReader.Store(true)
if !has() {
- t.Fatal("armed capability absent")
+ t.Fatal("first pass after arming did not publish capability")
+ }
+ if slices.Contains(baseCaps, democlaim.MovedCapability) || slices.Contains(edgesFileCapabilities(getenv), democlaim.MovedCapability) {
+ t.Fatal("dynamic capability frozen into startup configuration")
}
- for _, c := range edgesFileCapabilities(func(k string) string {
- if k == "CARLOS_DEMO_DOMAIN" {
- return ""
+ for _, domain := range []string{"", "bad_domain.example.com", "DEMO.example.com", "demo.example.com:443", "demo.example.com/path"} {
+ env["CARLOS_DEMO_DOMAIN"] = domain
+ if has() {
+ t.Fatalf("invalid demo domain %q advertised capability", domain)
}
- return env(k)
- }) {
- if c == democlaim.MovedCapability {
- t.Fatal("unconfigured demo domain advertised moved capability")
+ }
+ env["CARLOS_DEMO_DOMAIN"] = "demo.example.com"
+ for _, mode := range []string{"", "0", "write"} {
+ env["CARLOS_CHANGE_INDEX"] = mode
+ if has() {
+ t.Fatalf("change index mode %q advertised capability", mode)
}
}
+ env["CARLOS_CHANGE_INDEX"] = "read"
+ armedChangeWatch.Store(nil)
+ if has() {
+ t.Fatal("reader without watch advertised capability")
+ }
+ armedChangeWatch.Store(release.NewChangeWatch(cs))
+ armedDemoMovedReader.Store(false)
+ if has() {
+ t.Fatal("stopped reader retained capability")
+ }
}
func TestDemoMovedDeliveryStream(t *testing.T) {
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go
index d464289e4..0bb439c3b 100644
--- a/internal/host/edgesfile.go
+++ b/internal/host/edgesfile.go
@@ -198,7 +198,7 @@ const capLifetimes1 = "lifetimes-1"
// edgesFileCapabilities publishes lifetimes-1 always, and region-ha-1 only
// when CARLOS_REGION_HA is set to something other than "" or "0".
-// offline-move-1 is added per pass by withOfflineCapability.
+// Worker capabilities are added per pass after their readers arm.
func edgesFileCapabilities(getenv func(string) string) []string {
caps := []string{capLifetimes1}
if regionHAEnabled(getenv) {
@@ -208,8 +208,14 @@ func edgesFileCapabilities(getenv func(string) string) []string {
if getenv("CARLOS_DEMO_CLAIM") == "1" {
caps = append(caps, seeds.DemoClaimCapability)
}
+ return caps
+}
+
+// withDemoMovedCapability observes readers that may arm after the edges loop starts.
+// caps is not modified.
+func withDemoMovedCapability(caps []string, getenv func(string) string) []string {
if demo.ValidDomain(getenv("CARLOS_DEMO_DOMAIN")) && changeIndexArmed(getenv) && armedChangeWatch.Load() != nil && armedDemoMovedReader.Load() {
- caps = append(caps, democlaim.MovedCapability)
+ return append(slices.Clone(caps), democlaim.MovedCapability)
}
return caps
}
@@ -1220,7 +1226,8 @@ func edgesFileLoop(reg *registry.Registry, lifetimes bool, assets *assetPolicy)
}
// The total is read once at arm; the disk half is not needed.
ident.BoxMemTotalMiB, _ = capacityMiB(readMemBytes, func() (uint64, uint64, error) { return 0, 0, errors.ErrUnsupported })
- // The flag-derived capabilities; offline-move-1 joins them on each pass
+ // The flag-derived capabilities; demo-moved-v1 joins them after its
+ // watch and reader arm. offline-move-1 joins them on each pass
// once the moves worker is armed and capable, and db-read-1 joins them
// on each pass while the armed db-reads loop's last readiness probe
// passed (db region forward spec §7.1). The db-reads agent's draining
@@ -1289,7 +1296,7 @@ func edgesFileLoop(reg *registry.Registry, lifetimes bool, assets *assetPolicy)
if state.timed() {
eip = readPublicIP()
}
- ident.Capabilities = withDBReadCapability(withOfflineCapability(baseCaps, armedOfflineCapable()), dbReadsCapable())
+ ident.Capabilities = withDemoMovedCapability(withDBReadCapability(withOfflineCapability(baseCaps, armedOfflineCapable()), dbReadsCapable()), os.Getenv)
dbReadsDraining.Store(ident.Draining)
ident.Headroom = headroomFor(headroomCapabilities(ident.Capabilities), dataDir, reg)
ident = withMovesFields(ident, dataDir, optDir)
diff --git a/internal/instancectl/demo_snapshot_disk.go b/internal/instancectl/demo_snapshot_disk.go
index 58283afdf..8f9f4e529 100644
--- a/internal/instancectl/demo_snapshot_disk.go
+++ b/internal/instancectl/demo_snapshot_disk.go
@@ -130,9 +130,9 @@ func (p *demoSnapshotSupervisor) checkUnit(ctx context.Context, id string) error
"MemoryDenyWriteExecute": "yes", "NetworkNamespacePath": "", "JoinsNamespaceOf": "", "IPAddressAllow": "",
"ProtectKernelTunables": "yes", "ProtectKernelModules": "yes", "ProtectKernelLogs": "yes", "ProtectClock": "yes", "ProtectHostname": "yes",
"RemoveIPC": "yes", "LockPersonality": "yes", "RestrictRealtime": "yes", "Slice": "system.slice",
- "StandardInput": "null", "StandardOutput": "null", "StandardError": "null", "PassEnvironment": "", "EnvironmentFiles": "",
+ "StandardInput": "null", "StandardOutput": "null", "StandardError": "null", "PassEnvironment": "",
}
- keys := []string{"BindPaths", "BindReadOnlyPaths", "TemporaryFileSystem", "Environment", "ExecStart", "IPAddressDeny", "RootDirectory", "RootImage", "ReadWritePaths"}
+ keys := []string{"BindPaths", "BindReadOnlyPaths", "TemporaryFileSystem", "Environment", "EnvironmentFiles", "ExecStart", "IPAddressDeny", "RootDirectory", "RootImage", "ReadWritePaths"}
for k := range want {
keys = append(keys, k)
}
@@ -152,7 +152,7 @@ func (p *demoSnapshotSupervisor) checkUnit(ctx context.Context, id string) error
if !binds(actual["BindPaths"], filepath.Join(p.root, id, "work")+":/work") || !binds(actual["BindReadOnlyPaths"], "/opt/carlos/carlos:/snapshot-worker") {
return democlaim.ErrSnapshot
}
- if actual["RootDirectory"] != "" || actual["RootImage"] != "" || actual["ReadWritePaths"] != "" {
+ if actual["RootDirectory"] != "" || actual["RootImage"] != "" || actual["ReadWritePaths"] != "" || actual["EnvironmentFiles"] != "" {
return democlaim.ErrSnapshot
}
if strings.Join(strings.Fields(actual["Environment"]), " ") != "HOME=/work TMPDIR=/work GOMEMLIMIT=192MiB" {
diff --git a/internal/instancectl/demo_snapshot_kernel_linux_test.go b/internal/instancectl/demo_snapshot_kernel_linux_test.go
index 1fc2c7e33..811e89fc3 100644
--- a/internal/instancectl/demo_snapshot_kernel_linux_test.go
+++ b/internal/instancectl/demo_snapshot_kernel_linux_test.go
@@ -4,6 +4,7 @@ package instancectl
import (
"context"
+ "database/sql"
"encoding/json"
"errors"
"fmt"
@@ -30,6 +31,57 @@ type snapshotWitnessInput struct {
Socket string
}
+func TestDemoClaimSnapshotRealWorker(t *testing.T) {
+ if os.Getenv("CARLOS_SNAPSHOT_WITNESS_HELPER") != "1" {
+ t.Skip("private snapshot witness helper")
+ }
+ if err := democlaim.RunSnapshotWorker(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func prepareSnapshotWorkerWAL(t *testing.T, work string) {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "source.db")
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ db.SetMaxOpenConns(1)
+ for _, query := range []string{"PRAGMA journal_mode=WAL", "PRAGMA wal_autocheckpoint=0", "CREATE TABLE items(value TEXT)", "PRAGMA wal_checkpoint(TRUNCATE)", "INSERT INTO items VALUES ('committed in WAL')"} {
+ if _, err = db.ExecContext(t.Context(), query); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Copy before closing SQLite: its last connection checkpoints the source WAL.
+ for _, suffix := range []string{"", "-wal"} {
+ raw, err := os.ReadFile(path + suffix)
+ if err != nil || len(raw) == 0 {
+ t.Fatal("missing fixture bytes", suffix, err)
+ }
+ f, err := os.OpenFile(filepath.Join(work, "snapshot.db"+suffix), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, writeErr := f.Write(raw)
+ err = errors.Join(writeErr, f.Chmod(0666), f.Sync(), f.Close())
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Immutable mode ignores the WAL, proving that the copied DB lacks the row.
+ base, err := sql.Open("sqlite", "file:"+filepath.Join(work, "snapshot.db")+"?immutable=1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer base.Close()
+ var count int
+ if err = base.QueryRowContext(t.Context(), "SELECT count(*) FROM items").Scan(&count); err != nil || count != 0 {
+ t.Fatal("fixture row is not WAL-only", count, err)
+ }
+}
+
// This hostile replacement for SQLite uses the already-built test binary.
// Only the gated witness installs it, under the shipped unit's restrictions.
func TestDemoClaimSnapshotHostileHelper(t *testing.T) {
@@ -193,7 +245,7 @@ func TestDemoClaimSnapshotRuntimeDevWitness(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- for _, mode := range []string{"isolation", "memory", "duration"} {
+ for _, mode := range []string{"realWorker", "isolation", "memory", "duration"} {
t.Run(mode, func(t *testing.T) {
id, e := demobuild.NewJobID()
if e != nil {
@@ -215,6 +267,11 @@ func TestDemoClaimSnapshotRuntimeDevWitness(t *testing.T) {
if e = p.prepareDisk(ctx, id); e != nil {
t.Fatal(e)
}
+ helper := "TestDemoClaimSnapshotHostileHelper"
+ if mode == "realWorker" {
+ helper = "TestDemoClaimSnapshotRealWorker"
+ prepareSnapshotWorkerWAL(t, filepath.Join(dir, "work"))
+ }
input := snapshotWitnessInput{Mode: mode}
for _, base := range []string{"/data", "/etc/carlos", "/var/lib"} {
path := filepath.Join(base, "snapshot-witness-"+id)
@@ -249,7 +306,8 @@ func TestDemoClaimSnapshotRuntimeDevWitness(t *testing.T) {
os.Remove(drop)
ctl(context.Background(), "daemon-reload")
}()
- text := "[Service]\nExecStart=\nExecStart=/snapshot-worker -test.run=^TestDemoClaimSnapshotHostileHelper$\nBindReadOnlyPaths=\nBindReadOnlyPaths=" + filepath.Join(fixture, "worker") + ":/snapshot-worker\nEnvironment=CARLOS_SNAPSHOT_WITNESS_HELPER=1\n"
+ // An empty BindReadOnlyPaths= clears every bind mount, BindPaths too.
+ text := "[Service]\nExecStart=\nExecStart=/snapshot-worker -test.run=^" + helper + "$\nBindReadOnlyPaths=\nBindPaths=" + filepath.Join(dir, "work") + ":/work\nBindReadOnlyPaths=" + filepath.Join(fixture, "worker") + ":/snapshot-worker\nEnvironment=CARLOS_SNAPSHOT_WITNESS_HELPER=1\n"
if e = os.WriteFile(filepath.Join(drop, "90-witness.conf"), []byte(text), 0644); e != nil {
t.Fatal(e)
}
@@ -263,6 +321,43 @@ func TestDemoClaimSnapshotRuntimeDevWitness(t *testing.T) {
oldAssert := p.assertUnit
p.assertUnit = func(context.Context, string) error { return nil }
defer func() { p.assertUnit = oldAssert }()
+ if mode == "realWorker" {
+ if e = p.run(ctx, id); e != nil {
+ t.Fatal("real worker failed", e)
+ }
+ // Match exportDemoSnapshot: reap before trusting the result files.
+ if e = p.stop(id); e != nil {
+ t.Fatal("real worker did not stop", e)
+ }
+ source, meta, e := p.result(ctx, id)
+ if e != nil {
+ t.Fatal("real worker result rejected", e)
+ }
+ if e = source.Close(); e != nil {
+ t.Fatal(e)
+ }
+ if meta.Bytes <= 0 || meta.SHA256 == "" {
+ t.Fatal("empty snapshot metadata", meta)
+ }
+ // Read the DB alone as root; the worker must have checkpointed the WAL.
+ db, e := sql.Open("sqlite", "file:"+filepath.Join(dir, "work/snapshot.db")+"?immutable=1")
+ if e != nil {
+ t.Fatal(e)
+ }
+ var value string
+ e = db.QueryRowContext(ctx, "SELECT value FROM items").Scan(&value)
+ e = errors.Join(e, db.Close())
+ if e != nil || value != "committed in WAL" {
+ t.Fatal("committed WAL row missing", value, e)
+ }
+ if e = p.cleanup(id); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = os.Stat(dir); !os.IsNotExist(e) {
+ t.Fatal("scratch survived", e)
+ }
+ return
+ }
runCtx, stop := context.WithTimeout(ctx, democlaim.SnapshotWindow)
defer stop()
watcherDone := make(chan struct{})
diff --git a/internal/instancectl/demo_snapshot_unit_test.go b/internal/instancectl/demo_snapshot_unit_test.go
index 96b7f98f6..b1d85c020 100644
--- a/internal/instancectl/demo_snapshot_unit_test.go
+++ b/internal/instancectl/demo_snapshot_unit_test.go
@@ -2,11 +2,62 @@ package instancectl
import (
"context"
+ "errors"
+ "os"
"path/filepath"
+ "slices"
"strings"
"testing"
+
+ "github.com/carlosframework/platform/internal/democlaim"
)
+func TestDemoSnapshotCheckUnitSystemd257(t *testing.T) {
+ fixture, err := os.ReadFile("testdata/systemd257-snapshot-unit.txt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ properties := string(fixture)
+ id := strings.Repeat("A", 43)
+ for _, tc := range []struct {
+ name string
+ raw string
+ wantErr bool
+ }{
+ {name: "omittedEnvironmentFiles", raw: properties},
+ {name: "emptyEnvironmentFiles", raw: properties + "EnvironmentFiles=\n"},
+ {name: "environmentFiles", raw: properties + "EnvironmentFiles=/work/env (ignore_errors=no)\n", wantErr: true},
+ {name: "memoryMax", raw: strings.Replace(properties, "MemoryMax=268435456\n", "MemoryMax=infinity\n", 1), wantErr: true},
+ {name: "execStartPath", raw: strings.Replace(properties, "path=/snapshot-worker ;", "path=/work/worker ;", 1), wantErr: true},
+ {name: "bindPaths", raw: strings.Replace(properties, "BindPaths="+filepath.Join(demoSnapshotRoot, id, "work"), "BindPaths=/work/other", 1), wantErr: true},
+ {name: "missingNonEmptyProperty", raw: strings.Replace(properties, "PrivatePIDs=yes\n", "", 1), wantErr: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if tc.wantErr && tc.raw == properties {
+ t.Fatal("fault did not change the fixture")
+ }
+ s := &Server{Systemctl: func(_ context.Context, args ...string) (string, error) {
+ if len(args) != 4 || args[0] != "show" || args[1] != snapshotUnit(id) || args[2] != "-p" {
+ t.Fatalf("unexpected systemctl arguments: %q", args)
+ }
+ if !slices.Contains(strings.Split(args[3], ","), "EnvironmentFiles") {
+ t.Fatal("EnvironmentFiles must still be requested")
+ }
+ return tc.raw, nil
+ }}
+ p := &demoSnapshotSupervisor{s: s, root: demoSnapshotRoot}
+ err := p.checkUnit(t.Context(), id)
+ if tc.wantErr {
+ if !errors.Is(err, democlaim.ErrSnapshot) {
+ t.Fatalf("checkUnit = %v, want ErrSnapshot", err)
+ }
+ } else if err != nil {
+ t.Fatalf("checkUnit = %v, want nil", err)
+ }
+ })
+ }
+}
+
func TestDemoClaimSnapshotEffectiveUnit(t *testing.T) {
const properties = `Type=exec
RemainAfterExit=yes
diff --git a/internal/instancectl/testdata/systemd257-snapshot-unit.txt b/internal/instancectl/testdata/systemd257-snapshot-unit.txt
new file mode 100644
index 000000000..153c1cbb1
--- /dev/null
+++ b/internal/instancectl/testdata/systemd257-snapshot-unit.txt
@@ -0,0 +1,57 @@
+Type=exec
+Restart=no
+TimeoutStopUSec=5s
+RuntimeMaxUSec=2min
+RemainAfterExit=yes
+OOMPolicy=kill
+ExecStart={ path=/snapshot-worker ; argv[]=/snapshot-worker __demo-snapshot ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }
+Slice=system.slice
+CPUQuotaPerSecUSec=500ms
+MemoryMax=268435456
+MemorySwapMax=0
+TasksMax=32
+IPAddressAllow=
+IPAddressDeny=::/0 0.0.0.0/0
+Environment=HOME=/work TMPDIR=/work GOMEMLIMIT=192MiB
+PassEnvironment=
+LimitFSIZE=268435456
+LimitFSIZESoft=268435456
+WorkingDirectory=/work
+RootDirectory=
+RootImage=
+StandardInput=null
+StandardOutput=null
+StandardError=null
+CapabilityBoundingSet=
+AmbientCapabilities=
+DynamicUser=yes
+RemoveIPC=yes
+ReadWritePaths=
+PrivateDevices=yes
+ProtectClock=yes
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectKernelLogs=yes
+ProtectControlGroups=yes
+PrivateNetwork=yes
+PrivateIPC=yes
+PrivatePIDs=yes
+ProtectHome=yes
+ProtectSystem=strict
+NoNewPrivileges=yes
+LockPersonality=yes
+RestrictAddressFamilies=AF_UNIX
+MemoryDenyWriteExecute=yes
+RestrictRealtime=yes
+RestrictNamespaces=yes
+BindPaths=/var/lib/carlos-demo-snapshots/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/work:/work:rbind
+BindReadOnlyPaths=/opt/carlos/carlos:/snapshot-worker:rbind
+TemporaryFileSystem=/data:ro /run:ro /var:ro /opt:ro /etc:ro /tmp:ro /dev/shm:ro /dev/mqueue:ro /dev/pts:ro
+ProtectProc=invisible
+ProcSubset=pid
+ProtectHostname=yes
+NetworkNamespacePath=
+KillMode=control-group
+SendSIGKILL=yes
+JoinsNamespaceOf=
+LoadState=loaded
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 4f7275289..f3b8315b8 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -107,4 +107,6 @@ plan14-root-reads-restart-new-box-gap.tsv 18e4df5f599a48a881526fc2f85a9b591e3ea8
plan14-root-reads-agent-start-demo-3.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939
plan14-root-reads-lease-renew-after-pause.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939
plan14-root-reads-demo-api-claim-paths.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939
-plan14-root-reads-region-ha-g2-fixes.tsv f4c2ef292f645dccbfa9b2b570074d1033b3be9fc2b4dc76e2f14aec1f8b94b7
+plan14-root-reads-demo-moved-capability.tsv ebeaa693941f5592cd7bc3458effc2a333a8d12ba4f192a93d0aa32589048939
+plan14-root-reads-demo-snapshot-unit-check.tsv 1e83ce23d7d1306e3963f802fecf8c914a2624726255e3bc30382104e568adde
+plan14-root-reads-region-ha-g2-fixes.tsv 3c1d54d297da31d147cdb4e1ad4627f759c8cb8eae2db53cc92218db35e59c7b
diff --git a/internal/provision/testdata/plan14-root-reads-demo-moved-capability.tsv b/internal/provision/testdata/plan14-root-reads-demo-moved-capability.tsv
new file mode 100644
index 000000000..fef8f5eb8
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-demo-moved-capability.tsv
@@ -0,0 +1,5 @@
+# Census overlay demo-moved-capability, written by census-propose (#369). census-ruling-demo-moved-capability, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-demo-moved-capability.md.
+# 0 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/democlaim 593978caf6561c684ecb94b80245973b37865589d8616aff4fb9f00686d46fd6
+@coverage internal/edge 4d7c05e78166ea2cfce4c096e4736def2a47e59cf652134140826d8c7ccfebcd
+@coverage internal/host 65233f7f6a757ada19b69aab6e4ca02b9513c11a4dede6dfd8374a17e41fa622
diff --git a/internal/provision/testdata/plan14-root-reads-demo-snapshot-unit-check.tsv b/internal/provision/testdata/plan14-root-reads-demo-snapshot-unit-check.tsv
new file mode 100644
index 000000000..921c08735
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-demo-snapshot-unit-check.tsv
@@ -0,0 +1,17 @@
+# Census overlay demo-snapshot-unit-check, written by census-propose (#369). census-ruling-demo-snapshot-unit-check, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-demo-snapshot-unit-check.md.
+# 2 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 3 new dispositions: 0 reads re-frozen at their disposition with the claim, 3 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy c3ea54a8e526ae95620099433ac5c537d66e8d4eb04f98af9cf267042725c5ff internal/democlaim/worker.go RunSnapshotWorkerIn legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Open only fixed private helper files and write bounded snapshot metadata; caller-provided live source paths never reach SQLite as root. Census read-site delta: +file:OpenFile.;rev3=census-ruling-demo-snapshot-unit-check;basis=Select OpenWorkerSource for fixed snapshot.db and optional snapshot.db-wal in private /work. Preserve root refusal, result-name reservation, timeout, VerifyUnchanged, checkpoint, integrity check, hashing and failed-result cleanup. No new path input or read is added here. file:OpenFile@415 a8c4558d93231e981f238d55569fd6246418b4046bef10d13afc4628932871ee
+@legacy a9f4a77dc7d8520df2ca3bdad419a9036584fb6d321eb698be683b1a583d882d internal/instancectl/demo_snapshot_disk.go demoSnapshotSupervisor.checkUnit legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Inspect the effective fixed systemd snapshot unit and require its declared isolation, resource and execution settings. Census read-site delta: +data-literal.;rev3=census-ruling-demo-snapshot-unit-check;basis=Accept an omitted EnvironmentFiles property as empty, as emitted by systemd 257; continue requesting it and reject every non-empty value. All other property checks remain unchanged. No read added; the existing systemctl query requests the same properties. data-literal@2502 45a6caa9bbf6c9c099a6510bc3b24f86fd991c327a088c921a8d93ad845e965e
+@legacy 26488921960addf575f00f610d4fb8cfbdc42d56738d9460f48b2f4c991deeb6 internal/democlaim/source_linux.go OpenSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-snapshot-unit-check;basis=Retain the existing instancefs directory open and openat2 flags for root and agent callers; move the file syscall from Source.open into this constructor's opener. No fallback is added. Shared validation still rejects unsafe names, nonregular files, multiple links and oversized DB plus WAL. file:Openat2@219 2b8aba2d2ff9a2052320e09c076ae722d7344b1bbddfd552ac3d35e96280ab7d
+@legacy f23cb704cd544f04910b4922ecebb9919eadfda64e27cb0e2718a99164228d3f internal/democlaim/source_linux.go OpenWorkerSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-snapshot-unit-check;basis=Open only the worker's private directory with open O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC, then use the worker file opener and shared Source checks. The private command supplies /work; no root or agent caller switches to this constructor. New direct directory read replaces the worker's blocked openat2 path. file:Open@139 ef3b5ffd251d71ba3a3aa4ad1a4d0c771124bd4df39cbec96f03bbc5d4330c2d
+@legacy 3db7d78561424d3239eac16f31df2d7be45be4c0fa9a2193ce7b579c4dcb9758 internal/democlaim/source_linux.go openWorkerFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-snapshot-unit-check;basis=Open a single component relative to the held private worker directory with openat O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOFOLLOW. Refuse empty, dot, dot-dot, slash, backslash and NUL names before the syscall. New direct file read is used only by OpenWorkerSource, including VerifyUnchanged. file:Openat@180 584d2fddd1fa75eb35a41538f6121ca6bfaf849b0777736bcc04b5494d192cf6
+@legacy 3511d07846656f365bf46f07998e6ad6b3d513fbcd18c0ccb7d61e1a80efc06b internal/democlaim/source_linux.go Source.open legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Open DB and WAL beneath the retained source directory with openat2 no-follow/beneath constraints and enforce regular-file bounds. Census read-site delta: +file:Fstat, +file:Openat2.;rev3=census-ruling-demo-snapshot-unit-check;basis=Route the file open through the constructor-selected opener; retain identical Fstat, regular-file, nlink==1 and nonnegative-size checks. Root and agent still select openat2; the private worker selects openat. VerifyUnchanged uses this same seam with its existing inode, timestamps, size and link checks. file:Fstat@186 63cb063611680dbced88283992e996102313e6a9fb138c29e9092946781e86ec
+internal/democlaim/worker.go RunSnapshotWorkerIn legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Open only fixed private helper files and write bounded snapshot metadata; caller-provided live source paths never reach SQLite as root. Census read-site delta: +file:OpenFile.;rev3=census-ruling-demo-snapshot-unit-check;basis=Select OpenWorkerSource for fixed snapshot.db and optional snapshot.db-wal in private /work. Preserve root refusal, result-name reservation, timeout, VerifyUnchanged, checkpoint, integrity check, hashing and failed-result cleanup. No new path input or read is added here. file:OpenFile@415 a8c4558d93231e981f238d55569fd6246418b4046bef10d13afc4628932871ee
+internal/instancectl/demo_snapshot_disk.go demoSnapshotSupervisor.checkUnit legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Inspect the effective fixed systemd snapshot unit and require its declared isolation, resource and execution settings. Census read-site delta: +data-literal.;rev3=census-ruling-demo-snapshot-unit-check;basis=Accept an omitted EnvironmentFiles property as empty, as emitted by systemd 257; continue requesting it and reject every non-empty value. All other property checks remain unchanged. No read added; the existing systemctl query requests the same properties. data-literal@2502 45a6caa9bbf6c9c099a6510bc3b24f86fd991c327a088c921a8d93ad845e965e
+internal/democlaim/source_linux.go OpenSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-snapshot-unit-check;basis=Retain the existing instancefs directory open and openat2 flags for root and agent callers; move the file syscall from Source.open into this constructor's opener. No fallback is added. Shared validation still rejects unsafe names, nonregular files, multiple links and oversized DB plus WAL. file:Openat2@219 2b8aba2d2ff9a2052320e09c076ae722d7344b1bbddfd552ac3d35e96280ab7d
+internal/democlaim/source_linux.go OpenWorkerSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-snapshot-unit-check;basis=Open only the worker's private directory with open O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC, then use the worker file opener and shared Source checks. The private command supplies /work; no root or agent caller switches to this constructor. New direct directory read replaces the worker's blocked openat2 path. file:Open@139 ef3b5ffd251d71ba3a3aa4ad1a4d0c771124bd4df39cbec96f03bbc5d4330c2d
+internal/democlaim/source_linux.go openWorkerFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-demo-snapshot-unit-check;basis=Open a single component relative to the held private worker directory with openat O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOFOLLOW. Refuse empty, dot, dot-dot, slash, backslash and NUL names before the syscall. New direct file read is used only by OpenWorkerSource, including VerifyUnchanged. file:Openat@180 584d2fddd1fa75eb35a41538f6121ca6bfaf849b0777736bcc04b5494d192cf6
+internal/democlaim/source_linux.go Source.open legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Open DB and WAL beneath the retained source directory with openat2 no-follow/beneath constraints and enforce regular-file bounds. Census read-site delta: +file:Fstat, +file:Openat2.;rev3=census-ruling-demo-snapshot-unit-check;basis=Route the file open through the constructor-selected opener; retain identical Fstat, regular-file, nlink==1 and nonnegative-size checks. Root and agent still select openat2; the private worker selects openat. VerifyUnchanged uses this same seam with its existing inode, timestamps, size and link checks. file:Fstat@186 63cb063611680dbced88283992e996102313e6a9fb138c29e9092946781e86ec
+@coverage internal/democlaim 803d33a415e0f4b765bfd1d8cbc8e2206b2d99d4bd4a0a4a04f6c86ca33c8e63
+@coverage internal/instancectl 0a26ffced872e6261a077002c7fb869ed636a468e7335b57f363adc5115abf38
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-g2-fixes.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-g2-fixes.tsv
index 6a1fce529..c3e3e2fad 100644
--- a/internal/provision/testdata/plan14-root-reads-region-ha-g2-fixes.tsv
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-g2-fixes.tsv
@@ -187,9 +187,9 @@ internal/host/hadepartures.go Controller.step legacy accepted-legacy accepted-le
@coverage infra/modules/region-host/tests 570051ac6edc48d1bf6ddac7ea364952f79b0c869b1cc006190c6650d2dde39d
@coverage internal/activator 0adbc3c8fbeec03f94035c0b80f2dbc2de3a3ac7f76ee2185ca85590a8c7a7fc
@coverage internal/domains 18f910822bf518e3ee917ff51dba552bf7a6668c313eeef3d01610d38cb4bb53
-@coverage internal/edge 62112fbbb8ee10311c409e45f00570b2a56f96d1ef0ffd6056c61cd81243d623
+@coverage internal/edge 36737ec26c04057f0d5011919869df194116c67495c2a2cacdf1c8d30a0d9a77
@coverage internal/hafresh 5a10a9c971ba3a811e4bfdd2f59bd5715c41f991c872593d4ba42d4dfbfe6b21
-@coverage internal/host c90e13ee3f67f655edc20cf2037f687d7e1c35ddbf0272894eaedf8b3058f3cb
+@coverage internal/host 0b15bde00fe7bde264d16d698faa7f652c913c5025913678a166a655a982c650
@coverage internal/lease 4c730668ace9bf2f7ea3fbbffae2bc7113253ce2a089b00f46c0651904dc8450
@coverage internal/provision a8c0f86e654fda131d5f2636125bb5c84aad234ebe94f3382f9e2ed85ba2cbe5
@coverage internal/registry bcbd1fb23f5d3b809d53d11c58f58bbb2cbcf2065d811f4cc8a7a0fa8cb90000