host: a unit's User decides the rail; a newer registry read supersedes a sweep's (#328)
Review fix round 1 on Task 5. systemd runs a DynamicUser=yes unit as an existing static user of that name, so the configured User is checked first (by name, uid or another name for the agent's uid); only no User, another user, or a name with no static account under DynamicUser=yes is exempt. Every registry read takes a generation; the newest finished read is kept and a running sweep answers from it, so an Assert that applied a revoke cannot be undone by a sweep still holding an older read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+237
−56
internal/host/egress_source.go+105 −43internal/host/egress_source_sweep_linux_test.go+84 −2internal/host/egress_source_test.go+48 −11
diff --git a/internal/host/egress_source.go b/internal/host/egress_source.go| index 3acf38d96..b1ca59a53 100644 |
| --- a/internal/host/egress_source.go |
| +++ b/internal/host/egress_source.go |
| @@ -100,8 +100,12 @@ func boxWhollyNested(rows []registry.Route, dataDir string, unitAsAgent func(uni |
| // |
| // 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. |
| +// every host of that sweep, and the rail, from that read or from any newer |
| +// one. Any other Assert (a start path, POST /egress) reads afresh, and its |
| +// read supersedes the sweep's: every read takes a generation when it |
| +// starts, the newest finished read is kept, and a sweep answers from it. |
| +// So once an Assert has applied a newer read to a host (a revoke, say), a |
| +// sweep still running on an older read cannot re-open it. |
| // |
| // 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 |
| @@ -114,49 +118,76 @@ 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 and systemctl are |
| -// seams: production's read the registry read-only and run systemctl. |
| +// 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. |
| 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) |
| 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 |
| + snapMu sync.Mutex |
| + gen uint64 // the last generation a read took |
| + latest *egressSnapshot // the finished read with the highest generation |
| + sweepID uint64 // the sweep latest serves; 0 before any |
| } |
| // egressSnapshot is one read of the registry and, once asked, its rail. |
| +// A snapshot is shared once it is latest, so the rail is behind railMu. |
| type egressSnapshot struct { |
| - sweep uint64 |
| - rows []registry.Route |
| - err error |
| + gen uint64 |
| + rows []registry.Route |
| + err error |
| + |
| + railMu sync.Mutex |
| 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 ®istrySource{dataDir: dataDir, now: now, list: list, systemctl: systemctl, allowedUntil: map[string]time.Time{}} |
| + return ®istrySource{dataDir: dataDir, now: now, list: list, systemctl: systemctl, lookupUID: userUID, 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} |
| +// snapshot is the read to answer from. Outside a sweep it reads afresh. In |
| +// a sweep it reads once, at the sweep's first ask, and after that answers |
| +// from the newest finished read, which a fresher read outside the sweep |
| +// may have replaced since. |
| +func (s *registrySource) snapshot(ctx context.Context) *egressSnapshot { |
| + id, inSweep := instancectl.EgressSweep(ctx) |
| + if inSweep { |
| + s.snapMu.Lock() |
| + if s.sweepID == id && s.latest != nil { |
| + snap := s.latest |
| + s.snapMu.Unlock() |
| + return snap |
| } |
| - snap = s.sweep |
| - } else { |
| - rows, err := s.list() |
| - snap = &egressSnapshot{rows: rows, err: err} |
| + s.snapMu.Unlock() |
| + } |
| + s.snapMu.Lock() |
| + s.gen++ |
| + snap := &egressSnapshot{gen: s.gen} |
| + s.snapMu.Unlock() |
| + snap.rows, snap.err = s.list() |
| + s.snapMu.Lock() |
| + defer s.snapMu.Unlock() |
| + if s.latest == nil || snap.gen > s.latest.gen { |
| + s.latest = snap |
| + } |
| + if inSweep { |
| + s.sweepID = id |
| } |
| + // A read that started later and finished first is at least as fresh. |
| + return s.latest |
| +} |
| + |
| +func (s *registrySource) read(ctx context.Context, host string) (instancectl.EgressPolicy, error) { |
| + snap := s.snapshot(ctx) |
| now := s.now() |
| if snap.err != nil { |
| s.mu.Lock() |
| @@ -191,14 +222,17 @@ func (s *registrySource) policyFrom(ctx context.Context, snap *egressSnapshot, h |
| if row == nil || strings.TrimSpace(row.EgressAllow) == "" { |
| return instancectl.EgressPolicy{}, time.Time{} |
| } |
| + snap.railMu.Lock() |
| if !snap.railDone { |
| snap.nested, snap.reason = boxWhollyNested(snap.rows, s.dataDir, func(unit string) (bool, error) { |
| - return unitRunsAsAgent(ctx, s.systemctl, unit) |
| + return unitRunsAsAgent(ctx, s.systemctl, s.lookupUID, unit) |
| }) |
| snap.railDone = true |
| } |
| - if !snap.nested { |
| - return instancectl.EgressPolicy{Closed: instancectl.EgressNotNested, Detail: snap.reason}, time.Time{} |
| + nested, reason := snap.nested, snap.reason |
| + snap.railMu.Unlock() |
| + if !nested { |
| + return instancectl.EgressPolicy{Closed: instancectl.EgressNotNested, Detail: reason}, time.Time{} |
| } |
| secs, err := strconv.ParseInt(row.PolicyExpiresAt, 10, 64) |
| if err != nil || secs <= 0 { |
| @@ -218,12 +252,17 @@ func expiredDetail(until time.Time) string { |
| } |
| // 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) { |
| +// systemctl and reports whether it runs as the agent's user (serviceUser). |
| +// The configured User decides, whatever DynamicUser says: systemd runs a |
| +// DynamicUser=yes unit as an existing static user of that name. So a User |
| +// that is the agent's by name, or that resolves to the agent's uid (a |
| +// number, or another name for that uid), counts. Exempt: no User (root |
| +// with DynamicUser=no, a fresh dynamic user with yes), another user, and a |
| +// User with no static account under DynamicUser=yes (systemd allocates |
| +// one). Anything it cannot read or resolve 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), lookup func(string) (string, bool, error), unit string) (bool, error) { |
| if unit == "" || !registry.ValidUnitName(unit) || strings.HasPrefix(unit, "-") { |
| return false, errors.New("not a unit name") |
| } |
| @@ -245,24 +284,47 @@ func unitRunsAsAgent(ctx context.Context, systemctl func(context.Context, ...str |
| if !sawUser || !sawDynamic { |
| return false, fmt.Errorf("systemctl show answered %q", strings.TrimSpace(out)) |
| } |
| - switch dynamic { |
| - case "yes": |
| - return false, nil |
| - case "no": |
| - default: |
| + if dynamic != "yes" && dynamic != "no" { |
| return false, fmt.Errorf("DynamicUser is %q", dynamic) |
| } |
| - if unitUser == serviceUser { |
| + switch unitUser { |
| + case "": |
| + return false, nil |
| + case 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) |
| + agentUID, found, err := lookup(serviceUser) |
| + if err != nil || !found { |
| + return false, fmt.Errorf("User is %s and the agent's uid could not be read (found %v): %v", unitUser, found, err) |
| + } |
| + uid := unitUser |
| + if _, err := strconv.Atoi(unitUser); err != nil { |
| + var found bool |
| + uid, found, err = lookup(unitUser) |
| + switch { |
| + case err != nil: |
| + return false, fmt.Errorf("User %s could not be read: %v", unitUser, err) |
| + case !found && dynamic == "yes": |
| + return false, nil |
| + case !found: |
| + return false, fmt.Errorf("User %s is not an account on this box", unitUser) |
| } |
| - return unitUser == agent.Uid, nil |
| } |
| - return false, nil |
| + return uid == agentUID, nil |
| +} |
| + |
| +// userUID is the user database's uid for name; found is false when no |
| +// such user exists. |
| +func userUID(name string) (string, bool, error) { |
| + u, err := user.Lookup(name) |
| + var unknown user.UnknownUserError |
| + if errors.As(err, &unknown) { |
| + return "", false, nil |
| + } |
| + if err != nil { |
| + return "", false, err |
| + } |
| + return u.Uid, true, nil |
| } |
| // systemctlOutput runs systemctl and returns its combined output. |
diff --git a/internal/host/egress_source_sweep_linux_test.go b/internal/host/egress_source_sweep_linux_test.go| index cc103052d..02dd7e790 100644 |
| --- a/internal/host/egress_source_sweep_linux_test.go |
| +++ b/internal/host/egress_source_sweep_linux_test.go |
| @@ -22,10 +22,21 @@ import ( |
| type sliceCtl struct { |
| mu sync.Mutex |
| allow map[string]string |
| + // pause, when set, holds the next show of that slice: it says so on |
| + // paused and waits for resume. |
| + pause string |
| + paused, resume chan struct{} |
| } |
| func (c *sliceCtl) run(_ context.Context, args ...string) (string, error) { |
| c.mu.Lock() |
| + if len(args) == 5 && args[0] == "show" && c.pause != "" && args[4] == c.pause { |
| + c.pause = "" |
| + c.mu.Unlock() |
| + c.paused <- struct{}{} |
| + <-c.resume |
| + c.mu.Lock() |
| + } |
| defer c.mu.Unlock() |
| switch { |
| case len(args) == 5 && args[0] == "show": |
| @@ -41,6 +52,13 @@ func (c *sliceCtl) run(_ context.Context, args ...string) (string, error) { |
| return "", nil |
| } |
| +// held is what host's slice holds. |
| +func (c *sliceCtl) held(host string) string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.allow[instancectl.SliceName(host)] |
| +} |
| + |
| // 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 |
| @@ -68,10 +86,12 @@ func TestRegistryEgressSourceReadsOncePerSweep(t *testing.T) { |
| 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) { |
| + rs := newRegistrySource(dd, clock.Now, func() ([]registry.Route, error) { |
| reads.Add(1) |
| return listRegistryReadOnly(path) |
| - }, units.run).read |
| + }, units.run) |
| + rs.lookupUID = fakeUsers |
| + src := rs.read |
| ctl := &sliceCtl{allow: map[string]string{}} |
| e := &instancectl.EgressAsserter{ |
| Systemctl: ctl.run, |
| @@ -112,3 +132,65 @@ func TestRegistryEgressSourceReadsOncePerSweep(t *testing.T) { |
| t.Fatalf("shop-b after its revoke: %+v, want nothing allowed", r) |
| } |
| } |
| + |
| +// TestRegistryEgressSweepCannotReopenARevoke is review finding 2: a sweep |
| +// reads the registry once, while shop-a and shop-b both hold an allow; |
| +// it is held at shop-a; shop-b's allow is revoked in the registry and a |
| +// start path's Assert closes it; the sweep resumes and asserts shop-b. |
| +// It must answer from the newer read, so shop-b stays closed. |
| +func TestRegistryEgressSweepCannotReopenARevoke(t *testing.T) { |
| + t.Parallel() |
| + reg, dd := egressRegistry(t) |
| + clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)} |
| + cgroup := t.TempDir() |
| + const a, b = "shop-a.example.com", "shop-b.example.com" |
| + for _, h := range []string{a, b} { |
| + 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) |
| + } |
| + } |
| + src := registryEgressSource(dd, clock.Now) |
| + ctl := &sliceCtl{allow: map[string]string{}, paused: make(chan struct{}), resume: make(chan struct{})} |
| + 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, |
| + Logf: func(string, ...any) {}, |
| + } |
| + e.Sweep(context.Background()) |
| + if got := ctl.held(b); got != "10.0.5.20/32" { |
| + t.Fatalf("shop-b after the first sweep holds %q, want 10.0.5.20/32", got) |
| + } |
| + |
| + // The second sweep reads the registry at shop-a, then is held there. |
| + ctl.mu.Lock() |
| + ctl.pause = instancectl.SliceName(a) |
| + ctl.mu.Unlock() |
| + done := make(chan struct{}) |
| + go func() { defer close(done); e.Sweep(context.Background()) }() |
| + <-ctl.paused |
| + |
| + setAllow(t, reg, b, "", "") |
| + if err := e.Assert(context.Background(), b); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := ctl.held(b); got != "" { |
| + t.Fatalf("shop-b after its revoke holds %q, want nothing", got) |
| + } |
| + |
| + close(ctl.resume) |
| + <-done |
| + if got := ctl.held(b); got != "" { |
| + t.Fatalf("the held sweep re-opened shop-b's revoked allow: it holds %q", got) |
| + } |
| + if r := e.Reports()[b]; len(r.Allowed) != 0 { |
| + t.Fatalf("shop-b's report after the sweep: %+v, want nothing allowed", r) |
| + } |
| +} |
diff --git a/internal/host/egress_source_test.go b/internal/host/egress_source_test.go| index ee04e07aa..f78e3f489 100644 |
| --- a/internal/host/egress_source_test.go |
| +++ b/internal/host/egress_source_test.go |
| @@ -512,16 +512,40 @@ func (f *fakeUnitShow) run(_ context.Context, args ...string) (string, error) { |
| return out, nil |
| } |
| +// fakeUsers is a user database: carlos (the agent) is 1001, alias is |
| +// another name for 1001, console is 1002; broken cannot be read; every |
| +// other name does not exist. |
| +func fakeUsers(name string) (string, bool, error) { |
| + switch name { |
| + case "carlos", "alias": |
| + return "1001", true, nil |
| + case "console": |
| + return "1002", true, nil |
| + case "broken": |
| + return "", false, errors.New("nss: timed out") |
| + } |
| + return "", false, 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", |
| + "agent.service": "User=carlos\nDynamicUser=no\n", |
| + "dynamic.service": "User=carlos\nDynamicUser=yes\n", |
| + "alias.service": "User=alias\nDynamicUser=no\n", |
| + "alias-dynamic.service": "User=alias\nDynamicUser=yes\n", |
| + "uid.service": "User=1001\nDynamicUser=no\n", |
| + "uid-dynamic.service": "User=1001\nDynamicUser=yes\n", |
| + "otheruid.service": "User=1002\nDynamicUser=no\n", |
| + "console.service": "User=console\nDynamicUser=no\n", |
| + "fresh.service": "User=\nDynamicUser=yes\n", |
| + "fresh-named.service": "User=shop-worker\nDynamicUser=yes\n", |
| + "ghost.service": "User=shop-worker\nDynamicUser=no\n", |
| + "broken.service": "User=broken\nDynamicUser=yes\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 |
| @@ -529,15 +553,26 @@ func TestUnitRunsAsAgent(t *testing.T) { |
| err bool |
| }{ |
| {"agent.service", true, false}, |
| - {"dynamic.service", false, false}, |
| + // systemd reuses an existing static user even with DynamicUser=yes: |
| + // User=carlos runs as the agent's user either way. |
| + {"dynamic.service", true, false}, |
| + {"alias.service", true, false}, |
| + {"alias-dynamic.service", true, false}, |
| + {"uid.service", true, false}, |
| + {"uid-dynamic.service", true, false}, |
| + {"otheruid.service", false, false}, |
| {"console.service", false, false}, |
| + {"fresh.service", false, false}, // a fresh dynamic user |
| + {"fresh-named.service", false, false}, // no static account: systemd allocates one |
| + {"ghost.service", false, true}, // no such account, DynamicUser=no |
| + {"broken.service", false, true}, |
| {"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) |
| + asAgent, err := unitRunsAsAgent(context.Background(), f.run, fakeUsers, 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) |
| } |
| @@ -545,7 +580,7 @@ func TestUnitRunsAsAgent(t *testing.T) { |
| // 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 { |
| + if _, err := unitRunsAsAgent(context.Background(), f.run, fakeUsers, bad); err == nil { |
| t.Errorf("%q: no error", bad) |
| } |
| } |
| @@ -568,7 +603,9 @@ func TestRegistryEgressSourceUnitRows(t *testing.T) { |
| "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 |
| + rs := newRegistrySource(dd, clock.Now, func() ([]registry.Route, error) { return listRegistryReadOnly(path) }, f.run) |
| + rs.lookupUID = fakeUsers |
| + src := rs.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"}}) |