carlos / platform Public

feat: build demo source in isolated offline units

Add the root-owned bounded offline builder, verified toolchain bundles, durable admission and cleanup, isolated systemd units, readiness proof and client transport. Preserve sanitized build diagnostics through worker results and job status.

Targeted demo, installer and compatibility tests pass across instancectl, demobuild, host and console; vet passes for all four packages. The gated real systemd witness was skipped and remains controller work, along with independent review and census approval.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev b21e4da8dee3c6fcba143d97c65a4641fccc7536 parent 5108690
28 files changed, +2,582 −33
  • internal/console/apidemo.go +2 −1
  • internal/console/demo_build_test.go +22 −0
  • internal/console/demo_jobs.go +8 −2
  • internal/demobuild/bundle.go +151 −0
  • internal/demobuild/bundle_test.go +76 −0
  • internal/demobuild/diagnostics.go +13 −2
  • internal/demobuild/job.go +13 −11
  • internal/demobuild/probe.go +70 −0
  • internal/demobuild/runner.go +181 −0
  • internal/demobuild/runner_test.go +122 −0
  • internal/demobuild/security_linux.go +63 −0
  • internal/demobuild/security_other.go +10 −0
  • internal/demobuild/unit.go +497 −0
  • internal/demobuild/unit_kernel_linux_test.go +321 −0
  • internal/demobuild/unit_test.go +135 −0
  • internal/demobuild/worker.go +278 −0
  • internal/demobuild/worker_test.go +162 −0
  • internal/host/claimunit.go +17 −2
  • internal/host/demo_build_linux_test.go +153 −0
  • internal/host/demo_jobs.go +18 −11
  • internal/host/demo_toolchain.go +8 −0
  • internal/host/systemapply.go +5 −2
  • internal/host/systemunits.go +1 −1
  • internal/host/units/carlos-demo-build@.service +63 −0
  • internal/host/units/carlos-demo-builds.slice +9 −0
  • internal/instancectl/demo_build.go +133 −0
  • internal/instancectl/demo_build_test.go +31 −0
  • internal/instancectl/server.go +20 −1

CI cancelled — superseded by a newer push — run details

Intent

Human

<task-notification> <task-id>b5hpwo3tw</task-id> <tool-use-id>toolu_01PUMW95nUDb5Kqw3Dooiymx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/b5hpwo3tw.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 5 continuation" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a387dba0c8be6231d</task-id> <tool-use-id>toolu_01DXcBtM1tSRjxtdgJS47SLB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/a387dba0c8be6231d.output</output-file> <status>completed</status> <summary>Agent "Review Task 5 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Verdict: NOT READY (P1-1) - P1-1: The worker uses `CARLOS_TUNNEL_URL` as its base (`internal/host/demo_jobs.go:91`). That is the hub's tunnel hostname, and the edge only serves `/register` and `/store/` there (`internal/edge/edge.go:1907-1918`, `internal/edge/tunnel.go:143`). So the stream, pickup and result requests all get 404, and no build can be delivered. The run relay instead attaches to the console origin. The tests point straight at the console, so they miss this. - P2-1: `RunDemoJobs` runs every 2 s and opens `demoTx` each time. `demoTx` does a real write (`UPDATE demo_settings SET ip_salt=ip_salt`, `internal/console/demo_store.go:94`), so an idle console commits about 43k writes a day. If console.db is replicated, that is a steady per-tick request stream. - P2-2: The new `GET /api/box/demo-builds` stream is not exempt from the lifetimes cutover gate (`lifetimesExempt`) or from `consolePerfSkip`, unlike the other box streams. On a console that has not cut over yet, a connected worker holds a legacy unit open, so cutover never finishes. - P2-3: Build output (up to 32 MiB) is stored as a BLOB in console.db (`internal/console/demo_jobs.go:50`, `:404`), not as the brief's console-local spool. That holds the writer lock during the write and bloats the database and its replicas. - P2-4: The worker rejects a picked grant if `time.Until(deadline) &gt; 180s` (`internal/host/demo_jobs.go:145`). If the worker's clock is even slightly behind the console's, every build fails after pickup. The full review is in `.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-5-review-r1.md`.</result> <usage><subagent_tokens>222772</subagent_tokens><tool_uses>55</tool_uses><duration_ms>705229</duration_ms></usage> </task-notification>

Attributed to this commit: 11.4 g CO₂e (1,410,330 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-1, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go
index 6b5a8d801..2208aa5d3 100644
--- a/internal/console/apidemo.go
+++ b/internal/console/apidemo.go
@@ -497,7 +497,8 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) {
state = "failed"
}
w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(map[string]any{"jobID": id, "status": state, "diagnostics": demoResultDiagnostics(row.Result)})
+ diagnostics, truncated := demoResultDiagnosticStatus(row.Result)
+ _ = json.NewEncoder(w).Encode(map[string]any{"jobID": id, "status": state, "diagnostics": diagnostics, "diagnosticsTruncated": truncated})
}
diff --git a/internal/console/demo_build_test.go b/internal/console/demo_build_test.go
new file mode 100644
index 000000000..f27cec6ad
--- /dev/null
+++ b/internal/console/demo_build_test.go
@@ -0,0 +1,22 @@
+package console
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+func TestDemoBuildStatusDiagnostics(t *testing.T) {
+ raw, _ := json.Marshal(demobuild.Result{Diagnostics: []demobuild.Diagnostic{{File: "main.go", Line: 1, Message: "undefined: item"}}, DiagnosticsTruncated: true})
+ d, cut := demoResultDiagnosticStatus(raw)
+ if !cut || len(d) != 1 || d[0].Message != "undefined: item" {
+ t.Fatal(d, cut)
+ }
+ raw, _ = json.Marshal(demobuild.Result{Diagnostics: []demobuild.Diagnostic{{File: "main.go", Line: 1, Message: strings.Repeat("a ", 20000)}}})
+ _, cut = demoResultDiagnosticStatus(raw)
+ if !cut {
+ t.Fatal("status truncation missing")
+ }
+}
diff --git a/internal/console/demo_jobs.go b/internal/console/demo_jobs.go
index ad541990c..88f7b8255 100644
--- a/internal/console/demo_jobs.go
+++ b/internal/console/demo_jobs.go
@@ -550,15 +550,21 @@ func (s *Server) NotifyDemoBox(box string) {
// demoResultDiagnostics never exposes unchecked worker messages on status.
func demoResultDiagnostics(raw []byte) []demobuild.Diagnostic {
+ diagnostics, _ := demoResultDiagnosticStatus(raw)
+ return diagnostics
+}
+
+func demoResultDiagnosticStatus(raw []byte) ([]demobuild.Diagnostic, bool) {
var r demobuild.Result
if json.Unmarshal(raw, &r) != nil {
- return nil
+ return nil, false
}
var lines strings.Builder
for _, d := range r.Diagnostics {
fmt.Fprintf(&lines, "%s:%d:%s\n", d.File, d.Line, d.Message)
}
- return demobuild.TrimDiagnostics([]byte(lines.String()))
+ diagnostics, truncated := demobuild.TrimDiagnosticsWithStatus([]byte(lines.String()))
+ return diagnostics, truncated || r.DiagnosticsTruncated
}
// putDemoObject is idempotent after partial or uncertain writes. Source is
diff --git a/internal/demobuild/bundle.go b/internal/demobuild/bundle.go
new file mode 100644
index 000000000..f82c025e4
--- /dev/null
+++ b/internal/demobuild/bundle.go
@@ -0,0 +1,151 @@
+package demobuild
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/instancefs"
+)
+
+// MANIFEST is UTF-8 with LF endings and a final LF. The first two lines are
+// "go<TAB>1.26.10" and "modules<TAB><Lock.ModulesDigest()>". Remaining lines,
+// sorted by relative path, are path<TAB>four-digit octal mode<TAB>decimal size
+// <TAB>lowercase SHA-256. Every regular file except MANIFEST occurs exactly
+// once. Symlinks, hard links, special files and writable bundle files fail.
+// The bundle digest hashes these exact manifest bytes, including the final LF.
+func CheckBundle(dir string, lock Lock) (string, error) {
+ return checkBundle(dir, lock, immutableRootFile)
+}
+
+func checkBundle(dir string, lock Lock, trusted func(os.FileInfo) bool) (string, error) {
+ if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir || dir == "/" || strings.ContainsAny(dir, " \t\r\n%\\:,\x00") || lock.validate() != nil {
+ return "", ErrBuild
+ }
+ // Ancestors cannot be exchanged by the agent. They may be root-writable;
+ // the bundle itself is immutable until operators drain and replace it.
+ for p := dir; p != "/"; p = filepath.Dir(p) {
+ st, err := os.Lstat(p)
+ if err != nil || !st.IsDir() || !trusted(st) {
+ return "", ErrBuild
+ }
+ }
+ f, err := instancefs.OpenBeneath(dir, "MANIFEST", os.O_RDONLY, 0)
+ if err != nil {
+ return "", ErrBuild
+ }
+ st, err := f.Stat()
+ if err != nil || !trusted(st) {
+ f.Close()
+ return "", ErrBuild
+ }
+ b, err := io.ReadAll(io.LimitReader(f, 16<<20+1))
+ f.Close()
+ if err != nil || len(b) > 16<<20 || !strings.HasSuffix(string(b), "\n") {
+ return "", ErrBuild
+ }
+ lines := strings.Split(strings.TrimSuffix(string(b), "\n"), "\n")
+ if len(lines) < 3 || lines[0] != "go\t"+ToolchainVersion || lines[1] != "modules\t"+lock.ModulesDigest() {
+ return "", ErrBuild
+ }
+ type entry struct {
+ mode os.FileMode
+ size int64
+ digest string
+ }
+ want := map[string]entry{}
+ prev := ""
+ for _, line := range lines[2:] {
+ v := strings.Split(line, "\t")
+ if len(v) != 4 || !validPath(v[0]) || v[0] == "MANIFEST" || v[0] <= prev {
+ return "", ErrBuild
+ }
+ mode, e1 := strconv.ParseUint(v[1], 8, 32)
+ size, e2 := strconv.ParseInt(v[2], 10, 64)
+ if e1 != nil || e2 != nil || (mode != 0444 && mode != 0555) || fmt.Sprintf("%04o", mode) != v[1] || size < 0 || strconv.FormatInt(size, 10) != v[2] || !ValidDigest(v[3]) {
+ return "", ErrBuild
+ }
+ want[v[0]] = entry{os.FileMode(mode), size, v[3]}
+ prev = v[0]
+ }
+ required := []string{"VERSION", "bin/go", "pkg/tool/linux_arm64/compile", "pkg/tool/linux_arm64/link"}
+ for _, name := range required {
+ if _, ok := want[name]; !ok {
+ return "", ErrBuild
+ }
+ }
+ for _, prefix := range []string{"src/", "mod/", "cache/"} {
+ found := false
+ for name := range want {
+ if strings.HasPrefix(name, prefix) {
+ found = true
+ break
+ }
+ }
+ if !found {
+ return "", ErrBuild
+ }
+ }
+ err = filepath.WalkDir(dir, func(p string, de fs.DirEntry, e error) error {
+ if e != nil {
+ return e
+ }
+ st, e := de.Info()
+ if e != nil || !trusted(st) {
+ return ErrBuild
+ }
+ if st.IsDir() {
+ return nil
+ }
+ if !st.Mode().IsRegular() {
+ return ErrBuild
+ }
+ rel, e := filepath.Rel(dir, p)
+ if e != nil {
+ return e
+ }
+ if rel == "MANIFEST" {
+ return nil
+ }
+ entry, ok := want[rel]
+ if !ok || st.Mode().Perm() != entry.mode || st.Size() != entry.size {
+ return ErrBuild
+ }
+ file, e := instancefs.OpenBeneath(dir, rel, os.O_RDONLY, 0)
+ if e != nil {
+ return e
+ }
+ defer file.Close()
+ opened, e := file.Stat()
+ if e != nil || !os.SameFile(st, opened) || !trusted(opened) {
+ return ErrBuild
+ }
+ h := sha256.New()
+ n, e := io.Copy(h, io.LimitReader(file, entry.size+1))
+ if e != nil || n != entry.size || hex.EncodeToString(h.Sum(nil)) != entry.digest {
+ return ErrBuild
+ }
+ delete(want, rel)
+ return nil
+ })
+ if err != nil || len(want) != 0 {
+ return "", ErrBuild
+ }
+ v, err := instancefs.OpenBeneath(dir, "VERSION", os.O_RDONLY, 0)
+ if err != nil {
+ return "", ErrBuild
+ }
+ version, err := io.ReadAll(io.LimitReader(v, 1024))
+ v.Close()
+ if err != nil || strings.SplitN(string(version), "\n", 2)[0] != "go"+ToolchainVersion {
+ return "", ErrBuild
+ }
+ h := sha256.Sum256(b)
+ return hex.EncodeToString(h[:]), nil
+}
diff --git a/internal/demobuild/bundle_test.go b/internal/demobuild/bundle_test.go
new file mode 100644
index 000000000..ad7bce21e
--- /dev/null
+++ b/internal/demobuild/bundle_test.go
@@ -0,0 +1,76 @@
+//go:build linux
+
+package demobuild
+
+import (
+ "crypto/sha256"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "testing"
+)
+
+func bundleFixture(t *testing.T) string {
+ t.Helper()
+ dir := t.TempDir()
+ files := map[string]string{"VERSION": "go1.26.10\n", "bin/go": "compiler", "pkg/tool/linux_arm64/compile": "compiler", "pkg/tool/linux_arm64/link": "linker", "src/runtime/runtime.go": "source", "mod/cache/download/seed": "module", "cache/00/seed-a": "cache"}
+ keys := []string{}
+ for p := range files {
+ keys = append(keys, p)
+ }
+ sort.Strings(keys)
+ manifest := "go\t1.26.10\nmodules\t" + testLock(t).ModulesDigest() + "\n"
+ for _, p := range keys {
+ b := []byte(files[p])
+ if err := os.MkdirAll(filepath.Dir(filepath.Join(dir, p)), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, p), b, 0444); err != nil {
+ t.Fatal(err)
+ }
+ manifest += fmt.Sprintf("%s\t0444\t%d\t%x\n", p, len(b), sha256.Sum256(b))
+ }
+ if err := os.WriteFile(filepath.Join(dir, "MANIFEST"), []byte(manifest), 0444); err != nil {
+ t.Fatal(err)
+ }
+ return dir
+}
+
+func TestDemoBuildBundle(t *testing.T) {
+ for _, mutation := range []string{"none", "changed", "extra", "link", "lock", "missing-cache"} {
+ t.Run(mutation, func(t *testing.T) {
+ dir := bundleFixture(t)
+ lock := testLock(t)
+ switch mutation {
+ case "changed":
+ os.Chmod(filepath.Join(dir, "VERSION"), 0644)
+ os.WriteFile(filepath.Join(dir, "VERSION"), []byte("go1.26.11\n"), 0444)
+ os.Chmod(filepath.Join(dir, "VERSION"), 0444)
+ case "extra":
+ os.WriteFile(filepath.Join(dir, "extra"), []byte("extra"), 0444)
+ case "link":
+ os.Remove(filepath.Join(dir, "VERSION"))
+ os.Symlink("bin/go", filepath.Join(dir, "VERSION"))
+ case "lock":
+ lock.Modules[0].Version = "v0.0.1"
+ case "missing-cache":
+ os.Remove(filepath.Join(dir, "cache/00/seed-a"))
+ }
+ digest, err := checkBundle(dir, lock, func(os.FileInfo) bool { return true })
+ if (err == nil) != (mutation == "none") {
+ t.Fatalf("digest=%s err=%v", digest, err)
+ }
+ if err == nil && !ValidDigest(digest) {
+ t.Fatal(digest)
+ }
+ })
+ }
+ if _, err := CheckBundle("relative", testLock(t)); err == nil {
+ t.Fatal("relative bundle")
+ }
+ if _, err := CheckBundle(strings.Repeat("/", 2)+"opt/toolchain", testLock(t)); err == nil {
+ t.Fatal("aliased bundle")
+ }
+}
diff --git a/internal/demobuild/diagnostics.go b/internal/demobuild/diagnostics.go
index 8eaa51346..ec7c5ef4d 100644
--- a/internal/demobuild/diagnostics.go
+++ b/internal/demobuild/diagnostics.go
@@ -48,20 +48,29 @@ var (
// It drops banners and messages containing paths, credentials or environment
// assignments instead of trying to infer which fragment of them is safe.
func TrimDiagnostics(raw []byte) []Diagnostic {
+ out, _ := TrimDiagnosticsWithStatus(raw)
+ return out
+}
+
+func TrimDiagnosticsWithStatus(raw []byte) ([]Diagnostic, bool) {
cut := len(raw) > diagnosticRawMax
if cut {
raw = raw[:diagnosticRawMax]
if i := strings.LastIndexByte(string(raw), '\n'); i >= 0 {
raw = raw[:i]
} else {
- return nil
+ return nil, true
}
}
clean := ansiSequence.ReplaceAllString(strings.ToValidUTF8(string(raw), ""), "")
var out []Diagnostic
remaining := diagnosticMaxBytes
for _, line := range strings.Split(clean, "\n") {
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
if len(out) == diagnosticMaxEntries {
+ cut = true
break
}
m := diagnosticLine.FindStringSubmatch(line)
@@ -95,9 +104,11 @@ func TrimDiagnostics(raw []byte) []Diagnostic {
// Count every returned string byte, including filenames, within the budget.
room := remaining - len(file)
if room <= 0 {
+ cut = true
break
}
if len(msg) > room {
+ cut = true
msg = msg[:room]
for !utf8.ValidString(msg) {
msg = msg[:len(msg)-1]
@@ -109,5 +120,5 @@ func TrimDiagnostics(raw []byte) []Diagnostic {
out = append(out, Diagnostic{File: file, Line: n, Message: msg})
remaining -= len(file) + len(msg)
}
- return out
+ return out, cut
}
diff --git a/internal/demobuild/job.go b/internal/demobuild/job.go
index 4d8a6b545..871b73f3e 100644
--- a/internal/demobuild/job.go
+++ b/internal/demobuild/job.go
@@ -45,14 +45,15 @@ type Job struct {
}
type Result struct {
- JobID string `json:"job_id"`
- Attempt uint32 `json:"attempt"`
- SourceSHA256 string `json:"source_sha256"`
- BundleSHA256 string `json:"bundle_sha256"`
- BinaryPath string `json:"-"`
- BinarySHA256 string `json:"binary_sha256"`
- BinarySize int64 `json:"binary_size"`
- Diagnostics []Diagnostic `json:"diagnostics"`
+ JobID string `json:"job_id"`
+ Attempt uint32 `json:"attempt"`
+ SourceSHA256 string `json:"source_sha256"`
+ BundleSHA256 string `json:"bundle_sha256"`
+ BinaryPath string `json:"-"`
+ BinarySHA256 string `json:"binary_sha256"`
+ BinarySize int64 `json:"binary_size"`
+ Diagnostics []Diagnostic `json:"diagnostics"`
+ DiagnosticsTruncated bool `json:"diagnostics_truncated,omitempty"`
}
func NewJobID() (string, error) {
@@ -147,9 +148,10 @@ func (r WorkerReady) Valid() bool {
// BuildOutput is the bounded root builder response. The worker never executes it.
type BuildOutput struct {
- Binary []byte `json:"binary"`
- SHA256 string `json:"sha256"`
- Diagnostics []Diagnostic `json:"diagnostics"`
+ Binary []byte `json:"binary"`
+ SHA256 string `json:"sha256"`
+ Diagnostics []Diagnostic `json:"diagnostics"`
+ DiagnosticsTruncated bool `json:"diagnostics_truncated,omitempty"`
}
// StreamMessage carries signed work or a reconciliation hint. Hints grant no
diff --git a/internal/demobuild/probe.go b/internal/demobuild/probe.go
new file mode 100644
index 000000000..54d7eb92e
--- /dev/null
+++ b/internal/demobuild/probe.go
@@ -0,0 +1,70 @@
+package demobuild
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "strings"
+)
+
+// The readiness build proves the native compiler, offline dependency closure,
+// overlay support and actual namespace setup before advertising this bundle.
+// It imports the locked framework, never executes the resulting binary, and
+// uses the same resource, output and termination gates as submitted builds.
+func (w *Worker) probeBundle(ctx context.Context) (err error) {
+ if err = w.proof(ctx); err != nil {
+ return err
+ }
+ src, err := probeSource(w.lock)
+ if err != nil {
+ return err
+ }
+ id, err := NewJobID()
+ if err != nil {
+ return err
+ }
+ dir := filepath.Join(w.root, id, "1")
+ cleanup, err := w.prepareUnit(ctx, dir, src)
+ if cleanup != nil {
+ defer func() { err = errors.Join(err, cleanup()) }()
+ }
+ if err != nil {
+ return err
+ }
+ _, err = w.runUnit(ctx, dir, w.lock)
+ return err
+}
+
+func probeSource(lock Lock) (Source, error) {
+ var mod, sum strings.Builder
+ fmt.Fprintf(&mod, "module demo.local/app\n\ngo %s\n\nrequire (\n", lock.GoVersion)
+ for _, m := range lock.Modules {
+ fmt.Fprintf(&mod, "\t%s %s\n", m.Path, m.Version)
+ fmt.Fprintf(&sum, "%s %s %s\n%s %s/go.mod %s\n", m.Path, m.Version, m.Sum, m.Path, m.Version, m.GoModSum)
+ }
+ mod.WriteString(")\n")
+ files := []struct{ name, body string }{{"go.mod", mod.String()}, {"go.sum", sum.String()}, {"main.go", "package main\nimport _ \"" + lock.Rastrillo.Path + "\"\nfunc main() {}\n"}}
+ var b bytes.Buffer
+ gz := gzip.NewWriter(&b)
+ tw := tar.NewWriter(gz)
+ for _, f := range files {
+ if err := tw.WriteHeader(&tar.Header{Name: f.name, Mode: 0444, Size: int64(len(f.body)), Format: tar.FormatUSTAR}); err != nil {
+ return Source{}, err
+ }
+ if _, err := tw.Write([]byte(f.body)); err != nil {
+ return Source{}, err
+ }
+ }
+ if err := tw.Close(); err != nil {
+ return Source{}, err
+ }
+ if err := gz.Close(); err != nil {
+ return Source{}, err
+ }
+ src, _, err := ValidateSource(bytes.NewReader(b.Bytes()), lock)
+ return src, err
+}
diff --git a/internal/demobuild/runner.go b/internal/demobuild/runner.go
new file mode 100644
index 000000000..727e1f4d1
--- /dev/null
+++ b/internal/demobuild/runner.go
@@ -0,0 +1,181 @@
+package demobuild
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/sha256"
+ "debug/elf"
+ "encoding/hex"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/instancefs"
+)
+
+const (
+ MemoryMax int64 = 1073741824
+ WorkMax int64 = 536870912
+ TasksMax int64 = 128
+ BuildStopSeconds = 5
+)
+
+var ErrBuild = errors.New("DEMO-BUILD")
+
+func SliceProperties(slots int) map[string]int64 {
+ if slots < 1 || slots > 4 {
+ return nil
+ }
+ return map[string]int64{"MemoryMax": int64(slots) * MemoryMax, "MemorySwapMax": 0, "TasksMax": int64(slots) * TasksMax, "CPUQuota": int64(slots) * 50}
+}
+
+func BuildEnvironment() []string {
+ return []string{"GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off", "GOWORK=off", "GOENV=off", "CGO_ENABLED=0", "GOOS=linux", "GOARCH=arm64", "GOFLAGS=", "GOROOT=/opt/carlos/demo-toolchain", "GOMODCACHE=/opt/carlos/demo-toolchain/mod", "GOCACHE=/work/cache", "GOTMPDIR=/work/tmp", "TMPDIR=/work/tmp", "GOPATH=/work/home", "HOME=/work/home", "PATH=/opt/carlos/demo-toolchain/bin", "GOTELEMETRY=off"}
+}
+
+// ValidateOutput reads through the binary limit before parsing. Program headers
+// must describe an executable AArch64 image without an interpreter.
+func ValidateOutput(r io.Reader) (BuildOutput, error) {
+ b, err := io.ReadAll(io.LimitReader(r, BinaryMaxBytes+1))
+ if err != nil || len(b) > BinaryMaxBytes {
+ return BuildOutput{}, ErrBuild
+ }
+ f, err := elf.NewFile(bytes.NewReader(b))
+ if err != nil {
+ return BuildOutput{}, ErrBuild
+ }
+ defer f.Close()
+ if f.Class != elf.ELFCLASS64 || f.Data != elf.ELFDATA2LSB || f.Machine != elf.EM_AARCH64 || f.Type != elf.ET_EXEC || f.Version != elf.EV_CURRENT || (f.OSABI != elf.ELFOSABI_NONE && f.OSABI != elf.ELFOSABI_LINUX) {
+ return BuildOutput{}, ErrBuild
+ }
+ entry := false
+ for _, p := range f.Progs {
+ if p.Type == elf.PT_INTERP || p.Off > uint64(len(b)) || p.Filesz > uint64(len(b))-p.Off || p.Memsz < p.Filesz {
+ return BuildOutput{}, ErrBuild
+ }
+ if p.Type == elf.PT_LOAD && p.Flags&elf.PF_X != 0 && f.Entry >= p.Vaddr && f.Entry-p.Vaddr < p.Memsz {
+ entry = true
+ }
+ }
+ if !entry {
+ return BuildOutput{}, ErrBuild
+ }
+ h := sha256.Sum256(b)
+ return BuildOutput{Binary: b, SHA256: hex.EncodeToString(h[:])}, nil
+}
+
+// extractSource writes only the validator's regular-file inventory into a new
+// source directory. The parent is root-owned and no build has started yet.
+func extractSource(dir string, src Source) error {
+ r, err := instancefs.OpenRootBeneath(dir, ".")
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ if err = r.Mkdir("src", 0755); err != nil {
+ return err
+ }
+ gz, err := gzip.NewReader(bytes.NewReader(src.Archive))
+ if err != nil {
+ return err
+ }
+ defer gz.Close()
+ tr := tar.NewReader(gz)
+ want := map[string]SourceFile{}
+ for _, f := range src.Files {
+ want[f.Path] = f
+ }
+ for {
+ h, e := tr.Next()
+ if e == io.EOF {
+ break
+ }
+ if e != nil {
+ return e
+ }
+ if h.Typeflag == tar.TypeDir {
+ continue
+ }
+ f, ok := want[h.Name]
+ if !ok || !validPath(h.Name) || h.Size != f.Size || h.Typeflag != tar.TypeReg {
+ return ErrSource
+ }
+ p := filepath.Join("src", h.Name)
+ if err = r.MkdirAll(filepath.Dir(p), 0755); err != nil {
+ return err
+ }
+ out, e := instancefs.OpenBeneath(dir, p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0444)
+ if e != nil {
+ return e
+ }
+ hash := sha256.New()
+ n, e := io.Copy(io.MultiWriter(out, hash), io.LimitReader(tr, f.Size+1))
+ ce := out.Close()
+ if e != nil || ce != nil || n != f.Size || hex.EncodeToString(hash.Sum(nil)) != f.SHA256 {
+ return ErrSource
+ }
+ delete(want, h.Name)
+ }
+ if len(want) != 0 {
+ return ErrSource
+ }
+ return nil
+}
+
+type runContextKey struct{}
+type runInvocation struct {
+ dir string
+ startWait func(context.Context) error
+ stop func() error
+}
+
+// Run is entered only after root has validated a job and prepared its fixed
+// mounts. The invocation is private to this package; callers cannot supply
+// executable names, arguments, mount sources or an alternate compiler.
+func Run(ctx context.Context, workDir string, lock Lock) (BuildOutput, error) {
+ i, ok := ctx.Value(runContextKey{}).(*runInvocation)
+ if !ok || i.dir != workDir || lock.validate() != nil {
+ return BuildOutput{}, ErrBuild
+ }
+ runErr := i.startWait(ctx)
+ // Stop must prove the entire cgroup empty, including after cancellation.
+ if err := i.stop(); err != nil {
+ return BuildOutput{}, err
+ }
+ var out BuildOutput
+ d, err := instancefs.OpenBeneath(workDir, "diagnostics", os.O_RDONLY, 0)
+ if err == nil {
+ raw, e := io.ReadAll(io.LimitReader(d, diagnosticRawMax+1))
+ d.Close()
+ if e != nil {
+ return out, ErrBuild
+ }
+ out.Diagnostics, out.DiagnosticsTruncated = TrimDiagnosticsWithStatus(raw)
+ }
+ if runErr != nil {
+ return out, ErrBuild
+ }
+ f, err := instancefs.OpenBeneath(workDir, "out/app", os.O_RDONLY, 0)
+ if err != nil {
+ return out, ErrBuild
+ }
+ defer f.Close()
+ validated, err := ValidateOutput(f)
+ validated.Diagnostics = out.Diagnostics
+ validated.DiagnosticsTruncated = out.DiagnosticsTruncated
+ return validated, err
+}
+
+func showProperties(raw string) map[string]string {
+ m := map[string]string{}
+ for _, line := range strings.Split(raw, "\n") {
+ if k, v, ok := strings.Cut(line, "="); ok {
+ m[k] = v
+ }
+ }
+ return m
+}
diff --git a/internal/demobuild/runner_test.go b/internal/demobuild/runner_test.go
new file mode 100644
index 000000000..481b4f5b4
--- /dev/null
+++ b/internal/demobuild/runner_test.go
@@ -0,0 +1,122 @@
+package demobuild
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func arm64ELF() []byte {
+ b := make([]byte, 120)
+ copy(b, "\x7fELF\x02\x01\x01")
+ binary.LittleEndian.PutUint16(b[16:], 2)
+ binary.LittleEndian.PutUint16(b[18:], 183)
+ binary.LittleEndian.PutUint32(b[20:], 1)
+ binary.LittleEndian.PutUint64(b[24:], 0x400000)
+ binary.LittleEndian.PutUint64(b[32:], 64)
+ binary.LittleEndian.PutUint16(b[52:], 64)
+ binary.LittleEndian.PutUint16(b[54:], 56)
+ binary.LittleEndian.PutUint16(b[56:], 1)
+ binary.LittleEndian.PutUint32(b[64:], 1)
+ binary.LittleEndian.PutUint32(b[68:], 5)
+ binary.LittleEndian.PutUint64(b[80:], 0x400000)
+ binary.LittleEndian.PutUint64(b[96:], uint64(len(b)))
+ binary.LittleEndian.PutUint64(b[104:], uint64(len(b)))
+ return b
+}
+
+func TestDemoBuildOutput(t *testing.T) {
+ good := arm64ELF()
+ if _, err := ValidateOutput(bytes.NewReader(good)); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ name string
+ b []byte
+ }{
+ {"text", []byte("not an executable")},
+ {"other-os", func() []byte { b := bytes.Clone(good); b[7] = 9; return b }()},
+ {"oversized", make([]byte, BinaryMaxBytes+1)},
+ {"amd64", func() []byte { b := bytes.Clone(good); binary.LittleEndian.PutUint16(b[18:], 62); return b }()},
+ {"interpreter", func() []byte { b := bytes.Clone(good); binary.LittleEndian.PutUint32(b[64:], 3); return b }()},
+ {"truncated-segment", good[:100]},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, err := ValidateOutput(bytes.NewReader(tc.b)); err == nil {
+ t.Fatal("accepted invalid output")
+ }
+ })
+ }
+}
+
+func TestDemoBuildLimits(t *testing.T) {
+ if MemoryMax != 1073741824 || WorkMax != 536870912 || TasksMax != 128 || BuildStopSeconds != 5 {
+ t.Fatal("resource contract changed")
+ }
+ for n := 1; n <= 4; n++ {
+ s := SliceProperties(n)
+ if s["MemoryMax"] != int64(n)*MemoryMax || s["TasksMax"] != int64(n)*TasksMax || s["CPUQuota"] != int64(n)*50 {
+ t.Fatal(s)
+ }
+ }
+}
+
+func TestDemoOfflineBuild(t *testing.T) {
+ env := strings.Join(BuildEnvironment(), "\n")
+ for _, want := range []string{"CGO_ENABLED=0", "GOOS=linux", "GOARCH=arm64", "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off", "GOWORK=off", "GOENV=off", "GOFLAGS="} {
+ if !strings.Contains("\n"+env+"\n", "\n"+want+"\n") {
+ t.Error(want)
+ }
+ }
+ if _, err := Run(context.Background(), "/caller/chosen/path", testLock(t)); err == nil {
+ t.Fatal("accepted caller path")
+ }
+}
+
+func TestDemoBuildCleanupSymlinkSource(t *testing.T) {
+ dir := t.TempDir()
+ outside := t.TempDir()
+ if err := os.Symlink(outside, filepath.Join(dir, "src")); err != nil {
+ t.Fatal(err)
+ }
+ src, _, err := ValidateSource(bytes.NewReader(archive(t, starter(t))), testLock(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := extractSource(dir, src); err == nil {
+ t.Fatal("followed symlink source")
+ }
+ files, err := os.ReadDir(outside)
+ if err != nil || len(files) != 0 {
+ t.Fatalf("outside job modified: %v %v", files, err)
+ }
+}
+
+func TestDemoBuildDiagnosticTruncation(t *testing.T) {
+ for _, raw := range []string{strings.Repeat("main.go:1: failure\n", 51), "main.go:1: " + strings.Repeat("界", 10000), strings.Repeat("x", 65537)} {
+ _, cut := TrimDiagnosticsWithStatus([]byte(raw))
+ if !cut {
+ t.Fatal("missing truncation signal")
+ }
+ }
+ d, cut := TrimDiagnosticsWithStatus([]byte("main.go:1: undefined: item\n"))
+ if cut || len(d) != 1 {
+ t.Fatal(d, cut)
+ }
+}
+
+func TestDemoBuildProbeSource(t *testing.T) {
+ l := testLock(t)
+ src, err := probeSource(l)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, _, err := ValidateSource(bytes.NewReader(src.Archive), l)
+ if err != nil || got.SHA256 != src.SHA256 || len(got.Files) != 3 {
+ t.Fatal(got, err)
+ }
+}
diff --git a/internal/demobuild/security_linux.go b/internal/demobuild/security_linux.go
new file mode 100644
index 000000000..30b42e034
--- /dev/null
+++ b/internal/demobuild/security_linux.go
@@ -0,0 +1,63 @@
+//go:build linux
+
+package demobuild
+
+import (
+ "bufio"
+ "os"
+ "strings"
+ "syscall"
+
+ "github.com/carlosframework/platform/internal/instancefs"
+ "golang.org/x/sys/unix"
+)
+
+func immutableRootFile(st os.FileInfo) bool {
+ s, ok := st.Sys().(*syscall.Stat_t)
+ if !ok || s.Uid != 0 || st.Mode().Perm()&0022 != 0 || st.Mode()&(os.ModeSymlink|os.ModeSetuid|os.ModeSetgid) != 0 {
+ return false
+ }
+ return st.IsDir() || st.Mode().IsRegular() && s.Nlink == 1 && st.Mode().Perm()&0222 == 0
+}
+
+func lockWorker(dir string) (*os.File, error) {
+ f, err := instancefs.OpenBeneath(dir, "worker.lock", os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ return nil, err
+ }
+ if err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
+ f.Close()
+ return nil, err
+ }
+ return f, nil
+}
+
+func verifyWorkMount(p string, max int64) error {
+ var st unix.Statfs_t
+ if err := unix.Statfs(p, &st); err != nil {
+ return err
+ }
+ if st.Type != unix.TMPFS_MAGIC || st.Blocks*uint64(st.Bsize) > uint64(max) || !mountedAt(p) {
+ return ErrBuild
+ }
+ return nil
+}
+
+func mountedAt(p string) bool {
+ f, err := os.Open("/proc/self/mountinfo")
+ if err != nil {
+ return true
+ }
+ defer f.Close()
+ s := bufio.NewScanner(f)
+ for s.Scan() {
+ v := strings.Fields(s.Text())
+ if len(v) < 5 {
+ return true
+ }
+ if v[4] == p {
+ return true
+ }
+ }
+ return s.Err() != nil
+}
diff --git a/internal/demobuild/security_other.go b/internal/demobuild/security_other.go
new file mode 100644
index 000000000..79dcf4693
--- /dev/null
+++ b/internal/demobuild/security_other.go
@@ -0,0 +1,10 @@
+//go:build !linux
+
+package demobuild
+
+import "os"
+
+func immutableRootFile(os.FileInfo) bool { return false }
+func lockWorker(string) (*os.File, error) { return nil, ErrBuild }
+func verifyWorkMount(string, int64) error { return ErrBuild }
+func mountedAt(string) bool { return true }
diff --git a/internal/demobuild/unit.go b/internal/demobuild/unit.go
new file mode 100644
index 000000000..f9b7226bf
--- /dev/null
+++ b/internal/demobuild/unit.go
@@ -0,0 +1,497 @@
+package demobuild
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancefs"
+)
+
+var unitRoot = "/run/systemd/system"
+var buildCgroupRoot = "/sys/fs/cgroup/carlos.slice/carlos-demo.slice/carlos-demo-builds.slice"
+
+type buildLayout struct{ dir, work, cache, unit, workMount, cacheMount string }
+
+func layout(dir string) (buildLayout, error) { return layoutIn(BuildRoot, dir) }
+
+func layoutIn(root, dir string) (buildLayout, error) {
+ rel, err := filepath.Rel(root, dir)
+ p := strings.Split(rel, string(filepath.Separator))
+ if err != nil || len(p) != 2 || !ValidJobID(p[0]) {
+ return buildLayout{}, ErrBuild
+ }
+ n, err := strconv.ParseUint(p[1], 10, 32)
+ if err != nil || n == 0 || strconv.FormatUint(n, 10) != p[1] || filepath.Join(root, rel) != dir {
+ return buildLayout{}, ErrBuild
+ }
+ id, _ := base64.RawURLEncoding.DecodeString(p[0])
+ key := hex.EncodeToString(id) + "_" + p[1]
+ l := buildLayout{dir: dir, work: dir + "/work", cache: dir + "/work/cache", unit: "carlos-demo-build@" + key + ".service"}
+ l.workMount = mountName(l.work)
+ l.cacheMount = mountName(l.cache)
+ return l, nil
+}
+
+func mountName(p string) string {
+ var b strings.Builder
+ for _, c := range []byte(strings.TrimPrefix(p, "/")) {
+ 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"
+}
+
+var systemctl = func(ctx context.Context, args ...string) (string, error) {
+ c := exec.CommandContext(ctx, "/usr/bin/systemctl", args...)
+ c.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "SYSTEMD_COLORS=0", "SYSTEMD_PAGER="}
+ var b limitedLog
+ c.Stdout = &b
+ c.Stderr = &b
+ err := c.Run()
+ return string(b.b), err
+}
+
+type limitedLog struct{ b []byte }
+
+func (b *limitedLog) Write(p []byte) (int, error) {
+ n := len(p)
+ if room := 128*1024 - len(b.b); room > 0 {
+ b.b = append(b.b, p[:min(room, len(p))]...)
+ }
+ return n, nil
+}
+
+func writeUnit(name, content string) error {
+ if strings.ContainsAny(name, "/\x00\r\n") {
+ return ErrBuild
+ }
+ f, err := instancefs.OpenBeneath(unitRoot, name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
+ if err != nil {
+ return err
+ }
+ _, err = f.WriteString(content)
+ if err == nil {
+ err = f.Sync()
+ }
+ return errors.Join(err, f.Close())
+}
+
+func (w *Worker) prepareUnit(ctx context.Context, dir string, src Source) (func() error, error) {
+ l, err := layoutIn(w.root, dir)
+ if err != nil {
+ return nil, err
+ }
+ r, err := instancefs.OpenRootBeneath(w.root, ".")
+ if err != nil {
+ return nil, err
+ }
+ defer r.Close()
+ rel, _ := filepath.Rel(w.root, dir)
+ if err = r.Mkdir(filepath.Dir(rel), 0700); err != nil {
+ return nil, err
+ }
+ cleanup := func() error {
+ end := time.Now().Add(BuildStopSeconds * time.Second)
+ if deadline, ok := ctx.Deadline(); ok && deadline.Add(BuildStopSeconds*time.Second).Before(end) {
+ end = deadline.Add(BuildStopSeconds * time.Second)
+ }
+ cleanCtx, cancel := context.WithDeadline(context.Background(), end)
+ defer cancel()
+ return w.cleanUnit(cleanCtx, l)
+ }
+ if err = r.Mkdir(rel, 0700); err != nil {
+ return cleanup, err
+ }
+ if err = r.Mkdir(rel+"/work", 0700); err != nil {
+ return cleanup, err
+ }
+ content := fmt.Sprintf("[Unit]\nBindsTo=carlos-instance-control.service\nAfter=carlos-instance-control.service\n[Mount]\nWhat=tmpfs\nWhere=%s\nType=tmpfs\nOptions=size=%d,mode=0755,nosuid,nodev,noexec\nTimeoutSec=5\n", l.work, WorkMax)
+ if err = writeUnit(l.workMount, content); err != nil {
+ return cleanup, err
+ }
+ if _, err = systemctl(ctx, "daemon-reload"); err != nil {
+ return cleanup, err
+ }
+ if _, err = systemctl(ctx, "start", l.workMount); err != nil {
+ return cleanup, err
+ }
+ if err = verifyWorkMount(l.work, WorkMax); err != nil {
+ return cleanup, err
+ }
+ wr, err := instancefs.OpenRootBeneath(l.work, ".")
+ if err != nil {
+ return cleanup, err
+ }
+ defer wr.Close()
+ for _, d := range []string{"out", "tmp", "home", "cache", "cache-upper", "cache-work"} {
+ mode := os.FileMode(0700)
+ if d == "out" || d == "tmp" || d == "home" {
+ mode = 0777
+ }
+ if err = wr.Mkdir(d, mode); err != nil {
+ return cleanup, err
+ }
+ if err = wr.Chmod(d, mode); err != nil {
+ return cleanup, err
+ }
+ }
+ if err = extractSource(l.work, src); err != nil {
+ return cleanup, err
+ }
+ d, err := instancefs.OpenBeneath(l.work, "diagnostics", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if err != nil {
+ return cleanup, err
+ }
+ d.Close()
+ content = fmt.Sprintf("[Unit]\nBindsTo=%s\nAfter=%s\n[Mount]\nWhat=overlay\nWhere=%s\nType=overlay\nOptions=lowerdir=%s/cache,upperdir=%s/cache-upper,workdir=%s/cache-work,nosuid,nodev,noexec\nTimeoutSec=5\n", l.workMount, l.workMount, l.cache, w.cfg.ToolchainDir, l.work, l.work)
+ if err = writeUnit(l.cacheMount, content); err != nil {
+ return cleanup, err
+ }
+ if _, err = systemctl(ctx, "daemon-reload"); err != nil {
+ return cleanup, err
+ }
+ if _, err = systemctl(ctx, "start", l.cacheMount); err != nil {
+ return cleanup, err
+ }
+ // Only directories copy up. Seed bytes stay on the root-owned lower
+ // mount; every writable cache file belongs to this private upper tree.
+ if err = filepath.WalkDir(l.cache, func(p string, de fs.DirEntry, e error) error {
+ if e != nil {
+ return e
+ }
+ if de.Type()&os.ModeSymlink != 0 {
+ return ErrBuild
+ }
+ if de.IsDir() {
+ return os.Chmod(p, 0777)
+ }
+ return nil
+ }); err != nil {
+ return cleanup, err
+ }
+ ur, err := instancefs.OpenRootBeneath(unitRoot, ".")
+ if err != nil {
+ return cleanup, err
+ }
+ defer ur.Close()
+ if err = ur.Mkdir(l.unit+".d", 0755); err != nil {
+ return cleanup, err
+ }
+ drop := fmt.Sprintf("[Unit]\nBindsTo=%s %s carlos-instance-control.service\nAfter=%s %s carlos-instance-control.service\n[Service]\nBindPaths=%s:/work\nBindReadOnlyPaths=%s:/opt/carlos/demo-toolchain %s/src:/work/src\nStandardOutput=truncate:%s/diagnostics\nStandardError=inherit\n", l.workMount, l.cacheMount, l.workMount, l.cacheMount, l.work, w.cfg.ToolchainDir, l.work, l.work)
+ f, err := instancefs.OpenBeneath(unitRoot, l.unit+".d/50-job.conf", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
+ if err != nil {
+ return cleanup, err
+ }
+ _, err = f.WriteString(drop)
+ err = errors.Join(err, f.Close())
+ if err != nil {
+ return cleanup, err
+ }
+ if _, err = systemctl(ctx, "daemon-reload"); err != nil {
+ return cleanup, err
+ }
+ if err = w.assertUnit(ctx, l); err != nil {
+ return cleanup, err
+ }
+ return cleanup, nil
+}
+
+func (w *Worker) runUnit(ctx context.Context, dir string, lock Lock) (BuildOutput, error) {
+ l, err := layoutIn(w.root, dir)
+ if err != nil {
+ return BuildOutput{}, err
+ }
+ i := &runInvocation{dir: l.work, startWait: func(ctx context.Context) error {
+ if err := w.assertUnit(ctx, l); err != nil {
+ return err
+ }
+ if _, err := systemctl(ctx, "start", "--no-block", l.unit); err != nil {
+ return err
+ }
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ out, e := systemctl(ctx, "show", l.unit, "-p", "ActiveState,SubState,Result,ExecMainStatus,ExecMainStartTimestampMonotonic")
+ if e != nil {
+ return e
+ }
+ m := showProperties(out)
+ if m["ActiveState"] == "failed" {
+ return ErrBuild
+ }
+ if m["SubState"] == "exited" && m["ExecMainStartTimestampMonotonic"] != "0" && m["ExecMainStartTimestampMonotonic"] != "" {
+ if m["Result"] != "success" || m["ExecMainStatus"] != "0" {
+ return ErrBuild
+ }
+ return nil
+ }
+ }
+ }
+ }, stop: func() error { return stopBuild(l) }}
+ return Run(context.WithValue(ctx, runContextKey{}, i), l.work, lock)
+}
+
+func stopBuild(l buildLayout) error {
+ ctx, cancel := context.WithTimeout(context.Background(), BuildStopSeconds*time.Second)
+ defer cancel()
+ return stopBuildContext(ctx, l)
+}
+
+func stopBuildContext(ctx context.Context, l buildLayout) error {
+ if _, err := systemctl(ctx, "stop", "--no-block", l.unit); err != nil {
+ out, e := systemctl(ctx, "show", l.unit, "-p", "LoadState")
+ if e != nil || showProperties(out)["LoadState"] != "not-found" {
+ return ErrBuild
+ }
+ }
+ // Disposable compilers have no shutdown protocol. Kill descendants now;
+ // systemd's stop job still owns reaping and the final inactive transition.
+ _, _ = systemctl(ctx, "kill", "--kill-whom=all", "--signal=SIGKILL", l.unit)
+ tick := time.NewTicker(20 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ out, err := systemctl(ctx, "show", l.unit, "-p", "ActiveState,MainPID,ControlPID,LoadState")
+ m := showProperties(out)
+ inactive := m["LoadState"] == "not-found" || (m["ActiveState"] == "inactive" || m["ActiveState"] == "failed") && m["MainPID"] == "0" && m["ControlPID"] == "0"
+ if err == nil && inactive && emptyBuildCgroup(l.unit) == nil {
+ return nil
+ }
+ select {
+ case <-ctx.Done():
+ return ErrBuild
+ case <-tick.C:
+ }
+ }
+}
+
+func emptyBuildCgroup(unit string) error {
+ p := filepath.Join(buildCgroupRoot, unit)
+ f, absent, err := instancefs.OpenBeneathOrAbsent(p, "cgroup.events")
+ if errors.Is(err, os.ErrNotExist) { // Missing cgroup directory means no descendants.
+ if _, e := os.Lstat(p); os.IsNotExist(e) {
+ return nil
+ }
+ }
+ if err != nil || absent {
+ return ErrBuild
+ }
+ defer f.Close()
+ var b [4096]byte
+ n, err := f.Read(b[:])
+ if err != nil {
+ return err
+ }
+ if !strings.Contains("\n"+string(b[:n])+"\n", "\npopulated 0\n") {
+ return ErrBuild
+ }
+ return nil
+}
+
+func (w *Worker) cleanUnit(ctx context.Context, l buildLayout) error {
+ if err := stopBuildContext(ctx, l); err != nil {
+ return err
+ }
+ for _, unit := range []string{l.cacheMount, l.workMount} {
+ out, err := systemctl(ctx, "show", unit, "-p", "LoadState,ActiveState")
+ if err != nil {
+ return err
+ }
+ if showProperties(out)["LoadState"] != "not-found" {
+ if _, err = systemctl(ctx, "stop", unit); err != nil {
+ return err
+ }
+ }
+ }
+ if mountedAt(l.work) || mountedAt(l.cache) {
+ return ErrBuild
+ }
+ r, err := instancefs.OpenRootBeneath(w.root, ".")
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ rel, _ := filepath.Rel(w.root, l.dir)
+ if err = r.RemoveAll(rel); err != nil {
+ return err
+ }
+ if err = r.Remove(filepath.Dir(rel)); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ ur, err := instancefs.OpenRootBeneath(unitRoot, ".")
+ if err != nil {
+ return err
+ }
+ defer ur.Close()
+ for _, p := range []string{l.unit + ".d/50-job.conf", l.unit + ".d", l.cacheMount, l.workMount} {
+ if err = ur.Remove(p); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ _, err = systemctl(ctx, "daemon-reload")
+ return err
+}
+
+func (w *Worker) recover(ctx context.Context) error {
+ r, err := instancefs.OpenDirBeneath(w.root, ".")
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ entries, err := r.ReadDir(-1)
+ if err != nil {
+ return err
+ }
+ for _, e := range entries {
+ if !ValidJobID(e.Name()) {
+ continue
+ }
+ job, err := instancefs.OpenDirBeneath(w.root, e.Name())
+ if err != nil {
+ return err
+ }
+ attempts, err := job.ReadDir(-1)
+ job.Close()
+ if err != nil {
+ return err
+ }
+ if len(attempts) == 0 {
+ root, openErr := instancefs.OpenRootBeneath(w.root, ".")
+ if openErr != nil {
+ return openErr
+ }
+ removeErr := root.Remove(e.Name())
+ root.Close()
+ if removeErr != nil {
+ return removeErr
+ }
+ continue
+ }
+ for _, attempt := range attempts {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ l, err := layoutIn(w.root, filepath.Join(w.root, e.Name(), attempt.Name()))
+ if err != nil {
+ return err
+ }
+ if err = w.cleanUnit(ctx, l); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+func (w *Worker) assertBudget(ctx context.Context) error {
+ out, err := systemctl(ctx, "show", "carlos-demo-builds.slice", "-p", "MemoryMax,MemorySwapMax,TasksMax,CPUQuotaPerSecUSec")
+ if err != nil {
+ return err
+ }
+ m := showProperties(out)
+ n := cap(w.slots)
+ if m["MemoryMax"] != strconv.FormatInt(int64(n)*MemoryMax, 10) || m["MemorySwapMax"] != "0" || m["TasksMax"] != strconv.Itoa(n*int(TasksMax)) || m["CPUQuotaPerSecUSec"] != quotaString(n) {
+ return ErrBuild
+ }
+ return nil
+}
+
+func quotaString(n int) string {
+ if n%2 == 0 {
+ return strconv.Itoa(n/2) + "s"
+ }
+ if n == 1 {
+ return "500ms"
+ }
+ return "1.500000s"
+}
+
+func (w *Worker) assertUnit(ctx context.Context, l buildLayout) error {
+ if err := w.assertBudget(ctx); err != nil {
+ return err
+ }
+ want := map[string]string{"DynamicUser": "yes", "PrivateNetwork": "yes", "RestrictAddressFamilies": "AF_UNIX", "MemoryMax": "1073741824", "MemorySwapMax": "0", "LimitFSIZE": "33554432", "LimitFSIZESoft": "33554432", "TasksMax": "128", "CPUQuotaPerSecUSec": "500ms", "CPUWeight": "10", "RuntimeMaxUSec": "3min", "TimeoutStopUSec": "5s", "KillMode": "control-group", "MemoryDenyWriteExecute": "yes", "CapabilityBoundingSet": "", "AmbientCapabilities": "", "NoNewPrivileges": "yes", "ProtectSystem": "strict", "ProtectHome": "yes", "PrivateDevices": "yes", "PrivateIPC": "yes", "PrivatePIDs": "yes", "RestrictNamespaces": "yes", "ProtectControlGroups": "yes", "ProtectProc": "invisible", "ProcSubset": "pid", "NetworkNamespacePath": "", "JoinsNamespaceOf": "", "Slice": "carlos-demo-builds.slice", "WorkingDirectory": "/work/src", "IPAddressAllow": ""}
+ keys := []string{}
+ for k := range want {
+ keys = append(keys, k)
+ }
+ keys = append(keys, "IPAddressDeny", "TemporaryFileSystem", "Environment", "BindPaths", "BindReadOnlyPaths")
+ out, err := systemctl(ctx, "show", l.unit, "-p", strings.Join(keys, ","))
+ if err != nil {
+ return err
+ }
+ m := showProperties(out)
+ for k, v := range want {
+ if got, ok := m[k]; !ok || got != v {
+ return ErrBuild
+ }
+ }
+ deny := strings.Fields(m["IPAddressDeny"])
+ if !(len(deny) == 1 && deny[0] == "any" || len(deny) == 2 && (deny[0] == "0.0.0.0/0" && deny[1] == "::/0" || deny[1] == "0.0.0.0/0" && deny[0] == "::/0")) {
+ return ErrBuild
+ }
+ for _, p := range []string{"/data:ro", "/run:ro", "/var:ro", "/opt:ro", "/tmp:ro", "/dev/shm:ro", "/dev/mqueue:ro", "/dev/pts:ro"} {
+ if !containsField(m["TemporaryFileSystem"], p) {
+ return ErrBuild
+ }
+ }
+ for _, e := range BuildEnvironment() {
+ if !containsField(m["Environment"], e) {
+ return ErrBuild
+ }
+ }
+ // Bind readback can include rbind/norbind suffixes. Compare normalized
+ // source/destination pairs and refuse every unexpected bind.
+ if !bindsEqual(m["BindPaths"], []string{l.work + ":/work"}) || !bindsEqual(m["BindReadOnlyPaths"], []string{w.cfg.ToolchainDir + ":/opt/carlos/demo-toolchain", l.work + "/src:/work/src"}) {
+ return ErrBuild
+ }
+ return nil
+}
+
+func containsField(s, want string) bool {
+ for _, f := range strings.Fields(s) {
+ if f == want {
+ return true
+ }
+ }
+ return false
+}
+func bindsEqual(raw string, want []string) bool {
+ f := strings.Fields(raw)
+ if len(f) != len(want) {
+ return false
+ }
+ for _, v := range f {
+ v = strings.TrimSuffix(strings.TrimSuffix(v, ":rbind"), ":norbind")
+ found := false
+ for _, w := range want {
+ if w == v {
+ found = true
+ break
+ }
+ }
+ if !found {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/demobuild/unit_kernel_linux_test.go b/internal/demobuild/unit_kernel_linux_test.go
new file mode 100644
index 000000000..7cb53aa95
--- /dev/null
+++ b/internal/demobuild/unit_kernel_linux_test.go
@@ -0,0 +1,321 @@
+//go:build linux
+
+package demobuild
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "golang.org/x/sys/unix"
+)
+
+func TestMain(m *testing.M) {
+ if os.Getenv("CARLOS_DEMO_WITNESS_HELPER") == "1" {
+ if len(os.Args) > 1 && os.Args[1] == "child" {
+ signal.Ignore(syscall.SIGTERM)
+ for {
+ time.Sleep(time.Hour)
+ }
+ }
+ if err := demoBuildKernelHelper(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ os.Exit(0)
+ }
+ os.Exit(m.Run())
+}
+
+// This is a malicious compiler fixture, not submitted Go source. It exercises
+// the real template and root supervisor even if a compiler were compromised.
+func demoBuildKernelHelper() error {
+ if os.Geteuid() == 0 {
+ return fmt.Errorf("root compiler")
+ }
+ for _, entry := range BuildEnvironment() {
+ k, v, _ := strings.Cut(entry, "=")
+ if os.Getenv(k) != v {
+ return fmt.Errorf("environment %s", k)
+ }
+ }
+ for _, family := range []int{unix.AF_INET, unix.AF_INET6} {
+ fd, err := unix.Socket(family, unix.SOCK_STREAM, 0)
+ if err == nil {
+ unix.Close(fd)
+ return fmt.Errorf("network socket available")
+ }
+ }
+ for _, p := range strings.Split(os.Getenv("CARLOS_DEMO_WITNESS_FILES"), ":") {
+ if _, err := os.ReadFile(p); err == nil {
+ return fmt.Errorf("host file readable")
+ }
+ }
+ if c, err := net.DialTimeout("unix", os.Getenv("CARLOS_DEMO_WITNESS_SOCKET"), time.Second); err == nil {
+ c.Close()
+ return fmt.Errorf("control socket reachable")
+ }
+ if err := os.WriteFile("/opt/carlos/demo-toolchain/cache/seed", []byte("changed"), 0600); err == nil {
+ return fmt.Errorf("shared seed writable")
+ }
+ if b, err := unix.Mmap(-1, 0, 4096, unix.PROT_READ|unix.PROT_WRITE|unix.PROT_EXEC, unix.MAP_ANON|unix.MAP_PRIVATE); err == nil {
+ unix.Munmap(b)
+ return fmt.Errorf("W^X absent")
+ }
+ // Many files stay below RLIMIT_FSIZE while challenging the whole tmpfs.
+ buf := make([]byte, 1<<20)
+ var written int64
+ full := false
+ for n := 0; n < 33 && !full; n++ {
+ f, err := os.Create(fmt.Sprintf("/work/tmp/fill-%d", n))
+ if err != nil {
+ return err
+ }
+ 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()
+ return e
+ }
+ full = true
+ break
+ }
+ }
+ f.Close()
+ }
+ if !full || written > WorkMax {
+ return fmt.Errorf("work filesystem unbounded")
+ }
+ entries, err := os.ReadDir("/work/tmp")
+ if err != nil {
+ return err
+ }
+ for _, e := range entries {
+ if strings.HasPrefix(e.Name(), "fill-") {
+ if err = os.Remove("/work/tmp/" + e.Name()); err != nil {
+ return err
+ }
+ }
+ }
+ child := exec.Command("/opt/carlos/demo-toolchain/bin/go", "child")
+ child.Env = os.Environ()
+ if err = child.Start(); err != nil {
+ return err
+ }
+ fmt.Fprintln(os.Stdout, "main.go:1: witness-ready")
+ signal.Ignore(syscall.SIGTERM)
+ for {
+ time.Sleep(time.Hour)
+ }
+}
+
+func TestDemoBuildKernel(t *testing.T) {
+ if os.Getenv("CARLOS_DEMO_KERNEL_WITNESS") != "1" {
+ t.Skip("kernel witness outstanding: needs a designated systemd sandbox (not evidence)")
+ }
+ if os.Geteuid() != 0 || runtime.GOARCH != "arm64" {
+ t.Fatal("witness requires an idle root linux-arm64 systemd sandbox")
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Minute)
+ defer cancel()
+ for _, name := range []string{"carlos-demo-build@.service", "carlos-demo-builds.slice"} {
+ want, err := os.ReadFile("../host/units/" + name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := os.ReadFile("/etc/systemd/system/" + name)
+ if err != nil || !bytes.Equal(want, got) {
+ t.Fatalf("install this checkout's %s with concurrency 1: %v", name, err)
+ }
+ }
+ if out, err := systemctl(ctx, "is-active", "carlos-instance-control.service"); err != nil || strings.TrimSpace(out) != "active" {
+ t.Fatal("root control must be active with its build-worker switch off")
+ }
+ if out, err := systemctl(ctx, "list-units", "--state=active,activating", "--no-legend", "carlos-demo-build@*.service"); err != nil || strings.TrimSpace(out) != "" {
+ t.Fatal("sandbox has active builds", out, err)
+ }
+ created := false
+ if err := os.Mkdir(BuildRoot, 0700); err == nil {
+ created = true
+ } else if !os.IsExist(err) {
+ t.Fatal(err)
+ }
+ if created {
+ defer os.Remove(BuildRoot)
+ }
+ guard, err := lockWorker(BuildRoot)
+ if err != nil {
+ t.Fatal("another root builder owns the sandbox", err)
+ }
+ defer guard.Close()
+ // The fixture owns only a lock it created in a fresh root. Existing lock
+ // files belong to the installed root service and are retained.
+ if created {
+ defer os.Remove(BuildRoot + "/worker.lock")
+ }
+ lock := testLock(t)
+ bundle := os.Getenv("CARLOS_DEMO_TOOLCHAIN_DIR")
+ digest, err := CheckBundle(bundle, lock)
+ if err != nil {
+ t.Fatal("verified operator bundle required", err)
+ }
+ w := &Worker{cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1, ToolchainDir: bundle}, lock: lock, digest: digest, root: BuildRoot, slots: make(chan struct{}, 1)}
+ src, _, err := ValidateSource(bytes.NewReader(archive(t, starter(t))), lock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ run := func(malicious bool) {
+ id, err := NewJobID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := filepath.Join(BuildRoot, id, "1")
+ jobCtx, stop := context.WithTimeout(ctx, BuildWindow)
+ defer stop()
+ cleanup, err := w.prepareUnit(jobCtx, dir, src)
+ if cleanup != nil {
+ defer func() {
+ if err := cleanup(); err != nil {
+ t.Error("cleanup", err)
+ }
+ }()
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ l, _ := layout(dir)
+ if malicious {
+ f, err := os.OpenFile(filepath.Join(unitRoot, l.unit+".d/90-witness.conf"), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = fmt.Fprintf(f, "[Service]\nEnvironment=CARLOS_DEMO_WITNESS_HELPER=1 CARLOS_DEMO_WITNESS_FILES=%s CARLOS_DEMO_WITNESS_SOCKET=%s\n", os.Getenv("CARLOS_DEMO_WITNESS_FILES"), os.Getenv("CARLOS_DEMO_WITNESS_SOCKET"))
+ f.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.Remove(filepath.Join(unitRoot, l.unit+".d/90-witness.conf"))
+ if _, err = systemctl(ctx, "daemon-reload"); err != nil {
+ t.Fatal(err)
+ }
+ watchDone := make(chan struct{})
+ defer func() { stop(); <-watchDone }()
+ go func() {
+ defer close(watchDone)
+ timer := time.NewTimer(30 * time.Second)
+ defer timer.Stop()
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-jobCtx.Done():
+ return
+ case <-timer.C:
+ stop()
+ return
+ case <-ticker.C:
+ b, _ := os.ReadFile(l.work + "/diagnostics")
+ if bytes.Contains(b, []byte("witness-ready")) {
+ stop()
+ return
+ }
+ }
+ }
+ }()
+ }
+ start := time.Now()
+ out, err := w.runUnit(jobCtx, dir, lock)
+ if time.Since(start) > 185*time.Second {
+ t.Fatal("wall clock exceeded")
+ }
+ if !malicious && err != nil {
+ t.Fatal(err, out.Diagnostics)
+ }
+ if malicious {
+ b, e := os.ReadFile(l.work + "/diagnostics")
+ if err == nil || e != nil || !bytes.Contains(b, []byte("witness-ready")) {
+ t.Fatalf("malicious fixture did not reach timeout: %s %v %v", b, err, e)
+ }
+ if e = emptyBuildCgroup(l.unit); e != nil {
+ t.Fatal("descendant survived", e)
+ }
+ }
+ }
+ run(false)
+ // Every sentinel is fresh and world-readable/connectable outside the unit.
+ id, _ := NewJobID()
+ name := "demo-build-witness-" + id
+ paths := []string{"/data/" + name, "/etc/carlos/" + name}
+ for _, p := range paths {
+ f, e := os.OpenFile(p, 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(p)
+ }
+ socket := "/run/carlos-control/" + name
+ ln, err := net.Listen("unix", socket)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ if err = os.Chmod(socket, 0666); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CARLOS_DEMO_WITNESS_FILES", strings.Join(paths, ":"))
+ t.Setenv("CARLOS_DEMO_WITNESS_SOCKET", socket)
+ fixture := t.TempDir()
+ if err = os.Chmod(fixture, 0755); err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range []string{"bin", "cache"} {
+ if err = os.Mkdir(filepath.Join(fixture, d), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ in, err := os.Open(exe)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out, err := os.OpenFile(fixture+"/bin/go", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0555)
+ if err != nil {
+ in.Close()
+ t.Fatal(err)
+ }
+ _, err = io.Copy(out, in)
+ out.Close()
+ in.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(fixture+"/cache/seed", []byte("seed"), 0444); err != nil {
+ t.Fatal(err)
+ }
+ w.cfg.ToolchainDir = fixture
+ run(true)
+ b, err := os.ReadFile(fixture + "/cache/seed")
+ if err != nil || string(b) != "seed" {
+ t.Fatal("shared seed changed")
+ }
+}
diff --git a/internal/demobuild/unit_test.go b/internal/demobuild/unit_test.go
new file mode 100644
index 000000000..bd7557bbc
--- /dev/null
+++ b/internal/demobuild/unit_test.go
@@ -0,0 +1,135 @@
+//go:build linux
+
+package demobuild
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func fakeUnitController(t *testing.T) {
+ t.Helper()
+ oldCtl, oldRoot, oldCG := systemctl, unitRoot, buildCgroupRoot
+ unitRoot = t.TempDir()
+ buildCgroupRoot = t.TempDir()
+ systemctl = func(_ context.Context, args ...string) (string, error) {
+ if args[0] == "show" {
+ return "LoadState=not-found\nActiveState=inactive\nMainPID=0\nControlPID=0\n", nil
+ }
+ return "", nil
+ }
+ t.Cleanup(func() { systemctl, unitRoot, buildCgroupRoot = oldCtl, oldRoot, oldCG })
+}
+
+func TestDemoBuildCleanupRecovery(t *testing.T) {
+ fakeUnitController(t)
+ w, j, _, _ := workerFixture(t)
+ dir := filepath.Join(w.root, j.ID, "1")
+ if err := os.MkdirAll(dir+"/work/out", 0700); err != nil {
+ t.Fatal(err)
+ }
+ outside := t.TempDir()
+ sentinel := filepath.Join(outside, "keep")
+ os.WriteFile(sentinel, []byte("keep"), 0600)
+ os.Symlink(outside, dir+"/work/link")
+ os.Mkdir(filepath.Join(w.root, "unrelated"), 0700)
+ l, err := layoutIn(w.root, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.Mkdir(filepath.Join(unitRoot, l.unit+".d"), 0700)
+ os.WriteFile(filepath.Join(unitRoot, l.unit+".d/50-job.conf"), []byte("job"), 0600)
+ if err = w.recover(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = os.Stat(dir); !os.IsNotExist(err) {
+ t.Fatal("job scratch survived", err)
+ }
+ for _, p := range []string{sentinel, filepath.Join(w.root, "unrelated")} {
+ if _, err = os.Stat(p); err != nil {
+ t.Fatal("unrelated path removed", err)
+ }
+ }
+}
+
+func TestDemoBuildCleanupRefusesLiveDescendant(t *testing.T) {
+ fakeUnitController(t)
+ w, j, _, _ := workerFixture(t)
+ dir := filepath.Join(w.root, j.ID, "1")
+ os.MkdirAll(dir+"/work", 0700)
+ l, err := layoutIn(w.root, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.Mkdir(filepath.Join(buildCgroupRoot, l.unit), 0755)
+ os.WriteFile(filepath.Join(buildCgroupRoot, l.unit, "cgroup.events"), []byte("populated 1\n"), 0600)
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if err = w.cleanUnit(ctx, l); err == nil {
+ t.Fatal("removed live job")
+ }
+ if _, err = os.Stat(dir); err != nil {
+ t.Fatal("removed scratch without termination proof", err)
+ }
+ os.WriteFile(filepath.Join(buildCgroupRoot, l.unit, "cgroup.events"), []byte("populated 0\n"), 0600)
+ if err = w.cleanUnit(context.Background(), l); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDemoBuildFixedPaths(t *testing.T) {
+ _, j, _, _ := workerFixture(t)
+ for _, p := range []string{"/caller/path", BuildRoot + "/../outside/1", BuildRoot + "/" + j.ID + "/01", BuildRoot + "/" + j.ID + "/0", BuildRoot + "/" + j.ID + "/1/extra"} {
+ if _, err := layout(p); err == nil {
+ t.Fatal("accepted", p)
+ }
+ }
+ l, err := layout(BuildRoot + "/" + j.ID + "/1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.ContainsAny(l.unit, "/ \n%") || len(l.unit) > 255 || !strings.HasPrefix(l.unit, "carlos-demo-build@") {
+ t.Fatal(l.unit)
+ }
+ if bindsEqual("/correct:/work /extra:/etc", []string{"/correct:/work"}) || bindsEqual("/wrong:/work", []string{"/correct:/work"}) {
+ t.Fatal("accepted unexpected bind")
+ }
+}
+
+func TestDemoBuildStartupSwitch(t *testing.T) {
+ called := false
+ w, err := NewWorker(func(k string) string {
+ if k != "CARLOS_DEMO_BUILD_WORKER" {
+ t.Fatal("off switch read", k)
+ }
+ return ""
+ }, func(context.Context) error { called = true; return nil })
+ if w != nil || err != nil || called {
+ t.Fatal(w, err, called)
+ }
+ for _, value := range []string{"0", "1", "true"} {
+ if _, err := NewWorker(func(k string) string {
+ if k == "CARLOS_DEMO_BUILD_WORKER" {
+ return value
+ }
+ return ""
+ }, func(context.Context) error { return nil }); err == nil {
+ t.Fatal("worker without root box tuple")
+ }
+ }
+}
+
+func TestDemoBuildBudgetReadback(t *testing.T) {
+ fakeUnitController(t)
+ w := &Worker{slots: make(chan struct{}, 3)}
+ systemctl = func(context.Context, ...string) (string, error) {
+ return "MemoryMax=3221225472\nMemorySwapMax=0\nTasksMax=384\nCPUQuotaPerSecUSec=1.500000s\n", nil
+ }
+ if err := w.assertBudget(context.Background()); err != nil {
+ t.Fatal("canonical systemd 257 readback refused", err)
+ }
+}
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go
new file mode 100644
index 000000000..5d7b6302b
--- /dev/null
+++ b/internal/demobuild/worker.go
@@ -0,0 +1,278 @@
+package demobuild
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/hostwrite"
+ "github.com/carlosframework/platform/internal/instancefs"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const BuildRoot = "/var/lib/carlos-demo-builds"
+
+// Worker belongs to the root service, surviving agent disconnects and restarts.
+// An exclusive root-process lock and recovery precede any readiness response.
+type Worker struct {
+ cfg demo.Config
+ box string
+ pub ed25519.PublicKey
+ lock Lock
+ digest, root string
+ slots chan struct{}
+ proof func(context.Context) error
+ prepare func(context.Context, string, Source) (func() error, error)
+ run func(context.Context, string, Lock) (BuildOutput, error)
+ processLock *os.File
+ mu sync.Mutex
+ poisoned bool
+}
+
+func NewWorker(getenv func(string) string, proof func(context.Context) error) (*Worker, error) {
+ if getenv("CARLOS_DEMO_BUILD_WORKER") == "" {
+ return nil, nil
+ }
+ boxCfg, err := demo.BoxConfig(getenv)
+ if err != nil || !boxCfg.BoxMode() || hostwrite.Enabled(getenv) || runtime.GOOS != "linux" || runtime.GOARCH != "arm64" || os.Geteuid() != 0 {
+ return nil, ErrBuild
+ }
+ cfg, err := demo.LoadConfig(getenv)
+ if err != nil || !cfg.BuildWorker {
+ return nil, ErrBuild
+ }
+ box := strings.TrimSpace(getenv("CARLOS_FLEET_BOX"))
+ if box == "" {
+ var ok bool
+ box, ok = strings.CutPrefix(strings.TrimSpace(getenv("CARLOS_TUNNEL_NAME")), cfg.Fleet+"/")
+ if !ok {
+ return nil, ErrBuild
+ }
+ }
+ if strings.TrimSpace(getenv("CARLOS_FLEET")) != cfg.Fleet || !registry.ValidTunnelName(box) || proof == nil {
+ return nil, ErrBuild
+ }
+ pub, err := release.ParsePublicKey(getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY")
+ if err != nil {
+ return nil, ErrBuild
+ }
+ lock, err := DefaultLock()
+ if err != nil {
+ return nil, err
+ }
+ digest, err := CheckBundle(cfg.ToolchainDir, lock)
+ if err != nil {
+ return nil, err
+ }
+ r, err := instancefs.OpenRootBeneath(BuildRoot, ".")
+ if err != nil {
+ return nil, err
+ }
+ defer r.Close()
+ st, err := r.Stat(".")
+ if err != nil || !immutableRootFile(st) || st.Mode().Perm() != 0700 {
+ return nil, ErrBuild
+ }
+ guard, err := lockWorker(BuildRoot)
+ if err != nil {
+ return nil, err
+ }
+ w := &Worker{cfg: cfg, box: box, pub: pub, lock: lock, digest: digest, root: BuildRoot, slots: make(chan struct{}, cfg.BuildConcurrency), proof: proof, processLock: guard}
+ w.prepare = w.prepareUnit
+ w.run = w.runUnit
+ ctx, cancel := context.WithTimeout(context.Background(), BuildWindow)
+ defer cancel()
+ if err = w.recover(ctx); err != nil {
+ guard.Close()
+ return nil, err
+ }
+ if err = w.probeBundle(ctx); err != nil {
+ guard.Close()
+ return nil, err
+ }
+ return w, nil
+}
+
+func (w *Worker) Close() error {
+ if w == nil || w.processLock == nil {
+ return nil
+ }
+ return w.processLock.Close()
+}
+
+func (w *Worker) Readiness(ctx context.Context) (WorkerReady, error) {
+ w.mu.Lock()
+ bad := w.poisoned
+ w.mu.Unlock()
+ if bad || w.proof == nil || w.proof(ctx) != nil {
+ return WorkerReady{}, ErrBuild
+ }
+ if err := w.assertBudget(ctx); err != nil {
+ return WorkerReady{}, err
+ }
+ return WorkerReady{Capability: "anonymous-demo-v1", GOARCH: "arm64", BundleSHA256: w.digest, Slots: cap(w.slots)}, nil
+}
+
+func (w *Worker) validate(wire []byte) (Job, error) {
+ j, err := VerifyJob(w.pub, wire, time.Now())
+ if err != nil || time.Until(j.Deadline) > BuildWindow || j.Box != w.box || j.BundleSHA256 != w.digest {
+ return Job{}, ErrJob
+ }
+ d := demo.Descriptor{ID: j.DemoID, Host: j.Host, Lifetime: j.Lifetime, ExpiresAt: j.Deadline.Unix()}
+ if w.cfg.ValidateBinding(d, j.Account, j.App, j.Host, j.Lifetime, j.Fleet) != nil {
+ return Job{}, ErrJob
+ }
+ return j, nil
+}
+
+func (w *Worker) GrantDeadline(wire []byte) (time.Time, error) {
+ j, err := w.validate(wire)
+ return j.Deadline, err
+}
+
+func (w *Worker) Build(ctx context.Context, wire []byte, source io.Reader) (out BuildOutput, err error) {
+ j, err := w.validate(wire)
+ if err != nil {
+ return out, err
+ }
+ ctx, cancel := context.WithDeadline(ctx, j.Deadline)
+ defer cancel()
+ select {
+ case w.slots <- struct{}{}:
+ defer func() { <-w.slots }()
+ default:
+ return out, ErrBuild
+ }
+ w.mu.Lock()
+ bad := w.poisoned
+ w.mu.Unlock()
+ if bad || w.proof(ctx) != nil {
+ return out, ErrBuild
+ }
+ if err = w.reserve(j); err != nil {
+ return out, err
+ }
+ src, diags, err := ValidateSource(source, w.lock)
+ if err != nil {
+ return BuildOutput{Diagnostics: diags}, err
+ }
+ if src.SHA256 != j.SourceSHA256 || ctx.Err() != nil || !time.Now().Before(j.Deadline) {
+ return out, ErrJob
+ }
+ dir := filepath.Join(w.root, j.ID, strconv.FormatUint(uint64(j.Attempt), 10))
+ cleanup, err := w.prepare(ctx, dir, src)
+ if cleanup != nil {
+ defer func() {
+ if e := cleanup(); e != nil {
+ w.mu.Lock()
+ w.poisoned = true
+ w.mu.Unlock()
+ out = BuildOutput{}
+ err = errors.Join(err, e)
+ }
+ }()
+ }
+ if err != nil {
+ return out, err
+ }
+ return w.run(ctx, dir, w.lock)
+}
+
+// A root-owned durable marker forbids a second invocation of this job, even
+// after successful scratch cleanup or an agent/root-service restart. Markers
+// may be retired only after their signed deadline; no compiler sees them.
+func (w *Worker) reserve(j Job) error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ r, err := instancefs.OpenRootBeneath(w.root, ".")
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ if err = r.Mkdir("seen", 0700); err != nil && !os.IsExist(err) {
+ return err
+ }
+ if err = w.expireMarkers(); err != nil {
+ return err
+ }
+ f, err := instancefs.OpenBeneath(w.root, "seen/"+j.ID, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
+ if err != nil {
+ return ErrJob
+ }
+ b, err := json.Marshal(j)
+ if err != nil {
+ f.Close()
+ return err
+ }
+ _, err = f.Write(b)
+ if err == nil {
+ err = f.Sync()
+ }
+ err = errors.Join(err, f.Close())
+ if err != nil {
+ return err
+ }
+ d, err := instancefs.OpenDirBeneath(w.root, "seen")
+ if err != nil {
+ return err
+ }
+ defer d.Close()
+ if err = d.Sync(); err != nil {
+ return err
+ }
+ parent, err := instancefs.OpenDirBeneath(w.root, ".")
+ if err != nil {
+ return err
+ }
+ defer parent.Close()
+ return parent.Sync()
+}
+
+func (w *Worker) expireMarkers() error {
+ d, err := instancefs.OpenDirBeneath(w.root, "seen")
+ if err != nil {
+ return err
+ }
+ defer d.Close()
+ entries, err := d.ReadDir(-1)
+ if err != nil {
+ return err
+ }
+ r, err := instancefs.OpenRootBeneath(w.root, "seen")
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ for _, e := range entries {
+ if !ValidJobID(e.Name()) {
+ continue
+ }
+ f, err := instancefs.OpenBeneath(w.root, "seen/"+e.Name(), os.O_RDONLY, 0)
+ if err != nil {
+ return err
+ }
+ b, err := io.ReadAll(io.LimitReader(f, MaxJobWire+1))
+ f.Close()
+ var j Job
+ if err != nil || len(b) > MaxJobWire || DecodeMessage(b, &j) != nil || j.ID != e.Name() || j.validate() != nil {
+ return ErrBuild
+ }
+ if !time.Now().Before(j.Deadline) {
+ if err = r.Remove(e.Name()); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/demobuild/worker_test.go b/internal/demobuild/worker_test.go
new file mode 100644
index 000000000..2e1a6a5b6
--- /dev/null
+++ b/internal/demobuild/worker_test.go
@@ -0,0 +1,162 @@
+//go:build linux
+
+package demobuild
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func workerFixture(t *testing.T) (*Worker, Job, ed25519.PrivateKey, []byte) {
+ t.Helper()
+ pub, priv, _ := ed25519.GenerateKey(rand.Reader)
+ src := archive(t, starter(t))
+ v, _, err := ValidateSource(bytes.NewReader(src), testLock(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := &Worker{cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1}, box: "box-1", pub: pub, lock: testLock(t), digest: strings.Repeat("b", 64), root: t.TempDir(), slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }}
+ w.prepare = func(context.Context, string, Source) (func() error, error) { return func() error { return nil }, nil }
+ w.run = func(context.Context, string, Lock) (BuildOutput, error) { return BuildOutput{}, nil }
+ j := Job{ID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)), DemoID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{2}, 16)), Account: "shop", App: "tmp-demo-bright-otter-42", Host: "bright-otter-42.example.com", Lifetime: "life-1", Fleet: "demo", Box: "box-1", SourceSHA256: v.SHA256, BundleSHA256: w.digest, Generation: 1, Attempt: 1, Deadline: time.Now().UTC().Add(time.Minute)}
+ return w, j, priv, src
+}
+
+type neverRead struct{ t *testing.T }
+
+func (r neverRead) Read([]byte) (int, error) {
+ r.t.Fatal("read source before grant refusal")
+ return 0, io.EOF
+}
+
+func TestDemoBuildWrongGrant(t *testing.T) {
+ for _, mutate := range []func(*Job){func(j *Job) { j.Account = "other" }, func(j *Job) { j.Box = "box-2" }, func(j *Job) { j.Fleet = "other" }, func(j *Job) { j.Host = "bright-otter-42.other.example.com" }, func(j *Job) { j.BundleSHA256 = strings.Repeat("c", 64) }, func(j *Job) { j.Deadline = time.Now().Add(181 * time.Second) }} {
+ w, j, priv, _ := workerFixture(t)
+ mutate(&j)
+ wire, err := SignJob(priv, j)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = w.Build(context.Background(), wire, neverRead{t}); err == nil {
+ t.Fatal("accepted wrong grant")
+ }
+ files, _ := os.ReadDir(w.root)
+ if len(files) != 0 {
+ t.Fatal("wrong grant created root state")
+ }
+ }
+}
+
+func TestDemoBuildSlotsAndReplay(t *testing.T) {
+ w, j, priv, src := workerFixture(t)
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ var live atomic.Int32
+ w.run = func(ctx context.Context, _ string, _ Lock) (BuildOutput, error) {
+ if live.Add(1) > 1 {
+ t.Error("concurrency exceeded")
+ }
+ close(entered)
+ <-release
+ live.Add(-1)
+ return BuildOutput{}, nil
+ }
+ wire, _ := SignJob(priv, j)
+ done := make(chan error, 1)
+ go func() { _, err := w.Build(context.Background(), wire, bytes.NewReader(src)); done <- err }()
+ <-entered
+ j.ID = base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32))
+ second, _ := SignJob(priv, j)
+ if _, err := w.Build(context.Background(), second, neverRead{t}); err == nil {
+ t.Fatal("overfilled slots")
+ }
+ close(release)
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Build(context.Background(), wire, neverRead{t}); err == nil {
+ t.Fatal("replayed completed attempt")
+ }
+ // A new process reads the same durable marker before it opens source.
+ w2 := &Worker{cfg: w.cfg, box: w.box, pub: w.pub, lock: w.lock, digest: w.digest, root: w.root, slots: make(chan struct{}, 1), proof: w.proof, prepare: w.prepare, run: w.run}
+ if _, err := w2.Build(context.Background(), wire, neverRead{t}); err == nil {
+ t.Fatal("replayed after root restart")
+ }
+}
+
+func TestDemoBuildCleanupOrder(t *testing.T) {
+ for _, failure := range []string{"success", "compile", "cancel", "stop"} {
+ t.Run(failure, func(t *testing.T) {
+ dir := t.TempDir()
+ os.Mkdir(filepath.Join(dir, "out"), 0755)
+ os.WriteFile(filepath.Join(dir, "out/app"), arm64ELF(), 0644)
+ stopped := false
+ i := &runInvocation{dir: dir, startWait: func(ctx context.Context) error {
+ if failure == "compile" {
+ return errors.New("compile")
+ }
+ if failure == "cancel" {
+ return context.Canceled
+ }
+ return nil
+ }, stop: func() error {
+ stopped = true
+ if failure == "stop" {
+ return errors.New("stop unproven")
+ }
+ return nil
+ }}
+ out, err := Run(context.WithValue(context.Background(), runContextKey{}, i), dir, testLock(t))
+ if !stopped || (err == nil) != (failure == "success") {
+ t.Fatalf("stop=%v err=%v", stopped, err)
+ }
+ if failure != "success" && len(out.Binary) != 0 {
+ t.Fatal("collected before successful termination")
+ }
+ })
+ }
+}
+
+func TestDemoBuildOutputSymlink(t *testing.T) {
+ dir := t.TempDir()
+ outside := filepath.Join(t.TempDir(), "app")
+ if err := os.WriteFile(outside, arm64ELF(), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(filepath.Join(dir, "out"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outside, filepath.Join(dir, "out/app")); err != nil {
+ t.Fatal(err)
+ }
+ i := &runInvocation{dir: dir, startWait: func(context.Context) error { return nil }, stop: func() error { return nil }}
+ if _, err := Run(context.WithValue(t.Context(), runContextKey{}, i), dir, testLock(t)); err == nil {
+ t.Fatal("followed output outside job")
+ }
+}
+
+func TestDemoBuildSourceHash(t *testing.T) {
+ w, j, priv, src := workerFixture(t)
+ j.SourceSHA256 = strings.Repeat("d", 64)
+ w.prepare = func(context.Context, string, Source) (func() error, error) {
+ t.Fatal("wrong source reached filesystem preparation")
+ return nil, nil
+ }
+ wire, _ := SignJob(priv, j)
+ if _, err := w.Build(t.Context(), wire, bytes.NewReader(src)); err == nil {
+ t.Fatal("accepted different source")
+ }
+}
diff --git a/internal/host/claimunit.go b/internal/host/claimunit.go
index 93b4b0b3b..1e9a123a4 100644
--- a/internal/host/claimunit.go
+++ b/internal/host/claimunit.go
@@ -29,7 +29,7 @@ type claimUnitSettings struct {
}
func readClaimUnitSettings(path string) (settings claimUnitSettings, readErr error) {
- values := map[string]string{"CARLOS_HOST_CLAIM": "", "CARLOS_DATA_DIR": "", "CARLOS_OPT_DIR": "", "CARLOS_DEMO_BOX": "", "CARLOS_DEMO_ACCOUNT": "", "CARLOS_DEMO_FLEET": "", "CARLOS_DEMO_DOMAIN": ""}
+ values := map[string]string{"CARLOS_HOST_CLAIM": "", "CARLOS_DATA_DIR": "", "CARLOS_OPT_DIR": "", "CARLOS_DEMO_BOX": "", "CARLOS_DEMO_ACCOUNT": "", "CARLOS_DEMO_FLEET": "", "CARLOS_DEMO_DOMAIN": "", "CARLOS_DEMO_BUILD_WORKER": "", "CARLOS_DEMO_BUILD_CONCURRENCY": "", "CARLOS_DEMO_TOOLCHAIN_DIR": ""}
raw, err := readClaimUnitFile(path)
defer func() {
if readErr != nil && demoBoxSettingPresent(raw) {
@@ -82,6 +82,13 @@ func readClaimUnitSettings(path string) (settings claimUnitSettings, readErr err
if err != nil {
return claimUnitSettings{}, err
}
+ if values["CARLOS_DEMO_BUILD_WORKER"] != "" {
+ worker, e := demo.LoadConfig(func(k string) string { return values[k] })
+ if e != nil || !cfg.demo.BoxMode() || cfg.enabled {
+ return claimUnitSettings{}, demo.ErrConfig
+ }
+ cfg.demo.BuildWorker, cfg.demo.BuildConcurrency, cfg.demo.ToolchainDir = worker.BuildWorker, worker.BuildConcurrency, worker.ToolchainDir
+ }
if cfg.data == "" {
cfg.data = "/data"
}
@@ -105,12 +112,20 @@ func readClaimUnitSettings(path string) (settings claimUnitSettings, readErr err
}
func claimUnitContent(name string, content []byte, cfg claimUnitSettings) []byte {
+ if name == "carlos-demo-builds.slice" && cfg.demo.BuildWorker {
+ return []byte(fmt.Sprintf("[Unit]\nDescription=carlos offline demo build budget\n\n[Slice]\nMemoryMax=%d\nMemorySwapMax=0\nTasksMax=%d\nCPUQuota=%d%%\nCPUWeight=10\n", int64(cfg.demo.BuildConcurrency)*1073741824, cfg.demo.BuildConcurrency*128, cfg.demo.BuildConcurrency*50))
+ }
if name != claimControlUnit {
return content
}
if !cfg.enabled {
if cfg.demo.BoxMode() {
- return bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\n"+claimControlEnvironment), 1)
+ content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\n"+claimControlEnvironment), 1)
+ if cfg.demo.BuildWorker {
+ content = bytes.Replace(content, []byte("[Service]\n"), []byte("[Service]\nStateDirectory=carlos-demo-builds\nStateDirectoryMode=0700\nReadWritePaths=/var/lib/carlos-demo-builds\n"), 1)
+ content = bytes.Replace(content, []byte("MemoryMax=64M\n"), []byte("MemoryMax=1073741824\nEnvironment=GOMEMLIMIT=768MiB\n"), 1)
+ }
+ return content
}
return content
}
diff --git a/internal/host/demo_build_linux_test.go b/internal/host/demo_build_linux_test.go
new file mode 100644
index 000000000..f96c56be9
--- /dev/null
+++ b/internal/host/demo_build_linux_test.go
@@ -0,0 +1,153 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+func TestDemoBuildUnitContract(t *testing.T) {
+ b, err := unitsFS.ReadFile("units/carlos-demo-build@.service")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := string(b)
+ for _, want := range []string{
+ "DynamicUser=yes", "PrivateNetwork=yes", "RestrictAddressFamilies=AF_UNIX",
+ "MemoryMax=1073741824", "MemorySwapMax=0", "TasksMax=128", "CPUQuota=50%", "CPUWeight=10",
+ "RuntimeMaxSec=180", "TimeoutStopSec=5", "KillMode=control-group", "MemoryDenyWriteExecute=yes",
+ "CapabilityBoundingSet=", "WorkingDirectory=/work/src",
+ "ExecStart=/opt/carlos/demo-toolchain/bin/go build -mod=readonly -trimpath -buildvcs=false -o /work/out/app .",
+ } {
+ if !strings.Contains(s, "\n"+want+"\n") {
+ t.Error(want)
+ }
+ }
+ for _, list := range [][]string{enabledUnits, ensureSystemArmed} {
+ for _, name := range list {
+ if strings.HasPrefix(name, "carlos-demo-build") {
+ t.Fatalf("builder armed: %s", name)
+ }
+ }
+ }
+ for _, problem := range demoHiddenRequiredPaths(s, "[Service]\nBindPaths=/fixture/work:/work\nBindReadOnlyPaths=/fixture/bundle:/opt/carlos/demo-toolchain /fixture/work/src:/work/src\n") {
+ t.Error(problem)
+ }
+ if strings.Contains(s, "[Install]") {
+ t.Fatal("builder enables itself")
+ }
+}
+
+func TestDemoBuildInstallation(t *testing.T) {
+ control, err := unitsFS.ReadFile("units/" + claimControlUnit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ slice, err := unitsFS.ReadFile("units/carlos-demo-builds.slice")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := claimUnitContent(claimControlUnit, control, claimUnitSettings{}); string(got) != string(control) {
+ t.Fatal("off control changed")
+ }
+ for n := 1; n <= 4; n++ {
+ cfg := claimUnitSettings{demo: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildWorker: true, BuildConcurrency: n}}
+ got := string(claimUnitContent(claimControlUnit, control, cfg))
+ for _, want := range []string{"StateDirectory=carlos-demo-builds", "StateDirectoryMode=0700", "ReadWritePaths=/var/lib/carlos-demo-builds", "MemoryMax=1073741824"} {
+ if !strings.Contains(got, want) {
+ t.Error(want)
+ }
+ }
+ got = string(claimUnitContent("carlos-demo-builds.slice", slice, cfg))
+ if !strings.Contains(got, "MemoryMax="+strconv.FormatInt(int64(n)*1073741824, 10)+"\n") {
+ t.Fatal(got)
+ }
+ }
+ dir := t.TempDir()
+ env := filepath.Join(dir, "host.env")
+ if err := os.WriteFile(env, []byte("CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\nCARLOS_DEMO_BUILD_WORKER=1\nCARLOS_DEMO_BUILD_CONCURRENCY=3\nCARLOS_DEMO_TOOLCHAIN_DIR=/opt/demo-toolchain\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ cfg, err := readClaimUnitSettings(env)
+ if err != nil || !cfg.demo.BuildWorker || cfg.demo.BuildConcurrency != 3 {
+ t.Fatalf("root config: %+v %v", cfg, err)
+ }
+}
+
+func TestDemoBuildIsolation(t *testing.T) {
+ if os.Getenv("CARLOS_DEMO_KERNEL_WITNESS") != "1" {
+ t.Skip("kernel witness outstanding: needs a designated systemd sandbox (not evidence)")
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 6*time.Minute)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "nice", "-n", "10", "go", "test", ".", "-run", "^TestDemoBuildKernel$", "-count=1", "-v")
+ cmd.Dir = "../demobuild"
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("kernel witness: %s: %v", out, err)
+ }
+ t.Log(string(out))
+}
+
+func TestDemoBuildAllInstallers(t *testing.T) {
+ writeEnv := func(etc string, n int) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Join(etc, "carlos"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ raw := "CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\nCARLOS_DEMO_BUILD_WORKER=1\nCARLOS_DEMO_TOOLCHAIN_DIR=/opt/demo-toolchain\nCARLOS_DEMO_BUILD_CONCURRENCY=" + strconv.Itoa(n) + "\n"
+ if err := os.WriteFile(filepath.Join(etc, "carlos/host.env"), []byte(raw), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ check := func(etc string, n int) {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join(etc, "systemd/system/carlos-demo-builds.slice"))
+ if err != nil || !strings.Contains(string(b), "MemoryMax="+strconv.FormatInt(int64(n)*1073741824, 10)+"\n") {
+ t.Fatal("slice budget", string(b), err)
+ }
+ }
+ stage := t.TempDir()
+ writeEnv(filepath.Join(stage, "etc"), 1)
+ if err := bootstrap(stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ check(filepath.Join(stage, "etc"), 1)
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ writeEnv(f.a.etcDir, 3)
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ check(f.a.etcDir, 3)
+ etc := t.TempDir()
+ writeEnv(etc, 4)
+ ctl := func(args ...string) (string, error) {
+ if (args[0] == "enable" || args[0] == "start") && strings.Contains(strings.Join(args, " "), "carlos-demo-build") {
+ t.Fatal("armed builder", args)
+ }
+ return "", nil
+ }
+ probe := func(args ...string) (string, error) {
+ if args[1] == dbReadSocketUnit {
+ if args[0] == "is-active" {
+ return "inactive\n", systemctlExit(3)
+ }
+ return "disabled\n", systemctlExit(1)
+ }
+ if args[0] == "is-active" {
+ return "active\n", nil
+ }
+ return "enabled\n", nil
+ }
+ ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), ctl, probe, t.Logf)
+ check(etc, 4)
+}
diff --git a/internal/host/demo_jobs.go b/internal/host/demo_jobs.go
index 5a453ff42..804498543 100644
--- a/internal/host/demo_jobs.go
+++ b/internal/host/demo_jobs.go
@@ -70,13 +70,6 @@ func startDemoWorker(ctx context.Context) {
log.Printf("agent: demo worker: root build backend unavailable")
return
}
- rctx, cancel := context.WithTimeout(ctx, 10*time.Second)
- ready, err := root.DemoBuildReadiness(rctx)
- cancel()
- if err != nil || !ready.Valid() || ready.Slots != cfg.BuildConcurrency {
- log.Printf("agent: demo worker: root readiness refused")
- return
- }
pub, err := release.ParsePublicKey(os.Getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY")
if err != nil {
log.Printf("agent: demo worker: release key unavailable")
@@ -88,13 +81,25 @@ func startDemoWorker(ctx context.Context) {
log.Printf("agent: demo worker: store door unavailable")
return
}
- w := &demoWorker{cfg: cfg, pub: pub, box: identity.Label, base: strings.TrimRight(os.Getenv("CARLOS_TUNNEL_URL"), "/"), ready: ready, store: store, credentials: fleetCredential(os.Getenv), build: root.BuildDemo, notify: func() { backstopFullDue.Store(true) }}
+ w := &demoWorker{cfg: cfg, pub: pub, box: identity.Label, base: strings.TrimRight(os.Getenv("CARLOS_TUNNEL_URL"), "/"), store: store, credentials: fleetCredential(os.Getenv), build: root.BuildDemo, notify: func() { backstopFullDue.Store(true) }}
w.http = &http.Client{Timeout: demobuild.ResultGrace, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
w.pickup = w.pickupHTTP
go func() {
delay := time.Second
for {
- if err := w.Connect(ctx); ctx.Err() != nil {
+ // Root's first readiness check compiles a trusted smoke source in
+ // the sandbox. Retry on this existing reconnect path while it
+ // initializes; no console/store polling is added.
+ rctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ ready, err := root.DemoBuildReadiness(rctx)
+ cancel()
+ if err == nil && ready.Valid() && ready.Slots == cfg.BuildConcurrency {
+ w.ready = ready
+ err = w.Connect(ctx)
+ } else if err == nil {
+ err = demobuild.ErrBuild
+ }
+ if ctx.Err() != nil {
return
} else if err != nil {
log.Printf("agent: demo stream: %v", err)
@@ -155,13 +160,15 @@ func (w *demoWorker) Accept(ctx context.Context, signedJob []byte) error {
if err != nil {
out.Binary = nil
- out.Diagnostics = []demobuild.Diagnostic{{Message: "DEMO-BUILD"}}
+ if len(out.Diagnostics) == 0 {
+ out.Diagnostics = []demobuild.Diagnostic{{Message: "DEMO-BUILD"}}
+ }
}
if len(out.Binary) > demobuild.BinaryMaxBytes {
return demobuild.ErrJob
}
sum := sha256.Sum256(out.Binary)
- result := demobuild.Result{JobID: j.ID, Attempt: j.Attempt, SourceSHA256: j.SourceSHA256, BundleSHA256: j.BundleSHA256, BinarySHA256: hex.EncodeToString(sum[:]), BinarySize: int64(len(out.Binary)), Diagnostics: out.Diagnostics}
+ result := demobuild.Result{JobID: j.ID, Attempt: j.Attempt, SourceSHA256: j.SourceSHA256, BundleSHA256: j.BundleSHA256, BinarySHA256: hex.EncodeToString(sum[:]), BinarySize: int64(len(out.Binary)), Diagnostics: out.Diagnostics, DiagnosticsTruncated: out.DiagnosticsTruncated}
uploadCtx, uploadCancel := context.WithDeadline(ctx, picked.Deadline.Add(demobuild.ResultGrace))
defer uploadCancel()
return w.uploadResult(uploadCtx, picked, result, out.Binary)
diff --git a/internal/host/demo_toolchain.go b/internal/host/demo_toolchain.go
new file mode 100644
index 000000000..15ecf65ce
--- /dev/null
+++ b/internal/host/demo_toolchain.go
@@ -0,0 +1,8 @@
+package host
+
+import "github.com/carlosframework/platform/internal/demobuild"
+
+func CheckDemoToolchain(dir string, lock demobuild.Lock) error {
+ _, err := demobuild.CheckBundle(dir, lock)
+ return err
+}
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index 7a2fb2250..1be22c4a4 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -1412,8 +1412,11 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
if e.IsDir() {
continue
}
- if e.Name() == claimControlUnit {
- if keepControl {
+ if e.Name() == claimControlUnit || e.Name() == "carlos-demo-builds.slice" {
+ if settingsErr != nil && e.Name() == "carlos-demo-builds.slice" {
+ continue
+ }
+ if keepControl && e.Name() == claimControlUnit {
a.ops.logf("system apply: %s kept as installed: host.env cannot be parsed", claimControlUnit)
continue
}
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index d3b5d50c2..20ab61df9 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -33,7 +33,7 @@ var ensureSystemArmed = []string{systemUpdatePathUnit, systemRecoverUnit, instan
// carlos-dbread.socket and its service template are the db-read worker's
// (db region forward spec §8.3): installed and the socket armed here, the
// template never started.
-var systemUnitFiles = []string{"carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service", dbReadSocketUnit, "carlos-dbread@.service"}
+var systemUnitFiles = []string{"carlos-system-update.path", "carlos-system-update.service", systemRecoverUnit, instanceControlSocket, "carlos-instance-control.service", dbReadSocketUnit, "carlos-dbread@.service", "carlos-demo-build@.service", "carlos-demo-builds.slice"}
// ensureSystemUnits is the second belt of spec §7: a box the roll script
// forgot to arm is armed within the hour by the root adopt pass. It
diff --git a/internal/host/units/carlos-demo-build@.service b/internal/host/units/carlos-demo-build@.service
new file mode 100644
index 000000000..112afcc2f
--- /dev/null
+++ b/internal/host/units/carlos-demo-build@.service
@@ -0,0 +1,63 @@
+[Unit]
+Description=carlos offline demo build
+BindsTo=carlos-instance-control.service
+After=carlos-instance-control.service
+
+[Service]
+Type=exec
+RemainAfterExit=yes
+DynamicUser=yes
+Slice=carlos-demo-builds.slice
+ExecStart=/opt/carlos/demo-toolchain/bin/go build -mod=readonly -trimpath -buildvcs=false -o /work/out/app .
+WorkingDirectory=/work/src
+Restart=no
+KillMode=control-group
+RuntimeMaxSec=180
+TimeoutStopSec=5
+SendSIGKILL=yes
+OOMPolicy=kill
+MemoryMax=1073741824
+MemorySwapMax=0
+TasksMax=128
+CPUQuota=50%
+CPUWeight=10
+LimitFSIZE=33554432
+UMask=0077
+Environment=GOTOOLCHAIN=local GOPROXY=off GOSUMDB=off GOWORK=off GOENV=off CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOFLAGS=
+Environment=GOROOT=/opt/carlos/demo-toolchain GOMODCACHE=/opt/carlos/demo-toolchain/mod GOCACHE=/work/cache GOTMPDIR=/work/tmp TMPDIR=/work/tmp GOPATH=/work/home HOME=/work/home PATH=/opt/carlos/demo-toolchain/bin GOTELEMETRY=off
+PassEnvironment=
+UnsetEnvironment=LD_PRELOAD LD_LIBRARY_PATH GOCACHEPROG GOEXPERIMENT GODEBUG GOTOOLDIR GOARM64 GO_EXTLINK_ENABLED CC CXX PKG_CONFIG
+SetLoginEnvironment=no
+StandardInput=null
+StandardOutput=null
+StandardError=null
+ProtectSystem=strict
+ProtectHome=yes
+TemporaryFileSystem=/data:ro /run:ro /var:ro /opt:ro /tmp:ro
+InaccessiblePaths=/etc/carlos -/run/carlos-control
+PrivateDevices=yes
+TemporaryFileSystem=/dev/shm:ro /dev/mqueue:ro /dev/pts:ro
+PrivateIPC=yes
+PrivatePIDs=yes
+PrivateNetwork=yes
+NetworkNamespacePath=
+RestrictAddressFamilies=AF_UNIX
+IPAddressDeny=any
+IPAddressAllow=
+CapabilityBoundingSet=
+AmbientCapabilities=
+NoNewPrivileges=yes
+RestrictNamespaces=yes
+ProtectControlGroups=yes
+ProtectProc=invisible
+ProcSubset=pid
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectKernelLogs=yes
+ProtectClock=yes
+ProtectHostname=yes
+RemoveIPC=yes
+LockPersonality=yes
+RestrictRealtime=yes
+MemoryDenyWriteExecute=yes
+SystemCallArchitectures=native
diff --git a/internal/host/units/carlos-demo-builds.slice b/internal/host/units/carlos-demo-builds.slice
new file mode 100644
index 000000000..616541b58
--- /dev/null
+++ b/internal/host/units/carlos-demo-builds.slice
@@ -0,0 +1,9 @@
+[Unit]
+Description=carlos offline demo build budget
+
+[Slice]
+MemoryMax=1073741824
+MemorySwapMax=0
+TasksMax=128
+CPUQuota=50%
+CPUWeight=10
diff --git a/internal/instancectl/demo_build.go b/internal/instancectl/demo_build.go
new file mode 100644
index 000000000..4e3b78184
--- /dev/null
+++ b/internal/instancectl/demo_build.go
@@ -0,0 +1,133 @@
+package instancectl
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "encoding/json"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+// The request is a big-endian uint32 grant length, signed grant bytes, then
+// the bounded original source archive. There is no path or command field.
+func (c *Client) BuildDemo(ctx context.Context, signedJob []byte, source io.Reader) (demobuild.BuildOutput, error) {
+ if len(signedJob) == 0 || len(signedJob) > demobuild.MaxJobWire {
+ return demobuild.BuildOutput{}, demobuild.ErrJob
+ }
+ ctx, cancel := context.WithTimeout(ctx, demobuild.BuildWindow+5*time.Second)
+ defer cancel()
+ var header [4]byte
+ binary.BigEndian.PutUint32(header[:], uint32(len(signedJob)))
+ body := io.MultiReader(bytes.NewReader(header[:]), bytes.NewReader(signedJob), io.LimitReader(source, demo.SourceMaxBytes+1))
+ req, err := http.NewRequestWithContext(ctx, "POST", "http://control/demo-build", body)
+ if err != nil {
+ return demobuild.BuildOutput{}, err
+ }
+ resp, err := c.httpClient().Do(req)
+ if err != nil {
+ return demobuild.BuildOutput{}, err
+ }
+ defer resp.Body.Close()
+ var out demobuild.BuildOutput
+ // JSON's base64 binary encoding expands by 4/3. The reader is bounded
+ // before decoding, then the ELF and its digest are independently checked.
+ d := json.NewDecoder(io.LimitReader(resp.Body, demobuild.BinaryMaxBytes*4/3+128*1024))
+ d.DisallowUnknownFields()
+ if d.Decode(&out) != nil || d.Decode(new(any)) != io.EOF {
+ return demobuild.BuildOutput{}, demobuild.ErrBuild
+ }
+ if resp.StatusCode != http.StatusOK {
+ out.Binary = nil
+ out.SHA256 = ""
+ return out, demobuild.ErrBuild
+ }
+ v, err := demobuild.ValidateOutput(bytes.NewReader(out.Binary))
+ if err != nil || v.SHA256 != out.SHA256 {
+ return demobuild.BuildOutput{}, demobuild.ErrBuild
+ }
+ return out, nil
+}
+
+func (c *Client) DemoBuildReadiness(ctx context.Context) (demobuild.WorkerReady, error) {
+ ctx, cancel := context.WithTimeout(ctx, DeadlineReady)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, "GET", "http://control/demo-build/ready", nil)
+ if err != nil {
+ return demobuild.WorkerReady{}, err
+ }
+ resp, err := c.httpClient().Do(req)
+ if err != nil {
+ return demobuild.WorkerReady{}, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return demobuild.WorkerReady{}, demobuild.ErrBuild
+ }
+ if c.Build != "" && resp.Header.Get(BuildHeader) != c.Build {
+ return demobuild.WorkerReady{}, &StaleBuildError{Running: resp.Header.Get(BuildHeader), Want: c.Build}
+ }
+ b, err := io.ReadAll(io.LimitReader(resp.Body, 8193))
+ var out demobuild.WorkerReady
+ if err != nil || len(b) > 8192 || demobuild.DecodeMessage(b, &out) != nil || !out.Valid() {
+ return demobuild.WorkerReady{}, demobuild.ErrBuild
+ }
+ return out, nil
+}
+
+func (s *Server) handleDemoBuildReady(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set(BuildHeader, s.Build)
+ ready, err := s.DemoBuilder.Readiness(r.Context())
+ if err != nil {
+ http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(ready)
+}
+
+func (s *Server) handleDemoBuild(w http.ResponseWriter, r *http.Request) {
+ // Reading a stalled body must share the hard wall-clock bound. Context
+ // cancellation alone does not interrupt a net/http request-body read.
+ deadline := time.Now().Add(demobuild.BuildWindow)
+ ctl := http.NewResponseController(w)
+ _ = ctl.SetReadDeadline(deadline)
+ ctx, cancel := context.WithDeadline(r.Context(), deadline)
+ defer cancel()
+ r.Body = http.MaxBytesReader(w, r.Body, 4+demobuild.MaxJobWire+demo.SourceMaxBytes+1)
+ var header [4]byte
+ if _, err := io.ReadFull(r.Body, header[:]); err != nil {
+ http.Error(w, demobuild.ErrJob.Error(), 400)
+ return
+ }
+ n := binary.BigEndian.Uint32(header[:])
+ if n == 0 || n > demobuild.MaxJobWire {
+ http.Error(w, demobuild.ErrJob.Error(), 400)
+ return
+ }
+ wire := make([]byte, n)
+ if _, err := io.ReadFull(r.Body, wire); err != nil {
+ http.Error(w, demobuild.ErrJob.Error(), 400)
+ return
+ }
+ grantDeadline, err := s.DemoBuilder.GrantDeadline(wire)
+ if err != nil {
+ http.Error(w, demobuild.ErrJob.Error(), 400)
+ return
+ }
+ if grantDeadline.Before(deadline) {
+ _ = ctl.SetReadDeadline(grantDeadline)
+ }
+ out, err := s.DemoBuilder.Build(ctx, wire, r.Body)
+ w.Header().Set("Content-Type", "application/json")
+ if err != nil {
+ out.Binary = nil
+ out.SHA256 = ""
+ w.WriteHeader(http.StatusUnprocessableEntity)
+ }
+ json.NewEncoder(w).Encode(out)
+}
diff --git a/internal/instancectl/demo_build_test.go b/internal/instancectl/demo_build_test.go
new file mode 100644
index 000000000..0ef87164c
--- /dev/null
+++ b/internal/instancectl/demo_build_test.go
@@ -0,0 +1,31 @@
+package instancectl
+
+import (
+ "context"
+ "io"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+var _ interface {
+ BuildDemo(context.Context, []byte, io.Reader) (demobuild.BuildOutput, error)
+ DemoBuildReadiness(context.Context) (demobuild.WorkerReady, error)
+} = (*Client)(nil)
+
+func TestDemoBuildOff(t *testing.T) {
+ s := new(Server)
+ for _, p := range []string{"/demo-build", "/demo-build/ready"} {
+ r := httptest.NewRequest("POST", p, strings.NewReader("{}"))
+ if strings.HasSuffix(p, "ready") {
+ r.Method = "GET"
+ }
+ w := httptest.NewRecorder()
+ s.Handler().ServeHTTP(w, r)
+ if w.Code != 404 {
+ t.Fatalf("off route: %s: %d", p, w.Code)
+ }
+ }
+}
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index 42af863c1..283fca5cd 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -26,6 +26,7 @@ import (
"github.com/carlosframework/platform/internal/cliflag"
"github.com/carlosframework/platform/internal/controlsock"
"github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -41,7 +42,8 @@ import (
// source; nothing from a request reaches systemctl as a string.
type Server struct {
// DemoBox is fixed from root-owned environment at service startup.
- DemoBox bool
+ DemoBox bool
+ DemoBuilder *demobuild.Worker
ClaimStop http.Handler
// ClaimHeldRelease is the moves held-release route's handler (moves
@@ -319,6 +321,19 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s.InspectMountpoints(ctx)
+ if os.Getenv("CARLOS_DEMO_BUILD_WORKER") != "" {
+ s.RunProbe(ctx)
+ }
+ s.DemoBuilder, err = demobuild.NewWorker(os.Getenv, func(context.Context) error {
+ if _, ready := s.Ready(); !ready {
+ return demobuild.ErrBuild
+ }
+ return nil
+ })
+ if err != nil {
+ log.Fatalf("instance-control: demo builder: %v", err)
+ }
+ defer s.DemoBuilder.Close()
go s.probeLoop(ctx)
go s.diskLoop(ctx)
go s.Egress.Loop(ctx, s.DiskEvery)
@@ -410,6 +425,10 @@ func (s *Server) peerOK(c net.Conn) error { return s.PeerOK(c) }
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
+ if s.DemoBox && s.DemoBuilder != nil {
+ mux.HandleFunc("POST /demo-build", s.handleDemoBuild)
+ mux.HandleFunc("GET /demo-build/ready", s.handleDemoBuildReady)
+ }
if s.ClaimStop != nil {
mux.Handle("POST /claim/stop", s.ClaimStop)
mux.Handle("POST /claim/retire", s.ClaimStop)