| 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) |
| + } |
| + }) |
| + } |
| +} |