carlos / platform Public

feat: freeze demo data for a bounded claim export

Add signed claim work, the authenticated box transport contract, checked
DB/WAL copying, and the identity-only root freeze primitive. Preserve purge
behavior through shared stop proof and add targeted refusal tests.

This is the authorized Task 3 subset. Persistent holds, the claim executor,
the isolated snapshot service and capability activation remain for
continuation. Targeted tests and vet pass; the root census intentionally
awaits the controller's single overlay and independent review.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev aaba81601fd7d18eb3b8f69f0422e7f4b90ccd07 parent 8b202f2
16 files changed, +1,467 −58
  • internal/demobuild/claim_test.go +33 −0
  • internal/demobuild/job.go +9 −6
  • internal/democlaim/protocol.go +39 −0
  • internal/democlaim/snapshot.go +202 −0
  • internal/democlaim/snapshot_test.go +182 −0
  • internal/democlaim/source_linux.go +124 −0
  • internal/democlaim/source_other.go +17 −0
  • internal/democlaim/work.go +110 −0
  • internal/democlaim/work_test.go +98 −0
  • internal/host/demo_claim.go +119 −0
  • internal/host/demo_claim_linux_test.go +92 −0
  • internal/host/demo_claim_test.go +82 −0
  • internal/instancectl/demo_claim.go +105 −0
  • internal/instancectl/demo_claim_test.go +189 −0
  • internal/instancectl/demo_cleanup.go +65 −52
  • internal/instancectl/server.go +1 −0

CI failed — run details

Intent

Attributed to this commit: 8.54 g CO₂e (997,260 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/claim_test.go b/internal/demobuild/claim_test.go
new file mode 100644
index 000000000..76ca06fe3
--- /dev/null
+++ b/internal/demobuild/claim_test.go
@@ -0,0 +1,33 @@
+package demobuild
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func TestDemoClaimWorkCapability(t *testing.T) {
+ build := WorkerReady{Capability: "anonymous-demo-v1", GOARCH: "arm64", BundleSHA256: strings.Repeat("a", 64), Slots: 1}
+ for _, claim := range []string{"", "anonymous-demo-claim-v1", "unknown"} {
+ r := build
+ r.ClaimCapability = claim
+ if !r.Valid() || r.EmptyBuild() {
+ t.Fatal("claim capability changed build readiness")
+ }
+ r = WorkerReady{ClaimCapability: claim, ServingProbe: 3, ServingAck: 4}
+ if r.Valid() || !r.EmptyBuild() {
+ t.Fatal("control metadata treated as build readiness")
+ }
+ }
+ m := StreamMessage{Claim: []byte("signed work"), Serving: &demo.ServingControl{Revision: 1}}
+ raw, err := json.Marshal(m)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got StreamMessage
+ if err = DecodeMessage(raw, &got); err != nil || string(got.Claim) != "signed work" || got.Serving == nil || got.Serving.Revision != 1 {
+ t.Fatalf("stream: %+v %v", got, err)
+ }
+}
diff --git a/internal/demobuild/job.go b/internal/demobuild/job.go
index f0c342174..062262995 100644
--- a/internal/demobuild/job.go
+++ b/internal/demobuild/job.go
@@ -137,12 +137,13 @@ func strictJobJSON(b []byte, v any) error {
// WorkerReady is reported over an authenticated box stream only after root
// verifies its bundle and isolation contract. Slots is the root build budget.
type WorkerReady struct {
- ServingProbe uint64 `json:"servingProbe,omitempty"`
- ServingAck int64 `json:"servingAck,omitempty"`
- Capability string `json:"capability"`
- GOARCH string `json:"goarch"`
- BundleSHA256 string `json:"bundle_sha256"`
- Slots int `json:"slots"`
+ ClaimCapability string `json:"claimCapability,omitempty"`
+ ServingProbe uint64 `json:"servingProbe,omitempty"`
+ ServingAck int64 `json:"servingAck,omitempty"`
+ Capability string `json:"capability"`
+ GOARCH string `json:"goarch"`
+ BundleSHA256 string `json:"bundle_sha256"`
+ Slots int `json:"slots"`
}
func (r WorkerReady) Valid() bool {
@@ -160,6 +161,7 @@ type BuildOutput struct {
// StreamMessage carries signed work or a reconciliation hint. Hints grant no
// authority: the existing pass verifies the policies and records it reads.
type StreamMessage struct {
+ Claim []byte `json:"claim,omitempty"`
Serving *demo.ServingControl `json:"serving,omitempty"`
Retirement []byte `json:"retirement,omitempty"`
Job []byte `json:"job,omitempty"`
@@ -181,6 +183,7 @@ var demoLockJSON string
func DefaultLock() (Lock, error) { return ReadLock(strings.NewReader(demoLockJSON)) }
func (r WorkerReady) EmptyBuild() bool {
+ r.ClaimCapability = ""
r.ServingProbe = 0
r.ServingAck = 0
return r == (WorkerReady{})
diff --git a/internal/democlaim/protocol.go b/internal/democlaim/protocol.go
new file mode 100644
index 000000000..42b6a1d57
--- /dev/null
+++ b/internal/democlaim/protocol.go
@@ -0,0 +1,39 @@
+package democlaim
+
+import "github.com/carlosframework/platform/internal/demobuild"
+
+const (
+ BoxClaimsPath = "/api/box/demo-claims/"
+ SnapshotSHA256Header = "Carlos-Demo-Claim-SHA256"
+ SnapshotBytesHeader = "Carlos-Demo-Claim-Bytes"
+)
+
+// BoxPath accepts only an operation ID and one fixed protocol verb.
+func BoxPath(id, verb string) (string, error) {
+ if !demobuild.ValidJobID(id) || (verb != "pickup" && verb != "snapshot" && verb != "ack") {
+ return "", ErrWork
+ }
+ return BoxClaimsPath + id + "/" + verb, nil
+}
+
+// Pickup returns 200 with the same signed Work. A superseded,
+// aborted or committed action is refused, never refreshed into authority.
+type PickupRequest struct {
+ Action string `json:"action"`
+ Generation uint64 `json:"generation"`
+}
+
+type PickupResponse struct {
+ Work []byte `json:"work"`
+ // RollbackProven is required for abort. It never permits resuming an
+ // expired source and does not override an independent retirement.
+ RollbackProven bool `json:"rollbackProven,omitempty"`
+}
+
+// Ack returns 204 only after recording completion of this exact action.
+// Snapshot returns 204 only after checking its digest and byte count and
+// storing the raw application/vnd.sqlite3 body. Neither response commits a claim.
+type AckRequest struct {
+ Action string `json:"action"`
+ Generation uint64 `json:"generation"`
+}
diff --git a/internal/democlaim/snapshot.go b/internal/democlaim/snapshot.go
new file mode 100644
index 000000000..0545bb9e3
--- /dev/null
+++ b/internal/democlaim/snapshot.go
@@ -0,0 +1,202 @@
+package democlaim
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/carlosframework/platform/internal/lease"
+)
+
+const (
+ MaxSnapshotBytes int64 = 268435456
+ MaxScratchBytes int64 = 805306368
+ SnapshotWindow = 120 * time.Second
+)
+
+var ErrSnapshot = errors.New("DEMO-CLAIM-SNAPSHOT")
+
+type Snapshot struct {
+ Path string `json:"-"`
+ SHA256 string `json:"sha256"`
+ Bytes int64 `json:"bytes"`
+}
+
+// ExportSQLite runs only as an unprivileged caller on a stopped DB or a
+// private copy. Production must additionally impose the helper's OS resource
+// limits. On success the caller owns Path's private parent directory; on
+// failure this function removes it. It never changes the input DB or WAL.
+func ExportSQLite(ctx context.Context, dbDir, dbBase, scratchDir string) (out Snapshot, err error) {
+ if os.Geteuid() == 0 || !filepath.IsAbs(scratchDir) {
+ return out, ErrSnapshot
+ }
+ ctx, cancel := context.WithTimeout(ctx, SnapshotWindow)
+ defer cancel()
+ if err = ctx.Err(); err != nil {
+ return out, err
+ }
+ source, err := OpenSource(dbDir, dbBase)
+ if err != nil {
+ return out, err
+ }
+ defer source.Close()
+ // scratchDir is a caller-owned private directory, never a wire parameter.
+ dir, err := os.MkdirTemp(scratchDir, "snapshot-")
+ if err != nil {
+ return out, err
+ }
+ defer func() {
+ if err != nil {
+ os.RemoveAll(dir)
+ out = Snapshot{}
+ }
+ }()
+ path := filepath.Join(dir, "snapshot.db")
+ if err = copySnapshotFile(ctx, path, source.DB, source.DBBytes); err != nil {
+ return out, err
+ }
+ if source.WAL != nil {
+ if err = copySnapshotFile(ctx, path+"-wal", source.WAL, source.WALBytes); err != nil {
+ return out, err
+ }
+ }
+ if err = source.VerifyUnchanged(); err != nil {
+ return out, err
+ }
+ if err = source.Close(); err != nil {
+ return out, err
+ }
+ if err = checkWALBounds(ctx, path+"-wal"); err != nil {
+ return out, err
+ }
+ if err = lease.TruncateWAL(ctx, path); err != nil {
+ return out, err
+ }
+ if err = lease.CheckDBContext(ctx, path); err != nil {
+ return out, err
+ }
+ f, err := os.Open(path)
+ if err != nil {
+ return out, err
+ }
+ defer f.Close()
+ st, err := f.Stat()
+ if err != nil {
+ return out, err
+ }
+ if st.Size() <= 0 || st.Size() > MaxSnapshotBytes {
+ return out, ErrSnapshot
+ }
+ h := sha256.New()
+ n, err := io.Copy(h, contextReader{ctx: ctx, r: io.LimitReader(f, MaxSnapshotBytes+1)})
+ if err != nil {
+ return out, err
+ }
+ if n != st.Size() {
+ return out, ErrSnapshot
+ }
+ if err = ctx.Err(); err != nil {
+ return out, err
+ }
+ return Snapshot{Path: path, SHA256: hex.EncodeToString(h.Sum(nil)), Bytes: n}, nil
+}
+
+type contextReader struct {
+ ctx context.Context
+ r io.Reader
+}
+
+func (r contextReader) Read(b []byte) (int, error) {
+ if err := r.ctx.Err(); err != nil {
+ return 0, err
+ }
+ return r.r.Read(b)
+}
+
+func copySnapshotFile(ctx context.Context, path string, r io.Reader, size int64) (err error) {
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
+ if err != nil {
+ return err
+ }
+ defer func() { err = errors.Join(err, f.Close()) }()
+ n, err := io.Copy(f, contextReader{ctx: ctx, r: io.LimitReader(r, size+1)})
+ if err != nil {
+ return err
+ }
+ if n != size {
+ return ErrSnapshot
+ }
+ return f.Sync()
+}
+
+// A small WAL can name a huge page number. Refuse that before SQLite can
+// grow the private DB while checkpointing. Validate every checksum too:
+// SQLite can silently discard an invalid WAL, losing committed source data.
+func checkWALBounds(ctx context.Context, path string) error {
+ f, err := os.Open(path)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ st, err := f.Stat()
+ if err != nil {
+ return err
+ }
+ if st.Size() == 0 {
+ return nil
+ }
+ var header [32]byte
+ if _, err = io.ReadFull(f, header[:]); err != nil {
+ return ErrSnapshot
+ }
+ magic := binary.BigEndian.Uint32(header[0:4])
+ page := int64(binary.BigEndian.Uint32(header[8:12]))
+ if (magic != 0x377f0682 && magic != 0x377f0683) || binary.BigEndian.Uint32(header[4:8]) != 3007000 || page < 512 || page > 65536 || page&(page-1) != 0 || (st.Size()-32)%(page+24) != 0 {
+ return ErrSnapshot
+ }
+ var order binary.ByteOrder = binary.LittleEndian
+ if magic == 0x377f0683 {
+ order = binary.BigEndian
+ }
+ s0, s1 := litestream.WALChecksum(order, 0, 0, header[:24])
+ if s0 != binary.BigEndian.Uint32(header[24:28]) || s1 != binary.BigEndian.Uint32(header[28:32]) {
+ return ErrSnapshot
+ }
+ data := make([]byte, page)
+ var frame [24]byte
+ for offset := int64(32); offset < st.Size(); offset += page + 24 {
+ if err = ctx.Err(); err != nil {
+ return err
+ }
+ if _, err = f.ReadAt(frame[:], offset); err != nil {
+ return err
+ }
+ pg, commit := int64(binary.BigEndian.Uint32(frame[0:4])), int64(binary.BigEndian.Uint32(frame[4:8]))
+ if pg == 0 || pg > MaxSnapshotBytes/page || commit > MaxSnapshotBytes/page {
+ return ErrSnapshot
+ }
+ if !bytes.Equal(frame[8:16], header[16:24]) {
+ return ErrSnapshot
+ }
+ if _, err = f.ReadAt(data, offset+24); err != nil {
+ return err
+ }
+ s0, s1 = litestream.WALChecksum(order, s0, s1, frame[:8])
+ s0, s1 = litestream.WALChecksum(order, s0, s1, data)
+ if s0 != binary.BigEndian.Uint32(frame[16:20]) || s1 != binary.BigEndian.Uint32(frame[20:24]) {
+ return ErrSnapshot
+ }
+ }
+ return nil
+}
diff --git a/internal/democlaim/snapshot_test.go b/internal/democlaim/snapshot_test.go
new file mode 100644
index 000000000..88664fe99
--- /dev/null
+++ b/internal/democlaim/snapshot_test.go
@@ -0,0 +1,182 @@
+//go:build linux
+
+package democlaim
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/binary"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "golang.org/x/sys/unix"
+ _ "modernc.org/sqlite"
+)
+
+func walFixture(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ db, e := sql.Open("sqlite", filepath.Join(dir, "source.db"))
+ if e != nil {
+ t.Fatal(e)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { db.Close() })
+ for _, q := 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 _, e = db.Exec(q); e != nil {
+ t.Fatal(e)
+ }
+ }
+ return dir
+}
+
+func fileHash(t *testing.T, p string) string {
+ t.Helper()
+ b, e := os.ReadFile(p)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return fmt.Sprintf("%x", sha256.Sum256(b))
+}
+
+func TestDemoClaimSnapshotWAL(t *testing.T) {
+ t.Run("committedWALOnlyRowAndSourceHashes", func(t *testing.T) {
+ dir := walFixture(t)
+ dbHash, walHash := fileHash(t, filepath.Join(dir, "source.db")), fileHash(t, filepath.Join(dir, "source.db-wal"))
+ s, e := ExportSQLite(t.Context(), dir, "source.db", t.TempDir())
+ if e != nil {
+ t.Fatal(e)
+ }
+ if s.SHA256 != fileHash(t, s.Path) || s.Bytes <= 0 || s.Bytes > MaxSnapshotBytes {
+ t.Fatalf("bad snapshot: %+v", s)
+ }
+ db, e := sql.Open("sqlite", "file:"+s.Path+"?mode=ro")
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer db.Close()
+ var v string
+ if e = db.QueryRow("SELECT value FROM items").Scan(&v); e != nil || v != "committed in WAL" {
+ t.Fatalf("row=%q err=%v", v, e)
+ }
+ if dbHash != fileHash(t, filepath.Join(dir, "source.db")) || walHash != fileHash(t, filepath.Join(dir, "source.db-wal")) {
+ t.Fatal("source altered")
+ }
+ })
+ for _, fault := range []string{"missingDBEvenWithPendingMarker", "symlink", "directorySymlink", "hardlink", "nonregular", "corrupt", "over256MiB", "walHardlink", "walSymlink", "combinedOversize"} {
+ t.Run(fault, func(t *testing.T) {
+ dir := t.TempDir()
+ scratch := t.TempDir()
+ base := filepath.Join(dir, "source.db")
+ must := func(e error) {
+ t.Helper()
+ if e != nil {
+ t.Fatal(e)
+ }
+ }
+ switch fault {
+ case "missingDBEvenWithPendingMarker":
+ must(os.WriteFile(base+".demo-init-pending", []byte("pending"), 0600))
+ case "symlink":
+ must(os.WriteFile(filepath.Join(dir, "target"), []byte("private"), 0600))
+ must(os.Symlink("target", base))
+ case "directorySymlink":
+ real := t.TempDir()
+ must(os.WriteFile(filepath.Join(real, "source.db"), []byte("private"), 0600))
+ must(os.Symlink(real, filepath.Join(dir, "link")))
+ dir = filepath.Join(dir, "link")
+ case "nonregular":
+ must(unix.Mkfifo(base, 0600))
+ default:
+ must(os.WriteFile(base, []byte("not sqlite"), 0600))
+ if fault == "hardlink" {
+ must(os.Link(base, base+".other"))
+ }
+ if fault == "over256MiB" {
+ must(os.Truncate(base, MaxSnapshotBytes+1))
+ }
+ if fault == "walHardlink" {
+ must(os.Link(base, base+"-wal"))
+ }
+ if fault == "walSymlink" {
+ must(os.Symlink(base, base+"-wal"))
+ }
+ if fault == "combinedOversize" {
+ must(os.Truncate(base, MaxSnapshotBytes))
+ must(os.WriteFile(base+"-wal", []byte("wal"), 0600))
+ }
+ }
+ if s, e := ExportSQLite(t.Context(), dir, "source.db", scratch); e == nil || s.Path != "" {
+ t.Fatalf("unsafe snapshot %+v %v", s, e)
+ }
+ entries, e := os.ReadDir(scratch)
+ must(e)
+ if len(entries) != 0 {
+ t.Fatal("failed export left scratch")
+ }
+ })
+ }
+}
+
+func TestDemoClaimExportBounded(t *testing.T) {
+ t.Run("corruptWALCannotDisappear", func(t *testing.T) {
+ dir := walFixture(t)
+ p := filepath.Join(dir, "source.db-wal")
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b[len(b)-1] ^= 1
+ if err = os.WriteFile(p, b, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = ExportSQLite(t.Context(), dir, "source.db", t.TempDir()); err == nil {
+ t.Fatal("corrupt WAL silently discarded")
+ }
+ })
+ t.Run("hugeWALPage", func(t *testing.T) {
+ dir := walFixture(t)
+ p := filepath.Join(dir, "source.db-wal")
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ binary.BigEndian.PutUint32(b[32:36], 0x7fffffff)
+ if err = os.WriteFile(p, b, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = ExportSQLite(t.Context(), dir, "source.db", t.TempDir()); err == nil {
+ t.Fatal("huge WAL page accepted")
+ }
+ })
+ t.Run("cancelRemovesScratch", func(t *testing.T) {
+ dir := walFixture(t)
+ scratch := t.TempDir()
+ ctx, cancel := context.WithCancel(t.Context())
+ cancel()
+ if _, e := ExportSQLite(ctx, dir, "source.db", scratch); e == nil {
+ t.Fatal("cancel ignored")
+ }
+ entries, e := os.ReadDir(scratch)
+ if e != nil || len(entries) != 0 {
+ t.Fatalf("scratch: %v %v", entries, e)
+ }
+ })
+ t.Run("sourceChanged", func(t *testing.T) {
+ dir := walFixture(t)
+ s, e := OpenSource(dir, "source.db")
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer s.Close()
+ if e = os.Truncate(filepath.Join(dir, "source.db"), 1); e != nil {
+ t.Fatal(e)
+ }
+ if e = s.VerifyUnchanged(); e == nil {
+ t.Fatal("changed source accepted")
+ }
+ })
+}
diff --git a/internal/democlaim/source_linux.go b/internal/democlaim/source_linux.go
new file mode 100644
index 000000000..f35c41c40
--- /dev/null
+++ b/internal/democlaim/source_linux.go
@@ -0,0 +1,124 @@
+//go:build linux
+
+package democlaim
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/instancefs"
+ "golang.org/x/sys/unix"
+)
+
+// Source holds the stopped demo's DB and optional WAL by descriptor. No
+// SQLite connection is opened here. The caller must prove stop before entry.
+type Source struct {
+ DB, WAL *os.File
+ DBBytes, WALBytes int64
+ dir *os.File
+ base string
+ dbStat, walStat unix.Stat_t
+}
+
+func OpenSource(dir, base string) (s *Source, err error) {
+ if !filepath.IsAbs(dir) || base == "" || base == "." || base == ".." || strings.ContainsAny(base, "/\\\x00") {
+ return nil, ErrSnapshot
+ }
+ d, err := instancefs.OpenDirBeneath(dir, ".")
+ if err != nil {
+ return nil, err
+ }
+ s = &Source{dir: d, base: base}
+ defer func() {
+ if err != nil {
+ s.Close()
+ s = nil
+ }
+ }()
+ s.DB, s.dbStat, err = s.open(base)
+ if err != nil {
+ return s, err
+ }
+ s.DBBytes = s.dbStat.Size
+ if s.DBBytes <= 0 || s.DBBytes > MaxSnapshotBytes {
+ return s, ErrSnapshot
+ }
+ s.WAL, s.walStat, err = s.open(base + "-wal")
+ if errors.Is(err, os.ErrNotExist) {
+ err = nil
+ }
+ if err != nil {
+ return s, err
+ }
+ if s.WAL != nil {
+ s.WALBytes = s.walStat.Size
+ }
+ if s.WALBytes > MaxSnapshotBytes-s.DBBytes {
+ return s, ErrSnapshot
+ }
+ return s, nil
+}
+
+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})
+ if err != nil {
+ return nil, st, err
+ }
+ if err = unix.Fstat(fd, &st); err != nil {
+ unix.Close(fd)
+ return nil, st, err
+ }
+ if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1 || st.Size < 0 {
+ unix.Close(fd)
+ return nil, st, ErrSnapshot
+ }
+ return os.NewFile(uintptr(fd), name), st, nil
+}
+
+func (s *Source) VerifyUnchanged() error {
+ for _, entry := range []struct {
+ name string
+ file *os.File
+ stat unix.Stat_t
+ }{{s.base, s.DB, s.dbStat}, {s.base + "-wal", s.WAL, s.walStat}} {
+ f, st, err := s.open(entry.name)
+ if entry.file == nil {
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ if f != nil {
+ f.Close()
+ }
+ return ErrSnapshot
+ }
+ if err != nil {
+ return err
+ }
+ f.Close()
+ var held unix.Stat_t
+ if err = unix.Fstat(int(entry.file.Fd()), &held); err != nil {
+ return err
+ }
+ unchanged := func(a, b unix.Stat_t) bool {
+ return a.Dev == b.Dev && a.Ino == b.Ino && a.Size == b.Size && a.Mtim == b.Mtim && a.Ctim == b.Ctim && b.Nlink == 1 && b.Mode&unix.S_IFMT == unix.S_IFREG
+ }
+ if !unchanged(entry.stat, st) || !unchanged(entry.stat, held) {
+ return ErrSnapshot
+ }
+ }
+ return nil
+}
+
+func (s *Source) Close() error {
+ var errs []error
+ for _, f := range []*os.File{s.DB, s.WAL, s.dir} {
+ if f != nil {
+ errs = append(errs, f.Close())
+ }
+ }
+ s.DB, s.WAL, s.dir = nil, nil, nil
+ return errors.Join(errs...)
+}
diff --git a/internal/democlaim/source_other.go b/internal/democlaim/source_other.go
new file mode 100644
index 000000000..a9ec1d708
--- /dev/null
+++ b/internal/democlaim/source_other.go
@@ -0,0 +1,17 @@
+//go:build !linux
+
+package democlaim
+
+import (
+ "errors"
+ "os"
+)
+
+type Source struct {
+ DB, WAL *os.File
+ 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 }
diff --git a/internal/democlaim/work.go b/internal/democlaim/work.go
new file mode 100644
index 000000000..68798ced3
--- /dev/null
+++ b/internal/democlaim/work.go
@@ -0,0 +1,110 @@
+package democlaim
+
+import (
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const (
+ Capability = "anonymous-demo-claim-v1"
+ workDomain = "carlos demo claim work v1\n"
+ AbortDeliveryWindow = 30 * time.Second
+ MaxWorkWire = 8192
+)
+
+var ErrWork = errors.New("DEMO-CLAIM-WORK")
+
+type Work struct {
+ ID string `json:"id"`
+ Demo demo.Descriptor `json:"demo"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Fleet string `json:"fleet"`
+ Box string `json:"box"`
+ Generation uint64 `json:"generation"`
+ Action string `json:"action"`
+ Deadline time.Time `json:"deadline"`
+}
+
+// Hold has no expiry. Only a current console decision may release it.
+type Hold struct {
+ ID string `json:"id"`
+ Generation uint64 `json:"generation"`
+}
+
+func (w Work) valid() bool {
+ if !demobuild.ValidJobID(w.ID) || demo.ValidateBinding(w.Demo, w.Account, w.App, w.Demo.Host, w.Demo.Lifetime, w.Fleet) != nil || !registry.ValidTunnelName(w.Box) || w.Generation == 0 || w.Deadline.IsZero() || w.Deadline.Unix() <= 0 || len(w.Demo.Lifetime) > 128 || strings.ContainsAny(w.Demo.Lifetime, "/\\\x00") {
+ return false
+ }
+ switch w.Action {
+ case "freeze", "export":
+ return !w.Deadline.After(time.Unix(w.Demo.ExpiresAt, 0))
+ case "abort":
+ return true
+ default:
+ return false
+ }
+}
+
+type signedWork struct {
+ Payload string `json:"payload"`
+ Sig string `json:"sig"`
+}
+
+func SignWork(priv ed25519.PrivateKey, w Work) ([]byte, error) {
+ if len(priv) != ed25519.PrivateKeySize || !w.valid() {
+ return nil, ErrWork
+ }
+ b, err := json.Marshal(w)
+ if err != nil {
+ return nil, err
+ }
+ p := base64.StdEncoding.EncodeToString(b)
+ wire, err := json.Marshal(signedWork{Payload: p, Sig: base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(workDomain+p)))})
+ if len(wire) > MaxWorkWire {
+ return nil, ErrWork
+ }
+ return wire, err
+}
+
+func VerifyWork(pub ed25519.PublicKey, wire []byte, now time.Time) (Work, error) {
+ var envelope signedWork
+ if len(pub) != ed25519.PublicKeySize || len(wire) > MaxWorkWire || demobuild.DecodeMessage(wire, &envelope) != nil {
+ return Work{}, ErrWork
+ }
+ sig, err := base64.StdEncoding.Strict().DecodeString(envelope.Sig)
+ if err != nil || !ed25519.Verify(pub, []byte(workDomain+envelope.Payload), sig) {
+ return Work{}, ErrWork
+ }
+ b, err := base64.StdEncoding.Strict().DecodeString(envelope.Payload)
+ var w Work
+ if err != nil || demobuild.DecodeMessage(b, &w) != nil || !w.valid() || !now.Before(w.Deadline) {
+ return Work{}, ErrWork
+ }
+ if w.Action == "abort" && w.Deadline.After(now.Add(AbortDeliveryWindow)) {
+ return Work{}, ErrWork
+ }
+ return w, nil
+}
+
+// MatchCurrent compares the signed delivery with the console's current work.
+// It is not a substitute for authenticated pickup or a local route check.
+func (w Work) MatchCurrent(current Work) error {
+ if !w.valid() || !current.valid() || !w.Deadline.Equal(current.Deadline) {
+ return ErrWork
+ }
+ w.Deadline = time.Time{}
+ current.Deadline = time.Time{}
+ if w != current {
+ return ErrWork
+ }
+ return nil
+}
diff --git a/internal/democlaim/work_test.go b/internal/democlaim/work_test.go
new file mode 100644
index 000000000..15f07238b
--- /dev/null
+++ b/internal/democlaim/work_test.go
@@ -0,0 +1,98 @@
+package democlaim
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+func claimWork(t *testing.T) Work {
+ t.Helper()
+ id, err := demobuild.NewJobID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return Work{ID: id, Demo: demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "bright-otter-42.example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}, Account: "shop", App: "tmp-demo-bright-otter-42", Fleet: "demo", Box: "box", Generation: 1, Action: "freeze", Deadline: time.Now().Add(20 * time.Second).UTC()}
+}
+
+func TestDemoClaimWorkBinding(t *testing.T) {
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := claimWork(t)
+ wire, err := SignWork(priv, w)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"replayCurrent", "wrongBox", "fleet", "lifetime", "generation", "signature", "action", "expired", "replayAborted"} {
+ t.Run(name, func(t *testing.T) {
+ current := w
+ raw := append([]byte(nil), wire...)
+ switch name {
+ case "wrongBox":
+ current.Box = "other"
+ case "fleet":
+ current.Fleet = "other"
+ case "lifetime":
+ current.Demo.Lifetime = "other"
+ case "generation":
+ current.Generation++
+ case "action", "replayAborted":
+ current.Action = "abort"
+ case "signature":
+ raw[len(raw)-4] ^= 1
+ case "expired":
+ current.Deadline = time.Now().Add(-time.Second)
+ }
+ got, err := VerifyWork(pub, raw, time.Now())
+ if err == nil {
+ err = got.MatchCurrent(current)
+ }
+ if (err == nil) != (name == "replayCurrent") {
+ t.Fatalf("accepted=%v err=%v", err == nil, err)
+ }
+ })
+ }
+ for _, action := range []string{"freeze", "export", "abort", "other"} {
+ v := w
+ v.Action = action
+ v.Demo.ExpiresAt = time.Now().Add(-time.Second).Unix()
+ raw, e := SignWork(priv, v)
+ if action == "abort" {
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = VerifyWork(pub, raw, time.Now()); e != nil {
+ t.Fatal(e)
+ }
+ } else if e == nil {
+ t.Fatalf("signed %s past expiry", action)
+ }
+ }
+ w.Action = "abort"
+ w.Deadline = time.Now().Add(31 * time.Second)
+ raw, _ := SignWork(priv, w)
+ if _, e := VerifyWork(pub, raw, time.Now()); e == nil {
+ t.Fatal("unbounded abort delivery")
+ }
+}
+
+func TestDemoClaimWorkStrictWire(t *testing.T) {
+ pub, priv, _ := ed25519.GenerateKey(rand.Reader)
+ w := claimWork(t)
+ b, _ := json.Marshal(w)
+ for _, p := range []string{string(b[:len(b)-1]) + `,"action":"abort"}`, string(b[:len(b)-1]) + `,"path":"/data/other.db"}`, string(b) + `{}`} {
+ payload := base64.StdEncoding.EncodeToString([]byte(p))
+ raw, _ := json.Marshal(map[string]string{"payload": payload, "sig": base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte("carlos demo claim work v1\n"+payload)))})
+ if _, e := VerifyWork(pub, raw, time.Now()); e == nil {
+ t.Fatal("ambiguous wire accepted")
+ }
+ }
+}
diff --git a/internal/host/demo_claim.go b/internal/host/demo_claim.go
new file mode 100644
index 000000000..3faf83747
--- /dev/null
+++ b/internal/host/demo_claim.go
@@ -0,0 +1,119 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
+)
+
+// These transport methods do not freeze, resume or open source data. The
+// claim executor must hold its lifecycle lock through the current decision
+// and the local transition, and recheck before every later side effect.
+func (w *demoWorker) demoClaimRequest(ctx context.Context, work democlaim.Work, verb string, body io.Reader) (*http.Request, error) {
+ if work.Box != w.box || w.cfg.ValidateBinding(work.Demo, work.Account, work.App, work.Demo.Host, work.Demo.Lifetime, work.Fleet) != nil || w.credentials == nil {
+ return nil, democlaim.ErrWork
+ }
+ path, err := democlaim.BoxPath(work.ID, verb)
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", w.base+path, body)
+ if err != nil {
+ return nil, err
+ }
+ req.Header, err = w.headers()
+ if err != nil {
+ return nil, err
+ }
+ return req, nil
+}
+
+func (w *demoWorker) doDemoClaim(req *http.Request) (*http.Response, error) {
+ if w.http == nil {
+ return nil, democlaim.ErrWork
+ }
+ // Never forward box credentials to a redirect target, even when a test
+ // or an embedding caller supplied a client with permissive defaults.
+ client := *w.http
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ return client.Do(req)
+}
+
+func (w *demoWorker) pickupDemoClaimHTTP(ctx context.Context, work democlaim.Work) (democlaim.PickupResponse, error) {
+ var result democlaim.PickupResponse
+ raw, err := json.Marshal(democlaim.PickupRequest{Action: work.Action, Generation: work.Generation})
+ if err != nil {
+ return result, err
+ }
+ req, err := w.demoClaimRequest(ctx, work, "pickup", bytes.NewReader(raw))
+ if err != nil {
+ return result, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ res, err := w.doDemoClaim(req)
+ if err != nil {
+ return result, err
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return result, democlaim.ErrWork
+ }
+ b, err := io.ReadAll(io.LimitReader(res.Body, 2*democlaim.MaxWorkWire+1))
+ if err != nil || len(b) > 2*democlaim.MaxWorkWire || demobuild.DecodeMessage(b, &result) != nil {
+ return democlaim.PickupResponse{}, democlaim.ErrWork
+ }
+ current, err := democlaim.VerifyWork(w.pub, result.Work, time.Now())
+ if err != nil || work.MatchCurrent(current) != nil || (current.Action == "abort" && !result.RollbackProven) {
+ return democlaim.PickupResponse{}, democlaim.ErrWork
+ }
+ return result, nil
+}
+
+func (w *demoWorker) uploadDemoClaimHTTP(ctx context.Context, work democlaim.Work, db io.Reader, size int64, digest string) error {
+ if work.Action != "export" || size <= 0 || size > democlaim.MaxSnapshotBytes || !demobuild.ValidDigest(digest) || db == nil {
+ return democlaim.ErrWork
+ }
+ ctx, cancel := context.WithTimeout(ctx, democlaim.SnapshotWindow)
+ defer cancel()
+ req, err := w.demoClaimRequest(ctx, work, "snapshot", io.LimitReader(db, size))
+ if err != nil {
+ return err
+ }
+ req.ContentLength = size
+ req.Header.Set("Content-Type", "application/vnd.sqlite3")
+ req.Header.Set(democlaim.SnapshotSHA256Header, digest)
+ req.Header.Set(democlaim.SnapshotBytesHeader, strconv.FormatInt(size, 10))
+ return w.demoClaimNoContent(req)
+}
+
+func (w *demoWorker) ackDemoClaimHTTP(ctx context.Context, work democlaim.Work) error {
+ raw, err := json.Marshal(democlaim.AckRequest{Action: work.Action, Generation: work.Generation})
+ if err != nil {
+ return err
+ }
+ req, err := w.demoClaimRequest(ctx, work, "ack", bytes.NewReader(raw))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ return w.demoClaimNoContent(req)
+}
+
+func (w *demoWorker) demoClaimNoContent(req *http.Request) error {
+ res, err := w.doDemoClaim(req)
+ if err != nil {
+ return err
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusNoContent {
+ return democlaim.ErrWork
+ }
+ return nil
+}
diff --git a/internal/host/demo_claim_linux_test.go b/internal/host/demo_claim_linux_test.go
new file mode 100644
index 000000000..522d9dcf4
--- /dev/null
+++ b/internal/host/demo_claim_linux_test.go
@@ -0,0 +1,92 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "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/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The existing witness copies this already-built test binary into its idle,
+// disposable systemd sandbox. It never compiles on the demo box. This covers
+// freeze and source descriptor refusal only, not the pending snapshot unit.
+func TestDemoClaimFreezeDevWitness(t *testing.T) {
+ if os.Getenv("CARLOS_DEMO_CLAIM_DEV_WITNESS") != "1" {
+ t.Skip("R6: real cgroup/freeze/no-follow witness not run; requires a designated disposable systemd sandbox and a prebuilt test binary")
+ }
+ t.Setenv("CARLOS_DEMO_KERNEL_WITNESS", "1")
+ demoKernelAppWitness(t, func(t *testing.T, s *instancectl.Server, host string) {
+ op, err := demobuild.NewJobID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ identity, err := demo.NewIdentity(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ d := demo.Descriptor{ID: identity.ID, Host: host, Lifetime: "witness", ExpiresAt: time.Now().Add(time.Hour).Unix()}
+ name, _, _ := strings.Cut(host, ".")
+ s.DemoConfig = demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}
+ s.DemoPurgeGuard = instanceDemoPurgeGuard
+ s.HostDemo = func(h string) (*registry.Route, error) {
+ if h != host {
+ t.Fatal("foreign lookup")
+ }
+ return &registry.Route{Host: host, Account: "shop", App: demo.AppPrefix + name, DemoID: d.ID, DemoHost: host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt, Status: "moving", HoldOp: "demo-claim/" + op}, nil
+ }
+ dir := filepath.Join("/data/instances", provision.InstanceID(host))
+ base := "claim-witness.db"
+ f, err := os.OpenFile(filepath.Join(dir, base), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = f.Write([]byte("retained source")); err != nil {
+ f.Close()
+ t.Fatal(err)
+ }
+ if err = f.Close(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Remove(filepath.Join(dir, base)); os.Remove(filepath.Join(dir, base+"-wal")) })
+ for i := 0; i < 2; i++ {
+ raw, _ := json.Marshal(instancectl.DemoFreezeRequest{Demo: d, OperationID: op})
+ out := httptest.NewRecorder()
+ s.Handler().ServeHTTP(out, httptest.NewRequest("POST", "/demo-freeze", bytes.NewReader(raw)).WithContext(t.Context()))
+ if out.Code != 204 {
+ t.Fatalf("real freeze: %d %s", out.Code, out.Body.String())
+ }
+ }
+ b, err := os.ReadFile(filepath.Join(dir, base))
+ if err != nil || string(b) != "retained source" {
+ t.Fatal("freeze removed or changed source")
+ }
+ for _, query := range []string{"", "&gen=7", "&gen=8"} {
+ out := httptest.NewRecorder()
+ s.Handler().ServeHTTP(out, httptest.NewRequest("POST", "/start?host="+host+"&role=run"+query, nil))
+ if out.Code != 409 {
+ t.Fatalf("held start: %d", out.Code)
+ }
+ }
+ if err = os.Symlink(base, filepath.Join(dir, base+"-wal")); err != nil {
+ t.Fatal(err)
+ }
+ if source, err := democlaim.OpenSource(dir, base); err == nil {
+ source.Close()
+ t.Fatal("WAL symlink opened")
+ }
+ })
+}
diff --git a/internal/host/demo_claim_test.go b/internal/host/demo_claim_test.go
new file mode 100644
index 000000000..18e0c69f4
--- /dev/null
+++ b/internal/host/demo_claim_test.go
@@ -0,0 +1,82 @@
+package host
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/democlaim"
+)
+
+func TestDemoClaimWorkConsoleContract(t *testing.T) {
+ pub, priv, _ := ed25519.GenerateKey(rand.Reader)
+ id, _ := demobuild.NewJobID()
+ work := democlaim.Work{ID: id, Demo: demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "bright-otter-42.example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}, Account: "shop", App: "tmp-demo-bright-otter-42", Fleet: "demo", Box: "box", Generation: 1, Action: "freeze", Deadline: time.Now().Add(20 * time.Second).UTC()}
+ current := work
+ calls := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if r.Method != "POST" || r.Header.Get("Authorization") != "Bearer test-secret" || r.Header.Get("Carlos-Tunnel-Name") != "demo/box" {
+ t.Error("missing box auth")
+ }
+ switch r.URL.Path {
+ case "/api/box/demo-claims/" + id + "/pickup":
+ var req democlaim.PickupRequest
+ if e := json.NewDecoder(r.Body).Decode(&req); e != nil || req.Action != work.Action || req.Generation != work.Generation {
+ t.Errorf("pickup: %+v %v", req, e)
+ }
+ wire, _ := democlaim.SignWork(priv, current)
+ json.NewEncoder(w).Encode(democlaim.PickupResponse{Work: wire})
+ case "/api/box/demo-claims/" + id + "/snapshot":
+ b, _ := io.ReadAll(r.Body)
+ if string(b) != "sqlite" || r.ContentLength != 6 || r.Header.Get(democlaim.SnapshotBytesHeader) != "6" || r.Header.Get(democlaim.SnapshotSHA256Header) != strings.Repeat("a", 64) {
+ t.Error("snapshot contract")
+ }
+ w.WriteHeader(204)
+ case "/api/box/demo-claims/" + id + "/ack":
+ var ack democlaim.AckRequest
+ if e := json.NewDecoder(r.Body).Decode(&ack); e != nil || ack.Action != "freeze" || ack.Generation != 1 {
+ t.Error("ack contract")
+ }
+ w.WriteHeader(204)
+ default:
+ t.Error("unexpected path")
+ w.WriteHeader(404)
+ }
+ }))
+ defer srv.Close()
+ w := &demoWorker{cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}, box: "box", pub: pub, base: srv.URL, http: srv.Client(), credentials: func() (string, string, bool) { return "demo/box", "test-secret", true }}
+ if _, e := w.pickupDemoClaimHTTP(t.Context(), work); e != nil {
+ t.Fatal(e)
+ }
+ current.Action = "abort"
+ if _, e := w.pickupDemoClaimHTTP(t.Context(), work); e == nil {
+ t.Fatal("stale freeze accepted")
+ }
+ current = work
+ current.Generation++
+ if _, e := w.pickupDemoClaimHTTP(t.Context(), work); e == nil {
+ t.Fatal("generation rebound")
+ }
+ export := work
+ export.Action = "export"
+ if e := w.uploadDemoClaimHTTP(t.Context(), export, strings.NewReader("sqlite"), 6, strings.Repeat("a", 64)); e != nil {
+ t.Fatal(e)
+ }
+ if e := w.ackDemoClaimHTTP(t.Context(), work); e != nil {
+ t.Fatal(e)
+ }
+ before := calls
+ work.Box = "other"
+ if _, e := w.pickupDemoClaimHTTP(t.Context(), work); e == nil || calls != before {
+ t.Fatal("foreign work contacted console")
+ }
+}
diff --git a/internal/instancectl/demo_claim.go b/internal/instancectl/demo_claim.go
new file mode 100644
index 000000000..7c701e25a
--- /dev/null
+++ b/internal/instancectl/demo_claim.go
@@ -0,0 +1,105 @@
+package instancectl
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+type DemoFreezeRequest struct {
+ Demo demo.Descriptor `json:"demo"`
+ OperationID string `json:"operationId"`
+}
+
+func (c *Client) FreezeDemo(ctx context.Context, d demo.Descriptor, operationID string) error {
+ ctx, cancel := context.WithTimeout(ctx, DeadlineControl)
+ defer cancel()
+ raw, err := json.Marshal(DemoFreezeRequest{Demo: d, OperationID: operationID})
+ if err != nil {
+ return err
+ }
+ req, err := http.NewRequestWithContext(ctx, "POST", "http://control/demo-freeze", bytes.NewReader(raw))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ res, err := c.httpClient().Do(req)
+ if err != nil {
+ return err
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusNoContent {
+ return demo.ErrPolicy
+ }
+ return nil
+}
+
+func (s *Server) handleDemoFreeze(w http.ResponseWriter, r *http.Request) {
+ defer r.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(r.Body, 16385))
+ var in DemoFreezeRequest
+ if err != nil || len(raw) > 16384 || demobuild.DecodeMessage(raw, &in) != nil || !demobuild.ValidJobID(in.OperationID) {
+ http.Error(w, "DEMO-POLICY", http.StatusBadRequest)
+ return
+ }
+ // The existing guard serializes root mutations with the host coordinator.
+ if s.DemoPurgeGuard == nil {
+ http.Error(w, "DEMO-POLICY", http.StatusConflict)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+ err = s.DemoPurgeGuard(ctx, func() error { return s.freezeDemoLocal(ctx, in.Demo, in.OperationID) })
+ if err != nil {
+ http.Error(w, "DEMO-POLICY", http.StatusConflict)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// freezeDemoLocal receives identity only. It proves stop again on every
+// replay and never reads or removes database files. The caller must already
+// have durably installed this operation's hold before invoking the root door.
+func (s *Server) freezeDemoLocal(ctx context.Context, d demo.Descriptor, operationID string) error {
+ if !s.DemoBox || !demobuild.ValidJobID(operationID) || !provision.ValidHostShape(d.Host) || s.HostDemo == nil || s.CgroupRoot == "" || s.Systemctl == nil || !s.DemoConfig.BoxMode() {
+ return demo.ErrPolicy
+ }
+ name, _, ok := strings.Cut(d.Host, ".")
+ if !ok || s.DemoConfig.ValidateBinding(d, s.DemoConfig.Account, demo.AppPrefix+name, d.Host, d.Lifetime, s.DemoConfig.Fleet) != nil {
+ return demo.ErrPolicy
+ }
+ defer s.lockDemo(d.Host)()
+ rt, err := s.HostDemo(d.Host)
+ if err != nil {
+ return err
+ }
+ if rt == nil || !rt.IsDemo() || rt.Host != d.Host || rt.DemoID != d.ID || rt.DemoHost != d.Host || rt.DemoLifetime != d.Lifetime || rt.DemoExpiresAt != d.ExpiresAt || rt.Account != s.DemoConfig.Account || rt.App != demo.AppPrefix+name || rt.Status != "moving" || rt.HoldOp != "demo-claim/"+operationID {
+ return demo.ErrPolicy
+ }
+ // A vanished unit cgroup can prove emptiness, but a missing cgroup
+ // hierarchy cannot. Keep the parent check around the stop proof.
+ parent := filepath.Join(s.CgroupRoot, parentSlices)
+ before, err := os.Stat(parent)
+ if err != nil || !before.IsDir() {
+ return demo.ErrPolicy
+ }
+ _, err = s.stopDemoUnits(ctx, d.Host)
+ if err != nil {
+ return err
+ }
+ after, err := os.Stat(parent)
+ if err != nil || !after.IsDir() || !os.SameFile(before, after) {
+ return demo.ErrPolicy
+ }
+ return nil
+}
diff --git a/internal/instancectl/demo_claim_test.go b/internal/instancectl/demo_claim_test.go
new file mode 100644
index 000000000..84376ffb0
--- /dev/null
+++ b/internal/instancectl/demo_claim_test.go
@@ -0,0 +1,189 @@
+package instancectl
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestDemoClaimFreezeClientCancellation(t *testing.T) {
+ started := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer r.Body.Close()
+ var req DemoFreezeRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.OperationID != "operation" || r.URL.Path != "/demo-freeze" || r.Method != "POST" {
+ t.Error("freeze wire changed")
+ }
+ close(started)
+ <-r.Context().Done()
+ }))
+ defer srv.Close()
+ c := &Client{Dial: func(ctx context.Context, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "tcp", srv.Listener.Addr().String())
+ }}
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() { done <- c.FreezeDemo(ctx, demo.Descriptor{}, "operation") }()
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("request did not arrive")
+ }
+ cancel()
+ select {
+ case err := <-done:
+ if err == nil {
+ t.Fatal("cancellation lost")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("freeze did not cancel")
+ }
+}
+
+func TestDemoClaimFreezeRecovery(t *testing.T) {
+ for _, fault := range []string{"restartBeforeAck", "otherHold", "foreignLifetime", "unheld", "noGuard", "unprovenStop", "missingCgroupTree", "unknownCgroup", "populated", "missingRoute", "allGenerations"} {
+ t.Run(fault, func(t *testing.T) {
+ op, _ := demobuild.NewJobID()
+ d := demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: "bright-otter-42.example.com", Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}
+ rt := &registry.Route{Host: d.Host, Account: "shop", App: "tmp-demo-bright-otter-42", DemoID: d.ID, DemoHost: d.Host, DemoLifetime: d.Lifetime, DemoExpiresAt: d.ExpiresAt, Status: "moving", HoldOp: "demo-claim/" + op}
+ cg := t.TempDir()
+ slice := filepath.Join(cg, parentSlices, SliceName(d.Host))
+ if e := os.MkdirAll(slice, 0700); e != nil {
+ t.Fatal(e)
+ }
+ events := "populated 0\n"
+ if fault == "unknownCgroup" {
+ events = "unknown\n"
+ }
+ if fault == "populated" {
+ events = "populated 1\n"
+ }
+ if e := os.WriteFile(filepath.Join(slice, "cgroup.events"), []byte(events), 0600); e != nil {
+ t.Fatal(e)
+ }
+ switch fault {
+ case "otherHold":
+ rt.HoldOp = "other"
+ case "foreignLifetime":
+ rt.DemoLifetime = "other"
+ case "unheld":
+ rt.Status = "ready"
+ case "missingRoute":
+ rt = nil
+ }
+ var stopped []string
+ s := &Server{DemoBox: true, DemoConfig: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}, HostDemo: func(string) (*registry.Route, error) { return rt, nil }, CgroupRoot: cg, cgroupWaitBudget: 10 * time.Millisecond, ExeRoot: t.TempDir(), DropInDir: t.TempDir()}
+ if fault == "missingCgroupTree" {
+ s.CgroupRoot = filepath.Join(cg, "missing")
+ }
+ if e := os.Mkdir(filepath.Join(s.ExeRoot, GenKey(d.Host, 7)), 0700); e != nil {
+ t.Fatal(e)
+ }
+ if e := os.Mkdir(filepath.Join(s.DropInDir, GenUnitName(d.Host, 8)+".d"), 0700); e != nil {
+ t.Fatal(e)
+ }
+ s.Systemctl = func(ctx context.Context, args ...string) (string, error) {
+ switch args[0] {
+ case "list-units":
+ return GenUnitName(d.Host, 6) + " loaded active running\n" + GenUnitName("sibling.example.com", 3) + " loaded active running\n", nil
+ case "stop":
+ stopped = append(stopped, args[1])
+ if fault == "unprovenStop" {
+ return "", errors.New("unproven")
+ }
+ return "", nil
+ case "show":
+ return "ActiveState=inactive\n", nil
+ }
+ t.Fatalf("unexpected command %v", args)
+ return "", nil
+ }
+ if fault != "noGuard" {
+ s.DemoPurgeGuard = func(ctx context.Context, f func() error) error { return f() }
+ }
+ for attempt := 0; attempt < 2; attempt++ {
+ raw, _ := json.Marshal(DemoFreezeRequest{Demo: d, OperationID: op})
+ out := httptest.NewRecorder()
+ s.Handler().ServeHTTP(out, httptest.NewRequest("POST", "/demo-freeze", bytes.NewReader(raw)))
+ want := 409
+ if fault == "restartBeforeAck" || fault == "allGenerations" {
+ want = 204
+ }
+ if out.Code != want {
+ t.Fatalf("status %d want %d: %s", out.Code, want, out.Body.String())
+ }
+ }
+ if fault == "otherHold" || fault == "foreignLifetime" || fault == "unheld" || fault == "missingRoute" || fault == "noGuard" {
+ if len(stopped) != 0 {
+ t.Fatal("refusal stopped something")
+ }
+ }
+ if fault == "allGenerations" || fault == "restartBeforeAck" {
+ for _, unit := range []string{UnitName(RoleRun, d.Host), GenUnitName(d.Host, 6), GenUnitName(d.Host, 7), GenUnitName(d.Host, 8), SliceName(d.Host)} {
+ count := 0
+ for _, got := range stopped {
+ if got == unit {
+ count++
+ }
+ }
+ if count != 2 {
+ t.Fatalf("%s stopped %d times", unit, count)
+ }
+ }
+ }
+ for _, unit := range stopped {
+ if strings.Contains(unit, "sibling") {
+ t.Fatal("sibling stopped")
+ }
+ }
+ if rt != nil && fault == "otherHold" && rt.HoldOp != "other" {
+ t.Fatal("other hold altered")
+ }
+ })
+ }
+}
+
+func TestDemoClaimFreezeStartGate(t *testing.T) {
+ for _, query := range []string{"", "&gen=7", "&gen=8&exe=/opt/carlos/versions/v1/shop/app"} {
+ for _, missing := range []bool{false, true} {
+ s := &Server{DemoBox: true, HostDemo: func(string) (*registry.Route, error) {
+ if missing {
+ return nil, nil
+ }
+ return &registry.Route{DemoID: "AAAAAAAAAAAAAAAAAAAAAA", Status: "moving", HoldOp: "demo-claim/operation"}, nil
+ }}
+ called := false
+ h := s.demoHandler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }))
+ out := httptest.NewRecorder()
+ h.ServeHTTP(out, httptest.NewRequest("POST", "/start?host=bright-otter-42.example.com"+query, nil))
+ if called || out.Code != 409 {
+ t.Fatal("held or unknown start dispatched")
+ }
+ }
+ }
+}
+
+func TestDemoClaimFreezeStrictRequest(t *testing.T) {
+ for _, body := range []string{`{"path":"/data/source.db"}`, `{"operationId":"one","operationId":"two"}`, strings.Repeat(" ", 16385) + `{}`} {
+ s := &Server{DemoBox: true, DemoPurgeGuard: func(context.Context, func() error) error { t.Fatal("invalid request reached guard"); return nil }}
+ out := httptest.NewRecorder()
+ s.Handler().ServeHTTP(out, httptest.NewRequest("POST", "/demo-freeze", strings.NewReader(body)))
+ if out.Code != 400 {
+ t.Fatalf("status=%d", out.Code)
+ }
+ }
+}
diff --git a/internal/instancectl/demo_cleanup.go b/internal/instancectl/demo_cleanup.go
index 1d574d952..d6f8d2efc 100644
--- a/internal/instancectl/demo_cleanup.go
+++ b/internal/instancectl/demo_cleanup.go
@@ -119,11 +119,62 @@ func (s *Server) purgeDemoWithJobs(ctx context.Context, d demo.Descriptor, jobs
}
ctx, cancel := context.WithTimeout(ctx, s.waitBudget())
defer cancel()
- out, err := s.Systemctl(ctx, "list-units", "--all", "--plain", "--no-legend", "--no-pager")
+ units, err := s.stopDemoUnits(ctx, d.Host)
if err != nil {
return err
}
- units := map[string]bool{UnitName(RoleRun, d.Host): true}
+ // Every path is a derived direct child. RemoveAllBeneath holds directory
+ // descriptors and never follows a leaf or intermediate symlink.
+ remove := func(root, name string) error {
+ if root == "" {
+ return nil
+ }
+ err := instancefs.RemoveAllBeneath(root, name)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return err
+ }
+ // Delete the database before its local initialization proof.
+ dir := filepath.Join(s.DataRoot, id)
+ for _, suffix := range []string{".db-wal", ".db-shm", ".db"} {
+ if err := instancefs.RemoveBeneath(dir, d.Host+suffix); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ }
+ if err = remove(s.DataRoot, id); err != nil {
+ return err
+ }
+ if err = remove(s.DemoRunRoot, id); err != nil {
+ return err
+ }
+ if err = remove(s.ExeRoot, id); err != nil {
+ return err
+ }
+ for unit := range units {
+ if err = remove(s.DropInDir, unit+".d"); err != nil {
+ return err
+ }
+ if _, n, ok := ParseGenUnitName(unit); ok {
+ if err = remove(s.ExeRoot, GenKey(d.Host, n)); err != nil {
+ return err
+ }
+ }
+ }
+ return s.purgeDemoVersions(ctx, d)
+}
+
+// stopDemoUnits is shared by reversible claim freeze and permanent purge.
+// Callers hold lockDemo and validate their own operation's persistent hold.
+func (s *Server) stopDemoUnits(ctx context.Context, host string) (map[string]bool, error) {
+ id := provision.InstanceID(host)
+ ctx, cancel := context.WithTimeout(ctx, s.waitBudget())
+ defer cancel()
+ out, err := s.Systemctl(ctx, "list-units", "--all", "--plain", "--no-legend", "--no-pager")
+ if err != nil {
+ return nil, err
+ }
+ units := map[string]bool{UnitName(RoleRun, host): true}
for _, line := range strings.Split(out, "\n") {
f := strings.Fields(line)
if len(f) == 0 {
@@ -145,12 +196,12 @@ func (s *Server) purgeDemoWithJobs(ctx context.Context, d demo.Descriptor, jobs
continue
}
if err != nil {
- return err
+ return nil, err
}
for _, e := range entries {
if root == s.ExeRoot {
if iid, n, ok := ParseGenKey(e.Name()); ok && iid == id {
- units[GenUnitName(d.Host, n)] = true
+ units[GenUnitName(host, n)] = true
}
}
if root == s.DropInDir {
@@ -163,65 +214,27 @@ func (s *Server) purgeDemoWithJobs(ctx context.Context, d demo.Descriptor, jobs
}
for unit := range units {
if _, err = s.Systemctl(ctx, "stop", unit); err != nil {
- return err
+ return nil, err
}
}
- if _, err = s.Systemctl(ctx, "stop", SliceName(d.Host)); err != nil {
- return err
+ if _, err = s.Systemctl(ctx, "stop", SliceName(host)); err != nil {
+ return nil, err
}
for unit := range units {
out, err = s.Systemctl(ctx, "show", unit, "-p", "ActiveState")
if err != nil {
- return err
+ return nil, err
}
state := parseShow(out)["ActiveState"]
if state != "inactive" && state != "failed" {
- return demo.ErrPolicy
- }
- if err = WaitCgroupEmpty(ctx, s.CgroupRoot, SliceName(d.Host), unit, time.Millisecond); err != nil {
- return err
+ return nil, demo.ErrPolicy
}
- }
- if err = WaitCgroupEmpty(ctx, s.CgroupRoot, SliceName(d.Host), "", time.Millisecond); err != nil {
- return err
- }
- // Every path is a derived direct child. RemoveAllBeneath holds directory
- // descriptors and never follows a leaf or intermediate symlink.
- remove := func(root, name string) error {
- if root == "" {
- return nil
- }
- err := instancefs.RemoveAllBeneath(root, name)
- if errors.Is(err, os.ErrNotExist) {
- return nil
- }
- return err
- }
- // Delete the database before its local initialization proof.
- dir := filepath.Join(s.DataRoot, id)
- for _, suffix := range []string{".db-wal", ".db-shm", ".db"} {
- if err := instancefs.RemoveBeneath(dir, d.Host+suffix); err != nil && !errors.Is(err, os.ErrNotExist) {
- return err
+ if err = WaitCgroupEmpty(ctx, s.CgroupRoot, SliceName(host), unit, time.Millisecond); err != nil {
+ return nil, err
}
}
- if err = remove(s.DataRoot, id); err != nil {
- return err
- }
- if err = remove(s.DemoRunRoot, id); err != nil {
- return err
- }
- if err = remove(s.ExeRoot, id); err != nil {
- return err
+ if err = WaitCgroupEmpty(ctx, s.CgroupRoot, SliceName(host), "", time.Millisecond); err != nil {
+ return nil, err
}
- for unit := range units {
- if err = remove(s.DropInDir, unit+".d"); err != nil {
- return err
- }
- if _, n, ok := ParseGenUnitName(unit); ok {
- if err = remove(s.ExeRoot, GenKey(d.Host, n)); err != nil {
- return err
- }
- }
- }
- return s.purgeDemoVersions(ctx, d)
+ return units, nil
}
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index 90da0756c..e3319e7e8 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -471,6 +471,7 @@ func (s *Server) peerOK(c net.Conn) error { return s.PeerOK(c) }
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
if s.DemoBox {
+ mux.HandleFunc("POST /demo-freeze", s.handleDemoFreeze)
mux.HandleFunc("POST /demo-purge", s.handleDemoPurge)
mux.HandleFunc("POST /demo-build", s.handleDemoBuild)
mux.HandleFunc("GET /demo-build/ready", s.handleDemoBuildReady)