carlos / platform Public

feat: supervise held demo snapshots from root

Complete Task 3 with fixed multipart snapshot transport, root supervision,
preallocated bounded scratch, shared builder exclusion and restart cleanup.
Wire the no-follow agent adapter and require checked root capability before
advertising claims. Preserve source DB/WAL bytes and wait for cleanup on close.

Add fake systemd/control-socket and real SQLite WAL tests, plus opt-in
resource/isolation witnesses. Repair the prior private dispatch's separate
record-write inventory after source review.

Targeted tests, vet and formatting pass. Real systemd/cgroup witnesses were
not run. Root census remains expected red pending the controller's single
overlay and independent review. Nothing is pushed or deployed.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 51022c0b74b11856dbde1a5c55af04c3b3acdd87 parent 13f924f
23 files changed, +2,383 −12
  • internal/demobuild/snapshot_slot.go +30 −0
  • internal/demobuild/snapshot_slot_test.go +37 −0
  • internal/democlaim/worker.go +5 −2
  • internal/democlaim/worker_test.go +2 −2
  • internal/host/agent.go +1 −0
  • internal/host/demo_claim_executor.go +3 −3
  • internal/host/demo_claim_snapshot.go +54 −0
  • internal/host/demo_claim_snapshot_test.go +266 −0
  • internal/host/demo_snapshot_linux_test.go +1 −1
  • internal/host/demo_snapshot_test.go +15 −3
  • internal/host/units/carlos-demo-snapshot@.service +2 −0
  • internal/host/units/carlos-instance-control.service +2 −0
  • internal/instancectl/demo_build.go +5 −0
  • internal/instancectl/demo_snapshot.go +510 −0
  • internal/instancectl/demo_snapshot_client.go +182 −0
  • internal/instancectl/demo_snapshot_disk.go +187 −0
  • internal/instancectl/demo_snapshot_kernel_linux_test.go +324 −0
  • internal/instancectl/demo_snapshot_linux.go +91 −0
  • internal/instancectl/demo_snapshot_other.go +14 −0
  • internal/instancectl/demo_snapshot_test.go +527 −0
  • internal/instancectl/demo_snapshot_unit_test.go +109 −0
  • internal/instancectl/server.go +11 −0
  • internal/provision/agent_start_demo_3_census_test.go +5 −1

CI failed — run details

Intent

Human

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

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

diff --git a/internal/demobuild/snapshot_slot.go b/internal/demobuild/snapshot_slot.go
new file mode 100644
index 000000000..f8f738709
--- /dev/null
+++ b/internal/demobuild/snapshot_slot.go
@@ -0,0 +1,30 @@
+package demobuild
+
+import "context"
+
+// AcquireSnapshot excludes builds and purges for the entire export, including
+// response delivery and cleanup. A failed reap poisons build admission too.
+func (w *Worker) AcquireSnapshot(ctx context.Context) (func(bool), error) {
+ if w == nil || !w.buildPurge.TryLock() {
+ return nil, ErrBuild
+ }
+ if !w.available() || ctx.Err() != nil || w.proof == nil || w.proof(ctx) != nil {
+ w.buildPurge.Unlock()
+ return nil, ErrBuild
+ }
+ select {
+ case w.slots <- struct{}{}:
+ default:
+ w.buildPurge.Unlock()
+ return nil, ErrBuild
+ }
+ return func(clean bool) {
+ if !clean {
+ w.mu.Lock()
+ w.poisoned = true
+ w.mu.Unlock()
+ }
+ <-w.slots
+ w.buildPurge.Unlock()
+ }, nil
+}
diff --git a/internal/demobuild/snapshot_slot_test.go b/internal/demobuild/snapshot_slot_test.go
new file mode 100644
index 000000000..5ba3c39b8
--- /dev/null
+++ b/internal/demobuild/snapshot_slot_test.go
@@ -0,0 +1,37 @@
+package demobuild
+
+import (
+ "context"
+ "testing"
+)
+
+func TestDemoClaimExportBuilderSlot(t *testing.T) {
+ w := &Worker{ready: true, slots: make(chan struct{}, 2), proof: func(context.Context) error { return nil }}
+ w.buildPurge.RLock()
+ if release, e := w.AcquireSnapshot(t.Context()); e == nil {
+ release(true)
+ t.Fatal("export overlapped build")
+ }
+ w.buildPurge.RUnlock()
+ release, e := w.AcquireSnapshot(t.Context())
+ if e != nil {
+ t.Fatal(e)
+ }
+ if w.buildPurge.TryRLock() {
+ w.buildPurge.RUnlock()
+ t.Fatal("build overlapped export")
+ }
+ if r, e := w.AcquireSnapshot(t.Context()); e == nil {
+ r(true)
+ t.Fatal("second export admitted")
+ }
+ release(true)
+ release, e = w.AcquireSnapshot(t.Context())
+ if e != nil {
+ t.Fatal(e)
+ }
+ release(false)
+ if w.available() {
+ t.Fatal("failed snapshot cleanup did not poison builder")
+ }
+}
diff --git a/internal/democlaim/worker.go b/internal/democlaim/worker.go
index f9dfd2c66..66d63709b 100644
--- a/internal/democlaim/worker.go
+++ b/internal/democlaim/worker.go
@@ -11,10 +11,13 @@ import (
// RunSnapshotWorker is the private unit entry point. Neither argv nor the
// environment can choose its files. Root supplies bytes in this unit's /work.
func RunSnapshotWorker(ctx context.Context) error {
- return runSnapshotWorkerIn(ctx, "/work")
+ return RunSnapshotWorkerIn(ctx, "/work")
}
-func runSnapshotWorkerIn(ctx context.Context, dir string) (err error) {
+// RunSnapshotWorkerIn runs the same worker on an already private copy. The
+// private command always supplies /work; in-process tests supply a temp directory.
+// Root is refused here too. No root control handler calls this function.
+func RunSnapshotWorkerIn(ctx context.Context, dir string) (err error) {
if os.Geteuid() == 0 {
return ErrSnapshot
}
diff --git a/internal/democlaim/worker_test.go b/internal/democlaim/worker_test.go
index d656c7c7f..6cfc1d3df 100644
--- a/internal/democlaim/worker_test.go
+++ b/internal/democlaim/worker_test.go
@@ -31,7 +31,7 @@ func receivedCopy(t *testing.T) string {
func TestDemoClaimExportBoundedWorker(t *testing.T) {
t.Run("checkpointCheckedResult", func(t *testing.T) {
work := receivedCopy(t)
- if err := runSnapshotWorkerIn(t.Context(), work); err != nil {
+ if err := RunSnapshotWorkerIn(t.Context(), work); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(filepath.Join(work, "result.json"))
@@ -91,7 +91,7 @@ func TestDemoClaimExportBoundedWorker(t *testing.T) {
if fault == "resultExists" {
beforeDB, beforeWAL = fileHash(t, db), fileHash(t, db+"-wal")
}
- if err := runSnapshotWorkerIn(ctx, work); err == nil {
+ if err := RunSnapshotWorkerIn(ctx, work); err == nil {
t.Fatal("unsafe worker succeeded")
}
if fault == "resultExists" {
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 5ce685cc3..a4a593491 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -1009,6 +1009,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
armPolicyCache()
startDemoWorker(agentCtx, reg, demoData, cfg.Prefix, traffic, stopDemoTraffic, func(w *demoWorker) {
w.claimActivator = svc
+ w.wireDemoClaimSnapshot(instancectl.NewClient(controlsock.Path), dd)
w.trafficGate = &demoGate
w.serving.cancel = func(ids ...demo.TrafficIdentity) {
if e := demoEdge.Load(); e != nil {
diff --git a/internal/host/demo_claim_executor.go b/internal/host/demo_claim_executor.go
index d5e26dfa9..146f2c277 100644
--- a/internal/host/demo_claim_executor.go
+++ b/internal/host/demo_claim_executor.go
@@ -22,7 +22,7 @@ type demoClaimActivator interface {
LiftFenceAs(string, uint64, string) bool
}
-// Part 3c supplies a streamed snapshot from root's isolated worker. Closing
+// Root supplies a streamed snapshot from its isolated worker. Closing
// Body must reap the worker and remove its private scratch, including on error.
type demoClaimSnapshot struct {
Body io.ReadCloser
@@ -31,10 +31,10 @@ type demoClaimSnapshot struct {
}
// Flip only when the root snapshot door, isolation and slot budget are wired.
-const demoClaimSnapshotWired = false
+const demoClaimSnapshotWired = true
func (w *demoWorker) demoClaimCapability() string {
- if demoClaimSnapshotWired && w.claimActivator != nil && w.claimFreeze != nil && w.claimSnapshot != nil {
+ if demoClaimSnapshotWired && w.claimActivator != nil && w.claimFreeze != nil && w.claimSnapshot != nil && w.buildReady().ClaimCapability == democlaim.Capability {
return democlaim.Capability
}
return ""
diff --git a/internal/host/demo_claim_snapshot.go b/internal/host/demo_claim_snapshot.go
new file mode 100644
index 000000000..b2f8f95ae
--- /dev/null
+++ b/internal/host/demo_claim_snapshot.go
@@ -0,0 +1,54 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "io"
+ "path/filepath"
+
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func (w *demoWorker) wireDemoClaimSnapshot(root *instancectl.Client, dataDir string) {
+ if root == nil || !filepath.IsAbs(dataDir) {
+ return
+ }
+ w.claimFreeze = root.FreezeDemo
+ w.claimSnapshot = func(ctx context.Context, work democlaim.Work, rt registry.Route) (demoClaimSnapshot, error) {
+ if ctx.Err() != nil || w.claimActivator == nil || !w.claimActivator.Quiesced(work.Demo.Host) || w.claimActivator.StopUncertain(work.Demo.Host) || !rt.Provisioned || rt.Host != work.Demo.Host || rt.DemoID != work.Demo.ID || rt.DemoHost != work.Demo.Host || rt.DemoLifetime != work.Demo.Lifetime || rt.DemoExpiresAt != work.Demo.ExpiresAt || rt.Account != work.Account || rt.App != work.App || rt.FleetBox != work.Box || rt.Region != "fleet/"+work.Fleet || rt.Status != "moving" || rt.HoldOp != "demo-claim/"+work.ID {
+ return demoClaimSnapshot{}, democlaim.ErrSnapshot
+ }
+ // Demo durability supports the nested layout only. Even a registry DBPath
+ // cannot select another host's files or an agent credential.
+ path := provision.NestedDBPath(dataDir, rt.Host)
+ if rt.DBPath != path {
+ return demoClaimSnapshot{}, democlaim.ErrSnapshot
+ }
+ source, err := democlaim.OpenSource(filepath.Dir(path), filepath.Base(path))
+ if err != nil {
+ return demoClaimSnapshot{}, err
+ }
+ var wal io.Reader
+ if source.WAL != nil {
+ wal = source.WAL
+ }
+ body, err := root.SnapshotDemo(ctx, work.Demo, work.ID, source.DB, source.DBBytes, wal, source.WALBytes)
+ err = errors.Join(err, source.VerifyUnchanged(), source.Close())
+ if err != nil {
+ if body != nil {
+ err = errors.Join(err, body.Close())
+ }
+ return demoClaimSnapshot{}, err
+ }
+ metadata, ok := body.(interface{ SnapshotMetadata() democlaim.Snapshot })
+ if !ok {
+ body.Close()
+ return demoClaimSnapshot{}, democlaim.ErrSnapshot
+ }
+ snapshot := metadata.SnapshotMetadata()
+ return demoClaimSnapshot{Body: body, Bytes: snapshot.Bytes, SHA256: snapshot.SHA256}, nil
+ }
+}
diff --git a/internal/host/demo_claim_snapshot_test.go b/internal/host/demo_claim_snapshot_test.go
new file mode 100644
index 000000000..781d6c810
--- /dev/null
+++ b/internal/host/demo_claim_snapshot_test.go
@@ -0,0 +1,266 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+func TestDemoClaimSnapshotAdapterWAL(t *testing.T) {
+ f := newClaimFixture(t)
+ f.work.Action = "export"
+ dd := t.TempDir()
+ dbPath := provision.NestedDBPath(dd, f.work.Demo.Host)
+ if err := os.MkdirAll(filepath.Dir(dbPath), 0700); err != nil {
+ t.Fatal(err)
+ }
+ db, err := sql.Open("sqlite", dbPath)
+ 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.Exec(query); err != nil {
+ t.Fatal(err)
+ }
+ }
+ hash := func(path string) string {
+ b, e := os.ReadFile(path)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return fmt.Sprintf("%x", sha256.Sum256(b))
+ }
+ beforeDB, beforeWAL := hash(dbPath), hash(dbPath+"-wal")
+ if err = f.w.holdDemoClaim(t.Context(), f.work); err != nil {
+ t.Fatal(err)
+ }
+ rt, err := f.w.claimRoute(f.work)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt.DBPath = dbPath
+ scratch := t.TempDir()
+ calls, closed := 0, 0
+ mutateSource := false
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/demo-snapshot/close" {
+ closed++
+ if err := os.RemoveAll(filepath.Join(scratch, "work")); err != nil {
+ t.Error(err)
+ }
+ w.WriteHeader(204)
+ return
+ }
+ if r.URL.Path != "/demo-snapshot" {
+ t.Error(r.URL.Path)
+ w.WriteHeader(404)
+ return
+ }
+ calls++
+ mr, e := r.MultipartReader()
+ if e != nil {
+ t.Error(e)
+ w.WriteHeader(400)
+ return
+ }
+ part, e := mr.NextPart()
+ if e != nil {
+ t.Error(e)
+ return
+ }
+ var meta struct {
+ Demo any `json:"demo"`
+ OperationID, TransferID string
+ DBBytes, WALBytes int64
+ }
+ if e = json.NewDecoder(part).Decode(&meta); e != nil || part.FormName() != "metadata" || meta.OperationID != f.work.ID {
+ t.Errorf("metadata %v %v", meta, e)
+ return
+ }
+ work := filepath.Join(scratch, "work")
+ os.Mkdir(work, 0700)
+ for _, name := range []string{"db", "wal"} {
+ part, e = mr.NextPart()
+ if e != nil || part.FormName() != name || part.FileName() != "" {
+ t.Error("bad multipart", e)
+ return
+ }
+ base := "snapshot.db"
+ want := meta.DBBytes
+ if name == "wal" {
+ base += "-wal"
+ want = meta.WALBytes
+ }
+ out, e := os.Create(filepath.Join(work, base))
+ if e != nil {
+ t.Error(e)
+ return
+ }
+ n, e := io.Copy(out, part)
+ out.Close()
+ if e != nil || n != want {
+ t.Error("bad byte count", n, want, e)
+ return
+ }
+ }
+ if _, e = mr.NextPart(); e != io.EOF {
+ t.Error("extra part", e)
+ return
+ }
+ if e = democlaim.RunSnapshotWorkerIn(t.Context(), work); e != nil {
+ t.Error(e)
+ w.WriteHeader(422)
+ return
+ }
+ raw, e := os.ReadFile(filepath.Join(work, "result.json"))
+ if e != nil {
+ t.Error(e)
+ return
+ }
+ var result democlaim.Snapshot
+ if e = json.Unmarshal(raw, &result); e != nil {
+ t.Error(e)
+ return
+ }
+ if mutateSource {
+ if e := os.Chtimes(dbPath, time.Now(), time.Now().Add(time.Second)); e != nil {
+ t.Error(e)
+ }
+ }
+ w.Header().Set(democlaim.SnapshotBytesHeader, strconv.FormatInt(result.Bytes, 10))
+ w.Header().Set(democlaim.SnapshotSHA256Header, result.SHA256)
+ out, e := os.Open(filepath.Join(work, "snapshot.db"))
+ if e != nil {
+ t.Error(e)
+ return
+ }
+ defer out.Close()
+ io.Copy(w, out)
+ }))
+ defer server.Close()
+ root := &instancectl.Client{Dial: func(ctx context.Context, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "tcp", server.Listener.Addr().String())
+ }}
+ f.w.wireDemoClaimSnapshot(root, dd)
+ snapshot, err := f.w.claimSnapshot(t.Context(), f.work, *rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ result := filepath.Join(t.TempDir(), "snapshot.db")
+ out, err := os.Create(result)
+ if err != nil {
+ t.Fatal(err)
+ }
+ n, err := io.Copy(out, snapshot.Body)
+ out.Close()
+ if err != nil || n != snapshot.Bytes || hash(result) != snapshot.SHA256 {
+ t.Fatal("snapshot mismatch", err)
+ }
+ if err = snapshot.Body.Close(); err != nil {
+ t.Fatal(err)
+ }
+ resultDB, err := sql.Open("sqlite", "file:"+result+"?mode=ro")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resultDB.Close()
+ var value string
+ if err = resultDB.QueryRow("SELECT value FROM items").Scan(&value); err != nil || value != "committed in WAL" {
+ t.Fatal(value, err)
+ }
+ if hash(dbPath) != beforeDB || hash(dbPath+"-wal") != beforeWAL {
+ t.Fatal("source changed")
+ }
+ if calls != 1 || closed != 1 {
+ t.Fatal("transport or cleanup omitted", calls, closed)
+ }
+ for _, fault := range []string{"unquiesced", "uncertain", "unheld", "wrongPath", "symlink"} {
+ t.Run(fault, func(t *testing.T) {
+ route := *rt
+ switch fault {
+ case "unquiesced":
+ f.act.quiet = false
+ defer func() { f.act.quiet = true }()
+ case "uncertain":
+ f.act.uncertain = true
+ defer func() { f.act.uncertain = false }()
+ case "unheld":
+ route.HoldOp = ""
+ case "wrongPath":
+ route.DBPath = filepath.Join(dd, "credentials")
+ case "symlink":
+ os.Rename(dbPath+"-wal", dbPath+"-saved")
+ os.Symlink(dbPath+"-saved", dbPath+"-wal")
+ defer func() { os.Remove(dbPath + "-wal"); os.Rename(dbPath+"-saved", dbPath+"-wal") }()
+ }
+ if got, e := f.w.claimSnapshot(t.Context(), f.work, route); e == nil {
+ got.Body.Close()
+ t.Fatal("unsafe source reached root")
+ }
+ if calls != 1 {
+ t.Fatal("refusal contacted root")
+ }
+ })
+ }
+ t.Run("sourceChangedDuringTransfer", func(t *testing.T) {
+ mutateSource = true
+ if got, e := f.w.claimSnapshot(t.Context(), f.work, *rt); e == nil {
+ got.Body.Close()
+ t.Fatal("source mutation ignored")
+ }
+ if calls != 2 || closed != 2 {
+ t.Fatal("failed source verification did not close root response", calls, closed)
+ }
+ })
+}
+
+func TestDemoClaimSnapshotProductionCapability(t *testing.T) {
+ f := newClaimFixture(t)
+ f.w.wireDemoClaimSnapshot(&instancectl.Client{}, t.TempDir())
+ f.w.ready = demobuild.WorkerReady{ClaimCapability: democlaim.Capability}
+ if !demoClaimSnapshotWired || f.w.demoHeartbeat(time.Now()).ClaimCapability != democlaim.Capability {
+ t.Fatal("production wiring does not advertise")
+ }
+ for _, piece := range []string{"activator", "freeze", "snapshot", "root"} {
+ t.Run(piece, func(t *testing.T) {
+ oldAct, oldFreeze, oldSnapshot, oldReady := f.w.claimActivator, f.w.claimFreeze, f.w.claimSnapshot, f.w.ready
+ defer func() {
+ f.w.claimActivator, f.w.claimFreeze, f.w.claimSnapshot, f.w.ready = oldAct, oldFreeze, oldSnapshot, oldReady
+ }()
+ switch piece {
+ case "activator":
+ f.w.claimActivator = nil
+ case "freeze":
+ f.w.claimFreeze = nil
+ case "snapshot":
+ f.w.claimSnapshot = nil
+ case "root":
+ f.w.ready.ClaimCapability = ""
+ }
+ if got := f.w.demoHeartbeat(time.Now()).ClaimCapability; strings.TrimSpace(got) != "" {
+ t.Fatal("incomplete wiring advertised", got)
+ }
+ })
+ }
+}
diff --git a/internal/host/demo_snapshot_linux_test.go b/internal/host/demo_snapshot_linux_test.go
index 89db96165..60769e089 100644
--- a/internal/host/demo_snapshot_linux_test.go
+++ b/internal/host/demo_snapshot_linux_test.go
@@ -28,7 +28,7 @@ func TestDemoClaimSnapshotUnitDevWitness(t *testing.T) {
t.Fatal("install this binary's snapshot unit in the designated sandbox", err)
}
properties := map[string]string{
- "DynamicUser": "yes", "MemoryMax": "268435456", "MemorySwapMax": "0", "CPUQuotaPerSecUSec": "500ms", "TasksMax": "32",
+ "Slice": "system.slice", "DynamicUser": "yes", "MemoryMax": "268435456", "MemorySwapMax": "0", "CPUQuotaPerSecUSec": "500ms", "TasksMax": "32",
"RuntimeMaxUSec": "2min", "TimeoutStopUSec": "5s", "KillMode": "control-group", "SendSIGKILL": "yes", "OOMPolicy": "kill",
"LimitFSIZE": "268435456", "LimitFSIZESoft": "268435456", "WorkingDirectory": "/work",
"ProtectSystem": "strict", "ProtectHome": "yes", "PrivateNetwork": "yes", "PrivateDevices": "yes", "PrivateIPC": "yes", "PrivatePIDs": "yes",
diff --git a/internal/host/demo_snapshot_test.go b/internal/host/demo_snapshot_test.go
index 9ce2bbd8c..115927621 100644
--- a/internal/host/demo_snapshot_test.go
+++ b/internal/host/demo_snapshot_test.go
@@ -38,7 +38,7 @@ func TestDemoClaimSnapshotUnitContract(t *testing.T) {
props[key] = v
}
want := map[string]string{
- "Type": "exec", "RemainAfterExit": "yes", "DynamicUser": "yes", "Restart": "no",
+ "Type": "exec", "RemainAfterExit": "yes", "DynamicUser": "yes", "Restart": "no", "Slice": "system.slice",
"ExecStart": "/snapshot-worker __demo-snapshot", "WorkingDirectory": "/work",
"BindPaths": "/var/lib/carlos-demo-snapshots/%i/work:/work",
"BindReadOnlyPaths": "/opt/carlos/carlos:/snapshot-worker",
@@ -72,6 +72,9 @@ func TestDemoClaimSnapshotUnitContract(t *testing.T) {
t.Error(k)
}
}
+ if props["[Unit]/RequiresMountsFor"] != "/var/lib/carlos-demo-snapshots/%i/work" {
+ t.Fatal("snapshot lacks mount ordering")
+ }
for k := range props {
if strings.HasPrefix(k, "[Install]/") {
t.Fatal("snapshot unit enables itself")
@@ -112,6 +115,15 @@ func TestDemoClaimSnapshotBootstrap(t *testing.T) {
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("staged snapshot template differs: %v", err)
}
+ control, err := os.ReadFile(filepath.Join(root, "etc/systemd/system/carlos-instance-control.service"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, directive := range []string{"StateDirectory=carlos-demo-snapshots", "StateDirectoryMode=0700"} {
+ if !strings.Contains(string(control), "\n"+directive+"\n") {
+ t.Fatal("root scratch not installed", directive)
+ }
+ }
}
func TestDemoClaimSnapshotCapabilityStaysOff(t *testing.T) {
@@ -119,7 +131,7 @@ func TestDemoClaimSnapshotCapabilityStaysOff(t *testing.T) {
if f.w.claimActivator == nil || f.w.claimFreeze == nil || f.w.claimSnapshot == nil {
t.Fatal("fixture must provide every callback")
}
- if demoClaimSnapshotWired || f.w.demoHeartbeat(time.Now()).ClaimCapability != "" {
- t.Fatal("snapshot advertised before root reservation and cleanup are wired")
+ if f.w.demoHeartbeat(time.Now()).ClaimCapability != "" {
+ t.Fatal("snapshot advertised without root readiness")
}
}
diff --git a/internal/host/units/carlos-demo-snapshot@.service b/internal/host/units/carlos-demo-snapshot@.service
index 82e9a8d07..a9a63d6ea 100644
--- a/internal/host/units/carlos-demo-snapshot@.service
+++ b/internal/host/units/carlos-demo-snapshot@.service
@@ -2,9 +2,11 @@
Description=DEMO-CLAIM-SNAPSHOT
BindsTo=carlos-instance-control.service
After=carlos-instance-control.service
+RequiresMountsFor=/var/lib/carlos-demo-snapshots/%i/work
[Service]
Type=exec
+Slice=system.slice
RemainAfterExit=yes
DynamicUser=yes
ExecStart=/snapshot-worker __demo-snapshot
diff --git a/internal/host/units/carlos-instance-control.service b/internal/host/units/carlos-instance-control.service
index 59b2d2b55..45a8bdc0d 100644
--- a/internal/host/units/carlos-instance-control.service
+++ b/internal/host/units/carlos-instance-control.service
@@ -33,6 +33,8 @@ ProtectSystem=strict
# /run/systemd/system: the per-generation runtime drop-in (zero-downtime
# deploys, plan 2 D1); nothing else is written there.
ReadWritePaths=/run/carlos-control /run/systemd/system
+StateDirectory=carlos-demo-snapshots
+StateDirectoryMode=0700
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
diff --git a/internal/instancectl/demo_build.go b/internal/instancectl/demo_build.go
index 5d46526f0..739ec3a4c 100644
--- a/internal/instancectl/demo_build.go
+++ b/internal/instancectl/demo_build.go
@@ -11,6 +11,7 @@ import (
"github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
)
type demoBuilder interface {
@@ -97,6 +98,10 @@ func (s *Server) handleDemoBuildReady(w http.ResponseWriter, r *http.Request) {
http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable)
return
}
+ ready.ClaimCapability = ""
+ if _, ok := s.DemoBuilder.(snapshotSlot); ok && s.snapshots != nil && s.snapshots.ready.Load() {
+ ready.ClaimCapability = democlaim.Capability
+ }
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ready)
}
diff --git a/internal/instancectl/demo_snapshot.go b/internal/instancectl/demo_snapshot.go
new file mode 100644
index 000000000..5b243e830
--- /dev/null
+++ b/internal/instancectl/demo_snapshot.go
@@ -0,0 +1,510 @@
+package instancectl
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+const demoSnapshotRoot = "/var/lib/carlos-demo-snapshots"
+
+type snapshotSlot interface {
+ AcquireSnapshot(context.Context) (func(bool), error)
+}
+type snapshotSession struct {
+ op string
+ cancel context.CancelFunc
+ done chan struct{}
+ cleanupErr error
+ created time.Time
+}
+type demoSnapshotSupervisor struct {
+ s *Server
+ root string
+ poll, stopWindow time.Duration
+ prepare func(context.Context, string) error
+ unmount func(context.Context, string) error
+ assertUnit func(context.Context, string) error
+ empty func(string) error
+ ready, busy atomic.Bool
+ mu sync.Mutex
+ sessions map[string]*snapshotSession
+}
+
+func newDemoSnapshotSupervisor(s *Server) *demoSnapshotSupervisor {
+ p := &demoSnapshotSupervisor{s: s, root: demoSnapshotRoot, poll: 100 * time.Millisecond, stopWindow: 10 * time.Second, sessions: map[string]*snapshotSession{}}
+ p.prepare = p.prepareDisk
+ p.unmount = p.unmountDisk
+ p.assertUnit = p.checkUnit
+ p.empty = p.emptyCgroup
+ return p
+}
+func snapshotUnit(id string) string { return "carlos-demo-snapshot@" + id + ".service" }
+
+func (s *Server) snapshotHeld(ctx context.Context, in demoSnapshotRequest) error {
+ if !s.DemoBox || s.HostDemo == nil || s.DemoPurgeGuard == nil || !s.DemoConfig.BoxMode() || !demobuild.ValidJobID(in.OperationID) || !provision.ValidHostShape(in.Demo.Host) || ctx.Err() != nil {
+ return demo.ErrPolicy
+ }
+ name, _, ok := strings.Cut(in.Demo.Host, ".")
+ if !ok || s.DemoConfig.ValidateBinding(in.Demo, s.DemoConfig.Account, demo.AppPrefix+name, in.Demo.Host, in.Demo.Lifetime, s.DemoConfig.Fleet) != nil || time.Now().Unix() >= in.Demo.ExpiresAt {
+ return demo.ErrPolicy
+ }
+ return s.DemoPurgeGuard(ctx, func() error {
+ defer s.lockDemo(in.Demo.Host)()
+ rt, err := s.HostDemo(in.Demo.Host)
+ if err != nil {
+ return err
+ }
+ if rt == nil || !rt.IsDemo() || rt.Host != in.Demo.Host || rt.DemoID != in.Demo.ID || rt.DemoHost != in.Demo.Host || rt.DemoLifetime != in.Demo.Lifetime || rt.DemoExpiresAt != in.Demo.ExpiresAt || rt.Account != s.DemoConfig.Account || rt.App != demo.AppPrefix+name || rt.Status != "moving" || rt.HoldOp != "demo-claim/"+in.OperationID {
+ return demo.ErrPolicy
+ }
+ return nil
+ })
+}
+func snapshotPart(m *multipart.Reader, name string) (*multipart.Part, error) {
+ p, err := m.NextRawPart()
+ if err != nil {
+ return nil, err
+ }
+ kind, params, err := mime.ParseMediaType(p.Header.Get("Content-Disposition"))
+ if err != nil || len(p.Header) != 1 || kind != "form-data" || len(params) != 1 || params["name"] != name {
+ return nil, democlaim.ErrSnapshot
+ }
+ return p, nil
+}
+func (s *Server) handleDemoSnapshot(w http.ResponseWriter, r *http.Request) {
+ defer r.Body.Close()
+ p := s.snapshots
+ if p == nil || !p.ready.Load() {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ deadline := time.Now().Add(democlaim.SnapshotWindow)
+ ctl := http.NewResponseController(w)
+ _ = ctl.SetReadDeadline(deadline)
+ _ = ctl.SetWriteDeadline(deadline)
+ ctx, cancel := context.WithDeadline(r.Context(), deadline)
+ defer cancel()
+ // The socket deadline interrupts stalled net/http reads; cancellation also
+ // interrupts them when a separate close request arrives.
+ stopRead := context.AfterFunc(ctx, func() { _ = ctl.SetReadDeadline(time.Now()); _ = ctl.SetWriteDeadline(time.Now()) })
+ defer stopRead()
+ r.Body = http.MaxBytesReader(w, r.Body, democlaim.MaxSnapshotBytes+16384)
+ kind, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil || kind != "multipart/form-data" || len(params) != 1 || params["boundary"] == "" {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 400)
+ return
+ }
+ m := multipart.NewReader(r.Body, params["boundary"])
+ part, err := snapshotPart(m, "metadata")
+ if err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 400)
+ return
+ }
+ raw, err := io.ReadAll(io.LimitReader(part, 4097))
+ var in demoSnapshotRequest
+ if err != nil || len(raw) > 4096 || demobuild.DecodeMessage(raw, &in) != nil || !demobuild.ValidJobID(in.TransferID) || !demobuild.ValidJobID(in.OperationID) || in.DBBytes <= 0 || in.DBBytes > democlaim.MaxSnapshotBytes || in.WALBytes < 0 || in.WALBytes > democlaim.MaxSnapshotBytes-in.DBBytes {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 400)
+ return
+ }
+ session, err := p.register(in, cancel)
+ if err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ defer close(session.done)
+ if err = s.snapshotHeld(ctx, in); err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ if !p.busy.CompareAndSwap(false, true) {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ defer p.busy.Store(false)
+ slot, ok := s.DemoBuilder.(snapshotSlot)
+ if !ok {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ release, err := slot.AcquireSnapshot(ctx)
+ if err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ defer func() { release(session.cleanupErr == nil) }()
+ if s.Statfs == nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ available, _, err := s.Statfs(p.root)
+ if err != nil || available < uint64(democlaim.MaxScratchBytes) {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 507)
+ return
+ }
+ root, err := instancefs.OpenRootBeneath(p.root, ".")
+ if err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ defer root.Close()
+ if err = root.Mkdir(in.OperationID, 0700); err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ cleaned := false
+ cleanup := func() {
+ if !cleaned {
+ cleaned = true
+ session.cleanupErr = p.cleanup(in.OperationID)
+ }
+ }
+ defer cleanup()
+ if err = p.prepare(ctx, in.OperationID); err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ work := filepath.Join(p.root, in.OperationID, "work")
+ for _, field := range []struct {
+ name, file string
+ bytes int64
+ }{{"db", "snapshot.db", in.DBBytes}, {"wal", "snapshot.db-wal", in.WALBytes}} {
+ part, err := snapshotPart(m, field.name)
+ if err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 400)
+ return
+ }
+ f, err := instancefs.OpenBeneath(work, field.file, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ n, copyErr := io.CopyN(f, part, field.bytes)
+ var extra [1]byte
+ extraN, endErr := part.Read(extra[:])
+ // The enclosing root-only operation directory keeps these writable private
+ // copies inaccessible on the host. The dynamic UID sees only its /work bind.
+ modeErr := f.Chmod(0666)
+ syncErr := f.Sync()
+ closeErr := f.Close()
+ if ctx.Err() != nil || copyErr != nil || extraN != 0 || endErr != io.EOF || modeErr != nil || syncErr != nil || closeErr != nil || n != field.bytes {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 400)
+ return
+ }
+ }
+ if _, err = m.NextRawPart(); err != io.EOF {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 400)
+ return
+ }
+ if err = s.snapshotHeld(ctx, in); err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ if err = p.run(ctx, in.OperationID); err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 422)
+ return
+ }
+ // Reap before interpreting any worker-controlled inode or metadata.
+ if err = p.stop(in.OperationID); err != nil {
+ session.cleanupErr = err
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ source, meta, err := p.result(ctx, in.OperationID)
+ if err != nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 422)
+ return
+ }
+ if err = s.snapshotHeld(ctx, in); err != nil {
+ source.Close()
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ w.Header().Set(BuildHeader, s.Build)
+ w.Header().Set("Content-Type", "application/vnd.sqlite3")
+ w.Header().Set(democlaim.SnapshotBytesHeader, strconv.FormatInt(meta.Bytes, 10))
+ w.Header().Set(democlaim.SnapshotSHA256Header, meta.SHA256)
+ // A trailer keeps EOF behind cleanup. Close additionally asks the root door
+ // for a cleanup acknowledgment, including when transport cancellation hid EOF.
+ w.Header().Set("Trailer", "Carlos-Demo-Snapshot-Clean")
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.Copy(w, io.LimitReader(source.DB, meta.Bytes))
+ source.Close()
+ cleanup()
+ if session.cleanupErr == nil {
+ w.Header().Set("Carlos-Demo-Snapshot-Clean", "1")
+ }
+}
+func (p *demoSnapshotSupervisor) register(in demoSnapshotRequest, cancel context.CancelFunc) (*snapshotSession, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.prune()
+ if _, ok := p.sessions[in.TransferID]; ok || len(p.sessions) >= 64 {
+ return nil, democlaim.ErrSnapshot
+ }
+ session := &snapshotSession{op: in.OperationID, cancel: cancel, done: make(chan struct{}), created: time.Now()}
+ p.sessions[in.TransferID] = session
+ return session, nil
+}
+func (p *demoSnapshotSupervisor) prune() {
+ for key, v := range p.sessions {
+ if time.Since(v.created) > democlaim.SnapshotWindow+30*time.Second {
+ select {
+ case <-v.done:
+ delete(p.sessions, key)
+ default:
+ }
+ }
+ }
+}
+func (s *Server) handleDemoSnapshotClose(w http.ResponseWriter, r *http.Request) {
+ defer r.Body.Close()
+ p := s.snapshots
+ if p == nil {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+ return
+ }
+ _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(15 * time.Second))
+ raw, err := io.ReadAll(io.LimitReader(r.Body, 1025))
+ var in demoSnapshotClose
+ if err != nil || len(raw) > 1024 || demobuild.DecodeMessage(raw, &in) != nil || !demobuild.ValidJobID(in.OperationID) || !demobuild.ValidJobID(in.TransferID) {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 400)
+ return
+ }
+ p.mu.Lock()
+ p.prune()
+ session := p.sessions[in.TransferID]
+ if session == nil && len(p.sessions) < 64 {
+ // Remember an early cancellation before a delayed POST can register.
+ session = &snapshotSession{op: in.OperationID, done: make(chan struct{}), created: time.Now(), cancel: func() {}}
+ close(session.done)
+ p.sessions[in.TransferID] = session
+ }
+ p.mu.Unlock()
+ if session == nil || session.op != in.OperationID {
+ http.Error(w, democlaim.ErrSnapshot.Error(), 409)
+ return
+ }
+ session.cancel()
+ ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
+ defer cancel()
+ select {
+ case <-session.done:
+ if session.cleanupErr == nil {
+ w.WriteHeader(204)
+ return
+ }
+ case <-ctx.Done():
+ }
+ http.Error(w, democlaim.ErrSnapshot.Error(), 503)
+}
+
+func (p *demoSnapshotSupervisor) run(ctx context.Context, id string) error {
+ if err := p.assertUnit(ctx, id); err != nil {
+ return err
+ }
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ if _, err := p.s.Systemctl(ctx, "start", "--no-block", snapshotUnit(id)); err != nil {
+ return err
+ }
+ ticker := time.NewTicker(p.poll)
+ defer ticker.Stop()
+ for {
+ raw, err := p.s.Systemctl(ctx, "show", snapshotUnit(id), "-p", "ActiveState,SubState,Result,ExecMainCode,ExecMainStatus,ExecMainStartTimestampMonotonic")
+ if err != nil {
+ return err
+ }
+ m := snapshotProperties(raw)
+ if m["ActiveState"] == "failed" {
+ return democlaim.ErrSnapshot
+ }
+ if m["ActiveState"] == "active" && m["SubState"] == "exited" && m["ExecMainStartTimestampMonotonic"] != "" && m["ExecMainStartTimestampMonotonic"] != "0" {
+ if m["Result"] != "success" || m["ExecMainCode"] != "1" || m["ExecMainStatus"] != "0" {
+ return democlaim.ErrSnapshot
+ }
+ return ctx.Err()
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ }
+ }
+}
+func snapshotProperties(raw string) map[string]string {
+ out := map[string]string{}
+ for _, line := range strings.Split(raw, "\n") {
+ k, v, ok := strings.Cut(line, "=")
+ if ok {
+ out[k] = v
+ }
+ }
+ return out
+}
+func (p *demoSnapshotSupervisor) stop(id string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), p.stopWindow)
+ defer cancel()
+ return p.stopContext(ctx, id)
+}
+func (p *demoSnapshotSupervisor) stopContext(ctx context.Context, id string) error {
+ if p.s.Systemctl == nil {
+ return democlaim.ErrSnapshot
+ }
+ _, stopErr := p.s.Systemctl(ctx, "stop", "--no-block", snapshotUnit(id))
+ _, _ = p.s.Systemctl(ctx, "kill", "--kill-whom=all", "--signal=SIGKILL", snapshotUnit(id))
+ ticker := time.NewTicker(p.poll)
+ defer ticker.Stop()
+ for {
+ raw, err := p.s.Systemctl(ctx, "show", snapshotUnit(id), "-p", "LoadState,ActiveState,MainPID,ControlPID")
+ m := snapshotProperties(raw)
+ gone := m["LoadState"] == "not-found"
+ inactive := (m["ActiveState"] == "inactive" || m["ActiveState"] == "failed") && m["MainPID"] == "0" && m["ControlPID"] == "0"
+ if err == nil && (gone || stopErr == nil && inactive) && p.empty(id) == nil {
+ _, _ = p.s.Systemctl(ctx, "reset-failed", snapshotUnit(id))
+ return nil
+ }
+ select {
+ case <-ctx.Done():
+ return democlaim.ErrSnapshot
+ case <-ticker.C:
+ }
+ }
+}
+func (p *demoSnapshotSupervisor) cleanup(id string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), p.stopWindow)
+ defer cancel()
+ if err := p.stopContext(ctx, id); err != nil {
+ p.ready.Store(false)
+ return err
+ }
+ if err := p.unmount(ctx, id); err != nil {
+ p.ready.Store(false)
+ return err
+ }
+ root, err := instancefs.OpenRootBeneath(p.root, ".")
+ if err != nil {
+ p.ready.Store(false)
+ return err
+ }
+ defer root.Close()
+ if err = root.RemoveAll(id); err != nil {
+ p.ready.Store(false)
+ }
+ return err
+}
+func (p *demoSnapshotSupervisor) result(ctx context.Context, id string) (*democlaim.Source, democlaim.Snapshot, error) {
+ work := filepath.Join(p.root, id, "work")
+ f, err := instancefs.OpenBeneath(work, "result.json", os.O_RDONLY, 0)
+ if err != nil {
+ return nil, democlaim.Snapshot{}, err
+ }
+ raw, err := io.ReadAll(io.LimitReader(f, 1025))
+ err = errors.Join(err, f.Close())
+ var meta struct {
+ SHA256 string `json:"sha256"`
+ Bytes int64 `json:"bytes"`
+ }
+ if err != nil || len(raw) > 1024 || demobuild.DecodeMessage(raw, &meta) != nil || meta.Bytes <= 0 || meta.Bytes > democlaim.MaxSnapshotBytes {
+ return nil, democlaim.Snapshot{}, democlaim.ErrSnapshot
+ }
+ source, err := democlaim.OpenSource(work, "snapshot.db")
+ if err != nil {
+ return nil, democlaim.Snapshot{}, err
+ }
+ hash := sha256.New()
+ n, err := io.Copy(hash, io.LimitReader(source.DB, democlaim.MaxSnapshotBytes+1))
+ if err == nil {
+ err = source.VerifyUnchanged()
+ }
+ if err != nil || ctx.Err() != nil || n != meta.Bytes || hex.EncodeToString(hash.Sum(nil)) != meta.SHA256 {
+ source.Close()
+ return nil, democlaim.Snapshot{}, democlaim.ErrSnapshot
+ }
+ if _, err = source.DB.Seek(0, io.SeekStart); err != nil {
+ source.Close()
+ return nil, democlaim.Snapshot{}, err
+ }
+ return source, democlaim.Snapshot{SHA256: meta.SHA256, Bytes: meta.Bytes}, nil
+}
+func (p *demoSnapshotSupervisor) initialize(ctx context.Context) error {
+ p.ready.Store(false)
+ root, err := instancefs.OpenRootBeneath(p.root, ".")
+ if err != nil {
+ return err
+ }
+ defer root.Close()
+ st, err := root.Stat(".")
+ if err != nil || st.Mode().Perm() != 0700 || !snapshotRootOwned(st) {
+ return democlaim.ErrSnapshot
+ }
+ raw, err := p.s.Systemctl(ctx, "list-units", "--all", "--plain", "--no-legend", "carlos-demo-snapshot@*.service")
+ if err != nil {
+ return err
+ }
+ ids := map[string]bool{}
+ for _, line := range strings.Split(raw, "\n") {
+ fields := strings.Fields(line)
+ if len(fields) == 0 {
+ continue
+ }
+ id, ok := strings.CutPrefix(fields[0], "carlos-demo-snapshot@")
+ if !ok || !strings.HasSuffix(id, ".service") {
+ return democlaim.ErrSnapshot
+ }
+ id = strings.TrimSuffix(id, ".service")
+ if !demobuild.ValidJobID(id) {
+ return democlaim.ErrSnapshot
+ }
+ ids[id] = true
+ }
+ dir, err := instancefs.OpenDirBeneath(p.root, ".")
+ if err != nil {
+ return err
+ }
+ entries, err := dir.ReadDir(-1)
+ dir.Close()
+ if err != nil {
+ return err
+ }
+ for _, entry := range entries {
+ if !demobuild.ValidJobID(entry.Name()) || !entry.IsDir() {
+ return democlaim.ErrSnapshot
+ }
+ ids[entry.Name()] = true
+ }
+ for id := range ids {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ if err = p.cleanup(id); err != nil {
+ return err
+ }
+ }
+ // A valid, never-started instance resolves the installed template. Refuse
+ // capability when its effective restrictions or entry point are missing.
+ if err = p.assertUnit(ctx, strings.Repeat("A", 43)); err != nil {
+ return err
+ }
+ p.ready.Store(true)
+ return nil
+}
diff --git a/internal/instancectl/demo_snapshot_client.go b/internal/instancectl/demo_snapshot_client.go
new file mode 100644
index 000000000..9fa449526
--- /dev/null
+++ b/internal/instancectl/demo_snapshot_client.go
@@ -0,0 +1,182 @@
+package instancectl
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "hash"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
+)
+
+type demoSnapshotRequest struct {
+ Demo demo.Descriptor `json:"demo"`
+ OperationID string `json:"operationId"`
+ TransferID string `json:"transferId"`
+ DBBytes int64 `json:"dbBytes"`
+ WALBytes int64 `json:"walBytes"`
+}
+type demoSnapshotClose struct {
+ OperationID string `json:"operationId"`
+ TransferID string `json:"transferId"`
+}
+
+// SnapshotDemo sends only bytes, counts and identity. The caller retains the
+// source descriptors until this call returns. Close waits for root cleanup,
+// even when the request context has been cancelled or the body is unread.
+func (c *Client) SnapshotDemo(ctx context.Context, d demo.Descriptor, operationID string, db io.Reader, dbBytes int64, wal io.Reader, walBytes int64) (io.ReadCloser, error) {
+ if !demobuild.ValidJobID(operationID) || db == nil || dbBytes <= 0 || dbBytes > democlaim.MaxSnapshotBytes || walBytes < 0 || walBytes > democlaim.MaxSnapshotBytes-dbBytes || wal == nil && walBytes != 0 {
+ return nil, democlaim.ErrSnapshot
+ }
+ transfer, err := demobuild.NewJobID()
+ if err != nil {
+ return nil, err
+ }
+ in := demoSnapshotRequest{d, operationID, transfer, dbBytes, walBytes}
+ body, kind, err := snapshotMultipart(in, db, wal)
+ if err != nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithTimeout(ctx, democlaim.SnapshotWindow)
+ req, err := http.NewRequestWithContext(ctx, "POST", "http://control/demo-snapshot", body)
+ if err != nil {
+ cancel()
+ return nil, err
+ }
+ req.Header.Set("Content-Type", kind)
+ client := c.httpClient()
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ res, err := client.Do(req)
+ if err != nil {
+ cancel()
+ return nil, errors.Join(err, c.closeDemoSnapshot(in))
+ }
+ fail := func() (io.ReadCloser, error) {
+ res.Body.Close()
+ cancel()
+ return nil, errors.Join(democlaim.ErrSnapshot, c.closeDemoSnapshot(in))
+ }
+ if res.StatusCode != http.StatusOK || c.Build != "" && res.Header.Get(BuildHeader) != c.Build {
+ return fail()
+ }
+ n, err := strconv.ParseInt(res.Header.Get(democlaim.SnapshotBytesHeader), 10, 64)
+ digest := res.Header.Get(democlaim.SnapshotSHA256Header)
+ decoded, e := hex.DecodeString(digest)
+ if err != nil || n <= 0 || n > democlaim.MaxSnapshotBytes || e != nil || len(decoded) != 32 || hex.EncodeToString(decoded) != digest {
+ return fail()
+ }
+ return &demoSnapshotBody{body: res.Body, c: c, in: in, cancel: cancel, ctx: ctx, meta: democlaim.Snapshot{SHA256: digest, Bytes: n}, hash: sha256.New()}, nil
+}
+
+func snapshotMultipart(in demoSnapshotRequest, db, wal io.Reader) (io.Reader, string, error) {
+ // Multipart headers are tiny. Source descriptors stream directly without
+ // an extra producer goroutine. Read one extra byte to expose lies.
+ var buf bytes.Buffer
+ mw := multipart.NewWriter(&buf)
+ p, err := mw.CreateFormField("metadata")
+ if err != nil {
+ return nil, "", err
+ }
+ if err = json.NewEncoder(p).Encode(in); err != nil {
+ return nil, "", err
+ }
+ if _, err = mw.CreateFormField("db"); err != nil {
+ return nil, "", err
+ }
+ prefix := append([]byte(nil), buf.Bytes()...)
+ buf.Reset()
+ if _, err = mw.CreateFormField("wal"); err != nil {
+ return nil, "", err
+ }
+ middle := append([]byte(nil), buf.Bytes()...)
+ buf.Reset()
+ if err = mw.Close(); err != nil {
+ return nil, "", err
+ }
+ if wal == nil {
+ wal = bytes.NewReader(nil)
+ }
+ return io.MultiReader(bytes.NewReader(prefix), io.LimitReader(db, in.DBBytes+1), bytes.NewReader(middle), io.LimitReader(wal, in.WALBytes+1), bytes.NewReader(buf.Bytes())), mw.FormDataContentType(), nil
+}
+
+func (c *Client) closeDemoSnapshot(in demoSnapshotRequest) error {
+ // Independent of the upload deadline: root gets time to stop/reap and
+ // unmount. This request acknowledges cleanup, never authorizes an export.
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ raw, _ := json.Marshal(demoSnapshotClose{in.OperationID, in.TransferID})
+ req, err := http.NewRequestWithContext(ctx, "POST", "http://control/demo-snapshot/close", bytes.NewReader(raw))
+ if err != nil {
+ return err
+ }
+ client := c.httpClient()
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ res, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusNoContent {
+ return democlaim.ErrSnapshot
+ }
+ return nil
+}
+
+type demoSnapshotBody struct {
+ body io.ReadCloser
+ c *Client
+ in demoSnapshotRequest
+ cancel context.CancelFunc
+ ctx context.Context
+ meta democlaim.Snapshot
+ hash hash.Hash
+ read int64
+ readErr error
+ once sync.Once
+ closeErr error
+}
+
+func (b *demoSnapshotBody) SnapshotMetadata() democlaim.Snapshot { return b.meta }
+func (b *demoSnapshotBody) Read(p []byte) (int, error) {
+ if b.readErr != nil {
+ return 0, b.readErr
+ }
+ n, err := b.body.Read(p)
+ b.read += int64(n)
+ b.hash.Write(p[:n])
+ if b.read > b.meta.Bytes {
+ err = democlaim.ErrSnapshot
+ }
+ if err == io.EOF && (b.read != b.meta.Bytes || hex.EncodeToString(b.hash.Sum(nil)) != b.meta.SHA256) {
+ err = democlaim.ErrSnapshot
+ }
+ if err != nil {
+ b.readErr = err
+ }
+ return n, err
+}
+func (b *demoSnapshotBody) Close() error {
+ b.once.Do(func() {
+ if b.ctx.Err() == nil && b.readErr == nil {
+ _, b.closeErr = io.Copy(io.Discard, b)
+ }
+ if b.readErr != nil && b.readErr != io.EOF {
+ b.closeErr = errors.Join(b.closeErr, b.readErr)
+ }
+ b.closeErr = errors.Join(b.closeErr, b.body.Close())
+ b.cancel()
+ b.closeErr = errors.Join(b.closeErr, b.c.closeDemoSnapshot(b.in))
+ })
+ return b.closeErr
+}
diff --git a/internal/instancectl/demo_snapshot_disk.go b/internal/instancectl/demo_snapshot_disk.go
new file mode 100644
index 000000000..58283afdf
--- /dev/null
+++ b/internal/instancectl/demo_snapshot_disk.go
@@ -0,0 +1,187 @@
+package instancectl
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/instancefs"
+)
+
+func (p *demoSnapshotSupervisor) mountName(id string) string {
+ var b strings.Builder
+ for _, c := range []byte(strings.TrimPrefix(filepath.Join(p.root, id, "work"), "/")) {
+ switch {
+ case c == '/':
+ b.WriteByte('-')
+ case c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '.':
+ b.WriteByte(c)
+ default:
+ fmt.Fprintf(&b, "\\x%02x", c)
+ }
+ }
+ return b.String() + ".mount"
+}
+func (p *demoSnapshotSupervisor) prepareDisk(ctx context.Context, id string) error {
+ if p.root != demoSnapshotRoot || p.s.DropInDir != "/run/systemd/system" || p.s.Run == nil {
+ return democlaim.ErrSnapshot
+ }
+ dir := filepath.Join(p.root, id)
+ root, err := instancefs.OpenRootBeneath(dir, ".")
+ if err != nil {
+ return err
+ }
+ defer root.Close()
+ if err = root.Mkdir("work", 0700); err != nil {
+ return err
+ }
+ image, err := instancefs.OpenBeneath(dir, "snapshot.img", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
+ if err != nil {
+ return err
+ }
+ // Allocate real blocks before reading input. nodiscard below preserves that
+ // reservation. The loop filesystem bounds *all* worker files, not just DB/WAL.
+ err = allocateSnapshotDisk(image)
+ closeErr := image.Close()
+ if err != nil {
+ return err
+ }
+ if closeErr != nil {
+ return closeErr
+ }
+ if _, err = p.s.Run(ctx, "/usr/sbin/mkfs.ext4", "-q", "-F", "-m", "0", "-O", "^has_journal", "-E", "nodiscard,lazy_itable_init=0", filepath.Join(dir, "snapshot.img")); err != nil {
+ return err
+ }
+ content := fmt.Sprintf("[Unit]\nBindsTo=carlos-instance-control.service\nAfter=carlos-instance-control.service\n[Mount]\nWhat=%s/snapshot.img\nWhere=%s/work\nType=ext4\nOptions=loop,nosuid,nodev,noexec\nTimeoutSec=5\n", dir, dir)
+ f, err := instancefs.OpenBeneath(p.s.DropInDir, p.mountName(id), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
+ if err != nil {
+ return err
+ }
+ _, err = f.WriteString(content)
+ syncErr := f.Sync()
+ closeErr = f.Close()
+ if err != nil {
+ return err
+ }
+ if syncErr != nil {
+ return syncErr
+ }
+ if closeErr != nil {
+ return closeErr
+ }
+ if _, err = p.s.Systemctl(ctx, "daemon-reload"); err != nil {
+ return err
+ }
+ if _, err = p.s.Systemctl(ctx, "start", p.mountName(id)); err != nil {
+ return err
+ }
+ if err = verifySnapshotDisk(filepath.Join(dir, "work")); err != nil {
+ return err
+ }
+ work, err := instancefs.OpenRootBeneath(dir, "work")
+ if err != nil {
+ return err
+ }
+ defer work.Close()
+ // systemd mounts this directory at /work before dropping to its dynamic UID.
+ return work.Chmod(".", 0777)
+}
+func (p *demoSnapshotSupervisor) unmountDisk(ctx context.Context, id string) error {
+ if p.s.DropInDir == "" {
+ return democlaim.ErrSnapshot
+ }
+ unit := p.mountName(id)
+ raw, err := p.s.Systemctl(ctx, "show", unit, "-p", "LoadState,ActiveState")
+ if err != nil {
+ return err
+ }
+ if snapshotProperties(raw)["LoadState"] != "not-found" {
+ if _, err = p.s.Systemctl(ctx, "stop", unit); err != nil {
+ return err
+ }
+ }
+ if err = snapshotDiskUnmounted(filepath.Join(p.root, id, "work")); err != nil {
+ return err
+ }
+ root, err := instancefs.OpenRootBeneath(p.s.DropInDir, ".")
+ if err != nil {
+ return err
+ }
+ defer root.Close()
+ if err = root.Remove(unit); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ _, err = p.s.Systemctl(ctx, "daemon-reload")
+ return err
+}
+
+func (p *demoSnapshotSupervisor) checkUnit(ctx context.Context, id string) error {
+ want := map[string]string{
+ "Type": "exec", "RemainAfterExit": "yes", "DynamicUser": "yes", "Restart": "no",
+ "MemoryMax": "268435456", "MemorySwapMax": "0", "TasksMax": "32", "CPUQuotaPerSecUSec": "500ms",
+ "RuntimeMaxUSec": "2min", "TimeoutStopUSec": "5s", "KillMode": "control-group", "SendSIGKILL": "yes", "OOMPolicy": "kill",
+ "LimitFSIZE": "268435456", "LimitFSIZESoft": "268435456", "WorkingDirectory": "/work",
+ "ProtectSystem": "strict", "ProtectHome": "yes", "PrivateNetwork": "yes", "PrivateDevices": "yes", "PrivateIPC": "yes", "PrivatePIDs": "yes",
+ "RestrictAddressFamilies": "AF_UNIX", "CapabilityBoundingSet": "", "AmbientCapabilities": "", "NoNewPrivileges": "yes",
+ "RestrictNamespaces": "yes", "ProtectControlGroups": "yes", "ProtectProc": "invisible", "ProcSubset": "pid",
+ "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": "",
+ }
+ keys := []string{"BindPaths", "BindReadOnlyPaths", "TemporaryFileSystem", "Environment", "ExecStart", "IPAddressDeny", "RootDirectory", "RootImage", "ReadWritePaths"}
+ for k := range want {
+ keys = append(keys, k)
+ }
+ raw, err := p.s.Systemctl(ctx, "show", snapshotUnit(id), "-p", strings.Join(keys, ","))
+ if err != nil {
+ return err
+ }
+ actual := snapshotProperties(raw)
+ for k, v := range want {
+ if got, ok := actual[k]; !ok || got != v {
+ return democlaim.ErrSnapshot
+ }
+ }
+ binds := func(raw, want string) bool {
+ return strings.TrimSuffix(strings.TrimSuffix(raw, ":rbind"), ":norbind") == want
+ }
+ 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"] != "" {
+ return democlaim.ErrSnapshot
+ }
+ if strings.Join(strings.Fields(actual["Environment"]), " ") != "HOME=/work TMPDIR=/work GOMEMLIMIT=192MiB" {
+ return democlaim.ErrSnapshot
+ }
+ expected := strings.Fields("/data:ro /run:ro /var:ro /opt:ro /etc:ro /tmp:ro /dev/shm:ro /dev/mqueue:ro /dev/pts:ro")
+ fields := strings.Fields(actual["TemporaryFileSystem"])
+ if len(fields) != len(expected) {
+ return democlaim.ErrSnapshot
+ }
+ for _, f := range expected {
+ found := false
+ for _, v := range fields {
+ if f == v {
+ found = true
+ }
+ }
+ if !found {
+ return democlaim.ErrSnapshot
+ }
+ }
+ deny := actual["IPAddressDeny"]
+ if deny != "any" && deny != "0.0.0.0/0 ::/0" && deny != "::/0 0.0.0.0/0" {
+ return democlaim.ErrSnapshot
+ }
+ // systemctl formats ExecStart as a property record, including status fields.
+ exec := actual["ExecStart"]
+ if !strings.HasPrefix(exec, "{ path=/snapshot-worker ; argv[]=/snapshot-worker __demo-snapshot ; ignore_errors=no ; ") || strings.Count(exec, "path=") != 1 {
+ return democlaim.ErrSnapshot
+ }
+ return nil
+}
diff --git a/internal/instancectl/demo_snapshot_kernel_linux_test.go b/internal/instancectl/demo_snapshot_kernel_linux_test.go
new file mode 100644
index 000000000..1fc2c7e33
--- /dev/null
+++ b/internal/instancectl/demo_snapshot_kernel_linux_test.go
@@ -0,0 +1,324 @@
+//go:build linux
+
+package instancectl
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
+ "golang.org/x/sys/unix"
+)
+
+type snapshotWitnessInput struct {
+ Mode string
+ Files []string
+ Socket string
+}
+
+// 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) {
+ if os.Getenv("CARLOS_SNAPSHOT_WITNESS_HELPER") != "1" {
+ t.Skip("private snapshot witness helper")
+ }
+ if os.Geteuid() == 0 {
+ t.Fatal("root worker")
+ }
+ raw, err := os.ReadFile("/work/witness.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var in snapshotWitnessInput
+ if err = json.Unmarshal(raw, &in); err != nil {
+ t.Fatal(err)
+ }
+ if in.Mode == "memory" {
+ if err = os.WriteFile("/work/started", []byte("1"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ var held [][]byte
+ for n := 0; n < 40; n++ {
+ b := make([]byte, 8<<20)
+ for i := 0; i < len(b); i += 4096 {
+ b[i] = 1
+ }
+ held = append(held, b)
+ }
+ runtime.KeepAlive(held)
+ os.WriteFile("/work/escaped", []byte("memory"), 0600)
+ t.Fatal("memory limit absent")
+ }
+ if in.Mode == "isolation" {
+ for _, path := range in.Files {
+ if _, e := os.ReadFile(path); e == nil {
+ t.Fatal("host file readable", path)
+ }
+ }
+ for _, family := range []int{unix.AF_INET, unix.AF_INET6} {
+ fd, e := unix.Socket(family, unix.SOCK_STREAM, 0)
+ if e == nil {
+ unix.Close(fd)
+ t.Fatal("network available")
+ }
+ }
+ if c, e := net.DialTimeout("unix", in.Socket, time.Second); e == nil {
+ c.Close()
+ t.Fatal("host socket reachable")
+ }
+ if e := os.WriteFile("/tmp/snapshot-escape", []byte("x"), 0600); e == nil {
+ t.Fatal("writable scratch outside quota")
+ }
+ buf := make([]byte, 1<<20)
+ written := int64(0)
+ full := false
+ var files []string
+ for n := 0; n < 49 && !full; n++ {
+ name := fmt.Sprintf("/work/fill-%d", n)
+ f, e := os.Create(name)
+ if e != nil {
+ t.Fatal(e)
+ }
+ files = append(files, name)
+ for k := 0; k < 16; k++ {
+ count, e := f.Write(buf)
+ written += int64(count)
+ if e != nil {
+ if !errors.Is(e, syscall.ENOSPC) {
+ f.Close()
+ t.Fatal(e)
+ }
+ full = true
+ break
+ }
+ }
+ f.Close()
+ }
+ if !full || written > democlaim.MaxScratchBytes {
+ t.Fatal("aggregate disk limit absent", written)
+ }
+ for _, path := range files {
+ if e := os.Remove(path); e != nil {
+ t.Fatal(e)
+ }
+ }
+ child := exec.Command("/snapshot-worker", "-test.run=^TestDemoClaimSnapshotDescendant$")
+ child.Env = os.Environ()
+ if err = child.Start(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err = os.WriteFile("/work/ready", []byte("1"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ signal.Ignore(syscall.SIGTERM)
+ for {
+ time.Sleep(time.Second)
+ }
+}
+func TestDemoClaimSnapshotDescendant(t *testing.T) {
+ if os.Getenv("CARLOS_SNAPSHOT_WITNESS_HELPER") != "1" {
+ t.Skip("private snapshot witness descendant")
+ }
+ signal.Ignore(syscall.SIGTERM)
+ for {
+ time.Sleep(time.Second)
+ }
+}
+
+func TestDemoClaimSnapshotRuntimeDevWitness(t *testing.T) {
+ if os.Getenv("CARLOS_DEMO_CLAIM_DEV_WITNESS") != "1" {
+ t.Skip("R6: real snapshot mount, resource, isolation and descendant witness requires an explicitly designated idle systemd sandbox and a prebuilt test binary")
+ }
+ if os.Geteuid() != 0 {
+ t.Fatal("sandbox root required; never compile this test on the box")
+ }
+ ctl := func(ctx context.Context, args ...string) (string, error) {
+ cmd := exec.CommandContext(ctx, "/usr/bin/systemctl", args...)
+ cmd.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "SYSTEMD_COLORS=0", "SYSTEMD_PAGER="}
+ out, e := cmd.CombinedOutput()
+ return string(out), e
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute)
+ defer cancel()
+ if raw, e := ctl(ctx, "is-active", "carlos-instance-control.service"); e != nil || strings.TrimSpace(raw) != "active" {
+ t.Fatal("sandbox root control must be active, with build worker disabled", e)
+ }
+ if raw, e := ctl(ctx, "list-units", "--no-legend", "--state=active,activating", "carlos-demo-build@*.service", "carlos-demo-snapshot@*.service"); e != nil || strings.TrimSpace(raw) != "" {
+ t.Fatal("sandbox has active work", raw, e)
+ }
+ entries, err := os.ReadDir(demoSnapshotRoot)
+ if err != nil || len(entries) != 0 {
+ t.Fatal("sandbox snapshot root must be installed and empty", err)
+ }
+ s := &Server{Systemctl: ctl, Run: func(ctx context.Context, args ...string) (string, error) {
+ out, e := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput()
+ return string(out), e
+ }, DropInDir: "/run/systemd/system", CgroupRoot: "/sys/fs/cgroup"}
+ p := newDemoSnapshotSupervisor(s)
+ if err = p.initialize(ctx); err != nil {
+ t.Fatal("installed template refused", err)
+ }
+ fixture := t.TempDir()
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ src, err := os.Open(exe)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dst, err := os.OpenFile(filepath.Join(fixture, "worker"), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0555)
+ if err != nil {
+ src.Close()
+ t.Fatal(err)
+ }
+ _, err = io.Copy(dst, src)
+ src.Close()
+ dst.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, mode := range []string{"isolation", "memory", "duration"} {
+ t.Run(mode, func(t *testing.T) {
+ id, e := demobuild.NewJobID()
+ if e != nil {
+ t.Fatal(e)
+ }
+ dir := filepath.Join(p.root, id)
+ if e = os.Mkdir(dir, 0700); e != nil {
+ t.Fatal(e)
+ }
+ // Cleanup reaps before unmounting, even when a witness assertion fails.
+ defer func() {
+ if e := p.cleanup(id); e != nil {
+ t.Error("sandbox cleanup", e)
+ }
+ }()
+ if avail, _, e := statfsBytes(p.root); e != nil || avail < uint64(democlaim.MaxScratchBytes) {
+ t.Fatal("sandbox disk reservation unavailable", e)
+ }
+ if e = p.prepareDisk(ctx, id); e != nil {
+ t.Fatal(e)
+ }
+ input := snapshotWitnessInput{Mode: mode}
+ for _, base := range []string{"/data", "/etc/carlos", "/var/lib"} {
+ path := filepath.Join(base, "snapshot-witness-"+id)
+ f, e := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
+ if e != nil {
+ t.Fatal(e)
+ }
+ io.WriteString(f, "host sentinel")
+ f.Close()
+ defer os.Remove(path)
+ input.Files = append(input.Files, path)
+ }
+ input.Socket = "/run/carlos-control/snapshot-" + id
+ ln, e := net.Listen("unix", input.Socket)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer ln.Close()
+ if e = os.Chmod(input.Socket, 0666); e != nil {
+ t.Fatal(e)
+ }
+ raw, _ := json.Marshal(input)
+ if e = os.WriteFile(filepath.Join(dir, "work/witness.json"), raw, 0644); e != nil {
+ t.Fatal(e)
+ }
+ drop := filepath.Join(s.DropInDir, snapshotUnit(id)+".d")
+ if e = os.Mkdir(drop, 0755); e != nil {
+ t.Fatal(e)
+ }
+ defer func() {
+ os.Remove(filepath.Join(drop, "90-witness.conf"))
+ 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"
+ if e = os.WriteFile(filepath.Join(drop, "90-witness.conf"), []byte(text), 0644); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = ctl(ctx, "daemon-reload"); e != nil {
+ t.Fatal(e)
+ }
+ if e = p.checkUnit(ctx, id); e == nil {
+ t.Fatal("production gate accepted witness executable override")
+ }
+ // The template was checked before this test-only executable replacement.
+ oldAssert := p.assertUnit
+ p.assertUnit = func(context.Context, string) error { return nil }
+ defer func() { p.assertUnit = oldAssert }()
+ runCtx, stop := context.WithTimeout(ctx, democlaim.SnapshotWindow)
+ defer stop()
+ watcherDone := make(chan struct{})
+ go func() {
+ defer close(watcherDone)
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-runCtx.Done():
+ return
+ case <-ticker.C:
+ if mode == "isolation" {
+ if _, e := os.Stat(filepath.Join(dir, "work/ready")); e == nil {
+ stop()
+ return
+ }
+ }
+ }
+ }
+ }()
+ start := time.Now()
+ e = p.run(runCtx, id)
+ stop()
+ <-watcherDone
+ if e == nil {
+ t.Fatal("hostile worker completed")
+ }
+ if time.Since(start) > democlaim.SnapshotWindow+5*time.Second {
+ t.Fatal("runtime bound exceeded")
+ }
+ if mode == "memory" {
+ result, e := ctl(ctx, "show", snapshotUnit(id), "-p", "Result")
+ if e != nil || snapshotProperties(result)["Result"] != "oom-kill" {
+ t.Fatal("memory limit did not kill helper", result, e)
+ }
+ if _, e = os.Stat(filepath.Join(dir, "work/escaped")); !os.IsNotExist(e) {
+ t.Fatal("helper exceeded memory budget")
+ }
+ } else {
+ if _, e = os.Stat(filepath.Join(dir, "work/ready")); e != nil {
+ t.Fatal("helper failed isolation or disk assertions", e)
+ }
+ }
+ if e = p.stop(id); e != nil {
+ t.Fatal("descendants survived", e)
+ }
+ if e = p.emptyCgroup(id); e != nil {
+ t.Fatal(e)
+ }
+ if e = p.cleanup(id); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = os.Stat(dir); !os.IsNotExist(e) {
+ t.Fatal("scratch survived", e)
+ }
+ })
+ }
+}
diff --git a/internal/instancectl/demo_snapshot_linux.go b/internal/instancectl/demo_snapshot_linux.go
new file mode 100644
index 000000000..1afe5a49c
--- /dev/null
+++ b/internal/instancectl/demo_snapshot_linux.go
@@ -0,0 +1,91 @@
+//go:build linux
+
+package instancectl
+
+import (
+ "bufio"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "golang.org/x/sys/unix"
+)
+
+func snapshotRootOwned(st os.FileInfo) bool {
+ stat, ok := st.Sys().(*syscall.Stat_t)
+ return ok && stat.Uid == uint32(os.Geteuid())
+}
+func allocateSnapshotDisk(f *os.File) error {
+ if err := unix.Fallocate(int(f.Fd()), 0, 0, democlaim.MaxScratchBytes); err != nil {
+ return err
+ }
+ return f.Sync()
+}
+func verifySnapshotDisk(dir string) error {
+ var st, parent unix.Stat_t
+ var fs unix.Statfs_t
+ if err := unix.Stat(dir, &st); err != nil {
+ return err
+ }
+ if err := unix.Stat(filepath.Dir(dir), &parent); err != nil {
+ return err
+ }
+ if err := unix.Statfs(dir, &fs); err != nil {
+ return err
+ }
+ if st.Dev == parent.Dev || fs.Type != unix.EXT4_SUPER_MAGIC || fs.Blocks*uint64(fs.Bsize) > uint64(democlaim.MaxScratchBytes) || fs.Flags&unix.ST_NODEV == 0 || fs.Flags&unix.ST_NOSUID == 0 || fs.Flags&unix.ST_NOEXEC == 0 {
+ return democlaim.ErrSnapshot
+ }
+ return nil
+}
+func snapshotDiskUnmounted(dir string) error {
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ scan := bufio.NewScanner(f)
+ for scan.Scan() {
+ fields := strings.Fields(scan.Text())
+ if len(fields) < 5 {
+ return democlaim.ErrSnapshot
+ }
+ if fields[4] == dir || strings.HasPrefix(fields[4], dir+"/") {
+ return democlaim.ErrSnapshot
+ }
+ }
+ return scan.Err()
+}
+func (p *demoSnapshotSupervisor) emptyCgroup(id string) error {
+ // Verify the hierarchy itself exists; an unknown tree is never proof.
+ parent := filepath.Join(p.s.CgroupRoot, "system.slice")
+ root, err := instancefs.OpenDirBeneath(parent, ".")
+ if err != nil {
+ return err
+ }
+ defer root.Close()
+ path := filepath.Join(parent, snapshotUnit(id))
+ f, absent, err := instancefs.OpenBeneathOrAbsent(path, "cgroup.events")
+ if errors.Is(err, os.ErrNotExist) {
+ if _, e := os.Lstat(path); os.IsNotExist(e) {
+ return nil
+ }
+ }
+ if err != nil || absent {
+ return democlaim.ErrSnapshot
+ }
+ defer f.Close()
+ var raw [4096]byte
+ n, err := f.Read(raw[:])
+ if err != nil {
+ return err
+ }
+ if !strings.Contains("\n"+string(raw[:n])+"\n", "\npopulated 0\n") {
+ return democlaim.ErrSnapshot
+ }
+ return nil
+}
diff --git a/internal/instancectl/demo_snapshot_other.go b/internal/instancectl/demo_snapshot_other.go
new file mode 100644
index 000000000..f5b2ab956
--- /dev/null
+++ b/internal/instancectl/demo_snapshot_other.go
@@ -0,0 +1,14 @@
+//go:build !linux
+
+package instancectl
+
+import (
+ "errors"
+ "os"
+)
+
+func snapshotRootOwned(os.FileInfo) bool { return false }
+func allocateSnapshotDisk(*os.File) error { return errors.ErrUnsupported }
+func verifySnapshotDisk(string) error { return errors.ErrUnsupported }
+func snapshotDiskUnmounted(string) error { return errors.ErrUnsupported }
+func (*demoSnapshotSupervisor) emptyCgroup(string) error { return errors.ErrUnsupported }
diff --git a/internal/instancectl/demo_snapshot_test.go b/internal/instancectl/demo_snapshot_test.go
new file mode 100644
index 000000000..205ef0eee
--- /dev/null
+++ b/internal/instancectl/demo_snapshot_test.go
@@ -0,0 +1,527 @@
+package instancectl
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "mime/multipart"
+ "net"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+type snapshotBuilderFake struct {
+ demoBuilder
+ mu sync.Mutex
+ busy, poisoned bool
+}
+
+func (b *snapshotBuilderFake) AcquireSnapshot(context.Context) (func(bool), error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.busy || b.poisoned {
+ return nil, demobuild.ErrBuild
+ }
+ b.busy = true
+ return func(clean bool) { b.mu.Lock(); defer b.mu.Unlock(); b.busy = false; b.poisoned = !clean }, nil
+}
+
+type snapshotFixture struct {
+ s *Server
+ p *demoSnapshotSupervisor
+ d demo.Descriptor
+ op string
+ rt *registry.Route
+ builder *snapshotBuilderFake
+ client *Client
+ mu sync.Mutex
+ stopped, started int
+ run func(context.Context, string) error
+ failStop bool
+ status string
+}
+
+func newSnapshotFixture(t *testing.T) *snapshotFixture {
+ t.Helper()
+ f := &snapshotFixture{status: "success"}
+ f.op, _ = demobuild.NewJobID()
+ f.d = demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "bright-otter-42.example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}
+ f.rt = &registry.Route{Host: f.d.Host, Account: "shop", App: "tmp-demo-bright-otter-42", DemoID: f.d.ID, DemoHost: f.d.Host, DemoLifetime: f.d.Lifetime, DemoExpiresAt: f.d.ExpiresAt, Status: "moving", HoldOp: "demo-claim/" + f.op}
+ f.builder = &snapshotBuilderFake{}
+ f.s = &Server{DemoBox: true, DemoConfig: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}, DemoBuilder: f.builder, HostDemo: func(string) (*registry.Route, error) { return f.rt, nil }, DemoPurgeGuard: func(ctx context.Context, fn func() error) error { return fn() }, Statfs: func(string) (uint64, uint64, error) {
+ return 2 * uint64(democlaim.MaxScratchBytes), 3 * uint64(democlaim.MaxScratchBytes), nil
+ }}
+ f.s.Systemctl = func(ctx context.Context, args ...string) (string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ switch args[0] {
+ case "list-units":
+ return "", nil
+ case "start":
+ f.started++
+ if f.run != nil {
+ return "", f.run(ctx, filepath.Join(f.p.root, f.op, "work"))
+ }
+ raw, err := os.ReadFile(filepath.Join(f.p.root, f.op, "work/snapshot.db"))
+ if err != nil {
+ return "", err
+ }
+ sum := sha256.Sum256(raw)
+ meta, _ := json.Marshal(democlaim.Snapshot{SHA256: hex.EncodeToString(sum[:]), Bytes: int64(len(raw))})
+ return "", os.WriteFile(filepath.Join(f.p.root, f.op, "work/result.json"), meta, 0600)
+ case "stop":
+ f.stopped++
+ if f.failStop {
+ return "", errors.New("stop failed")
+ }
+ return "", nil
+ case "kill", "reset-failed":
+ return "", nil
+ case "show":
+ if f.stopped > 0 && !f.failStop {
+ return "LoadState=loaded\nActiveState=inactive\nMainPID=0\nControlPID=0\n", nil
+ }
+ return "LoadState=loaded\nActiveState=active\nSubState=exited\nResult=" + f.status + "\nExecMainCode=1\nExecMainStatus=0\nExecMainStartTimestampMonotonic=123\nMainPID=0\nControlPID=0\n", nil
+ }
+ return "", errors.New("unexpected systemctl")
+ }
+ f.p = newDemoSnapshotSupervisor(f.s)
+ f.p.root = t.TempDir()
+ if e := os.Chmod(f.p.root, 0700); e != nil {
+ t.Fatal(e)
+ }
+ f.p.poll = time.Millisecond
+ f.p.stopWindow = 20 * time.Millisecond
+ f.p.prepare = func(ctx context.Context, id string) error { return os.Mkdir(filepath.Join(f.p.root, id, "work"), 0777) }
+ f.p.unmount = func(context.Context, string) error { return nil }
+ f.p.assertUnit = func(context.Context, string) error { return nil }
+ f.p.empty = func(string) error { return nil }
+ f.s.snapshots = f.p
+ if err := f.p.initialize(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(f.s.Handler())
+ t.Cleanup(srv.Close)
+ f.client = &Client{Dial: func(ctx context.Context, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "tcp", srv.Listener.Addr().String())
+ }}
+ return f
+}
+func (f *snapshotFixture) noScratch(t *testing.T) {
+ t.Helper()
+ entries, e := os.ReadDir(f.p.root)
+ if e != nil || len(entries) != 0 {
+ t.Fatalf("scratch remains %v %v", entries, e)
+ }
+}
+func TestDemoClaimExportBounded(t *testing.T) {
+ t.Run("streamAndClose", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ body, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("db bytes"), 8, nil, 0)
+ if e != nil {
+ t.Fatal(e)
+ }
+ got, e := io.ReadAll(body)
+ if e != nil || string(got) != "db bytes" {
+ t.Fatal(string(got), e)
+ }
+ if e = body.Close(); e != nil {
+ t.Fatal(e)
+ }
+ f.noScratch(t)
+ if f.stopped == 0 {
+ t.Fatal("unit not stopped")
+ }
+ })
+ for _, fault := range []string{"unheld", "wrongOperation", "wrongLifetime", "shortDisk", "builderBusy", "overLimit", "lengthMismatch", "extraWAL", "failedUnit", "badDigest", "badSize", "outputSymlink", "outputHardlink", "resultPath", "credentialPath", "filename", "extraField"} {
+ t.Run(fault, func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ db := io.Reader(strings.NewReader("data"))
+ n := int64(4)
+ wal := io.Reader(nil)
+ wn := int64(0)
+ switch fault {
+ case "unheld":
+ f.rt.Status = "ready"
+ case "wrongOperation":
+ f.rt.HoldOp = "demo-claim/other"
+ case "wrongLifetime":
+ f.rt.DemoLifetime = "other"
+ case "shortDisk":
+ f.s.Statfs = func(string) (uint64, uint64, error) { return uint64(democlaim.MaxScratchBytes - 1), 0, nil }
+ case "builderBusy":
+ f.builder.busy = true
+ case "overLimit":
+ n = democlaim.MaxSnapshotBytes
+ wn = 1
+ wal = strings.NewReader("x")
+ case "lengthMismatch":
+ n = 3
+ case "extraWAL":
+ wal = strings.NewReader("unexpected")
+ case "failedUnit":
+ f.status = "exit-code"
+ case "badDigest", "badSize", "outputSymlink", "outputHardlink", "resultPath":
+ f.run = func(_ context.Context, dir string) error {
+ sum := sha256.Sum256([]byte("data"))
+ result := map[string]any{"sha256": hex.EncodeToString(sum[:]), "bytes": 4}
+ switch fault {
+ case "badDigest":
+ result["sha256"] = strings.Repeat("0", 64)
+ case "badSize":
+ result["bytes"] = democlaim.MaxSnapshotBytes + 1
+ case "resultPath":
+ result["path"] = "/etc/credentials"
+ case "outputSymlink":
+ os.Remove(filepath.Join(dir, "snapshot.db"))
+ secret := filepath.Join(t.TempDir(), "credentials")
+ if e := os.WriteFile(secret, []byte("data"), 0600); e != nil {
+ return e
+ }
+ os.Symlink(secret, filepath.Join(dir, "snapshot.db"))
+ case "outputHardlink":
+ os.Link(filepath.Join(dir, "snapshot.db"), filepath.Join(dir, "sibling"))
+ }
+ raw, _ := json.Marshal(result)
+ return os.WriteFile(filepath.Join(dir, "result.json"), raw, 0600)
+ }
+ }
+ if fault == "credentialPath" || fault == "filename" || fault == "extraField" {
+ var raw bytes.Buffer
+ mw := multipart.NewWriter(&raw)
+ meta := map[string]any{"demo": f.d, "operationId": f.op, "transferId": f.op, "dbBytes": 4, "walBytes": 0}
+ if fault == "credentialPath" {
+ meta["path"] = "/etc/credentials"
+ }
+ b, _ := json.Marshal(meta)
+ p, _ := mw.CreateFormField("metadata")
+ p.Write(b)
+ if fault == "filename" {
+ p, _ = mw.CreateFormFile("db", "/data/sibling.db")
+ } else {
+ p, _ = mw.CreateFormField("db")
+ }
+ p.Write([]byte("data"))
+ mw.CreateFormField("wal")
+ if fault == "extraField" {
+ mw.WriteField("argv", "/bin/sh")
+ }
+ mw.Close()
+ req := httptest.NewRequest("POST", "/demo-snapshot", &raw)
+ req.Header.Set("Content-Type", mw.FormDataContentType())
+ out := httptest.NewRecorder()
+ f.s.Handler().ServeHTTP(out, req)
+ if out.Code == 200 {
+ t.Fatal("unsafe fields accepted")
+ }
+ } else {
+ body, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, db, n, wal, wn)
+ if body != nil {
+ body.Close()
+ }
+ if e == nil {
+ t.Fatal("unsafe export accepted")
+ }
+ }
+ f.noScratch(t)
+ if fault == "unheld" || fault == "wrongOperation" || fault == "shortDisk" || fault == "builderBusy" || fault == "credentialPath" {
+ if f.started != 0 {
+ t.Fatal("worker started before admission")
+ }
+ }
+ })
+ }
+ t.Run("oneExportPerBox", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ started := make(chan struct{})
+ release := make(chan struct{})
+ f.run = func(ctx context.Context, _ string) error {
+ close(started)
+ select {
+ case <-release:
+ case <-ctx.Done():
+ }
+ return democlaim.ErrSnapshot
+ }
+ done := make(chan error, 1)
+ go func() {
+ _, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("data"), 4, nil, 0)
+ done <- e
+ }()
+ <-started
+ if _, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("data"), 4, nil, 0); e == nil {
+ t.Fatal("overlapping export")
+ }
+ close(release)
+ <-done
+ f.noScratch(t)
+ })
+ t.Run("cancelStopsBeforeCleanup", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ started := make(chan struct{})
+ f.run = func(ctx context.Context, _ string) error { close(started); <-ctx.Done(); return ctx.Err() }
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan error, 1)
+ go func() { _, e := f.client.SnapshotDemo(ctx, f.d, f.op, strings.NewReader("data"), 4, nil, 0); done <- e }()
+ <-started
+ cancel()
+ select {
+ case e := <-done:
+ if e == nil {
+ t.Fatal("cancel succeeded")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("cancel hung")
+ }
+ f.noScratch(t)
+ if f.stopped == 0 {
+ t.Fatal("cancel left unit")
+ }
+ })
+ t.Run("restartClearsLeftovers", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ os.Mkdir(filepath.Join(f.p.root, f.op), 0700)
+ os.WriteFile(filepath.Join(f.p.root, f.op, "leftover"), []byte("partial"), 0600)
+ if e := f.p.initialize(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ f.noScratch(t)
+ if f.stopped == 0 {
+ t.Fatal("restart did not stop unit")
+ }
+ })
+ t.Run("failedReapPoisonsAndRetainsScratch", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ f.failStop = true
+ if body, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("data"), 4, nil, 0); e == nil {
+ body.Close()
+ t.Fatal("unproven reap succeeded")
+ }
+ if !f.builder.poisoned {
+ t.Fatal("builder remains available")
+ }
+ if _, e := os.Stat(filepath.Join(f.p.root, f.op)); e != nil {
+ t.Fatal("removed live scratch", e)
+ }
+ })
+}
+
+type snapshotCountingReader struct{ read int64 }
+
+func (r *snapshotCountingReader) Read(b []byte) (int, error) {
+ clear(b)
+ r.read += int64(len(b))
+ return len(b), nil
+}
+
+func TestDemoClaimExportBoundedStreaming(t *testing.T) {
+ t.Run("overLimitWhileStreaming", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ input := &snapshotCountingReader{}
+ in := demoSnapshotRequest{Demo: f.d, OperationID: f.op, TransferID: f.op, DBBytes: democlaim.MaxSnapshotBytes}
+ reader, kind, err := snapshotMultipart(in, input, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest("POST", "/demo-snapshot", reader)
+ req.Header.Set("Content-Type", kind)
+ out := httptest.NewRecorder()
+ f.s.Handler().ServeHTTP(out, req)
+ if out.Code != 400 || f.started != 0 || input.read != democlaim.MaxSnapshotBytes+1 {
+ t.Fatal("stream not bounded", out.Code, f.started, input.read)
+ }
+ f.noScratch(t)
+ })
+ t.Run("reservationBeforeData", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ f.s.Statfs = func(string) (uint64, uint64, error) { return 1, 1, nil }
+ input := &snapshotCountingReader{}
+ in := demoSnapshotRequest{Demo: f.d, OperationID: f.op, TransferID: f.op, DBBytes: democlaim.MaxSnapshotBytes}
+ reader, kind, _ := snapshotMultipart(in, input, nil)
+ req := httptest.NewRequest("POST", "/demo-snapshot", reader)
+ req.Header.Set("Content-Type", kind)
+ out := httptest.NewRecorder()
+ f.s.Handler().ServeHTTP(out, req)
+ // multipart may prefetch one 4 KiB block while parsing metadata.
+ if out.Code != 507 || input.read > 4096 || f.started != 0 {
+ t.Fatal("data consumed before reservation", out.Code, input.read)
+ }
+ f.noScratch(t)
+ })
+ t.Run("holdChangedAfterInput", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ before := f.p.prepare
+ f.p.prepare = func(ctx context.Context, id string) error { err := before(ctx, id); f.rt.HoldOp = "other"; return err }
+ if body, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("data"), 4, nil, 0); e == nil {
+ body.Close()
+ t.Fatal("changed hold accepted")
+ }
+ if f.started != 0 {
+ t.Fatal("started after hold changed")
+ }
+ f.noScratch(t)
+ })
+ t.Run("deadlineStopsWorker", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ f.run = func(ctx context.Context, _ string) error {
+ deadline, ok := ctx.Deadline()
+ if !ok || time.Until(deadline) > democlaim.SnapshotWindow {
+ t.Error("unbounded worker")
+ }
+ <-ctx.Done()
+ return ctx.Err()
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 30*time.Millisecond)
+ defer cancel()
+ if body, e := f.client.SnapshotDemo(ctx, f.d, f.op, strings.NewReader("data"), 4, nil, 0); e == nil {
+ body.Close()
+ t.Fatal("deadline ignored")
+ }
+ f.noScratch(t)
+ if f.stopped == 0 {
+ t.Fatal("worker not stopped")
+ }
+ })
+ t.Run("earlyCloseWaitsForCleanup", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ body, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("data"), 4, nil, 0)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = body.Close(); e != nil {
+ t.Fatal(e)
+ }
+ if e = body.Close(); e != nil {
+ t.Fatal("close not idempotent", e)
+ }
+ f.noScratch(t)
+ })
+ t.Run("failedUnmountPoisons", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ f.p.unmount = func(context.Context, string) error { return errors.New("mounted") }
+ body, e := f.client.SnapshotDemo(t.Context(), f.d, f.op, strings.NewReader("data"), 4, nil, 0)
+ if e != nil {
+ t.Fatal(e)
+ }
+ io.Copy(io.Discard, body)
+ if e = body.Close(); e == nil {
+ t.Fatal("cleanup failure hidden")
+ }
+ if !f.builder.poisoned || f.p.ready.Load() {
+ t.Fatal("unclean worker stays ready")
+ }
+ })
+ t.Run("restartRejectsSymlink", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ other := t.TempDir()
+ os.WriteFile(filepath.Join(other, "sentinel"), []byte("keep"), 0600)
+ os.Symlink(other, filepath.Join(f.p.root, f.op))
+ if e := f.p.initialize(t.Context()); e == nil {
+ t.Fatal("startup followed scratch symlink")
+ }
+ if _, e := os.Stat(filepath.Join(other, "sentinel")); e != nil {
+ t.Fatal("sibling removed")
+ }
+ })
+ t.Run("missingInstalledRestrictions", func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ f.p.assertUnit = func(context.Context, string) error { return democlaim.ErrSnapshot }
+ if e := f.p.initialize(t.Context()); e == nil || f.p.ready.Load() {
+ t.Fatal("startup did not verify snapshot template")
+ }
+ })
+ t.Run("ordinaryBoxHasNoDoor", func(t *testing.T) {
+ s := &Server{}
+ for _, path := range []string{"/demo-snapshot", "/demo-snapshot/close"} {
+ out := httptest.NewRecorder()
+ s.Handler().ServeHTTP(out, httptest.NewRequest("POST", path, nil))
+ if out.Code != 404 {
+ t.Fatal(path, out.Code)
+ }
+ }
+ })
+}
+
+func TestDemoClaimSnapshotCloseStalledInput(t *testing.T) {
+ f := newSnapshotFixture(t)
+ prepared := make(chan struct{})
+ prepare := f.p.prepare
+ f.p.prepare = func(ctx context.Context, id string) error { e := prepare(ctx, id); close(prepared); return e }
+ transfer, _ := demobuild.NewJobID()
+ in := demoSnapshotRequest{Demo: f.d, OperationID: f.op, TransferID: transfer, DBBytes: 1 << 20}
+ var prefix bytes.Buffer
+ mw := multipart.NewWriter(&prefix)
+ part, _ := mw.CreateFormField("metadata")
+ json.NewEncoder(part).Encode(in)
+ mw.CreateFormField("db")
+ conn, e := f.client.Dial(t.Context(), "")
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer conn.Close()
+ fmt.Fprintf(conn, "POST /demo-snapshot HTTP/1.1\r\nHost: control\r\nContent-Type: %s\r\nContent-Length: 1048576\r\n\r\n", mw.FormDataContentType())
+ conn.Write(prefix.Bytes())
+ select {
+ case <-prepared:
+ case <-time.After(time.Second):
+ t.Fatal("request did not reach input")
+ }
+ start := time.Now()
+ if e = f.client.closeDemoSnapshot(in); e != nil {
+ t.Fatal(e)
+ }
+ if time.Since(start) > time.Second {
+ t.Fatal("close did not interrupt input")
+ }
+ f.noScratch(t)
+ if f.started != 0 {
+ t.Fatal("stalled body started worker")
+ }
+}
+
+func (b *snapshotBuilderFake) Readiness(context.Context) (demobuild.WorkerReady, error) {
+ return demobuild.WorkerReady{Capability: "anonymous-demo-v1", GOARCH: "arm64", BundleSHA256: strings.Repeat("b", 64), Slots: 1}, nil
+}
+func TestDemoClaimSnapshotRootCapability(t *testing.T) {
+ f := newSnapshotFixture(t)
+ for _, ready := range []bool{true, false} {
+ f.p.ready.Store(ready)
+ out := httptest.NewRecorder()
+ f.s.Handler().ServeHTTP(out, httptest.NewRequest("GET", "/demo-build/ready", nil))
+ var got demobuild.WorkerReady
+ if e := json.Unmarshal(out.Body.Bytes(), &got); e != nil {
+ t.Fatal(e)
+ }
+ if (got.ClaimCapability == democlaim.Capability) != ready {
+ t.Fatal("wrong root capability", got)
+ }
+ }
+}
+
+func TestDemoClaimSnapshotReadinessIdentity(t *testing.T) {
+ f := newSnapshotFixture(t)
+ f.p.assertUnit = func(_ context.Context, id string) error {
+ if !demobuild.ValidJobID(id) {
+ return errors.New("readiness left an unrecoverable unit name")
+ }
+ return nil
+ }
+ if e := f.p.initialize(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+}
diff --git a/internal/instancectl/demo_snapshot_unit_test.go b/internal/instancectl/demo_snapshot_unit_test.go
new file mode 100644
index 000000000..96b7f98f6
--- /dev/null
+++ b/internal/instancectl/demo_snapshot_unit_test.go
@@ -0,0 +1,109 @@
+package instancectl
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestDemoClaimSnapshotEffectiveUnit(t *testing.T) {
+ const properties = `Type=exec
+RemainAfterExit=yes
+DynamicUser=yes
+Restart=no
+MemoryMax=268435456
+MemorySwapMax=0
+TasksMax=32
+CPUQuotaPerSecUSec=500ms
+RuntimeMaxUSec=2min
+TimeoutStopUSec=5s
+KillMode=control-group
+SendSIGKILL=yes
+OOMPolicy=kill
+LimitFSIZE=268435456
+LimitFSIZESoft=268435456
+WorkingDirectory=/work
+ProtectSystem=strict
+ProtectHome=yes
+PrivateNetwork=yes
+PrivateDevices=yes
+PrivateIPC=yes
+PrivatePIDs=yes
+RestrictAddressFamilies=AF_UNIX
+CapabilityBoundingSet=
+AmbientCapabilities=
+NoNewPrivileges=yes
+RestrictNamespaces=yes
+ProtectControlGroups=yes
+ProtectProc=invisible
+ProcSubset=pid
+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=
+RootDirectory=
+RootImage=
+ReadWritePaths=
+TemporaryFileSystem=/data:ro /run:ro /var:ro /opt:ro /etc:ro /tmp:ro /dev/shm:ro /dev/mqueue:ro /dev/pts:ro
+Environment=HOME=/work TMPDIR=/work GOMEMLIMIT=192MiB
+IPAddressDeny=0.0.0.0/0 ::/0
+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 }
+BindReadOnlyPaths=/opt/carlos/carlos:/snapshot-worker:rbind
+`
+ for _, fault := range []string{"none", "memory", "swap", "tasks", "runtime", "killMode", "slice", "network", "credentials", "siblingBind", "writableOutsideQuota", "extraEnvironment", "rootImage", "executable", "missingProperty"} {
+ t.Run(fault, func(t *testing.T) {
+ f := newSnapshotFixture(t)
+ raw := properties + "BindPaths=" + filepath.Join(f.p.root, f.op, "work") + ":/work:rbind\n"
+ switch fault {
+ case "memory":
+ raw = strings.ReplaceAll(raw, "MemoryMax=268435456", "MemoryMax=infinity")
+ case "swap":
+ raw = strings.ReplaceAll(raw, "MemorySwapMax=0", "MemorySwapMax=infinity")
+ case "tasks":
+ raw = strings.ReplaceAll(raw, "TasksMax=32", "TasksMax=infinity")
+ case "runtime":
+ raw = strings.ReplaceAll(raw, "RuntimeMaxUSec=2min", "RuntimeMaxUSec=infinity")
+ case "killMode":
+ raw = strings.ReplaceAll(raw, "KillMode=control-group", "KillMode=process")
+ case "slice":
+ raw = strings.ReplaceAll(raw, "Slice=system.slice", "Slice=other.slice")
+ case "network":
+ raw = strings.ReplaceAll(raw, "PrivateNetwork=yes", "PrivateNetwork=no")
+ case "credentials":
+ raw = strings.ReplaceAll(raw, "/etc:ro ", "")
+ case "siblingBind":
+ raw = strings.ReplaceAll(raw, ":/work:rbind", ":/work:rbind /data/sibling:/sibling:rbind")
+ case "writableOutsideQuota":
+ raw = strings.ReplaceAll(raw, "ReadWritePaths=\n", "ReadWritePaths=/var\n")
+ case "extraEnvironment":
+ raw = strings.ReplaceAll(raw, "GOMEMLIMIT=192MiB", "GOMEMLIMIT=192MiB LD_PRELOAD=/work/preload")
+ case "rootImage":
+ raw = strings.ReplaceAll(raw, "RootImage=\n", "RootImage=/work/image\n")
+ case "executable":
+ raw = strings.ReplaceAll(raw, "__demo-snapshot ;", "__demo-snapshot /data/credentials ;")
+ case "missingProperty":
+ raw = strings.ReplaceAll(raw, "PrivatePIDs=yes\n", "")
+ }
+ f.s.Systemctl = func(context.Context, ...string) (string, error) { return raw, nil }
+ err := f.p.checkUnit(t.Context(), f.op)
+ if (err == nil) != (fault == "none") {
+ t.Fatal("effective restrictions verdict", err)
+ }
+ })
+ }
+}
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index e3319e7e8..d2140745a 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -51,6 +51,7 @@ type Server struct {
DemoRoutes func() ([]registry.Route, error)
DemoPurgeGuard func(context.Context, func() error) error
demoLocks sync.Map
+ snapshots *demoSnapshotSupervisor
ClaimStop http.Handler
// ClaimHeldRelease is the moves held-release route's handler (moves
@@ -356,6 +357,9 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
if builder != nil {
s.DemoBuilder = builder
}
+ if s.DemoBox {
+ s.snapshots = newDemoSnapshotSupervisor(s)
+ }
go s.probeLoop(ctx, firstProbe)
go s.diskLoop(ctx)
go s.Egress.Loop(ctx, s.DiskEvery)
@@ -370,6 +374,11 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
+ if s.snapshots != nil {
+ if err := s.snapshots.initialize(ctx); err != nil {
+ return err
+ }
+ }
if s.DemoBuilder != nil {
done := make(chan struct{})
go func() {
@@ -472,6 +481,8 @@ func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
if s.DemoBox {
mux.HandleFunc("POST /demo-freeze", s.handleDemoFreeze)
+ mux.HandleFunc("POST /demo-snapshot", s.handleDemoSnapshot)
+ mux.HandleFunc("POST /demo-snapshot/close", s.handleDemoSnapshotClose)
mux.HandleFunc("POST /demo-purge", s.handleDemoPurge)
mux.HandleFunc("POST /demo-build", s.handleDemoBuild)
mux.HandleFunc("GET /demo-build/ready", s.handleDemoBuildReady)
diff --git a/internal/provision/agent_start_demo_3_census_test.go b/internal/provision/agent_start_demo_3_census_test.go
index 68a6c7359..57c5c6447 100644
--- a/internal/provision/agent_start_demo_3_census_test.go
+++ b/internal/provision/agent_start_demo_3_census_test.go
@@ -5,10 +5,14 @@ package provision
// write or record key. runningThings was changed by Task 2: it records hosts
// already counted, then adds the outstanding SQL claim reservations. Its
// only object-store access remains the same bounded prefix lists. Neither
-// unit bypasses WriteRecord. Independent branch review is still pending.
+// unit bypasses WriteRecord. Part 3d also reviews Part 3c's main dispatch:
+// __demo-snapshot accepts no arguments, runs the fixed non-root worker and
+// returns before public dispatch. The instances/sidecars literals and their
+// calls are unchanged; no new record write. Independent review is pending.
func agentStartDemo3WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), agentStartDemo2WriteCensusInventory()...)
for _, next := range []censusEntry{
+ {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "10fd9b177a6bfbf46dac51134a3b1db2212c234ff9e35035c08de329bf505545"},
{"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "80ba9d52a062a71915bb49bfe0a1315bb0d3dfe6fc866abd957dcda8ba091250"},
{"internal/console/plancaps.go", "Server.runningThings", "key-site", "key:ParseRecordKey,key:RecordsPrefix", "5079fd758e620905ab39fdfe6b44ac1214ab155abb988b0edfa395a2a6d83aab"},
} {