| new file mode 100644 |
| index 000000000..0b3a07a88 |
| --- /dev/null |
| +++ b/internal/host/egress_startpaths_rootrunner_linux_test.go |
| @@ -0,0 +1,1319 @@ |
| +//go:build linux && rootrunner |
| + |
| +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" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "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() |
| + 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) |
| + t.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) |
| + t.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) |
| + } |
| + t.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 |
| +} |
| + |
| +// 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() |
| + deadline := time.Now().Add(10 * time.Second) |
| + 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) |
| + } |
| +} |
| + |
| +// 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)) |
| + } |
| + return b.tenant(t, unit, "run.sock") |
| +} |
| + |
| +// TestRootEgressStartPathsPreClaim: through the real control service and |
| +// the installed templates, each start path (run, gen, seed, sidecar, cmd) |
| +// leaves the host slice holding the registry column's allow, written by |
| +// that path itself (the slice is reset by hand before each), and the |
| +// instance it started reaches the allowed address: a serving role's |
| +// tenant answers ?dial with 204, a oneshot's dial exits 0. |
| +func TestRootEgressStartPathsPreClaim(t *testing.T) { |
| + b := newEgressPreClaimBox(t) |
| + ctx := t.Context() |
| + tier := cgroup.TierDefault.MemoryMax |
| + target := b.targets["10.0.5.20"] |
| + if got := b.allow(t); got != "" { |
| + t.Fatalf("slice holds %q before any start", got) |
| + } |
| + |
| + // run: POST /start role=run. |
| + run := instancectl.UnitName(instancectl.RoleRun, b.host) |
| + c := b.startRun(t) |
| + b.wantAllowed(t, "run") |
| + if !egressReach(t, c, target) { |
| + t.Fatal("run: the tenant cannot reach 10.0.5.20") |
| + } |
| + if err := b.client.Stop(ctx, b.host, instancectl.RoleRun); err != nil { |
| + t.Fatal("stop run:", err) |
| + } |
| + b.resetSlice(t) |
| + |
| + // gen: POST /start with a generation. |
| + gen := instancectl.GenUnitName(b.host, egressGen) |
| + if _, err := b.client.StartGen(ctx, b.host, egressGen, tier); err != nil { |
| + t.Fatalf("POST /start gen: %v\n%s", err, egressJournal(gen)) |
| + } |
| + b.wantAllowed(t, "gen") |
| + if !egressReach(t, b.tenant(t, gen, "gen.sock"), target) { |
| + t.Fatal("gen: the tenant cannot reach 10.0.5.20") |
| + } |
| + if err := b.client.StopGen(ctx, b.host, egressGen, false); err != nil { |
| + t.Fatal("stop gen:", err) |
| + } |
| + b.resetSlice(t) |
| + |
| + // seed: POST /seed, a oneshot whose exit status is its dial. |
| + seed := instancectl.UnitName(instancectl.RoleSeed, b.host) |
| + res, err := b.client.Seed(ctx, b.host, tier) |
| + if err != nil { |
| + t.Fatalf("POST /seed: %v\n%s", err, egressJournal(seed)) |
| + } |
| + b.wantAllowed(t, "seed") |
| + if res.Result != "success" || res.Status != "0" { |
| + t.Fatalf("seed: %+v, want success with status 0 (10.0.5.20 reached)\n%s", res, egressJournal(seed)) |
| + } |
| + b.resetSlice(t) |
| + |
| + // sidecar: POST /start role=sidecar naming the staged build. |
| + sidecar := instancectl.UnitName(instancectl.RoleSidecar, b.host) |
| + if _, err := b.client.StartSidecarExe(ctx, b.host, tier, b.staged); err != nil { |
| + t.Fatalf("POST /start sidecar: %v\n%s", err, egressJournal(sidecar)) |
| + } |
| + b.wantAllowed(t, "sidecar") |
| + if !egressReach(t, b.tenant(t, sidecar, "sidecar.sock"), target) { |
| + t.Fatal("sidecar: the tenant cannot reach 10.0.5.20") |
| + } |
| + if err := b.client.Stop(ctx, b.host, instancectl.RoleSidecar); err != nil { |
| + t.Fatal("stop sidecar:", err) |
| + } |
| + b.resetSlice(t) |
| + |
| + // cmd: POST /cmd, then the long-poll until the command is done. |
| + cmd := instancectl.UnitName(instancectl.RoleCmd, b.host) |
| + inv, err := b.client.Cmd(ctx, b.host, tier) |
| + if err != nil { |
| + t.Fatalf("POST /cmd: %v\n%s", err, egressJournal(cmd)) |
| + } |
| + b.wantAllowed(t, "cmd") |
| + var st instancectl.CmdStatus |
| + for deadline := time.Now().Add(30 * time.Second); ; { |
| + if st, err = b.client.CmdStatus(ctx, b.host, inv); err != nil { |
| + t.Fatal("GET /cmd:", err) |
| + } |
| + if st.State != instancectl.CmdRunning { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("cmd still running: %+v", st) |
| + } |
| + } |
| + if st.State != instancectl.CmdDone || st.Status != "0" { |
| + t.Fatalf("cmd: %+v, want done with status 0 (10.0.5.20 reached)\n%s", st, egressJournal(cmd)) |
| + } |
| + if err := b.client.Stop(ctx, b.host, instancectl.RoleCmd); err != nil { |
| + t.Fatal("stop cmd:", err) |
| + } |
| + if got := egressShow(t, run, "IPAddressAllow"); got != "" { |
| + t.Errorf("the run unit's own IPAddressAllow is %q: root writes the slice's, never the unit's", got) |
| + } |
| +} |
| + |
| +// TestRootEgressRevokeWhileRunning: with the run unit serving, a cleared |
| +// column and POST /egress close the address within 2 s; a regrant opens |
| +// it again; then a revoke whose write fails answers 502 and reports |
| +// failing with the address still held, and the next sweep closes it |
| +// (Astra plan R1-11: the failing write has something to write). |
| +func TestRootEgressRevokeWhileRunning(t *testing.T) { |
| + b := newEgressPreClaimBox(t) |
| + ctx := t.Context() |
| + target := b.targets["10.0.5.20"] |
| + c := b.startRun(t) |
| + b.wantAllowed(t, "start") |
| + if !egressReach(t, c, target) { |
| + t.Fatal("start: the tenant cannot reach 10.0.5.20") |
| + } |
| + |
| + // Revoke: the agent clears the column (SetPolicy, ruling C2) and |
| + // nudges root. |
| + if err := b.reg.SetPolicy(b.host, "", "", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.client.Egress(ctx, b.host); err != nil { |
| + t.Fatal("POST /egress (revoke):", err) |
| + } |
| + if !egressWithin(t, time.Now().Add(2*time.Second), c, false, target) { |
| + t.Fatal("revoke: 10.0.5.20 still reachable 2 s after POST /egress") |
| + } |
| + if got := b.allow(t); got != "" { |
| + t.Fatalf("revoke: slice holds %q", got) |
| + } |
| + if rep := b.report(t); len(rep.Allowed) != 0 || rep.State != "" { |
| + t.Fatalf("revoke: GET /egress = %+v, want nothing allowed and no state", rep) |
| + } |
| + |
| + // Regrant, so the failing revoke below has an allow to remove. |
| + if err := b.reg.SetPolicy(b.host, "10.0.5.20", "", egressExpiry()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.client.Egress(ctx, b.host); err != nil { |
| + t.Fatal("POST /egress (regrant):", err) |
| + } |
| + if !egressWithin(t, time.Now().Add(2*time.Second), c, true, target) { |
| + t.Fatal("regrant: 10.0.5.20 not reachable 2 s after POST /egress") |
| + } |
| + b.wantAllowed(t, "regrant") |
| + |
| + // A revoke whose write fails. |
| + if err := b.reg.SetPolicy(b.host, "", "", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.ctl.armed.Store(true) |
| + err := b.client.Egress(ctx, b.host) |
| + if err == nil || !strings.Contains(err.Error(), ": 502: ") { |
| + t.Fatalf("failing revoke: POST /egress = %v, want a 502", err) |
| + } |
| + if n := b.ctl.failed.Load(); n != 1 || b.ctl.armed.Load() { |
| + t.Fatalf("failing revoke: %d failed set-property (armed %v), want exactly 1", n, b.ctl.armed.Load()) |
| + } |
| + if rep := b.report(t); rep.State != instancectl.EgressFailing || !slices.Equal(rep.Allowed, []string{"10.0.5.20"}) { |
| + t.Fatalf("failing revoke: GET /egress = %+v, want failing with allowed [10.0.5.20]", rep) |
| + } |
| + if got := b.allow(t); got != "10.0.5.20/32" { |
| + t.Fatalf("failing revoke: slice holds %q, want the allow still there", got) |
| + } |
| + if !egressReach(t, c, target) { |
| + t.Fatal("failing revoke: 10.0.5.20 closed though the write failed") |
| + } |
| + |
| + // The next sweep (the 30 s loop's pass) closes it. |
| + b.egress.Sweep(ctx) |
| + deadline := time.Now().Add(2 * time.Second) |
| + if got := b.allow(t); got != "" { |
| + t.Fatalf("sweep: slice holds %q", got) |
| + } |
| + if !egressWithin(t, deadline, c, false, target) { |
| + t.Fatal("sweep: 10.0.5.20 still reachable 2 s after the sweep") |
| + } |
| + if rep := b.report(t); rep.State != "" || len(rep.Allowed) != 0 { |
| + t.Fatalf("sweep: GET /egress = %+v, want no state and nothing allowed", rep) |
| + } |
| + if n := b.ctl.failed.Load(); n != 1 { |
| + t.Fatalf("%d failed set-property, want 1", n) |
| + } |
| +} |
| + |
| +// TestRootEgressMixedBoxWritesNothing: a flat row makes the box not |
| +// wholly nested; POST /egress then leaves the slice holding nothing (the |
| +// allow written before is reset, the running tenant loses the address) |
| +// and GET /egress says not_nested. |
| +func TestRootEgressMixedBoxWritesNothing(t *testing.T) { |
| + b := newEgressPreClaimBox(t) |
| + ctx := t.Context() |
| + target := b.targets["10.0.5.20"] |
| + c := b.startRun(t) |
| + b.wantAllowed(t, "start") |
| + if !egressReach(t, c, target) { |
| + t.Fatal("start: the tenant cannot reach 10.0.5.20") |
| + } |
| + |
| + flat := "flat.example.com" |
| + if err := b.reg.Upsert(registry.Route{Host: flat, Kind: "instance", Account: "abc", App: "shop-b", Channel: "stable", Hibernate: true, Status: "ready", |
| + DBPath: provision.DefaultDBPath("/data", flat), Socket: provision.DefaultSocket(flat)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := b.client.Egress(ctx, b.host); err != nil { |
| + t.Fatal("POST /egress:", err) |
| + } |
| + if !egressWithin(t, time.Now().Add(2*time.Second), c, false, target) { |
| + t.Fatal("mixed box: 10.0.5.20 still reachable 2 s after POST /egress") |
| + } |
| + if got := b.allow(t); got != "" { |
| + t.Fatalf("mixed box: slice holds %q, want nothing", got) |
| + } |
| + rep := b.report(t) |
| + if rep.State != instancectl.EgressNotNested || len(rep.Allowed) != 0 || !strings.Contains(rep.Detail, flat) { |
| + t.Fatalf("mixed box: GET /egress = %+v, want not_nested naming %s and nothing allowed", rep, flat) |
| + } |
| +} |
| + |
| +// TestPlan14EgressClaimLaunchRootRunner is ruling 9's witness through the |
| +// real claim launch (plan14InstalledClaimLaunch's egress: mode): an allow |
| +// granted by hand before claims were on, a registry row and a signed |
| +// policy both granting 10.0.5.20, and the claims asserter in the runtime |
| +// resources. The launch closes the slice before the start; the tenant |
| +// cannot reach the address; root reports under_claims. |
| +func TestPlan14EgressClaimLaunchRootRunner(t *testing.T) { |
| + plan14InstalledClaimLaunch(t, "egress:") |
| +} |
| + |
| +// plan14EgressClaimSetup is the egress: mode's setup, before the launch: |
| +// the target fixture, the slice's drop-in cleanup, an allow on the slice |
| +// granted by hand, and a registry (in its own carlos-owned data dir under |
| +// dir) whose row carries 10.0.5.20 with an unexpired expiry. The registry |
| +// is the one the claims asserter is built over (instanceControlClaimResources); |
| +// under claims it only names slices. |
| +func plan14EgressClaimSetup(t *testing.T, host, dir string, uid, gid int) (targets map[string]string, reg *registry.Registry, data string) { |
| + t.Helper() |
| + targets = egressTargetNetns(t) |
| + slice := instancectl.SliceName(host) |
| + egressSliceProperties(t, slice) |
| + data = filepath.Join(dir, "egress-data") |
| + if err := os.Mkdir(data, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chown(data, uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg, err := openServiceRegistry(filepath.Join(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) |
| + } |
| + egressMustCtl(t, "set-property", "--runtime", slice, "IPAddressAllow=", "IPAddressAllow=10.0.5.20/32") |
| + if got := egressShow(t, slice, "IPAddressAllow"); got != "10.0.5.20/32" { |
| + t.Fatalf("hand grant: slice holds %q", got) |
| + } |
| + return targets, reg, data |
| +} |
| + |
| +// plan14EgressClaimPolicy puts, in the harness's store, a policy for the |
| +// launched app signed with the harness's release key and granting |
| +// 10.0.5.20: what root would trust if it read the store, which under |
| +// claims it must not (ruling 9). |
| +func plan14EgressClaimPolicy(t *testing.T, store release.Store, priv ed25519.PrivateKey, account, app string) { |
| + t.Helper() |
| + if err := apppolicy.PutIfMatch(t.Context(), store, priv, apppolicy.Policy{V: 1, Account: account, App: app, Revision: 1, |
| + SignedAt: time.Now(), EgressAllow: []string{"10.0.5.20"}}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if keys, err := store.List(t.Context(), apppolicy.Prefix); err != nil || len(keys) != 1 { |
| + t.Fatalf("the signed policy is not in the store: %v %v", keys, err) |
| + } |
| +} |
| + |
| +// plan14EgressClaimChecks runs after the claim launch served: the slice |
| +// holds nothing, the tenant cannot reach 10.0.5.20, GET /egress (the |
| +// control service's handler over the same asserter) reports under_claims |
| +// with claimsEgressDetail, the agent's status probe publishes it for the |
| +// row that carries the allow (REASON "egress: not yet supported under |
| +// claims"), and root wrote no policy of its own. |
| +func plan14EgressClaimChecks(t *testing.T, host string, tenant *http.Client, targets map[string]string, egress *instancectl.EgressAsserter, reg *registry.Registry, optDir string) { |
| + t.Helper() |
| + slice := instancectl.SliceName(host) |
| + if got := egressShow(t, slice, "IPAddressAllow"); got != "" { |
| + t.Fatalf("under claims: slice holds %q after the claim launch, want nothing", got) |
| + } |
| + if egressReach(t, tenant, targets["10.0.5.20"]) { |
| + t.Fatal("under claims: the claim-launched tenant reached 10.0.5.20") |
| + } |
| + client := egressServe(t, &instancectl.Server{ClaimStop: http.NotFoundHandler(), Egress: egress, Logf: t.Logf}, filepath.Join(t.TempDir(), "control.sock")) |
| + st, err := client.EgressStatus(t.Context()) |
| + if err != nil { |
| + t.Fatal("GET /egress:", err) |
| + } |
| + if rep := st.Hosts[host]; rep.State != instancectl.EgressUnderClaims || rep.Detail != claimsEgressDetail || len(rep.Allowed) != 0 || len(rep.Refused) != 0 { |
| + t.Fatalf("under claims: GET /egress[%s] = %+v, want under_claims %q and nothing allowed", host, rep, claimsEgressDetail) |
| + } |
| + rows, err := reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + published := egressStatusProbe(client, rows, nil) |
| + h, ok := published[host] |
| + if !ok || h.State != instancectl.EgressUnderClaims || h.Detail != claimsEgressDetail { |
| + t.Fatalf("under claims: the status probe published %+v (%v), want under_claims %q", h, ok, claimsEgressDetail) |
| + } |
| + // instances_cli.go's egressReason renders REASON as the label and the detail. |
| + if reason := "egress: " + h.Detail; reason != "egress: not yet supported under claims" { |
| + t.Fatalf("REASON would read %q", reason) |
| + } |
| + policyDir := filepath.Join(systemGuardDir(optDir), "app-policy") |
| + if _, err := os.Lstat(policyDir); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("root wrote %s under claims: %v", policyDir, err) |
| + } |
| +} |
| + |
| +// TestRootEgressInstanceControlUnderClaims is RunInstanceControl's claims |
| +// branch end to end (carried from Task 6): the seed-construction harness |
| +// runs the real RunInstanceControl with host claims on (its owners and |
| +// census are that harness's fixtures; NewProductionRootClaimStop, |
| +// WithProductionClaimLaunch and runClaimControl are production), and the |
| +// edge peer reaches it through the production peer check. Before it |
| +// constructs, a running tenant's host slice holds an allow granted |
| +// pre-claim and the registry row carries one. The service's first sweep |
| +// resets it; a hand regrant is closed again by POST /egress; GET /egress |
| +// reports under_claims. |
| +func TestRootEgressInstanceControlUnderClaims(t *testing.T) { |
| + runServingParkPeerNamespace(t, false, false, "seed-construction-egress") |
| +} |
| + |
| +// egressUnderClaimsWitness is the seed-construction-egress namespace's |
| +// part: prepare runs once /data exists and before the control service |
| +// constructs; check runs once the edge peer is connected. |
| +type egressUnderClaimsWitness struct { |
| + host, slice string |
| + targets map[string]string |
| + tenant *http.Client |
| +} |
| + |
| +func (w *egressUnderClaimsWitness) prepare(t *testing.T) { |
| + t.Helper() |
| + egressRootPrereqs(t) |
| + w.host = egressTestHost |
| + w.slice = instancectl.SliceName(w.host) |
| + w.targets = egressTargetNetns(t) |
| + reg, err := openServiceRegistry("/data/registry.db") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.Upsert(egressNestedRow("/data", w.host)); err != nil { |
| + reg.Close() |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetPolicy(w.host, "10.0.5.20", "", egressExpiry()); err != nil { |
| + reg.Close() |
| + t.Fatal(err) |
| + } |
| + if err := reg.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + egressSliceProperties(t, w.slice) |
| + // The allow a pre-claim root wrote, then a tenant running under it. |
| + egressMustCtl(t, "set-property", "--runtime", w.slice, "IPAddressAllow=", "IPAddressAllow=10.0.5.20/32") |
| + scratch, err := os.MkdirTemp("/run", "egr-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(scratch) }) |
| + w.tenant = egressUnitTenant(t, "carlos-egress-claims", w.slice, egressTemplateDeny(t), filepath.Join(scratch, "tenant.sock")) |
| + if !egressReach(t, w.tenant, w.targets["10.0.5.20"]) { |
| + t.Fatal("pre-claim: the tenant cannot reach 10.0.5.20 under the hand grant") |
| + } |
| +} |
| + |
| +func (w *egressUnderClaimsWitness) check(t *testing.T, egress func(host string) servingPeerReply) { |
| + t.Helper() |
| + target := w.targets["10.0.5.20"] |
| + // The control service's first sweep (RunWithClaim's Loop) resets the |
| + // allow granted before claims were switched on. |
| + for deadline := time.Now().Add(10 * time.Second); egressShow(t, w.slice, "IPAddressAllow") != ""; time.Sleep(100 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("under claims: slice still holds %q 10 s after the control service started", egressShow(t, w.slice, "IPAddressAllow")) |
| + } |
| + } |
| + if !egressWithin(t, time.Now().Add(2*time.Second), w.tenant, false, target) { |
| + t.Fatal("under claims: 10.0.5.20 reachable after the sweep reset the slice") |
| + } |
| + |
| + // A hand regrant, closed by POST /egress through the production peer |
| + // check; GET /egress reports under_claims. |
| + egressMustCtl(t, "set-property", "--runtime", w.slice, "IPAddressAllow=", "IPAddressAllow=10.0.5.20/32") |
| + if !egressWithin(t, time.Now().Add(2*time.Second), w.tenant, true, target) { |
| + t.Fatal("hand regrant: 10.0.5.20 not reachable") |
| + } |
| + reply := egress(w.host) |
| + deadline := time.Now().Add(2 * time.Second) |
| + if rep := reply.Egress.Hosts[w.host]; rep.State != instancectl.EgressUnderClaims || rep.Detail != claimsEgressDetail || len(rep.Allowed) != 0 { |
| + t.Fatalf("under claims: GET /egress[%s] = %+v, want under_claims %q and nothing allowed", w.host, rep, claimsEgressDetail) |
| + } |
| + if got := egressShow(t, w.slice, "IPAddressAllow"); got != "" { |
| + t.Fatalf("under claims: slice holds %q after POST /egress", got) |
| + } |
| + if !egressWithin(t, deadline, w.tenant, false, target) { |
| + t.Fatal("under claims: 10.0.5.20 reachable 2 s after POST /egress") |
| + } |
| +} |