host: the egress witnesses' fixtures move to their own file (#328)
Review fix round 1, minor: the target namespace, the tenants, the pre-claim box and their helpers move unchanged from egress_startpaths_rootrunner_linux_test.go into egress_fixtures_rootrunner_linux_test.go (same build tags). No behaviour changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+989
−960
internal/host/egress_fixtures_rootrunner_linux_test.go+986 −0internal/host/egress_startpaths_rootrunner_linux_test.go+3 −960
CI failed — run details
diff --git a/internal/host/egress_fixtures_rootrunner_linux_test.go b/internal/host/egress_fixtures_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..ff381a412 |
| --- /dev/null |
| +++ b/internal/host/egress_fixtures_rootrunner_linux_test.go |
| @@ -0,0 +1,986 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "io/fs" |
| + "net" |
| + "net/http" |
| + "net/netip" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "runtime" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// Fixtures for the egress witnesses (#328, plan 2 Task 13; Task 14 uses |
| +// them too): the target namespace, the tenants, the pre-claim box and its |
| +// helpers. The witnesses are in egress_startpaths_rootrunner_linux_test.go. |
| + |
| +// Production-wired egress witnesses (#328, plan 2 Task 13). Every test |
| +// here drives the real control service (instancectl.Server) over its |
| +// unix socket, with the real egress asserter (newEgressAsserter over the |
| +// pre-claim registry source, or the claims source), and real units from |
| +// the embedded templates, run by systemd as the carlos user. |
| +// |
| +// Network: the tests reach nothing beyond their own target fixture, |
| +// egressTargetNetns: a network namespace behind a veth pair, holding the |
| +// target addresses and the listeners on them. The tenants are this test |
| +// binary (plan14-tenant, or egress-dial below) and dial only those |
| +// listeners. |
| + |
| +const ( |
| + egressTestHost = "shop-a.example.com" |
| + // egressNetns and its veth pair are this task's own names (ruling C16: |
| + // Task 1's kernel proof uses the dummy link carlos-egr0 on the box, so |
| + // the host end here is carlos-egr1, never carlos-egr0). |
| + egressNetns = "carlos-egr" |
| + egressHostLink = "carlos-egr1" |
| + egressNsLink = "carlos-egr1n" |
| +) |
| + |
| +// egressTargets are the addresses egressTargetNetns puts in its namespace. |
| +var egressTargets = []string{"10.0.5.20", "10.0.5.21", "fd00:5::20"} |
| + |
| +// The egress-dial payload: a oneshot tenant (seed, cmd) that dials one |
| +// host:port and exits 0 when it connected, 3 when it did not. It runs |
| +// before TestMain, so the unit's ExecMainStatus is the dial's answer. |
| +func init() { |
| + if len(os.Args) == 3 && os.Args[1] == "egress-dial" { |
| + c, err := net.DialTimeout("tcp", os.Args[2], 2*time.Second) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "egress-dial:", err) |
| + os.Exit(3) |
| + } |
| + c.Close() |
| + os.Exit(0) |
| + } |
| +} |
| + |
| +// egressRootPrereqs fails, never skips, without real root, systemd as |
| +// PID 1, cgroup v2, ip and systemctl. |
| +func egressRootPrereqs(t *testing.T) { |
| + t.Helper() |
| + if os.Geteuid() != 0 { |
| + t.Fatal("needs real root") |
| + } |
| + if pid1, err := os.ReadFile("/proc/1/comm"); err != nil || strings.TrimSpace(string(pid1)) != "systemd" { |
| + t.Fatalf("needs systemd as PID 1: %q %v", pid1, err) |
| + } |
| + var st unix.Statfs_t |
| + if err := unix.Statfs("/sys/fs/cgroup", &st); err != nil || st.Type != unix.CGROUP2_SUPER_MAGIC { |
| + t.Fatalf("needs cgroup v2 at /sys/fs/cgroup: type %#x %v", st.Type, err) |
| + } |
| + for _, tool := range []string{"ip", "systemctl", "journalctl"} { |
| + if _, err := exec.LookPath(tool); err != nil { |
| + t.Fatal("needs", tool, err) |
| + } |
| + } |
| +} |
| + |
| +func egressCtl(args ...string) (string, error) { |
| + out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + return strings.TrimSpace(string(out)), err |
| +} |
| + |
| +func egressMustCtl(t *testing.T, args ...string) string { |
| + t.Helper() |
| + out, err := egressCtl(args...) |
| + if err != nil { |
| + t.Fatalf("systemctl %s: %v: %s", strings.Join(args, " "), err, out) |
| + } |
| + return out |
| +} |
| + |
| +func egressShow(t *testing.T, unit, prop string) string { |
| + t.Helper() |
| + return egressMustCtl(t, "show", "-p", prop, "--value", unit) |
| +} |
| + |
| +func egressJournal(unit string) string { |
| + out, _ := exec.Command("journalctl", "-u", unit, "--no-pager", "-n", "40").CombinedOutput() |
| + return string(out) |
| +} |
| + |
| +func egressIP(t *testing.T, args ...string) { |
| + t.Helper() |
| + if out, err := exec.Command("ip", args...).CombinedOutput(); err != nil { |
| + t.Fatalf("ip %s: %v: %s", strings.Join(args, " "), err, out) |
| + } |
| +} |
| + |
| +// egressTemplateDeny is the IPAddressDeny= list of the embedded instance |
| +// template, verbatim (keywords included: only the unit-file parser takes |
| +// them, which is why the tenants here are unit files, never systemd-run). |
| +func egressTemplateDeny(t *testing.T) string { |
| + t.Helper() |
| + raw, err := unitsFS.ReadFile("units/carlos-instance@.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var deny string |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + if v, ok := strings.CutPrefix(line, "IPAddressDeny="); ok { |
| + if deny != "" { |
| + t.Fatal("template carries more than one IPAddressDeny= line") |
| + } |
| + deny = v |
| + } |
| + } |
| + if deny == "" { |
| + t.Fatal("template carries no IPAddressDeny= line") |
| + } |
| + return deny |
| +} |
| + |
| +// egressTargetNetns is the egress target: a network namespace carlos-egr |
| +// behind a veth pair (carlos-egr1 on the box, carlos-egr1n inside), so the |
| +// targets are reachable from the box but are NOT addresses of the box |
| +// (Astra plan R1-6): the asserter's production validation, its check |
| +// against LocalAddresses included, stays on. |
| +// |
| +// - box side: 10.0.5.1/32 and fd00:5::1/128 on carlos-egr1, with routes |
| +// to 10.0.5.20, 10.0.5.21 (src 10.0.5.1) and fd00:5::20 (src |
| +// fd00:5::1) through it; |
| +// - namespace side: the three targets on carlos-egr1n, routes back to |
| +// 10.0.5.1 and fd00:5::1, lo up; |
| +// - a TCP listener on each target, opened inside the namespace and |
| +// served by this process. |
| +// |
| +// It returns each target's dialable host:port, keyed by address, after |
| +// checking that each answers from the box and that LocalAddresses holds |
| +// none of them. Everything is removed in t.Cleanup: listeners, the veth |
| +// pair and the namespace. |
| +func egressTargetNetns(t *testing.T) map[string]string { |
| + t.Helper() |
| + addrs, _ := egressTargetNetnsClosable(t) |
| + return addrs |
| +} |
| + |
| +// egressTargetNetnsClosable is egressTargetNetns with its teardown, for a |
| +// test that must have the fixture gone before it goes on: `ip netns add` |
| +// bind-mounts the namespace at /run/netns, and the root generation census |
| +// (generationMounts) refuses any nsfs mount on purpose. Calling close, or |
| +// the test's end, tears it down once, last-made first. |
| +func egressTargetNetnsClosable(t *testing.T) (map[string]string, func()) { |
| + t.Helper() |
| + var steps []func() |
| + var once sync.Once |
| + closeAll := func() { |
| + once.Do(func() { |
| + for i := len(steps) - 1; i >= 0; i-- { |
| + steps[i]() |
| + } |
| + }) |
| + } |
| + t.Cleanup(closeAll) |
| + cleanup := func(f func()) { steps = append(steps, f) } |
| + if os.Geteuid() != 0 { |
| + t.Fatal("needs real root") |
| + } |
| + if _, err := exec.LookPath("ip"); err != nil { |
| + t.Fatal("needs ip", err) |
| + } |
| + nsPath := filepath.Join("/run/netns", egressNetns) |
| + if _, err := os.Lstat(nsPath); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatal("network namespace already exists", nsPath, err) |
| + } |
| + if _, err := net.InterfaceByName(egressHostLink); err == nil { |
| + t.Fatal("link already exists", egressHostLink) |
| + } |
| + |
| + egressIP(t, "netns", "add", egressNetns) |
| + cleanup(func() { |
| + if out, err := exec.Command("ip", "netns", "del", egressNetns).CombinedOutput(); err != nil { |
| + t.Errorf("ip netns del %s: %v: %s", egressNetns, err, out) |
| + } |
| + if _, err := os.Lstat(nsPath); !errors.Is(err, fs.ErrNotExist) { |
| + t.Errorf("network namespace %s left behind: %v", nsPath, err) |
| + } |
| + }) |
| + egressIP(t, "link", "add", egressHostLink, "type", "veth", "peer", "name", egressNsLink, "netns", egressNetns) |
| + cleanup(func() { |
| + // Deleting one end removes the pair. The namespace's own deletion |
| + // would too, but only once nothing holds the namespace, so the |
| + // pair goes first and explicitly. |
| + if _, err := net.InterfaceByName(egressHostLink); err == nil { |
| + if out, err := exec.Command("ip", "link", "del", egressHostLink).CombinedOutput(); err != nil { |
| + t.Errorf("ip link del %s: %v: %s", egressHostLink, err, out) |
| + } |
| + } |
| + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| + if _, err := net.InterfaceByName(egressHostLink); err != nil { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Errorf("link %s left behind", egressHostLink) |
| + break |
| + } |
| + } |
| + }) |
| + egressIP(t, "addr", "add", "10.0.5.1/32", "dev", egressHostLink) |
| + egressIP(t, "-6", "addr", "add", "fd00:5::1/128", "dev", egressHostLink, "nodad") |
| + egressIP(t, "link", "set", egressHostLink, "up") |
| + egressIP(t, "route", "add", "10.0.5.20/32", "dev", egressHostLink, "src", "10.0.5.1") |
| + egressIP(t, "route", "add", "10.0.5.21/32", "dev", egressHostLink, "src", "10.0.5.1") |
| + egressIP(t, "-6", "route", "add", "fd00:5::20/128", "dev", egressHostLink, "src", "fd00:5::1") |
| + |
| + in := func(args ...string) { t.Helper(); egressIP(t, append([]string{"-n", egressNetns}, args...)...) } |
| + in("link", "set", "lo", "up") |
| + in("addr", "add", "10.0.5.20/32", "dev", egressNsLink) |
| + in("addr", "add", "10.0.5.21/32", "dev", egressNsLink) |
| + in("-6", "addr", "add", "fd00:5::20/128", "dev", egressNsLink, "nodad") |
| + in("link", "set", egressNsLink, "up") |
| + in("route", "add", "10.0.5.1/32", "dev", egressNsLink) |
| + in("-6", "route", "add", "fd00:5::1/128", "dev", egressNsLink) |
| + |
| + addrs := map[string]string{} |
| + for _, a := range egressTargets { |
| + ln, err := egressListenIn(nsPath, net.JoinHostPort(a, "0")) |
| + if err != nil { |
| + t.Fatalf("listen on %s in %s: %v", a, egressNetns, err) |
| + } |
| + cleanup(func() { ln.Close() }) |
| + go func() { |
| + for { |
| + c, err := ln.Accept() |
| + if err != nil { |
| + return |
| + } |
| + c.Close() |
| + } |
| + }() |
| + addrs[a] = ln.Addr().String() // an explicit port: tenants dial host:port (C15) |
| + } |
| + // Each answers from the box itself (no cgroup filter here). IPv6 |
| + // neighbour discovery on a fresh veth can take a moment. |
| + for a, hp := range addrs { |
| + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| + c, err := net.DialTimeout("tcp", hp, 500*time.Millisecond) |
| + if err == nil { |
| + c.Close() |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("target %s (%s) unreachable from the box: %v", a, hp, err) |
| + } |
| + } |
| + } |
| + // None is the box's own: the asserter would refuse it (Task 2). |
| + local, err := instancectl.LocalAddresses() |
| + if err != nil { |
| + t.Fatal("LocalAddresses:", err) |
| + } |
| + for _, a := range egressTargets { |
| + addr := netip.MustParseAddr(a) |
| + for _, p := range local { |
| + if p.Contains(addr) { |
| + t.Fatalf("target %s is an address of this box (%s): the fixture would bypass the own-address check", a, p) |
| + } |
| + } |
| + } |
| + return addrs, closeAll |
| +} |
| + |
| +// egressListenIn opens a TCP listener inside the network namespace at |
| +// nsPath. The socket keeps that namespace after the thread leaves it. The |
| +// work runs on a goroutine of its own with its OS thread locked; if the |
| +// thread cannot get back to the box's namespace it stays locked, and Go |
| +// ends it with the goroutine. |
| +func egressListenIn(nsPath, addr string) (net.Listener, error) { |
| + type result struct { |
| + ln net.Listener |
| + err error |
| + } |
| + ch := make(chan result, 1) |
| + go func() { |
| + runtime.LockOSThread() |
| + self, err := os.Open("/proc/thread-self/ns/net") |
| + if err != nil { |
| + runtime.UnlockOSThread() |
| + ch <- result{err: err} |
| + return |
| + } |
| + defer self.Close() |
| + target, err := os.Open(nsPath) |
| + if err != nil { |
| + runtime.UnlockOSThread() |
| + ch <- result{err: err} |
| + return |
| + } |
| + defer target.Close() |
| + if err := unix.Setns(int(target.Fd()), unix.CLONE_NEWNET); err != nil { |
| + runtime.UnlockOSThread() |
| + ch <- result{err: fmt.Errorf("setns into %s: %w", nsPath, err)} |
| + return |
| + } |
| + ln, lerr := net.Listen("tcp", addr) |
| + if err := unix.Setns(int(self.Fd()), unix.CLONE_NEWNET); err != nil { |
| + if ln != nil { |
| + ln.Close() |
| + } |
| + ch <- result{err: fmt.Errorf("setns back: %w", err)} |
| + return |
| + } |
| + runtime.UnlockOSThread() |
| + ch <- result{ln, lerr} |
| + }() |
| + r := <-ch |
| + return r.ln, r.err |
| +} |
| + |
| +// egressTenantClient is an HTTP client for a plan14-tenant's unix socket. |
| +func egressTenantClient(socket string) *http.Client { |
| + return &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "unix", socket) |
| + }, DisableKeepAlives: true}, Timeout: 3 * time.Second} |
| +} |
| + |
| +// egressServing waits up to 10 s for a tenant to answer on its socket. |
| +func egressServing(t *testing.T, unit string, c *http.Client) { |
| + t.Helper() |
| + egressServingBy(t, unit, c, time.Now().Add(10*time.Second)) |
| +} |
| + |
| +// The bounds a revoke is held to, each taken once, when the operation |
| +// that revokes (POST /egress, a sweep) returns, and carried through the |
| +// tenant's readiness and the connectivity check (review fix round 1): |
| +// a live revoke closes within egressLiveBound; one closed by restarting |
| +// the slice's units (closeByRestart) has egressRestartBound to restart |
| +// the unit, see it serve again and find the address closed. |
| +const ( |
| + egressLiveBound = 2 * time.Second |
| + egressRestartBound = 10 * time.Second |
| +) |
| + |
| +// egressServingBy waits until deadline for a tenant to answer on its socket. |
| +func egressServingBy(t *testing.T, unit string, c *http.Client, deadline time.Time) { |
| + t.Helper() |
| + for { |
| + resp, err := c.Get("http://tenant/") |
| + if err == nil { |
| + resp.Body.Close() |
| + if resp.StatusCode == http.StatusOK { |
| + return |
| + } |
| + err = errors.New(resp.Status) |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("%s did not serve: %v\n%s", unit, err, egressJournal(unit)) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| +} |
| + |
| +// egressReach asks a tenant to dial addr (host:port): 204 reachable, 403 not. |
| +func egressReach(t *testing.T, c *http.Client, addr string) bool { |
| + t.Helper() |
| + resp, err := c.Get("http://tenant/?dial=" + url.QueryEscape(addr)) |
| + if err != nil { |
| + t.Fatal("tenant probe", addr, err) |
| + } |
| + resp.Body.Close() |
| + switch resp.StatusCode { |
| + case http.StatusNoContent: |
| + return true |
| + case http.StatusForbidden: |
| + return false |
| + } |
| + t.Fatal("tenant probe", addr, resp.Status) |
| + return false |
| +} |
| + |
| +// egressWithin polls every 100 ms until the tenant sees addr as want, by |
| +// one deadline; an observation counts only if its probe finished before |
| +// the deadline (Task 1's rule). |
| +func egressWithin(t *testing.T, deadline time.Time, c *http.Client, want bool, addr string) bool { |
| + t.Helper() |
| + for { |
| + got := egressReach(t, c, addr) |
| + if time.Now().After(deadline) { |
| + return false |
| + } |
| + if got == want { |
| + return true |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| +} |
| + |
| +// egressFirewallDiag logs, for a tenant whose reachability was not what |
| +// the test wanted, what systemd shows for the unit, its slice and the |
| +// parents, and the kernel's effective programs (bpftool, when present). |
| +// Then it restarts the unit and probes once more: unreachable after the |
| +// restart means the slice's allow was right but did not reach the running |
| +// unit; still reachable means the deny is not in force for the unit at all. |
| +// The caller fails the test. |
| +func egressFirewallDiag(t *testing.T, unit, slice string, c *http.Client, target string) { |
| + t.Helper() |
| + for _, u := range []string{unit, slice, instancectl.InstancesSlice, "carlos.slice"} { |
| + out, _ := egressCtl("show", "-p", "IPAddressAllow", "-p", "IPAddressDeny", "-p", "ControlGroup", "-p", "ActiveState", u) |
| + t.Logf("diag: %s: %q", u, out) |
| + } |
| + if cg, _ := egressCtl("show", "-p", "ControlGroup", "--value", unit); cg != "" { |
| + if _, err := exec.LookPath("bpftool"); err == nil { |
| + out, _ := exec.Command("bpftool", "cgroup", "show", filepath.Join("/sys/fs/cgroup", cg), "effective").CombinedOutput() |
| + t.Logf("diag: bpftool cgroup show %s effective:\n%s", cg, out) |
| + } else { |
| + t.Logf("diag: no bpftool on this box") |
| + } |
| + } |
| + t.Logf("diag: before a restart of %s, %s reachable: %v", unit, target, egressReach(t, c, target)) |
| + if out, err := egressCtl("restart", unit); err != nil { |
| + t.Logf("diag: restart %s: %v: %s", unit, err, out) |
| + return |
| + } |
| + egressServing(t, unit, c) |
| + t.Logf("diag: after a restart of %s, %s reachable: %v", unit, target, egressReach(t, c, target)) |
| +} |
| + |
| +// egressPeerIsSelf is a PeerOK that accepts only this process: the test |
| +// is the control service's one client. |
| +func egressPeerIsSelf(c net.Conn) error { |
| + uc, ok := c.(*net.UnixConn) |
| + if !ok { |
| + return errors.New("not a unix connection") |
| + } |
| + raw, err := uc.SyscallConn() |
| + if err != nil { |
| + return err |
| + } |
| + var cred *unix.Ucred |
| + var credErr error |
| + if err := raw.Control(func(fd uintptr) { |
| + cred, credErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) |
| + }); err != nil { |
| + return err |
| + } |
| + if credErr != nil { |
| + return credErr |
| + } |
| + if int(cred.Pid) != os.Getpid() { |
| + return fmt.Errorf("peer pid %d is not this test (%d)", cred.Pid, os.Getpid()) |
| + } |
| + return nil |
| +} |
| + |
| +// egressServe serves srv on a unix socket at path until the test ends and |
| +// returns a client for it. |
| +func egressServe(t *testing.T, srv *instancectl.Server, path string) *instancectl.Client { |
| + t.Helper() |
| + if srv.PeerOK == nil { |
| + srv.PeerOK = egressPeerIsSelf |
| + } |
| + ln, err := net.Listen("unix", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan error, 1) |
| + go func() { done <- srv.Serve(ctx, ln) }() |
| + t.Cleanup(func() { |
| + cancel() |
| + if err := <-done; err != nil { |
| + t.Error("control service:", err) |
| + } |
| + os.Remove(path) |
| + }) |
| + return &instancectl.Client{Path: path} |
| +} |
| + |
| +// egressUnitTenant installs and starts a plan14-tenant unit in slice with |
| +// the template's deny, as Task 1 does (a unit file under |
| +// /run/systemd/system, the deny line verbatim), and returns a client for |
| +// it. The unit, its file and its failed state are removed in t.Cleanup. |
| +func egressUnitTenant(t *testing.T, unit, slice, deny, socket string) *http.Client { |
| + t.Helper() |
| + exe, err := os.Executable() |
| + if err != nil || !filepath.IsAbs(exe) { |
| + t.Fatal("test binary path", exe, err) |
| + } |
| + for _, p := range []string{exe, socket} { |
| + if strings.ContainsAny(p, " \t\n\"'\\%$;") { |
| + t.Fatalf("path %q is not safe to write into a unit file", p) |
| + } |
| + } |
| + name := unit + ".service" |
| + path := filepath.Join("/run/systemd/system", name) |
| + if state := egressShow(t, name, "LoadState"); state != "not-found" { |
| + t.Fatal("unit already present", name, state) |
| + } |
| + body := "[Unit]\nDescription=carlos egress witness tenant\n\n[Service]\n" + |
| + "Slice=" + slice + "\n" + |
| + "IPAddressDeny=" + deny + "\n" + |
| + "Environment=PLAN14_TENANT_SOCKET=" + socket + "\n" + |
| + "ExecStart=" + exe + " plan14-tenant\n" |
| + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.WriteString(body); err != nil { |
| + f.Close() |
| + t.Fatal(err) |
| + } |
| + f.Close() |
| + t.Cleanup(func() { |
| + if out, _ := egressCtl("show", "-p", "LoadState", "--value", name); out != "not-found" { |
| + if out, err := egressCtl("stop", name); err != nil { |
| + t.Errorf("stop %s: %v: %s", name, err, out) |
| + } |
| + } |
| + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + t.Error(err) |
| + } |
| + if out, err := egressCtl("daemon-reload"); err != nil { |
| + t.Errorf("daemon-reload: %v: %s", err, out) |
| + } |
| + egressCtl("reset-failed", name) |
| + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| + if out, _ := egressCtl("show", "-p", "LoadState", "--value", name); out == "not-found" { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Errorf("unit %s left behind", name) |
| + break |
| + } |
| + } |
| + }) |
| + egressMustCtl(t, "daemon-reload") |
| + if out, err := egressCtl("start", name); err != nil { |
| + t.Fatalf("start %s: %v: %s\n%s", name, err, out, egressJournal(name)) |
| + } |
| + c := egressTenantClient(socket) |
| + egressServing(t, name, c) |
| + if got := egressShow(t, name, "Slice"); got != slice { |
| + t.Fatalf("%s runs in %q, want %q", name, got, slice) |
| + } |
| + return c |
| +} |
| + |
| +// egressSliceProperties refuses a slice that already carries set-property |
| +// drop-ins or an allow, and removes the runtime drop-ins this test's |
| +// writes leave, after the slice (and so everything in it) is stopped. |
| +func egressSliceProperties(t *testing.T, slice string) { |
| + t.Helper() |
| + for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} { |
| + if _, err := os.Lstat(filepath.Join(root, slice+".d")); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatal("slice already has set-property drop-ins", slice, root, err) |
| + } |
| + } |
| + if allow := egressShow(t, slice, "IPAddressAllow"); allow != "" { |
| + t.Fatal("slice already carries an allow", slice, allow) |
| + } |
| + // Starting a unit in a host slice starts its ancestors; stop on |
| + // cleanup only the ones found inactive here. |
| + stopAfter := []string{slice} |
| + for _, s := range []string{instancectl.InstancesSlice, "carlos.slice"} { |
| + if egressShow(t, s, "ActiveState") == "inactive" { |
| + stopAfter = append(stopAfter, s) |
| + } |
| + } |
| + t.Cleanup(func() { |
| + for _, s := range stopAfter { |
| + if out, _ := egressCtl("show", "-p", "ActiveState", "--value", s); out != "inactive" { |
| + if out, err := egressCtl("stop", s); err != nil { |
| + t.Errorf("stop %s: %v: %s", s, err, out) |
| + } |
| + } |
| + } |
| + if err := os.RemoveAll(filepath.Join("/run/systemd/system.control", slice+".d")); err != nil { |
| + t.Error(err) |
| + } |
| + if out, err := egressCtl("daemon-reload"); err != nil { |
| + t.Errorf("daemon-reload: %v: %s", err, out) |
| + } |
| + if out, _ := egressCtl("show", "-p", "IPAddressAllow", "--value", slice); out != "" { |
| + t.Errorf("slice %s still carries an allow after cleanup: %q", slice, out) |
| + } |
| + }) |
| +} |
| + |
| +// egressNestedRow is an activator-managed instance row at the nested |
| +// defaults under dataDir: the row the pre-claim rail counts as nested. |
| +func egressNestedRow(dataDir, host string) registry.Route { |
| + return registry.Route{Host: host, Kind: "instance", Account: "abc", App: "shop", Channel: "stable", Hibernate: true, Status: "ready", |
| + DBPath: provision.NestedDBPath(dataDir, host), Socket: provision.NestedSocket(host)} |
| +} |
| + |
| +// egressExpiry is a policy_expires_at an hour ahead. |
| +func egressExpiry() string { return strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10) } |
| + |
| +// egressFailingCtl wraps the asserter's production Systemctl. Armed, it |
| +// fails the next set-property on its slice once, without running it, and |
| +// counts it; otherwise it passes every call through. |
| +type egressFailingCtl struct { |
| + next func(context.Context, ...string) (string, error) |
| + slice string |
| + armed atomic.Bool |
| + failed atomic.Int32 |
| +} |
| + |
| +func (c *egressFailingCtl) run(ctx context.Context, args ...string) (string, error) { |
| + if len(args) > 0 && args[0] == "set-property" && slices.Contains(args, c.slice) && c.armed.CompareAndSwap(true, false) { |
| + c.failed.Add(1) |
| + return "injected set-property failure", errors.New("exit status 1") |
| + } |
| + return c.next(ctx, args...) |
| +} |
| + |
| +// egressLogTail keeps what the tenants' log sockets carried, for a |
| +// failing test's output. |
| +type egressLogTail struct { |
| + mu sync.Mutex |
| + buf bytes.Buffer |
| +} |
| + |
| +func (l *egressLogTail) writer(name string) io.Writer { |
| + return writerFunc(func(p []byte) (int, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + if l.buf.Len() < 256<<10 { |
| + fmt.Fprintf(&l.buf, "[%s] %s", name, p) |
| + } |
| + return len(p), nil |
| + }) |
| +} |
| + |
| +// egressBox is a pre-claim box: the real control service with the |
| +// production pre-claim asserter, the five instance templates installed, |
| +// one nested registry row for egressTestHost carrying 10.0.5.20, and the |
| +// target fixture. |
| +type egressBox struct { |
| + host, slice string |
| + targets map[string]string |
| + reg *registry.Registry |
| + egress *instancectl.EgressAsserter |
| + ctl *egressFailingCtl |
| + client *instancectl.Client |
| + staged instancectl.StagedExe |
| +} |
| + |
| +// The templates the pre-claim start paths use. |
| +var egressTemplates = []string{ |
| + "carlos-instance@.service", |
| + "carlos-instance-gen@.service", |
| + "carlos-instance-seed@.service", |
| + "carlos-instance-sidecar@.service", |
| + "carlos-instance-cmd@.service", |
| +} |
| + |
| +const egressGen = 1 |
| + |
| +func newEgressPreClaimBox(t *testing.T) *egressBox { |
| + t.Helper() |
| + egressRootPrereqs(t) |
| + uid, gid := generationRunnerRegistryUser(t) |
| + host := egressTestHost |
| + b := &egressBox{host: host, slice: instancectl.SliceName(host)} |
| + t.Setenv("CARLOS_DATA_DIR", "/data") // instanceRegistryHostApp reads dataDir() |
| + |
| + units := []string{ |
| + instancectl.UnitName(instancectl.RoleRun, host), |
| + instancectl.UnitName(instancectl.RoleSeed, host), |
| + instancectl.UnitName(instancectl.RoleSidecar, host), |
| + instancectl.UnitName(instancectl.RoleCmd, host), |
| + instancectl.GenUnitName(host, egressGen), |
| + } |
| + for _, u := range units { |
| + if state := egressShow(t, u, "LoadState"); state != "not-found" { |
| + t.Fatal("unit already present", u, state) |
| + } |
| + } |
| + for _, name := range egressTemplates { |
| + for _, dir := range []string{"/run/systemd/system", "/etc/systemd/system"} { |
| + if _, err := os.Lstat(filepath.Join(dir, name)); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatal("template already installed", dir, name, err) |
| + } |
| + } |
| + } |
| + |
| + // Fixture roots: refused if present, removed last. |
| + for _, p := range []string{"/data", "/opt/carlos", "/run/carlos", "/run/carlos-control", "/etc/carlos"} { |
| + if err := os.Mkdir(p, 0o755); err != nil { |
| + t.Fatal("fixture root already exists", p, err) |
| + } |
| + t.Cleanup(func() { |
| + if err := os.RemoveAll(p); err != nil { |
| + t.Error(err) |
| + } |
| + }) |
| + } |
| + b.targets = egressTargetNetns(t) |
| + |
| + // The build: the test binary, as the platform binary the templates |
| + // run (instance-exec, instance-exit) and as the app's staged build, |
| + // behind the host's live link. |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + image, err := os.ReadFile(exe) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(instancectl.SystemBinary, image, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + staged := release.VersionPath("/opt/carlos", "abc", "v1", "shop") |
| + if err := os.MkdirAll(filepath.Dir(staged), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(staged, image, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + sum := sha256.Sum256(image) |
| + b.staged = instancectl.StagedExe{Path: staged, Version: "v1", Digest: hex.EncodeToString(sum[:])} |
| + if err := os.MkdirAll(filepath.Dir(release.LiveLink("/opt/carlos", host)), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(staged, release.LiveLink("/opt/carlos", host)); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // The instance's two directories, the carlos user's, and the log |
| + // sockets PID 1 connects each unit's output to. |
| + if err := os.Chown("/data", uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, d := range []string{provision.InstanceDir("/data", host), provision.InstanceRunDir(host), filepath.Join(provision.SocketDir, "logs")} { |
| + if err := os.MkdirAll(d, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, d := range []string{provision.InstanceDir("/data", host), provision.InstanceRunDir(host)} { |
| + if err := os.Chown(d, uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + logs := &egressLogTail{} |
| + t.Cleanup(func() { |
| + if t.Failed() { |
| + logs.mu.Lock() |
| + t.Logf("tenant output:\n%s", logs.buf.String()) |
| + logs.mu.Unlock() |
| + } |
| + }) |
| + for _, sock := range []string{ |
| + provision.LogSocket(host, "run"), provision.LogSocket(host, "seed"), provision.LogSocket(host, "sidecar"), |
| + provision.LogSocket(host, "cmd"), provision.LogSocket(host, "cmd-err"), instancectl.GenLogSocket(host, egressGen), |
| + } { |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { ln.Close() }) |
| + go func() { |
| + for { |
| + c, err := ln.Accept() |
| + if err != nil { |
| + return |
| + } |
| + go func() { io.Copy(logs.writer(filepath.Base(sock)), c); c.Close() }() |
| + } |
| + }() |
| + } |
| + |
| + // The templates, as TestRootFilesSeedIsolatedTenant installs them: the |
| + // edge and mount dependencies dropped, everything else verbatim. |
| + for _, name := range egressTemplates { |
| + raw, err := unitsFS.ReadFile("units/" + name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var lines []string |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + if strings.HasPrefix(line, "BindsTo=") || strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") { |
| + continue |
| + } |
| + lines = append(lines, line) |
| + } |
| + path := filepath.Join("/run/systemd/system", name) |
| + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, werr := f.WriteString(strings.Join(lines, "\n")) |
| + if err := errors.Join(werr, f.Close()); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + if err := os.Remove(path); err != nil { |
| + t.Error(err) |
| + } |
| + if out, err := egressCtl("daemon-reload"); err != nil { |
| + t.Errorf("daemon-reload: %v: %s", err, out) |
| + } |
| + }) |
| + } |
| + egressMustCtl(t, "daemon-reload") |
| + // The slice's drop-ins come off after its units have stopped. |
| + egressSliceProperties(t, b.slice) |
| + t.Cleanup(func() { |
| + for _, u := range units { |
| + if out, _ := egressCtl("show", "-p", "LoadState", "--value", u); out != "not-found" { |
| + if out, err := egressCtl("stop", u); err != nil { |
| + t.Errorf("stop %s: %v: %s", u, err, out) |
| + } |
| + } |
| + egressCtl("reset-failed", u) |
| + } |
| + if err := os.RemoveAll(filepath.Join("/run/systemd/system", instancectl.GenUnitName(host, egressGen)+".d")); err != nil { |
| + t.Error(err) |
| + } |
| + }) |
| + |
| + // The registry, written as the agent writes it: a child running as |
| + // the carlos user (openServiceRegistry). |
| + reg, err := openServiceRegistry("/data/registry.db") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + if err := reg.Upsert(egressNestedRow("/data", host)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetPolicy(host, "10.0.5.20", "", egressExpiry()); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.reg = reg |
| + |
| + // The launch files the agent writes before each start. Serving roles |
| + // run plan14-tenant on a socket in the instance's run directory; the |
| + // oneshots (seed, cmd) run egress-dial against 10.0.5.20. |
| + live := filepath.Join(instancectl.LiveDir, host) |
| + serve := func(sock string) instancectl.Launch { |
| + return instancectl.Launch{Schema: instancectl.LaunchSchema, Host: host, Argv: []string{live, "plan14-tenant"}, |
| + Env: []string{"PLAN14_TENANT_SOCKET=" + filepath.Join(provision.InstanceRunDir(host), sock)}} |
| + } |
| + dial := instancectl.Launch{Schema: instancectl.LaunchSchema, Host: host, Argv: []string{live, "egress-dial", b.targets["10.0.5.20"]}, Env: []string{}} |
| + for name, l := range map[string]instancectl.Launch{ |
| + instancectl.LaunchFileName(instancectl.RoleRun): serve("run.sock"), |
| + instancectl.GenLaunchFileName(egressGen): serve("gen.sock"), |
| + instancectl.LaunchFileName(instancectl.RoleSidecar): serve("sidecar.sock"), |
| + instancectl.LaunchFileName(instancectl.RoleSeed): dial, |
| + instancectl.LaunchFileName(instancectl.RoleCmd): dial, |
| + } { |
| + raw, err := json.Marshal(l) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(provision.InstanceDir("/data", host), name), raw, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + // The production pre-claim asserter (RunInstanceControl's !claims |
| + // branch), its systemctl behind a pass-through the revoke witness can |
| + // arm, and the control service as runWithClaim builds it, minus the |
| + // socket activation, the probe and the disk floors. |
| + b.egress = newEgressAsserter(registryEgressSource("/data", time.Now), registryEgressHosts("/data")) |
| + b.ctl = &egressFailingCtl{next: b.egress.Systemctl, slice: b.slice} |
| + b.egress.Systemctl = b.ctl.run |
| + b.egress.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, |
| + ExeRoot: "/run/carlos-control/exe", |
| + OptDir: "/opt/carlos", |
| + HostApp: instanceRegistryHostApp(nil), |
| + DropInDir: "/run/systemd/system", |
| + LocalAddrs: instancectl.LocalAddresses, |
| + DataRoot: "/data/instances", |
| + Egress: b.egress, |
| + } |
| + b.client = egressServe(t, srv, filepath.Join(t.TempDir(), "control.sock")) |
| + return b |
| +} |
| + |
| +// allow is the slice's IPAddressAllow as systemd shows it. |
| +func (b *egressBox) allow(t *testing.T) string { |
| + t.Helper() |
| + return egressShow(t, b.slice, "IPAddressAllow") |
| +} |
| + |
| +// resetSlice clears the slice's allow by hand, around the asserter, so the |
| +// next start path has something to write. |
| +func (b *egressBox) resetSlice(t *testing.T) { |
| + t.Helper() |
| + egressMustCtl(t, "set-property", "--runtime", b.slice, "IPAddressAllow=") |
| + if got := b.allow(t); got != "" { |
| + t.Fatalf("slice still holds %q after a reset", got) |
| + } |
| +} |
| + |
| +// report is GET /egress's report for the host. |
| +func (b *egressBox) report(t *testing.T) instancectl.EgressReport { |
| + t.Helper() |
| + st, err := b.client.EgressStatus(t.Context()) |
| + if err != nil { |
| + t.Fatal("GET /egress:", err) |
| + } |
| + return st.Hosts[b.host] |
| +} |
| + |
| +// wantAllowed: the slice holds 10.0.5.20/32 (Task 1's raw form) and root |
| +// reports it allowed, with no state. |
| +func (b *egressBox) wantAllowed(t *testing.T, step string) { |
| + t.Helper() |
| + if got := b.allow(t); got != "10.0.5.20/32" { |
| + t.Fatalf("%s: slice IPAddressAllow = %q, want %q", step, got, "10.0.5.20/32") |
| + } |
| + if rep := b.report(t); !slices.Equal(rep.Allowed, []string{"10.0.5.20"}) || rep.State != "" || len(rep.Refused) != 0 { |
| + t.Fatalf("%s: GET /egress = %+v, want allowed [10.0.5.20] and no state", step, rep) |
| + } |
| +} |
| + |
| +// tenant is a client for a serving role's socket, once it serves. |
| +func (b *egressBox) tenant(t *testing.T, unit, sock string) *http.Client { |
| + t.Helper() |
| + c := egressTenantClient(filepath.Join(provision.InstanceRunDir(b.host), sock)) |
| + egressServing(t, unit, c) |
| + return c |
| +} |
| + |
| +// startRun starts the run unit through POST /start and returns its tenant. |
| +func (b *egressBox) startRun(t *testing.T) *http.Client { |
| + t.Helper() |
| + unit := instancectl.UnitName(instancectl.RoleRun, b.host) |
| + if _, err := b.client.Start(t.Context(), b.host, instancectl.RoleRun, cgroup.TierDefault.MemoryMax); err != nil { |
| + t.Fatalf("POST /start run: %v\n%s", err, egressJournal(unit)) |
| + } |
| + c := b.tenant(t, unit, "run.sock") |
| + // The template's deny is in force: an address nothing grants is closed. |
| + if egressReach(t, c, b.targets["10.0.5.21"]) { |
| + egressFirewallDiag(t, unit, b.slice, c, b.targets["10.0.5.21"]) |
| + t.Fatal("run: the tenant reaches 10.0.5.21, which nothing allows: the template's deny is not in force") |
| + } |
| + return c |
| +} |
diff --git a/internal/host/egress_startpaths_rootrunner_linux_test.go b/internal/host/egress_startpaths_rootrunner_linux_test.go| index 142194883..e53c3e9ea 100644 |
| --- a/internal/host/egress_startpaths_rootrunner_linux_test.go |
| +++ b/internal/host/egress_startpaths_rootrunner_linux_test.go |
| @@ -3,34 +3,17 @@ |
| package host |
| import ( |
| - "bytes" |
| - "context" |
| "crypto/ed25519" |
| - "crypto/sha256" |
| - "encoding/hex" |
| - "encoding/json" |
| "errors" |
| - "fmt" |
| - "io" |
| "io/fs" |
| - "net" |
| "net/http" |
| - "net/netip" |
| - "net/url" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| - "runtime" |
| "slices" |
| - "strconv" |
| "strings" |
| - "sync" |
| - "sync/atomic" |
| "testing" |
| "time" |
| - "golang.org/x/sys/unix" |
| - |
| "github.com/carlosframework/platform/internal/apppolicy" |
| "github.com/carlosframework/platform/internal/cgroup" |
| "github.com/carlosframework/platform/internal/instancectl" |
| @@ -39,949 +22,9 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// Production-wired egress witnesses (#328, plan 2 Task 13). Every test |
| -// here drives the real control service (instancectl.Server) over its |
| -// unix socket, with the real egress asserter (newEgressAsserter over the |
| -// pre-claim registry source, or the claims source), and real units from |
| -// the embedded templates, run by systemd as the carlos user. |
| -// |
| -// Network: the tests reach nothing beyond their own target fixture, |
| -// egressTargetNetns: a network namespace behind a veth pair, holding the |
| -// target addresses and the listeners on them. The tenants are this test |
| -// binary (plan14-tenant, or egress-dial below) and dial only those |
| -// listeners. |
| - |
| -const ( |
| - egressTestHost = "shop-a.example.com" |
| - // egressNetns and its veth pair are this task's own names (ruling C16: |
| - // Task 1's kernel proof uses the dummy link carlos-egr0 on the box, so |
| - // the host end here is carlos-egr1, never carlos-egr0). |
| - egressNetns = "carlos-egr" |
| - egressHostLink = "carlos-egr1" |
| - egressNsLink = "carlos-egr1n" |
| -) |
| - |
| -// egressTargets are the addresses egressTargetNetns puts in its namespace. |
| -var egressTargets = []string{"10.0.5.20", "10.0.5.21", "fd00:5::20"} |
| - |
| -// The egress-dial payload: a oneshot tenant (seed, cmd) that dials one |
| -// host:port and exits 0 when it connected, 3 when it did not. It runs |
| -// before TestMain, so the unit's ExecMainStatus is the dial's answer. |
| -func init() { |
| - if len(os.Args) == 3 && os.Args[1] == "egress-dial" { |
| - c, err := net.DialTimeout("tcp", os.Args[2], 2*time.Second) |
| - if err != nil { |
| - fmt.Fprintln(os.Stderr, "egress-dial:", err) |
| - os.Exit(3) |
| - } |
| - c.Close() |
| - os.Exit(0) |
| - } |
| -} |
| - |
| -// egressRootPrereqs fails, never skips, without real root, systemd as |
| -// PID 1, cgroup v2, ip and systemctl. |
| -func egressRootPrereqs(t *testing.T) { |
| - t.Helper() |
| - if os.Geteuid() != 0 { |
| - t.Fatal("needs real root") |
| - } |
| - if pid1, err := os.ReadFile("/proc/1/comm"); err != nil || strings.TrimSpace(string(pid1)) != "systemd" { |
| - t.Fatalf("needs systemd as PID 1: %q %v", pid1, err) |
| - } |
| - var st unix.Statfs_t |
| - if err := unix.Statfs("/sys/fs/cgroup", &st); err != nil || st.Type != unix.CGROUP2_SUPER_MAGIC { |
| - t.Fatalf("needs cgroup v2 at /sys/fs/cgroup: type %#x %v", st.Type, err) |
| - } |
| - for _, tool := range []string{"ip", "systemctl", "journalctl"} { |
| - if _, err := exec.LookPath(tool); err != nil { |
| - t.Fatal("needs", tool, err) |
| - } |
| - } |
| -} |
| - |
| -func egressCtl(args ...string) (string, error) { |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| - return strings.TrimSpace(string(out)), err |
| -} |
| - |
| -func egressMustCtl(t *testing.T, args ...string) string { |
| - t.Helper() |
| - out, err := egressCtl(args...) |
| - if err != nil { |
| - t.Fatalf("systemctl %s: %v: %s", strings.Join(args, " "), err, out) |
| - } |
| - return out |
| -} |
| - |
| -func egressShow(t *testing.T, unit, prop string) string { |
| - t.Helper() |
| - return egressMustCtl(t, "show", "-p", prop, "--value", unit) |
| -} |
| - |
| -func egressJournal(unit string) string { |
| - out, _ := exec.Command("journalctl", "-u", unit, "--no-pager", "-n", "40").CombinedOutput() |
| - return string(out) |
| -} |
| - |
| -func egressIP(t *testing.T, args ...string) { |
| - t.Helper() |
| - if out, err := exec.Command("ip", args...).CombinedOutput(); err != nil { |
| - t.Fatalf("ip %s: %v: %s", strings.Join(args, " "), err, out) |
| - } |
| -} |
| - |
| -// egressTemplateDeny is the IPAddressDeny= list of the embedded instance |
| -// template, verbatim (keywords included: only the unit-file parser takes |
| -// them, which is why the tenants here are unit files, never systemd-run). |
| -func egressTemplateDeny(t *testing.T) string { |
| - t.Helper() |
| - raw, err := unitsFS.ReadFile("units/carlos-instance@.service") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - var deny string |
| - for _, line := range strings.Split(string(raw), "\n") { |
| - if v, ok := strings.CutPrefix(line, "IPAddressDeny="); ok { |
| - if deny != "" { |
| - t.Fatal("template carries more than one IPAddressDeny= line") |
| - } |
| - deny = v |
| - } |
| - } |
| - if deny == "" { |
| - t.Fatal("template carries no IPAddressDeny= line") |
| - } |
| - return deny |
| -} |
| - |
| -// egressTargetNetns is the egress target: a network namespace carlos-egr |
| -// behind a veth pair (carlos-egr1 on the box, carlos-egr1n inside), so the |
| -// targets are reachable from the box but are NOT addresses of the box |
| -// (Astra plan R1-6): the asserter's production validation, its check |
| -// against LocalAddresses included, stays on. |
| -// |
| -// - box side: 10.0.5.1/32 and fd00:5::1/128 on carlos-egr1, with routes |
| -// to 10.0.5.20, 10.0.5.21 (src 10.0.5.1) and fd00:5::20 (src |
| -// fd00:5::1) through it; |
| -// - namespace side: the three targets on carlos-egr1n, routes back to |
| -// 10.0.5.1 and fd00:5::1, lo up; |
| -// - a TCP listener on each target, opened inside the namespace and |
| -// served by this process. |
| -// |
| -// It returns each target's dialable host:port, keyed by address, after |
| -// checking that each answers from the box and that LocalAddresses holds |
| -// none of them. Everything is removed in t.Cleanup: listeners, the veth |
| -// pair and the namespace. |
| -func egressTargetNetns(t *testing.T) map[string]string { |
| - t.Helper() |
| - addrs, _ := egressTargetNetnsClosable(t) |
| - return addrs |
| -} |
| - |
| -// egressTargetNetnsClosable is egressTargetNetns with its teardown, for a |
| -// test that must have the fixture gone before it goes on: `ip netns add` |
| -// bind-mounts the namespace at /run/netns, and the root generation census |
| -// (generationMounts) refuses any nsfs mount on purpose. Calling close, or |
| -// the test's end, tears it down once, last-made first. |
| -func egressTargetNetnsClosable(t *testing.T) (map[string]string, func()) { |
| - t.Helper() |
| - var steps []func() |
| - var once sync.Once |
| - closeAll := func() { |
| - once.Do(func() { |
| - for i := len(steps) - 1; i >= 0; i-- { |
| - steps[i]() |
| - } |
| - }) |
| - } |
| - t.Cleanup(closeAll) |
| - cleanup := func(f func()) { steps = append(steps, f) } |
| - if os.Geteuid() != 0 { |
| - t.Fatal("needs real root") |
| - } |
| - if _, err := exec.LookPath("ip"); err != nil { |
| - t.Fatal("needs ip", err) |
| - } |
| - nsPath := filepath.Join("/run/netns", egressNetns) |
| - if _, err := os.Lstat(nsPath); !errors.Is(err, fs.ErrNotExist) { |
| - t.Fatal("network namespace already exists", nsPath, err) |
| - } |
| - if _, err := net.InterfaceByName(egressHostLink); err == nil { |
| - t.Fatal("link already exists", egressHostLink) |
| - } |
| - |
| - egressIP(t, "netns", "add", egressNetns) |
| - cleanup(func() { |
| - if out, err := exec.Command("ip", "netns", "del", egressNetns).CombinedOutput(); err != nil { |
| - t.Errorf("ip netns del %s: %v: %s", egressNetns, err, out) |
| - } |
| - if _, err := os.Lstat(nsPath); !errors.Is(err, fs.ErrNotExist) { |
| - t.Errorf("network namespace %s left behind: %v", nsPath, err) |
| - } |
| - }) |
| - egressIP(t, "link", "add", egressHostLink, "type", "veth", "peer", "name", egressNsLink, "netns", egressNetns) |
| - cleanup(func() { |
| - // Deleting one end removes the pair. The namespace's own deletion |
| - // would too, but only once nothing holds the namespace, so the |
| - // pair goes first and explicitly. |
| - if _, err := net.InterfaceByName(egressHostLink); err == nil { |
| - if out, err := exec.Command("ip", "link", "del", egressHostLink).CombinedOutput(); err != nil { |
| - t.Errorf("ip link del %s: %v: %s", egressHostLink, err, out) |
| - } |
| - } |
| - for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| - if _, err := net.InterfaceByName(egressHostLink); err != nil { |
| - break |
| - } |
| - if time.Now().After(deadline) { |
| - t.Errorf("link %s left behind", egressHostLink) |
| - break |
| - } |
| - } |
| - }) |
| - egressIP(t, "addr", "add", "10.0.5.1/32", "dev", egressHostLink) |
| - egressIP(t, "-6", "addr", "add", "fd00:5::1/128", "dev", egressHostLink, "nodad") |
| - egressIP(t, "link", "set", egressHostLink, "up") |
| - egressIP(t, "route", "add", "10.0.5.20/32", "dev", egressHostLink, "src", "10.0.5.1") |
| - egressIP(t, "route", "add", "10.0.5.21/32", "dev", egressHostLink, "src", "10.0.5.1") |
| - egressIP(t, "-6", "route", "add", "fd00:5::20/128", "dev", egressHostLink, "src", "fd00:5::1") |
| - |
| - in := func(args ...string) { t.Helper(); egressIP(t, append([]string{"-n", egressNetns}, args...)...) } |
| - in("link", "set", "lo", "up") |
| - in("addr", "add", "10.0.5.20/32", "dev", egressNsLink) |
| - in("addr", "add", "10.0.5.21/32", "dev", egressNsLink) |
| - in("-6", "addr", "add", "fd00:5::20/128", "dev", egressNsLink, "nodad") |
| - in("link", "set", egressNsLink, "up") |
| - in("route", "add", "10.0.5.1/32", "dev", egressNsLink) |
| - in("-6", "route", "add", "fd00:5::1/128", "dev", egressNsLink) |
| - |
| - addrs := map[string]string{} |
| - for _, a := range egressTargets { |
| - ln, err := egressListenIn(nsPath, net.JoinHostPort(a, "0")) |
| - if err != nil { |
| - t.Fatalf("listen on %s in %s: %v", a, egressNetns, err) |
| - } |
| - cleanup(func() { ln.Close() }) |
| - go func() { |
| - for { |
| - c, err := ln.Accept() |
| - if err != nil { |
| - return |
| - } |
| - c.Close() |
| - } |
| - }() |
| - addrs[a] = ln.Addr().String() // an explicit port: tenants dial host:port (C15) |
| - } |
| - // Each answers from the box itself (no cgroup filter here). IPv6 |
| - // neighbour discovery on a fresh veth can take a moment. |
| - for a, hp := range addrs { |
| - for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| - c, err := net.DialTimeout("tcp", hp, 500*time.Millisecond) |
| - if err == nil { |
| - c.Close() |
| - break |
| - } |
| - if time.Now().After(deadline) { |
| - t.Fatalf("target %s (%s) unreachable from the box: %v", a, hp, err) |
| - } |
| - } |
| - } |
| - // None is the box's own: the asserter would refuse it (Task 2). |
| - local, err := instancectl.LocalAddresses() |
| - if err != nil { |
| - t.Fatal("LocalAddresses:", err) |
| - } |
| - for _, a := range egressTargets { |
| - addr := netip.MustParseAddr(a) |
| - for _, p := range local { |
| - if p.Contains(addr) { |
| - t.Fatalf("target %s is an address of this box (%s): the fixture would bypass the own-address check", a, p) |
| - } |
| - } |
| - } |
| - return addrs, closeAll |
| -} |
| - |
| -// egressListenIn opens a TCP listener inside the network namespace at |
| -// nsPath. The socket keeps that namespace after the thread leaves it. The |
| -// work runs on a goroutine of its own with its OS thread locked; if the |
| -// thread cannot get back to the box's namespace it stays locked, and Go |
| -// ends it with the goroutine. |
| -func egressListenIn(nsPath, addr string) (net.Listener, error) { |
| - type result struct { |
| - ln net.Listener |
| - err error |
| - } |
| - ch := make(chan result, 1) |
| - go func() { |
| - runtime.LockOSThread() |
| - self, err := os.Open("/proc/thread-self/ns/net") |
| - if err != nil { |
| - runtime.UnlockOSThread() |
| - ch <- result{err: err} |
| - return |
| - } |
| - defer self.Close() |
| - target, err := os.Open(nsPath) |
| - if err != nil { |
| - runtime.UnlockOSThread() |
| - ch <- result{err: err} |
| - return |
| - } |
| - defer target.Close() |
| - if err := unix.Setns(int(target.Fd()), unix.CLONE_NEWNET); err != nil { |
| - runtime.UnlockOSThread() |
| - ch <- result{err: fmt.Errorf("setns into %s: %w", nsPath, err)} |
| - return |
| - } |
| - ln, lerr := net.Listen("tcp", addr) |
| - if err := unix.Setns(int(self.Fd()), unix.CLONE_NEWNET); err != nil { |
| - if ln != nil { |
| - ln.Close() |
| - } |
| - ch <- result{err: fmt.Errorf("setns back: %w", err)} |
| - return |
| - } |
| - runtime.UnlockOSThread() |
| - ch <- result{ln, lerr} |
| - }() |
| - r := <-ch |
| - return r.ln, r.err |
| -} |
| - |
| -// egressTenantClient is an HTTP client for a plan14-tenant's unix socket. |
| -func egressTenantClient(socket string) *http.Client { |
| - return &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| - return (&net.Dialer{}).DialContext(ctx, "unix", socket) |
| - }, DisableKeepAlives: true}, Timeout: 3 * time.Second} |
| -} |
| - |
| -// egressServing waits up to 10 s for a tenant to answer on its socket. |
| -func egressServing(t *testing.T, unit string, c *http.Client) { |
| - t.Helper() |
| - egressServingBy(t, unit, c, time.Now().Add(10*time.Second)) |
| -} |
| - |
| -// The bounds a revoke is held to, each taken once, when the operation |
| -// that revokes (POST /egress, a sweep) returns, and carried through the |
| -// tenant's readiness and the connectivity check (review fix round 1): |
| -// a live revoke closes within egressLiveBound; one closed by restarting |
| -// the slice's units (closeByRestart) has egressRestartBound to restart |
| -// the unit, see it serve again and find the address closed. |
| -const ( |
| - egressLiveBound = 2 * time.Second |
| - egressRestartBound = 10 * time.Second |
| -) |
| - |
| -// egressServingBy waits until deadline for a tenant to answer on its socket. |
| -func egressServingBy(t *testing.T, unit string, c *http.Client, deadline time.Time) { |
| - t.Helper() |
| - for { |
| - resp, err := c.Get("http://tenant/") |
| - if err == nil { |
| - resp.Body.Close() |
| - if resp.StatusCode == http.StatusOK { |
| - return |
| - } |
| - err = errors.New(resp.Status) |
| - } |
| - if time.Now().After(deadline) { |
| - t.Fatalf("%s did not serve: %v\n%s", unit, err, egressJournal(unit)) |
| - } |
| - time.Sleep(100 * time.Millisecond) |
| - } |
| -} |
| - |
| -// egressReach asks a tenant to dial addr (host:port): 204 reachable, 403 not. |
| -func egressReach(t *testing.T, c *http.Client, addr string) bool { |
| - t.Helper() |
| - resp, err := c.Get("http://tenant/?dial=" + url.QueryEscape(addr)) |
| - if err != nil { |
| - t.Fatal("tenant probe", addr, err) |
| - } |
| - resp.Body.Close() |
| - switch resp.StatusCode { |
| - case http.StatusNoContent: |
| - return true |
| - case http.StatusForbidden: |
| - return false |
| - } |
| - t.Fatal("tenant probe", addr, resp.Status) |
| - return false |
| -} |
| - |
| -// egressWithin polls every 100 ms until the tenant sees addr as want, by |
| -// one deadline; an observation counts only if its probe finished before |
| -// the deadline (Task 1's rule). |
| -func egressWithin(t *testing.T, deadline time.Time, c *http.Client, want bool, addr string) bool { |
| - t.Helper() |
| - for { |
| - got := egressReach(t, c, addr) |
| - if time.Now().After(deadline) { |
| - return false |
| - } |
| - if got == want { |
| - return true |
| - } |
| - time.Sleep(100 * time.Millisecond) |
| - } |
| -} |
| - |
| -// egressFirewallDiag logs, for a tenant whose reachability was not what |
| -// the test wanted, what systemd shows for the unit, its slice and the |
| -// parents, and the kernel's effective programs (bpftool, when present). |
| -// Then it restarts the unit and probes once more: unreachable after the |
| -// restart means the slice's allow was right but did not reach the running |
| -// unit; still reachable means the deny is not in force for the unit at all. |
| -// The caller fails the test. |
| -func egressFirewallDiag(t *testing.T, unit, slice string, c *http.Client, target string) { |
| - t.Helper() |
| - for _, u := range []string{unit, slice, instancectl.InstancesSlice, "carlos.slice"} { |
| - out, _ := egressCtl("show", "-p", "IPAddressAllow", "-p", "IPAddressDeny", "-p", "ControlGroup", "-p", "ActiveState", u) |
| - t.Logf("diag: %s: %q", u, out) |
| - } |
| - if cg, _ := egressCtl("show", "-p", "ControlGroup", "--value", unit); cg != "" { |
| - if _, err := exec.LookPath("bpftool"); err == nil { |
| - out, _ := exec.Command("bpftool", "cgroup", "show", filepath.Join("/sys/fs/cgroup", cg), "effective").CombinedOutput() |
| - t.Logf("diag: bpftool cgroup show %s effective:\n%s", cg, out) |
| - } else { |
| - t.Logf("diag: no bpftool on this box") |
| - } |
| - } |
| - t.Logf("diag: before a restart of %s, %s reachable: %v", unit, target, egressReach(t, c, target)) |
| - if out, err := egressCtl("restart", unit); err != nil { |
| - t.Logf("diag: restart %s: %v: %s", unit, err, out) |
| - return |
| - } |
| - egressServing(t, unit, c) |
| - t.Logf("diag: after a restart of %s, %s reachable: %v", unit, target, egressReach(t, c, target)) |
| -} |
| - |
| -// egressPeerIsSelf is a PeerOK that accepts only this process: the test |
| -// is the control service's one client. |
| -func egressPeerIsSelf(c net.Conn) error { |
| - uc, ok := c.(*net.UnixConn) |
| - if !ok { |
| - return errors.New("not a unix connection") |
| - } |
| - raw, err := uc.SyscallConn() |
| - if err != nil { |
| - return err |
| - } |
| - var cred *unix.Ucred |
| - var credErr error |
| - if err := raw.Control(func(fd uintptr) { |
| - cred, credErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) |
| - }); err != nil { |
| - return err |
| - } |
| - if credErr != nil { |
| - return credErr |
| - } |
| - if int(cred.Pid) != os.Getpid() { |
| - return fmt.Errorf("peer pid %d is not this test (%d)", cred.Pid, os.Getpid()) |
| - } |
| - return nil |
| -} |
| - |
| -// egressServe serves srv on a unix socket at path until the test ends and |
| -// returns a client for it. |
| -func egressServe(t *testing.T, srv *instancectl.Server, path string) *instancectl.Client { |
| - t.Helper() |
| - if srv.PeerOK == nil { |
| - srv.PeerOK = egressPeerIsSelf |
| - } |
| - ln, err := net.Listen("unix", path) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - ctx, cancel := context.WithCancel(context.Background()) |
| - done := make(chan error, 1) |
| - go func() { done <- srv.Serve(ctx, ln) }() |
| - t.Cleanup(func() { |
| - cancel() |
| - if err := <-done; err != nil { |
| - t.Error("control service:", err) |
| - } |
| - os.Remove(path) |
| - }) |
| - return &instancectl.Client{Path: path} |
| -} |
| - |
| -// egressUnitTenant installs and starts a plan14-tenant unit in slice with |
| -// the template's deny, as Task 1 does (a unit file under |
| -// /run/systemd/system, the deny line verbatim), and returns a client for |
| -// it. The unit, its file and its failed state are removed in t.Cleanup. |
| -func egressUnitTenant(t *testing.T, unit, slice, deny, socket string) *http.Client { |
| - t.Helper() |
| - exe, err := os.Executable() |
| - if err != nil || !filepath.IsAbs(exe) { |
| - t.Fatal("test binary path", exe, err) |
| - } |
| - for _, p := range []string{exe, socket} { |
| - if strings.ContainsAny(p, " \t\n\"'\\%$;") { |
| - t.Fatalf("path %q is not safe to write into a unit file", p) |
| - } |
| - } |
| - name := unit + ".service" |
| - path := filepath.Join("/run/systemd/system", name) |
| - if state := egressShow(t, name, "LoadState"); state != "not-found" { |
| - t.Fatal("unit already present", name, state) |
| - } |
| - body := "[Unit]\nDescription=carlos egress witness tenant\n\n[Service]\n" + |
| - "Slice=" + slice + "\n" + |
| - "IPAddressDeny=" + deny + "\n" + |
| - "Environment=PLAN14_TENANT_SOCKET=" + socket + "\n" + |
| - "ExecStart=" + exe + " plan14-tenant\n" |
| - f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, err := f.WriteString(body); err != nil { |
| - f.Close() |
| - t.Fatal(err) |
| - } |
| - f.Close() |
| - t.Cleanup(func() { |
| - if out, _ := egressCtl("show", "-p", "LoadState", "--value", name); out != "not-found" { |
| - if out, err := egressCtl("stop", name); err != nil { |
| - t.Errorf("stop %s: %v: %s", name, err, out) |
| - } |
| - } |
| - if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| - t.Error(err) |
| - } |
| - if out, err := egressCtl("daemon-reload"); err != nil { |
| - t.Errorf("daemon-reload: %v: %s", err, out) |
| - } |
| - egressCtl("reset-failed", name) |
| - for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| - if out, _ := egressCtl("show", "-p", "LoadState", "--value", name); out == "not-found" { |
| - break |
| - } |
| - if time.Now().After(deadline) { |
| - t.Errorf("unit %s left behind", name) |
| - break |
| - } |
| - } |
| - }) |
| - egressMustCtl(t, "daemon-reload") |
| - if out, err := egressCtl("start", name); err != nil { |
| - t.Fatalf("start %s: %v: %s\n%s", name, err, out, egressJournal(name)) |
| - } |
| - c := egressTenantClient(socket) |
| - egressServing(t, name, c) |
| - if got := egressShow(t, name, "Slice"); got != slice { |
| - t.Fatalf("%s runs in %q, want %q", name, got, slice) |
| - } |
| - return c |
| -} |
| - |
| -// egressSliceProperties refuses a slice that already carries set-property |
| -// drop-ins or an allow, and removes the runtime drop-ins this test's |
| -// writes leave, after the slice (and so everything in it) is stopped. |
| -func egressSliceProperties(t *testing.T, slice string) { |
| - t.Helper() |
| - for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} { |
| - if _, err := os.Lstat(filepath.Join(root, slice+".d")); !errors.Is(err, fs.ErrNotExist) { |
| - t.Fatal("slice already has set-property drop-ins", slice, root, err) |
| - } |
| - } |
| - if allow := egressShow(t, slice, "IPAddressAllow"); allow != "" { |
| - t.Fatal("slice already carries an allow", slice, allow) |
| - } |
| - // Starting a unit in a host slice starts its ancestors; stop on |
| - // cleanup only the ones found inactive here. |
| - stopAfter := []string{slice} |
| - for _, s := range []string{instancectl.InstancesSlice, "carlos.slice"} { |
| - if egressShow(t, s, "ActiveState") == "inactive" { |
| - stopAfter = append(stopAfter, s) |
| - } |
| - } |
| - t.Cleanup(func() { |
| - for _, s := range stopAfter { |
| - if out, _ := egressCtl("show", "-p", "ActiveState", "--value", s); out != "inactive" { |
| - if out, err := egressCtl("stop", s); err != nil { |
| - t.Errorf("stop %s: %v: %s", s, err, out) |
| - } |
| - } |
| - } |
| - if err := os.RemoveAll(filepath.Join("/run/systemd/system.control", slice+".d")); err != nil { |
| - t.Error(err) |
| - } |
| - if out, err := egressCtl("daemon-reload"); err != nil { |
| - t.Errorf("daemon-reload: %v: %s", err, out) |
| - } |
| - if out, _ := egressCtl("show", "-p", "IPAddressAllow", "--value", slice); out != "" { |
| - t.Errorf("slice %s still carries an allow after cleanup: %q", slice, out) |
| - } |
| - }) |
| -} |
| - |
| -// egressNestedRow is an activator-managed instance row at the nested |
| -// defaults under dataDir: the row the pre-claim rail counts as nested. |
| -func egressNestedRow(dataDir, host string) registry.Route { |
| - return registry.Route{Host: host, Kind: "instance", Account: "abc", App: "shop", Channel: "stable", Hibernate: true, Status: "ready", |
| - DBPath: provision.NestedDBPath(dataDir, host), Socket: provision.NestedSocket(host)} |
| -} |
| - |
| -// egressExpiry is a policy_expires_at an hour ahead. |
| -func egressExpiry() string { return strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10) } |
| - |
| -// egressFailingCtl wraps the asserter's production Systemctl. Armed, it |
| -// fails the next set-property on its slice once, without running it, and |
| -// counts it; otherwise it passes every call through. |
| -type egressFailingCtl struct { |
| - next func(context.Context, ...string) (string, error) |
| - slice string |
| - armed atomic.Bool |
| - failed atomic.Int32 |
| -} |
| - |
| -func (c *egressFailingCtl) run(ctx context.Context, args ...string) (string, error) { |
| - if len(args) > 0 && args[0] == "set-property" && slices.Contains(args, c.slice) && c.armed.CompareAndSwap(true, false) { |
| - c.failed.Add(1) |
| - return "injected set-property failure", errors.New("exit status 1") |
| - } |
| - return c.next(ctx, args...) |
| -} |
| - |
| -// egressLogTail keeps what the tenants' log sockets carried, for a |
| -// failing test's output. |
| -type egressLogTail struct { |
| - mu sync.Mutex |
| - buf bytes.Buffer |
| -} |
| - |
| -func (l *egressLogTail) writer(name string) io.Writer { |
| - return writerFunc(func(p []byte) (int, error) { |
| - l.mu.Lock() |
| - defer l.mu.Unlock() |
| - if l.buf.Len() < 256<<10 { |
| - fmt.Fprintf(&l.buf, "[%s] %s", name, p) |
| - } |
| - return len(p), nil |
| - }) |
| -} |
| - |
| -// egressBox is a pre-claim box: the real control service with the |
| -// production pre-claim asserter, the five instance templates installed, |
| -// one nested registry row for egressTestHost carrying 10.0.5.20, and the |
| -// target fixture. |
| -type egressBox struct { |
| - host, slice string |
| - targets map[string]string |
| - reg *registry.Registry |
| - egress *instancectl.EgressAsserter |
| - ctl *egressFailingCtl |
| - client *instancectl.Client |
| - staged instancectl.StagedExe |
| -} |
| - |
| -// The templates the pre-claim start paths use. |
| -var egressTemplates = []string{ |
| - "carlos-instance@.service", |
| - "carlos-instance-gen@.service", |
| - "carlos-instance-seed@.service", |
| - "carlos-instance-sidecar@.service", |
| - "carlos-instance-cmd@.service", |
| -} |
| - |
| -const egressGen = 1 |
| - |
| -func newEgressPreClaimBox(t *testing.T) *egressBox { |
| - t.Helper() |
| - egressRootPrereqs(t) |
| - uid, gid := generationRunnerRegistryUser(t) |
| - host := egressTestHost |
| - b := &egressBox{host: host, slice: instancectl.SliceName(host)} |
| - t.Setenv("CARLOS_DATA_DIR", "/data") // instanceRegistryHostApp reads dataDir() |
| - |
| - units := []string{ |
| - instancectl.UnitName(instancectl.RoleRun, host), |
| - instancectl.UnitName(instancectl.RoleSeed, host), |
| - instancectl.UnitName(instancectl.RoleSidecar, host), |
| - instancectl.UnitName(instancectl.RoleCmd, host), |
| - instancectl.GenUnitName(host, egressGen), |
| - } |
| - for _, u := range units { |
| - if state := egressShow(t, u, "LoadState"); state != "not-found" { |
| - t.Fatal("unit already present", u, state) |
| - } |
| - } |
| - for _, name := range egressTemplates { |
| - for _, dir := range []string{"/run/systemd/system", "/etc/systemd/system"} { |
| - if _, err := os.Lstat(filepath.Join(dir, name)); !errors.Is(err, fs.ErrNotExist) { |
| - t.Fatal("template already installed", dir, name, err) |
| - } |
| - } |
| - } |
| - |
| - // Fixture roots: refused if present, removed last. |
| - for _, p := range []string{"/data", "/opt/carlos", "/run/carlos", "/run/carlos-control", "/etc/carlos"} { |
| - if err := os.Mkdir(p, 0o755); err != nil { |
| - t.Fatal("fixture root already exists", p, err) |
| - } |
| - t.Cleanup(func() { |
| - if err := os.RemoveAll(p); err != nil { |
| - t.Error(err) |
| - } |
| - }) |
| - } |
| - b.targets = egressTargetNetns(t) |
| - |
| - // The build: the test binary, as the platform binary the templates |
| - // run (instance-exec, instance-exit) and as the app's staged build, |
| - // behind the host's live link. |
| - exe, err := os.Executable() |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - image, err := os.ReadFile(exe) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(instancectl.SystemBinary, image, 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - staged := release.VersionPath("/opt/carlos", "abc", "v1", "shop") |
| - if err := os.MkdirAll(filepath.Dir(staged), 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(staged, image, 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - sum := sha256.Sum256(image) |
| - b.staged = instancectl.StagedExe{Path: staged, Version: "v1", Digest: hex.EncodeToString(sum[:])} |
| - if err := os.MkdirAll(filepath.Dir(release.LiveLink("/opt/carlos", host)), 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.Symlink(staged, release.LiveLink("/opt/carlos", host)); err != nil { |
| - t.Fatal(err) |
| - } |
| - |
| - // The instance's two directories, the carlos user's, and the log |
| - // sockets PID 1 connects each unit's output to. |
| - if err := os.Chown("/data", uid, gid); err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, d := range []string{provision.InstanceDir("/data", host), provision.InstanceRunDir(host), filepath.Join(provision.SocketDir, "logs")} { |
| - if err := os.MkdirAll(d, 0o755); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - for _, d := range []string{provision.InstanceDir("/data", host), provision.InstanceRunDir(host)} { |
| - if err := os.Chown(d, uid, gid); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - logs := &egressLogTail{} |
| - t.Cleanup(func() { |
| - if t.Failed() { |
| - logs.mu.Lock() |
| - t.Logf("tenant output:\n%s", logs.buf.String()) |
| - logs.mu.Unlock() |
| - } |
| - }) |
| - for _, sock := range []string{ |
| - provision.LogSocket(host, "run"), provision.LogSocket(host, "seed"), provision.LogSocket(host, "sidecar"), |
| - provision.LogSocket(host, "cmd"), provision.LogSocket(host, "cmd-err"), instancectl.GenLogSocket(host, egressGen), |
| - } { |
| - ln, err := net.Listen("unix", sock) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { ln.Close() }) |
| - go func() { |
| - for { |
| - c, err := ln.Accept() |
| - if err != nil { |
| - return |
| - } |
| - go func() { io.Copy(logs.writer(filepath.Base(sock)), c); c.Close() }() |
| - } |
| - }() |
| - } |
| - |
| - // The templates, as TestRootFilesSeedIsolatedTenant installs them: the |
| - // edge and mount dependencies dropped, everything else verbatim. |
| - for _, name := range egressTemplates { |
| - raw, err := unitsFS.ReadFile("units/" + name) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - var lines []string |
| - for _, line := range strings.Split(string(raw), "\n") { |
| - if strings.HasPrefix(line, "BindsTo=") || strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") { |
| - continue |
| - } |
| - lines = append(lines, line) |
| - } |
| - path := filepath.Join("/run/systemd/system", name) |
| - f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - _, werr := f.WriteString(strings.Join(lines, "\n")) |
| - if err := errors.Join(werr, f.Close()); err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { |
| - if err := os.Remove(path); err != nil { |
| - t.Error(err) |
| - } |
| - if out, err := egressCtl("daemon-reload"); err != nil { |
| - t.Errorf("daemon-reload: %v: %s", err, out) |
| - } |
| - }) |
| - } |
| - egressMustCtl(t, "daemon-reload") |
| - // The slice's drop-ins come off after its units have stopped. |
| - egressSliceProperties(t, b.slice) |
| - t.Cleanup(func() { |
| - for _, u := range units { |
| - if out, _ := egressCtl("show", "-p", "LoadState", "--value", u); out != "not-found" { |
| - if out, err := egressCtl("stop", u); err != nil { |
| - t.Errorf("stop %s: %v: %s", u, err, out) |
| - } |
| - } |
| - egressCtl("reset-failed", u) |
| - } |
| - if err := os.RemoveAll(filepath.Join("/run/systemd/system", instancectl.GenUnitName(host, egressGen)+".d")); err != nil { |
| - t.Error(err) |
| - } |
| - }) |
| - |
| - // The registry, written as the agent writes it: a child running as |
| - // the carlos user (openServiceRegistry). |
| - reg, err := openServiceRegistry("/data/registry.db") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { reg.Close() }) |
| - if err := reg.Upsert(egressNestedRow("/data", host)); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := reg.SetPolicy(host, "10.0.5.20", "", egressExpiry()); err != nil { |
| - t.Fatal(err) |
| - } |
| - b.reg = reg |
| - |
| - // The launch files the agent writes before each start. Serving roles |
| - // run plan14-tenant on a socket in the instance's run directory; the |
| - // oneshots (seed, cmd) run egress-dial against 10.0.5.20. |
| - live := filepath.Join(instancectl.LiveDir, host) |
| - serve := func(sock string) instancectl.Launch { |
| - return instancectl.Launch{Schema: instancectl.LaunchSchema, Host: host, Argv: []string{live, "plan14-tenant"}, |
| - Env: []string{"PLAN14_TENANT_SOCKET=" + filepath.Join(provision.InstanceRunDir(host), sock)}} |
| - } |
| - dial := instancectl.Launch{Schema: instancectl.LaunchSchema, Host: host, Argv: []string{live, "egress-dial", b.targets["10.0.5.20"]}, Env: []string{}} |
| - for name, l := range map[string]instancectl.Launch{ |
| - instancectl.LaunchFileName(instancectl.RoleRun): serve("run.sock"), |
| - instancectl.GenLaunchFileName(egressGen): serve("gen.sock"), |
| - instancectl.LaunchFileName(instancectl.RoleSidecar): serve("sidecar.sock"), |
| - instancectl.LaunchFileName(instancectl.RoleSeed): dial, |
| - instancectl.LaunchFileName(instancectl.RoleCmd): dial, |
| - } { |
| - raw, err := json.Marshal(l) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(filepath.Join(provision.InstanceDir("/data", host), name), raw, 0o644); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - |
| - // The production pre-claim asserter (RunInstanceControl's !claims |
| - // branch), its systemctl behind a pass-through the revoke witness can |
| - // arm, and the control service as runWithClaim builds it, minus the |
| - // socket activation, the probe and the disk floors. |
| - b.egress = newEgressAsserter(registryEgressSource("/data", time.Now), registryEgressHosts("/data")) |
| - b.ctl = &egressFailingCtl{next: b.egress.Systemctl, slice: b.slice} |
| - b.egress.Systemctl = b.ctl.run |
| - b.egress.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, |
| - ExeRoot: "/run/carlos-control/exe", |
| - OptDir: "/opt/carlos", |
| - HostApp: instanceRegistryHostApp(nil), |
| - DropInDir: "/run/systemd/system", |
| - LocalAddrs: instancectl.LocalAddresses, |
| - DataRoot: "/data/instances", |
| - Egress: b.egress, |
| - } |
| - b.client = egressServe(t, srv, filepath.Join(t.TempDir(), "control.sock")) |
| - return b |
| -} |
| - |
| -// allow is the slice's IPAddressAllow as systemd shows it. |
| -func (b *egressBox) allow(t *testing.T) string { |
| - t.Helper() |
| - return egressShow(t, b.slice, "IPAddressAllow") |
| -} |
| - |
| -// resetSlice clears the slice's allow by hand, around the asserter, so the |
| -// next start path has something to write. |
| -func (b *egressBox) resetSlice(t *testing.T) { |
| - t.Helper() |
| - egressMustCtl(t, "set-property", "--runtime", b.slice, "IPAddressAllow=") |
| - if got := b.allow(t); got != "" { |
| - t.Fatalf("slice still holds %q after a reset", got) |
| - } |
| -} |
| - |
| -// report is GET /egress's report for the host. |
| -func (b *egressBox) report(t *testing.T) instancectl.EgressReport { |
| - t.Helper() |
| - st, err := b.client.EgressStatus(t.Context()) |
| - if err != nil { |
| - t.Fatal("GET /egress:", err) |
| - } |
| - return st.Hosts[b.host] |
| -} |
| - |
| -// wantAllowed: the slice holds 10.0.5.20/32 (Task 1's raw form) and root |
| -// reports it allowed, with no state. |
| -func (b *egressBox) wantAllowed(t *testing.T, step string) { |
| - t.Helper() |
| - if got := b.allow(t); got != "10.0.5.20/32" { |
| - t.Fatalf("%s: slice IPAddressAllow = %q, want %q", step, got, "10.0.5.20/32") |
| - } |
| - if rep := b.report(t); !slices.Equal(rep.Allowed, []string{"10.0.5.20"}) || rep.State != "" || len(rep.Refused) != 0 { |
| - t.Fatalf("%s: GET /egress = %+v, want allowed [10.0.5.20] and no state", step, rep) |
| - } |
| -} |
| - |
| -// tenant is a client for a serving role's socket, once it serves. |
| -func (b *egressBox) tenant(t *testing.T, unit, sock string) *http.Client { |
| - t.Helper() |
| - c := egressTenantClient(filepath.Join(provision.InstanceRunDir(b.host), sock)) |
| - egressServing(t, unit, c) |
| - return c |
| -} |
| - |
| -// startRun starts the run unit through POST /start and returns its tenant. |
| -func (b *egressBox) startRun(t *testing.T) *http.Client { |
| - t.Helper() |
| - unit := instancectl.UnitName(instancectl.RoleRun, b.host) |
| - if _, err := b.client.Start(t.Context(), b.host, instancectl.RoleRun, cgroup.TierDefault.MemoryMax); err != nil { |
| - t.Fatalf("POST /start run: %v\n%s", err, egressJournal(unit)) |
| - } |
| - c := b.tenant(t, unit, "run.sock") |
| - // The template's deny is in force: an address nothing grants is closed. |
| - if egressReach(t, c, b.targets["10.0.5.21"]) { |
| - egressFirewallDiag(t, unit, b.slice, c, b.targets["10.0.5.21"]) |
| - t.Fatal("run: the tenant reaches 10.0.5.21, which nothing allows: the template's deny is not in force") |
| - } |
| - return c |
| -} |
| +// The egress witnesses (#328, plan 2 Task 13); their fixtures, and what |
| +// network they reach (only their own target namespace), are in |
| +// egress_fixtures_rootrunner_linux_test.go. |
| // TestRootEgressStartPathsPreClaim: through the real control service and |
| // the installed templates, each start path (run, gen, seed, sidecar, cmd) |