| index f85fb835a..86b061fc2 100644 |
| --- a/internal/host/egress_claim_wiring_test.go |
| +++ b/internal/host/egress_claim_wiring_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "crypto/ed25519" |
| "encoding/json" |
| "fmt" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| @@ -21,6 +22,7 @@ import ( |
| "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/release" |
| "github.com/carlosframework/platform/internal/rootstate" |
| ) |
| @@ -44,16 +46,21 @@ func (o recordingClaimOwners) OpenClaimOwners(ctx context.Context, s release.Sto |
| 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. |
| +// claimEgressCtl is the one fake: systemctl for the claim units, the |
| +// effective-unit check and the egress asserter alike. It keeps each |
| +// slice's IPAddressAllow as systemd shows it, one run unit's state and its |
| +// effective properties, and records every call in order. A start makes the |
| +// test process the unit's MainPID and runs onStart, which plays the |
| +// trampoline at the exec gate. |
| type claimEgressCtl struct { |
| mu sync.Mutex |
| calls [][]string |
| allow map[string]string // slice -> IPAddressAllow as `show --value` prints it |
| + props map[string]string // the ordinary run unit's effective properties |
| active bool |
| invocations int |
| group string // the run unit's control group, relative to the cgroup root |
| + onStart func() |
| } |
| |
| func (c *claimEgressCtl) run(_ context.Context, args ...string) (string, error) { |
| @@ -63,11 +70,17 @@ func (c *claimEgressCtl) run(_ context.Context, args ...string) (string, error) |
| 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) == 5 && args[0] == "show" && args[1] == "-p" && args[4] == "--all": |
| + var out strings.Builder |
| + for _, key := range strings.Split(args[2], ",") { |
| + out.WriteString(key + "=" + c.props[key] + "\n") |
| + } |
| + return out.String(), 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 |
| + return fmt.Sprintf("InvocationID=inv-%d\nMainPID=%d\nControlGroup=/%s\nActiveState=active\n", c.invocations, os.Getpid(), 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 { |
| @@ -78,6 +91,12 @@ func (c *claimEgressCtl) run(_ context.Context, args ...string) (string, error) |
| case len(args) == 2 && args[0] == "start": |
| c.active = true |
| c.invocations++ |
| + if c.onStart != nil { |
| + c.onStart() |
| + } |
| + return "", nil |
| + case len(args) == 2 && args[0] == "stop": |
| + c.active = false |
| return "", nil |
| case len(args) == 1 && args[0] == "daemon-reload": |
| return "", nil |
| @@ -102,6 +121,31 @@ func (c *claimEgressCtl) held(slice string) string { |
| return c.allow[slice] |
| } |
| |
| +// effectiveInstanceProps is what systemd shows for host's ordinary run |
| +// unit loaded from the installed template with no drop-in: the embedded |
| +// template's own values, its FragmentPath, and the host's slice. |
| +func effectiveInstanceProps(t *testing.T, host string) map[string]string { |
| + t.Helper() |
| + definition, err := unitsFS.ReadFile("units/carlos-instance@.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + props := map[string]string{"FragmentPath": claimInstanceTemplate, "DropInPaths": "", "NeedDaemonReload": "no", |
| + "ExecStart": "{ path=" + instancectl.SystemBinary + " ; argv[]=" + instancectl.SystemBinary + " instance-exec run " + provision.InstanceID(host) + " ; }"} |
| + for _, line := range strings.Split(string(definition), "\n") { |
| + k, v, ok := strings.Cut(line, "=") |
| + switch { |
| + case !ok || k == "ExecStart": |
| + case k == "IPAddressAllow" || k == "IPAddressDeny": |
| + props[k] = strings.TrimSpace(props[k] + " " + v) |
| + default: |
| + props[k] = v |
| + } |
| + } |
| + props["Slice"] = instancectl.SliceName(host) |
| + return props |
| +} |
| + |
| // 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) { |
| @@ -113,8 +157,16 @@ func egressWrites(calls [][]string) (writes [][]string, at []int) { |
| return writes, at |
| } |
| |
| +// claimControlArgs is what runClaimControl handed its runner: in |
| +// production, instancectl.RunWithClaim. |
| +type claimControlArgs struct { |
| + handler, heldRelease http.Handler |
| + hostApp func(string) (string, string, error) |
| + egress *instancectl.EgressAsserter |
| +} |
| + |
| // egressClaimWiring is RunInstanceControl's claims branch, built as |
| -// production builds it, up to bindProductionClaimUnits: |
| +// production builds it: |
| // - the runtime resources are the branch's own (instanceControlClaimResources), |
| // with the box paths moved into temporary directories; |
| // - ensureProductionClaimAssembly opens the assembly through the real |
| @@ -122,16 +174,21 @@ func egressWrites(calls [][]string) (writes [][]string, at []int) { |
| // 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). |
| +// launch root needs systemd and the carlos account); |
| +// - runClaimControl hands its arguments to a recorder in place of |
| +// instancectl.RunWithClaim, whose server needs root and the socket. |
| // |
| -// The one fake is systemctl, shared by the units and the asserter. |
| +// The fakes: systemctl, shared by the units, the effective-unit check and |
| +// the asserter; the installed template, read from a copy of the embedded |
| +// one (readClaimInstanceTemplate); and the trampoline at the exec gate. |
| type egressClaimWiring struct { |
| - ctx context.Context |
| - opened []ClaimRuntimeResources |
| - asserter *instancectl.EgressAsserter // what the branch hands RunWithClaim |
| - launch ClaimRootWithLaunch |
| - store *egressCountingStore |
| - ctl *claimEgressCtl |
| + ctx context.Context |
| + opened []ClaimRuntimeResources |
| + run claimControlArgs // what the branch hands RunWithClaim |
| + launch ClaimRootWithLaunch |
| + store *egressCountingStore |
| + ctl *claimEgressCtl |
| + exe string // the units' ExeRoot |
| |
| logMu sync.Mutex |
| logs []string // the asserter's log lines |
| @@ -156,7 +213,8 @@ func (e *egressClaimWiring) takeLogs() []string { |
| // 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. |
| +// the template reader, the assembly world's roots), so its callers do not |
| +// run in parallel. The exec gate's socket needs a short TMPDIR (/tmp/g). |
| func newEgressClaimWiring(t *testing.T) *egressClaimWiring { |
| t.Helper() |
| w := newAssemblyWorld(t) |
| @@ -182,7 +240,25 @@ func newEgressClaimWiring(t *testing.T) *egressClaimWiring { |
| 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)}, |
| + props: effectiveInstanceProps(t, claimEgressHost), group: instancectl.ClaimUnitControlGroup(claimEgressHost)}, |
| + } |
| + |
| + // The installed template, as a copy of the embedded one. |
| + template, err := unitsFS.ReadFile("units/carlos-instance@.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + installed := filepath.Join(t.TempDir(), "carlos-instance@.service") |
| + if err := os.WriteFile(installed, template, 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + oldTemplate := readClaimInstanceTemplate |
| + t.Cleanup(func() { readClaimInstanceTemplate = oldTemplate }) |
| + readClaimInstanceTemplate = func(path string) ([]byte, error) { |
| + if path != claimInstanceTemplate { |
| + return nil, fmt.Errorf("read %s, not the installed template", path) |
| + } |
| + return os.ReadFile(installed) |
| } |
| |
| // The claim owners read the claims store through the counter too: the |
| @@ -228,17 +304,67 @@ func newEgressClaimWiring(t *testing.T) *egressClaimWiring { |
| 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} |
| + roots, err := os.MkdirTemp("", "eg") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(roots) }) |
| + e.exe = filepath.Join(roots, "exe") |
| + base := instancectl.ClaimUnits{Systemctl: e.ctl.run, CgroupRoot: t.TempDir(), ExeRoot: e.exe, UnitRoot: filepath.Join(roots, "unit"), |
| + DataRoot: filepath.Join(roots, "data"), 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) |
| + runClaimControl(ctx, nil, e.launch, func(_ []string, handler, heldRelease http.Handler, hostApp func(string) (string, string, error), egress *instancectl.EgressAsserter) { |
| + e.run = claimControlArgs{handler: handler, heldRelease: heldRelease, hostApp: hostApp, egress: egress} |
| + }) |
| + e.ctx = ctx |
| return e |
| } |
| |
| +// startReserved starts claimEgressHost through the launch's units (the |
| +// bound dispatch: forStart, then StartReserved and its root check), with |
| +// the test playing the trampoline: on systemctl start it dials the exec |
| +// gate and presents the permit. |
| +func (e *egressClaimWiring) startReserved(t *testing.T) { |
| + t.Helper() |
| + permit := instancectl.ClaimExecPermit{Reservation: "a:main", Inputs: "inputs", BootID: "boot", SafeUntil: 200, Containment: 1} |
| + gate := make(chan error, 1) |
| + e.ctl.mu.Lock() |
| + e.ctl.onStart = func() { |
| + go func() { |
| + c, err := net.Dial("unix", filepath.Join(e.exe, ".claim", provision.InstanceID(claimEgressHost), "exec.sock")) |
| + if err != nil { |
| + gate <- err |
| + return |
| + } |
| + defer c.Close() |
| + if err = json.NewEncoder(c).Encode(permit); err == nil { |
| + var back instancectl.ClaimExecPermit |
| + err = json.NewDecoder(c).Decode(&back) |
| + } |
| + gate <- err |
| + }() |
| + } |
| + e.ctl.mu.Unlock() |
| + in := instancectl.ClaimUnit{Host: claimEgressHost, Executable: filepath.Join(t.TempDir(), "shop"), MemoryMax: cgroup.TierDefault.MemoryMax} |
| + launch := instancectl.Launch{Schema: instancectl.LaunchSchema, Host: claimEgressHost, Argv: []string{instancectl.LiveDir + "/" + claimEgressHost}} |
| + checks := 0 |
| + started, err := e.launch.Launch.Units.StartReserved(e.ctx, in, launch, permit, func() error { checks++; return nil }) |
| + if err != nil { |
| + t.Fatal("start:", err) |
| + } |
| + if err := <-gate; err != nil { |
| + t.Fatal("the trampoline at the exec gate:", err) |
| + } |
| + if started.MainPID != os.Getpid() || checks != 2 { |
| + t.Fatalf("started %+v after %d root checks, want this process and 2", started, checks) |
| + } |
| +} |
| + |
| // units is the ClaimUnits the bound dispatch selects for claimEgressHost. |
| func (e *egressClaimWiring) units(t *testing.T) instancectl.ClaimUnits { |
| t.Helper() |
| @@ -256,8 +382,8 @@ func (e *egressClaimWiring) units(t *testing.T) instancectl.ClaimUnits { |
| // 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. |
| +// bindProductionClaimUnits puts in ClaimUnits.Egress and runClaimControl |
| +// hands RunWithClaim. Its source closes every host under claims. |
| // |
| // Not parallel: newEgressClaimWiring swaps package state. |
| func TestClaimEgressIsInTheRuntimeResourcesBeforeTheAssembly(t *testing.T) { |
| @@ -269,8 +395,11 @@ func TestClaimEgressIsInTheRuntimeResourcesBeforeTheAssembly(t *testing.T) { |
| 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 e.run.egress != got { |
| + t.Fatalf("the branch hands RunWithClaim %p, not the asserter the assembly saw (%p)", e.run.egress, got) |
| + } |
| + if e.run.handler == nil || e.run.hostApp == nil || e.run.heldRelease != nil { |
| + t.Fatal("runClaimControl's other arguments are not the claims branch's", e.run.handler == nil, e.run.hostApp == nil, e.run.heldRelease != nil) |
| } |
| if d := e.launch.Launch.Units.(claimUnitDispatch); d.base.Egress != got { |
| t.Fatalf("bindProductionClaimUnits bound %p, not %p", d.base.Egress, got) |
| @@ -281,7 +410,7 @@ func TestClaimEgressIsInTheRuntimeResourcesBeforeTheAssembly(t *testing.T) { |
| 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) |
| + pol, err := e.run.egress.Source(e.ctx, claimEgressHost) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -292,22 +421,21 @@ func TestClaimEgressIsInTheRuntimeResourcesBeforeTheAssembly(t *testing.T) { |
| |
| // 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. |
| +// policy in the claims store, the slice holding 10.0.5.20/32). A reserved |
| +// start through the launch's bound units (forStart, StartReserved, the |
| +// root check, the exec gate) resets the slice, and that reset is the only |
| +// egress write, before systemctl start; GET /egress, served with what the |
| +// branch hands RunWithClaim, 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) |
| - } |
| + e.startReserved(t) |
| calls := e.ctl.take() |
| writes, at := egressWrites(calls) |
| if want := [][]string{{"set-property", "--runtime", slice, "IPAddressAllow="}}; !reflect.DeepEqual(writes, want) { |
| @@ -317,6 +445,9 @@ func TestClaimEgressIsClosedThroughTheClaimWiring(t *testing.T) { |
| 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 !slices.ContainsFunc(calls[:start], func(c []string) bool { return len(c) == 5 && c[4] == "--all" }) { |
| + t.Fatalf("the start did not pass the effective-unit check (forStart): %q", calls) |
| + } |
| if held := e.ctl.held(slice); held != "" { |
| t.Fatalf("the slice still holds %q", held) |
| } |
| @@ -324,8 +455,9 @@ func TestClaimEgressIsClosedThroughTheClaimWiring(t *testing.T) { |
| 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} |
| + // GET /egress, served with the arguments the branch hands RunWithClaim |
| + // (runWithClaim's own server needs root, the carlos user and the socket). |
| + srv := &instancectl.Server{ClaimStop: e.run.handler, ClaimHeldRelease: e.run.heldRelease, HostApp: e.run.hostApp, Egress: e.run.egress} |
| rec := httptest.NewRecorder() |
| srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/egress", nil)) |
| if rec.Code != http.StatusOK { |
| @@ -348,9 +480,7 @@ func TestClaimEgressIsClosedThroughTheClaimWiring(t *testing.T) { |
| |
| // 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) |
| - } |
| + e.startReserved(t) |
| calls = e.ctl.take() |
| if writes, _ := egressWrites(calls); len(writes) != 0 { |
| t.Fatalf("the second start wrote egress: %q", writes) |