carlos / platform Public

instancectl: assert the egress allow on every start path (#328)

Server.Egress and ClaimUnits.Egress (nil is off) run EgressAsserter.Assert
after the tier step, or its populated-slice skip, and before systemctl
start on run, sidecar, seed, gen, cmd and the claim launch. An assert
error refuses the start: 502 "egress: <err>" (gen through fail, so its
files go), and the claim start returns it. With no policy the only new
call is the one IPAddressAllow read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4895e5954e26d2db0205861907c95c6f399941d5 parent fa9c586
6 files changed, +392 −4
  • internal/instancectl/claimunit.go +7 −0
  • internal/instancectl/cmd.go +5 −0
  • internal/instancectl/egress_startpaths_linux_test.go +58 −0
  • internal/instancectl/egress_startpaths_test.go +297 −0
  • internal/instancectl/gen.go +5 −0
  • internal/instancectl/server.go +20 −4
diff --git a/internal/instancectl/claimunit.go b/internal/instancectl/claimunit.go
index 5d099ab3d..d03d0cc4e 100644
--- a/internal/instancectl/claimunit.go
+++ b/internal/instancectl/claimunit.go
@@ -34,6 +34,10 @@ type ClaimUnits struct {
Room func() error
WaitBudget time.Duration
Poll time.Duration
+ // Egress asserts the host slice's egress allow after the tier and
+ // before systemctl start (#328); an assert error refuses the start.
+ // Nil is off.
+ Egress *EgressAsserter
}
// ClaimUnit is one start: the host, the verified build and the slice tier.
@@ -167,6 +171,9 @@ func (u ClaimUnits) start(ctx context.Context, in ClaimUnit, launch *Launch, che
if err := sliceTier(ctx, u.Systemctl, in.Host, tier); err != nil {
return ClaimUnitStarted{}, err
}
+ if err := u.Egress.Assert(ctx, in.Host); err != nil {
+ return ClaimUnitStarted{}, fmt.Errorf("egress: %w", err)
+ }
var invocation string
refuse := func(cause error) (ClaimUnitStarted, error) {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), u.budget())
diff --git a/internal/instancectl/cmd.go b/internal/instancectl/cmd.go
index ffd7de516..c55b4a569 100644
--- a/internal/instancectl/cmd.go
+++ b/internal/instancectl/cmd.go
@@ -87,6 +87,11 @@ func (s *Server) handleCmd(w http.ResponseWriter, r *http.Request) {
http.Error(w, "set-property: "+err.Error(), http.StatusBadGateway)
return
}
+ // The egress allow is asserted on a populated slice too (#328).
+ if err := s.Egress.Assert(ctx, req.host); err != nil {
+ http.Error(w, "egress: "+err.Error(), http.StatusBadGateway)
+ return
+ }
before := s.showValue(ctx, "InvocationID", unit)
if out, err := s.Systemctl(ctx, "start", "--no-block", unit); err != nil {
http.Error(w, "start: "+strings.TrimSpace(out+" "+err.Error()), http.StatusBadGateway)
diff --git a/internal/instancectl/egress_startpaths_linux_test.go b/internal/instancectl/egress_startpaths_linux_test.go
new file mode 100644
index 000000000..92448dbcf
--- /dev/null
+++ b/internal/instancectl/egress_startpaths_linux_test.go
@@ -0,0 +1,58 @@
+//go:build linux
+
+package instancectl
+
+import (
+ "errors"
+ "io"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The sidecar's populated-slice skip (a staged build on a populated slice
+// leaves the tier to the generation owner) still asserts the egress allow
+// before the start, and an assert error still refuses it (#328). The
+// staged-build fixture is linux-only, as in stagedexe_linux_test.go.
+func TestEgressAssertedBeforeStartStagedSidecar(t *testing.T) {
+ for _, failSet := range []error{nil, errors.New("exit status 1")} {
+ name := "asserted"
+ if failSet != nil {
+ name = "refused"
+ }
+ t.Run(name, func(t *testing.T) {
+ opt := t.TempDir()
+ staged := release.VersionPath(opt, release.OpsAccount, "v2", "blog")
+ digest := writeStaged(t, staged, "build v2")
+ ctl := &fakeCtl{answers: map[string]string{"show -p InvocationID --value": "abc123\n"}}
+ layer := &egressLayer{next: ctl.run, failSet: failSet}
+ _, c := newServer(t, ctl, func(s *Server) {
+ s.DropInDir, s.ExeRoot, s.OptDir = t.TempDir(), t.TempDir(), opt
+ s.HostApp = func(string) (string, string, error) { return release.OpsAccount, "blog", nil }
+ s.Egress = startPathAsserter(layer.run, allowOneSource)
+ populateSlice(t, s, genHost)
+ })
+ q := url.Values{"host": {genHost}, "role": {string(RoleSidecar)}, "memory_max": {startPathTier},
+ "exe": {staged}, "version": {"v2"}, "digest": {digest}}
+ resp := post(t, c, "/start?"+q.Encode())
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ calls := strings.Split(ctl.joined(), "\n")
+ if failSet == nil {
+ if resp.StatusCode != 200 {
+ t.Fatalf("status %d, body %q", resp.StatusCode, body)
+ }
+ checkEgressOrder(t, calls, genHost, "start "+UnitName(RoleSidecar, genHost), false)
+ return
+ }
+ if resp.StatusCode != 502 || !strings.HasPrefix(string(body), "egress: ") {
+ t.Fatalf("status %d, body %q; want 502 and egress: <err>", resp.StatusCode, body)
+ }
+ if callIndex(calls, setCall(genHost, "10.0.5.20/32")) < 0 || callIndex(calls, "start ") >= 0 {
+ t.Fatalf("want the write tried and no start:\n%s", strings.Join(calls, "\n"))
+ }
+ })
+ }
+}
diff --git a/internal/instancectl/egress_startpaths_test.go b/internal/instancectl/egress_startpaths_test.go
new file mode 100644
index 000000000..2706fcee6
--- /dev/null
+++ b/internal/instancectl/egress_startpaths_test.go
@@ -0,0 +1,297 @@
+package instancectl
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+)
+
+// egressLayer puts a slice's IPAddressAllow over a recording fake
+// systemctl (#328): next records every call, a set-property's
+// IPAddressAllow= assignments replace what show then reads back, and
+// failSet fails that set-property once it is recorded.
+type egressLayer struct {
+ next func(context.Context, ...string) (string, error)
+ mu sync.Mutex
+ held map[string]string // slice -> show's answer
+ failSet error
+}
+
+func (l *egressLayer) run(ctx context.Context, args ...string) (string, error) {
+ out, err := l.next(ctx, args...)
+ if err != nil {
+ return out, err
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ switch {
+ case len(args) == 5 && args[0] == "show" && args[1] == "-p" && args[2] == "IPAddressAllow" && args[3] == "--value":
+ return l.held[args[4]] + "\n", nil
+ case len(args) >= 4 && args[0] == "set-property" && strings.HasPrefix(args[3], "IPAddressAllow="):
+ if l.failSet != nil {
+ return "Failed to set unit properties", l.failSet
+ }
+ var v string
+ for _, a := range args[3:] {
+ v = strings.TrimPrefix(a, "IPAddressAllow=")
+ }
+ if l.held == nil {
+ l.held = map[string]string{}
+ }
+ l.held[args[2]] = v
+ return "", nil
+ }
+ return out, nil
+}
+
+// startPathAsserter is an asserter whose systemctl calls land in the
+// same transcript as the start path's own.
+func startPathAsserter(systemctl func(context.Context, ...string) (string, error), src EgressSource) *EgressAsserter {
+ return &EgressAsserter{
+ Systemctl: systemctl,
+ Source: src,
+ LocalAddrs: func() ([]netip.Prefix, error) { return []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}, nil },
+ }
+}
+
+var allowOneSource = staticSource(EgressPolicy{Allow: []string{"10.0.5.20"}}, nil)
+
+const startPathTier = "536870912"
+
+// startPathCase is one start path driven through the control service's
+// socket with a fake systemctl: the request, its fixture, and the
+// systemctl start it ends in.
+type startPathCase struct {
+ name string
+ path string
+ ctl func() *fakeCtl
+ setup func(t *testing.T, s *Server)
+ start string
+ tier bool // false: the populated-slice skip leaves the tier alone
+}
+
+func populateSlice(t *testing.T, s *Server, host string) {
+ t.Helper()
+ events := filepath.Join(s.CgroupRoot, parentSlices, SliceName(host), "cgroup.events")
+ if err := os.MkdirAll(filepath.Dir(events), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(events, []byte("populated 1\nfrozen 0\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func cmdStartCtl() *fakeCtl {
+ ctl := &fakeCtl{answers: map[string]string{
+ "show -p ActiveState --value": "inactive\n",
+ "show -p InvocationID --value": "old\n",
+ }}
+ ctl.onStart = func() { ctl.set("show -p InvocationID --value", "new\n") }
+ return ctl
+}
+
+func genStartSetup(t *testing.T, s *Server) { s.DropInDir, s.ExeRoot = t.TempDir(), t.TempDir() }
+
+func startPathCases() []startPathCase {
+ q := "host=" + genHost + "&memory_max=" + startPathTier
+ runCtl := func() *fakeCtl {
+ return &fakeCtl{answers: map[string]string{"show -p InvocationID --value": "abc123\n"}}
+ }
+ seedCtl := func() *fakeCtl {
+ return &fakeCtl{answers: map[string]string{
+ "show -p InvocationID,Result,ExecMainStatus,ExecMainCode": "InvocationID=feed\nResult=success\nExecMainStatus=0\nExecMainCode=exited\n",
+ }}
+ }
+ none := func(*testing.T, *Server) {}
+ return []startPathCase{
+ {name: "run", path: "/start?role=run&" + q, ctl: runCtl, setup: none, start: "start " + UnitName(RoleRun, genHost), tier: true},
+ {name: "sidecar", path: "/start?role=sidecar&" + q, ctl: runCtl, setup: none, start: "start " + UnitName(RoleSidecar, genHost), tier: true},
+ {name: "seed", path: "/seed?" + q, ctl: seedCtl, setup: none, start: "start " + UnitName(RoleSeed, genHost), tier: true},
+ {name: "gen", path: "/start?role=run&gen=7&" + q, ctl: genCtl, setup: genStartSetup, start: "start " + genUnit, tier: true},
+ {name: "gen populated", path: "/start?role=run&gen=7&" + q, ctl: genCtl, setup: func(t *testing.T, s *Server) {
+ genStartSetup(t, s)
+ populateSlice(t, s, genHost)
+ }, start: "start " + genUnit},
+ {name: "cmd", path: "/cmd?" + q, ctl: cmdStartCtl, setup: func(_ *testing.T, s *Server) { fastCmd(s) }, start: "start --no-block " + UnitName(RoleCmd, genHost), tier: true},
+ {name: "cmd populated", path: "/cmd?" + q, ctl: cmdStartCtl, setup: func(t *testing.T, s *Server) {
+ fastCmd(s)
+ populateSlice(t, s, genHost)
+ }, start: "start --no-block " + UnitName(RoleCmd, genHost)},
+ }
+}
+
+// runStartPath starts tc through the control service with egress set by
+// withEgress (nil leaves Server.Egress nil) and returns the status, body
+// and the server.
+func runStartPath(t *testing.T, tc startPathCase, ctl *fakeCtl, withEgress func(*Server)) (int, string, *Server) {
+ t.Helper()
+ s, c := newServer(t, ctl, func(s *Server) {
+ tc.setup(t, s)
+ if withEgress != nil {
+ withEgress(s)
+ }
+ })
+ resp := post(t, c, tc.path)
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ return resp.StatusCode, string(body), s
+}
+
+func callIndex(calls []string, prefix string) int {
+ for i, c := range calls {
+ if strings.HasPrefix(c, prefix) {
+ return i
+ }
+ }
+ return -1
+}
+
+func tierPrefix(host string) string {
+ return "set-property --runtime " + SliceName(host) + " MemoryMax="
+}
+
+// checkEgressOrder: the tier call (when not skipped), then at once the
+// asserter's read, its write and its read back, then the start.
+func checkEgressOrder(t *testing.T, calls []string, host, start string, tier bool) {
+ t.Helper()
+ ti := callIndex(calls, tierPrefix(host))
+ read := callIndex(calls, showCall(host))
+ set := callIndex(calls, setCall(host, "10.0.5.20/32"))
+ st := callIndex(calls, start)
+ if read < 0 || set != read+1 || set+1 >= len(calls) || calls[set+1] != showCall(host) {
+ t.Fatalf("no read, write and read back of the allow in a row:\n%s", strings.Join(calls, "\n"))
+ }
+ if st < 0 || st < set {
+ t.Fatalf("the start is not after the allow's write:\n%s", strings.Join(calls, "\n"))
+ }
+ switch {
+ case tier && ti < 0:
+ t.Fatalf("no tier call:\n%s", strings.Join(calls, "\n"))
+ case tier && ti+1 != read:
+ t.Fatalf("the allow is not asserted straight after the tier:\n%s", strings.Join(calls, "\n"))
+ case !tier && ti >= 0:
+ t.Fatalf("the populated slice's tier was touched:\n%s", strings.Join(calls, "\n"))
+ }
+}
+
+func TestEgressAssertedBeforeStart(t *testing.T) {
+ for _, tc := range startPathCases() {
+ t.Run(tc.name, func(t *testing.T) {
+ ctl := tc.ctl()
+ status, body, _ := runStartPath(t, tc, ctl, func(s *Server) {
+ s.Egress = startPathAsserter((&egressLayer{next: ctl.run}).run, allowOneSource)
+ })
+ if status != 200 {
+ t.Fatalf("status %d, body %q", status, body)
+ }
+ checkEgressOrder(t, strings.Split(ctl.joined(), "\n"), genHost, tc.start, tc.tier)
+ })
+ }
+}
+
+func TestEgressFailureRefusesTheStart(t *testing.T) {
+ for _, tc := range startPathCases() {
+ t.Run(tc.name, func(t *testing.T) {
+ ctl := tc.ctl()
+ layer := &egressLayer{next: ctl.run, failSet: errors.New("exit status 1")}
+ status, body, s := runStartPath(t, tc, ctl, func(s *Server) {
+ s.Egress = startPathAsserter(layer.run, allowOneSource)
+ })
+ if status != 502 || !strings.HasPrefix(body, "egress: ") {
+ t.Fatalf("status %d, body %q; want 502 and egress: <err>", status, body)
+ }
+ calls := ctl.joined()
+ if !strings.Contains(calls, setCall(genHost, "10.0.5.20/32")) {
+ t.Fatalf("the allow was never written:\n%s", calls)
+ }
+ if strings.Contains(calls, "\nstart ") || strings.HasPrefix(calls, "start ") {
+ t.Fatalf("started despite the failed assert:\n%s", calls)
+ }
+ if strings.HasPrefix(tc.name, "gen") {
+ // Refused through fail: the generation's files go too.
+ if dropIn, exe := genFilesPresent(t, s, s.DropInDir); dropIn || exe {
+ t.Errorf("files left behind: drop-in %v exe %v", dropIn, exe)
+ }
+ }
+ })
+ }
+}
+
+// With Egress set and no policy, the only new call on any start path is
+// the asserter's one read: nothing is written.
+func TestStartTranscriptsUnchangedWithNoPolicy(t *testing.T) {
+ for _, tc := range startPathCases() {
+ t.Run(tc.name, func(t *testing.T) {
+ off := tc.ctl()
+ if status, body, _ := runStartPath(t, tc, off, nil); status != 200 {
+ t.Fatalf("Egress nil: status %d, body %q", status, body)
+ }
+ on := tc.ctl()
+ if status, body, _ := runStartPath(t, tc, on, func(s *Server) {
+ s.Egress = startPathAsserter(on.run, staticSource(EgressPolicy{}, nil))
+ }); status != 200 {
+ t.Fatalf("Egress set: status %d, body %q", status, body)
+ }
+ checkOneReadMore(t, off.joined(), on.joined(), genHost)
+ })
+ }
+ t.Run("claim", func(t *testing.T) {
+ u, offCtl, in, _ := claimUnitFixture(t)
+ if _, err := u.Start(context.Background(), in); err != nil {
+ t.Fatal(err)
+ }
+ u2, onCtl, in2, _ := claimUnitFixture(t)
+ u2.Egress = startPathAsserter(onCtl.run, staticSource(EgressPolicy{}, nil))
+ if _, err := u2.Start(context.Background(), in2); err != nil {
+ t.Fatal(err)
+ }
+ checkOneReadMore(t, offCtl.joined(), onCtl.joined(), in.Host)
+ })
+}
+
+func checkOneReadMore(t *testing.T, off, on string, host string) {
+ t.Helper()
+ var rest []string
+ reads := 0
+ for _, c := range strings.Split(on, "\n") {
+ if c == showCall(host) {
+ reads++
+ continue
+ }
+ rest = append(rest, c)
+ }
+ if reads != 1 || strings.Join(rest, "\n") != off {
+ t.Fatalf("%d allow reads; transcript with Egress:\n%s\nwithout:\n%s", reads, on, off)
+ }
+}
+
+func TestClaimUnitStartAssertsEgress(t *testing.T) {
+ t.Run("asserted before the start", func(t *testing.T) {
+ u, ctl, in, _ := claimUnitFixture(t)
+ u.Egress = startPathAsserter((&egressLayer{next: ctl.run}).run, allowOneSource)
+ if _, err := u.Start(context.Background(), in); err != nil {
+ t.Fatal(err)
+ }
+ checkEgressOrder(t, strings.Split(ctl.joined(), "\n"), in.Host, "start "+UnitName(RoleRun, in.Host), true)
+ })
+ t.Run("a failed assert refuses the start", func(t *testing.T) {
+ u, ctl, in, _ := claimUnitFixture(t)
+ u.Egress = startPathAsserter((&egressLayer{next: ctl.run, failSet: errors.New("exit status 1")}).run, allowOneSource)
+ if _, err := u.Start(context.Background(), in); err == nil || !strings.HasPrefix(err.Error(), "egress: ") {
+ t.Fatalf("Start = %v, want egress: <err>", err)
+ }
+ calls := ctl.joined()
+ if !strings.Contains(calls, setCall(in.Host, "10.0.5.20/32")) {
+ t.Fatalf("the allow was never written:\n%s", calls)
+ }
+ if strings.Contains(calls, "start ") {
+ t.Fatalf("started despite the failed assert:\n%s", calls)
+ }
+ })
+}
diff --git a/internal/instancectl/gen.go b/internal/instancectl/gen.go
index 54b308362..1b6d34ad8 100644
--- a/internal/instancectl/gen.go
+++ b/internal/instancectl/gen.go
@@ -199,6 +199,11 @@ func (s *Server) startGen(w http.ResponseWriter, r *http.Request, req request) {
return
}
}
+ // The egress allow is asserted on a populated slice too (#328).
+ if err := s.Egress.Assert(ctx, req.host); err != nil {
+ fail(http.StatusBadGateway, "egress: "+err.Error())
+ return
+ }
// From the start on, systemd may have started the unit, whatever the
// answer says. A failure past this point kills it and proves it empty
// before its files go; one that cannot prove that keeps the files and
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index 6ccff14ff..f692f20d7 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -29,10 +29,11 @@ import (
// Server is the root instance-control service (design §5). It does four
// things and nothing else: starts, stops and sweeps the four templates'
-// instances, sets a host slice's memory tier before a start, runs the
-// readiness probe, and answers /ready. Every systemctl argument it passes
-// is built from a validated host by UnitName/SliceName; nothing from a
-// request reaches systemctl as a string.
+// instances, sets a host slice's memory tier and egress allow (#328)
+// before a start, runs the readiness probe, and answers /ready. Every
+// systemctl argument it passes is built from a validated host by
+// UnitName/SliceName, and every allowed address comes from the egress
+// source; nothing from a request reaches systemctl as a string.
type Server struct {
ClaimStop http.Handler
// ClaimHeldRelease is the moves held-release route's handler (moves
@@ -120,6 +121,11 @@ type Server struct {
// ran: that is exactly the stale-service case of #256.
ExeCurrent func() error
+ // Egress asserts the host slice's egress allow on every start path,
+ // after the tier step (or its skip) and before systemctl start (#328);
+ // an assert error refuses the start. Nil is off.
+ Egress *EgressAsserter
+
// cgroupWaitBudget bounds a wait for an empty cgroup; tests shorten it.
cgroupWaitBudget time.Duration
@@ -514,6 +520,12 @@ func (s *Server) handleStart(w http.ResponseWriter, r *http.Request) {
http.Error(w, "set-property: "+err.Error(), http.StatusBadGateway)
return
}
+ // The egress allow is asserted whether or not the tier was left to
+ // the generation owner (#328).
+ if err := s.Egress.Assert(ctx, req.host); err != nil {
+ http.Error(w, "egress: "+err.Error(), http.StatusBadGateway)
+ return
+ }
// Never submitted once cancelled (#292): a /stop of this host cancels
// the attempt before it joins it, and the client may have gone.
if err := ctx.Err(); err != nil {
@@ -589,6 +601,10 @@ func (s *Server) handleSeed(w http.ResponseWriter, r *http.Request) {
http.Error(w, "set-property: "+err.Error(), http.StatusBadGateway)
return
}
+ if err := s.Egress.Assert(ctx, req.host); err != nil {
+ http.Error(w, "egress: "+err.Error(), http.StatusBadGateway)
+ return
+ }
// A oneshot's start job completes when ExecStart exits; RemainAfterExit
// keeps the unit loaded with its result until the stop below.