carlos / platform Public

host: narrow the nested rail to agent-user processes; one registry read per sweep (#328)

Controller rulings on Task 5: a row counts against the box only when a
process of the agent's user may run for it (a sidecar member, a
non-nested activator exec child, or a named unit whose User is the
agent's with DynamicUser=no, read with systemctl show; unreadable counts),
plus unknown kinds and backings. carlos-app@, tunnel, addr-only, static
and service rows no longer block. The source reads the registry once per
sweep (instancectl.EgressSweep marks a sweep's Asserts) and afresh for
any other Assert.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d742633a4faa8241921853b5e606d39b7956e19f parent 3154db4
5 files changed, +488 −65
  • internal/host/egress_source.go +182 −60
  • internal/host/egress_source_sweep_linux_test.go +114 −0
  • internal/host/egress_source_test.go +143 −5
  • internal/instancectl/egress.go +17 −0
  • internal/instancectl/egress_sweep_linux_test.go +32 −0
diff --git a/internal/host/egress_source.go b/internal/host/egress_source.go
index 952ef2794..3acf38d96 100644
--- a/internal/host/egress_source.go
+++ b/internal/host/egress_source.go
@@ -6,14 +6,17 @@ package host
// those columns from the registry, read-only, to assert each host slice's
// IPAddressAllow. This adds no trust the agent does not already hold: the
// same registry decides which build a nested generation runs
-// (instanceRegistryHostApp). One extra rail: a box that is not wholly
-// nested gets no allow at all.
+// (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.
import (
"context"
+ "errors"
"fmt"
"log"
"os/exec"
+ "os/user"
"path/filepath"
"strconv"
"strings"
@@ -31,29 +34,46 @@ import (
// activator.ActivatorManaged row classifies LayoutNested under Classify with
// the layout journal; reason names the first row that fails.
//
-// The rail exists because a flat exec child runs as the agent's user and
-// may be able to write registry.db, the file this source trusts. So it
-// fails closed (ruling C14): a row counts only when it is a shape this
-// check knows. Known and harmless: an activator-managed row in the nested
-// layout (a rootfs app's row is one of these; it differs only in its
-// runtime, which this check never reads), an unflagged socket row (run by
-// another supervisor, nobody's to migrate or isolate, design §8.2 step 1)
-// and a static row (it runs no process). Every other row, including
-// unit-backed, tunnel-served and addr-only instance rows, service rows and
-// any kind this code does not know, makes the box not wholly nested.
-func boxWhollyNested(rows []registry.Route, dataDir string) (ok bool, reason string) {
+// 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
+// - 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);
+// - backed by a named systemd unit (Route.Unit) that unitAsAgent says
+// runs as the agent's user, or whose user it cannot read; or
+// - a kind or backing this code does not know (fail closed, ruling C14).
+//
+// Rows with no local process of the agent's user do not count: carlos-app@
+// unit tenants (DynamicUser), tunnel-served, addr-only, unflagged socket
+// rows run by another supervisor, static rows, and service rows (each
+// still subject to the named-unit check). A rootfs app's row is an
+// ordinary managed nested row; this check never reads Route.Runtime.
+func boxWhollyNested(rows []registry.Route, dataDir string, unitAsAgent func(unit string) (bool, error)) (ok bool, reason string) {
in := activator.LayoutInputs{
DataDir: dataDir,
Journal: func(host string) bool { return layout.JournalPresent(dataDir, host) },
}
for _, rt := range rows {
- switch {
- case rt.IsSidecar():
+ if rt.IsSidecar() {
return false, rt.Host + " is a sidecar member, which runs flat"
- case rt.Kind == "static":
+ }
+ if rt.Unit != "" {
+ asAgent, err := unitAsAgent(rt.Unit)
+ if err != nil {
+ return false, fmt.Sprintf("%s runs as %s, whose user could not be read: %v", rt.Host, rt.Unit, err)
+ }
+ if asAgent {
+ return false, fmt.Sprintf("%s runs as %s, which runs as the agent's user", rt.Host, rt.Unit)
+ }
+ }
+ switch {
+ case rt.Backing != "" && rt.Backing != registry.BackingUnit:
+ return false, fmt.Sprintf("%s has backing %q, which this check does not know", rt.Host, rt.Backing)
+ case rt.Kind == "static" || rt.Kind == "service":
continue
case rt.Kind != "instance":
- return false, fmt.Sprintf("%s is a %q row, which this check does not count as nested", rt.Host, rt.Kind)
+ return false, fmt.Sprintf("%s is a %q row, which this check does not know", rt.Host, rt.Kind)
case activator.ActivatorManaged(rt):
l, why := activator.Classify(rt, in)
if l == activator.LayoutNested {
@@ -63,22 +83,25 @@ func boxWhollyNested(rows []registry.Route, dataDir string) (ok bool, reason str
return false, fmt.Sprintf("%s is %s: %s", rt.Host, l, why)
}
return false, fmt.Sprintf("%s is %s", rt.Host, l)
- case rt.Socket != "" && !rt.Hibernate && rt.Backing == "" && rt.Tunnel == "":
- continue
- default:
- return false, fmt.Sprintf("%s is an instance row the nested layout does not cover (backing %q, tunnel %q, addr %q)", rt.Host, rt.Backing, rt.Tunnel, rt.Addr)
}
+ // An instance row the activator does not spawn: a carlos-app@ unit,
+ // tunnel-served, addr-only, or an unflagged socket.
}
return true, ""
}
-// registryEgressSource is root's pre-claim EgressSource. Each call opens
-// the registry read-only, lists its rows once and answers from them: no
-// row for the host, or a row with no allow, is no policy; an allow on a
-// box that is not wholly nested is closed EgressNotNested; an allow whose
-// recorded expiry is missing, unreadable or not after now() is closed
-// EgressExpired (ruling C1); otherwise the column split on spaces. It
-// writes nothing: not to the registry, not to the layout tree.
+// registryEgressSource is root's pre-claim EgressSource. It answers from
+// a read of the registry (read-only): no row for the host, or a row with
+// no allow, is no policy; an allow on a box that is not wholly nested is
+// closed EgressNotNested; an allow whose recorded expiry is missing,
+// unreadable or not after now() is closed EgressExpired (ruling C1);
+// otherwise the column split on spaces. It writes nothing: not to the
+// registry, not to the layout tree.
+//
+// The asserter's sweep asks for every populated slice in turn: the source
+// reads the registry once per sweep (instancectl.EgressSweep) and answers
+// every host of that sweep, and the rail, from the one read. Any other
+// Assert (a start path, POST /egress) reads afresh.
//
// A registry that cannot be opened or listed is returned as an error, and
// the asserter keeps the last policy it read, but only until the expiry
@@ -87,47 +110,95 @@ func boxWhollyNested(rows []registry.Route, dataDir string) (ok bool, reason str
//
// The registry is a local file: no store read.
func registryEgressSource(dataDir string, now func() time.Time) instancectl.EgressSource {
- var mu sync.Mutex
- allowedUntil := map[string]time.Time{} // host -> the expiry its last allow was read under
path := filepath.Join(dataDir, "registry.db")
- return func(_ context.Context, host string) (instancectl.EgressPolicy, error) {
- rows, err := listRegistryReadOnly(path)
- if err != nil {
- mu.Lock()
- until, ok := allowedUntil[host]
- mu.Unlock()
- if ok && !until.After(now()) {
- return instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: expiredDetail(until)}, nil
- }
- return instancectl.EgressPolicy{}, err
+ return newRegistrySource(dataDir, now, func() ([]registry.Route, error) { return listRegistryReadOnly(path) }, systemctlOutput).read
+}
+
+// registrySource is registryEgressSource's state. list and systemctl are
+// seams: production's read the registry read-only and run systemctl.
+type registrySource struct {
+ dataDir string
+ now func() time.Time
+ list func() ([]registry.Route, error)
+ systemctl func(ctx context.Context, args ...string) (string, error)
+
+ mu sync.Mutex
+ allowedUntil map[string]time.Time // host -> the expiry its last allow was read under
+
+ sweepMu sync.Mutex
+ sweep *egressSnapshot // the latest sweep's read
+}
+
+// egressSnapshot is one read of the registry and, once asked, its rail.
+type egressSnapshot struct {
+ sweep uint64
+ rows []registry.Route
+ err error
+ railDone bool
+ nested bool
+ reason string
+}
+
+func newRegistrySource(dataDir string, now func() time.Time, list func() ([]registry.Route, error), systemctl func(context.Context, ...string) (string, error)) *registrySource {
+ return &registrySource{dataDir: dataDir, now: now, list: list, systemctl: systemctl, allowedUntil: map[string]time.Time{}}
+}
+
+func (s *registrySource) read(ctx context.Context, host string) (instancectl.EgressPolicy, error) {
+ var snap *egressSnapshot
+ if id, ok := instancectl.EgressSweep(ctx); ok {
+ s.sweepMu.Lock()
+ defer s.sweepMu.Unlock()
+ if s.sweep == nil || s.sweep.sweep != id {
+ rows, err := s.list()
+ s.sweep = &egressSnapshot{sweep: id, rows: rows, err: err}
}
- pol, until := egressPolicyFrom(rows, host, dataDir, now())
- mu.Lock()
- if until.IsZero() {
- delete(allowedUntil, host)
- } else {
- allowedUntil[host] = until
+ snap = s.sweep
+ } else {
+ rows, err := s.list()
+ snap = &egressSnapshot{rows: rows, err: err}
+ }
+ now := s.now()
+ if snap.err != nil {
+ s.mu.Lock()
+ until, ok := s.allowedUntil[host]
+ s.mu.Unlock()
+ if ok && !until.After(now) {
+ return instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: expiredDetail(until)}, nil
}
- mu.Unlock()
- return pol, nil
+ return instancectl.EgressPolicy{}, snap.err
+ }
+ pol, until := s.policyFrom(ctx, snap, host, now)
+ s.mu.Lock()
+ if until.IsZero() {
+ delete(s.allowedUntil, host)
+ } else {
+ s.allowedUntil[host] = until
}
+ s.mu.Unlock()
+ return pol, nil
}
-// egressPolicyFrom is host's policy from the box's rows at now, and, when
-// it is an allow, the expiry it holds until (zero otherwise).
-func egressPolicyFrom(rows []registry.Route, host, dataDir string, now time.Time) (instancectl.EgressPolicy, time.Time) {
+// policyFrom is host's policy from snap at now, and, when it is an allow,
+// the expiry it holds until (zero otherwise).
+func (s *registrySource) policyFrom(ctx context.Context, snap *egressSnapshot, host string, now time.Time) (instancectl.EgressPolicy, time.Time) {
var row *registry.Route
- for i := range rows {
- if rows[i].Host == host {
- row = &rows[i]
+ for i := range snap.rows {
+ if snap.rows[i].Host == host {
+ row = &snap.rows[i]
break
}
}
if row == nil || strings.TrimSpace(row.EgressAllow) == "" {
return instancectl.EgressPolicy{}, time.Time{}
}
- if ok, reason := boxWhollyNested(rows, dataDir); !ok {
- return instancectl.EgressPolicy{Closed: instancectl.EgressNotNested, Detail: reason}, time.Time{}
+ if !snap.railDone {
+ snap.nested, snap.reason = boxWhollyNested(snap.rows, s.dataDir, func(unit string) (bool, error) {
+ return unitRunsAsAgent(ctx, s.systemctl, unit)
+ })
+ snap.railDone = true
+ }
+ if !snap.nested {
+ return instancectl.EgressPolicy{Closed: instancectl.EgressNotNested, Detail: snap.reason}, time.Time{}
}
secs, err := strconv.ParseInt(row.PolicyExpiresAt, 10, 64)
if err != nil || secs <= 0 {
@@ -146,6 +217,60 @@ func expiredDetail(until time.Time) string {
return "the policy expired at " + until.UTC().Format(time.RFC3339)
}
+// unitRunsAsAgent reads a named unit's User and DynamicUser through
+// systemctl and reports whether it runs as the agent's user (serviceUser,
+// by name or uid) with DynamicUser=no. Anything it cannot read or does not
+// recognise is an error, which the rail counts against the box. The unit
+// name reaches systemctl only as one argument, and only when it is a
+// valid unit name.
+func unitRunsAsAgent(ctx context.Context, systemctl func(context.Context, ...string) (string, error), unit string) (bool, error) {
+ if unit == "" || !registry.ValidUnitName(unit) || strings.HasPrefix(unit, "-") {
+ return false, errors.New("not a unit name")
+ }
+ out, err := systemctl(ctx, "show", "-p", "User", "-p", "DynamicUser", unit)
+ if err != nil {
+ return false, fmt.Errorf("systemctl show: %s: %v", strings.TrimSpace(out), err)
+ }
+ var unitUser, dynamic string
+ var sawUser, sawDynamic bool
+ for _, line := range strings.Split(out, "\n") {
+ k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
+ switch {
+ case ok && k == "User":
+ unitUser, sawUser = v, true
+ case ok && k == "DynamicUser":
+ dynamic, sawDynamic = v, true
+ }
+ }
+ if !sawUser || !sawDynamic {
+ return false, fmt.Errorf("systemctl show answered %q", strings.TrimSpace(out))
+ }
+ switch dynamic {
+ case "yes":
+ return false, nil
+ case "no":
+ default:
+ return false, fmt.Errorf("DynamicUser is %q", dynamic)
+ }
+ if unitUser == serviceUser {
+ return true, nil
+ }
+ if _, err := strconv.Atoi(unitUser); err == nil {
+ agent, err := user.Lookup(serviceUser)
+ if err != nil {
+ return false, fmt.Errorf("User is %s and the agent's uid could not be read: %v", unitUser, err)
+ }
+ return unitUser == agent.Uid, nil
+ }
+ return false, nil
+}
+
+// systemctlOutput runs systemctl and returns its combined output.
+func systemctlOutput(ctx context.Context, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+}
+
// listRegistryReadOnly opens the registry at path read-only (as
// instanceRegistryHostApp does), lists every row once and closes it.
func listRegistryReadOnly(path string) ([]registry.Route, error) {
@@ -180,10 +305,7 @@ func registryEgressHosts(dataDir string) func() ([]string, error) {
// /sys/fs/cgroup for the sweep, hosts to name slices, and the log.
func newEgressAsserter(src instancectl.EgressSource, hosts func() ([]string, error)) *instancectl.EgressAsserter {
return &instancectl.EgressAsserter{
- Systemctl: func(ctx context.Context, args ...string) (string, error) {
- out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
- return string(out), err
- },
+ Systemctl: systemctlOutput,
Source: src,
LocalAddrs: instancectl.LocalAddresses,
CgroupRoot: "/sys/fs/cgroup",
diff --git a/internal/host/egress_source_sweep_linux_test.go b/internal/host/egress_source_sweep_linux_test.go
new file mode 100644
index 000000000..cc103052d
--- /dev/null
+++ b/internal/host/egress_source_sweep_linux_test.go
@@ -0,0 +1,114 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// sliceCtl is a systemctl that keeps each slice's IPAddressAllow as
+// set-property --runtime leaves it, and answers show from it.
+type sliceCtl struct {
+ mu sync.Mutex
+ allow map[string]string
+}
+
+func (c *sliceCtl) run(_ context.Context, args ...string) (string, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ switch {
+ case len(args) == 5 && args[0] == "show":
+ return c.allow[args[4]] + "\n", nil
+ case len(args) >= 4 && args[0] == "set-property":
+ v := ""
+ for _, a := range args[3:] {
+ v = strings.TrimPrefix(a, "IPAddressAllow=")
+ }
+ c.allow[args[2]] = v
+ return "", nil
+ }
+ return "", nil
+}
+
+// TestRegistryEgressSourceReadsOncePerSweep is the batching ruling: the
+// asserter's real Sweep over several populated slices reads the registry
+// once and answers every host, and the rail, from that read; the next
+// sweep reads once more; an Assert outside a sweep (a start path, POST
+// /egress) reads afresh.
+func TestRegistryEgressSourceReadsOncePerSweep(t *testing.T) {
+ t.Parallel()
+ reg, dd := egressRegistry(t)
+ clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)}
+ hosts := []string{"shop-a.example.com", "shop-b.example.com", "shop-c.example.com"}
+ cgroup := t.TempDir()
+ for _, h := range hosts {
+ upsertRows(t, reg, nestedRow(dd, h))
+ setAllow(t, reg, h, "10.0.5.20", unixText(clock.Now().Add(time.Hour)))
+ dir := filepath.Join(cgroup, "carlos.slice", "carlos-instances.slice", instancectl.SliceName(h))
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "cgroup.events"), []byte("populated 1\nfrozen 0\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ upsertRows(t, reg, registry.Route{Host: "console.example.com", Kind: "instance", App: "console", Addr: "127.0.0.1:8090",
+ Backing: registry.BackingUnit, Unit: "console.service"})
+ units := &fakeUnitShow{units: map[string]string{"console.service": "User=console\nDynamicUser=no\n"}}
+ var reads atomic.Int32
+ path := reg.Path()
+ src := newRegistrySource(dd, clock.Now, func() ([]registry.Route, error) {
+ reads.Add(1)
+ return listRegistryReadOnly(path)
+ }, units.run).read
+ ctl := &sliceCtl{allow: map[string]string{}}
+ e := &instancectl.EgressAsserter{
+ Systemctl: ctl.run,
+ Source: src,
+ LocalAddrs: func() ([]netip.Prefix, error) { return []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}, nil },
+ CgroupRoot: cgroup,
+ Hosts: registryEgressHosts(dd),
+ Logf: func(string, ...any) {},
+ }
+
+ e.Sweep(context.Background())
+ 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)
+ }
+ reps := e.Reports()
+ for _, h := range hosts {
+ if r := reps[h]; r.State != "" || len(r.Allowed) != 1 || r.Allowed[0] != "10.0.5.20" {
+ t.Fatalf("%s after the sweep: %+v, want 10.0.5.20 allowed", h, r)
+ }
+ }
+
+ e.Sweep(context.Background())
+ if n := reads.Load(); n != 2 {
+ t.Fatalf("two sweeps read the registry %d times, want 2", n)
+ }
+ // A start path's Assert reads afresh: a revoke written just now lands.
+ setAllow(t, reg, "shop-b.example.com", "", "")
+ if err := e.Assert(context.Background(), "shop-b.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if n := reads.Load(); n != 3 {
+ t.Fatalf("an Assert outside a sweep: %d registry reads in all, want 3", n)
+ }
+ if r := e.Reports()["shop-b.example.com"]; len(r.Allowed) != 0 {
+ t.Fatalf("shop-b after its revoke: %+v, want nothing allowed", r)
+ }
+}
diff --git a/internal/host/egress_source_test.go b/internal/host/egress_source_test.go
index 559727532..ee04e07aa 100644
--- a/internal/host/egress_source_test.go
+++ b/internal/host/egress_source_test.go
@@ -61,6 +61,25 @@ func TestBoxWhollyNestedTable(t *testing.T) {
addrExec := registry.Route{Host: "tcp.example.com", Kind: "instance", Hibernate: true, Addr: "127.0.0.1:9000"}
service := registry.Route{Host: "svc.example.com", Kind: "service", Addr: "127.0.0.1:7000"}
unknown := registry.Route{Host: "new.example.com", Kind: "machine"}
+ oddBacking := nestedRow(dd, "odd-backing.example.com")
+ oddBacking.Backing = "vm"
+ appUnit := registry.Route{Host: "app.example.com", Kind: "instance", Hibernate: true, Socket: provision.NestedSocket("app.example.com"),
+ Backing: registry.BackingUnit, Unit: "carlos-app@app.example.com.service"}
+ console := registry.Route{Host: "console.example.com", Kind: "instance", Addr: "127.0.0.1:8090", Backing: registry.BackingUnit, Unit: "console.service"}
+ agentUnit := registry.Route{Host: "agentish.example.com", Kind: "instance", Addr: "127.0.0.1:8091", Unit: "agentish.service"}
+ agentService := registry.Route{Host: "svc-agent.example.com", Kind: "service", Addr: "127.0.0.1:7001", Unit: "agentish.service"}
+ unreadable := registry.Route{Host: "dark.example.com", Kind: "service", Addr: "127.0.0.1:7002", Unit: "dark.service"}
+ // The fake unit reader: agentish.service runs as the agent's user,
+ // dark.service cannot be read, every other unit runs as someone else.
+ unitAsAgent := func(unit string) (bool, error) {
+ switch unit {
+ case "agentish.service":
+ return true, nil
+ case "dark.service":
+ return false, errors.New("Failed to connect to bus")
+ }
+ return false, nil
+ }
for _, tc := range []struct {
name string
@@ -78,15 +97,21 @@ func TestBoxWhollyNestedTable(t *testing.T) {
{"one foreign", []registry.Route{a, foreign}, false, "odd.example.com is foreign"},
{"a sidecar member alone", []registry.Route{sidecar}, false, "worker.example.com is a sidecar member"},
{"a sidecar member beside nested rows", []registry.Route{a, sidecar, b}, false, "worker.example.com is a sidecar member"},
- {"a unit-backed row", []registry.Route{a, unit}, false, "unit.example.com"},
- {"a tunnel-served row", []registry.Route{a, tunnel}, false, "tun.example.com"},
- {"an addr exec row", []registry.Route{a, addrExec}, false, "tcp.example.com"},
- {"a service row", []registry.Route{a, service}, false, "svc.example.com"},
+ {"a carlos-app@ unit row", []registry.Route{a, unit}, true, ""},
+ {"a carlos-app@ unit row naming its unit", []registry.Route{a, appUnit}, true, ""},
+ {"a console unit route not run as the agent", []registry.Route{a, console}, true, ""},
+ {"a tunnel-served row", []registry.Route{a, tunnel}, true, ""},
+ {"an addr-only row", []registry.Route{a, addrExec}, true, ""},
+ {"a service row", []registry.Route{a, service}, true, ""},
+ {"a named unit run as the agent's user", []registry.Route{a, agentUnit}, false, "agentish.example.com runs as agentish.service, which runs as the agent's user"},
+ {"a service row on a unit run as the agent's user", []registry.Route{a, agentService}, false, "svc-agent.example.com runs as agentish.service"},
+ {"a named unit whose user cannot be read", []registry.Route{a, unreadable}, false, "dark.example.com runs as dark.service, whose user could not be read"},
+ {"an unknown backing", []registry.Route{a, oddBacking}, false, "odd-backing.example.com"},
{"an unknown kind", []registry.Route{a, unknown}, false, "new.example.com"},
{"the first failing row is named", []registry.Route{a, flatRow(dd, "first.example.com"), sidecar}, false, "first.example.com is flat"},
} {
t.Run(tc.name, func(t *testing.T) {
- ok, reason := boxWhollyNested(tc.rows, dd)
+ ok, reason := boxWhollyNested(tc.rows, dd, unitAsAgent)
if ok != tc.ok {
t.Fatalf("boxWhollyNested = %v (%q), want %v", ok, reason, tc.ok)
}
@@ -462,3 +487,116 @@ func TestRegistryEgressHostsListsTheRows(t *testing.T) {
t.Fatal("no registry: no error")
}
}
+
+// fakeUnitShow answers `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
+}
+
+func (f *fakeUnitShow) set(unit, out string) { f.mu.Lock(); f.units[unit] = out; f.mu.Unlock() }
+
+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 len(args) != 6 || args[0] != "show" || args[1] != "-p" || args[2] != "User" || args[3] != "-p" || args[4] != "DynamicUser" {
+ return "", errors.New("unexpected systemctl call")
+ }
+ out, ok := f.units[args[5]]
+ if !ok {
+ return "Failed to connect to bus: No such file or directory\n", errors.New("exit status 1")
+ }
+ return out, nil
+}
+
+func TestUnitRunsAsAgent(t *testing.T) {
+ t.Parallel()
+ f := &fakeUnitShow{units: map[string]string{
+ "agent.service": "User=carlos\nDynamicUser=no\n",
+ "dynamic.service": "User=carlos\nDynamicUser=yes\n",
+ "console.service": "User=console\nDynamicUser=no\n",
+ "root.service": "User=\nDynamicUser=no\n",
+ "odd.service": "User=carlos\nDynamicUser=maybe\n",
+ "short.service": "DynamicUser=no\n",
+ "junk.service": "Unit console.service could not be found.\n",
+ }}
+ for _, tc := range []struct {
+ unit string
+ asAgent bool
+ err bool
+ }{
+ {"agent.service", true, false},
+ {"dynamic.service", false, false},
+ {"console.service", false, false},
+ {"root.service", false, false},
+ {"odd.service", false, true},
+ {"short.service", false, true},
+ {"junk.service", false, true},
+ {"missing.service", false, true},
+ } {
+ asAgent, err := unitRunsAsAgent(context.Background(), f.run, tc.unit)
+ if asAgent != tc.asAgent || (err != nil) != tc.err {
+ t.Errorf("%s: as agent %v, err %v; want %v, error %v", tc.unit, asAgent, err, tc.asAgent, tc.err)
+ }
+ }
+ // Not a unit name: refused before systemctl is asked.
+ f.calls = nil
+ for _, bad := range []string{"", "--all", "a b.service", "../x.service"} {
+ if _, err := unitRunsAsAgent(context.Background(), f.run, bad); err == nil {
+ t.Errorf("%q: no error", bad)
+ }
+ }
+ if len(f.calls) != 0 {
+ t.Fatalf("systemctl asked about a bad name: %q", f.calls)
+ }
+}
+
+func TestRegistryEgressSourceUnitRows(t *testing.T) {
+ t.Parallel()
+ reg, dd := egressRegistry(t)
+ clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)}
+ upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"),
+ registry.Route{Host: "app.example.com", Kind: "instance", App: "app", Hibernate: true, Socket: provision.NestedSocket("app.example.com"),
+ Backing: registry.BackingUnit, Unit: "carlos-app@app.example.com.service"},
+ registry.Route{Host: "console.example.com", Kind: "instance", App: "console", Addr: "127.0.0.1:8090", Backing: registry.BackingUnit, Unit: "console.service"})
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour)))
+ f := &fakeUnitShow{units: map[string]string{
+ "carlos-app@app.example.com.service": "User=\nDynamicUser=yes\n",
+ "console.service": "User=console\nDynamicUser=no\n",
+ }}
+ path := reg.Path()
+ src := newRegistrySource(dd, clock.Now, func() ([]registry.Route, error) { return listRegistryReadOnly(path) }, f.run).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"}})
+
+ // The console's unit run as the agent's user: closed.
+ f.set("console.service", "User=carlos\nDynamicUser=no\n")
+ got := readPolicy(t, src, "shop-a.example.com")
+ if got.Closed != instancectl.EgressNotNested || !strings.Contains(got.Detail, "console.example.com runs as console.service, which runs as the agent's user") {
+ t.Fatalf("a unit run as the agent's user: %+v", got)
+ }
+
+ // Its user cannot be read: closed.
+ f.mu.Lock()
+ delete(f.units, "console.service")
+ f.mu.Unlock()
+ got = readPolicy(t, src, "shop-a.example.com")
+ if got.Closed != instancectl.EgressNotNested || !strings.Contains(got.Detail, "whose user could not be read") {
+ t.Fatalf("a unit whose user cannot be read: %+v", got)
+ }
+
+ // A tunnel-served, an addr-only and a static row do not block.
+ f.set("console.service", "User=console\nDynamicUser=no\n")
+ tunnel := nestedRow(dd, "tun.example.com")
+ upsertRows(t, reg, tunnel,
+ registry.Route{Host: "tcp.example.com", Kind: "instance", App: "tcp", Addr: "127.0.0.1:9000"},
+ registry.Route{Host: "files.example.com", Kind: "static", App: "files"})
+ if err := reg.SetTunnel("tun.example.com", "fleet/pi"); err != nil {
+ t.Fatal(err)
+ }
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+}
diff --git a/internal/instancectl/egress.go b/internal/instancectl/egress.go
index 048fc188d..19a219772 100644
--- a/internal/instancectl/egress.go
+++ b/internal/instancectl/egress.go
@@ -27,6 +27,7 @@ import (
"slices"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/carlosframework/platform/internal/egressaddr"
@@ -500,6 +501,21 @@ func (e *EgressAsserter) seedNames() {
}
}
+// egressSweepKey carries one Sweep's id in the context of its Asserts.
+type egressSweepKey struct{}
+
+// egressSweeps numbers sweeps, from 1, across every asserter.
+var egressSweeps atomic.Uint64
+
+// EgressSweep reports which Sweep ctx belongs to. Every Assert one sweep
+// makes carries the same id, so a source can read once per sweep and
+// answer every host from that read; an Assert from anywhere else (a
+// start path, POST /egress) carries none, and a source reads afresh.
+func EgressSweep(ctx context.Context) (id uint64, ok bool) {
+ id, ok = ctx.Value(egressSweepKey{}).(uint64)
+ return id, ok
+}
+
// Sweep asserts every populated per-host slice once. A slice is named
// by its instance id: a host Assert or Hosts recorded for it, or, for an
// id that is not hashed, the id itself. A slice it cannot name is
@@ -517,6 +533,7 @@ func (e *EgressAsserter) Sweep(ctx context.Context) {
e.logf("egress: sweep: %v", err)
return
}
+ ctx = context.WithValue(ctx, egressSweepKey{}, egressSweeps.Add(1))
swept := map[string]bool{}
for _, slice := range populated {
if ctx.Err() != nil {
diff --git a/internal/instancectl/egress_sweep_linux_test.go b/internal/instancectl/egress_sweep_linux_test.go
index 83b8efa94..27e9cb7cd 100644
--- a/internal/instancectl/egress_sweep_linux_test.go
+++ b/internal/instancectl/egress_sweep_linux_test.go
@@ -232,3 +232,35 @@ func TestEgressSeededNamesOutliveAnAssert(t *testing.T) {
t.Fatalf("reports = %+v, want %s asserted by name", e.Reports(), longEgressHost)
}
}
+
+func TestEgressSweepGivesItsAssertsOneID(t *testing.T) {
+ t.Parallel()
+ root := t.TempDir()
+ cgroupSlice(t, root, SliceName("shop-a.example.com"), true)
+ cgroupSlice(t, root, SliceName("shop-b.example.com"), true)
+ var mu sync.Mutex
+ var ids []uint64
+ var outside int
+ e := newEgressAsserter(newEgressCtl(), func(ctx context.Context, _ string) (EgressPolicy, error) {
+ mu.Lock()
+ defer mu.Unlock()
+ if id, ok := EgressSweep(ctx); ok {
+ ids = append(ids, id)
+ } else {
+ outside++
+ }
+ return EgressPolicy{}, nil
+ })
+ e.CgroupRoot = root
+ e.Sweep(context.Background())
+ e.Sweep(context.Background())
+ if err := e.Assert(context.Background(), "shop-a.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if len(ids) != 4 || ids[0] != ids[1] || ids[2] != ids[3] || ids[0] == ids[2] || ids[0] == 0 {
+ t.Fatalf("sweep ids = %v, want one id per sweep, two sweeps", ids)
+ }
+ if outside != 1 {
+ t.Fatalf("Asserts outside a sweep = %d, want 1 (with no id)", outside)
+ }
+}