carlos / platform Public

fix: demo isolation review round 2

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 93ae8e708121427c5f36cba0a228f080d18ed2a0 parent b7f1c15
7 files changed, +310 −10
  • internal/host/demo_mounts_test.go +181 −0
  • internal/host/demo_policy.go +2 −1
  • internal/host/demo_policy_linux_test.go +24 −1
  • internal/host/demo_policy_test.go +98 −1
  • internal/host/demo_units/demo.conf +2 −0
  • internal/hostenv/demo_test.go +3 −3
  • internal/hostenv/hostenv.go +0 −4

CI failed — run details

Intent

Human

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

Attributed to this commit: 12.3 g CO₂e (1,549,432 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/host/demo_mounts_test.go b/internal/host/demo_mounts_test.go
new file mode 100644
index 000000000..7d913ff15
--- /dev/null
+++ b/internal/host/demo_mounts_test.go
@@ -0,0 +1,181 @@
+package host
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+func TestDemoPolicyMergedMountPaths(t *testing.T) {
+ root := t.TempDir()
+ if err := installDemoUnits(root, demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}); err != nil {
+ t.Fatal(err)
+ }
+ // Discover the installed drop-ins so adding another covered template also
+ // adds it to this check. Generations need their real per-start drop-in.
+ paths, err := filepath.Glob(filepath.Join(root, "etc/systemd/system/*.service.d/90-carlos-demo.conf"))
+ if err != nil || len(paths) == 0 {
+ t.Fatalf("demo drop-ins: %v %v", paths, err)
+ }
+ for _, path := range paths {
+ unit := strings.TrimSuffix(filepath.Base(filepath.Dir(path)), ".d")
+ t.Run(unit, func(t *testing.T) {
+ raw, err := unitsFS.ReadFile("units/" + unit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ drop, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const host = "shop.example.com"
+ key := provision.InstanceID(host)
+ generation := ""
+ if unit == "carlos-instance-gen@.service" {
+ key = instancectl.GenKey(host, 7)
+ small, _ := cgroup.SizeByName("small")
+ generation = instancectl.GenDropIn(host, 7, small.Limit)
+ }
+ template := strings.NewReplacer("%I", key, "%i", key).Replace(string(raw))
+ for _, problem := range demoHiddenRequiredPaths(template, generation, string(drop)) {
+ t.Error(problem)
+ }
+ })
+ }
+}
+
+// This checks the simple unquoted path syntax used by the embedded units,
+// including list resets across drop-ins. It is not a systemd parser: the
+// gated real-unit witness remains the proof of namespace setup.
+func demoHiddenRequiredPaths(parts ...string) []string {
+ values := map[string][]string{}
+ for _, part := range parts {
+ service := false
+ for _, line := range strings.Split(part, "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "[") {
+ service = line == "[Service]"
+ continue
+ }
+ if !service || line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
+ continue
+ }
+ key, value, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ key, value = strings.TrimSpace(key), strings.TrimSpace(value)
+ if value == "" && (key == "BindPaths" || key == "BindReadOnlyPaths") {
+ values["BindPaths"], values["BindReadOnlyPaths"] = nil, nil
+ }
+ if value == "" || key == "WorkingDirectory" || strings.HasPrefix(key, "Standard") {
+ values[key] = nil
+ }
+ values[key] = append(values[key], strings.Fields(value)...)
+ }
+ }
+ within := func(path, parent string) bool { return path == parent || strings.HasPrefix(path, parent+"/") }
+ var mounts, binds []string
+ for _, value := range values["TemporaryFileSystem"] {
+ mounts = append(mounts, strings.SplitN(value, ":", 2)[0])
+ }
+ for _, key := range []string{"BindPaths", "BindReadOnlyPaths"} {
+ for _, value := range values[key] {
+ // Optional sources do not prove their destination exists.
+ if strings.HasPrefix(value, "-") {
+ continue
+ }
+ fields := strings.Split(value, ":")
+ dest := fields[0]
+ if len(fields) > 1 {
+ dest = fields[1]
+ }
+ binds = append(binds, dest)
+ }
+ }
+ var problems []string
+ for key, paths := range values {
+ switch key {
+ case "TemporaryFileSystem", "BindPaths", "BindReadOnlyPaths":
+ // Mount targets are created; bind sources are opened on the host.
+ continue
+ case "StandardInput", "StandardOutput", "StandardError", "EnvironmentFile":
+ // systemd opens these on the host before entering the namespace.
+ continue
+ }
+ for i, path := range paths {
+ if strings.HasPrefix(key, "Exec") && i != 0 {
+ continue
+ }
+ if strings.HasPrefix(path, "-") {
+ continue
+ }
+ // These directory names are relative to systemd's fixed roots.
+ // Neither template uses them. Flag future additions beneath tmpfs
+ // for an explicit bind/namespace audit, rather than assuming one.
+ switch key {
+ case "RuntimeDirectory":
+ path = "/run/" + path
+ case "StateDirectory":
+ path = "/var/lib/" + path
+ case "CacheDirectory":
+ path = "/var/cache/" + path
+ case "LogsDirectory":
+ path = "/var/log/" + path
+ case "ConfigurationDirectory":
+ path = "/etc/" + path
+ }
+ if !strings.HasPrefix(path, "/") {
+ continue
+ }
+ path = filepath.Clean(path)
+ hiddenBy := ""
+ for _, mount := range mounts {
+ if within(path, mount) && len(mount) > len(hiddenBy) {
+ hiddenBy = mount
+ }
+ }
+ if hiddenBy == "" || path == hiddenBy {
+ continue
+ }
+ restored := false
+ for _, bind := range binds {
+ if within(path, bind) && within(bind, hiddenBy) {
+ restored = true
+ }
+ }
+ if !restored {
+ problems = append(problems, fmt.Sprintf("%s=%s requires a path hidden by TemporaryFileSystem=%s", key, path, hiddenBy))
+ }
+ }
+ }
+ return problems
+}
+
+func TestDemoPolicyMountPathGuard(t *testing.T) {
+ const base = "[Service]\nTemporaryFileSystem=/run:ro /var:ro\nBindPaths=/run/carlos/instances/shop\n"
+ for _, directive := range []string{
+ "InaccessiblePaths=/run/carlos-control", "ReadWritePaths=/run/missing", "ReadOnlyPaths=/var/missing",
+ "WorkingDirectory=/run/missing", "ExecStart=/run/missing", "ExecStopPost=/run/missing",
+ "RuntimeDirectory=missing", "LogsDirectory=missing", "StateDirectory=missing", "CacheDirectory=missing",
+ "BindPaths=\nReadWritePaths=/run/carlos/instances/shop",
+ "BindReadOnlyPaths=\nReadWritePaths=/run/carlos/instances/shop",
+ "BindPaths=-/run/optional\nReadWritePaths=/run/optional",
+ "TemporaryFileSystem=/run/carlos/instances/shop/hidden:ro\nReadWritePaths=/run/carlos/instances/shop/hidden/missing",
+ } {
+ if problems := demoHiddenRequiredPaths(base, "[Service]\n"+directive); len(problems) == 0 {
+ t.Errorf("missed hidden required path: %s", directive)
+ }
+ }
+ const safe = "[Service]\nInaccessiblePaths=/run/missing\nInaccessiblePaths=\nInaccessiblePaths=-/run/missing /etc/carlos\nReadWritePaths=/run/carlos/instances/shop\nReadOnlyPaths=/runtime/visible\nStandardOutput=file:/run/carlos/logs/shop.sock\nBindReadOnlyPaths=/run/carlos-control/exe/shop:/opt/carlos/app\n"
+ if problems := demoHiddenRequiredPaths(base, safe); len(problems) != 0 {
+ t.Fatal(problems)
+ }
+}
diff --git a/internal/host/demo_policy.go b/internal/host/demo_policy.go
index 34c0f8202..1ca344171 100644
--- a/internal/host/demo_policy.go
+++ b/internal/host/demo_policy.go
@@ -5,6 +5,7 @@ import (
"context"
_ "embed"
"fmt"
+ "log"
"os"
"path/filepath"
"time"
@@ -36,7 +37,7 @@ func installDemoUnitsIn(unitDir string, cfg demo.Config) (bool, error) {
if err := os.Remove(path); err == nil {
changed = true
} else if !os.IsNotExist(err) {
- return changed, err
+ log.Printf("demo unit cleanup: remove %s: %v; will retry next pass", path, err)
}
continue
}
diff --git a/internal/host/demo_policy_linux_test.go b/internal/host/demo_policy_linux_test.go
index 605d2504c..aa1881873 100644
--- a/internal/host/demo_policy_linux_test.go
+++ b/internal/host/demo_policy_linux_test.go
@@ -261,7 +261,17 @@ func TestDemoDenyAllKernel(t *testing.T) {
mkdir(dir)
}
create(logPath, nil, 0644)
- sock := runtimeDir + "/witness.sock"
+ socketDir := runtimeDir
+ if i == 1 {
+ // Match the agent's per-generation socket layout beneath the
+ // runtime bind, so the /run overlay must preserve this too.
+ socketDir = filepath.Join(runtimeDir, "g7")
+ mkdir(socketDir)
+ if err := os.Chown(socketDir, uid, gid); err != nil {
+ t.Fatal(err)
+ }
+ }
+ sock := socketDir + "/app.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)
@@ -314,13 +324,23 @@ func TestDemoDenyAllKernel(t *testing.T) {
}
break
}
+ state := run("show", unit, "-p", "ActiveState", "-p", "Result", "-p", "ExecMainStatus")
+ if strings.Contains(state, "ActiveState=failed") || strings.Contains(state, "ActiveState=inactive") {
+ t.Fatalf("real unit exited before publishing its socket (226 means NAMESPACE): %s; log: %s", state, readDemoWitnessLog(logPath))
+ }
select {
case <-ctx.Done():
t.Fatalf("fixture did not prove isolation: %v; log: %s", err, readDemoWitnessLog(logPath))
case <-time.After(50 * time.Millisecond):
}
}
+ if state := strings.TrimSpace(run("show", unit, "-p", "ActiveState", "--value")); state != "active" {
+ t.Fatalf("socket served without an active real unit: %s", state)
+ }
run("stop", unit)
+ if result := strings.TrimSpace(run("show", unit, "-p", "Result", "--value")); result != "success" {
+ t.Fatalf("real unit stop/ExecStopPost failed: %s; log: %s", result, readDemoWitnessLog(logPath))
+ }
_ = os.Remove(sock)
})
}
@@ -365,6 +385,9 @@ func TestDemoDenyAllKernelHelper(t *testing.T) {
if sock == "control" {
return
}
+ if _, err := os.Stat("/run/carlos-control"); !errors.Is(err, syscall.ENOENT) {
+ t.Fatalf("control directory must be absent beneath the /run tmpfs: %v", err)
+ }
for _, path := range demoResolverSockets {
demoResolutionRefused(t, path)
}
diff --git a/internal/host/demo_policy_test.go b/internal/host/demo_policy_test.go
index c964ef5f7..02af7858a 100644
--- a/internal/host/demo_policy_test.go
+++ b/internal/host/demo_policy_test.go
@@ -1,8 +1,10 @@
package host
import (
+ "bytes"
"context"
"errors"
+ "log"
"os"
"path/filepath"
"strings"
@@ -23,7 +25,7 @@ func TestDemoPolicyRoundTrip(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- 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"} {
+ for _, want := range []string{"PrivateNetwork=yes", "TemporaryFileSystem=/run:ro /var:ro", "InaccessiblePaths=\nInaccessiblePaths=/etc/carlos -/run/carlos-control", "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)
}
@@ -241,3 +243,98 @@ func TestDemoPolicyConsoleTupleDoesNotConfigureBox(t *testing.T) {
t.Fatal("ordinary control unit changed")
}
}
+
+func TestDemoPolicyRemovalWarningsRetry(t *testing.T) {
+ var warnings bytes.Buffer
+ oldWriter := log.Writer()
+ log.SetOutput(&warnings)
+ t.Cleanup(func() { log.SetOutput(oldWriter) })
+ for _, obstruction := range []string{"parent-file", "nonempty-drop-in-directory"} {
+ t.Run(obstruction, func(t *testing.T) {
+ dir := t.TempDir()
+ badDir := filepath.Join(dir, "carlos-instance@.service.d")
+ bad := filepath.Join(badDir, "90-carlos-demo.conf")
+ if obstruction == "parent-file" {
+ if err := os.WriteFile(badDir, nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if err := os.MkdirAll(bad, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(bad, "keep"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ goodDir := filepath.Join(dir, "carlos-instance-gen@.service.d")
+ if err := os.Mkdir(goodDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ good := filepath.Join(goodDir, "90-carlos-demo.conf")
+ if err := os.WriteFile(good, []byte(demoNetworkDropIn), 0644); err != nil {
+ t.Fatal(err)
+ }
+ warnings.Reset()
+ changed, err := installDemoUnitsIn(dir, demo.Config{})
+ if err != nil || !changed {
+ t.Errorf("ordinary cleanup must continue: changed=%v err=%v", changed, err)
+ }
+ if !strings.Contains(warnings.String(), bad) || !strings.Contains(warnings.String(), "retry") {
+ t.Errorf("missing path/retry warning: %q", warnings.String())
+ }
+ if _, err := os.Stat(good); !os.IsNotExist(err) {
+ t.Errorf("other drop-in not removed: %v", err)
+ }
+ // An enabled demo box must still refuse an unreadable drop-in.
+ if _, err := installDemoUnitsIn(dir, demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com"}); err == nil {
+ t.Error("demo install ignored obstruction")
+ }
+ if err := os.RemoveAll(badDir); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Mkdir(badDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(bad, []byte(demoNetworkDropIn), 0644); err != nil {
+ t.Fatal(err)
+ }
+ warnings.Reset()
+ if changed, err := installDemoUnitsIn(dir, demo.Config{}); err != nil || !changed {
+ t.Fatalf("next pass did not retry: %v %v", changed, err)
+ }
+ if changed, err := installDemoUnitsIn(dir, demo.Config{}); err != nil || changed {
+ t.Fatalf("absent drop-in: %v %v", changed, err)
+ }
+ if warnings.Len() != 0 {
+ t.Errorf("successful/absent cleanup warned: %s", &warnings)
+ }
+ })
+ }
+}
+
+func TestDemoPolicyOrdinaryInstallersIgnoreRemovalFailure(t *testing.T) {
+ obstruct := func(unitDir string) {
+ t.Helper()
+ if err := os.MkdirAll(unitDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(unitDir, "carlos-instance@.service.d"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ root := t.TempDir()
+ obstruct(filepath.Join(root, "etc/systemd/system"))
+ if err := bootstrap(root, nil); err != nil {
+ t.Fatalf("ordinary bootstrap: %v", err)
+ }
+
+ stage := t.TempDir()
+ if err := bootstrap(stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ obstruct(filepath.Join(f.a.etcDir, "systemd/system"))
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatalf("ordinary apply: %v", err)
+ }
+}
diff --git a/internal/host/demo_units/demo.conf b/internal/host/demo_units/demo.conf
index 9554d6677..7dc3c8282 100644
--- a/internal/host/demo_units/demo.conf
+++ b/internal/host/demo_units/demo.conf
@@ -6,4 +6,6 @@ IPAddressAllow=
IPAddressDeny=
IPAddressDeny=any
TemporaryFileSystem=/run:ro /var:ro
+InaccessiblePaths=
+InaccessiblePaths=/etc/carlos -/run/carlos-control
NetworkNamespacePath=
diff --git a/internal/hostenv/demo_test.go b/internal/hostenv/demo_test.go
index 7d8692c5a..4a3890243 100644
--- a/internal/hostenv/demo_test.go
+++ b/internal/hostenv/demo_test.go
@@ -2,10 +2,10 @@ package hostenv
import "testing"
-func TestDemoBoxKeysAllowed(t *testing.T) {
+func TestDemoBoxKeysArePerBoxOnly(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)
+ if Allowed(key) {
+ t.Errorf("box authority allowed in shared/region parameters: %s", key)
}
}
}
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go
index 2c28c610e..aeef72cd6 100644
--- a/internal/hostenv/hostenv.go
+++ b/internal/hostenv/hostenv.go
@@ -75,10 +75,6 @@ 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",