carlos / platform Public

instancectl: the egress asserter (validate, read back, write on difference) (#328)

EgressAsserter owns a per-host slice's IPAddressAllow: it validates the
source's entries with egressaddr and against the box's own addresses,
reads the slice back, writes reset-then-list only on a difference, and
reports. The kernel proof's four verdicts (all yes) head egress.go: the
live path, no restart on revoke, no parent subtraction. LocalAddresses
exports the procfs reader for the agent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3b54d94875cc03d3b0a7c81c01f2be62f1da53e9 parent 6b32e92
3 files changed, +823 −0
  • internal/instancectl/egress.go +400 −0
  • internal/instancectl/egress_test.go +416 −0
  • internal/instancectl/localaddrs.go +7 −0
diff --git a/internal/instancectl/egress.go b/internal/instancectl/egress.go
new file mode 100644
index 000000000..16c070def
--- /dev/null
+++ b/internal/instancectl/egress.go
@@ -0,0 +1,400 @@
+// Kernel proof (plan 2 Task 1, TestRootEgressKernelProof in
+// internal/host/egress_kernel_rootrunner_linux_test.go), run on a real
+// root runner 2026-10-25 (runs 20261025T131239-52420b and
+// 20261025T131702-62b868, both PASS):
+//
+// revoke live: yes
+// open live: yes
+// combines with parent: yes
+// slice show is own entries only: yes
+//
+// So a slice's IPAddressAllow written with set-property --runtime takes
+// effect on the instances already running in it, both ways: Assert never
+// restarts a unit to close or open an address. A per-host slice's allow
+// adds to carlos-instances.slice's resolver allow rather than replacing
+// it. And `systemctl show -p IPAddressAllow --value <slice>` lists only
+// the slice's own entries, so the read-back is compared as it is, with
+// nothing of the parent's to subtract. systemd's read-back form for one
+// IPv4 address is "10.0.5.20/32".
+
+package instancectl
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/netip"
+ "slices"
+ "strings"
+ "sync"
+
+ "github.com/carlosframework/platform/internal/egressaddr"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// EgressPolicy is one host's desired allow as a source reads it. Root
+// validates every entry; a source never pre-filters.
+type EgressPolicy struct {
+ Allow []string // entries as stored (the registry column split on spaces)
+ Closed string // non-empty: write no allow; becomes the report's State
+ Detail string // why, when Closed is set; becomes the report's Detail (Astra plan R2-4)
+}
+
+// EgressSource reads one host's policy. A non-nil error means "could not read
+// it now": the asserter keeps the last policy it read for that host, and with
+// none cached it closes the slice.
+type EgressSource func(ctx context.Context, host string) (EgressPolicy, error)
+
+const (
+ EgressFailing = "failing" // desired and held differ after a write
+ EgressUnreadable = "unreadable" // the source could not be read, or the policy was malformed
+ EgressExpired = "expired" // the recorded expiry has passed (plan 1's policy_expires_at)
+ EgressNotNested = "not_nested" // pre-claim box not wholly nested
+ EgressUnderClaims = "under_claims" // host claims on: egress deferred (ruling 9), no allow written
+)
+
+// EgressReport is one host's read-back (spec §4.4).
+type EgressReport struct {
+ Allowed []string `json:"allowed,omitempty"` // what the slice holds, as bare addresses, sorted
+ Refused []string `json:"refused,omitempty"` // "<entry>: <reason>"
+ State string `json:"state,omitempty"` // "" when held == desired and the policy was read
+ Detail string `json:"detail,omitempty"`
+}
+
+// EgressAsserter owns each per-host slice's IPAddressAllow (#328): it
+// takes a host's desired list from Source, validates every entry with
+// egressaddr and against the box's own addresses, reads the slice back,
+// and writes only when what the slice holds differs from what is wanted.
+//
+// Every address it writes comes from Source; the host only names the
+// slice (SliceName), so nothing from a request reaches systemctl as a
+// string. A nil *EgressAsserter does nothing.
+type EgressAsserter struct {
+ Systemctl func(context.Context, ...string) (string, error)
+ Source EgressSource
+ LocalAddrs func() ([]netip.Prefix, error)
+ CgroupRoot string // Task 4's sweep
+ Hosts func() ([]string, error) // Task 4: names for slices at start
+ Logf func(string, ...any)
+
+ mu sync.Mutex
+ last map[string]EgressPolicy // host -> the last policy Source read
+ reports map[string]EgressReport // host -> its last read-back
+ names map[string]string // instance id -> host, for the sweep
+ busy map[string]*sync.Mutex // host -> held for one whole Assert
+}
+
+// Assert brings host's slice to its policy and records the report. It
+// returns an error only when the slice could not be read or written, or
+// a write did not hold: a start path refuses the start on it. A policy
+// that cannot be read or vouched for is not an error: the slice is closed
+// (or kept at the last policy read) and the report says why.
+func (e *EgressAsserter) Assert(ctx context.Context, host string) error {
+ if e == nil {
+ return nil
+ }
+ if !provision.ValidHostShape(host) {
+ return fmt.Errorf("%q is not a host", host)
+ }
+ unlock := e.lockHost(host)
+ defer unlock()
+
+ var rep EgressReport
+ pol, err := e.readSource(ctx, host)
+ if err != nil {
+ rep.State, rep.Detail = EgressUnreadable, err.Error()
+ cached, ok := e.cached(host)
+ if !ok {
+ // The source is a local file: a fresh control service that
+ // cannot read it closes rather than keeping an allow it cannot
+ // vouch for, and reopens on the next good read.
+ cached = EgressPolicy{Closed: EgressUnreadable}
+ }
+ pol = cached
+ } else {
+ e.remember(host, pol)
+ }
+
+ var want []netip.Prefix
+ if pol.Closed != "" {
+ if rep.State == "" {
+ rep.State, rep.Detail = pol.Closed, pol.Detail
+ }
+ } else {
+ var tooMany string
+ want, rep.Refused, tooMany = e.desired(host, pol.Allow)
+ if tooMany != "" && rep.State == "" {
+ rep.State, rep.Detail = EgressUnreadable, tooMany
+ }
+ }
+
+ slice := SliceName(host)
+ held, readErr := e.readBack(ctx, slice)
+ if readErr == nil && held.equal(want) {
+ rep.Allowed = held.addrs()
+ e.record(host, rep)
+ return nil
+ }
+ if readErr != nil {
+ // A read-back that fails is a difference: the write below is
+ // what is wanted either way, and the read after it decides.
+ e.logf("egress: %s: read back: %v", slice, readErr)
+ }
+
+ args := []string{"set-property", "--runtime", slice, "IPAddressAllow="}
+ if len(want) > 0 {
+ list := make([]string, len(want))
+ for i, p := range want {
+ list[i] = p.String()
+ }
+ args = append(args, "IPAddressAllow="+strings.Join(list, " "))
+ }
+ if out, err := e.Systemctl(ctx, args...); err != nil {
+ rep.State, rep.Detail = EgressFailing, fmt.Sprintf("set-property: %s: %v", strings.TrimSpace(out), err)
+ e.record(host, rep)
+ return fmt.Errorf("%s: %s", slice, rep.Detail)
+ }
+ held, readErr = e.readBack(ctx, slice)
+ if readErr != nil {
+ rep.State, rep.Detail = EgressFailing, "read back after the write: "+readErr.Error()
+ e.record(host, rep)
+ return fmt.Errorf("%s: %s", slice, rep.Detail)
+ }
+ rep.Allowed = held.addrs()
+ if !held.equal(want) {
+ rep.State, rep.Detail = EgressFailing, fmt.Sprintf("after the write the slice holds %s, not %s", held.text(), prefixesText(want))
+ e.record(host, rep)
+ e.logf("egress: %s: %s", slice, rep.Detail)
+ return fmt.Errorf("%s: %s", slice, rep.Detail)
+ }
+ e.logf("egress: %s: allow is now %s", slice, prefixesText(want))
+ e.record(host, rep)
+ return nil
+}
+
+// Reports is a copy of every host's last report.
+func (e *EgressAsserter) Reports() map[string]EgressReport {
+ if e == nil {
+ return nil
+ }
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ out := make(map[string]EgressReport, len(e.reports))
+ for h, r := range e.reports {
+ r.Allowed = slices.Clone(r.Allowed)
+ r.Refused = slices.Clone(r.Refused)
+ out[h] = r
+ }
+ return out
+}
+
+// desired validates a policy's entries in order: egressaddr.Parse, then
+// egressaddr.Allowed, then not one of the box's own addresses. It returns
+// the full-length prefixes to write, sorted, and a refusal per entry
+// refused. More than egressaddr.MaxAllow accepted closes them all, and
+// tooMany says so. When the box's addresses cannot be read, no entry is
+// accepted: an allow that might name the box itself is never written.
+func (e *EgressAsserter) desired(host string, allow []string) (want []netip.Prefix, refused []string, tooMany string) {
+ local, lerr := e.localAddrs()
+ if lerr != nil {
+ e.logf("egress: %s: this box's addresses: %v; every entry is closed", host, lerr)
+ }
+ seen := map[netip.Addr]bool{}
+ for _, s := range allow {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ continue
+ }
+ a, err := egressaddr.Parse(s)
+ if err == nil && seen[a] {
+ continue
+ }
+ if err == nil {
+ seen[a] = true
+ err = egressaddr.Allowed(a)
+ }
+ if err != nil {
+ // egressaddr's errors already name the address.
+ refused = append(refused, err.Error())
+ continue
+ }
+ if lerr != nil {
+ refused = append(refused, s+": this box's addresses could not be read")
+ continue
+ }
+ if lp, ok := isLocal(a, local); ok {
+ refused = append(refused, fmt.Sprintf("%s: an address of this box (%s)", s, lp))
+ continue
+ }
+ want = append(want, netip.PrefixFrom(a, a.BitLen()))
+ }
+ if len(want) > egressaddr.MaxAllow {
+ return nil, refused, fmt.Sprintf("the policy has more than %d addresses (%d); every one is closed", egressaddr.MaxAllow, len(want))
+ }
+ slices.SortFunc(want, comparePrefix)
+ return want, refused, ""
+}
+
+// heldSet is a slice's IPAddressAllow as read back: a set of masked
+// prefixes, and any token that did not parse.
+type heldSet struct {
+ set map[netip.Prefix]bool
+ unknown []string
+}
+
+// readBack reads the slice's own IPAddressAllow. systemd prints it in
+// its own form (its order, a bare address or /32, IPv6 written its way),
+// so each token is parsed: a bare address is its full-length prefix.
+func (e *EgressAsserter) readBack(ctx context.Context, slice string) (heldSet, error) {
+ out, err := e.Systemctl(ctx, "show", "-p", "IPAddressAllow", "--value", slice)
+ if err != nil {
+ return heldSet{}, fmt.Errorf("%s: %v", strings.TrimSpace(out), err)
+ }
+ h := heldSet{set: map[netip.Prefix]bool{}}
+ for _, tok := range strings.Fields(out) {
+ if p, ok := parseHeld(tok); ok {
+ h.set[p] = true
+ } else {
+ h.unknown = append(h.unknown, tok)
+ }
+ }
+ return h, nil
+}
+
+func parseHeld(tok string) (netip.Prefix, bool) {
+ if strings.Contains(tok, "/") {
+ p, err := netip.ParsePrefix(tok)
+ if err != nil {
+ return netip.Prefix{}, false
+ }
+ return p.Masked(), true
+ }
+ a, err := netip.ParseAddr(tok)
+ if err != nil || a.Zone() != "" {
+ return netip.Prefix{}, false
+ }
+ return netip.PrefixFrom(a, a.BitLen()), true
+}
+
+// equal is true when the slice holds exactly want; a token that did not
+// parse makes it unequal.
+func (h heldSet) equal(want []netip.Prefix) bool {
+ if len(h.unknown) > 0 || len(h.set) != len(want) {
+ return false
+ }
+ for _, p := range want {
+ if !h.set[p] {
+ return false
+ }
+ }
+ return true
+}
+
+// addrs is the held list for the report: a full-length prefix as its
+// bare address, anything else as systemd printed it, sorted.
+func (h heldSet) addrs() []string {
+ ps := make([]netip.Prefix, 0, len(h.set))
+ for p := range h.set {
+ ps = append(ps, p)
+ }
+ slices.SortFunc(ps, comparePrefix)
+ var out []string
+ for _, p := range ps {
+ if p.IsSingleIP() {
+ out = append(out, p.Addr().String())
+ } else {
+ out = append(out, p.String())
+ }
+ }
+ return append(out, slices.Sorted(slices.Values(h.unknown))...)
+}
+
+func (h heldSet) text() string {
+ if s := h.addrs(); len(s) > 0 {
+ return strings.Join(s, " ")
+ }
+ return "nothing"
+}
+
+func prefixesText(ps []netip.Prefix) string {
+ if len(ps) == 0 {
+ return "nothing"
+ }
+ s := make([]string, len(ps))
+ for i, p := range ps {
+ s[i] = p.String()
+ }
+ return strings.Join(s, " ")
+}
+
+func comparePrefix(a, b netip.Prefix) int {
+ if c := a.Addr().Compare(b.Addr()); c != 0 {
+ return c
+ }
+ return a.Bits() - b.Bits()
+}
+
+func (e *EgressAsserter) readSource(ctx context.Context, host string) (EgressPolicy, error) {
+ if e.Source == nil {
+ return EgressPolicy{}, errors.New("no egress source")
+ }
+ return e.Source(ctx, host)
+}
+
+func (e *EgressAsserter) localAddrs() ([]netip.Prefix, error) {
+ if e.LocalAddrs == nil {
+ return nil, errors.New("no way to list them")
+ }
+ return e.LocalAddrs()
+}
+
+// lockHost serialises Asserts of one host, the source read included, so
+// the last write is always from the last read.
+func (e *EgressAsserter) lockHost(host string) func() {
+ e.mu.Lock()
+ if e.busy == nil {
+ e.busy = map[string]*sync.Mutex{}
+ }
+ m := e.busy[host]
+ if m == nil {
+ m = &sync.Mutex{}
+ e.busy[host] = m
+ }
+ e.mu.Unlock()
+ m.Lock()
+ return m.Unlock
+}
+
+func (e *EgressAsserter) cached(host string) (EgressPolicy, bool) {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ p, ok := e.last[host]
+ return p, ok
+}
+
+func (e *EgressAsserter) remember(host string, p EgressPolicy) {
+ p.Allow = slices.Clone(p.Allow)
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if e.last == nil {
+ e.last = map[string]EgressPolicy{}
+ }
+ e.last[host] = p
+}
+
+func (e *EgressAsserter) record(host string, r EgressReport) {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if e.reports == nil {
+ e.reports = map[string]EgressReport{}
+ e.names = map[string]string{}
+ }
+ e.reports[host] = r
+ e.names[provision.InstanceID(host)] = host
+}
+
+func (e *EgressAsserter) logf(format string, args ...any) {
+ if e.Logf != nil {
+ e.Logf(format, args...)
+ }
+}
diff --git a/internal/instancectl/egress_test.go b/internal/instancectl/egress_test.go
new file mode 100644
index 000000000..d1284bb7f
--- /dev/null
+++ b/internal/instancectl/egress_test.go
@@ -0,0 +1,416 @@
+package instancectl
+
+import (
+ "context"
+ "errors"
+ "net/netip"
+ "reflect"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+)
+
+const egressHost = "shop-a.example.com"
+
+// egressCtl is a fake systemctl for the asserter: it records every call
+// and answers `show -p IPAddressAllow --value <slice>` with what the slice
+// holds, which a `set-property --runtime <slice> IPAddressAllow= ...`
+// replaces (the reset first, then the list, as systemd applies them).
+type egressCtl struct {
+ mu sync.Mutex
+ calls []string
+ held map[string]string // slice -> show's answer
+ ignore bool // accept set-property but change nothing
+}
+
+func newEgressCtl() *egressCtl { return &egressCtl{held: map[string]string{}} }
+
+func (f *egressCtl) run(_ context.Context, args ...string) (string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls = append(f.calls, strings.Join(args, " "))
+ switch {
+ case len(args) == 5 && args[0] == "show" && args[1] == "-p" && args[2] == "IPAddressAllow" && args[3] == "--value":
+ return f.held[args[4]] + "\n", nil
+ case len(args) >= 4 && args[0] == "set-property" && args[1] == "--runtime":
+ if f.ignore {
+ return "", nil
+ }
+ var v string
+ for _, a := range args[3:] {
+ val, ok := strings.CutPrefix(a, "IPAddressAllow=")
+ if !ok {
+ return "", errors.New("unexpected property " + a)
+ }
+ v = val // "" is the reset; the next assignment appends to it
+ }
+ f.held[args[2]] = v
+ return "", nil
+ }
+ return "", errors.New("unexpected call: " + strings.Join(args, " "))
+}
+
+func (f *egressCtl) setHeld(slice, v string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.held[slice] = v
+}
+
+func (f *egressCtl) takeCalls() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ c := f.calls
+ f.calls = nil
+ return c
+}
+
+func (f *egressCtl) sets() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []string
+ for _, c := range f.calls {
+ if strings.HasPrefix(c, "set-property ") {
+ out = append(out, c)
+ }
+ }
+ return out
+}
+
+// staticSource answers every host with one policy (or one error).
+func staticSource(p EgressPolicy, err error) EgressSource {
+ return func(context.Context, string) (EgressPolicy, error) { return p, err }
+}
+
+func newEgressAsserter(ctl *egressCtl, src EgressSource) *EgressAsserter {
+ return &EgressAsserter{
+ Systemctl: ctl.run,
+ Source: src,
+ LocalAddrs: func() ([]netip.Prefix, error) { return []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}, nil },
+ Logf: func(string, ...any) {},
+ }
+}
+
+func showCall(host string) string { return "show -p IPAddressAllow --value " + SliceName(host) }
+
+func setCall(host string, list ...string) string {
+ c := "set-property --runtime " + SliceName(host) + " IPAddressAllow="
+ if len(list) > 0 {
+ c += " IPAddressAllow=" + strings.Join(list, " ")
+ }
+ return c
+}
+
+func mustAssert(t *testing.T, e *EgressAsserter, host string) EgressReport {
+ t.Helper()
+ if err := e.Assert(context.Background(), host); err != nil {
+ t.Fatalf("Assert(%s): %v", host, err)
+ }
+ return e.Reports()[host]
+}
+
+func wantCalls(t *testing.T, got []string, want ...string) {
+ t.Helper()
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("systemctl calls:\n got %q\n want %q", got, want)
+ }
+}
+
+func TestEgressNoPolicyWritesNothing(t *testing.T) {
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{}, nil))
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.takeCalls(), showCall(egressHost))
+ if !reflect.DeepEqual(rep, EgressReport{}) {
+ t.Fatalf("report = %+v, want {}", rep)
+ }
+}
+
+func TestEgressWritesResetThenList(t *testing.T) {
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"fd00:5::20", "10.0.5.20", "10.0.5.20"}}, nil))
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.takeCalls(),
+ showCall(egressHost),
+ setCall(egressHost, "10.0.5.20/32", "fd00:5::20/128"),
+ showCall(egressHost))
+ if want := (EgressReport{Allowed: []string{"10.0.5.20", "fd00:5::20"}}); !reflect.DeepEqual(rep, want) {
+ t.Fatalf("report = %+v, want %+v", rep, want)
+ }
+}
+
+func TestEgressRefusesEachBadEntryWithItsReason(t *testing.T) {
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{
+ "10.0.5.20", "127.0.0.1", "8.8.8.8", "10.0.5.20:5432", "::ffff:10.0.5.21",
+ }}, nil))
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost, "10.0.5.20/32", "10.0.5.21/32"))
+ // egressaddr's errors already name the address (C4): carried as-is.
+ want := []string{
+ "127.0.0.1 is a loopback address",
+ "8.8.8.8 is a public address and is already reachable. No allow is needed",
+ `"10.0.5.20:5432" has a port. An allow opens an address, never a port`,
+ }
+ if !reflect.DeepEqual(rep.Refused, want) {
+ t.Fatalf("Refused = %q, want %q", rep.Refused, want)
+ }
+ if want := []string{"10.0.5.20", "10.0.5.21"}; !reflect.DeepEqual(rep.Allowed, want) || rep.State != "" {
+ t.Fatalf("report = %+v, want Allowed %q and no state", rep, want)
+ }
+}
+
+func TestEgressDropsTheBoxsOwnAddress(t *testing.T) {
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20", "10.0.5.21"}}, nil))
+ e.LocalAddrs = func() ([]netip.Prefix, error) {
+ return []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("10.0.5.20/32")}, nil
+ }
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost, "10.0.5.21/32"))
+ if want := []string{"10.0.5.20: an address of this box (10.0.5.20/32)"}; !reflect.DeepEqual(rep.Refused, want) {
+ t.Fatalf("Refused = %q, want %q", rep.Refused, want)
+ }
+ if want := []string{"10.0.5.21"}; !reflect.DeepEqual(rep.Allowed, want) {
+ t.Fatalf("Allowed = %q, want %q", rep.Allowed, want)
+ }
+}
+
+func TestEgressClosesWhenTheBoxsAddressesCannotBeRead(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.setHeld(SliceName(egressHost), "10.0.5.20/32")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20", "fd00:5::20"}}, nil))
+ e.LocalAddrs = func() ([]netip.Prefix, error) { return nil, errors.New("/proc/net/fib_trie: permission denied") }
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost))
+ want := []string{
+ "10.0.5.20: this box's addresses could not be read",
+ "fd00:5::20: this box's addresses could not be read",
+ }
+ if !reflect.DeepEqual(rep.Refused, want) {
+ t.Fatalf("Refused = %q, want %q", rep.Refused, want)
+ }
+ if rep.Allowed != nil {
+ t.Fatalf("Allowed = %q, want none", rep.Allowed)
+ }
+}
+
+func TestEgressMoreThanEightClosesAll(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.setHeld(SliceName(egressHost), "10.0.5.20/32")
+ var nine []string
+ for i := 20; i < 29; i++ {
+ nine = append(nine, "10.0.5."+strconv.Itoa(i))
+ }
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: nine}, nil))
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost))
+ if rep.State != EgressUnreadable || !strings.Contains(rep.Detail, "more than 8") {
+ t.Fatalf("report = %+v, want state %q and a detail saying more than 8", rep, EgressUnreadable)
+ }
+ if rep.Allowed != nil {
+ t.Fatalf("Allowed = %q, want none", rep.Allowed)
+ }
+}
+
+func TestEgressClosedPolicyResets(t *testing.T) {
+ for _, state := range []string{EgressExpired, EgressNotNested, EgressUnderClaims} {
+ t.Run(state, func(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.setHeld(SliceName(egressHost), "10.0.5.20/32")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}, Closed: state}, nil))
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost))
+ if rep.State != state || rep.Allowed != nil {
+ t.Fatalf("report = %+v, want state %q and nothing allowed", rep, state)
+ }
+ })
+ }
+}
+
+func TestEgressClosedPolicyCarriesItsDetail(t *testing.T) {
+ ctl := newEgressCtl()
+ detail := "the policy expired at 2026-10-24T00:00:00Z"
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Closed: EgressExpired, Detail: detail}, nil))
+ rep := mustAssert(t, e, egressHost)
+ if rep.State != "expired" || rep.Detail != detail {
+ t.Fatalf("report = %+v, want state expired and detail %q", rep, detail)
+ }
+
+ e = newEgressAsserter(ctl, staticSource(EgressPolicy{}, errors.New("registry: locked")))
+ rep = mustAssert(t, e, egressHost)
+ if rep.State != EgressUnreadable || !strings.Contains(rep.Detail, "registry: locked") {
+ t.Fatalf("report = %+v, want state %q and a detail naming the source error", rep, EgressUnreadable)
+ }
+}
+
+func TestEgressUnderClaimsResetsAHeldAllow(t *testing.T) {
+ ctl := newEgressCtl()
+ held, empty := "shop-a.example.com", "shop-b.example.com"
+ ctl.setHeld(SliceName(held), "10.0.5.20/32")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Closed: EgressUnderClaims}, nil))
+
+ rep := mustAssert(t, e, held)
+ wantCalls(t, ctl.takeCalls(), showCall(held), setCall(held), showCall(held))
+ if rep.State != EgressUnderClaims || rep.Allowed != nil {
+ t.Fatalf("held slice: report = %+v, want state %q and nothing allowed", rep, EgressUnderClaims)
+ }
+
+ rep = mustAssert(t, e, empty)
+ wantCalls(t, ctl.takeCalls(), showCall(empty))
+ if rep.State != EgressUnderClaims || rep.Allowed != nil {
+ t.Fatalf("empty slice: report = %+v, want state %q and nothing allowed", rep, EgressUnderClaims)
+ }
+}
+
+func TestEgressReadBackFormsAreOneSet(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.setHeld(SliceName(egressHost), "fd00:5:0:0:0:0:0:20/128 10.0.5.20")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20", "fd00:5::20"}}, nil))
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.takeCalls(), showCall(egressHost))
+ if want := (EgressReport{Allowed: []string{"10.0.5.20", "fd00:5::20"}}); !reflect.DeepEqual(rep, want) {
+ t.Fatalf("report = %+v, want %+v", rep, want)
+ }
+}
+
+func TestEgressReadBackUnparseableTokenIsADifference(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.setHeld(SliceName(egressHost), "10.0.5.20/32 localhost")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost, "10.0.5.20/32"))
+ if want := []string{"10.0.5.20"}; !reflect.DeepEqual(rep.Allowed, want) {
+ t.Fatalf("Allowed = %q, want %q", rep.Allowed, want)
+ }
+}
+
+func TestEgressFailingAfterAWriteThatDoesNotHold(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.ignore = true
+ ctl.setHeld(SliceName(egressHost), "10.0.5.21/32")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ if err := e.Assert(context.Background(), egressHost); err == nil {
+ t.Fatal("Assert = nil, want an error when the write does not hold")
+ }
+ rep := e.Reports()[egressHost]
+ if rep.State != EgressFailing {
+ t.Fatalf("State = %q, want %q", rep.State, EgressFailing)
+ }
+ if want := []string{"10.0.5.21"}; !reflect.DeepEqual(rep.Allowed, want) {
+ t.Fatalf("Allowed = %q, want what show returned, %q", rep.Allowed, want)
+ }
+}
+
+func TestEgressSourceErrorKeepsTheLastPolicy(t *testing.T) {
+ ctl := newEgressCtl()
+ var srcErr error
+ e := newEgressAsserter(ctl, func(context.Context, string) (EgressPolicy, error) {
+ if srcErr != nil {
+ return EgressPolicy{}, srcErr
+ }
+ return EgressPolicy{Allow: []string{"10.0.5.20"}}, nil
+ })
+ mustAssert(t, e, egressHost)
+ ctl.takeCalls()
+
+ srcErr = errors.New("registry: locked")
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.takeCalls(), showCall(egressHost))
+ if rep.State != EgressUnreadable || !reflect.DeepEqual(rep.Allowed, []string{"10.0.5.20"}) {
+ t.Fatalf("report = %+v, want state %q and Allowed [10.0.5.20]", rep, EgressUnreadable)
+ }
+}
+
+func TestEgressNoCacheAndSourceErrorCloses(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.setHeld(SliceName(egressHost), "10.0.5.20/32")
+ var srcErr = errors.New("registry: locked")
+ e := newEgressAsserter(ctl, func(context.Context, string) (EgressPolicy, error) {
+ if srcErr != nil {
+ return EgressPolicy{}, srcErr
+ }
+ return EgressPolicy{Allow: []string{"10.0.5.20"}}, nil
+ })
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost))
+ if rep.State != EgressUnreadable || rep.Allowed != nil {
+ t.Fatalf("report = %+v, want state %q and nothing allowed", rep, EgressUnreadable)
+ }
+ ctl.takeCalls()
+
+ srcErr = nil
+ rep = mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost, "10.0.5.20/32"))
+ if want := (EgressReport{Allowed: []string{"10.0.5.20"}}); !reflect.DeepEqual(rep, want) {
+ t.Fatalf("report = %+v, want %+v", rep, want)
+ }
+}
+
+func TestEgressNilAsserterIsANoOp(t *testing.T) {
+ var e *EgressAsserter
+ if err := e.Assert(context.Background(), egressHost); err != nil {
+ t.Fatalf("nil Assert = %v, want nil", err)
+ }
+ if r := e.Reports(); r != nil {
+ t.Fatalf("nil Reports = %v, want nil", r)
+ }
+}
+
+func TestEgressReportsIsACopy(t *testing.T) {
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ rep := mustAssert(t, e, egressHost)
+ rep.Allowed[0] = "10.0.5.99"
+ r := e.Reports()
+ delete(r, egressHost)
+ if got := e.Reports()[egressHost].Allowed; !reflect.DeepEqual(got, []string{"10.0.5.20"}) {
+ t.Fatalf("Reports after the caller changed its copy: Allowed = %q", got)
+ }
+}
+
+func TestEgressReadBackErrorStillWrites(t *testing.T) {
+ ctl := newEgressCtl()
+ ctl.setHeld(SliceName(egressHost), "10.0.5.21/32")
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{}, nil))
+ first := true
+ e.Systemctl = func(ctx context.Context, args ...string) (string, error) {
+ out, err := ctl.run(ctx, args...)
+ if args[0] == "show" && first {
+ first = false
+ return "Failed to get properties", errors.New("exit status 1")
+ }
+ return out, err
+ }
+ rep := mustAssert(t, e, egressHost)
+ wantCalls(t, ctl.sets(), setCall(egressHost))
+ if !reflect.DeepEqual(rep, EgressReport{}) {
+ t.Fatalf("report = %+v, want {}", rep)
+ }
+}
+
+func TestEgressWriteErrorIsFailing(t *testing.T) {
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ e.Systemctl = func(ctx context.Context, args ...string) (string, error) {
+ if args[0] == "set-property" {
+ return "Failed to set unit properties", errors.New("exit status 1")
+ }
+ return ctl.run(ctx, args...)
+ }
+ if err := e.Assert(context.Background(), egressHost); err == nil {
+ t.Fatal("Assert = nil, want the set-property error")
+ }
+ if rep := e.Reports()[egressHost]; rep.State != EgressFailing || !strings.Contains(rep.Detail, "Failed to set unit properties") {
+ t.Fatalf("report = %+v, want state %q naming systemctl's output", rep, EgressFailing)
+ }
+}
+
+func TestEgressRefusesABadHost(t *testing.T) {
+ ctl := newEgressCtl()
+ e := newEgressAsserter(ctl, staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil))
+ if err := e.Assert(context.Background(), "../x y"); err == nil {
+ t.Fatal("Assert(bad host) = nil, want an error")
+ }
+ wantCalls(t, ctl.takeCalls())
+}
diff --git a/internal/instancectl/localaddrs.go b/internal/instancectl/localaddrs.go
index 7b152dd00..4be41e2ec 100644
--- a/internal/instancectl/localaddrs.go
+++ b/internal/instancectl/localaddrs.go
@@ -125,3 +125,10 @@ func isLocal(a netip.Addr, local []netip.Prefix) (netip.Prefix, bool) {
}
return netip.Prefix{}, false
}
+
+// LocalAddresses is everything that routes to this box, read from
+// procfs as the resolver allow reads it: the egress asserter's
+// LocalAddrs, and the agent's list of the box's addresses.
+func LocalAddresses() ([]netip.Prefix, error) {
+ return localPrefixes(fibTriePath, ifInet6Path)
+}