carlos / platform Public

egress: what a slice owes its running services is kept under /run/carlos-control/egress-due, so a control service that exits mid-revoke leaves it for the next (#328, final review F1)

The obligation to nudge or restart a slice's running units after its allow
changes lived only in memory. A control service that exited between the
slice write and the per-unit step left the slice reading as wanted and the
running unit under its old filter for good. Root now writes a per-slice
record before the slice write and removes it once the change reached every
running unit; every sweep (the first as the service starts) and any Assert
finish a recorded change, and a slice where nothing runs is discharged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev db11b64ecf811036db19d85e4e11c31597301208 parent 31b400c
8 files changed, +751 −22
  • internal/host/egress_claim_wiring_test.go +1 −0
  • internal/host/egress_interrupt_rootrunner_linux_test.go +164 −0
  • internal/host/egress_nopolicy_linux_test.go +1 −0
  • internal/host/egress_source.go +4 −1
  • internal/host/egress_source_test.go +20 −0
  • internal/instancectl/egress.go +81 −21
  • internal/instancectl/egress_due.go +208 −0
  • internal/instancectl/egress_due_linux_test.go +272 −0
diff --git a/internal/host/egress_claim_wiring_test.go b/internal/host/egress_claim_wiring_test.go
index 86b061fc2..84fd62090 100644
--- a/internal/host/egress_claim_wiring_test.go
+++ b/internal/host/egress_claim_wiring_test.go
@@ -288,6 +288,7 @@ func newEgressClaimWiring(t *testing.T) *egressClaimWiring {
r.OptDir, r.UnitsDir = w.r.OptDir, w.r.UnitsDir
r.Egress.Systemctl = e.ctl.run
r.Egress.Logf = e.logf
+ r.Egress.DueDir = filepath.Join(t.TempDir(), "egress-due") // never the box's /run
ctx = withClaimRuntimeResources(ctx, r)
ctx, err = ensureProductionClaimAssembly(ctx)
if err != nil {
diff --git a/internal/host/egress_interrupt_rootrunner_linux_test.go b/internal/host/egress_interrupt_rootrunner_linux_test.go
new file mode 100644
index 000000000..659f0ef32
--- /dev/null
+++ b/internal/host/egress_interrupt_rootrunner_linux_test.go
@@ -0,0 +1,164 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// Final review F1 (#328): a control service that exits between a slice
+// write and the per-unit step must not lose the revoke. Fixtures are in
+// egress_fixtures_rootrunner_linux_test.go.
+
+// egressInterruptedArg runs this test binary as an interrupted control
+// service: the production pre-claim asserter (newEgressAsserter over the
+// registry at /data, EgressDueDir included) asserts one host, and the
+// process exits, with egressInterruptedExit, at the first systemctl call
+// that names the host's run unit, before that call runs: after the slice's
+// allow is written and read back, before any running unit is nudged or
+// restarted. It exits egressInterruptedEarly if the slice was not written
+// first, and egressInterruptedNever if Assert returned without reaching
+// the unit.
+const (
+ egressInterruptedArg = "egress-interrupted-assert"
+ egressInterruptedExit = 7
+ egressInterruptedEarly = 4
+ egressInterruptedNever = 5
+)
+
+func init() {
+ if len(os.Args) == 3 && os.Args[1] == egressInterruptedArg {
+ os.Exit(egressInterruptedAssert(os.Args[2]))
+ }
+}
+
+func egressInterruptedAssert(host string) int {
+ e := newEgressAsserter(registryEgressSource("/data", time.Now), registryEgressHosts("/data"))
+ e.Logf = func(f string, a ...any) { fmt.Fprintf(os.Stderr, f+"\n", a...) }
+ slice := instancectl.SliceName(host)
+ run := instancectl.UnitName(instancectl.RoleRun, host)
+ next := e.Systemctl
+ wrote := false
+ e.Systemctl = func(ctx context.Context, args ...string) (string, error) {
+ if slices.Contains(args, run) {
+ if !wrote {
+ fmt.Fprintln(os.Stderr, "interrupted before the slice was written:", strings.Join(args, " "))
+ os.Exit(egressInterruptedEarly)
+ }
+ fmt.Fprintln(os.Stderr, "exiting before:", strings.Join(args, " "))
+ os.Exit(egressInterruptedExit)
+ }
+ out, err := next(ctx, args...)
+ if err == nil && len(args) > 2 && args[0] == "set-property" && args[2] == slice {
+ wrote = true
+ }
+ return out, err
+ }
+ err := e.Assert(context.Background(), host)
+ fmt.Fprintln(os.Stderr, "Assert returned without reaching the run unit:", err)
+ return egressInterruptedNever
+}
+
+// TestRootEgressInterruptedRevoke is final review F1's witness, through
+// real systemd and the production asserter. The run unit serves with an
+// allow for 10.0.5.20, and carlos-instances.slice's allow is rewritten
+// while it runs (as the probe's allowResolvers does every five minutes),
+// so a change of the host slice's allow no longer reaches the unit without
+// the nudge (run 20261025T173953-8a3366). The column is cleared, and a
+// control service process asserts the host and exits after the slice's
+// allow is written and before the run unit is nudged.
+//
+// Then: the slice reads back empty, EgressDueDir holds the revoke, and the
+// running unit still reaches 10.0.5.20 (the obligation is real: without
+// it, nothing would ever close the address). A fresh control service's
+// asserter starts as runWithClaim starts it (Loop: name the slices, sweep
+// once); within egressLiveBound of that the unit, which keeps its
+// invocation, no longer reaches 10.0.5.20, the record is gone, and GET
+// /egress on the fresh service reports nothing allowed and no state.
+func TestRootEgressInterruptedRevoke(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)
+ egressParentAllow(t, "fd00:5::20/128")
+ egressRewriteParent(t, "fd00:5::20/128")
+ b.wantAllowed(t, "start")
+ if !egressReach(t, c, target) {
+ t.Fatal("start: the tenant cannot reach 10.0.5.20")
+ }
+
+ // The revoke, and the control service that dies doing it.
+ if err := b.reg.SetPolicy(b.host, "", "", ""); err != nil {
+ t.Fatal(err)
+ }
+ before := b.runInvocation(t)
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ out, err := exec.CommandContext(ctx, exe, egressInterruptedArg, b.host).CombinedOutput()
+ var exit *exec.ExitError
+ if !errors.As(err, &exit) || exit.ExitCode() != egressInterruptedExit {
+ t.Fatalf("interrupted control service: %v, want exit status %d\n%s", err, egressInterruptedExit, out)
+ }
+ t.Logf("interrupted control service:\n%s", out)
+
+ if got := b.allow(t); got != "" {
+ t.Fatalf("after the interruption the slice holds %q, want the revoke written", got)
+ }
+ record := filepath.Join(instancectl.EgressDueDir, b.slice)
+ if raw, err := os.ReadFile(record); err != nil || strings.TrimSpace(string(raw)) != "revoke" {
+ t.Fatalf("after the interruption %s = %q, %v; want revoke", record, raw, err)
+ }
+ if !egressReach(t, c, target) {
+ t.Fatal("after the interruption the run unit no longer reaches 10.0.5.20: the slice write alone closed it, so this witness cannot tell recovery from nothing (the kernel finding of run 20261025T173953-8a3366 did not hold here)")
+ }
+ if after := b.runInvocation(t); after != before {
+ t.Fatalf("the interrupted control service restarted the run unit (%s -> %s)", before, after)
+ }
+
+ // The next control service: the production asserter, as it starts.
+ fresh := newEgressAsserter(registryEgressSource("/data", time.Now), registryEgressHosts("/data"))
+ fresh.Logf = t.Logf
+ srv := &instancectl.Server{
+ Systemctl: func(ctx context.Context, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+ },
+ CgroupRoot: "/sys/fs/cgroup",
+ Logf: t.Logf,
+ Egress: fresh,
+ }
+ client := egressServe(t, srv, filepath.Join(t.TempDir(), "control2.sock"))
+ fresh.Loop(ctx, 0)
+ deadline := time.Now().Add(egressLiveBound)
+ if !egressWithin(t, deadline, c, false, target) {
+ egressFirewallDiag(t, run, b.slice, c, target)
+ t.Fatal("the fresh control service's first sweep did not close 10.0.5.20 on the running unit")
+ }
+ if after := b.runInvocation(t); after != before {
+ t.Fatalf("the run unit was restarted (%s -> %s); with a parent allow the revoke is applied by the nudge", before, after)
+ }
+ if _, err := os.Lstat(record); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("%s is still there after the revoke reached the run unit: %v", record, err)
+ }
+ st, err := client.EgressStatus(ctx)
+ if err != nil {
+ t.Fatal("GET /egress:", err)
+ }
+ if rep := st.Hosts[b.host]; len(rep.Allowed) != 0 || rep.State != "" || rep.Detail != "" {
+ t.Fatalf("GET /egress on the fresh service = %+v, want nothing allowed, no state, no detail", rep)
+ }
+}
diff --git a/internal/host/egress_nopolicy_linux_test.go b/internal/host/egress_nopolicy_linux_test.go
index 0bc8ffbd0..ec52b0a74 100644
--- a/internal/host/egress_nopolicy_linux_test.go
+++ b/internal/host/egress_nopolicy_linux_test.go
@@ -223,6 +223,7 @@ func TestEgressNoPolicyBoxPublishesAsMain(t *testing.T) {
ctl := &noPolicyCtl{}
e.Systemctl = ctl.run
e.CgroupRoot = cgroup
+ e.DueDir = filepath.Join(t.TempDir(), "egress-due") // never the box's /run
e.LocalAddrs = func() ([]netip.Prefix, error) {
return []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("10.0.1.5/32")}, nil
}
diff --git a/internal/host/egress_source.go b/internal/host/egress_source.go
index 8e76cd7b4..efc378d5a 100644
--- a/internal/host/egress_source.go
+++ b/internal/host/egress_source.go
@@ -396,7 +396,9 @@ func claimsEgressAsserter(hosts func() ([]string, error)) *instancectl.EgressAss
// newEgressAsserter is root's production asserter over src: the real
// systemctl, the box's own addresses from procfs, cgroupfs at
-// /sys/fs/cgroup for the sweep, hosts to name slices, and the log.
+// /sys/fs/cgroup for the sweep, hosts to name slices, the log, and
+// instancectl.EgressDueDir, where what a slice owes its running services
+// outlives this control service (final review F1).
func newEgressAsserter(src instancectl.EgressSource, hosts func() ([]string, error)) *instancectl.EgressAsserter {
return &instancectl.EgressAsserter{
Systemctl: systemctlOutput,
@@ -405,5 +407,6 @@ func newEgressAsserter(src instancectl.EgressSource, hosts func() ([]string, err
CgroupRoot: "/sys/fs/cgroup",
Hosts: hosts,
Logf: log.Printf,
+ DueDir: instancectl.EgressDueDir,
}
}
diff --git a/internal/host/egress_source_test.go b/internal/host/egress_source_test.go
index 6e59aa339..43be75b13 100644
--- a/internal/host/egress_source_test.go
+++ b/internal/host/egress_source_test.go
@@ -749,3 +749,23 @@ func TestClaimsEgressSourceClosesEveryHost(t *testing.T) {
t.Fatalf("the registry's directory changed:\nbefore %v\nafter %v", before, after)
}
}
+
+// TestEgressAssertersKeepOwedChangesUnderRun pins final review F1's
+// wiring: root's asserters, pre-claim and under claims, keep what a slice
+// owes its running services in instancectl.EgressDueDir, in root's
+// control directory under /run, so a control service that exits between
+// a slice write and the per-unit step leaves it for the next one.
+func TestEgressAssertersKeepOwedChangesUnderRun(t *testing.T) {
+ t.Parallel()
+ if want := "/run/carlos-control/egress-due"; instancectl.EgressDueDir != want {
+ t.Fatalf("EgressDueDir = %q, want %q", instancectl.EgressDueDir, want)
+ }
+ for name, e := range map[string]*instancectl.EgressAsserter{
+ "pre-claim": newEgressAsserter(claimsEgressSource(), nil),
+ "under claims": claimsEgressAsserter(nil),
+ } {
+ if e.DueDir != instancectl.EgressDueDir {
+ t.Errorf("%s: DueDir = %q, want %q", name, e.DueDir, instancectl.EgressDueDir)
+ }
+ }
+}
diff --git a/internal/instancectl/egress.go b/internal/instancectl/egress.go
index d869b8935..269c8f25e 100644
--- a/internal/instancectl/egress.go
+++ b/internal/instancectl/egress.go
@@ -109,6 +109,10 @@ type EgressAsserter struct {
// the sweep's reset of a slice it cannot name included, where there is
// no host whose policy could say so.
UnderClaims bool
+ // DueDir keeps what each slice owes its running services across
+ // control service lifetimes (EgressDueDir in production; egress_due.go).
+ // Empty keeps it in memory only.
+ DueDir string
mu sync.Mutex
last map[string]EgressPolicy // host -> the last policy Source read
@@ -120,8 +124,11 @@ type EgressAsserter struct {
// shown to reach the services running in it (reach): recorded before
// the write, cleared once every running service took it, and retried
// by the next Assert of the slice, though the slice already reads back
- // what is wanted.
- due map[string]egressDue
+ // what is wanted. It is kept in DueDir too, so a control service that
+ // exits before the change reaches them leaves it for the next one;
+ // dueLoaded is whether DueDir has been read into it yet.
+ due map[string]egressDue
+ dueLoaded bool
// heldSome is, per slice, whether its last successful read-back held
// an allow. A start path whose read fails with nothing wanted refuses
// only on such a slice, or one owing a change (mayHold, AssertStart).
@@ -279,14 +286,18 @@ func (e *EgressAsserter) assert(ctx context.Context, host string, start bool) er
}
// What this change owes the running services is recorded before it is
- // written: an uncertain outcome (the write answers an error after it
- // applied, or the read after it fails) must not lose it, or the next
- // Assert would find the slice as wanted and stop there. A change that
- // removes an address, or whose before is unknown, is a revoke.
- if !readBefore || held.removes(want) {
- e.setDue(slice, dueRevoke)
- } else if e.dueOf(slice) != dueRevoke {
- e.setDue(slice, dueGrant)
+ // written, in memory and in DueDir: an uncertain outcome (the write
+ // answers an error after it applied, or the read after it fails), or a
+ // control service that exits before reach is done, must not lose it,
+ // or the next Assert would find the slice as wanted and stop there. A
+ // change that removes an address, or whose before is unknown, is a
+ // revoke. A record that cannot be kept writes nothing.
+ owe := dueGrant
+ if !readBefore || held.removes(want) || e.dueOf(slice) == dueRevoke {
+ owe = dueRevoke
+ }
+ if err := e.setDue(slice, owe); err != nil {
+ return fail("recording the change it will owe its running services: " + err.Error() + "; nothing written")
}
args := []string{"set-property", "--runtime", slice, "IPAddressAllow="}
if len(want) > 0 {
@@ -348,7 +359,7 @@ func (e *EgressAsserter) reach(ctx context.Context, slice string, revoke, emptie
}
err := e.nudgeRunning(ctx, slice)
if err == nil {
- e.setDue(slice, dueNone)
+ e.clearDue(slice)
return nil
}
if revoke {
@@ -436,7 +447,7 @@ func (e *EgressAsserter) closeByRestart(ctx context.Context, slice string, rep *
// run under the old filter.
func (e *EgressAsserter) restartRunning(ctx context.Context, slice string, rep *EgressReport) error {
keepDue := func(err error) error {
- e.setDue(slice, dueRevoke)
+ e.keepDueRevoke(slice)
return err
}
if e.CgroupRoot == "" {
@@ -447,7 +458,7 @@ func (e *EgressAsserter) restartRunning(ctx context.Context, slice string, rep *
return keepDue(fmt.Errorf("revoked, but the slice's running units could not be read to restart them: %v", err))
}
if !populated {
- e.setDue(slice, dueNone)
+ e.clearDue(slice)
return nil // nothing runs under the old filter
}
if len(units) == 0 {
@@ -483,7 +494,7 @@ func (e *EgressAsserter) restartRunning(ctx context.Context, slice string, rep *
if len(failed) > 0 {
return keepDue(fmt.Errorf("revoked, but restarting the slice's units failed: %s", strings.Join(failed, "; ")))
}
- e.setDue(slice, dueNone)
+ e.clearDue(slice)
if rep.Detail == "" {
rep.Detail = egressRestarted
} else {
@@ -499,20 +510,27 @@ func (e *EgressAsserter) isRestartDue(slice string) bool { return e.dueOf(slice)
func (e *EgressAsserter) dueOf(slice string) egressDue {
e.mu.Lock()
defer e.mu.Unlock()
+ e.ensureDueLoadedLocked()
return e.due[slice]
}
-func (e *EgressAsserter) setDue(slice string, d egressDue) {
+// setDue records what slice owes, in memory whatever happens and in
+// DueDir: its file written for a grant or revoke (every time, so a record
+// an earlier write failed to keep is kept now), removed for dueNone. The
+// error is the file's.
+func (e *EgressAsserter) setDue(slice string, d egressDue) error {
e.mu.Lock()
defer e.mu.Unlock()
+ e.ensureDueLoadedLocked()
if d == dueNone {
delete(e.due, slice)
- return
- }
- if e.due == nil {
- e.due = map[string]egressDue{}
+ } else {
+ if e.due == nil {
+ e.due = map[string]egressDue{}
+ }
+ e.due[slice] = d
}
- e.due[slice] = d
+ return e.persistDueLocked(slice, d)
}
// mayHold says whether slice may hold an allow as far as this asserter
@@ -523,6 +541,7 @@ func (e *EgressAsserter) setDue(slice string, d egressDue) {
func (e *EgressAsserter) mayHold(slice string) bool {
e.mu.Lock()
defer e.mu.Unlock()
+ e.ensureDueLoadedLocked()
return e.due[slice] != dueNone || e.heldSome[slice]
}
@@ -884,6 +903,11 @@ func EgressSweep(ctx context.Context) (id uint64, ok bool) {
// 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
// closed. It reads cgroupfs and asks Source, which reads no store.
+//
+// It reads DueDir first, so a change an earlier control service wrote but
+// did not finish is finished by the Assert of its slice (the first sweep
+// runs as Loop starts); a slice that owes a change and in which nothing
+// runs owes nothing more (dischargeIdle).
func (e *EgressAsserter) Sweep(ctx context.Context) {
if e == nil {
return
@@ -897,6 +921,7 @@ func (e *EgressAsserter) Sweep(ctx context.Context) {
e.logf("egress: sweep: %v", err)
return
}
+ e.reloadDue()
ctx = context.WithValue(ctx, egressSweepKey{}, egressSweeps.Add(1))
swept := map[string]bool{}
for _, slice := range populated {
@@ -919,6 +944,36 @@ func (e *EgressAsserter) Sweep(ctx context.Context) {
}
}
e.mu.Unlock()
+ for _, slice := range e.dueSlices() {
+ if ctx.Err() != nil {
+ return
+ }
+ if !slices.Contains(populated, slice) {
+ e.dischargeIdle(slice)
+ }
+ }
+}
+
+// dischargeIdle drops what slice owes when nothing runs in it: no running
+// service holds an old filter, and a unit started later compiles its
+// filter from the slice as it is. It holds the slice's lock, so a start
+// path's Assert of it finishes first; a slice found running again is left
+// for the next sweep's Assert.
+func (e *EgressAsserter) dischargeIdle(slice string) {
+ unlock := e.lockSlice(slice)
+ defer unlock()
+ if e.dueOf(slice) == dueNone {
+ return
+ }
+ populated, _, err := sliceRunningServices(e.CgroupRoot, slice)
+ if err != nil {
+ e.logf("egress: %s: the change it owes stays owed: %v", slice, err)
+ return
+ }
+ if populated {
+ return
+ }
+ e.clearDue(slice)
}
// hostOf names a slice, or reports false. The name must give the slice
@@ -973,7 +1028,12 @@ func (e *EgressAsserter) closeUnnamed(ctx context.Context, slice string) (string
}
return "", false
}
- e.setDue(slice, dueRevoke) // before the reset, as Assert records it
+ // Before the reset, as Assert records it; a record that cannot be
+ // kept writes nothing.
+ if err := e.setDue(slice, dueRevoke); err != nil {
+ e.logf("egress: %s: no host for this slice; recording the revoke it will owe: %v; nothing written", slice, err)
+ return "", false
+ }
if out, err := e.Systemctl(ctx, "set-property", "--runtime", slice, "IPAddressAllow="); err != nil {
e.logf("egress: %s: no host for this slice; closing its allow: set-property: %s: %v", slice, strings.TrimSpace(out), err)
return "", false
diff --git a/internal/instancectl/egress_due.go b/internal/instancectl/egress_due.go
new file mode 100644
index 000000000..6b861aa57
--- /dev/null
+++ b/internal/instancectl/egress_due.go
@@ -0,0 +1,208 @@
+package instancectl
+
+import (
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/controlsock"
+)
+
+// EgressDueDir is where root keeps what each host slice still owes the
+// services running in it (#328, final review F1): one file per slice,
+// named for the slice, holding "grant" or "revoke". It is written before
+// the slice's allow is, and removed once the change has reached every
+// running service (reach); the directory goes when it is empty. A control service that exits in between
+// (a crash, a restart, an upgrade) leaves the file, and the next one
+// finds it: the first sweep at its start, a start path's Assert, or any
+// later sweep finishes the change, though the slice already reads back
+// what is wanted. Without it that slice would read as done, and a running
+// unit could keep the filter the slice no longer holds (the kernel
+// findings at the top of egress.go).
+//
+// It is under /run, so it goes at reboot with the runtime allows it
+// guards, in root's control directory beside the control socket: the
+// directory the control service may write (carlos-instance-control.service
+// ReadWritePaths), which the agent's group may list but not write, and
+// which every instance unit has as InaccessiblePaths. The directory itself
+// is root's alone (0700).
+const EgressDueDir = controlsock.Dir + "/egress-due"
+
+// The file's contents. Anything else, a torn write included, reads as a
+// revoke: the stronger obligation.
+const (
+ dueGrantText = "grant"
+ dueRevokeText = "revoke"
+)
+
+// isHostSliceName is true for a per-host slice's unit name, the only names
+// a file in DueDir may have.
+func isHostSliceName(name string) bool {
+ esc, ok := strings.CutPrefix(name, hostSlicePrefix)
+ if !ok {
+ return false
+ }
+ esc, ok = strings.CutSuffix(esc, ".slice")
+ if !ok || esc == "" || strings.ContainsRune(name, '/') {
+ return false
+ }
+ _, ok = Unescape(esc)
+ return ok
+}
+
+// persistDueLocked writes slice's file for d, or removes it for dueNone.
+// The caller holds e.mu. With no DueDir it does nothing (tests that keep
+// what is owed in memory only).
+func (e *EgressAsserter) persistDueLocked(slice string, d egressDue) error {
+ if e.DueDir == "" {
+ return nil
+ }
+ if !isHostSliceName(slice) {
+ return fmt.Errorf("%q is not a host slice", slice)
+ }
+ path := filepath.Join(e.DueDir, slice)
+ if d == dueNone {
+ if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ if len(e.due) == 0 {
+ // Nothing is owed: the directory goes too, so a box (and a
+ // test's fixture root) holds none of it at rest. Anything
+ // still in it (a file whose removal failed) keeps it.
+ _ = os.Remove(e.DueDir)
+ }
+ return nil
+ }
+ if err := ensureDueDir(e.DueDir); err != nil {
+ return err
+ }
+ text := dueRevokeText
+ if d == dueGrant {
+ text = dueGrantText
+ }
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+ if err != nil {
+ return err
+ }
+ _, werr := f.WriteString(text + "\n")
+ return errors.Join(werr, f.Close())
+}
+
+// ensureDueDir makes dir (one level: its parent, root's control directory,
+// must already be there, with the ownership the box gives it) private to
+// root, and refuses anything there that is not a directory.
+func ensureDueDir(dir string) error {
+ if err := os.Mkdir(dir, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
+ return err
+ }
+ fi, err := os.Lstat(dir)
+ if err != nil {
+ return err
+ }
+ if !fi.IsDir() {
+ return fmt.Errorf("%s is not a directory", dir)
+ }
+ return nil
+}
+
+// loadDueLocked merges what DueDir says each slice owes into e.due: a
+// revoke on disk outranks a grant in memory, and nothing in memory is
+// dropped (a removal that failed leaves its file, and loading it again
+// only makes the change be applied once more). The caller holds e.mu. A
+// directory that is not there owes nothing.
+func (e *EgressAsserter) loadDueLocked() error {
+ e.dueLoaded = true
+ if e.DueDir == "" {
+ return nil
+ }
+ entries, err := os.ReadDir(e.DueDir)
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ var errs []error
+ for _, ent := range entries {
+ name := ent.Name()
+ if !ent.Type().IsRegular() || !isHostSliceName(name) {
+ continue
+ }
+ raw, err := os.ReadFile(filepath.Join(e.DueDir, name))
+ if errors.Is(err, fs.ErrNotExist) {
+ continue // discharged between the list and the read
+ }
+ if err != nil {
+ errs = append(errs, err)
+ continue
+ }
+ d := dueRevoke
+ if strings.TrimSpace(string(raw)) == dueGrantText {
+ d = dueGrant
+ }
+ if e.due == nil {
+ e.due = map[string]egressDue{}
+ }
+ if e.due[name] < d {
+ e.due[name] = d
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// ensureDueLoadedLocked loads DueDir once, the first time anything asks
+// what a slice owes, so a start path that comes before the first sweep of
+// a fresh control service sees what the last one left. The caller holds
+// e.mu.
+func (e *EgressAsserter) ensureDueLoadedLocked() {
+ if e.dueLoaded {
+ return
+ }
+ if err := e.loadDueLocked(); err != nil {
+ e.logf("egress: reading the changes owed in %s: %v", e.DueDir, err)
+ }
+}
+
+// reloadDue reads DueDir again; every sweep does, so a file whose removal
+// failed is taken up again, and so is one a fresh control service could
+// not read at its start.
+func (e *EgressAsserter) reloadDue() {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if err := e.loadDueLocked(); err != nil {
+ e.logf("egress: reading the changes owed in %s: %v", e.DueDir, err)
+ }
+}
+
+// dueSlices is every slice that owes something, sorted.
+func (e *EgressAsserter) dueSlices() []string {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ e.ensureDueLoadedLocked()
+ out := make([]string, 0, len(e.due))
+ for s := range e.due {
+ out = append(out, s)
+ }
+ slices.Sort(out)
+ return out
+}
+
+// clearDue records that slice owes nothing more; a file that could not be
+// removed is logged, and the next sweep applies the change again.
+func (e *EgressAsserter) clearDue(slice string) {
+ if err := e.setDue(slice, dueNone); err != nil {
+ e.logf("egress: %s: removing the change it owed from %s: %v", slice, e.DueDir, err)
+ }
+}
+
+// keepDueRevoke records that slice still owes a revoke; it is in memory
+// whatever the disk says, and a failed write is logged.
+func (e *EgressAsserter) keepDueRevoke(slice string) {
+ if err := e.setDue(slice, dueRevoke); err != nil {
+ e.logf("egress: %s: recording the revoke it owes in %s: %v", slice, e.DueDir, err)
+ }
+}
diff --git a/internal/instancectl/egress_due_linux_test.go b/internal/instancectl/egress_due_linux_test.go
new file mode 100644
index 000000000..772803d29
--- /dev/null
+++ b/internal/instancectl/egress_due_linux_test.go
@@ -0,0 +1,272 @@
+//go:build linux
+
+package instancectl
+
+// Final review F1 (#328): what a slice owes its running services outlives
+// the control service that wrote the slice. The first asserter is stopped
+// dead between the slice write and the per-unit step (runtime.Goexit in
+// its systemctl, the in-process stand-in for the process exiting there;
+// TestRootEgressInterruptedRevoke in internal/host is the real one), and a
+// fresh asserter over the same DueDir must finish the change.
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+// egressInterrupt passes calls to next until one names unit, the first
+// per-unit step after a slice write; there the goroutine ends, as if the
+// process had exited, and nothing of the call runs.
+type egressInterrupt struct {
+ next func(context.Context, ...string) (string, error)
+ unit string
+ hit atomic.Bool
+}
+
+func (c *egressInterrupt) run(ctx context.Context, args ...string) (string, error) {
+ if slices.Contains(args, c.unit) && c.hit.CompareAndSwap(false, true) {
+ runtime.Goexit()
+ }
+ return c.next(ctx, args...)
+}
+
+// interruptedAssert runs e.Assert(host) in its own goroutine and waits for
+// it to end, at the interruption or otherwise; it reports whether the
+// interruption was hit.
+func interruptedAssert(e *EgressAsserter, in *egressInterrupt, host string) bool {
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ e.Assert(context.Background(), host)
+ }()
+ <-done
+ return in.hit.Load()
+}
+
+func readDueFile(t *testing.T, dir, slice string) (string, bool) {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join(dir, slice))
+ if os.IsNotExist(err) {
+ return "", false
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.TrimSpace(string(raw)), true
+}
+
+func TestEgressOwedChangeOutlivesTheControlService(t *testing.T) {
+ slice := SliceName(egressHost)
+ run := UnitName(RoleRun, egressHost)
+ nudge := "set-property --runtime " + run + " IPAddressAllow="
+ restart := "try-restart " + run
+
+ // box: the slice holds held, the parent holds parent, and the run unit
+ // runs in the slice. The first asserter applies p and is stopped at its
+ // first call naming the run unit; it returns the fake systemctl, the
+ // cgroup root and DueDir for the second.
+ box := func(t *testing.T, held, parent string, p EgressPolicy) (*egressCtl, string, string) {
+ t.Helper()
+ root := t.TempDir()
+ cgroupSlice(t, root, slice, true)
+ cgroupService(t, root, slice, run, true)
+ ctl := newEgressCtl()
+ ctl.setHeld(slice, held)
+ ctl.setHeld(InstancesSlice, parent)
+ ctl.active[run] = "active"
+ due := filepath.Join(t.TempDir(), "egress-due")
+
+ first := newEgressAsserter(ctl, staticSource(p, nil))
+ first.CgroupRoot, first.DueDir = root, due
+ in := &egressInterrupt{next: ctl.run, unit: run}
+ first.Systemctl = in.run
+ if !interruptedAssert(first, in, egressHost) {
+ t.Fatalf("the first asserter never reached the run unit; calls %q", ctl.takeCalls())
+ }
+ calls := ctl.takeCalls()
+ if !slices.ContainsFunc(calls, func(c string) bool { return strings.HasPrefix(c, "set-property --runtime "+slice+" ") }) {
+ t.Fatalf("fixture: the slice was not written before the interruption; calls %q", calls)
+ }
+ if slices.Contains(calls, nudge) || slices.Contains(calls, restart) {
+ t.Fatalf("fixture: the run unit was reached before the interruption; calls %q", calls)
+ }
+ return ctl, root, due
+ }
+ fresh := func(ctl *egressCtl, root, due string, p EgressPolicy) *EgressAsserter {
+ e := newEgressAsserter(ctl, staticSource(p, nil))
+ e.CgroupRoot, e.DueDir = root, due
+ e.Hosts = func() ([]string, error) { return []string{egressHost}, nil }
+ return e
+ }
+
+ t.Run("a revoke applied by the nudge: the next control service's first sweep nudges", func(t *testing.T) {
+ ctl, root, due := box(t, "10.0.5.20/32", "10.0.5.53/32", EgressPolicy{})
+ if got, ok := readDueFile(t, due, slice); !ok || got != "revoke" {
+ t.Fatalf("after the interruption the due file is %q (present %v), want revoke", got, ok)
+ }
+ e := fresh(ctl, root, due, EgressPolicy{})
+ e.Loop(context.Background(), 0) // as the control service starts: name, then sweep once
+ if calls := ctl.takeCalls(); !slices.Contains(calls, nudge) {
+ t.Fatalf("the fresh control service did not apply the revoke to the run unit; calls %q", calls)
+ }
+ if got, ok := readDueFile(t, due, slice); ok {
+ t.Fatalf("the due file is still there (%q) after the revoke reached the run unit", got)
+ }
+ // Done: the next sweep reads the slice back and touches no unit.
+ e.Sweep(context.Background())
+ wantCalls(t, ctl.takeCalls(), showCall(egressHost))
+ })
+ t.Run("a revoke to empty with no parent allow: the next control service restarts", func(t *testing.T) {
+ ctl, root, due := box(t, "10.0.5.20/32", "", EgressPolicy{})
+ e := fresh(ctl, root, due, EgressPolicy{})
+ e.Loop(context.Background(), 0)
+ if calls := ctl.takeCalls(); !slices.Contains(calls, restart) {
+ t.Fatalf("the fresh control service did not restart the run unit; calls %q", calls)
+ }
+ if rep := e.Reports()[egressHost]; rep.Detail != egressRestarted {
+ t.Fatalf("report = %+v, want detail %q", rep, egressRestarted)
+ }
+ if _, ok := readDueFile(t, due, slice); ok {
+ t.Fatal("the due file is still there after the restart")
+ }
+ })
+ t.Run("a narrowing: POST /egress on the next control service nudges", func(t *testing.T) {
+ p := EgressPolicy{Allow: []string{"10.0.5.21"}}
+ ctl, root, due := box(t, "10.0.5.20/32 10.0.5.21/32", "", p)
+ mustAssert(t, fresh(ctl, root, due, p), egressHost)
+ if calls := ctl.takeCalls(); !slices.Contains(calls, nudge) {
+ t.Fatalf("the fresh control service did not apply the narrowing to the run unit; calls %q", calls)
+ }
+ })
+ t.Run("a grant: recorded as a grant and nudged by the next control service", func(t *testing.T) {
+ p := EgressPolicy{Allow: []string{"10.0.5.20"}}
+ ctl, root, due := box(t, "", "", p)
+ if got, _ := readDueFile(t, due, slice); got != "grant" {
+ t.Fatalf("due file = %q, want grant", got)
+ }
+ fresh(ctl, root, due, p).Loop(context.Background(), 0)
+ if calls := ctl.takeCalls(); !slices.Contains(calls, nudge) || slices.Contains(calls, restart) {
+ t.Fatalf("calls %q, want the nudge and no restart", calls)
+ }
+ })
+ t.Run("a start path on the next control service whose read fails refuses", func(t *testing.T) {
+ ctl, root, due := box(t, "10.0.5.20/32", "10.0.5.53/32", EgressPolicy{})
+ e := fresh(ctl, root, due, EgressPolicy{})
+ e.Systemctl = func(ctx context.Context, args ...string) (string, error) {
+ if len(args) == 5 && args[0] == "show" && args[4] == slice {
+ return "Failed to connect to bus", os.ErrDeadlineExceeded
+ }
+ return ctl.run(ctx, args...)
+ }
+ if err := e.AssertStart(context.Background(), egressHost); err == nil {
+ t.Fatal("AssertStart went ahead though the last control service left a revoke owed")
+ }
+ })
+}
+
+func TestEgressDueDirSweepDischargesAnIdleSlice(t *testing.T) {
+ slice := SliceName(egressHost)
+ root := t.TempDir()
+ cgroupSlice(t, root, slice, false) // nothing runs in it
+ due := t.TempDir()
+ if err := os.WriteFile(filepath.Join(due, slice), []byte("revoke\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ // Not a host slice's name: never read, never removed.
+ if err := os.WriteFile(filepath.Join(due, "notes"), []byte("revoke\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{}, nil))
+ e.CgroupRoot, e.DueDir = root, due
+ e.Sweep(context.Background())
+ wantCalls(t, ctl.takeCalls()) // nothing runs: no unit is touched
+ if _, ok := readDueFile(t, due, slice); ok {
+ t.Fatal("an idle slice's owed change was not discharged")
+ }
+ if _, ok := readDueFile(t, due, "notes"); !ok {
+ t.Fatal("a file that is not a slice's was removed")
+ }
+}
+
+func TestEgressDueDirTornRecordIsARevoke(t *testing.T) {
+ slice := SliceName(egressHost)
+ run := UnitName(RoleRun, egressHost)
+ root := t.TempDir()
+ cgroupSlice(t, root, slice, true)
+ cgroupService(t, root, slice, run, true)
+ due := t.TempDir()
+ if err := os.WriteFile(filepath.Join(due, slice), []byte("gr"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ ctl := newEgressCtl()
+ ctl.active[run] = "active"
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{}, nil))
+ e.CgroupRoot, e.DueDir = root, due
+ mustAssert(t, e, egressHost)
+ // A revoke to an empty slice with no parent allow restarts; a grant
+ // would only have nudged.
+ if calls := ctl.takeCalls(); !slices.Contains(calls, "try-restart "+run) {
+ t.Fatalf("calls %q, want the run unit restarted", calls)
+ }
+}
+
+func TestEgressDueRecordFailureWritesNothing(t *testing.T) {
+ slice := SliceName(egressHost)
+ notDir := filepath.Join(t.TempDir(), "file")
+ if err := os.WriteFile(notDir, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ ctl := newEgressCtl()
+ ctl.setHeld(slice, "10.0.5.20/32")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{}, nil))
+ e.DueDir = filepath.Join(notDir, "egress-due") // its parent is a file
+ if err := e.Assert(context.Background(), egressHost); err == nil {
+ t.Fatal("Assert succeeded though the owed change could not be recorded")
+ }
+ wantCalls(t, ctl.takeCalls(), showCall(egressHost))
+ if rep := e.Reports()[egressHost]; rep.State != EgressFailing || !slices.Equal(rep.Allowed, []string{"10.0.5.20"}) {
+ t.Fatalf("report = %+v, want failing with the allow still held", rep)
+ }
+}
+
+func TestEgressDueFileIsPrivateAndGoesWhenDone(t *testing.T) {
+ slice := SliceName(egressHost)
+ run := UnitName(RoleRun, egressHost)
+ root := t.TempDir()
+ cgroupSlice(t, root, slice, true)
+ cgroupService(t, root, slice, run, true)
+ due := filepath.Join(t.TempDir(), "egress-due")
+ ctl := newEgressCtl()
+ p := EgressPolicy{Allow: []string{"10.0.5.20"}}
+ e := newEgressAsserter(ctl, staticSource(p, nil))
+ e.CgroupRoot, e.DueDir = root, due
+ in := &egressInterrupt{next: ctl.run, unit: run}
+ e.Systemctl = in.run
+ if !interruptedAssert(e, in, egressHost) {
+ t.Fatal("the asserter never reached the run unit")
+ }
+ for path, want := range map[string]os.FileMode{due: 0o700, filepath.Join(due, slice): 0o600} {
+ fi, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fi.Mode().Perm() != want {
+ t.Fatalf("%s is %v, want %v", path, fi.Mode().Perm(), want)
+ }
+ }
+ // The next control service finishes the grant: the record and the
+ // directory are gone.
+ e2 := newEgressAsserter(ctl, staticSource(p, nil))
+ e2.CgroupRoot, e2.DueDir = root, due
+ mustAssert(t, e2, egressHost)
+ if _, err := os.Lstat(due); !os.IsNotExist(err) {
+ t.Fatalf("%s is still there with nothing owed: %v", due, err)
+ }
+}