carlos / platform Public

egress: prove nothing changes on an instance with no policy (#328)

Plan 2 Task 15, the byte-identical proof (spec §7), through the real
control service, the real asserter and production's sources:

- every start path (run, sidecar, seed, gen, cmd, both populated skips,
  the claim path), before claims and under them, with the host's slice
  running a service of every role: the transcript is the Egress-nil one
  plus one read of the slice's allow; no set-property, no nudge, no
  restart;
- root's Loop, three sweeps (a named, a Hosts-named and an unnamed
  hashed slice), before and under claims, and with each first read
  failing: reads only, and no log line where the reads work;
- the agent side: the nudge sends nothing, POST /egress reads only, the
  rail never runs, the registry is unchanged, the status probe publishes
  nothing, the snapshot WriteBox stores is main's byte for byte with
  main's store requests, and the edges file is main's but for the
  documented addrs field, with main's requests (goldens made at
  bcae2a72).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev f509134b9e2712643989240e60faadb86d3aaab6 parent 9022a49
3 files changed, +606 −13
  • internal/host/egress_nopolicy_linux_test.go +390 −0
  • internal/instancectl/egress_startpaths_linux_test.go +112 −0
  • internal/instancectl/egress_startpaths_test.go +104 −13
diff --git a/internal/host/egress_nopolicy_linux_test.go b/internal/host/egress_nopolicy_linux_test.go
new file mode 100644
index 000000000..0bc8ffbd0
--- /dev/null
+++ b/internal/host/egress_nopolicy_linux_test.go
@@ -0,0 +1,390 @@
+//go:build linux
+
+package host
+
+// The agent's half of the byte-identical proof (plan 2 Task 15; spec §7:
+// "Nothing is on by default. With no policy object, every unit, slice and
+// probe line is byte-identical to today"). The start paths' and the
+// sweep's systemctl transcripts are instancectl's
+// TestStartTranscriptsUnchangedWithNoPolicy and ...Loop.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// noPolicyLongHost is longer than provision.MaxInstanceID: its slice is
+// named by a hashed instance id.
+const noPolicyLongHost = "shop-a-long-name-for-an-instance.example.com"
+
+// noPolicyBoxRows is the box the byte-identical proof publishes, every row
+// without a policy: two nested instances (one with a hashed slice), a flat
+// one, so the box is not wholly nested, a console-style row backed by a
+// named unit, whose user the rail would read, and a static row.
+//
+// The main* goldens below were made by this same function, verbatim, run
+// at main (bcae2a72, the merge base) through main's CollectBox, WriteBox
+// and edgesFileWriteClaims.
+func noPolicyBoxRows(dataDir string) []registry.Route {
+ nested := func(host, account, app string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Account: account, App: app, Channel: "stable", Hibernate: true, Status: "ready",
+ DBPath: provision.NestedDBPath(dataDir, host), Socket: provision.NestedSocket(host)}
+ }
+ flat := nested("old.example.com", "zzz", "blog")
+ flat.DBPath, flat.Socket = provision.DefaultDBPath(dataDir, flat.Host), provision.DefaultSocket(flat.Host)
+ return []registry.Route{
+ nested("shop-a.example.com", "abc", "shop"),
+ nested(noPolicyLongHost, "abc", "shop"),
+ flat,
+ {Host: "console.example.com", Kind: "instance", Account: "abc", App: "console", Addr: "127.0.0.1:8090", Backing: registry.BackingUnit, Unit: "console.service"},
+ {Host: "files.example.com", Kind: "static", Account: "abc", App: "files"},
+ }
+}
+
+// noPolicyNow is the snapshot's clock.
+var noPolicyNow = time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
+
+// noPolicyProbes are the snapshot's other probes: enough for a Metrics
+// block, the one egress would join.
+func noPolicyProbes() status.Probes {
+ return status.Probes{UpdateSettings: 1, ConfigGuard: "guarded"}
+}
+
+// mainNoPolicySnapshot is status/boxes/quiet-harbour.json as main's
+// WriteBox wrote it for noPolicyBoxRows with noPolicyProbes.
+const mainNoPolicySnapshot = `{
+ "generated_at": "2026-10-25T09:00:00Z",
+ "label": "quiet-harbour",
+ "routes": {
+ "static": 1,
+ "resident": 1,
+ "hibernating": 3,
+ "awake": null,
+ "asleep": null
+ },
+ "load": null,
+ "capacity": null,
+ "replication": {
+ "healthy": null,
+ "lag_seconds": null
+ },
+ "adoption_running": null,
+ "config_path_running": null,
+ "restart_path_running": null,
+ "expired_canaries": null,
+ "metrics": {
+ "update_settings": 1,
+ "config_guard": "guarded"
+ }
+}`
+
+// mainNoPolicyEdges is control/edges/quiet-harbour.json as main's
+// edgesFileWriteClaims wrote it for noPolicyBoxRows, with %s for its
+// generation.
+const mainNoPolicyEdges = `{"v":1,"box":"quiet-harbour","eip":"203.0.113.10","hibernation_configured":false,"serves_shared_pool":false,"accepts_inbound":false,"moves_protocol":0,"seeds_protocol":0,"generation":"%s","hosts":{"console.example.com":{"role":"home","platform":false,"account":"abc","app":"console"},"files.example.com":{"role":"home","platform":false,"account":"abc","app":"files"},"old.example.com":{"role":"home","platform":false,"account":"zzz","app":"blog"},"shop-a-long-name-for-an-instance.example.com":{"role":"home","platform":false,"account":"abc","app":"shop"},"shop-a.example.com":{"role":"home","platform":false,"account":"abc","app":"shop"}}}`
+
+// The store requests main made for them: the snapshot's write, the edges
+// file's first pass, and its second, unchanged pass.
+var (
+ mainNoPolicySnapshotOps = []string{"GET status/boxes/quiet-harbour.json", "PUT status/boxes/quiet-harbour.json"}
+ mainNoPolicyEdgesOps = [][]string{{"GET control/edges/quiet-harbour.json", "PUT control/edges/quiet-harbour.json"}, nil}
+)
+
+// noPolicyCtl is systemctl on a box where no slice holds an allow: it
+// records every call, answers a read of an allow with nothing, and
+// refuses anything else.
+type noPolicyCtl struct {
+ mu sync.Mutex
+ calls []string
+ // after is called with the count of calls made so far.
+ after func(n int)
+}
+
+func (c *noPolicyCtl) run(_ context.Context, args ...string) (string, error) {
+ c.mu.Lock()
+ c.calls = append(c.calls, strings.Join(args, " "))
+ n, after := len(c.calls), c.after
+ c.mu.Unlock()
+ if after != nil {
+ after(n)
+ }
+ if len(args) == 5 && args[0] == "show" && args[1] == "-p" && args[2] == "IPAddressAllow" && args[3] == "--value" {
+ return "\n", nil
+ }
+ return "", fmt.Errorf("unexpected systemctl %q", args)
+}
+
+func (c *noPolicyCtl) take() []string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ out := c.calls
+ c.calls = nil
+ return out
+}
+
+// takeRequests returns the store requests since the last take.
+func takeRequests(s *egressCountingStore) []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := s.seen
+ s.seen = nil
+ return out
+}
+
+// countedNudge counts the agent's POST /egress calls on their way to root.
+type countedNudge struct {
+ c *instancectl.Client
+ mu sync.Mutex
+ hosts []string
+}
+
+func (n *countedNudge) Egress(ctx context.Context, host string) error {
+ n.mu.Lock()
+ n.hosts = append(n.hosts, host)
+ n.mu.Unlock()
+ return n.c.Egress(ctx, host)
+}
+
+// TestEgressNoPolicyBoxPublishesAsMain: a box with no policy anywhere, as
+// production wires it. Root's asserter over its real source (the registry,
+// read-only; under claims the claims source) serves the real control
+// service on a socket; its Loop sweeps three times; the agent's nudge
+// ticks three times over the registry; every host is asserted through
+// POST /egress all the same; the status tick reads GET /egress through
+// the client. Then:
+//
+// - systemctl saw only reads of a populated slice's allow: no write, no
+// nudge of a running unit, no restart; the rail never ran (no read of
+// a unit's user); nothing was logged; the registry is unchanged;
+// - the agent sent no POST /egress of its own;
+// - the snapshot, written by WriteBox, is main's byte for byte (no
+// "egress" key), with main's store requests;
+// - the edges file is main's byte for byte but for the documented
+// "addrs" field (Task 8), at its place, with main's store requests:
+// a write on the first pass and none on an unchanged second.
+//
+// Its socket needs a short TMPDIR (/tmp/g).
+func TestEgressNoPolicyBoxPublishesAsMain(t *testing.T) {
+ t.Parallel()
+ for _, claims := range []bool{false, true} {
+ name := "before claims"
+ if claims {
+ name = "under claims"
+ }
+ t.Run(name, func(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ reg, dd := egressRegistry(t)
+ upsertRows(t, reg, noPolicyBoxRows(dd)...)
+ rows, err := reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ fpBefore, err := reg.SnapshotFingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cgroup := t.TempDir()
+ nested := []string{"shop-a.example.com", noPolicyLongHost}
+ for _, h := range nested {
+ populatedHostCgroup(t, cgroup, h)
+ }
+
+ // Root's production asserter, its systemctl, cgroup root, box
+ // addresses and log the test's.
+ units := &fakeUnitShow{units: map[string]string{"console.service": "User=console\nDynamicUser=no\n"}}
+ var e *instancectl.EgressAsserter
+ report := instancectl.EgressReport{}
+ if claims {
+ e = claimsEgressAsserter(registryEgressHosts(dd))
+ report = instancectl.EgressReport{State: instancectl.EgressUnderClaims, Detail: claimsEgressDetail}
+ } else {
+ path := reg.Path()
+ rs := newRegistrySource(dd, time.Now, func() ([]registry.Route, error) { return listRegistryReadOnly(path) }, units.run)
+ rs.lookupUID = fakeUsers
+ e = newEgressAsserter(rs.read, registryEgressHosts(dd))
+ }
+ ctl := &noPolicyCtl{}
+ e.Systemctl = ctl.run
+ e.CgroupRoot = cgroup
+ e.LocalAddrs = func() ([]netip.Prefix, error) {
+ return []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("10.0.1.5/32")}, nil
+ }
+ var logMu sync.Mutex
+ var logs []string
+ e.Logf = func(f string, args ...any) {
+ logMu.Lock()
+ logs = append(logs, fmt.Sprintf(f, args...))
+ logMu.Unlock()
+ }
+
+ // The control service, as runWithClaim serves it, on a socket.
+ srv := &instancectl.Server{PeerOK: func(net.Conn) error { return nil }, Logf: t.Logf, Egress: e}
+ dir, err := os.MkdirTemp("", "np")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ sock := filepath.Join(dir, "c.sock")
+ ln, err := net.Listen("unix", sock)
+ if err != nil {
+ t.Skipf("cannot bind a unix socket here (%v); run with TMPDIR=/tmp/g outside the sandbox", err)
+ }
+ srvCtx, stop := context.WithCancel(ctx)
+ served := make(chan error, 1)
+ go func() { served <- srv.Serve(srvCtx, ln) }()
+ t.Cleanup(func() {
+ stop()
+ if err := <-served; err != nil {
+ t.Error("control service:", err)
+ }
+ })
+ client := instancectl.NewClient(sock)
+
+ // Root's Loop: three sweeps, one read per populated slice each.
+ loopCtx, cancel := context.WithCancel(ctx)
+ ctl.mu.Lock()
+ ctl.after = func(n int) {
+ if n == 3*len(nested) {
+ cancel()
+ }
+ }
+ ctl.mu.Unlock()
+ done := make(chan struct{})
+ go func() { defer close(done); e.Loop(loopCtx, time.Millisecond) }()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ cancel()
+ <-done
+ t.Fatalf("Loop did not make three sweeps of reads in 10 s: %q", ctl.take())
+ }
+ ctl.mu.Lock()
+ ctl.after = nil
+ ctl.mu.Unlock()
+ var want []string
+ for range 3 {
+ for _, slice := range slices.Sorted(slices.Values([]string{instancectl.SliceName(nested[0]), instancectl.SliceName(nested[1])})) {
+ want = append(want, "show -p IPAddressAllow --value "+slice)
+ }
+ }
+ if got := ctl.take(); !slices.Equal(got, want) {
+ t.Fatalf("Loop's systemctl calls:\n got %q\n want %q", got, want)
+ }
+
+ // The agent's nudge: three ticks over the registry, sending none.
+ nudges := &countedNudge{c: client}
+ n := newEgressNudger(nudges)
+ n.logf = t.Logf
+ for range 3 {
+ n.tick(ctx, reg)
+ }
+ if len(nudges.hosts) != 0 {
+ t.Fatalf("the agent nudged root for %q", nudges.hosts)
+ }
+
+ // POST /egress for every host all the same: a read each.
+ want = nil
+ for _, rt := range rows {
+ if err := client.Egress(ctx, rt.Host); err != nil {
+ t.Fatalf("POST /egress %s: %v", rt.Host, err)
+ }
+ want = append(want, "show -p IPAddressAllow --value "+instancectl.SliceName(rt.Host))
+ }
+ if got := ctl.take(); !slices.Equal(got, want) {
+ t.Fatalf("POST /egress's systemctl calls:\n got %q\n want %q", got, want)
+ }
+ if len(units.calls) != 0 {
+ t.Fatalf("the rail read a unit's user with no policy: %q", units.calls)
+ }
+ logMu.Lock()
+ if len(logs) != 0 {
+ t.Errorf("root logged %q, want nothing", logs)
+ }
+ logMu.Unlock()
+ if fp, err := reg.SnapshotFingerprint(); err != nil || fp != fpBefore {
+ t.Fatalf("the registry changed: %s, was %s (%v)", fp, fpBefore, err)
+ }
+
+ // GET /egress through the client: the documented reports.
+ st, err := client.EgressStatus(ctx)
+ if err != nil {
+ t.Fatal("GET /egress:", err)
+ }
+ for _, rt := range rows {
+ if got, ok := st.Hosts[rt.Host]; !ok || !slices.Equal(got.Allowed, nil) || got.State != report.State || got.Detail != report.Detail || len(got.Refused) != 0 {
+ t.Fatalf("GET /egress for %s = %+v (%v), want %+v", rt.Host, got, ok, report)
+ }
+ }
+
+ // The status tick's probe, then WriteBox: main's snapshot.
+ store := &egressCountingStore{Store: release.NewDirStore(t.TempDir())}
+ probe := egressStatusProbe(client, rows, provision.PolicyReadStates())
+ if probe != nil {
+ t.Fatalf("the status probe publishes %+v for a box with no policy", probe)
+ }
+ p := noPolicyProbes()
+ p.Egress = probe
+ box := status.CollectBox(rows, p, noPolicyNow)
+ box.Label = "quiet-harbour"
+ if err := status.WriteBox(ctx, store, box); err != nil {
+ t.Fatal(err)
+ }
+ snap, _, err := store.Store.Get(ctx, "status/boxes/quiet-harbour.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(snap) != mainNoPolicySnapshot {
+ t.Fatalf("the snapshot is not main's:\n%s\nmain's:\n%s", snap, mainNoPolicySnapshot)
+ }
+ if got := takeRequests(store); !slices.Equal(got, mainNoPolicySnapshotOps) {
+ t.Fatalf("the snapshot's store requests = %q, main's %q", got, mainNoPolicySnapshotOps)
+ }
+
+ // The edges file, twice: main's bytes and requests, but for addrs.
+ addrs := func() ([]netip.Prefix, error) {
+ return []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("10.0.1.5/32"), netip.MustParsePrefix("fe80::1/128")}, nil
+ }
+ var last []byte
+ for pass, wantOps := range mainNoPolicyEdgesOps {
+ if err := edgesFileWriteClaims(ctx, store, reg, edgesFile{Box: "quiet-harbour"}, "203.0.113.10", &last, false, nil, addrs); err != nil {
+ t.Fatal(err)
+ }
+ if got := takeRequests(store); !slices.Equal(got, wantOps) {
+ t.Fatalf("edges pass %d's store requests = %q, main's %q", pass+1, got, wantOps)
+ }
+ }
+ body, _, err := store.Store.Get(ctx, "control/edges/quiet-harbour.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var probeGen struct {
+ Generation string `json:"generation"`
+ }
+ if err := json.Unmarshal(body, &probeGen); err != nil {
+ t.Fatal(err)
+ }
+ mainBody := fmt.Sprintf(mainNoPolicyEdges, probeGen.Generation)
+ const addrsField = `"addrs":["10.0.1.5","fe80::1"],`
+ if wantBody := strings.Replace(mainBody, `"generation":`, addrsField+`"generation":`, 1); string(body) != wantBody {
+ t.Fatalf("the edges file is not main's plus addrs:\n%s\nwant:\n%s", body, wantBody)
+ }
+ })
+ }
+}
diff --git a/internal/instancectl/egress_startpaths_linux_test.go b/internal/instancectl/egress_startpaths_linux_test.go
index 92448dbcf..1c611e5f0 100644
--- a/internal/instancectl/egress_startpaths_linux_test.go
+++ b/internal/instancectl/egress_startpaths_linux_test.go
@@ -3,11 +3,17 @@
package instancectl
import (
+ "context"
"errors"
+ "fmt"
"io"
"net/url"
+ "reflect"
+ "slices"
"strings"
+ "sync"
"testing"
+ "time"
"github.com/carlosframework/platform/internal/release"
)
@@ -56,3 +62,109 @@ func TestEgressAssertedBeforeStartStagedSidecar(t *testing.T) {
})
}
}
+
+// TestStartTranscriptsUnchangedWithNoPolicyLoop is the sweep's half of the
+// byte-identical proof (plan 2 Task 15; the start paths' half is
+// TestStartTranscriptsUnchangedWithNoPolicy). On main nothing sweeps the
+// slices. Here root's Loop, run for three sweeps over a box with no policy,
+// may read each populated slice's allow and nothing more: no set-property
+// on a slice or a unit, no restart, no other systemctl call, and no log
+// line. The box: a short host, a long host named through Hosts, a long
+// host nothing names (the sweep's reset path, which writes only a slice
+// that holds something), each slice running its run unit, and a slice
+// with nothing running, which is never swept. Before claims and under
+// them; and with each slice's first read failing, which with nothing
+// wanted writes nothing either (Task 2 ruling).
+func TestStartTranscriptsUnchangedWithNoPolicyLoop(t *testing.T) {
+ const short, unnamed = "shop-a.example.com", "shop-b-long-name-for-an-instance.example.com"
+ long := longEgressHost
+ if !strings.HasPrefix(SliceName(unnamed), hostSlicePrefix+"_") || SliceName(unnamed) == SliceName(long) {
+ t.Fatalf("fixture: %s is not a second hashed slice name", SliceName(unnamed))
+ }
+
+ // Main's control service has no asserter: Loop on nil returns at once.
+ (*EgressAsserter)(nil).Loop(context.Background(), time.Millisecond)
+
+ for _, a := range noPolicyAsserters() {
+ for _, firstReadFails := range []bool{false, true} {
+ name := a.name
+ if firstReadFails {
+ name += ", first read fails"
+ }
+ t.Run(name, func(t *testing.T) {
+ root := t.TempDir()
+ var populated []string
+ for _, h := range []string{short, long, unnamed} {
+ cgroupSlice(t, root, SliceName(h), true)
+ cgroupService(t, root, SliceName(h), UnitName(RoleRun, h), true)
+ populated = append(populated, SliceName(h))
+ }
+ cgroupSlice(t, root, SliceName("shop-c.example.com"), false)
+ slices.Sort(populated) // the sweep's order: cgroupfs's, by name
+
+ ctl := newEgressCtl()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var mu sync.Mutex
+ calls, failed := 0, map[string]bool{}
+ e := a.make(func(ctx context.Context, args ...string) (string, error) {
+ out, err := ctl.run(ctx, args...)
+ mu.Lock()
+ defer mu.Unlock()
+ if firstReadFails && err == nil && len(args) == 5 && args[0] == "show" && !failed[args[4]] {
+ failed[args[4]] = true
+ out, err = "Failed to get properties: Connection timed out", errors.New("exit status 1")
+ }
+ // Three sweeps of one read per populated slice: stop
+ // there. A call more or fewer shows in the transcript.
+ if calls++; calls == 3*len(populated) {
+ cancel()
+ }
+ return out, err
+ }, root)
+ e.Hosts = func() ([]string, error) { return []string{short, long}, nil }
+ var logs []string
+ e.Logf = func(f string, args ...any) {
+ mu.Lock()
+ logs = append(logs, fmt.Sprintf(f, args...))
+ mu.Unlock()
+ }
+
+ done := make(chan struct{})
+ go func() { defer close(done); e.Loop(ctx, time.Millisecond) }()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ cancel()
+ <-done
+ t.Fatalf("Loop did not make three sweeps of reads in 10 s: %q", ctl.takeCalls())
+ }
+
+ var want []string
+ for range 3 {
+ for _, slice := range populated {
+ want = append(want, "show -p IPAddressAllow --value "+slice)
+ }
+ }
+ got := ctl.takeCalls()
+ checkNoEgressWrite(t, strings.Join(got, "\n"))
+ wantCalls(t, got, want...)
+ // Every named host ends with the documented report; the
+ // unnamed slice has none.
+ if reps := e.Reports(); !reflect.DeepEqual(reps, map[string]EgressReport{short: a.report, long: a.report}) {
+ t.Fatalf("reports = %+v, want %s and %s: %+v", reps, short, long, a.report)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if !firstReadFails && len(logs) != 0 {
+ t.Fatalf("the sweeps logged %q, want nothing", logs)
+ }
+ for _, l := range logs {
+ if !strings.Contains(l, "nothing written") {
+ t.Fatalf("a failed read logged %q, want it to say nothing was written", l)
+ }
+ }
+ })
+ }
+ }
+}
diff --git a/internal/instancectl/egress_startpaths_test.go b/internal/instancectl/egress_startpaths_test.go
index 2e96f61f9..b16f9a275 100644
--- a/internal/instancectl/egress_startpaths_test.go
+++ b/internal/instancectl/egress_startpaths_test.go
@@ -7,6 +7,7 @@ import (
"net/netip"
"os"
"path/filepath"
+ "reflect"
"strings"
"sync"
"testing"
@@ -226,8 +227,81 @@ func TestEgressFailureRefusesTheStart(t *testing.T) {
}
}
-// With Egress set and no policy, the only new call on any start path is
-// the asserter's one read: nothing is written.
+// noPolicyAsserter is an asserter as a box with no policy runs it (plan 2
+// Task 15): before claims, a source with nothing for the host (no row, or
+// a row with no egress_allow); under host claims, the claims source, which
+// answers every host under_claims. Its cgroup root has the host's slice
+// running a service of every role (runningSliceRoot), so a nudge or a
+// restart, had one been made, would be in the transcript.
+type noPolicyAsserter struct {
+ name string
+ report EgressReport // what GET /egress then says for the host
+ make func(systemctl func(context.Context, ...string) (string, error), cgroupRoot string) *EgressAsserter
+}
+
+// claimsDetail is the host package's claimsEgressDetail.
+const claimsDetail = "not yet supported under claims"
+
+func noPolicyAsserters() []noPolicyAsserter {
+ return []noPolicyAsserter{
+ {name: "no policy", make: func(systemctl func(context.Context, ...string) (string, error), root string) *EgressAsserter {
+ e := startPathAsserter(systemctl, staticSource(EgressPolicy{}, nil))
+ e.CgroupRoot = root
+ return e
+ }},
+ {name: "under claims", report: EgressReport{State: EgressUnderClaims, Detail: claimsDetail},
+ make: func(systemctl func(context.Context, ...string) (string, error), root string) *EgressAsserter {
+ e := startPathAsserter(systemctl, staticSource(EgressPolicy{Closed: EgressUnderClaims, Detail: claimsDetail}, nil))
+ e.CgroupRoot = root
+ e.UnderClaims = true
+ return e
+ }},
+ }
+}
+
+// runningSliceRoot is a cgroup tree, laid out as /sys/fs/cgroup is, in
+// which host's slice is populated and runs a service of every role.
+func runningSliceRoot(t *testing.T, host string) string {
+ t.Helper()
+ root := t.TempDir()
+ slice := filepath.Join(root, parentSlices, SliceName(host))
+ for _, dir := range []string{
+ slice,
+ filepath.Join(slice, UnitName(RoleRun, host)),
+ filepath.Join(slice, UnitName(RoleSeed, host)),
+ filepath.Join(slice, UnitName(RoleSidecar, host)),
+ filepath.Join(slice, UnitName(RoleCmd, host)),
+ filepath.Join(slice, GenUnitName(host, 7)),
+ } {
+ 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)
+ }
+ }
+ return root
+}
+
+// checkNoEgressWrite: no set-property of an allow on anything (a slice or
+// a unit: the nudge), and no restart.
+func checkNoEgressWrite(t *testing.T, transcript string) {
+ t.Helper()
+ for _, c := range strings.Split(transcript, "\n") {
+ if (strings.HasPrefix(c, "set-property ") && strings.Contains(c, "IPAddressAllow=")) || strings.HasPrefix(c, "try-restart ") {
+ t.Fatalf("a box with no policy got %q:\n%s", c, transcript)
+ }
+ }
+}
+
+// The byte-identical proof (plan 2 Task 15; spec §7: "with no policy
+// object, every unit, slice and probe line is byte-identical to today").
+// Root changes a unit or slice property only through systemctl, so on
+// every start path, with Egress set and no policy, the transcript must be
+// the Egress-nil transcript (main's) plus the asserter's one read of the
+// slice's allow: no set-property (so no runtime drop-in), no nudge of a
+// running service, no restart. Before claims and under them. The sweep's
+// half is TestStartTranscriptsUnchangedWithNoPolicyLoop.
func TestStartTranscriptsUnchangedWithNoPolicy(t *testing.T) {
for _, tc := range startPathCases() {
t.Run(tc.name, func(t *testing.T) {
@@ -235,13 +309,22 @@ func TestStartTranscriptsUnchangedWithNoPolicy(t *testing.T) {
if status, body, _ := runStartPath(t, tc, off, nil); status != 200 {
t.Fatalf("Egress nil: status %d, body %q", status, body)
}
- on := tc.ctl()
- if status, body, _ := runStartPath(t, tc, on, func(s *Server) {
- s.Egress = startPathAsserter(on.run, staticSource(EgressPolicy{}, nil))
- }); status != 200 {
- t.Fatalf("Egress set: status %d, body %q", status, body)
+ for _, a := range noPolicyAsserters() {
+ t.Run(a.name, func(t *testing.T) {
+ on := tc.ctl()
+ status, body, s := runStartPath(t, tc, on, func(s *Server) {
+ s.Egress = a.make(on.run, runningSliceRoot(t, genHost))
+ })
+ if status != 200 {
+ t.Fatalf("Egress set: status %d, body %q", status, body)
+ }
+ checkNoEgressWrite(t, on.joined())
+ checkOneReadMore(t, off.joined(), on.joined(), genHost)
+ if got := s.Egress.Reports(); !reflect.DeepEqual(got, map[string]EgressReport{genHost: a.report}) {
+ t.Fatalf("reports = %+v, want %s: %+v", got, genHost, a.report)
+ }
+ })
}
- checkOneReadMore(t, off.joined(), on.joined(), genHost)
})
}
t.Run("claim", func(t *testing.T) {
@@ -249,12 +332,20 @@ func TestStartTranscriptsUnchangedWithNoPolicy(t *testing.T) {
if _, err := u.Start(context.Background(), in); err != nil {
t.Fatal(err)
}
- u2, onCtl, in2, _ := claimUnitFixture(t)
- u2.Egress = startPathAsserter(onCtl.run, staticSource(EgressPolicy{}, nil))
- if _, err := u2.Start(context.Background(), in2); err != nil {
- t.Fatal(err)
+ for _, a := range noPolicyAsserters() {
+ t.Run(a.name, func(t *testing.T) {
+ u2, onCtl, in2, _ := claimUnitFixture(t)
+ u2.Egress = a.make(onCtl.run, runningSliceRoot(t, in2.Host))
+ if _, err := u2.Start(context.Background(), in2); err != nil {
+ t.Fatal(err)
+ }
+ checkNoEgressWrite(t, onCtl.joined())
+ checkOneReadMore(t, offCtl.joined(), onCtl.joined(), in.Host)
+ if got := u2.Egress.Reports(); !reflect.DeepEqual(got, map[string]EgressReport{in2.Host: a.report}) {
+ t.Fatalf("reports = %+v, want %s: %+v", got, in2.Host, a.report)
+ }
+ })
}
- checkOneReadMore(t, offCtl.joined(), onCtl.joined(), in.Host)
})
}