egress: the wholly-nested rail decides from root's own evidence, which a flat tenant cannot rewrite (#328, final review F2)
The rail read only registry rows, the agent's records, which a flat tenant runs as the agent's user and can rewrite: remove its own row, widen a nested host's allow. Before any allow is honoured root now reads, once per snapshot: systemd's unit table (one batched show; a running service whose User resolves to the agent's user, other than the platform's own units, refuses), the agent's delegated cgroup subtree (anything populated outside the agent's supervise leaf refuses: flat exec children and sidecar members run in carlos-exec@ cgroups there), and registry.db, its journal files and its directory (group- or world-writable refuses). The row check stays as a further refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+935
−32
internal/cgroup/cgroup.go+12 −1internal/cgroup/verify_linux.go+1 −1internal/host/egress_rail.go+216 −0internal/host/egress_rail_linux.go+95 −0internal/host/egress_rail_linux_test.go+260 −0internal/host/egress_rail_other.go+11 −0internal/host/egress_rail_rootrunner_linux_test.go+242 −0internal/host/egress_source.go+32 −11internal/host/egress_source_sweep_linux_test.go+6 −3internal/host/egress_source_test.go+60 −16
diff --git a/internal/cgroup/cgroup.go b/internal/cgroup/cgroup.go| index db5faf516..1dfa0cfb3 100644 |
| --- a/internal/cgroup/cgroup.go |
| +++ b/internal/cgroup/cgroup.go |
| @@ -31,6 +31,17 @@ import ( |
| "testing" |
| ) |
| +// SuperviseLeaf is the agent's own leaf in its delegated subtree: setupAt |
| +// moves the agent's process there before it enables controllers, and every |
| +// child the agent places goes elsewhere (a carlos-exec@ cgroup). |
| +// PlacementCheckName is VerifyPlacement's scratch cgroup beside them, which |
| +// holds the agent's own probe for at most its 4 s budget. Root's egress |
| +// rail (internal/host) reads the subtree by these names. |
| +const ( |
| + SuperviseLeaf = "supervise" |
| + PlacementCheckName = "carlos-placement-check" |
| +) |
| + |
| // execPrefix is the ONE definition of the per-host exec cgroup naming — |
| // activator.ExecName and the sampler's directory match both come through |
| // this package. |
| @@ -267,7 +278,7 @@ func setupAt(root string, logf func(string, ...any), retain bool) (*Manager, err |
| f.Close() |
| } |
| // 2. Move ourselves into a supervise/ leaf, making step 3 legal. |
| - sup := filepath.Join(root, "supervise") |
| + sup := filepath.Join(root, SuperviseLeaf) |
| if err := os.MkdirAll(sup, 0o755); err != nil { |
| return nil, fmt.Errorf("create supervise leaf: %w", err) |
| } |
diff --git a/internal/cgroup/verify_linux.go b/internal/cgroup/verify_linux.go| index 5259daf63..650d1f2a6 100644 |
| --- a/internal/cgroup/verify_linux.go |
| +++ b/internal/cgroup/verify_linux.go |
| @@ -21,7 +21,7 @@ import ( |
| // placementCheckName is the scratch child of the delegated root that |
| // VerifyPlacement places its probe in. It is no carlos-exec@ name, so no |
| // host's cleanup or the stale sweep ever takes it for a host's cgroup. |
| -const placementCheckName = "carlos-placement-check" |
| +const placementCheckName = PlacementCheckName |
| // placementProbeArgs is the probe tenant's argv after shimExe. Only tests |
| // change it, to stand in a probe that misreports or never exits. |
diff --git a/internal/host/egress_rail.go b/internal/host/egress_rail.go| new file mode 100644 |
| index 000000000..154e4c39f |
| --- /dev/null |
| +++ b/internal/host/egress_rail.go |
| @@ -0,0 +1,216 @@ |
| +package host |
| + |
| +// The wholly-nested rail's root-controlled evidence (#328, final review F2). |
| +// The registry rows boxWhollyNested reads are the agent's records, and a |
| +// flat tenant runs as the agent's user, so it can rewrite them: remove its |
| +// own row, or give a nested host an allow. Changing a row does not stop a |
| +// process that is running. So before any allow is honoured, root looks at |
| +// what it can trust and a tenant of the agent's user cannot rewrite: |
| +// |
| +// - systemd's unit table (one batched systemctl show): every running |
| +// service whose User resolves to the agent's user, other than the |
| +// platform's own units, makes the box not wholly nested; |
| +// - the agent's delegated cgroup subtree (cgroupfs, under the ControlGroup |
| +// systemd gives carlos-edge.service): flat exec children and sidecar |
| +// members run in carlos-exec@ cgroups there, so any populated cgroup |
| +// other than the agent's own leaf makes the box not wholly nested; |
| +// - registry.db, its journal files and its directory: group- or |
| +// world-writable lets a user other than the agent write the rows. |
| +// |
| +// The registry-row check stays as a further refusal (registrySource.policyFrom). |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| +) |
| + |
| +// agentUnit is the agent's own service: the edge, which runs as the agent's |
| +// user and whose delegated subtree holds the flat processes. |
| +const agentUnit = "carlos-edge.service" |
| + |
| +// railShowArgs is the rail's one batched read of systemd's unit table: |
| +// every loaded service's name, state, user and cgroup. The pattern is a |
| +// constant; nothing from the registry reaches systemctl here. |
| +var railShowArgs = []string{"show", "-p", "Id,ActiveState,User,DynamicUser,ControlGroup", "*.service"} |
| + |
| +// railService is one service as railShowArgs prints it. |
| +type railService struct { |
| + id, active, user, dynamic, controlGroup string |
| +} |
| + |
| +// railEvidence reads the rail's evidence on this box. cgroupRoot is |
| +// /sys/fs/cgroup in production; dataDir holds registry.db. |
| +type railEvidence struct { |
| + cgroupRoot string |
| + dataDir string |
| + systemctl func(context.Context, ...string) (string, error) |
| + lookupUID func(name string) (uid string, found bool, err error) |
| +} |
| + |
| +// check is true when the evidence shows no process of the agent's user |
| +// outside the agent itself and the nested units, and no other user able to |
| +// write the registry; reason names the first thing that is not so, or what |
| +// could not be read (which counts against the box). |
| +func (r railEvidence) check(ctx context.Context) (ok bool, reason string) { |
| + out, err := r.systemctl(ctx, railShowArgs...) |
| + if err != nil { |
| + return false, fmt.Sprintf("the box's running services could not be read: %s: %v", strings.TrimSpace(out), err) |
| + } |
| + services, err := parseRailServices(out) |
| + if err != nil { |
| + return false, "the box's running services could not be read: " + err.Error() |
| + } |
| + lookup := cachedLookup(r.lookupUID) |
| + var agentCgroup string |
| + for _, svc := range services { |
| + if svc.id == agentUnit { |
| + agentCgroup = svc.controlGroup |
| + } |
| + if !railRunning(svc.active) || platformService(svc.id) { |
| + continue |
| + } |
| + asAgent, err := userIsAgent(svc.user, svc.dynamic, lookup) |
| + if err != nil { |
| + return false, fmt.Sprintf("%s is running, and its user could not be read: %v", svc.id, err) |
| + } |
| + if asAgent { |
| + return false, fmt.Sprintf("%s is running as the agent's user", svc.id) |
| + } |
| + } |
| + if agentCgroup != "" { |
| + if reason, err := agentSubtreeOthers(r.cgroupRoot, agentCgroup); err != nil { |
| + return false, "the agent's cgroup could not be read: " + err.Error() |
| + } else if reason != "" { |
| + return false, reason |
| + } |
| + } |
| + if reason, err := registryWritableByOthers(r.dataDir); err != nil { |
| + return false, "the registry's permissions could not be read: " + err.Error() |
| + } else if reason != "" { |
| + return false, reason |
| + } |
| + return true, "" |
| +} |
| + |
| +// parseRailServices reads railShowArgs' output: one block per unit, the |
| +// blocks separated by a blank line, each with all five properties. A block |
| +// missing one, or a line that is not a property, is an error. |
| +func parseRailServices(out string) ([]railService, error) { |
| + var services []railService |
| + for _, block := range strings.Split(strings.ReplaceAll(out, "\r\n", "\n"), "\n\n") { |
| + if strings.TrimSpace(block) == "" { |
| + continue |
| + } |
| + props := map[string]string{} |
| + for _, line := range strings.Split(strings.TrimSpace(block), "\n") { |
| + k, v, ok := strings.Cut(line, "=") |
| + if !ok { |
| + return nil, fmt.Errorf("systemctl show printed %q", line) |
| + } |
| + props[k] = v |
| + } |
| + for _, k := range []string{"Id", "ActiveState", "User", "DynamicUser", "ControlGroup"} { |
| + if _, ok := props[k]; !ok { |
| + return nil, fmt.Errorf("systemctl show printed a unit without %s: %q", k, block) |
| + } |
| + } |
| + if props["Id"] == "" { |
| + return nil, fmt.Errorf("systemctl show printed a unit with no name: %q", block) |
| + } |
| + services = append(services, railService{id: props["Id"], active: props["ActiveState"], user: props["User"], |
| + dynamic: props["DynamicUser"], controlGroup: props["ControlGroup"]}) |
| + } |
| + return services, nil |
| +} |
| + |
| +// railRunning is whether a service in this ActiveState may have processes: |
| +// every state but inactive and failed, an unknown one included. |
| +func railRunning(active string) bool { return active != "inactive" && active != "failed" } |
| + |
| +// platformService is whether name is one of the platform's own services, |
| +// installed by root from the units bootstrap embeds (unitsFS): a fixed |
| +// unit, or an instance of a template ("carlos-instance@<id>.service" of |
| +// carlos-instance@.service). Only root installs units, so a tenant cannot |
| +// take one of these names. Those that run as the agent's user are the agent |
| +// itself (carlos-edge.service, whose flat children agentSubtreeOthers |
| +// reads), the nested instance templates and the probe (each sandboxed away |
| +// from /data/registry.db: TemporaryFileSystem=/data:ro), and platform |
| +// programs (litestream, relay, the verify timers). |
| +func platformService(name string) bool { |
| + fixed, templates := platformServiceNames() |
| + if slices.Contains(fixed, name) { |
| + return true |
| + } |
| + for _, prefix := range templates { |
| + if inst, ok := strings.CutPrefix(name, prefix); ok && strings.HasSuffix(inst, ".service") && inst != ".service" { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// platformServiceNames is unitsFS's services: fixed names, and each |
| +// template's "<name>@" prefix. |
| +var platformServiceNames = sync.OnceValues(func() (fixed, templates []string) { |
| + names, err := unitNames() |
| + if err != nil { |
| + return nil, nil // nothing is exempt: the rail fails closed |
| + } |
| + for _, n := range names { |
| + if !strings.HasSuffix(n, ".service") { |
| + continue |
| + } |
| + if prefix, ok := strings.CutSuffix(n, "@.service"); ok { |
| + templates = append(templates, prefix+"@") |
| + } else { |
| + fixed = append(fixed, n) |
| + } |
| + } |
| + return fixed, templates |
| +}) |
| + |
| +// cachedLookup answers each name once per rail read. |
| +func cachedLookup(lookup func(string) (string, bool, error)) func(string) (string, bool, error) { |
| + type answer struct { |
| + uid string |
| + found bool |
| + err error |
| + } |
| + seen := map[string]answer{} |
| + return func(name string) (string, bool, error) { |
| + if a, ok := seen[name]; ok { |
| + return a.uid, a.found, a.err |
| + } |
| + uid, found, err := lookup(name) |
| + seen[name] = answer{uid, found, err} |
| + return uid, found, err |
| + } |
| +} |
| + |
| +// registryWritableByOthers reports, as a reason, registry.db, any of its |
| +// journal files that exist, or its directory being group- or |
| +// world-writable: a user other than the agent could then write the rows. |
| +// A fresh bootstrap makes /data 0750 and registry.db 0640. |
| +func registryWritableByOthers(dataDir string) (string, error) { |
| + base := filepath.Join(dataDir, "registry.db") |
| + for _, p := range []string{dataDir, base, base + "-wal", base + "-shm", base + "-journal"} { |
| + fi, err := os.Stat(p) |
| + if err != nil { |
| + if p != dataDir && p != base && errors.Is(err, fs.ErrNotExist) { |
| + continue |
| + } |
| + return "", err |
| + } |
| + if perm := fi.Mode().Perm(); perm&0o022 != 0 { |
| + return fmt.Sprintf("%s is writable by users other than the agent (mode %04o)", p, perm), nil |
| + } |
| + } |
| + return "", nil |
| +} |
diff --git a/internal/host/egress_rail_linux.go b/internal/host/egress_rail_linux.go| new file mode 100644 |
| index 000000000..fed38cd3a |
| --- /dev/null |
| +++ b/internal/host/egress_rail_linux.go |
| @@ -0,0 +1,95 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/cgroup" |
| +) |
| + |
| +// agentSubtreeOthers reads the agent's delegated cgroup subtree (its |
| +// unit's ControlGroup under cgroupRoot) and reports, as a reason, the |
| +// first thing that runs there outside the agent's own leaf |
| +// (cgroup.SuperviseLeaf): a populated child cgroup (a flat exec child or a |
| +// sidecar member, in its carlos-exec@ cgroup), a populated cgroup under the |
| +// leaf, or a process in the subtree's root itself (an agent that never |
| +// moved to its leaf, so its children cannot be told from it). Not counted: |
| +// the leaf's own processes (the agent and the helpers it runs there), |
| +// cgroup.PlacementCheckName (the agent's own placement probe, at most 4 s |
| +// at arm time) and systemd's ".control" (the unit file's own control |
| +// processes, ExecReload). A subtree that is gone has nothing running. |
| +func agentSubtreeOthers(cgroupRoot, controlGroup string) (string, error) { |
| + rel := strings.TrimPrefix(controlGroup, "/") |
| + if rel == "" || !filepath.IsLocal(rel) { |
| + return "", fmt.Errorf("%s's ControlGroup is %q", agentUnit, controlGroup) |
| + } |
| + root := filepath.Join(cgroupRoot, rel) |
| + procs, err := os.ReadFile(filepath.Join(root, "cgroup.procs")) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return "", nil // the unit stopped between systemd's answer and this read |
| + } |
| + if err != nil { |
| + return "", err |
| + } |
| + if strings.TrimSpace(string(procs)) != "" { |
| + return fmt.Sprintf("processes run in the agent's cgroup %s outside its own leaf (%s)", controlGroup, cgroup.SuperviseLeaf), nil |
| + } |
| + entries, err := os.ReadDir(root) |
| + if err != nil { |
| + return "", err |
| + } |
| + for _, ent := range entries { |
| + name := ent.Name() |
| + if !ent.IsDir() || name == cgroup.PlacementCheckName || name == ".control" { |
| + continue |
| + } |
| + if name == cgroup.SuperviseLeaf { |
| + kids, err := os.ReadDir(filepath.Join(root, name)) |
| + if err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + return "", err |
| + } |
| + for _, kid := range kids { |
| + if !kid.IsDir() { |
| + continue |
| + } |
| + populated, err := cgroupPopulated(filepath.Join(root, name, kid.Name())) |
| + if err != nil { |
| + return "", err |
| + } |
| + if populated { |
| + return fmt.Sprintf("%s/%s runs under the agent's own leaf in its cgroup %s", name, kid.Name(), controlGroup), nil |
| + } |
| + } |
| + continue |
| + } |
| + populated, err := cgroupPopulated(filepath.Join(root, name)) |
| + if err != nil { |
| + return "", err |
| + } |
| + if populated { |
| + return fmt.Sprintf("%s runs in the agent's cgroup %s, outside its own leaf", name, controlGroup), nil |
| + } |
| + } |
| + return "", nil |
| +} |
| + |
| +// cgroupPopulated reads a cgroup's cgroup.events ("populated 1": something |
| +// runs in it or below it). One that went between the list and the read |
| +// holds nothing. |
| +func cgroupPopulated(dir string) (bool, error) { |
| + b, err := os.ReadFile(filepath.Join(dir, "cgroup.events")) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + return slices.Contains(strings.Split(string(b), "\n"), "populated 1"), nil |
| +} |
diff --git a/internal/host/egress_rail_linux_test.go b/internal/host/egress_rail_linux_test.go| new file mode 100644 |
| index 000000000..fcd47cacd |
| --- /dev/null |
| +++ b/internal/host/egress_rail_linux_test.go |
| @@ -0,0 +1,260 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +// Final review F2 (#328): the wholly-nested rail decides from root's own |
| +// evidence (railEvidence), which a flat tenant cannot rewrite, and the |
| +// registry rows can only refuse further. The cgroup trees here are laid |
| +// out as cgroupfs is; TestRootEgressFlatProcessFalsifiedRow is the real |
| +// one. |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// railEdgeCgroup is carlos-edge.service's ControlGroup in the fixtures. |
| +const railEdgeCgroup = "/carlos.slice/carlos-edge.service" |
| + |
| +// railBox is a box's evidence: a cgroup tree with the agent's delegated |
| +// subtree (the agent in its leaf), the services systemd lists, and a data |
| +// dir with a private registry. |
| +type railBox struct { |
| + cgroup, data string |
| + units *fakeUnitShow |
| +} |
| + |
| +func newRailBox(t *testing.T) *railBox { |
| + t.Helper() |
| + b := &railBox{cgroup: t.TempDir(), units: &fakeUnitShow{units: map[string]string{}}} |
| + b.dir(t, "", false) |
| + b.procs(t, "", "") |
| + b.dir(t, cgroup.SuperviseLeaf, true) // the agent |
| + b.procs(t, cgroup.SuperviseLeaf, "4242\n") |
| + reg, dd := egressRegistry(t) |
| + reg.Close() |
| + b.data = dd |
| + b.units.services = []string{ |
| + railBlock(agentUnit, "active", "carlos", "no", railEdgeCgroup), |
| + railBlock("carlos-instance@shop-a.example.com.service", "active", "carlos", "no", "/carlos.slice/carlos-instances.slice/x"), |
| + railBlock("carlos-instance-gen@shop-a.example.com-1.service", "active", "carlos", "no", "/x"), |
| + railBlock("carlos-litestream.service", "active", "carlos", "no", "/x"), |
| + railBlock("carlos-app@app.example.com.service", "active", "", "yes", "/x"), |
| + railBlock("console.service", "active", "console", "no", "/x"), |
| + railBlock("sshd.service", "active", "", "no", "/x"), |
| + railBlock("old-worker.service", "inactive", "carlos", "no", ""), |
| + } |
| + return b |
| +} |
| + |
| +func railBlock(id, active, user, dynamic, cg string) string { |
| + return "Id=" + id + "\nActiveState=" + active + "\nUser=" + user + "\nDynamicUser=" + dynamic + "\nControlGroup=" + cg |
| +} |
| + |
| +// dir makes a cgroup under the agent's subtree ("" is its root), with |
| +// cgroup.events saying whether something runs in or below it. |
| +func (b *railBox) dir(t *testing.T, rel string, populated bool) { |
| + t.Helper() |
| + d := filepath.Join(b.cgroup, railEdgeCgroup, rel) |
| + if err := os.MkdirAll(d, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + ev := "populated 0\nfrozen 0\n" |
| + if populated { |
| + ev = "populated 1\nfrozen 0\n" |
| + } |
| + if err := os.WriteFile(filepath.Join(d, "cgroup.events"), []byte(ev), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (b *railBox) procs(t *testing.T, rel, pids string) { |
| + t.Helper() |
| + if err := os.WriteFile(filepath.Join(b.cgroup, railEdgeCgroup, rel, "cgroup.procs"), []byte(pids), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (b *railBox) check() (bool, string) { |
| + return railEvidence{cgroupRoot: b.cgroup, dataDir: b.data, systemctl: b.units.run, lookupUID: fakeUsers}.check(context.Background()) |
| +} |
| + |
| +func TestEgressRailEvidence(t *testing.T) { |
| + t.Parallel() |
| + for _, tc := range []struct { |
| + name string |
| + change func(t *testing.T, b *railBox) |
| + reason string // "" is wholly nested |
| + }{ |
| + {"the agent alone in its leaf, nested units, platform and other users' services", func(*testing.T, *railBox) {}, ""}, |
| + {"an empty carlos-exec@ cgroup a stopped flat child left", func(t *testing.T, b *railBox) { |
| + b.dir(t, cgroup.ExecName("old.example.com"), false) |
| + }, ""}, |
| + {"the agent's placement probe and systemd's control processes", func(t *testing.T, b *railBox) { |
| + b.dir(t, cgroup.PlacementCheckName, true) |
| + b.dir(t, ".control", true) |
| + }, ""}, |
| + {"a running flat exec child", func(t *testing.T, b *railBox) { |
| + b.dir(t, cgroup.ExecName("flat.example.com"), true) |
| + }, "carlos-exec@flat.example.com runs in the agent's cgroup /carlos.slice/carlos-edge.service, outside its own leaf"}, |
| + {"a cgroup under the agent's leaf", func(t *testing.T, b *railBox) { |
| + b.dir(t, filepath.Join(cgroup.SuperviseLeaf, "hide"), true) |
| + }, "supervise/hide runs under the agent's own leaf"}, |
| + {"processes in the subtree's root (no delegated layout)", func(t *testing.T, b *railBox) { |
| + b.procs(t, "", "4242\n4243\n") |
| + }, "processes run in the agent's cgroup /carlos.slice/carlos-edge.service outside its own leaf"}, |
| + {"the agent not running: no subtree to read", func(t *testing.T, b *railBox) { |
| + b.dir(t, cgroup.ExecName("flat.example.com"), true) // stale, never read |
| + b.units.services[0] = railBlock(agentUnit, "inactive", "carlos", "no", "") |
| + }, ""}, |
| + {"the agent's subtree gone between systemd's answer and the read", func(t *testing.T, b *railBox) { |
| + b.units.services[0] = railBlock(agentUnit, "active", "carlos", "no", "/carlos.slice/gone.service") |
| + }, ""}, |
| + {"an agent ControlGroup that leaves cgroupfs", func(t *testing.T, b *railBox) { |
| + b.units.services[0] = railBlock(agentUnit, "active", "carlos", "no", "/../etc") |
| + }, "the agent's cgroup could not be read"}, |
| + {"a tenant service running as the agent's user", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, railBlock("shop-worker.service", "active", "carlos", "no", "/x")) |
| + }, "shop-worker.service is running as the agent's user"}, |
| + {"one starting as the agent's uid", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, railBlock("shop-worker.service", "activating", "1001", "no", "/x")) |
| + }, "shop-worker.service is running as the agent's user"}, |
| + {"one under DynamicUser naming the agent's user", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, railBlock("shop-worker.service", "reloading", "alias", "yes", "/x")) |
| + }, "shop-worker.service is running as the agent's user"}, |
| + {"one in a state this check does not know", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, railBlock("shop-worker.service", "maintenance", "carlos", "no", "/x")) |
| + }, "shop-worker.service is running as the agent's user"}, |
| + {"one stopped or failed", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, railBlock("a.service", "failed", "carlos", "no", "")) |
| + }, ""}, |
| + {"a running service whose user cannot be read", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, railBlock("odd.service", "active", "broken", "no", "/x")) |
| + }, "odd.service is running, and its user could not be read"}, |
| + {"a name that only looks like a platform unit", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, railBlock("carlos-edge-helper.service", "active", "carlos", "no", "/x")) |
| + }, "carlos-edge-helper.service is running as the agent's user"}, |
| + {"the unit table cannot be read", func(t *testing.T, b *railBox) { b.units.failAll = true }, |
| + "the box's running services could not be read"}, |
| + {"a unit table answer missing a property", func(t *testing.T, b *railBox) { |
| + b.units.services = append(b.units.services, "Id=x.service\nActiveState=active") |
| + }, "the box's running services could not be read: systemctl show printed a unit without User"}, |
| + {"a group-writable registry", func(t *testing.T, b *railBox) { |
| + railChmod(t, filepath.Join(b.data, "registry.db"), 0o660) |
| + }, "registry.db is writable by users other than the agent (mode 0660)"}, |
| + {"a world-writable journal file", func(t *testing.T, b *railBox) { |
| + railWriteFile(t, filepath.Join(b.data, "registry.db-wal"), 0o666) |
| + }, "registry.db-wal is writable by users other than the agent (mode 0666)"}, |
| + {"a group-writable data dir", func(t *testing.T, b *railBox) { |
| + railChmod(t, b.data, 0o770) |
| + }, "is writable by users other than the agent (mode 0770)"}, |
| + {"no registry to read", func(t *testing.T, b *railBox) { |
| + if err := os.Remove(filepath.Join(b.data, "registry.db")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "the registry's permissions could not be read"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + t.Parallel() |
| + b := newRailBox(t) |
| + tc.change(t, b) |
| + ok, reason := b.check() |
| + if tc.reason == "" { |
| + if !ok { |
| + t.Fatalf("not wholly nested: %s", reason) |
| + } |
| + return |
| + } |
| + if ok || !strings.Contains(reason, tc.reason) { |
| + t.Fatalf("ok %v, reason %q; want refused with %q", ok, reason, tc.reason) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func railChmod(t *testing.T, p string, mode os.FileMode) { |
| + t.Helper() |
| + if err := os.Chmod(p, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func railWriteFile(t *testing.T, p string, mode os.FileMode) { |
| + t.Helper() |
| + if err := os.WriteFile(p, nil, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + railChmod(t, p, mode) |
| +} |
| + |
| +func TestEgressPlatformService(t *testing.T) { |
| + t.Parallel() |
| + for name, want := range map[string]bool{ |
| + "carlos-edge.service": true, |
| + "carlos-litestream.service": true, |
| + "carlos-instance@shop-a.example.com.service": true, |
| + "carlos-instance-gen@shop-a.example.com-1.service": true, |
| + "carlos-instance-sidecar@x.service": true, |
| + "carlos-instance-probe.service": true, |
| + "carlos-instance@.service": false, // the template itself never runs |
| + "carlos-edge-helper.service": false, |
| + "xcarlos-instance@a.service": false, |
| + "carlos-instance@a.socket": false, |
| + "shop-worker.service": false, |
| + } { |
| + if got := platformService(name); got != want { |
| + t.Errorf("platformService(%q) = %v, want %v", name, got, want) |
| + } |
| + } |
| +} |
| + |
| +// TestRegistryEgressSourceFlatProcessWithoutARow is the finding's case: the |
| +// flat tenant removed its own row, so every row left is nested and the |
| +// nested host carries an allow, but its process still runs in a |
| +// carlos-exec@ cgroup under the agent. The allow is closed, and opens once |
| +// the process is gone. Then a tenant unit running as the agent's user, |
| +// with no row at all, closes it the same way. |
| +func TestRegistryEgressSourceFlatProcessWithoutARow(t *testing.T) { |
| + t.Parallel() |
| + b := newRailBox(t) |
| + reg, err := registry.Open(filepath.Join(b.data, "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)} |
| + upsertRows(t, reg, nestedRow(b.data, "shop-a.example.com"), flatRow(b.data, "flat.example.com")) |
| + setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour))) |
| + if err := reg.Delete("flat.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + privateRegistryFiles(t, reg.Path()) |
| + b.dir(t, cgroup.ExecName("flat.example.com"), true) |
| + rs := testRegistrySource(t, b.data, clock.Now, b.units) |
| + rs.cgroupRoot = b.cgroup |
| + src := rs.read |
| + |
| + got := readPolicy(t, src, "shop-a.example.com") |
| + if got.Closed != instancectl.EgressNotNested || len(got.Allow) != 0 || !strings.Contains(got.Detail, "carlos-exec@flat.example.com runs in the agent's cgroup") { |
| + t.Fatalf("a running flat process with no row: %+v, want closed %q naming its cgroup", got, instancectl.EgressNotNested) |
| + } |
| + |
| + b.dir(t, cgroup.ExecName("flat.example.com"), false) // it exited |
| + wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}}) |
| + |
| + b.units.mu.Lock() |
| + b.units.services = append(b.units.services, railBlock("shop-worker.service", "active", "carlos", "no", "/system.slice/shop-worker.service")) |
| + b.units.mu.Unlock() |
| + got = readPolicy(t, src, "shop-a.example.com") |
| + if got.Closed != instancectl.EgressNotNested || !strings.Contains(got.Detail, "shop-worker.service is running as the agent's user") { |
| + t.Fatalf("a tenant unit of the agent's user with no row: %+v", got) |
| + } |
| +} |
diff --git a/internal/host/egress_rail_other.go b/internal/host/egress_rail_other.go| new file mode 100644 |
| index 000000000..b90cdfb57 |
| --- /dev/null |
| +++ b/internal/host/egress_rail_other.go |
| @@ -0,0 +1,11 @@ |
| +//go:build !linux |
| + |
| +package host |
| + |
| +import "errors" |
| + |
| +// agentSubtreeOthers reads cgroupfs, which only linux has; root's control |
| +// service runs on linux alone, so elsewhere the rail fails closed. |
| +func agentSubtreeOthers(string, string) (string, error) { |
| + return "", errors.New("the agent's cgroup is a linux cgroup feature") |
| +} |
diff --git a/internal/host/egress_rail_rootrunner_linux_test.go b/internal/host/egress_rail_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..7af56e939 |
| --- /dev/null |
| +++ b/internal/host/egress_rail_rootrunner_linux_test.go |
| @@ -0,0 +1,242 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// Final review F2 (#328): the wholly-nested rail decides from root's own |
| +// evidence, so a flat process that removed its registry row is still |
| +// seen. Fixtures are in egress_fixtures_rootrunner_linux_test.go. |
| + |
| +// The stand-in agent: this test binary as /opt/carlos/carlos, run by |
| +// systemd in a carlos-edge.service unit (User=carlos, Delegate=), does the |
| +// agent's delegation dance (cgroup.Setup: the agent moves to its supervise |
| +// leaf), then starts one flat child, of its own uid, and moves it into |
| +// carlos-exec@<host> in its delegated subtree, as the activator places a |
| +// flat exec child. Both then sleep until the unit is stopped. |
| +const ( |
| + egressFlatAgentArg = "egress-flat-agent" |
| + egressFlatChildArg = "egress-flat-child" |
| + egressFlatHost = "flat.example.com" |
| +) |
| + |
| +func init() { |
| + switch { |
| + case len(os.Args) == 3 && os.Args[1] == egressFlatAgentArg: |
| + os.Exit(egressFlatAgent(os.Args[2])) |
| + case len(os.Args) == 2 && os.Args[1] == egressFlatChildArg: |
| + for { |
| + time.Sleep(time.Hour) |
| + } |
| + } |
| +} |
| + |
| +func egressFlatAgent(host string) int { |
| + logf := func(f string, a ...any) { fmt.Fprintf(os.Stderr, f+"\n", a...) } |
| + m := cgroup.Setup(logf) |
| + if m == nil { |
| + logf("no delegated subtree") |
| + return 3 |
| + } |
| + dir := filepath.Join(m.Root(), cgroup.ExecName(host)) |
| + if err := os.Mkdir(dir, 0o755); err != nil { |
| + logf("%v", err) |
| + return 3 |
| + } |
| + child := &syscall.ProcAttr{Files: []uintptr{0, 1, 2}} |
| + pid, err := syscall.ForkExec(instancectl.SystemBinary, []string{instancectl.SystemBinary, egressFlatChildArg}, child) |
| + if err != nil { |
| + logf("start the flat child: %v", err) |
| + return 3 |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0o644); err != nil { |
| + logf("place the flat child: %v", err) |
| + return 3 |
| + } |
| + logf("flat child %d runs in %s", pid, dir) |
| + for { |
| + time.Sleep(time.Hour) |
| + } |
| +} |
| + |
| +// egressStandInAgent installs and starts carlos-edge.service running the |
| +// stand-in agent for host, and returns the flat child's cgroup. The unit |
| +// and its file are removed in t.Cleanup; the unit's cgroup subtree goes |
| +// with it. |
| +func egressStandInAgent(t *testing.T, host string) string { |
| + t.Helper() |
| + path := filepath.Join("/run/systemd/system", agentUnit) |
| + if state := egressShow(t, agentUnit, "LoadState"); state != "not-found" { |
| + t.Fatal("unit already present", agentUnit, state) |
| + } |
| + if _, err := os.Lstat(filepath.Join("/etc/systemd/system", agentUnit)); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatal("unit file already installed", agentUnit, err) |
| + } |
| + body := "[Unit]\nDescription=carlos egress witness agent stand-in\n\n[Service]\n" + |
| + "User=" + serviceUser + "\nGroup=" + serviceUser + "\n" + |
| + "Slice=carlos.slice\nDelegate=cpu memory io pids\n" + |
| + "ExecStart=" + instancectl.SystemBinary + " " + egressFlatAgentArg + " " + host + "\n" |
| + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, werr := f.WriteString(body) |
| + if err := errors.Join(werr, f.Close()); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + if out, _ := egressCtl("show", "-p", "LoadState", "--value", agentUnit); out != "not-found" { |
| + if out, err := egressCtl("stop", agentUnit); err != nil { |
| + t.Errorf("stop %s: %v: %s", agentUnit, err, out) |
| + } |
| + } |
| + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + t.Error(err) |
| + } |
| + if out, err := egressCtl("daemon-reload"); err != nil { |
| + t.Errorf("daemon-reload: %v: %s", err, out) |
| + } |
| + egressCtl("reset-failed", agentUnit) |
| + }) |
| + egressMustCtl(t, "daemon-reload") |
| + if out, err := egressCtl("start", agentUnit); err != nil { |
| + t.Fatalf("start %s: %v: %s\n%s", agentUnit, err, out, egressJournal(agentUnit)) |
| + } |
| + cg := egressShow(t, agentUnit, "ControlGroup") |
| + root := filepath.Join("/sys/fs/cgroup", strings.TrimPrefix(cg, "/")) |
| + flat := filepath.Join(root, cgroup.ExecName(host)) |
| + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| + if ev, err := os.ReadFile(filepath.Join(flat, "cgroup.events")); err == nil && slices.Contains(strings.Split(string(ev), "\n"), "populated 1") { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the stand-in agent's flat child is not running in %s\n%s", flat, egressJournal(agentUnit)) |
| + } |
| + } |
| + // The agent is in its own leaf, and nothing else of the subtree runs |
| + // but the flat child. |
| + if procs, err := os.ReadFile(filepath.Join(root, cgroup.SuperviseLeaf, "cgroup.procs")); err != nil || strings.TrimSpace(string(procs)) != egressShow(t, agentUnit, "MainPID") { |
| + t.Fatalf("the agent's leaf holds %q (%v), want only its MainPID", procs, err) |
| + } |
| + return flat |
| +} |
| + |
| +// TestRootEgressFlatProcessFalsifiedRow is final review F2's witness, |
| +// through real systemd, real cgroup delegation and the production |
| +// pre-claim asserter. The run unit serves with 10.0.5.20 allowed. A flat |
| +// tenant is registered, starts running (in carlos-exec@flat.example.com |
| +// under a carlos-edge.service of User=carlos with Delegate=), and then |
| +// falsifies the registry as the agent's user can: it deletes its own row |
| +// and gives the nested host a wider allow with a future expiry. Every row |
| +// left is nested, so the rows alone would pass. POST /egress must leave |
| +// the slice holding nothing, close 10.0.5.20 for the running unit, and |
| +// report not_nested naming the flat child's cgroup. Once the flat process |
| +// has exited, the next POST /egress grants again. |
| +func TestRootEgressFlatProcessFalsifiedRow(t *testing.T) { |
| + b := newEgressPreClaimBox(t) |
| + ctx := t.Context() |
| + target := b.targets["10.0.5.20"] |
| + run := instancectl.UnitName(instancectl.RoleRun, b.host) |
| + c := b.startRun(t) |
| + b.wantAllowed(t, "start") |
| + if !egressReach(t, c, target) { |
| + t.Fatal("start: the tenant cannot reach 10.0.5.20") |
| + } |
| + |
| + // The flat tenant: registered, running, then its row gone and the |
| + // nested host's allow widened by its hand. |
| + if err := b.reg.Upsert(registry.Route{Host: egressFlatHost, Kind: "instance", Account: "abc", App: "shop-b", Channel: "stable", Hibernate: true, Status: "ready", |
| + DBPath: provision.DefaultDBPath("/data", egressFlatHost), Socket: provision.DefaultSocket(egressFlatHost)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + flat := egressStandInAgent(t, egressFlatHost) |
| + if err := b.reg.Delete(egressFlatHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.reg.SetPolicy(b.host, "10.0.5.20 10.0.5.21", "", egressExpiry()); err != nil { |
| + t.Fatal(err) |
| + } |
| + rows, err := b.reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, reason := boxWhollyNested(rows, "/data", func(string) (bool, error) { return false, nil }); !ok { |
| + t.Fatalf("fixture: the rows alone already refuse (%s); the witness needs a falsified registry", reason) |
| + } |
| + |
| + before := b.runInvocation(t) |
| + if err := b.client.Egress(ctx, b.host); err != nil { |
| + t.Fatal("POST /egress:", err) |
| + } |
| + // No parent allow: the reset to empty restarts the run unit. |
| + deadline := egressRevokeDeadline(true) |
| + if got := b.allow(t); got != "" { |
| + t.Fatalf("falsified registry: slice holds %q, want nothing", got) |
| + } |
| + if after := b.runInvocation(t); after == before { |
| + t.Fatalf("falsified registry: the run unit kept invocation %s", before) |
| + } |
| + egressServingBy(t, run, c, deadline) |
| + for _, a := range []string{"10.0.5.20", "10.0.5.21"} { |
| + if !egressWithin(t, deadline, c, false, b.targets[a]) { |
| + egressFirewallDiag(t, run, b.slice, c, b.targets[a]) |
| + t.Fatalf("falsified registry: %s reachable at the revoke's deadline", a) |
| + } |
| + } |
| + rep := b.report(t) |
| + want := cgroup.ExecName(egressFlatHost) + " runs in the agent's cgroup" |
| + if rep.State != instancectl.EgressNotNested || len(rep.Allowed) != 0 || !strings.Contains(rep.Detail, want) { |
| + t.Fatalf("falsified registry: GET /egress = %+v, want not_nested with %q and nothing allowed", rep, want) |
| + } |
| + |
| + // The flat process exits: nothing of the agent's user runs outside the |
| + // agent's leaf, and the allow is granted again. |
| + procs, err := os.ReadFile(filepath.Join(flat, "cgroup.procs")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, f := range strings.Fields(string(procs)) { |
| + pid, err := strconv.Atoi(f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := syscall.Kill(pid, syscall.SIGKILL); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| + if ev, err := os.ReadFile(filepath.Join(flat, "cgroup.events")); err == nil && slices.Contains(strings.Split(string(ev), "\n"), "populated 0") { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("the flat child did not exit") |
| + } |
| + } |
| + if err := b.reg.SetPolicy(b.host, "10.0.5.20", "", egressExpiry()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.client.Egress(ctx, b.host); err != nil { |
| + t.Fatal("POST /egress after the flat process exited:", err) |
| + } |
| + b.wantAllowed(t, "after the flat process exited") |
| + if !egressWithin(t, time.Now().Add(egressLiveBound), c, true, target) { |
| + t.Fatal("after the flat process exited: 10.0.5.20 not reachable 2 s after POST /egress") |
| + } |
| +} |
diff --git a/internal/host/egress_source.go b/internal/host/egress_source.go| index efc378d5a..6ff7e168d 100644 |
| --- a/internal/host/egress_source.go |
| +++ b/internal/host/egress_source.go |
| @@ -8,7 +8,10 @@ package host |
| // same registry decides which build a nested generation runs |
| // (instanceRegistryHostApp). One extra rail: a box where a process may run |
| // as the agent's user, and so may be able to write registry.db, gets no |
| -// allow at all. |
| +// allow at all. The rail decides from what root can trust (railEvidence: |
| +// systemd's unit table, the agent's cgroup subtree, the registry's |
| +// permissions), since a flat tenant can rewrite the rows (final review F2), |
| +// and the rows (boxWhollyNested) can only refuse further. |
| import ( |
| "context" |
| @@ -36,7 +39,10 @@ import ( |
| // |
| // The rail is for one thing (plan 2 ruling on Task 5): a process running |
| // as the agent's user may be able to write registry.db, the file this |
| -// source trusts. So a row counts against the box when it is |
| +// source trusts. The rows are that file's own records, which such a |
| +// process can rewrite, so this check can only refuse; what decides is |
| +// root's own evidence (railEvidence, final review F2), which the source |
| +// asks after the rows pass. A row counts against the box when it is |
| // - a sidecar member (it runs flat, as the agent's user); |
| // - an activator-managed exec child that is not nested (flat, fenced, |
| // foreign or conflict: the activator spawns it as the agent's user); |
| @@ -118,15 +124,17 @@ func registryEgressSource(dataDir string, now func() time.Time) instancectl.Egre |
| return newRegistrySource(dataDir, now, func() ([]registry.Route, error) { return listRegistryReadOnly(path) }, systemctlOutput).read |
| } |
| -// registrySource is registryEgressSource's state. list, systemctl and |
| -// lookupUID are seams: production's read the registry read-only, run |
| -// systemctl and read the user database. |
| +// registrySource is registryEgressSource's state. list, systemctl, |
| +// lookupUID and cgroupRoot are seams: production's read the registry |
| +// read-only, run systemctl, read the user database and read cgroupfs at |
| +// /sys/fs/cgroup. |
| type registrySource struct { |
| - dataDir string |
| - now func() time.Time |
| - list func() ([]registry.Route, error) |
| - systemctl func(ctx context.Context, args ...string) (string, error) |
| - lookupUID func(name string) (uid string, found bool, err error) |
| + dataDir string |
| + now func() time.Time |
| + list func() ([]registry.Route, error) |
| + systemctl func(ctx context.Context, args ...string) (string, error) |
| + lookupUID func(name string) (uid string, found bool, err error) |
| + cgroupRoot string |
| mu sync.Mutex |
| allowedUntil map[string]time.Time // host -> the expiry its last allow was read under |
| @@ -151,7 +159,8 @@ type egressSnapshot struct { |
| } |
| func newRegistrySource(dataDir string, now func() time.Time, list func() ([]registry.Route, error), systemctl func(context.Context, ...string) (string, error)) *registrySource { |
| - return ®istrySource{dataDir: dataDir, now: now, list: list, systemctl: systemctl, lookupUID: userUID, allowedUntil: map[string]time.Time{}} |
| + return ®istrySource{dataDir: dataDir, now: now, list: list, systemctl: systemctl, lookupUID: userUID, cgroupRoot: "/sys/fs/cgroup", |
| + allowedUntil: map[string]time.Time{}} |
| } |
| // snapshot is the read to answer from. Outside a sweep it reads afresh. In |
| @@ -224,9 +233,14 @@ func (s *registrySource) policyFrom(ctx context.Context, snap *egressSnapshot, h |
| } |
| snap.railMu.Lock() |
| if !snap.railDone { |
| + // The rows first (their reasons name a host), then root's own |
| + // evidence, which a tenant cannot rewrite: either refuses. |
| snap.nested, snap.reason = boxWhollyNested(snap.rows, s.dataDir, func(unit string) (bool, error) { |
| return unitRunsAsAgent(ctx, s.systemctl, s.lookupUID, unit) |
| }) |
| + if snap.nested { |
| + snap.nested, snap.reason = railEvidence{cgroupRoot: s.cgroupRoot, dataDir: s.dataDir, systemctl: s.systemctl, lookupUID: s.lookupUID}.check(ctx) |
| + } |
| snap.railDone = true |
| } |
| nested, reason := snap.nested, snap.reason |
| @@ -284,6 +298,13 @@ func unitRunsAsAgent(ctx context.Context, systemctl func(context.Context, ...str |
| if !sawUser || !sawDynamic { |
| return false, fmt.Errorf("systemctl show answered %q", strings.TrimSpace(out)) |
| } |
| + return userIsAgent(unitUser, dynamic, lookup) |
| +} |
| + |
| +// userIsAgent decides unitRunsAsAgent's question from a unit's User and |
| +// DynamicUser as systemctl show prints them; the rail's batched read of |
| +// every running service (railEvidence) asks it too. |
| +func userIsAgent(unitUser, dynamic string, lookup func(string) (string, bool, error)) (bool, error) { |
| if dynamic != "yes" && dynamic != "no" { |
| return false, fmt.Errorf("DynamicUser is %q", dynamic) |
| } |
diff --git a/internal/host/egress_source_sweep_linux_test.go b/internal/host/egress_source_sweep_linux_test.go| index 082ccc6d6..e3587c0bc 100644 |
| --- a/internal/host/egress_source_sweep_linux_test.go |
| +++ b/internal/host/egress_source_sweep_linux_test.go |
| @@ -101,6 +101,7 @@ func TestRegistryEgressSourceReadsOncePerSweep(t *testing.T) { |
| return listRegistryReadOnly(path) |
| }, units.run) |
| rs.lookupUID = fakeUsers |
| + rs.cgroupRoot = t.TempDir() |
| src := rs.read |
| ctl := &sliceCtl{allow: map[string]string{}} |
| e := &instancectl.EgressAsserter{ |
| @@ -116,8 +117,10 @@ func TestRegistryEgressSourceReadsOncePerSweep(t *testing.T) { |
| if n := reads.Load(); n != 1 { |
| t.Fatalf("one sweep over %d hosts read the registry %d times, want 1", len(hosts), n) |
| } |
| - if n := len(units.calls); n != 1 { |
| - t.Fatalf("one sweep read the console unit's user %d times, want 1", n) |
| + // One read of the named unit's user and one batched read of the |
| + // box's services (the rail's evidence, final review F2) per sweep. |
| + if n := len(units.calls); n != 2 || units.calls[1] != strings.Join(railShowArgs, " ") { |
| + t.Fatalf("one sweep asked systemctl %q, want the console unit's user, then the box's services, once each", units.calls) |
| } |
| reps := e.Reports() |
| for _, h := range hosts { |
| @@ -159,7 +162,7 @@ func TestRegistryEgressSweepCannotReopenARevoke(t *testing.T) { |
| setAllow(t, reg, h, "10.0.5.20", unixText(clock.Now().Add(time.Hour))) |
| populatedHostCgroup(t, cgroup, h) |
| } |
| - src := registryEgressSource(dd, clock.Now) |
| + src := testEgressSource(t, dd, clock.Now) |
| ctl := &sliceCtl{allow: map[string]string{}, paused: make(chan struct{}), resume: make(chan struct{})} |
| e := &instancectl.EgressAsserter{ |
| Systemctl: ctl.run, |
diff --git a/internal/host/egress_source_test.go b/internal/host/egress_source_test.go| index 43be75b13..b940f50d8 100644 |
| --- a/internal/host/egress_source_test.go |
| +++ b/internal/host/egress_source_test.go |
| @@ -129,12 +129,49 @@ func TestBoxWhollyNestedTable(t *testing.T) { |
| // egressRegistry is a temp registry in its own data dir (the package's |
| // testRegistry: <dataDir>/registry.db) holding rows, with policy columns |
| // set by SetPolicy, the agent's writer. |
| +// |
| +// Its files are made 0640 and its directory 0750, as a fresh bootstrap |
| +// makes them, so the rail's permission check (railEvidence) passes |
| +// whatever the umask. |
| func egressRegistry(t *testing.T) (*registry.Registry, string) { |
| t.Helper() |
| reg := testRegistry(t) |
| + privateRegistryFiles(t, reg.Path()) |
| return reg, filepath.Dir(reg.Path()) |
| } |
| +// privateRegistryFiles makes registry.db and its journal files 0640 and |
| +// their directory 0750, as bootstrap makes /data. |
| +func privateRegistryFiles(t *testing.T, path string) { |
| + t.Helper() |
| + if err := os.Chmod(filepath.Dir(path), 0o750); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range []string{path, path + "-wal", path + "-shm", path + "-journal"} { |
| + if err := os.Chmod(p, 0o640); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// testEgressSource is registryEgressSource as the unit tests run it: the |
| +// production registry read, behind the rail with its systemd and user |
| +// database answered by a fakeUnitShow (no running service) and fakeUsers, |
| +// and an empty cgroup tree, so no test reads the box's own systemd. |
| +func testEgressSource(t *testing.T, dataDir string, now func() time.Time) instancectl.EgressSource { |
| + t.Helper() |
| + return testRegistrySource(t, dataDir, now, &fakeUnitShow{units: map[string]string{}}).read |
| +} |
| + |
| +func testRegistrySource(t *testing.T, dataDir string, now func() time.Time, units *fakeUnitShow) *registrySource { |
| + t.Helper() |
| + path := filepath.Join(dataDir, "registry.db") |
| + rs := newRegistrySource(dataDir, now, func() ([]registry.Route, error) { return listRegistryReadOnly(path) }, units.run) |
| + rs.lookupUID = fakeUsers |
| + rs.cgroupRoot = t.TempDir() |
| + return rs |
| +} |
| + |
| func upsertRows(t *testing.T, reg *registry.Registry, rows ...registry.Route) { |
| t.Helper() |
| for _, rt := range rows { |
| @@ -184,7 +221,7 @@ func TestRegistryEgressSourceReadsTheColumn(t *testing.T) { |
| clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)} |
| upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"), nestedRow(dd, "shop-b.example.com")) |
| setAllow(t, reg, "shop-a.example.com", "10.0.5.20 fd00:5::20", unixText(clock.Now().Add(time.Hour))) |
| - src := registryEgressSource(dd, clock.Now) |
| + src := testEgressSource(t, dd, clock.Now) |
| wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20", "fd00:5::20"}}) |
| // A row with no policy, and a host with no row: no allow, and nothing to say. |
| @@ -198,7 +235,7 @@ func TestRegistryEgressSourceClosesOnAMixedBox(t *testing.T) { |
| clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)} |
| upsertRows(t, reg, nestedRow(dd, "shop-a.example.com")) |
| setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour))) |
| - src := registryEgressSource(dd, clock.Now) |
| + src := testEgressSource(t, dd, clock.Now) |
| wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}}) |
| upsertRows(t, reg, flatRow(dd, "old.example.com")) |
| @@ -267,7 +304,7 @@ func TestRegistryEgressSourceWritesNothing(t *testing.T) { |
| } |
| upsertRows(t, reg, nestedRow(dd, "shop-a.example.com")) |
| setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour))) |
| - src := registryEgressSource(dd, clock.Now) |
| + src := testEgressSource(t, dd, clock.Now) |
| check := func(phase string, call func()) { |
| t.Helper() |
| @@ -313,7 +350,7 @@ func TestRegistryEgressSourceClosesAtTheRecordedExpiry(t *testing.T) { |
| clock := &testClock{now: t0} |
| upsertRows(t, reg, nestedRow(dd, "shop-a.example.com")) |
| setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(exp)) |
| - src := registryEgressSource(dd, clock.Now) |
| + src := testEgressSource(t, dd, clock.Now) |
| allow := instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}} |
| expired := instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: "the policy expired at 2026-10-25T10:00:00Z"} |
| noExpiry := instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: "no expiry recorded"} |
| @@ -338,13 +375,13 @@ func TestRegistryEgressSourceClosesAtTheRecordedExpiry(t *testing.T) { |
| // control service, with the clock past: expired. |
| setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(exp)) |
| clock.Set(exp.Add(time.Minute)) |
| - wantPolicy(t, readPolicy(t, registryEgressSource(dd, clock.Now), "shop-a.example.com"), expired) |
| + wantPolicy(t, readPolicy(t, testEgressSource(t, dd, clock.Now), "shop-a.example.com"), expired) |
| // An allowed read, then the registry cannot be read: an error (the |
| // asserter keeps the last allow) only until the expiry it was read |
| // under, then expired, never the error. |
| clock.Set(t0) |
| - src = registryEgressSource(dd, clock.Now) |
| + src = testEgressSource(t, dd, clock.Now) |
| wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), allow) |
| if err := os.Rename(reg.Path(), reg.Path()+".away"); err != nil { |
| t.Fatal(err) |
| @@ -450,7 +487,7 @@ func TestPreClaimAllowClosesWhenAStoreOutageOutlastsTheRecord(t *testing.T) { |
| if want := unixText(signedAt.Add(apppolicy.Lifetime)); rt.EgressAllow != "10.0.5.20" || rt.PolicyExpiresAt != want { |
| t.Fatalf("converged row: egress %q expires %q, want %q %q", rt.EgressAllow, rt.PolicyExpiresAt, "10.0.5.20", want) |
| } |
| - src := registryEgressSource(dd, clock.Now) |
| + src := testEgressSource(t, dd, clock.Now) |
| wantPolicy(t, readPolicy(t, src, host), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}}) |
| // The outage: the agent's passes keep the row while its expiry is ahead. |
| @@ -464,7 +501,7 @@ func TestPreClaimAllowClosesWhenAStoreOutageOutlastsTheRecord(t *testing.T) { |
| wantExpired := instancectl.EgressPolicy{Closed: instancectl.EgressExpired, |
| Detail: "the policy expired at " + signedAt.Add(apppolicy.Lifetime).UTC().Format(time.RFC3339)} |
| wantPolicy(t, readPolicy(t, src, host), wantExpired) |
| - wantPolicy(t, readPolicy(t, registryEgressSource(dd, clock.Now), host), wantExpired) |
| + wantPolicy(t, readPolicy(t, testEgressSource(t, dd, clock.Now), host), wantExpired) |
| // When the agent does run, it clears the row: still no allow. |
| reconcile() |
| @@ -489,12 +526,16 @@ func TestRegistryEgressHostsListsTheRows(t *testing.T) { |
| } |
| } |
| -// fakeUnitShow answers `systemctl show -p User -p DynamicUser <unit>` from |
| +// fakeUnitShow answers the rail's batched show (railShowArgs) with |
| +// services, the units running on the box, and `systemctl show -p User -p |
| +// DynamicUser <unit>` from |
| // a table the test changes, and counts every call. |
| type fakeUnitShow struct { |
| - mu sync.Mutex |
| - units map[string]string // unit -> systemctl show's output; missing: an error |
| - calls []string |
| + mu sync.Mutex |
| + units map[string]string // unit -> systemctl show's output; missing: an error |
| + services []string // the batched show's blocks, in order |
| + failAll bool // the batched show fails |
| + calls []string |
| } |
| func (f *fakeUnitShow) set(unit, out string) { f.mu.Lock(); f.units[unit] = out; f.mu.Unlock() } |
| @@ -503,6 +544,12 @@ func (f *fakeUnitShow) run(_ context.Context, args ...string) (string, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.calls = append(f.calls, strings.Join(args, " ")) |
| + if slices.Equal(args, railShowArgs) { |
| + if f.failAll { |
| + return "Failed to connect to bus: No such file or directory\n", errors.New("exit status 1") |
| + } |
| + return strings.Join(f.services, "\n\n"), nil |
| + } |
| if len(args) != 6 || args[0] != "show" || args[1] != "-p" || args[2] != "User" || args[3] != "-p" || args[4] != "DynamicUser" { |
| return "", errors.New("unexpected systemctl call") |
| } |
| @@ -603,10 +650,7 @@ func TestRegistryEgressSourceUnitRows(t *testing.T) { |
| "carlos-app@app.example.com.service": "User=\nDynamicUser=yes\n", |
| "console.service": "User=console\nDynamicUser=no\n", |
| }} |
| - path := reg.Path() |
| - rs := newRegistrySource(dd, clock.Now, func() ([]registry.Route, error) { return listRegistryReadOnly(path) }, f.run) |
| - rs.lookupUID = fakeUsers |
| - src := rs.read |
| + src := testRegistrySource(t, dd, clock.Now, f).read |
| // A carlos-app@ tenant and a console unit run as another user: the allow. |
| wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}}) |