carlos / platform Public

fix: demo isolation review round 1

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 2b664c0ea0ce60122d13b1a7bdd9bee1150dc3e9 parent aa26510
14 files changed, +639 −111
  • internal/demo/descriptor.go +9 −5
  • internal/demo/descriptor_test.go +14 −8
  • internal/host/agent.go +2 −2
  • internal/host/claimunit.go +14 −2
  • internal/host/demo_policy.go +39 −3
  • internal/host/demo_policy_linux_test.go +365 −61
  • internal/host/demo_policy_test.go +110 −5
  • internal/host/demo_units/demo.conf +2 −0
  • internal/hostenv/demo_test.go +11 −0
  • internal/hostenv/hostenv.go +4 −0
  • internal/instancectl/demo_policy.go +26 −12
  • internal/instancectl/demo_policy_test.go +43 −5
  • internal/instancectl/gen.go +0 −4
  • internal/instancectl/server.go +0 −4

CI cancelled — superseded by a newer push — run details

Intent

Human

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

Human

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

Human

<task-notification> <task-id>a1ff621a78a686da2</task-id> <tool-use-id>toolu_01JTtGnxJCXmsz8WQTJbvwLx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/a1ff621a78a686da2.output</output-file> <status>completed</status> <summary>Agent "Review Task 4 (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: READY AFTER FIXES - **P2-1** (wakeidentity.go:238): the record read under the lease is checked against the demo shape only when the row itself is a demo. If a row has lost its Demo* fields but its record still carries `rec.Demo`, the wake proceeds as an ordinary app, with replica restore and Litestream upload. `leaseRouteChanged` also ignores the Demo* fields. Fix: refuse when `rec.Demo != nil || rt.IsDemo()` and the record doesn't match; add the Demo* fields to `leaseRouteChanged`. - **P2-2** (demo_durability.go:154-178): the remote marker is written before the local placement. So an ambiguous PUT, a failed read-back GET, or a crash between `establishAssignment` and `placeEmptyDB` permanently refuses a demo that never served. Fix: write a durable local "init-pending" file before the PUT, and allow a retry only while it is present. Losing the whole disk still refuses. Full review: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-1/.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-4-review-r1.md</result> <usage><subagent_tokens>139102</subagent_tokens><tool_uses>38</tool_uses><duration_ms>460170</duration_ms></usage> </task-notification>

Attributed to this commit: 8.45 g CO₂e (1,018,352 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/demo/descriptor.go b/internal/demo/descriptor.go
index cbc69cd43..664f7b6fc 100644
--- a/internal/demo/descriptor.go
+++ b/internal/demo/descriptor.go
@@ -39,13 +39,17 @@ func (c Config) ValidateBinding(d Descriptor, account, app, host, lifetime, flee
return nil
}
-// BoxConfig reads only the root-owned box identity settings. Any partial or
-// malformed configuration refuses startup, even with admission switched off.
+// BoxConfig requires the explicit root-owned box switch. Console admission
+// settings alone never change a box. Once enabled, the whole tuple is required.
func BoxConfig(getenv func(string) string) (Config, error) {
- c := Config{Account: getenv("CARLOS_DEMO_ACCOUNT"), Fleet: getenv("CARLOS_DEMO_FLEET"), Domain: getenv("CARLOS_DEMO_DOMAIN")}
- if c.Account == "" && c.Fleet == "" && c.Domain == "" {
- return c, nil
+ switch getenv("CARLOS_DEMO_BOX") {
+ case "":
+ return Config{}, nil
+ case "1":
+ default:
+ return Config{}, ErrConfig
}
+ c := Config{Account: getenv("CARLOS_DEMO_ACCOUNT"), Fleet: getenv("CARLOS_DEMO_FLEET"), Domain: getenv("CARLOS_DEMO_DOMAIN")}
if !validLabel(c.Account, 32) || !validLabel(c.Fleet, 32) || !ValidDomain(c.Domain) {
return Config{}, ErrConfig
}
diff --git a/internal/demo/descriptor_test.go b/internal/demo/descriptor_test.go
index 6c22c0985..a89989e7e 100644
--- a/internal/demo/descriptor_test.go
+++ b/internal/demo/descriptor_test.go
@@ -18,14 +18,20 @@ func TestDemoPolicyFailClosed(t *testing.T) {
t.Fatalf("accepted %v", args)
}
}
- for _, env := range []map[string]string{{}, {"CARLOS_DEMO_FLEET": "demo"}, {"CARLOS_DEMO_ACCOUNT": "shop", "CARLOS_DEMO_FLEET": "demo", "CARLOS_DEMO_DOMAIN": "example.com"}} {
- c, err := BoxConfig(func(k string) string { return env[k] })
- if len(env) == 1 {
- if err == nil {
- t.Fatal("partial box config accepted")
- }
- } else if err != nil || c.BoxMode() != (len(env) > 0) {
- t.Fatalf("box config %+v: %v", c, err)
+ for _, tc := range []struct {
+ env map[string]string
+ mode, bad bool
+ }{
+ {env: map[string]string{}},
+ {env: map[string]string{"CARLOS_DEMO_FLEET": "demo"}},
+ {env: map[string]string{"CARLOS_DEMO_ACCOUNT": "shop", "CARLOS_DEMO_FLEET": "demo", "CARLOS_DEMO_DOMAIN": "example.com"}},
+ {env: map[string]string{"CARLOS_DEMO_BOX": "1"}, bad: true},
+ {env: map[string]string{"CARLOS_DEMO_BOX": "0"}, bad: true},
+ {env: map[string]string{"CARLOS_DEMO_BOX": "1", "CARLOS_DEMO_ACCOUNT": "shop", "CARLOS_DEMO_FLEET": "demo", "CARLOS_DEMO_DOMAIN": "example.com"}, mode: true},
+ } {
+ c, err := BoxConfig(func(k string) string { return tc.env[k] })
+ if (err != nil) != tc.bad || c.BoxMode() != tc.mode {
+ t.Fatalf("env %v: config %+v err %v", tc.env, c, err)
}
}
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 39b6b797b..4b4557da0 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -466,7 +466,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// same registry copy (instance update settings spec §5.1).
UpdatesReader: updatesReader(reg, release.OptDir()),
// Asked inside Acquire, before the lease (amadan #213).
- ConfigGate: configGate(),
+ ConfigGate: demoRouteGate(os.Getenv, configGate()),
}
if claims.Writes.Enabled {
eb.Timers = schedule.ClaimTimers{TimerStore: reg, Writes: claims.Writes, Context: agentCtx}
@@ -618,7 +618,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
svc.SetIdleFor(planIdleFor)
svc.SetMaxRunFor(planMaxRunFor) // plans 4c: the continuous-awake ceiling
// Plans 4d: what a lapse turned off is never woken, and stops.
- svc.SetDisabledFor(planDisabledRoute)
+ svc.SetDisabledFor(demoDisabledFor(os.Getenv, planDisabledRoute))
// Settings spec §4.2: before any process runs a build against an
// instance's database, the build state names it, under the lease. A
// store that failed to start refuses every spawn (never "run
diff --git a/internal/host/claimunit.go b/internal/host/claimunit.go
index 296177d09..93b4b0b3b 100644
--- a/internal/host/claimunit.go
+++ b/internal/host/claimunit.go
@@ -29,10 +29,10 @@ 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_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": ""}
raw, err := readClaimUnitFile(path)
defer func() {
- if readErr != nil && bytes.Contains(raw, []byte("CARLOS_DEMO_")) {
+ if readErr != nil && demoBoxSettingPresent(raw) {
readErr = fmt.Errorf("%w: %v", demo.ErrConfig, readErr)
}
}()
@@ -158,3 +158,15 @@ func restartClaimControl(path string, before, after []byte, systemctl func(...st
}
return nil
}
+
+// A parse failure must not silently disable an explicitly configured box.
+// Scan assignments separately so a later switch still counts after an error.
+func demoBoxSettingPresent(raw []byte) bool {
+ for _, line := range strings.Split(string(raw), "\n") {
+ key, value, ok := strings.Cut(strings.TrimSpace(line), "=")
+ if ok && strings.TrimSpace(key) == "CARLOS_DEMO_BOX" && strings.Trim(strings.TrimSpace(value), "\"'") != "" {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/host/demo_policy.go b/internal/host/demo_policy.go
index 77153b221..34c0f8202 100644
--- a/internal/host/demo_policy.go
+++ b/internal/host/demo_policy.go
@@ -26,15 +26,20 @@ func installDemoUnits(root string, cfg demo.Config) error {
}
func installDemoUnitsIn(unitDir string, cfg demo.Config) (bool, error) {
- if !cfg.BoxMode() {
- return false, nil
- }
small, _ := cgroup.SizeByName("small")
content := []byte(demoNetworkDropIn + fmt.Sprintf("MemoryMax=%d\nMemoryHigh=%d\nMemorySwapMax=%d\nCPUWeight=%d\nCPUQuota=%d%%\nIOWeight=%d\n", small.Limit.MemoryMax, cgroup.HighOf(small.Limit.MemoryMax), small.Limit.MemoryMax, small.Shares.CPUWeight, small.Shares.CPUQuotaPercent, small.Shares.IOWeight))
changed := false
for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
dir := filepath.Join(unitDir, unit+".d")
path := filepath.Join(dir, "90-carlos-demo.conf")
+ if !cfg.BoxMode() {
+ if err := os.Remove(path); err == nil {
+ changed = true
+ } else if !os.IsNotExist(err) {
+ return changed, err
+ }
+ continue
+ }
before, err := os.ReadFile(path)
if err == nil && bytes.Equal(before, content) {
continue
@@ -57,6 +62,9 @@ func installDemoUnitsIn(unitDir string, cfg demo.Config) (bool, error) {
// starts a watcher; an unverified or not-yet-cached demo waits for reconcile.
func demoPolicyHook(getenv func(string) string, reg *registry.Registry, next func(context.Context, string, string) error) func(context.Context, string, string) error {
cfg, configErr := demo.BoxConfig(getenv)
+ if configErr == nil && !cfg.BoxMode() {
+ return next
+ }
claims := hostwrite.Enabled(getenv)
return func(ctx context.Context, host, build string) error {
if configErr != nil {
@@ -78,3 +86,31 @@ func demoPolicyHook(getenv func(string) string, reg *registry.Registry, next fun
return nil
}
}
+
+// demoDisabledFor checks the route already held by the activator. Ordinary
+// spawns need no registry read; marked routes on an ordinary box are refused.
+func demoDisabledFor(getenv func(string) string, next func(registry.Route) bool) func(registry.Route) bool {
+ cfg, err := demo.BoxConfig(getenv)
+ return func(rt registry.Route) bool {
+ return err != nil || (!cfg.BoxMode() && rt.IsDemo()) || (next != nil && next(rt))
+ }
+}
+
+// demoRouteGate also covers probes and direct backend preparation, which can
+// bypass the disabled-route wake gate. It uses the caller's existing route.
+func demoRouteGate(getenv func(string) string, next func(context.Context, registry.Route) error) func(context.Context, registry.Route) error {
+ cfg, err := demo.BoxConfig(getenv)
+ claims := hostwrite.Enabled(getenv)
+ return func(ctx context.Context, rt registry.Route) error {
+ if err != nil {
+ return err
+ }
+ if err := armedPolicyCache.Load().AssertDemoRoute(cfg, rt, claims, time.Now()); err != nil {
+ return err
+ }
+ if next != nil {
+ return next(ctx, rt)
+ }
+ return nil
+ }
+}
diff --git a/internal/host/demo_policy_linux_test.go b/internal/host/demo_policy_linux_test.go
index 9a54da7e3..605d2504c 100644
--- a/internal/host/demo_policy_linux_test.go
+++ b/internal/host/demo_policy_linux_test.go
@@ -4,21 +4,42 @@ package host
import (
"context"
+ "encoding/binary"
+ "encoding/json"
"errors"
"fmt"
+ "io"
"net"
"net/http"
+ "net/http/httptest"
"os"
"os/exec"
+ "os/user"
"path/filepath"
+ "strconv"
"strings"
+ "sync"
"syscall"
"testing"
"time"
"github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
)
+// These include aliases on distributions where /var/run is a symlink, and
+// nscd's alternate location. /var is hidden even when /var/run is a directory.
+var demoResolverSockets = []string{
+ "/run/systemd/resolve/io.systemd.Resolve",
+ "/var/run/systemd/resolve/io.systemd.Resolve",
+ "/run/dbus/system_bus_socket",
+ "/var/run/dbus/system_bus_socket",
+ "/run/nscd/socket",
+ "/var/run/nscd/socket",
+ "/var/lib/nscd/socket",
+}
+
func TestDemoDenyAllKernel(t *testing.T) {
if os.Getenv("CARLOS_DEMO_KERNEL_WITNESS") != "1" {
t.Skip("kernel witness outstanding: needs a designated systemd sandbox (not evidence)")
@@ -26,89 +47,330 @@ func TestDemoDenyAllKernel(t *testing.T) {
if os.Geteuid() != 0 {
t.Fatal("designated systemd sandbox must run witness as root")
}
- ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)
defer cancel()
+ ctl := func(ctx context.Context, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+ }
run := func(args ...string) string {
t.Helper()
- out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ out, err := ctl(ctx, args...)
if err != nil {
t.Fatalf("systemctl %v: %s: %v", args, out, err)
}
- return string(out)
+ return out
}
- root := t.TempDir()
- if err := installDemoUnits(root, demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}); err != nil {
- t.Fatal(err)
+ // The opt-in is for a disposable, idle, installed sandbox. Never replace
+ // another build's templates or share a box with active tenant units.
+ if out := run("list-units", "--state=active,activating", "--no-legend", "carlos-instance@*.service", "carlos-instance-gen@*.service"); strings.TrimSpace(out) != "" {
+ t.Fatalf("sandbox has active instances: %s", out)
+ }
+ for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
+ want, err := unitsFS.ReadFile("units/" + unit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := os.ReadFile(filepath.Join("/etc/systemd/system", unit))
+ if err != nil || string(got) != string(want) {
+ t.Fatalf("sandbox must have this build's template %s installed: %v", unit, err)
+ }
}
- drop, err := os.ReadFile(filepath.Join(root, "etc/systemd/system/carlos-instance@.service.d/90-carlos-demo.conf"))
+ u, err := user.Lookup("carlos")
if err != nil {
t.Fatal(err)
}
- exe, err := os.Executable()
+ uid, err := strconv.Atoi(u.Uid)
if err != nil {
t.Fatal(err)
}
- sock := filepath.Join(root, "app.sock")
- ln, err := net.Listen("unix", sock)
+ gid, err := strconv.Atoi(u.Gid)
if err != nil {
t.Fatal(err)
}
- server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })}
- done := make(chan struct{})
- go func() { defer close(done); _ = server.Serve(ln) }()
- defer func() { _ = server.Close(); <-done }()
- name := fmt.Sprintf("carlos-demo-witness-%d", os.Getpid())
- slice, unit := name+".slice", name+".service"
- files := []string{filepath.Join("/run/systemd/system", slice), filepath.Join("/run/systemd/system", unit)}
- // O_EXCL protects a pre-existing unit. Cleanup removes only files we created.
- var created []string
+ host := fmt.Sprintf("demo-witness-%d-%d.example.com", os.Getpid(), time.Now().UnixNano())
+ iid := provision.InstanceID(host)
+ data, runtimeDir := "/data/instances/"+iid, "/run/carlos/instances/"+iid
+ live := "/opt/carlos/live/" + host
+ units := []string{instancectl.UnitName(instancectl.RoleRun, host), instancectl.GenUnitName(host, 7)}
+ // All host-specific resources must be fresh before cleanup may own them.
+ for _, path := range []string{data, runtimeDir, live, "/run/systemd/system.control/" + instancectl.SliceName(host) + ".d"} {
+ if _, err := os.Lstat(path); !os.IsNotExist(err) {
+ t.Fatalf("witness path already exists: %s (%v)", path, err)
+ }
+ }
+ var files, dirs []string
+ var listeners []net.Listener
+ var listenerWG sync.WaitGroup
+ var submitted []string
+ // Registered before any mutation. Stop units before removing their files.
defer func() {
- cleanup, cancel := context.WithTimeout(context.Background(), 20*time.Second)
- defer cancel()
- for i := len(created) - 1; i >= 0; i-- {
- u := filepath.Base(created[i])
- _, _ = exec.CommandContext(cleanup, "systemctl", "stop", u).CombinedOutput()
- _, _ = exec.CommandContext(cleanup, "systemctl", "reset-failed", u).CombinedOutput()
+ cleanup, done := context.WithTimeout(context.Background(), 60*time.Second)
+ defer done()
+ for _, ln := range listeners {
+ _ = ln.Close()
+ }
+ listenerWG.Wait()
+ stopped := true
+ for _, unit := range submitted {
+ if out, err := ctl(cleanup, "stop", unit); err != nil {
+ t.Errorf("cleanup stop %s: %s: %v; retaining files", unit, out, err)
+ stopped = false
+ }
+ _, _ = ctl(cleanup, "reset-failed", unit)
+ }
+ if !stopped {
+ return
}
- for _, p := range created {
- _ = os.Remove(p)
+ _, _ = ctl(cleanup, "stop", instancectl.SliceName(host))
+ for i := len(files) - 1; i >= 0; i-- {
+ if err := os.Remove(files[i]); err != nil && !os.IsNotExist(err) {
+ t.Errorf("cleanup %s: %v", files[i], err)
+ }
}
- _, _ = exec.CommandContext(cleanup, "systemctl", "daemon-reload").CombinedOutput()
+ for i := len(dirs) - 1; i >= 0; i-- {
+ if err := os.RemoveAll(dirs[i]); err != nil {
+ t.Errorf("cleanup %s: %v", dirs[i], err)
+ }
+ }
+ // Only this fresh host's runtime properties were written by setTier.
+ _ = os.RemoveAll("/run/systemd/system.control/" + instancectl.SliceName(host) + ".d")
+ _, _ = ctl(cleanup, "daemon-reload")
}()
- contents := []string{"[Slice]\nIPAddressAllow=192.0.2.53 192.0.2.10\n", fmt.Sprintf("[Unit]\nRequires=%s\nAfter=%s\n[Service]\nType=oneshot\nRemainAfterExit=yes\nSlice=%s\nExecStart=%q -test.run=^TestDemoDenyAllKernelHelper$\nEnvironment=CARLOS_DEMO_KERNEL_HELPER=%s\n", slice, slice, slice, exe, sock) + string(drop)}
- for i, p := range files {
- f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
+ mkdir := func(path string) {
+ t.Helper()
+ if err := os.Mkdir(path, 0755); err != nil {
+ t.Fatal(err)
+ }
+ dirs = append(dirs, path)
+ }
+ create := func(path string, data []byte, mode os.FileMode) {
+ t.Helper()
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
t.Fatal(err)
}
- created = append(created, p)
- _, err = f.WriteString(contents[i])
+ files = append(files, path)
+ _, err = f.Write(data)
closeErr := f.Close()
if err != nil || closeErr != nil {
- t.Fatalf("write unit: %v %v", err, closeErr)
+ t.Fatalf("write %s: %v %v", path, err, closeErr)
}
}
- run("daemon-reload")
- show := run("show", unit, "-p", "PrivateNetwork,RestrictAddressFamilies,IPAddressDeny,IPAddressAllow,MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight")
- for _, line := range []string{"PrivateNetwork=yes", "RestrictAddressFamilies=AF_UNIX", "IPAddressAllow=", "MemoryMax=268435456", "CPUWeight=50", "CPUQuotaPerSecUSec=500ms", "IOWeight=50"} {
- if !strings.Contains("\n"+show, "\n"+line+"\n") {
- t.Fatalf("effective property missing %q: %s", line, show)
+ for _, path := range []string{data, runtimeDir} {
+ mkdir(path)
+ if err := os.Chown(path, uid, gid); err != nil {
+ t.Fatal(err)
}
}
- if !strings.Contains(show, "IPAddressDeny=0.0.0.0/0 ::/0") && !strings.Contains(show, "IPAddressDeny=::/0 0.0.0.0/0") {
- t.Fatalf("deny readback: %s", show)
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ binary, err := os.ReadFile(exe)
+ if err != nil {
+ t.Fatal(err)
}
- run("start", unit)
- if got := strings.TrimSpace(run("show", unit, "-p", "Result", "--value")); got != "success" {
- t.Fatalf("witness result %s", got)
+ create(live, binary, 0755)
+ // Exercise real reachable pathname sockets, including a generic service
+ // outside /run. If a resolver isn't installed, a sentinel occupies its
+ // exact path; a missing host daemon must not make the witness pass.
+ paths := append(append([]string{}, demoResolverSockets...), "/run/"+iid+".sock", "/var/"+iid+".sock")
+ for _, path := range paths {
+ if _, err := os.Stat(path); err == nil {
+ continue
+ } else if !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ var missing []string
+ for dir := filepath.Dir(path); ; dir = filepath.Dir(dir) {
+ if _, err := os.Stat(dir); err == nil {
+ break
+ } else if !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ missing = append(missing, dir)
+ }
+ for i := len(missing) - 1; i >= 0; i-- {
+ mkdir(missing[i])
+ }
+ ln, err := net.Listen("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ listeners = append(listeners, ln)
+ if err := os.Chmod(path, 0666); err != nil {
+ t.Fatal(err)
+ }
+ listenerWG.Add(1)
+ go func() {
+ defer listenerWG.Done()
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ _ = c.Close()
+ }
+ }()
+ }
+ pathsJSON, _ := json.Marshal(paths)
+ // Prove each socket is reachable as carlos outside the sandbox first.
+ preflight := exec.CommandContext(ctx, live, "-test.run=^TestDemoDenyAllKernelHelper$")
+ preflight.Env = []string{"CARLOS_DEMO_KERNEL_HELPER=control", "CARLOS_DEMO_KERNEL_PATHS=" + string(pathsJSON)}
+ preflight.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}}
+ if out, err := preflight.CombinedOutput(); err != nil {
+ t.Fatalf("socket control: %s: %v", out, err)
+ }
+ cfg := demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}
+ for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
+ dir := filepath.Join("/etc/systemd/system", unit+".d")
+ if _, err := os.Stat(dir); os.IsNotExist(err) {
+ mkdir(dir)
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "90-carlos-demo.conf")
+ // Do not overwrite a pre-existing template override, even in the sandbox.
+ if _, err := os.Lstat(path); !os.IsNotExist(err) {
+ t.Fatalf("sandbox needs no existing demo drop-in: %s (%v)", path, err)
+ }
+ files = append(files, path)
+ }
+ if err := installDemoUnits("/", cfg); err != nil {
+ t.Fatal(err)
+ }
+ // A per-host parent allow deliberately challenges the unit's private netns.
+ sliceDir := "/run/systemd/system/" + instancectl.SliceName(host) + ".d"
+ mkdir(sliceDir)
+ create(filepath.Join(sliceDir, "50-witness.conf"), []byte("[Slice]\nIPAddressAllow=192.0.2.53 192.0.2.10\n"), 0644)
+ for i, unit := range units {
+ t.Run(unit, func(t *testing.T) {
+ key := iid
+ launchName := instancectl.LaunchFileName(instancectl.RoleRun)
+ logPath := "/run/carlos/logs/" + iid + ".run.sock"
+ query := "/start?host=" + host + "&role=run&memory_max=2147483648"
+ if i == 1 {
+ key = instancectl.GenKey(host, 7)
+ launchName = instancectl.GenLaunchFileName(7)
+ logPath = instancectl.GenLogSocket(host, 7)
+ query += "&gen=7"
+ }
+ // Root owns executable mounts and writes the generation drop-in itself.
+ for _, dir := range []string{"/run/carlos-control/exe/" + key, "/run/systemd/system/" + unit + ".d"} {
+ mkdir(dir)
+ }
+ create(logPath, nil, 0644)
+ sock := runtimeDir + "/witness.sock"
+ launch := instancectl.Launch{Schema: instancectl.LaunchSchema, Host: host, Argv: []string{live, "-test.run=^TestDemoDenyAllKernelHelper$"}, Env: []string{"CARLOS_DEMO_KERNEL_HELPER=" + sock, "CARLOS_DEMO_KERNEL_PATHS=" + string(pathsJSON), "CARLOS_DEMO_KERNEL_UID=" + u.Uid}}
+ raw, _ := json.Marshal(launch)
+ create(filepath.Join(data, launchName), raw, 0644)
+ badDir := "/etc/systemd/system/" + unit + ".d"
+ mkdir(badDir)
+ bad := filepath.Join(badDir, "99-witness.conf")
+ create(bad, []byte("[Service]\nPrivateNetwork=no\n"), 0644)
+ run("daemon-reload")
+ starts, readbacks := 0, 0
+ s := &instancectl.Server{DemoBox: true, CgroupRoot: "/sys/fs/cgroup", DropInDir: "/run/systemd/system", ExeRoot: "/run/carlos-control/exe", Systemctl: func(c context.Context, args ...string) (string, error) {
+ if args[0] == "start" {
+ submitted = append(submitted, unit)
+ starts++
+ }
+ if strings.Contains(strings.Join(args, " "), "TemporaryFileSystem") {
+ readbacks++
+ }
+ return ctl(c, args...)
+ }}
+ request := func() *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ s.Handler().ServeHTTP(w, httptest.NewRequest("POST", query, nil).WithContext(ctx))
+ return w
+ }
+ w := request()
+ if w.Code < 400 || !strings.Contains(w.Body.String(), "DEMO-POLICY") || starts != 0 || readbacks == 0 {
+ t.Fatalf("bad drop-in not refused by root readback: %d %s starts=%d checks=%d", w.Code, w.Body, starts, readbacks)
+ }
+ if err := os.Remove(bad); err != nil {
+ t.Fatal(err)
+ }
+ run("daemon-reload")
+ w = request()
+ // A 200 from this handler requires both demoCgroup reads to pass.
+ if w.Code != 200 || starts != 1 || readbacks < 2 {
+ t.Fatalf("real root start/readback: %d %s; log: %s", w.Code, w.Body, readDemoWitnessLog(logPath))
+ }
+ transport := &http.Transport{DialContext: func(c context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(c, "unix", sock)
+ }}
+ defer transport.CloseIdleConnections()
+ client := &http.Client{Transport: transport, Timeout: time.Second}
+ for {
+ resp, err := client.Get("http://app/")
+ if err == nil {
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != 200 || string(body) != "ok" {
+ t.Fatalf("app response %s", body)
+ }
+ break
+ }
+ select {
+ case <-ctx.Done():
+ t.Fatalf("fixture did not prove isolation: %v; log: %s", err, readDemoWitnessLog(logPath))
+ case <-time.After(50 * time.Millisecond):
+ }
+ }
+ run("stop", unit)
+ _ = os.Remove(sock)
+ })
}
}
+func readDemoWitnessLog(path string) string { b, _ := os.ReadFile(path); return string(b) }
+
func TestDemoDenyAllKernelHelper(t *testing.T) {
sock := os.Getenv("CARLOS_DEMO_KERNEL_HELPER")
if sock == "" {
t.Skip("kernel helper only")
}
+ if os.Geteuid() == 0 {
+ t.Fatal("fixture must run as carlos")
+ }
+ var paths []string
+ if err := json.Unmarshal([]byte(os.Getenv("CARLOS_DEMO_KERNEL_PATHS")), &paths); err != nil {
+ t.Fatal(err)
+ }
+ for _, path := range paths {
+ conn, err := net.DialTimeout("unix", path, time.Second)
+ if sock == "control" {
+ if err != nil {
+ t.Fatalf("outside control %s: %v", path, err)
+ }
+ conn.Close()
+ continue
+ }
+ if conn != nil {
+ // A resolver request must not even reach the transport. This varlink
+ // request names a reserved test domain, never an external tenant.
+ if strings.Contains(path, "io.systemd.Resolve") {
+ _, _ = conn.Write([]byte("{\"method\":\"io.systemd.Resolve.ResolveHostname\",\"parameters\":{\"name\":\"demo-witness.example.com\",\"family\":2}}\x00"))
+ }
+ conn.Close()
+ t.Fatalf("host service socket reachable: %s", path)
+ }
+ if !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
+ t.Fatalf("%s: not a mount refusal: %v", path, err)
+ }
+ }
+ if sock == "control" {
+ return
+ }
+ for _, path := range demoResolverSockets {
+ demoResolutionRefused(t, path)
+ }
+ if strconv.Itoa(os.Geteuid()) != os.Getenv("CARLOS_DEMO_KERNEL_UID") {
+ t.Fatal("wrong fixture uid")
+ }
for _, addr := range []string{"203.0.113.1:80", "[2001:db8::1]:80", "127.0.0.1:80", "169.254.169.254:80", "192.0.2.53:53", "192.0.2.10:80"} {
conn, err := net.DialTimeout("tcp", addr, time.Second)
if conn != nil {
@@ -119,28 +381,70 @@ func TestDemoDenyAllKernelHelper(t *testing.T) {
t.Fatalf("%s: refusal does not prove filtering: %v", addr, err)
}
}
- transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
- return (&net.Dialer{}).DialContext(ctx, "unix", sock)
- }}
- defer transport.CloseIdleConnections()
- client := &http.Client{Transport: transport, Timeout: time.Second}
- resp, err := client.Get("http://app/")
+ if os.Getenv("CARLOS_DEMO_KERNEL_CHILD") == "1" {
+ return
+ }
+ exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
- resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- t.Fatal(resp.Status)
+ cmd := exec.Command(exe, "-test.run=^TestDemoDenyAllKernelHelper$")
+ cmd.Env = append(os.Environ(), "CARLOS_DEMO_KERNEL_CHILD=1")
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("child: %s: %v", out, err)
}
- if os.Getenv("CARLOS_DEMO_KERNEL_CHILD") == "" {
- exe, err := os.Executable()
- if err != nil {
- t.Fatal(err)
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ // Readiness is published only after every parent and child check passes.
+ server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })}
+ defer server.Close()
+ if err := server.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ t.Fatal(err)
+ }
+}
+
+// Attempt the resolver protocols as well as checking connect's precise errno.
+// The transport check above is essential: an unavailable method is not proof
+// that the socket itself is isolated.
+func demoResolutionRefused(t *testing.T, path string) {
+ t.Helper()
+ const name = "demo-witness.example.com"
+ if strings.Contains(path, "system_bus_socket") {
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "/usr/bin/busctl", "--address=unix:path="+path, "--timeout=1", "call", "org.freedesktop.resolve1", "/org/freedesktop/resolve1", "org.freedesktop.resolve1.Manager", "ResolveHostname", "isit", "0", name, "2", "0")
+ cmd.Env = append(os.Environ(), "LC_ALL=C")
+ out, err := cmd.CombinedOutput()
+ if err == nil {
+ t.Fatalf("D-Bus resolved %s through %s: %s", name, path, out)
+ }
+ if !strings.Contains(string(out), "No such file or directory") && !strings.Contains(string(out), "Permission denied") {
+ t.Fatalf("D-Bus failure was not socket isolation: %s: %v", out, err)
}
- cmd := exec.Command(exe, "-test.run=^TestDemoDenyAllKernelHelper$")
- cmd.Env = append(os.Environ(), "CARLOS_DEMO_KERNEL_CHILD=1")
- if out, err := cmd.CombinedOutput(); err != nil {
- t.Fatalf("child network witness: %s: %v", out, err)
+ return
+ }
+ // varlink ResolveHostname and nscd GETAI use a stream pathname socket.
+ request := []byte("{\"method\":\"io.systemd.Resolve.ResolveHostname\",\"parameters\":{\"name\":\"" + name + "\",\"family\":2}}\x00")
+ if strings.Contains(path, "nscd/socket") {
+ key := []byte(name + "\x00")
+ request = make([]byte, 12+len(key))
+ binary.NativeEndian.PutUint32(request[0:4], 2) // NSCD_VERSION
+ binary.NativeEndian.PutUint32(request[4:8], 14) // GETAI
+ binary.NativeEndian.PutUint32(request[8:12], uint32(len(key)))
+ copy(request[12:], key)
+ }
+ conn, err := net.DialTimeout("unix", path, time.Second)
+ if err != nil {
+ if !errors.Is(err, syscall.ENOENT) && !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) {
+ t.Fatalf("resolver transport: %v", err)
}
+ return
}
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(time.Second))
+ _, _ = conn.Write(request)
+ t.Fatalf("resolver transport allowed request through %s", path)
}
diff --git a/internal/host/demo_policy_test.go b/internal/host/demo_policy_test.go
index d9a560364..c964ef5f7 100644
--- a/internal/host/demo_policy_test.go
+++ b/internal/host/demo_policy_test.go
@@ -1,6 +1,7 @@
package host
import (
+ "context"
"errors"
"os"
"path/filepath"
@@ -8,6 +9,7 @@ import (
"testing"
"github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/registry"
)
func TestDemoPolicyRoundTrip(t *testing.T) {
@@ -21,7 +23,7 @@ func TestDemoPolicyRoundTrip(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- for _, want := range []string{"PrivateNetwork=yes", "RestrictAddressFamilies=\nRestrictAddressFamilies=AF_UNIX", "IPAddressAllow=\n", "IPAddressDeny=any", "MemoryMax=268435456", "CPUWeight=50", "CPUQuota=50%", "IOWeight=50"} {
+ for _, want := range []string{"PrivateNetwork=yes", "TemporaryFileSystem=/run:ro /var:ro", "RestrictAddressFamilies=\nRestrictAddressFamilies=AF_UNIX", "IPAddressAllow=\n", "IPAddressDeny=any", "MemoryMax=268435456", "CPUWeight=50", "CPUQuota=50%", "IOWeight=50"} {
if !strings.Contains(string(raw), want) {
t.Fatalf("missing %q in %s", want, raw)
}
@@ -40,7 +42,7 @@ func TestDemoPolicyRoundTrip(t *testing.T) {
func TestDemoPolicyBoxEnvironment(t *testing.T) {
root := t.TempDir()
env := filepath.Join(root, "host.env")
- if err := os.WriteFile(env, []byte("CARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
+ if err := os.WriteFile(env, []byte("CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
t.Fatal(err)
}
cfg, err := readClaimUnitSettings(env)
@@ -58,7 +60,7 @@ func TestDemoPolicyBoxEnvironment(t *testing.T) {
if strings.Contains(string(rendered), "StateDirectory=carlos-claims") {
t.Fatal("demo mode enabled claims machinery")
}
- if err := os.WriteFile(env, []byte("CARLOS_DEMO_FLEET=demo\n"), 0600); err != nil {
+ if err := os.WriteFile(env, []byte("CARLOS_DEMO_BOX=1\nCARLOS_DEMO_FLEET=demo\n"), 0600); err != nil {
t.Fatal(err)
}
if _, err := readClaimUnitSettings(env); err == nil {
@@ -68,7 +70,7 @@ func TestDemoPolicyBoxEnvironment(t *testing.T) {
func TestDemoPolicyMalformedEnvironment(t *testing.T) {
path := filepath.Join(t.TempDir(), "host.env")
- if err := os.WriteFile(path, []byte("CARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=\"demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
+ if err := os.WriteFile(path, []byte("CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=\"demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
t.Fatal(err)
}
if _, err := readClaimUnitSettings(path); !errors.Is(err, demo.ErrConfig) {
@@ -82,7 +84,7 @@ func TestDemoPolicyBoxInstallers(t *testing.T) {
if err := os.MkdirAll(filepath.Join(etc, "carlos"), 0755); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(filepath.Join(etc, "carlos/host.env"), []byte("CARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
+ if err := os.WriteFile(filepath.Join(etc, "carlos/host.env"), []byte("CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
t.Fatal(err)
}
}
@@ -135,4 +137,107 @@ func TestDemoPolicyBoxInstallers(t *testing.T) {
if len(calls) != 0 {
t.Fatalf("unchanged demo rewrote units: %v", calls)
}
+
+ if err := os.WriteFile(filepath.Join(etc, "carlos/host.env"), nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ ensureSystemUnits(etc, lock, ctl, probe, t.Logf)
+ if !strings.Contains(strings.Join(calls, "\n"), "daemon-reload") {
+ t.Fatalf("removed drop-ins not reloaded: %v", calls)
+ }
+ for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
+ if _, err := os.Stat(filepath.Join(etc, "systemd/system", unit+".d/90-carlos-demo.conf")); !os.IsNotExist(err) {
+ t.Fatalf("disabled box kept drop-in: %v", err)
+ }
+ }
+ raw, err := os.ReadFile(filepath.Join(etc, "systemd/system", claimControlUnit))
+ if err != nil || strings.Contains(string(raw), claimControlEnvironment) {
+ t.Fatalf("disabled box kept environment: %v", err)
+ }
+}
+
+func TestDemoPolicyOrdinarySpawn(t *testing.T) {
+ calls := 0
+ hook := demoPolicyHook(func(string) string { return "" }, nil, func(context.Context, string, string) error { calls++; return nil })
+ if err := hook(t.Context(), "shop.example.com", "v1"); err != nil || calls != 1 {
+ t.Fatalf("ordinary spawn %v calls %d", err, calls)
+ }
+}
+func TestDemoPolicyRemoveDropIns(t *testing.T) {
+ dir := t.TempDir()
+ cfg := demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}
+ if _, err := installDemoUnitsIn(dir, cfg); err != nil {
+ t.Fatal(err)
+ }
+ changed, err := installDemoUnitsIn(dir, demo.Config{})
+ if err != nil || !changed {
+ t.Fatalf("remove changed=%v err=%v", changed, err)
+ }
+ for _, unit := range []string{"carlos-instance@.service", "carlos-instance-gen@.service"} {
+ if _, err := os.Stat(filepath.Join(dir, unit+".d/90-carlos-demo.conf")); !os.IsNotExist(err) {
+ t.Fatalf("drop-in remains: %v", err)
+ }
+ }
+ if changed, err := installDemoUnitsIn(dir, demo.Config{}); changed || err != nil {
+ t.Fatalf("second removal: %v %v", changed, err)
+ }
+}
+func TestDemoPolicyUnrelatedMalformedEnvironment(t *testing.T) {
+ for _, prefix := range []string{"# CARLOS_DEMO_BOX=1\n", "CARLOS_DEMO_BUILD_WORKER=1\n", "CARLOS_DEMO_ACCOUNT=shop\n", "CARLOS_DEMO_BOX=\n"} {
+ path := filepath.Join(t.TempDir(), "host.env")
+ if err := os.WriteFile(path, []byte(prefix+"UNRELATED=\"bad\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readClaimUnitSettings(path); err == nil || errors.Is(err, demo.ErrConfig) {
+ t.Fatalf("%q: unrelated parse error reclassified: %v", prefix, err)
+ }
+ }
+}
+
+func TestDemoPolicyExistingRouteGate(t *testing.T) {
+ for _, marker := range []registry.Route{{DemoID: "id"}, {DemoHost: "shop.example.com"}, {DemoExpiresAt: 1}, {DemoLifetime: "life"}} {
+ called := false
+ gate := demoRouteGate(func(string) string { return "" }, func(context.Context, registry.Route) error { called = true; return nil })
+ if err := gate(t.Context(), marker); !errors.Is(err, demo.ErrPolicy) || called {
+ t.Fatalf("marked route admitted: %v %v", err, called)
+ }
+ if !demoDisabledFor(func(string) string { return "" }, nil)(marker) {
+ t.Fatal("marked route not disabled")
+ }
+ }
+ calls := 0
+ getenv := func(k string) string {
+ return map[string]string{"CARLOS_DEMO_ACCOUNT": "shop", "CARLOS_DEMO_FLEET": "demo", "CARLOS_DEMO_DOMAIN": "example.com"}[k]
+ }
+ gate := demoRouteGate(getenv, func(context.Context, registry.Route) error { calls++; return nil })
+ if err := gate(t.Context(), registry.Route{}); err != nil || calls != 1 {
+ t.Fatalf("ordinary route: %v %d", err, calls)
+ }
+ if demoDisabledFor(getenv, func(registry.Route) bool { return false })(registry.Route{}) {
+ t.Fatal("tuple disabled ordinary route")
+ }
+ if !demoDisabledFor(getenv, func(registry.Route) bool { return true })(registry.Route{}) {
+ t.Fatal("lost existing disabled gate")
+ }
+ if demoPolicyHook(getenv, nil, nil) != nil {
+ t.Fatal("ordinary nil hook changed")
+ }
+}
+
+func TestDemoPolicyConsoleTupleDoesNotConfigureBox(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "host.env")
+ if err := os.WriteFile(path, []byte("CARLOS_DEMO_ACCOUNT=shop\nCARLOS_DEMO_FLEET=demo\nCARLOS_DEMO_DOMAIN=example.com\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ cfg, err := readClaimUnitSettings(path)
+ if err != nil || cfg.demo.BoxMode() {
+ t.Fatalf("console tuple enabled box: %+v %v", cfg, err)
+ }
+ raw, err := unitsFS.ReadFile("units/" + claimControlUnit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(claimUnitContent(claimControlUnit, raw, cfg)) != string(raw) {
+ t.Fatal("ordinary control unit changed")
+ }
}
diff --git a/internal/host/demo_units/demo.conf b/internal/host/demo_units/demo.conf
index 33de5a0f3..9554d6677 100644
--- a/internal/host/demo_units/demo.conf
+++ b/internal/host/demo_units/demo.conf
@@ -5,3 +5,5 @@ RestrictAddressFamilies=AF_UNIX
IPAddressAllow=
IPAddressDeny=
IPAddressDeny=any
+TemporaryFileSystem=/run:ro /var:ro
+NetworkNamespacePath=
diff --git a/internal/hostenv/demo_test.go b/internal/hostenv/demo_test.go
new file mode 100644
index 000000000..7d8692c5a
--- /dev/null
+++ b/internal/hostenv/demo_test.go
@@ -0,0 +1,11 @@
+package hostenv
+
+import "testing"
+
+func TestDemoBoxKeysAllowed(t *testing.T) {
+ for _, key := range []string{"CARLOS_DEMO_BOX", "CARLOS_DEMO_ACCOUNT", "CARLOS_DEMO_FLEET", "CARLOS_DEMO_DOMAIN"} {
+ if !Allowed(key) {
+ t.Errorf("not allowed: %s", key)
+ }
+ }
+}
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go
index aeef72cd6..2c28c610e 100644
--- a/internal/hostenv/hostenv.go
+++ b/internal/hostenv/hostenv.go
@@ -75,6 +75,10 @@ var Optional = []string{
"CARLOS_ALERT_MEM_PCT",
"CARLOS_AWS_REGION",
"CARLOS_BACKHAUL_MAX_INFLIGHT",
+ "CARLOS_DEMO_ACCOUNT",
+ "CARLOS_DEMO_BOX",
+ "CARLOS_DEMO_DOMAIN",
+ "CARLOS_DEMO_FLEET",
"CARLOS_DEPLOYMENT_SINGLE_TENANT",
"CARLOS_DNS_PROVIDER",
"CARLOS_EDGE_GZIP",
diff --git a/internal/instancectl/demo_policy.go b/internal/instancectl/demo_policy.go
index 61e8952a4..313138e8a 100644
--- a/internal/instancectl/demo_policy.go
+++ b/internal/instancectl/demo_policy.go
@@ -28,24 +28,13 @@ func (s *Server) demoHandler(next http.Handler) http.Handler {
})
}
-func (s *Server) assertDemoPolicy(ctx context.Context, host string) error {
- if !s.DemoBox {
- return nil
- }
- small, _ := cgroup.SizeByName("small")
- if err := s.setTier(ctx, host, small.Limit); err != nil {
- return fmt.Errorf("%w: small tier: %v", demo.ErrPolicy, err)
- }
- return nil
-}
-
// assertDemoUnit proves the unit properties before each start, including a
// generation whose own drop-in was just reloaded. Missing properties fail.
func (s *Server) assertDemoUnit(ctx context.Context, host, unit string) error {
if !s.DemoBox {
return nil
}
- out, err := s.Systemctl(ctx, "show", unit, "-p", "PrivateNetwork,RestrictAddressFamilies,IPAddressDeny,IPAddressAllow,MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight,Slice")
+ out, err := s.Systemctl(ctx, "show", unit, "-p", "PrivateNetwork,NetworkNamespacePath,JoinsNamespaceOf,TemporaryFileSystem,RestrictAddressFamilies,IPAddressDeny,IPAddressAllow,MemoryMax,CPUWeight,CPUQuotaPerSecUSec,IOWeight,Slice")
if err != nil {
return fmt.Errorf("%w: unit readback: %v", demo.ErrPolicy, err)
}
@@ -58,6 +47,31 @@ func (s *Server) assertDemoUnit(ctx context.Context, host, unit string) error {
if _, present := m["IPAddressAllow"]; !present {
return demo.ErrPolicy
}
+ for _, key := range []string{"NetworkNamespacePath", "JoinsNamespaceOf"} {
+ if value, present := m[key]; !present || value != "" {
+ return fmt.Errorf("%w: %s readback", demo.ErrPolicy, key)
+ }
+ }
+ for _, path := range []string{"/run", "/var"} {
+ found := false
+ for _, mount := range strings.Fields(m["TemporaryFileSystem"]) {
+ target, options, _ := strings.Cut(mount, ":")
+ if target == path {
+ found = false
+ for _, option := range strings.Split(options, ",") {
+ if option == "ro" {
+ found = true
+ }
+ if option == "rw" {
+ return demo.ErrPolicy
+ }
+ }
+ }
+ }
+ if !found {
+ return fmt.Errorf("%w: %s mount readback", demo.ErrPolicy, path)
+ }
+ }
if m["Slice"] != SliceName(host) {
return fmt.Errorf("%w: unit slice", demo.ErrPolicy)
}
diff --git a/internal/instancectl/demo_policy_test.go b/internal/instancectl/demo_policy_test.go
index bb436c609..5766dcdb0 100644
--- a/internal/instancectl/demo_policy_test.go
+++ b/internal/instancectl/demo_policy_test.go
@@ -15,19 +15,19 @@ import (
)
func TestDemoPolicyFailClosed(t *testing.T) {
- for _, path := range []string{"/seed?host=shop.example.com", "/cmd?host=shop.example.com", "/tty?host=shop.example.com", "/claim/launch", "/start?host=shop.example.com&role=sidecar", "/start?host=shop.example.com&role=worker", "/start?host=shop.example.com&runtime=rootfs"} {
+ for _, path := range []string{"/seed?host=shop.example.com", "/cmd?host=shop.example.com", "/tty?host=shop.example.com", "/claim/launch", "/start?host=shop.example.com&role=sidecar&memory_max=268435456", "/start?host=shop.example.com&role=worker&worker=job&runtime=rootfs&image=/image&version=v1&digest=abc&memory_max=268435456", "/start?host=shop.example.com&role=run&runtime=rootfs&image=/image&version=v1&digest=abc&memory_max=268435456"} {
t.Run(path, func(t *testing.T) {
calls := 0
s := &Server{DemoBox: true, Systemctl: func(context.Context, ...string) (string, error) { calls++; return "", nil }}
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", path, nil))
- if w.Code < 400 || calls != 0 {
+ if w.Code != 403 || !strings.Contains(w.Body.String(), "DEMO-POLICY") || calls != 0 {
t.Fatalf("unsupported start: status=%d calls=%d", w.Code, calls)
}
})
}
- good := "Slice=" + SliceName("shop.example.com") + "\nPrivateNetwork=yes\nRestrictAddressFamilies=AF_UNIX\nIPAddressDeny=0.0.0.0/0 ::/0\nIPAddressAllow=\nMemoryMax=268435456\nCPUWeight=50\nCPUQuotaPerSecUSec=500ms\nIOWeight=50\n"
- for _, field := range []string{"", "PrivateNetwork=yes", "RestrictAddressFamilies=AF_UNIX", "IPAddressDeny=0.0.0.0/0 ::/0", "IPAddressAllow=", "MemoryMax=268435456", "CPUWeight=50", "CPUQuotaPerSecUSec=500ms", "IOWeight=50", "readError"} {
+ good := "Slice=" + SliceName("shop.example.com") + "\nPrivateNetwork=yes\nNetworkNamespacePath=\nJoinsNamespaceOf=\nTemporaryFileSystem=/run:ro /var:ro /var/lib:ro /var/cache:ro\nRestrictAddressFamilies=AF_UNIX\nIPAddressDeny=0.0.0.0/0 ::/0\nIPAddressAllow=\nMemoryMax=268435456\nCPUWeight=50\nCPUQuotaPerSecUSec=500ms\nIOWeight=50\n"
+ for _, field := range []string{"", "PrivateNetwork=yes", "NetworkNamespacePath=", "JoinsNamespaceOf=", "TemporaryFileSystem=/run:ro /var:ro /var/lib:ro /var/cache:ro", "RestrictAddressFamilies=AF_UNIX", "IPAddressDeny=0.0.0.0/0 ::/0", "IPAddressAllow=", "MemoryMax=268435456", "CPUWeight=50", "CPUQuotaPerSecUSec=500ms", "IOWeight=50", "readError"} {
t.Run("readback/"+field, func(t *testing.T) {
s := &Server{DemoBox: true, Systemctl: func(context.Context, ...string) (string, error) {
if field == "readError" {
@@ -85,8 +85,9 @@ func TestDemoPolicyStartReadback(t *testing.T) {
query += "&gen=7"
}
small, _ := cgroup.SizeByName("small")
- good := "Slice=" + SliceName(host) + "\nPrivateNetwork=yes\nRestrictAddressFamilies=AF_UNIX\nIPAddressDeny=0.0.0.0/0 ::/0\nIPAddressAllow=\nMemoryMax=268435456\nCPUWeight=50\nCPUQuotaPerSecUSec=500ms\nIOWeight=50\n"
+ good := "Slice=" + SliceName(host) + "\nPrivateNetwork=yes\nNetworkNamespacePath=\nJoinsNamespaceOf=\nTemporaryFileSystem=/run:ro /var:ro /var/lib:ro /var/cache:ro\nRestrictAddressFamilies=AF_UNIX\nIPAddressDeny=0.0.0.0/0 ::/0\nIPAddressAllow=\nMemoryMax=268435456\nCPUWeight=50\nCPUQuotaPerSecUSec=500ms\nIOWeight=50\n"
started, stopped := false, false
+ tierWrites := 0
s := &Server{DemoBox: true, CgroupRoot: root, DropInDir: t.TempDir(), ExeRoot: t.TempDir()}
for _, dir := range []string{filepath.Join(root, parentSlices, SliceName(host)), filepath.Join(root, parentSlices, SliceName(host), unit)} {
if err := os.MkdirAll(dir, 0755); err != nil {
@@ -103,6 +104,9 @@ func TestDemoPolicyStartReadback(t *testing.T) {
}
s.Systemctl = func(_ context.Context, args ...string) (string, error) {
line := strings.Join(args, " ")
+ if args[0] == "set-property" {
+ tierWrites++
+ }
if args[0] == "start" {
started = true
return "", nil
@@ -128,6 +132,9 @@ func TestDemoPolicyStartReadback(t *testing.T) {
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", query, nil))
if failure == "" {
+ if tierWrites > 1 {
+ t.Fatalf("redundant tier writes: %d", tierWrites)
+ }
if w.Code != 200 || !started || stopped {
t.Fatalf("start: status=%d started=%v stopped=%v body=%s", w.Code, started, stopped, w.Body)
}
@@ -144,3 +151,34 @@ func TestDemoPolicyStartReadback(t *testing.T) {
}
}
}
+
+func TestDemoPolicyNamespaceReadback(t *testing.T) {
+ const host = "shop.example.com"
+ good := "Slice=" + SliceName(host) + "\nPrivateNetwork=yes\nRestrictAddressFamilies=AF_UNIX\nIPAddressDeny=any\nIPAddressAllow=\nNetworkNamespacePath=\nJoinsNamespaceOf=\nTemporaryFileSystem=/run:ro /var:ro\nMemoryMax=268435456\nCPUWeight=50\nCPUQuotaPerSecUSec=500ms\nIOWeight=50\n"
+ for _, tc := range []struct {
+ from, to string
+ ok bool
+ }{
+ {"/run:ro /var:ro", "/var:ro,nodev /data:ro /run:ro,nodev", true},
+ {"NetworkNamespacePath=\n", "", false},
+ {"JoinsNamespaceOf=\n", "", false},
+ {"TemporaryFileSystem=/run:ro /var:ro\n", "", false},
+ {"/run:ro", "/run-other:ro", false},
+ {"/var:ro", "/var/lib:ro", false},
+ {"/run:ro", "/run:rw", false},
+ {"/run:ro", "/run:ro,rw", false},
+ {"/var:ro", "/var", false},
+ } {
+ t.Run(tc.from+"->"+tc.to, func(t *testing.T) {
+ s := &Server{DemoBox: true, Systemctl: func(_ context.Context, args ...string) (string, error) {
+ if strings.Contains(strings.Join(args, " "), "PrivateNetwork") {
+ return strings.Replace(good, tc.from, tc.to, 1), nil
+ }
+ return good, nil
+ }}
+ if err := s.assertDemoUnit(t.Context(), host, UnitName(RoleRun, host)); (err == nil) != tc.ok {
+ t.Fatalf("readback: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/instancectl/gen.go b/internal/instancectl/gen.go
index 06ffc4572..b4ed149b4 100644
--- a/internal/instancectl/gen.go
+++ b/internal/instancectl/gen.go
@@ -391,10 +391,6 @@ func (s *Server) startGen(w http.ResponseWriter, r *http.Request, req request) {
// answer says. A failure past this point kills it and proves it empty
// before its files go; one that cannot prove that keeps the files and
// says so (statusGenUnproven).
- if err := s.assertDemoPolicy(ctx, req.host); err != nil {
- fail(http.StatusBadGateway, err.Error())
- return
- }
if err := s.assertDemoUnit(ctx, req.host, unit); err != nil {
fail(http.StatusBadGateway, err.Error())
return
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index fa40dd0ae..42af863c1 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -816,10 +816,6 @@ func (s *Server) handleStart(w http.ResponseWriter, r *http.Request) {
http.Error(w, "start: cancelled before it was submitted: "+err.Error(), http.StatusConflict)
return
}
- if err := s.assertDemoPolicy(ctx, req.host); err != nil {
- http.Error(w, err.Error(), http.StatusBadGateway)
- return
- }
if err := s.assertDemoUnit(ctx, req.host, unit); err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return