| new file mode 100644 |
| index 000000000..f85fb835a |
| --- /dev/null |
| +++ b/internal/host/egress_claim_wiring_test.go |
| @@ -0,0 +1,366 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/apppolicy" |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootstate" |
| +) |
| + |
| +// Under host claims root writes no egress allow (ruling 9). These tests |
| +// build RunInstanceControl's claims branch the way production builds it |
| +// and prove that through it: newEgressClaimWiring. |
| + |
| +const claimEgressHost = "shop-a.example.com" |
| + |
| +// recordingClaimOwners is the registered owner provider: it records the |
| +// runtime resources OpenProductionClaimAssembly opens the owners with, and |
| +// opens them with the assembly world's owners. |
| +type recordingClaimOwners struct { |
| + inner ClaimOwnerProvider |
| + opened *[]ClaimRuntimeResources |
| +} |
| + |
| +func (o recordingClaimOwners) OpenClaimOwners(ctx context.Context, s release.Store, r ClaimRuntimeResources) (ClaimOwnerBindings, error) { |
| + *o.opened = append(*o.opened, r) |
| + return o.inner.OpenClaimOwners(ctx, s, r) |
| +} |
| + |
| +// claimEgressCtl is the one fake: systemctl for the claim units and the |
| +// egress asserter alike. It keeps each slice's IPAddressAllow as systemd |
| +// shows it and one run unit's state, and records every call in order. |
| +type claimEgressCtl struct { |
| + mu sync.Mutex |
| + calls [][]string |
| + allow map[string]string // slice -> IPAddressAllow as `show --value` prints it |
| + active bool |
| + invocations int |
| + group string // the run unit's control group, relative to the cgroup root |
| +} |
| + |
| +func (c *claimEgressCtl) run(_ context.Context, args ...string) (string, error) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.calls = append(c.calls, slices.Clone(args)) |
| + switch { |
| + case len(args) == 5 && args[0] == "show" && args[1] == "-p" && args[2] == "IPAddressAllow" && args[3] == "--value": |
| + return c.allow[args[4]], nil |
| + case len(args) == 4 && args[0] == "show" && args[1] == "-p": |
| + if !c.active { |
| + return fmt.Sprintf("ActiveState=inactive\nInvocationID=inv-%d\n", c.invocations), nil |
| + } |
| + return fmt.Sprintf("InvocationID=inv-%d\nMainPID=4242\nControlGroup=/%s\nActiveState=active\n", c.invocations, c.group), nil |
| + case len(args) >= 4 && args[0] == "set-property" && args[1] == "--runtime": |
| + for _, a := range args[3:] { |
| + if v, ok := strings.CutPrefix(a, "IPAddressAllow="); ok { |
| + c.allow[args[2]] = v |
| + } |
| + } |
| + return "", nil |
| + case len(args) == 2 && args[0] == "start": |
| + c.active = true |
| + c.invocations++ |
| + return "", nil |
| + case len(args) == 1 && args[0] == "daemon-reload": |
| + return "", nil |
| + } |
| + return "", fmt.Errorf("unexpected systemctl %q", args) |
| +} |
| + |
| +// take returns the calls since the last take. |
| +func (c *claimEgressCtl) take() [][]string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + out := c.calls |
| + c.calls = nil |
| + return out |
| +} |
| + |
| +func (c *claimEgressCtl) stopped() { c.mu.Lock(); c.active = false; c.mu.Unlock() } |
| + |
| +func (c *claimEgressCtl) held(slice string) string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.allow[slice] |
| +} |
| + |
| +// egressWrites are the calls that write a slice's IPAddressAllow, and the |
| +// index of each in calls. |
| +func egressWrites(calls [][]string) (writes [][]string, at []int) { |
| + for i, c := range calls { |
| + if len(c) > 0 && c[0] == "set-property" && slices.ContainsFunc(c, func(a string) bool { return strings.HasPrefix(a, "IPAddressAllow=") }) { |
| + writes, at = append(writes, c), append(at, i) |
| + } |
| + } |
| + return writes, at |
| +} |
| + |
| +// egressClaimWiring is RunInstanceControl's claims branch, built as |
| +// production builds it, up to bindProductionClaimUnits: |
| +// - the runtime resources are the branch's own (instanceControlClaimResources), |
| +// with the box paths moved into temporary directories; |
| +// - ensureProductionClaimAssembly opens the assembly through the real |
| +// OpenProductionClaimAssembly over a signed roster (newAssemblyWorld), |
| +// with the registered owner provider recording what it was opened with; |
| +// - bindProductionClaimUnits binds the launch's units, over the launch |
| +// fixture TestPlan14ProductionUnitStartupIsolation uses (the production |
| +// launch root needs systemd and the carlos account). |
| +// |
| +// The one fake is systemctl, shared by the units and the asserter. |
| +type egressClaimWiring struct { |
| + ctx context.Context |
| + opened []ClaimRuntimeResources |
| + asserter *instancectl.EgressAsserter // what the branch hands RunWithClaim |
| + launch ClaimRootWithLaunch |
| + store *egressCountingStore |
| + ctl *claimEgressCtl |
| + |
| + logMu sync.Mutex |
| + logs []string // the asserter's log lines |
| +} |
| + |
| +func (e *egressClaimWiring) logf(format string, args ...any) { |
| + e.logMu.Lock() |
| + e.logs = append(e.logs, fmt.Sprintf(format, args...)) |
| + e.logMu.Unlock() |
| +} |
| + |
| +func (e *egressClaimWiring) takeLogs() []string { |
| + e.logMu.Lock() |
| + defer e.logMu.Unlock() |
| + out := e.logs |
| + e.logs = nil |
| + return out |
| +} |
| + |
| +// newEgressClaimWiring builds the wiring over a box whose registry row for |
| +// claimEgressHost carries the allow 10.0.5.20 an hour from expiry, whose |
| +// claims store holds a policy signed for it, and whose slice holds |
| +// 10.0.5.20/32: a box switched to claims with an allow granted before. |
| +// It swaps package state (the owner registration, the claim-unit stores, |
| +// the assembly world's roots), so its callers do not run in parallel. |
| +func newEgressClaimWiring(t *testing.T) *egressClaimWiring { |
| + t.Helper() |
| + w := newAssemblyWorld(t) |
| + reg, dd := egressRegistry(t) |
| + for _, dir := range []string{".hostclaims", "hostguard", "instances"} { |
| + if err := os.Mkdir(filepath.Join(dd, dir), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + upsertRows(t, reg, nestedRow(dd, claimEgressHost)) |
| + setAllow(t, reg, claimEgressHost, "10.0.5.20", unixText(time.Now().Add(time.Hour))) |
| + _, priv, err := ed25519.GenerateKey(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := apppolicy.PutIfMatch(t.Context(), w.store, priv, apppolicy.Policy{V: 1, Account: "abc", App: "shop", Revision: 1, |
| + SignedAt: time.Now(), EgressAllow: []string{"10.0.5.20"}}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if keys, err := w.store.List(t.Context(), apppolicy.Prefix); err != nil || len(keys) != 1 { |
| + t.Fatalf("the signed policy is not in the claims store: %v %v", keys, err) |
| + } |
| + e := &egressClaimWiring{ |
| + store: &egressCountingStore{Store: w.store}, |
| + ctl: &claimEgressCtl{allow: map[string]string{instancectl.SliceName(claimEgressHost): "10.0.5.20/32"}, |
| + group: instancectl.ClaimUnitControlGroup(claimEgressHost)}, |
| + } |
| + |
| + // The claim owners read the claims store through the counter too: the |
| + // retirement authority must hold the very store the assembly is opened |
| + // with (claimEvidenceCoordinator). |
| + authority := *w.owners.base.RetirementAuthority |
| + authority.Store, authority.Directory.Store = e.store, e.store |
| + w.owners.base.RetirementAuthority = &authority |
| + w.owners.dir.Store = e.store |
| + |
| + claimOwnerRegistration.Lock() |
| + previous := claimOwnerRegistration.Provider |
| + claimOwnerRegistration.Provider = recordingClaimOwners{inner: w.owners, opened: &e.opened} |
| + claimOwnerRegistration.Unlock() |
| + t.Cleanup(func() { |
| + claimOwnerRegistration.Lock() |
| + claimOwnerRegistration.Provider = previous |
| + claimOwnerRegistration.Unlock() |
| + }) |
| + |
| + // RunInstanceControl's claims branch, in its order. |
| + ctx := context.WithValue(t.Context(), claimEntryKey{}, claimEntry{Enabled: true, FlagRead: true, Store: e.store}) |
| + r := instanceControlClaimResources(reg, dd) |
| + if r.Egress == nil { |
| + t.Fatal("the claims branch's runtime resources carry no egress asserter") |
| + } |
| + r.OptDir, r.UnitsDir = w.r.OptDir, w.r.UnitsDir |
| + r.Egress.Systemctl = e.ctl.run |
| + r.Egress.Logf = e.logf |
| + ctx = withClaimRuntimeResources(ctx, r) |
| + ctx, err = ensureProductionClaimAssembly(ctx) |
| + if err != nil { |
| + t.Fatal("the claim assembly:", err) |
| + } |
| + entry, _ := ctx.Value(claimEntryKey{}).(claimEntry) |
| + if entry.Assembly == nil { |
| + t.Fatal("no assembly") |
| + } |
| + t.Cleanup(func() { entry.Assembly.Close(context.Background()) }) |
| + |
| + f, _, _ := generationLaunchFixture(t) |
| + oldOpen, oldMaterials := openClaimUnitBindings, openClaimUnitMaterializations |
| + t.Cleanup(func() { openClaimUnitBindings, openClaimUnitMaterializations = oldOpen, oldMaterials }) |
| + openClaimUnitBindings = func() (rootstate.Store, error) { return &rollbackDisk{dir: t.TempDir()}, nil } |
| + openClaimUnitMaterializations = func() (rootstate.Store, error) { return &rollbackDisk{dir: t.TempDir()}, nil } |
| + base := instancectl.ClaimUnits{Systemctl: e.ctl.run, CgroupRoot: t.TempDir(), ExeRoot: t.TempDir(), UnitRoot: t.TempDir(), DataRoot: t.TempDir(), Poll: time.Millisecond} |
| + f.root.Units = base |
| + e.launch = ClaimRootWithLaunch{Launch: f.root} |
| + e.launch.Root.Stop.Coordinator.Kernel = claimUnitStopKernel{Units: base} |
| + if err := bindProductionClaimUnits(ctx, &e.launch, entry.Assembly); err != nil { |
| + t.Fatal("bind the claim units:", err) |
| + } |
| + e.ctx, e.asserter = ctx, claimRuntimeEgress(ctx) |
| + return e |
| +} |
| + |
| +// units is the ClaimUnits the bound dispatch selects for claimEgressHost. |
| +func (e *egressClaimWiring) units(t *testing.T) instancectl.ClaimUnits { |
| + t.Helper() |
| + d, ok := e.launch.Launch.Units.(claimUnitDispatch) |
| + if !ok { |
| + t.Fatalf("the launch's units are %T, not the bound dispatch", e.launch.Launch.Units) |
| + } |
| + u, err := d.selected(claimEgressHost) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return u |
| +} |
| + |
| +// TestClaimEgressIsInTheRuntimeResourcesBeforeTheAssembly (Astra plan |
| +// R1-5): the claims asserter is in the runtime resources when the |
| +// assembly is opened, and it is the one asserter: the same pointer |
| +// bindProductionClaimUnits puts in ClaimUnits.Egress and the branch hands |
| +// RunWithClaim. Its source closes every host under claims. |
| +// |
| +// Not parallel: newEgressClaimWiring swaps package state. |
| +func TestClaimEgressIsInTheRuntimeResourcesBeforeTheAssembly(t *testing.T) { |
| + e := newEgressClaimWiring(t) |
| + if len(e.opened) != 1 { |
| + t.Fatalf("the owners were opened %d times, want 1", len(e.opened)) |
| + } |
| + got := e.opened[0].Egress |
| + if got == nil { |
| + t.Fatal("the assembly was opened with no egress asserter in the runtime resources") |
| + } |
| + if e.asserter != got { |
| + t.Fatalf("the branch hands RunWithClaim %p, not the asserter the assembly saw (%p)", e.asserter, got) |
| + } |
| + if d := e.launch.Launch.Units.(claimUnitDispatch); d.base.Egress != got { |
| + t.Fatalf("bindProductionClaimUnits bound %p, not %p", d.base.Egress, got) |
| + } |
| + if u := e.units(t); u.Egress != got { |
| + t.Fatalf("the units selected for %s carry %p, not %p", claimEgressHost, u.Egress, got) |
| + } |
| + if k, ok := e.launch.Root.Stop.Coordinator.Kernel.(claimUnitStopKernel); !ok || k.Units.(claimUnitDispatch).base.Egress != got { |
| + t.Fatal("the stop kernel's units are not the bound dispatch over the same asserter") |
| + } |
| + pol, err := got.Source(e.ctx, claimEgressHost) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := (instancectl.EgressPolicy{Closed: instancectl.EgressUnderClaims, Detail: claimsEgressDetail}); !reflect.DeepEqual(pol, want) { |
| + t.Fatalf("the asserter's source answers %+v, want %+v", pol, want) |
| + } |
| +} |
| + |
| +// TestClaimEgressIsClosedThroughTheClaimWiring (Review Focus 2): a box |
| +// switched to claims with an allow granted before (registry row, signed |
| +// policy in the claims store, the slice holding 10.0.5.20/32). A start |
| +// through the bound units resets the slice, and that reset is the only |
| +// egress write, before systemctl start; GET /egress reports under_claims; |
| +// no store request touched control/app-policy/. A second start, the slice |
| +// now empty, writes nothing for egress. |
| +// |
| +// Not parallel: newEgressClaimWiring swaps package state. |
| +func TestClaimEgressIsClosedThroughTheClaimWiring(t *testing.T) { |
| + e := newEgressClaimWiring(t) |
| + slice := instancectl.SliceName(claimEgressHost) |
| + in := instancectl.ClaimUnit{Host: claimEgressHost, Executable: filepath.Join(t.TempDir(), "shop"), MemoryMax: cgroup.TierDefault.MemoryMax} |
| + e.ctl.take() |
| + |
| + if _, err := e.units(t).Start(e.ctx, in); err != nil { |
| + t.Fatal("start:", err) |
| + } |
| + calls := e.ctl.take() |
| + writes, at := egressWrites(calls) |
| + if want := [][]string{{"set-property", "--runtime", slice, "IPAddressAllow="}}; !reflect.DeepEqual(writes, want) { |
| + t.Fatalf("egress writes = %q, want only the reset %q\ncalls: %q", writes, want, calls) |
| + } |
| + start := slices.IndexFunc(calls, func(c []string) bool { return len(c) > 0 && c[0] == "start" }) |
| + if start < 0 || at[0] > start { |
| + t.Fatalf("the reset (call %d) is not before systemctl start (call %d): %q", at[0], start, calls) |
| + } |
| + if held := e.ctl.held(slice); held != "" { |
| + t.Fatalf("the slice still holds %q", held) |
| + } |
| + if want := []string{"egress: " + slice + ": allow is now nothing"}; !reflect.DeepEqual(e.takeLogs(), want) { |
| + t.Fatalf("the asserter's log is not the one reset line %q", want) |
| + } |
| + |
| + // GET /egress, through the handler RunWithClaim serves with this asserter. |
| + srv := &instancectl.Server{Egress: e.asserter} |
| + rec := httptest.NewRecorder() |
| + srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/egress", nil)) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("GET /egress: %d %s", rec.Code, rec.Body) |
| + } |
| + var st instancectl.EgressStatus |
| + if err := json.Unmarshal(rec.Body.Bytes(), &st); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := (instancectl.EgressReport{State: instancectl.EgressUnderClaims, Detail: claimsEgressDetail}); !reflect.DeepEqual(st.Hosts[claimEgressHost], want) { |
| + t.Fatalf("GET /egress for %s = %+v, want %+v", claimEgressHost, st.Hosts[claimEgressHost], want) |
| + } |
| + |
| + if got := e.store.under(apppolicy.Prefix); len(got) != 0 { |
| + t.Fatalf("root read the policy store under claims: %q", got) |
| + } |
| + if e.store.total() == 0 { |
| + t.Fatal("the counting store saw no request at all: it is not the store the claim wiring uses") |
| + } |
| + |
| + // The slice holds nothing now: a second start writes nothing for egress. |
| + e.ctl.stopped() |
| + if _, err := e.units(t).Start(e.ctx, in); err != nil { |
| + t.Fatal("second start:", err) |
| + } |
| + calls = e.ctl.take() |
| + if writes, _ := egressWrites(calls); len(writes) != 0 { |
| + t.Fatalf("the second start wrote egress: %q", writes) |
| + } |
| + if logs := e.takeLogs(); len(logs) != 0 { |
| + t.Fatalf("the second start logged %q", logs) |
| + } |
| + if !slices.ContainsFunc(calls, func(c []string) bool { |
| + return reflect.DeepEqual(c, []string{"show", "-p", "IPAddressAllow", "--value", slice}) |
| + }) { |
| + t.Fatalf("the second start did not read the slice back: %q", calls) |
| + } |
| +} |