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