egress: a start with a failed slice read consults the slice's runtime drop-in; the live byte-identical witness (#328)
Task 15 review fix round 1. 1. A restarted control service knows nothing of a slice, so the in-memory rule alone could admit a start under an allow being revoked. When a start path's read of the slice fails with nothing wanted, AssertStart now also reads systemd's runtime drop-in (/run/systemd/system.control/<slice>.d/50-IPAddressAllow.conf) as a trusted root file (no symlink at any step, root-owned, not group- or world-writable, one link): an allow there, or a file it cannot read or understand, refuses the start; no file, or the empty reset, lets it go ahead. The in-memory signals still refuse too. 2. TestRootEgressNoPolicyByteIdentical (rootrunner): each start path on real systemd with Egress nil and with the production asserter over a row with no policy; each unit's, the slice's and the parent's IPAddressAllow, IPAddressDeny and DropInPaths, and every runtime drop-in under /run/systemd/system.control for them, must be equal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+537
−28
internal/host/egress_fixtures_rootrunner_linux_test.go+12 −2internal/host/egress_startpaths_rootrunner_linux_test.go+173 −0internal/instancectl/egress.go+40 −11internal/instancectl/egress_dropin.go+67 −0internal/instancectl/egress_dropin_linux.go+77 −0internal/instancectl/egress_dropin_other.go+11 −0internal/instancectl/egress_restart_linux_test.go+149 −15internal/instancectl/egress_startpaths_test.go+2 −0internal/instancectl/egress_test.go+6 −0
diff --git a/internal/host/egress_fixtures_rootrunner_linux_test.go b/internal/host/egress_fixtures_rootrunner_linux_test.go| index ef79d0e8d..6cfa25609 100644 |
| --- a/internal/host/egress_fixtures_rootrunner_linux_test.go |
| +++ b/internal/host/egress_fixtures_rootrunner_linux_test.go |
| @@ -728,6 +728,11 @@ type egressBoxOptions struct { |
| // from unitsFS) and its fixtures, and gives the control service the |
| // probe's production fields, for Server.RunProbe. |
| probe bool |
| + // noPolicy leaves the host's row with no egress_allow (Task 15). |
| + noPolicy bool |
| + // egressOff serves the control service with Egress nil, as main's |
| + // (Task 15); the asserter is built all the same and left unused. |
| + egressOff bool |
| } |
| // egressOtherHost is another app's host on the box. |
| @@ -963,8 +968,10 @@ func newEgressPreClaimBoxWith(t *testing.T, o egressBoxOptions) *egressBox { |
| 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) |
| + if !o.noPolicy { |
| + if err := reg.SetPolicy(host, "10.0.5.20", "", egressExpiry()); err != nil { |
| + t.Fatal(err) |
| + } |
| } |
| for _, other := range o.others { |
| if err := reg.Upsert(egressNestedAppRow("/data", other.host, other.app)); err != nil { |
| @@ -1034,6 +1041,9 @@ func newEgressPreClaimBoxWith(t *testing.T, o egressBoxOptions) *egressBox { |
| DataRoot: "/data/instances", |
| Egress: b.egress, |
| } |
| + if o.egressOff { |
| + srv.Egress = nil |
| + } |
| if o.probe { |
| egressProbeFixture(t, uid, gid) |
| srv.ProbeOut = egressProbeOut |
diff --git a/internal/host/egress_startpaths_rootrunner_linux_test.go b/internal/host/egress_startpaths_rootrunner_linux_test.go| index 26a3a2a21..37b03eb2d 100644 |
| --- a/internal/host/egress_startpaths_rootrunner_linux_test.go |
| +++ b/internal/host/egress_startpaths_rootrunner_linux_test.go |
| @@ -12,6 +12,7 @@ import ( |
| "net/netip" |
| "os" |
| "path/filepath" |
| + "reflect" |
| "slices" |
| "strings" |
| "testing" |
| @@ -1070,3 +1071,175 @@ func plan14EgressNudgeBeforeClaims(t *testing.T, unit string, ctl func(context.C |
| t.Fatalf("the claim checks refuse the nudge's drop-in: rest %q, %v\n%s", rest, err, body) |
| } |
| } |
| + |
| +// TestRootEgressNoPolicyByteIdentical is the live byte-identical proof |
| +// (plan 2 Task 15, spec §7: with no policy object, every unit and slice |
| +// property is byte-identical to main). On real systemd, through the real |
| +// control service and the installed templates, each start path (run, gen, |
| +// seed, sidecar, cmd) is started on a box whose registry row carries no |
| +// egress_allow, twice: once with Server.Egress nil, main's control |
| +// service, and once with the production pre-claim asserter wired. After |
| +// each start, what systemd shows must be the same both times: each of the |
| +// host's units' and its slice's IPAddressAllow, IPAddressDeny and |
| +// DropInPaths, carlos-instances.slice's, and every runtime drop-in under |
| +// /run/systemd/system.control for those units and slices, by name and |
| +// bytes; and the oneshots' results. With egress wired, no |
| +// 50-IPAddressAllow.conf ever exists in the slice's runtime directory, and |
| +// GET /egress reports the host with nothing to say. |
| +func TestRootEgressNoPolicyByteIdentical(t *testing.T) { |
| + var runs [2]map[string]map[string]string |
| + for i, wired := range []bool{false, true} { |
| + name := "egress nil" |
| + if wired { |
| + name = "egress wired, no policy" |
| + } |
| + t.Run(name, func(t *testing.T) { runs[i] = egressNoPolicyStarts(t, wired) }) |
| + } |
| + if t.Failed() { |
| + return |
| + } |
| + for _, step := range []string{"run", "gen", "seed", "sidecar", "cmd"} { |
| + main, wired := runs[0][step], runs[1][step] |
| + for _, k := range slices.Sorted(maps.Keys(main)) { |
| + if w, ok := wired[k]; !ok || w != main[k] { |
| + t.Errorf("%s: %s: egress nil %q, egress wired %q (present %v)", step, k, main[k], w, ok) |
| + } |
| + } |
| + for _, k := range slices.Sorted(maps.Keys(wired)) { |
| + if _, ok := main[k]; !ok { |
| + t.Errorf("%s: %s: only with egress wired: %q", step, k, wired[k]) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// egressNoPolicyStarts starts each start path on a fresh pre-claim box |
| +// with no policy, egress wired or not, and returns what systemd shows |
| +// after each (egressObserve), keyed by the path. |
| +func egressNoPolicyStarts(t *testing.T, wired bool) map[string]map[string]string { |
| + t.Helper() |
| + b := newEgressPreClaimBoxWith(t, egressBoxOptions{noPolicy: true, egressOff: !wired}) |
| + ctx := t.Context() |
| + tier := cgroup.TierDefault.MemoryMax |
| + obs := map[string]map[string]string{} |
| + noAllowDropin := func(step string) { |
| + t.Helper() |
| + if !wired { |
| + return |
| + } |
| + path := filepath.Join("/run/systemd/system.control", b.slice+".d", "50-IPAddressAllow.conf") |
| + if _, err := os.Lstat(path); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("%s: %s exists (%v): egress wrote the slice's allow with no policy", step, path, err) |
| + } |
| + if rep := b.report(t); !reflect.DeepEqual(rep, instancectl.EgressReport{}) { |
| + t.Fatalf("%s: GET /egress = %+v, want nothing to say", step, rep) |
| + } |
| + } |
| + |
| + // run |
| + b.startRun(t) |
| + obs["run"] = egressObserve(t, b) |
| + noAllowDropin("run") |
| + if err := b.client.Stop(ctx, b.host, instancectl.RoleRun); err != nil { |
| + t.Fatal("stop run:", err) |
| + } |
| + |
| + // gen |
| + 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.tenant(t, gen, "gen.sock") |
| + obs["gen"] = egressObserve(t, b) |
| + noAllowDropin("gen") |
| + if err := b.client.StopGen(ctx, b.host, egressGen, false); err != nil { |
| + t.Fatal("stop gen:", err) |
| + } |
| + |
| + // seed: its dial of 10.0.5.20 is closed both times (no allow). |
| + 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)) |
| + } |
| + obs["seed"] = egressObserve(t, b) |
| + obs["seed"]["result"] = res.Result + " " + res.Status + " " + res.Code |
| + noAllowDropin("seed") |
| + |
| + // sidecar |
| + 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.tenant(t, sidecar, "sidecar.sock") |
| + obs["sidecar"] = egressObserve(t, b) |
| + noAllowDropin("sidecar") |
| + if err := b.client.Stop(ctx, b.host, instancectl.RoleSidecar); err != nil { |
| + t.Fatal("stop sidecar:", err) |
| + } |
| + |
| + // cmd: run to its end; its dial is closed both times. |
| + 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)) |
| + } |
| + 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) |
| + } |
| + } |
| + obs["cmd"] = egressObserve(t, b) |
| + obs["cmd"]["result"] = st.State + " " + st.Result + " " + st.Status + " " + st.Code |
| + noAllowDropin("cmd") |
| + if err := b.client.Stop(ctx, b.host, instancectl.RoleCmd); err != nil { |
| + t.Fatal("stop cmd:", err) |
| + } |
| + return obs |
| +} |
| + |
| +// egressObserve is what systemd shows for the box's host: for each of its |
| +// units, its slice and carlos-instances.slice, IPAddressAllow, |
| +// IPAddressDeny and DropInPaths, and each runtime drop-in under |
| +// /run/systemd/system.control/<name>.d by file name and bytes. |
| +func egressObserve(t *testing.T, b *egressBox) map[string]string { |
| + t.Helper() |
| + out := map[string]string{} |
| + names := []string{ |
| + instancectl.UnitName(instancectl.RoleRun, b.host), |
| + instancectl.UnitName(instancectl.RoleSeed, b.host), |
| + instancectl.UnitName(instancectl.RoleSidecar, b.host), |
| + instancectl.UnitName(instancectl.RoleCmd, b.host), |
| + instancectl.GenUnitName(b.host, egressGen), |
| + b.slice, |
| + instancectl.InstancesSlice, |
| + } |
| + for _, name := range names { |
| + for _, prop := range []string{"IPAddressAllow", "IPAddressDeny", "DropInPaths"} { |
| + out["show "+name+" "+prop] = egressShow(t, name, prop) |
| + } |
| + dir := filepath.Join("/run/systemd/system.control", name+".d") |
| + entries, err := os.ReadDir(dir) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, ent := range entries { |
| + body, err := os.ReadFile(filepath.Join(dir, ent.Name())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out["dropin "+filepath.Join(dir, ent.Name())] = string(body) |
| + } |
| + } |
| + return out |
| +} |
diff --git a/internal/instancectl/egress.go b/internal/instancectl/egress.go| index 73bc676d6..f716f2379 100644 |
| --- a/internal/instancectl/egress.go |
| +++ b/internal/instancectl/egress.go |
| @@ -126,6 +126,11 @@ type EgressAsserter struct { |
| // an allow. A start path whose read fails with nothing wanted refuses |
| // only on such a slice, or one owing a change (mayHold, AssertStart). |
| heldSome map[string]bool |
| + // controlDir is systemd's runtime control directory ("" is |
| + // runtimeControlDir) and dropinOwner the owner its drop-ins must have |
| + // (root); tests point both at a tree of their own. |
| + controlDir string |
| + dropinOwner uint32 |
| } |
| // egressDue is what a slice still owes its running services. |
| @@ -168,12 +173,13 @@ func (e *EgressAsserter) Assert(ctx context.Context, host string) error { |
| // AssertStart is Assert for a start path, which refuses the start on its |
| // error. It differs in one case: a read that fails with nothing wanted |
| -// is not an error unless the slice may hold an allow (mayHold: a change |
| -// it owes its running services, or a last read-back that held |
| -// something). Main would have started that instance, and a host with no |
| -// policy must start as on main; the report says failing and the loop |
| -// retries. A slice that may hold an allow refuses, as Assert does, since |
| -// the start could otherwise run under an allow that is being revoked. |
| +// is not an error unless the slice may hold an allow (startMayHold: what |
| +// this asserter knows, and the slice's runtime drop-in on disk, which |
| +// outlives a control service restart). Main would have started that |
| +// instance, and a host with no policy must start as on main; the report |
| +// says failing and the loop retries. A slice that may hold an allow |
| +// refuses, as Assert does, since the start could otherwise run under an |
| +// allow that is being revoked. |
| func (e *EgressAsserter) AssertStart(ctx context.Context, host string) error { |
| return e.assert(ctx, host, true) |
| } |
| @@ -256,12 +262,17 @@ func (e *EgressAsserter) assert(ctx context.Context, host string, start bool) er |
| // reset written blind would leave a runtime override on a |
| // slice that may hold nothing. The caller and the loop retry, |
| // and a revoke lands as soon as the slice can be read. |
| - err := fail("read back: " + readErr.Error() + "; nothing written") |
| - if start && !e.mayHold(slice) { |
| - e.logf("egress: %s: starting anyway: nothing is wanted and the slice is not known to hold an allow", slice) |
| - return nil |
| + detail := "read back: " + readErr.Error() + "; nothing written" |
| + if start { |
| + why, refuse := e.startMayHold(slice) |
| + if !refuse { |
| + _ = fail(detail) // recorded and logged; the loop retries |
| + e.logf("egress: %s: starting anyway: %s", slice, why) |
| + return nil |
| + } |
| + detail += "; refusing the start: " + why |
| } |
| - return err |
| + return fail(detail) |
| } |
| // An allow is wanted: write it, and the read after it decides. |
| e.logf("egress: %s: read back: %v; writing the allow", slice, readErr) |
| @@ -515,6 +526,24 @@ func (e *EgressAsserter) mayHold(slice string) bool { |
| return e.due[slice] != dueNone || e.heldSome[slice] |
| } |
| +// startMayHold decides a start whose read of slice failed with nothing |
| +// wanted: refuse when this asserter knows the slice may hold an allow |
| +// (mayHold), or when the slice's runtime drop-in sets one or cannot be |
| +// read; otherwise go ahead. why says which. |
| +func (e *EgressAsserter) startMayHold(slice string) (why string, refuse bool) { |
| + if e.mayHold(slice) { |
| + return "this control service saw the slice hold an allow, or owes it a change", true |
| + } |
| + held, err := e.sliceAllowOnDisk(slice) |
| + switch { |
| + case err != nil: |
| + return "its runtime allow drop-in could not be read: " + err.Error(), true |
| + case held: |
| + return "its runtime allow drop-in sets an allow", true |
| + } |
| + return "nothing is wanted and no allow is known or on disk", false |
| +} |
| + |
| func (e *EgressAsserter) setHeldSome(slice string, some bool) { |
| e.mu.Lock() |
| defer e.mu.Unlock() |
diff --git a/internal/instancectl/egress_dropin.go b/internal/instancectl/egress_dropin.go| new file mode 100644 |
| index 000000000..7539edaed |
| --- /dev/null |
| +++ b/internal/instancectl/egress_dropin.go |
| @@ -0,0 +1,67 @@ |
| +package instancectl |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "strings" |
| +) |
| + |
| +// The on-disk evidence of a slice's allow (Task 15 review, ruling on |
| +// finding 1): `systemctl set-property --runtime <slice> IPAddressAllow=...` |
| +// makes systemd write <runtimeControlDir>/<slice>.d/50-IPAddressAllow.conf |
| +// (the name Task 14 saw systemd give the nudge's drop-in on a real box), |
| +// and it stays there until reboot, whatever happens to the control |
| +// service. A start path whose read of the slice fails, with nothing |
| +// wanted, reads it to learn whether the slice may still hold an allow a |
| +// control service before this one wrote (AssertStart). |
| +const ( |
| + runtimeControlDir = "/run/systemd/system.control" |
| + allowDropinName = "50-IPAddressAllow.conf" |
| + maxAllowDropin = 64 << 10 |
| +) |
| + |
| +// sliceAllowOnDisk reports whether slice's runtime IPAddressAllow drop-in |
| +// sets a non-empty allow. No drop-in (no file, or no directory) is false. |
| +// A drop-in that cannot be read as a trusted root file (a symlink, another |
| +// owner, group- or world-writable, more than one link, not a regular |
| +// file), or whose content is not a [Slice] section of IPAddressAllow= |
| +// lines, is an error: the caller refuses on it. |
| +func (e *EgressAsserter) sliceAllowOnDisk(slice string) (bool, error) { |
| + dir := e.controlDir |
| + if dir == "" { |
| + dir = runtimeControlDir |
| + } |
| + body, err := readTrustedDropin(dir, slice+".d", allowDropinName, e.dropinOwner) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + return dropinAllowHeld(body) |
| +} |
| + |
| +// dropinAllowHeld applies a drop-in's IPAddressAllow= lines in order, as |
| +// systemd does (an empty assignment resets the list), and reports whether |
| +// a list is left. Comments and blank lines aside, it accepts only the |
| +// [Slice] header and IPAddressAllow= lines. |
| +func dropinAllowHeld(body []byte) (bool, error) { |
| + if len(body) > maxAllowDropin { |
| + return false, errors.New("the drop-in is too large") |
| + } |
| + held, section := false, false |
| + for _, line := range strings.Split(string(body), "\n") { |
| + line = strings.TrimSpace(line) |
| + switch { |
| + case line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";"): |
| + case line == "[Slice]": |
| + section = true |
| + case section && strings.HasPrefix(line, "IPAddressAllow="): |
| + held = strings.TrimSpace(strings.TrimPrefix(line, "IPAddressAllow=")) != "" |
| + default: |
| + return false, fmt.Errorf("unexpected drop-in line %q", line) |
| + } |
| + } |
| + return held, nil |
| +} |
diff --git a/internal/instancectl/egress_dropin_linux.go b/internal/instancectl/egress_dropin_linux.go| new file mode 100644 |
| index 000000000..4a97be3db |
| --- /dev/null |
| +++ b/internal/instancectl/egress_dropin_linux.go |
| @@ -0,0 +1,77 @@ |
| +//go:build linux |
| + |
| +package instancectl |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// readTrustedDropin reads <dir>/<sub>/<name> as a trusted root file: no |
| +// component of the path is followed through a symlink (O_NOFOLLOW at each |
| +// step from /), dir and sub are directories and name a regular file with |
| +// one link, each owned by owner (root in production) and not group- or |
| +// world-writable. A missing component is an error that matches |
| +// fs.ErrNotExist. |
| +func readTrustedDropin(dir, sub, name string, owner uint32) ([]byte, error) { |
| + if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir || dir == "/" || strings.Contains(sub, "/") || strings.Contains(name, "/") { |
| + return nil, os.ErrPermission |
| + } |
| + fd, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return nil, err |
| + } |
| + parts := append(strings.Split(strings.TrimPrefix(dir, "/"), "/"), sub) |
| + for i, part := range parts { |
| + next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| + unix.Close(fd) |
| + if err != nil { |
| + return nil, fmt.Errorf("%s: %w", part, err) |
| + } |
| + fd = next |
| + // The control directory and the slice's: root's own. |
| + if i >= len(parts)-2 { |
| + if err := trustedFD(fd, owner, unix.S_IFDIR); err != nil { |
| + unix.Close(fd) |
| + return nil, fmt.Errorf("%s: %w", part, err) |
| + } |
| + } |
| + } |
| + ffd, err := unix.Openat(fd, name, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0) |
| + unix.Close(fd) |
| + if err != nil { |
| + return nil, fmt.Errorf("%s: %w", name, err) |
| + } |
| + f := os.NewFile(uintptr(ffd), name) |
| + defer f.Close() |
| + if err := trustedFD(ffd, owner, unix.S_IFREG); err != nil { |
| + return nil, fmt.Errorf("%s: %w", name, err) |
| + } |
| + b, err := io.ReadAll(io.LimitReader(f, maxAllowDropin+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(b) > maxAllowDropin { |
| + return nil, errors.New("the drop-in is too large") |
| + } |
| + return b, nil |
| +} |
| + |
| +// trustedFD: fd is of kind, owned by owner, not group- or world-writable, |
| +// and, for a file, has one link. |
| +func trustedFD(fd int, owner uint32, kind uint32) error { |
| + var st unix.Stat_t |
| + if err := unix.Fstat(fd, &st); err != nil { |
| + return err |
| + } |
| + if st.Uid != owner || st.Mode&unix.S_IFMT != kind || st.Mode&0o022 != 0 || (kind == unix.S_IFREG && st.Nlink != 1) { |
| + return os.ErrPermission |
| + } |
| + return nil |
| +} |
diff --git a/internal/instancectl/egress_dropin_other.go b/internal/instancectl/egress_dropin_other.go| new file mode 100644 |
| index 000000000..d34a524ce |
| --- /dev/null |
| +++ b/internal/instancectl/egress_dropin_other.go |
| @@ -0,0 +1,11 @@ |
| +//go:build !linux |
| + |
| +package instancectl |
| + |
| +import "errors" |
| + |
| +// readTrustedDropin reads systemd's runtime drop-ins, which only a linux |
| +// box has; elsewhere it fails, and a start that needs it is refused. |
| +func readTrustedDropin(string, string, string, uint32) ([]byte, error) { |
| + return nil, errors.New("systemd drop-ins are read on linux only") |
| +} |
diff --git a/internal/instancectl/egress_restart_linux_test.go b/internal/instancectl/egress_restart_linux_test.go| index 9c3d37c05..438ccc95d 100644 |
| --- a/internal/instancectl/egress_restart_linux_test.go |
| +++ b/internal/instancectl/egress_restart_linux_test.go |
| @@ -592,20 +592,154 @@ func TestEgressStartRefusedWhileARevokeIsOwed(t *testing.T) { |
| t.Fatalf("wrote %q", sets) |
| } |
| }) |
| - t.Run("nothing known", func(t *testing.T) { |
| - ctl, e, _ := restartBox(t, egressHost) // the slice holds 10.0.5.20/32, unread |
| - failReads(e) |
| - if err := e.AssertStart(context.Background(), egressHost); err != nil { |
| - t.Fatalf("AssertStart = %v; a slice not known to hold an allow starts as on main", err) |
| - } |
| - if rep := e.Reports()[egressHost]; rep.State != EgressFailing { |
| - t.Fatalf("report = %+v, want failing", rep) |
| - } |
| - if err := e.Assert(context.Background(), egressHost); err == nil { |
| - t.Fatal("Assert (the sweep, POST /egress) no longer fails on a failed read") |
| - } |
| - if sets := ctl.sets(); len(sets) != 0 { |
| - t.Fatalf("wrote %q", sets) |
| + // A control service that restarted knows nothing of the slice; the |
| + // slice's runtime drop-in, which outlives it, decides (Task 15 review |
| + // ruling on finding 1). |
| + for _, tc := range []struct { |
| + name string |
| + dropin string // "" is none |
| + writable bool // the drop-in group-writable: not a file root can trust |
| + start bool |
| + refusal string |
| + }{ |
| + {name: "a restarted service, an allow on disk", dropin: "[Slice]\nIPAddressAllow=\nIPAddressAllow=10.0.5.20/32\n", |
| + refusal: "refusing the start: its runtime allow drop-in sets an allow"}, |
| + {name: "a restarted service, an untrusted drop-in", dropin: "[Slice]\nIPAddressAllow=\n", writable: true, |
| + refusal: "refusing the start: its runtime allow drop-in could not be read"}, |
| + {name: "a restarted service, the reset on disk", dropin: "[Slice]\nIPAddressAllow=\n", start: true}, |
| + {name: "a restarted service, no drop-in", start: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + ctl, e, _ := restartBox(t, egressHost) // the slice holds 10.0.5.20/32, unread |
| + dir := dropinBox(t, e, slice, tc.dropin) |
| + if tc.writable { |
| + if err := os.Chmod(filepath.Join(dir, slice+".d", allowDropinName), 0o664); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + failReads(e) |
| + err := e.AssertStart(context.Background(), egressHost) |
| + if tc.start && err != nil { |
| + t.Fatalf("AssertStart = %v; a slice with no allow known or on disk starts as on main", err) |
| + } |
| + if !tc.start && (err == nil || !strings.Contains(err.Error(), tc.refusal)) { |
| + t.Fatalf("AssertStart = %v; want the start refused: %s", err, tc.refusal) |
| + } |
| + if rep := e.Reports()[egressHost]; rep.State != EgressFailing { |
| + t.Fatalf("report = %+v, want failing", rep) |
| + } |
| + if err := e.Assert(context.Background(), egressHost); err == nil { |
| + t.Fatal("Assert (the sweep, POST /egress) no longer fails on a failed read") |
| + } |
| + if sets := ctl.sets(); len(sets) != 0 { |
| + t.Fatalf("wrote %q", sets) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// dropinBox points e at a runtime control directory of the test's own, |
| +// owned by the test's user, holding slice's IPAddressAllow drop-in with |
| +// body ("" is no drop-in), and returns the directory. |
| +func dropinBox(t *testing.T, e *EgressAsserter, slice, body string) string { |
| + t.Helper() |
| + root, err := filepath.EvalSymlinks(t.TempDir()) // the reader follows no symlink |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := filepath.Join(root, "system.control") |
| + if err := os.MkdirAll(filepath.Join(dir, slice+".d"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if body != "" { |
| + if err := os.WriteFile(filepath.Join(dir, slice+".d", allowDropinName), []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| } |
| - }) |
| + } |
| + e.controlDir, e.dropinOwner = dir, uint32(os.Getuid()) |
| + return dir |
| +} |
| + |
| +// TestSliceAllowOnDisk: the slice's runtime drop-in is read as a trusted |
| +// root file and applied as systemd applies it; anything it cannot trust |
| +// or understand is an error, which refuses the start. |
| +func TestSliceAllowOnDisk(t *testing.T) { |
| + slice := SliceName(egressHost) |
| + const systemdAllow = "# This is a drop-in unit file extension, created via \"systemctl set-property\"\n# or an equivalent operation. Do not edit.\n[Slice]\nIPAddressAllow=\nIPAddressAllow=10.0.5.20/32\n" |
| + for _, tc := range []struct { |
| + name string |
| + body string |
| + setup func(t *testing.T, e *EgressAsserter, dir string) |
| + held bool |
| + err bool |
| + }{ |
| + {name: "no drop-in", body: ""}, |
| + {name: "no slice directory", setup: func(t *testing.T, _ *EgressAsserter, dir string) { |
| + if err := os.Remove(filepath.Join(dir, slice+".d")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {name: "no control directory", setup: func(t *testing.T, e *EgressAsserter, dir string) { |
| + e.controlDir = filepath.Join(dir, "absent") |
| + }}, |
| + {name: "an allow, as systemd writes it", body: systemdAllow, held: true}, |
| + {name: "the empty reset", body: "[Slice]\nIPAddressAllow=\n"}, |
| + {name: "an allow, then the reset", body: "[Slice]\nIPAddressAllow=10.0.5.20/32\nIPAddressAllow=\n"}, |
| + {name: "another property", body: "[Slice]\nMemoryMax=1\n", err: true}, |
| + {name: "another section", body: "[Service]\nIPAddressAllow=10.0.5.20/32\n", err: true}, |
| + {name: "a symlinked drop-in", setup: func(t *testing.T, _ *EgressAsserter, dir string) { |
| + target := filepath.Join(dir, "elsewhere.conf") |
| + if err := os.WriteFile(target, []byte("[Slice]\nIPAddressAllow=\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(target, filepath.Join(dir, slice+".d", allowDropinName)); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, err: true}, |
| + {name: "a symlinked slice directory", setup: func(t *testing.T, _ *EgressAsserter, dir string) { |
| + other := filepath.Join(dir, "other.d") |
| + if err := os.Mkdir(other, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(other, allowDropinName), []byte("[Slice]\nIPAddressAllow=\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Remove(filepath.Join(dir, slice+".d")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(other, filepath.Join(dir, slice+".d")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, err: true}, |
| + {name: "a group-writable drop-in", body: "[Slice]\nIPAddressAllow=\n", setup: func(t *testing.T, _ *EgressAsserter, dir string) { |
| + if err := os.Chmod(filepath.Join(dir, slice+".d", allowDropinName), 0o664); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, err: true}, |
| + {name: "a world-writable slice directory", body: "[Slice]\nIPAddressAllow=\n", setup: func(t *testing.T, _ *EgressAsserter, dir string) { |
| + if err := os.Chmod(filepath.Join(dir, slice+".d"), 0o777); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, err: true}, |
| + {name: "a drop-in with two links", body: "[Slice]\nIPAddressAllow=\n", setup: func(t *testing.T, _ *EgressAsserter, dir string) { |
| + if err := os.Link(filepath.Join(dir, slice+".d", allowDropinName), filepath.Join(dir, "linked.conf")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, err: true}, |
| + {name: "another owner", body: "[Slice]\nIPAddressAllow=\n", setup: func(t *testing.T, e *EgressAsserter, _ string) { |
| + e.dropinOwner = uint32(os.Getuid()) + 1 // root's files must be root's |
| + }, err: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + e := newEgressAsserter(newEgressCtl(), staticSource(EgressPolicy{}, nil)) |
| + dir := dropinBox(t, e, slice, tc.body) |
| + if tc.setup != nil { |
| + tc.setup(t, e, dir) |
| + } |
| + held, err := e.sliceAllowOnDisk(slice) |
| + if held != tc.held || (err != nil) != tc.err { |
| + t.Fatalf("sliceAllowOnDisk = %v, %v; want %v, error %v", held, err, tc.held, tc.err) |
| + } |
| + }) |
| + } |
| } |
diff --git a/internal/instancectl/egress_startpaths_test.go b/internal/instancectl/egress_startpaths_test.go| index 2e678185a..5a88ba6aa 100644 |
| --- a/internal/instancectl/egress_startpaths_test.go |
| +++ b/internal/instancectl/egress_startpaths_test.go |
| @@ -66,6 +66,8 @@ func startPathAsserter(systemctl func(context.Context, ...string) (string, error |
| // As production, a cgroup root (one with no carlos.slice: nothing |
| // runs for a change to be applied to). |
| CgroupRoot: os.TempDir(), |
| + // No runtime drop-in for any slice. |
| + controlDir: noControlDir, |
| } |
| } |
diff --git a/internal/instancectl/egress_test.go b/internal/instancectl/egress_test.go| index 897bfad37..a134ebbc8 100644 |
| --- a/internal/instancectl/egress_test.go |
| +++ b/internal/instancectl/egress_test.go |
| @@ -121,9 +121,15 @@ func newEgressAsserter(ctl *egressCtl, src EgressSource) *EgressAsserter { |
| // populated. Tests of what runs set their own fixture tree. |
| CgroupRoot: os.TempDir(), |
| Logf: func(string, ...any) {}, |
| + // No runtime drop-ins: a directory that does not exist. Tests of |
| + // what one says make their own (dropinBox). |
| + controlDir: noControlDir, |
| } |
| } |
| +// noControlDir is a systemd runtime control directory that does not exist. |
| +const noControlDir = "/nonexistent-carlos-test/system.control" |
| + |
| func showCall(host string) string { return "show -p IPAddressAllow --value " + SliceName(host) } |
| // emptiedCalls are reach's systemctl calls after a revoke empties a slice |