carlos / platform Public

host: the pre-claim egress source and the wholly-nested rail (#328)

registryEgressSource reads the agent-written registry's egress_allow and
policy_expires_at columns read-only, per call; an allow on a box that is
not wholly nested closes as not_nested, one with no usable or a past
expiry closes as expired, and on a registry error a host whose last
allow's expiry has passed closes rather than keeping it. boxWhollyNested
fails closed on any row shape it does not know; sidecar members make a
box mixed. RunInstanceControl's pre-claim branch now passes the
production asserter to RunWithRegistry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3154db49150f08ea628a82adac677c2633d44eb5 parent cbdb23f
3 files changed, +660 −1
  • internal/host/claimstop_run.go +3 −1
  • internal/host/egress_source.go +193 −0
  • internal/host/egress_source_test.go +464 −0
diff --git a/internal/host/claimstop_run.go b/internal/host/claimstop_run.go
index 7a7e07ff5..2147cb5a7 100644
--- a/internal/host/claimstop_run.go
+++ b/internal/host/claimstop_run.go
@@ -33,7 +33,9 @@ func RunInstanceControl(args []string) {
log.Fatal(err)
}
if !hostwrite.Enabled(claimEntryEnv(ctx)) {
- instancectl.RunWithRegistry(args, instanceRegistryHostApp(nil), nil)
+ // Pre-claim egress (#328): the agent-written registry's columns,
+ // read-only, behind the wholly-nested rail.
+ instancectl.RunWithRegistry(args, instanceRegistryHostApp(nil), newEgressAsserter(registryEgressSource(dataDir(), time.Now), registryEgressHosts(dataDir())))
return
}
reg, err := openServiceRegistry(filepath.Join(dataDir(), "registry.db"))
diff --git a/internal/host/egress_source.go b/internal/host/egress_source.go
new file mode 100644
index 000000000..952ef2794
--- /dev/null
+++ b/internal/host/egress_source.go
@@ -0,0 +1,193 @@
+package host
+
+// Root's pre-claim egress source (#328, spec §4.3 "before claims"): the
+// agent converges each app's signed policy into its instance rows'
+// egress_allow and policy_expires_at columns (plan 1), and root reads
+// those columns from the registry, read-only, to assert each host slice's
+// IPAddressAllow. This adds no trust the agent does not already hold: the
+// same registry decides which build a nested generation runs
+// (instanceRegistryHostApp). One extra rail: a box that is not wholly
+// nested gets no allow at all.
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/layout"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// boxWhollyNested: no row is a sidecar member (IsSidecar, Kind "sidecar":
+// outside the layout pass and run flat, spec §4.3 rev 8), and every
+// activator.ActivatorManaged row classifies LayoutNested under Classify with
+// the layout journal; reason names the first row that fails.
+//
+// The rail exists because a flat exec child runs as the agent's user and
+// may be able to write registry.db, the file this source trusts. So it
+// fails closed (ruling C14): a row counts only when it is a shape this
+// check knows. Known and harmless: an activator-managed row in the nested
+// layout (a rootfs app's row is one of these; it differs only in its
+// runtime, which this check never reads), an unflagged socket row (run by
+// another supervisor, nobody's to migrate or isolate, design §8.2 step 1)
+// and a static row (it runs no process). Every other row, including
+// unit-backed, tunnel-served and addr-only instance rows, service rows and
+// any kind this code does not know, makes the box not wholly nested.
+func boxWhollyNested(rows []registry.Route, dataDir string) (ok bool, reason string) {
+ in := activator.LayoutInputs{
+ DataDir: dataDir,
+ Journal: func(host string) bool { return layout.JournalPresent(dataDir, host) },
+ }
+ for _, rt := range rows {
+ switch {
+ case rt.IsSidecar():
+ return false, rt.Host + " is a sidecar member, which runs flat"
+ case rt.Kind == "static":
+ continue
+ case rt.Kind != "instance":
+ return false, fmt.Sprintf("%s is a %q row, which this check does not count as nested", rt.Host, rt.Kind)
+ case activator.ActivatorManaged(rt):
+ l, why := activator.Classify(rt, in)
+ if l == activator.LayoutNested {
+ continue
+ }
+ if why != "" {
+ return false, fmt.Sprintf("%s is %s: %s", rt.Host, l, why)
+ }
+ return false, fmt.Sprintf("%s is %s", rt.Host, l)
+ case rt.Socket != "" && !rt.Hibernate && rt.Backing == "" && rt.Tunnel == "":
+ continue
+ default:
+ return false, fmt.Sprintf("%s is an instance row the nested layout does not cover (backing %q, tunnel %q, addr %q)", rt.Host, rt.Backing, rt.Tunnel, rt.Addr)
+ }
+ }
+ return true, ""
+}
+
+// registryEgressSource is root's pre-claim EgressSource. Each call opens
+// the registry read-only, lists its rows once and answers from them: no
+// row for the host, or a row with no allow, is no policy; an allow on a
+// box that is not wholly nested is closed EgressNotNested; an allow whose
+// recorded expiry is missing, unreadable or not after now() is closed
+// EgressExpired (ruling C1); otherwise the column split on spaces. It
+// writes nothing: not to the registry, not to the layout tree.
+//
+// A registry that cannot be opened or listed is returned as an error, and
+// the asserter keeps the last policy it read, but only until the expiry
+// that allow was read under: the source remembers it per host, and past
+// it answers EgressExpired instead of the error (Astra plan R1-3).
+//
+// The registry is a local file: no store read.
+func registryEgressSource(dataDir string, now func() time.Time) instancectl.EgressSource {
+ var mu sync.Mutex
+ allowedUntil := map[string]time.Time{} // host -> the expiry its last allow was read under
+ path := filepath.Join(dataDir, "registry.db")
+ return func(_ context.Context, host string) (instancectl.EgressPolicy, error) {
+ rows, err := listRegistryReadOnly(path)
+ if err != nil {
+ mu.Lock()
+ until, ok := allowedUntil[host]
+ mu.Unlock()
+ if ok && !until.After(now()) {
+ return instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: expiredDetail(until)}, nil
+ }
+ return instancectl.EgressPolicy{}, err
+ }
+ pol, until := egressPolicyFrom(rows, host, dataDir, now())
+ mu.Lock()
+ if until.IsZero() {
+ delete(allowedUntil, host)
+ } else {
+ allowedUntil[host] = until
+ }
+ mu.Unlock()
+ return pol, nil
+ }
+}
+
+// egressPolicyFrom is host's policy from the box's rows at now, and, when
+// it is an allow, the expiry it holds until (zero otherwise).
+func egressPolicyFrom(rows []registry.Route, host, dataDir string, now time.Time) (instancectl.EgressPolicy, time.Time) {
+ var row *registry.Route
+ for i := range rows {
+ if rows[i].Host == host {
+ row = &rows[i]
+ break
+ }
+ }
+ if row == nil || strings.TrimSpace(row.EgressAllow) == "" {
+ return instancectl.EgressPolicy{}, time.Time{}
+ }
+ if ok, reason := boxWhollyNested(rows, dataDir); !ok {
+ return instancectl.EgressPolicy{Closed: instancectl.EgressNotNested, Detail: reason}, time.Time{}
+ }
+ secs, err := strconv.ParseInt(row.PolicyExpiresAt, 10, 64)
+ if err != nil || secs <= 0 {
+ // '' (none recorded), '0' and anything that is not a time: the
+ // agent writes no allow without an expiry, so none is honoured.
+ return instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: "no expiry recorded"}, time.Time{}
+ }
+ until := time.Unix(secs, 0)
+ if !until.After(now) {
+ return instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: expiredDetail(until)}, time.Time{}
+ }
+ return instancectl.EgressPolicy{Allow: strings.Fields(row.EgressAllow)}, until
+}
+
+func expiredDetail(until time.Time) string {
+ return "the policy expired at " + until.UTC().Format(time.RFC3339)
+}
+
+// listRegistryReadOnly opens the registry at path read-only (as
+// instanceRegistryHostApp does), lists every row once and closes it.
+func listRegistryReadOnly(path string) ([]registry.Route, error) {
+ reg, err := openServiceRegistryReadOnly(path)
+ if err != nil {
+ return nil, err
+ }
+ defer reg.Close()
+ return reg.List()
+}
+
+// registryEgressHosts names the box's hosts from the registry, read-only,
+// for the asserter's Loop to name the slices it finds before any Assert
+// has (instancectl.EgressAsserter.Hosts).
+func registryEgressHosts(dataDir string) func() ([]string, error) {
+ path := filepath.Join(dataDir, "registry.db")
+ return func() ([]string, error) {
+ rows, err := listRegistryReadOnly(path)
+ if err != nil {
+ return nil, err
+ }
+ hosts := make([]string, 0, len(rows))
+ for _, rt := range rows {
+ hosts = append(hosts, rt.Host)
+ }
+ return hosts, nil
+ }
+}
+
+// newEgressAsserter is root's production asserter over src: the real
+// systemctl, the box's own addresses from procfs, cgroupfs at
+// /sys/fs/cgroup for the sweep, hosts to name slices, and the log.
+func newEgressAsserter(src instancectl.EgressSource, hosts func() ([]string, error)) *instancectl.EgressAsserter {
+ return &instancectl.EgressAsserter{
+ Systemctl: func(ctx context.Context, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput()
+ return string(out), err
+ },
+ Source: src,
+ LocalAddrs: instancectl.LocalAddresses,
+ CgroupRoot: "/sys/fs/cgroup",
+ Hosts: hosts,
+ Logf: log.Printf,
+ }
+}
diff --git a/internal/host/egress_source_test.go b/internal/host/egress_source_test.go
new file mode 100644
index 000000000..559727532
--- /dev/null
+++ b/internal/host/egress_source_test.go
@@ -0,0 +1,464 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "reflect"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apppolicy"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// nestedRow and flatRow (systemapply_test.go) are an activator-managed
+// instance row at the nested and the flat defaults under a data dir.
+
+// rootfsRow is a rootfs app's row (rootfs apps #366): an ordinary nested
+// instance row that differs only in Route.Runtime "rootfs-v1". This branch
+// predates that column, so the field is set by name when the struct has
+// it: once the two branches meet, the row carries the rootfs runtime and
+// the table still wants it nested (ruling C14: never key on Runtime).
+func rootfsRow(dataDir, host string) registry.Route {
+ rt := nestedRow(dataDir, host)
+ if f := reflect.ValueOf(&rt).Elem().FieldByName("Runtime"); f.IsValid() && f.Kind() == reflect.String {
+ f.SetString("rootfs-v1")
+ }
+ return rt
+}
+
+func TestBoxWhollyNestedTable(t *testing.T) {
+ t.Parallel()
+ dd := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(dd, "layout"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(provision.LayoutJournalPath(dd, "moving.example.com"), []byte("{}"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ a, b := nestedRow(dd, "shop-a.example.com"), nestedRow(dd, "shop-b.example.com")
+ foreign := nestedRow(dd, "odd.example.com")
+ foreign.DBPath = "/srv/odd.db"
+ external := registry.Route{Host: "ext.example.com", Kind: "instance", Socket: "/run/ext/app.sock"}
+ sidecar := registry.Route{Host: "worker.example.com", Kind: "sidecar", App: "shop"}
+ static := registry.Route{Host: "files.example.com", Kind: "static"}
+ unit := registry.Route{Host: "unit.example.com", Kind: "instance", Hibernate: true, Addr: "127.0.0.1:8090", Backing: registry.BackingUnit}
+ tunnel := nestedRow(dd, "tun.example.com")
+ tunnel.Tunnel = "fleet/pi"
+ addrExec := registry.Route{Host: "tcp.example.com", Kind: "instance", Hibernate: true, Addr: "127.0.0.1:9000"}
+ service := registry.Route{Host: "svc.example.com", Kind: "service", Addr: "127.0.0.1:7000"}
+ unknown := registry.Route{Host: "new.example.com", Kind: "machine"}
+
+ for _, tc := range []struct {
+ name string
+ rows []registry.Route
+ ok bool
+ reason string // a substring the reason must hold
+ }{
+ {"empty box", nil, true, ""},
+ {"all nested", []registry.Route{a, b}, true, ""},
+ {"a rootfs row is nested", []registry.Route{a, rootfsRow(dd, "image.example.com")}, true, ""},
+ {"an external unflagged socket row does not count", []registry.Route{a, external}, true, ""},
+ {"a static row runs nothing", []registry.Route{a, static}, true, ""},
+ {"one flat", []registry.Route{a, flatRow(dd, "old.example.com"), b}, false, "old.example.com is flat"},
+ {"one fenced by a journal", []registry.Route{a, nestedRow(dd, "moving.example.com")}, false, "moving.example.com is fenced: layout migration in flight"},
+ {"one foreign", []registry.Route{a, foreign}, false, "odd.example.com is foreign"},
+ {"a sidecar member alone", []registry.Route{sidecar}, false, "worker.example.com is a sidecar member"},
+ {"a sidecar member beside nested rows", []registry.Route{a, sidecar, b}, false, "worker.example.com is a sidecar member"},
+ {"a unit-backed row", []registry.Route{a, unit}, false, "unit.example.com"},
+ {"a tunnel-served row", []registry.Route{a, tunnel}, false, "tun.example.com"},
+ {"an addr exec row", []registry.Route{a, addrExec}, false, "tcp.example.com"},
+ {"a service row", []registry.Route{a, service}, false, "svc.example.com"},
+ {"an unknown kind", []registry.Route{a, unknown}, false, "new.example.com"},
+ {"the first failing row is named", []registry.Route{a, flatRow(dd, "first.example.com"), sidecar}, false, "first.example.com is flat"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ok, reason := boxWhollyNested(tc.rows, dd)
+ if ok != tc.ok {
+ t.Fatalf("boxWhollyNested = %v (%q), want %v", ok, reason, tc.ok)
+ }
+ if tc.ok && reason != "" {
+ t.Fatalf("a wholly nested box has a reason: %q", reason)
+ }
+ if !strings.Contains(reason, tc.reason) {
+ t.Fatalf("reason %q does not hold %q", reason, tc.reason)
+ }
+ })
+ }
+}
+
+// egressRegistry is a temp registry in its own data dir (the package's
+// testRegistry: <dataDir>/registry.db) holding rows, with policy columns
+// set by SetPolicy, the agent's writer.
+func egressRegistry(t *testing.T) (*registry.Registry, string) {
+ t.Helper()
+ reg := testRegistry(t)
+ return reg, filepath.Dir(reg.Path())
+}
+
+func upsertRows(t *testing.T, reg *registry.Registry, rows ...registry.Route) {
+ t.Helper()
+ for _, rt := range rows {
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func setAllow(t *testing.T, reg *registry.Registry, host, allow string, expires string) {
+ t.Helper()
+ if err := reg.SetPolicy(host, allow, "", expires); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// testClock is a clock the test moves.
+type testClock struct {
+ mu sync.Mutex
+ now time.Time
+}
+
+func (c *testClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now }
+func (c *testClock) Set(t time.Time) { c.mu.Lock(); c.now = t; c.mu.Unlock() }
+
+func unixText(t time.Time) string { return strconv.FormatInt(t.Unix(), 10) }
+
+func readPolicy(t *testing.T, src instancectl.EgressSource, host string) instancectl.EgressPolicy {
+ t.Helper()
+ p, err := src(context.Background(), host)
+ if err != nil {
+ t.Fatalf("source(%s): %v", host, err)
+ }
+ return p
+}
+
+func wantPolicy(t *testing.T, got, want instancectl.EgressPolicy) {
+ t.Helper()
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("policy = %+v, want %+v", got, want)
+ }
+}
+
+func TestRegistryEgressSourceReadsTheColumn(t *testing.T) {
+ t.Parallel()
+ reg, dd := egressRegistry(t)
+ clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)}
+ upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"), nestedRow(dd, "shop-b.example.com"))
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20 fd00:5::20", unixText(clock.Now().Add(time.Hour)))
+ src := registryEgressSource(dd, clock.Now)
+
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20", "fd00:5::20"}})
+ // A row with no policy, and a host with no row: no allow, and nothing to say.
+ wantPolicy(t, readPolicy(t, src, "shop-b.example.com"), instancectl.EgressPolicy{})
+ wantPolicy(t, readPolicy(t, src, "gone.example.com"), instancectl.EgressPolicy{})
+}
+
+func TestRegistryEgressSourceClosesOnAMixedBox(t *testing.T) {
+ t.Parallel()
+ reg, dd := egressRegistry(t)
+ clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)}
+ upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"))
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour)))
+ src := registryEgressSource(dd, clock.Now)
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+
+ upsertRows(t, reg, flatRow(dd, "old.example.com"))
+ got := readPolicy(t, src, "shop-a.example.com")
+ if got.Closed != instancectl.EgressNotNested || len(got.Allow) != 0 || !strings.Contains(got.Detail, "old.example.com is flat") {
+ t.Fatalf("a mixed box: %+v, want closed %q naming old.example.com", got, instancectl.EgressNotNested)
+ }
+ // A host without a policy on the same box has nothing to close.
+ wantPolicy(t, readPolicy(t, src, "old.example.com"), instancectl.EgressPolicy{})
+
+ // A sidecar member makes the box mixed on its own.
+ if err := reg.Delete("old.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+ upsertRows(t, reg, registry.Route{Host: "worker.example.com", Kind: "sidecar", App: "shop"})
+ got = readPolicy(t, src, "shop-a.example.com")
+ if got.Closed != instancectl.EgressNotNested || !strings.Contains(got.Detail, "worker.example.com is a sidecar member") {
+ t.Fatalf("a box with a sidecar member: %+v, want closed %q naming it", got, instancectl.EgressNotNested)
+ }
+}
+
+// treeState is every file and directory under root: mode, size, mtime and
+// bytes.
+func treeState(t *testing.T, root string) map[string]string {
+ t.Helper()
+ out := map[string]string{}
+ err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ fi, err := d.Info()
+ if err != nil {
+ return err
+ }
+ s := fi.Mode().String() + " " + strconv.FormatInt(fi.Size(), 10) + " " + fi.ModTime().Format(time.RFC3339Nano)
+ if !d.IsDir() {
+ b, err := os.ReadFile(p)
+ if err != nil {
+ return err
+ }
+ s += " " + string(b)
+ }
+ out[p] = s
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+
+func TestRegistryEgressSourceWritesNothing(t *testing.T) {
+ t.Parallel()
+ reg, dd := egressRegistry(t)
+ clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)}
+ if err := os.MkdirAll(filepath.Join(dd, "layout"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // A journal for a host that is not on this box, and a temp file.
+ if err := os.WriteFile(provision.LayoutJournalPath(dd, "elsewhere.example.com"), []byte(`{"host":"elsewhere.example.com"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dd, "layout", ".tmp-1"), []byte("x"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"))
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(clock.Now().Add(time.Hour)))
+ src := registryEgressSource(dd, clock.Now)
+
+ check := func(phase string, call func()) {
+ t.Helper()
+ // Let any earlier write's mtime settle into the past, so a write
+ // during call shows as a change.
+ time.Sleep(20 * time.Millisecond)
+ before := treeState(t, filepath.Join(dd, "layout"))
+ db := treeState(t, reg.Path())
+ call()
+ if after := treeState(t, filepath.Join(dd, "layout")); !reflect.DeepEqual(before, after) {
+ t.Fatalf("%s: the layout tree changed:\n before %v\n after %v", phase, before, after)
+ }
+ if after := treeState(t, reg.Path()); !reflect.DeepEqual(db, after) {
+ t.Fatalf("%s: registry.db changed:\n before %v\n after %v", phase, db, after)
+ }
+ }
+ check("an allow", func() {
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+ wantPolicy(t, readPolicy(t, src, "gone.example.com"), instancectl.EgressPolicy{})
+ })
+ upsertRows(t, reg, flatRow(dd, "old.example.com"))
+ check("a mixed box", func() {
+ if got := readPolicy(t, src, "shop-a.example.com"); got.Closed != instancectl.EgressNotNested {
+ t.Fatalf("a mixed box: %+v", got)
+ }
+ })
+ clock.Set(clock.Now().Add(2 * time.Hour))
+ if err := reg.Delete("old.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ check("an expired allow", func() {
+ if got := readPolicy(t, src, "shop-a.example.com"); got.Closed != instancectl.EgressExpired {
+ t.Fatalf("an expired allow: %+v", got)
+ }
+ })
+}
+
+func TestRegistryEgressSourceClosesAtTheRecordedExpiry(t *testing.T) {
+ t.Parallel()
+ reg, dd := egressRegistry(t)
+ t0 := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
+ exp := t0.Add(time.Hour)
+ clock := &testClock{now: t0}
+ upsertRows(t, reg, nestedRow(dd, "shop-a.example.com"))
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(exp))
+ src := registryEgressSource(dd, clock.Now)
+ allow := instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}}
+ expired := instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: "the policy expired at 2026-10-25T10:00:00Z"}
+ noExpiry := instancectl.EgressPolicy{Closed: instancectl.EgressExpired, Detail: "no expiry recorded"}
+
+ // Ahead: the allow. At the expiry itself and one second past: expired.
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), allow)
+ clock.Set(exp.Add(-time.Second))
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), allow)
+ clock.Set(exp)
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), expired)
+ clock.Set(exp.Add(time.Second))
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), expired)
+
+ // An allow with no usable expiry closes (ruling C1).
+ clock.Set(t0)
+ for _, col := range []string{"0", "", "soon", "-5"} {
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", col)
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), noExpiry)
+ }
+
+ // A fresh source over the same registry, as after a restart of the
+ // control service, with the clock past: expired.
+ setAllow(t, reg, "shop-a.example.com", "10.0.5.20", unixText(exp))
+ clock.Set(exp.Add(time.Minute))
+ wantPolicy(t, readPolicy(t, registryEgressSource(dd, clock.Now), "shop-a.example.com"), expired)
+
+ // An allowed read, then the registry cannot be read: an error (the
+ // asserter keeps the last allow) only until the expiry it was read
+ // under, then expired, never the error.
+ clock.Set(t0)
+ src = registryEgressSource(dd, clock.Now)
+ wantPolicy(t, readPolicy(t, src, "shop-a.example.com"), allow)
+ if err := os.Rename(reg.Path(), reg.Path()+".away"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := src(context.Background(), "shop-a.example.com"); err == nil {
+ t.Fatal("an unreadable registry inside the expiry: no error")
+ }
+ if _, err := src(context.Background(), "shop-b.example.com"); err == nil {
+ t.Fatal("an unreadable registry, a host never read: no error")
+ }
+ clock.Set(exp.Add(time.Second))
+ got, err := src(context.Background(), "shop-a.example.com")
+ if err != nil {
+ t.Fatalf("an unreadable registry past the expiry: %v, want %+v", err, expired)
+ }
+ wantPolicy(t, got, expired)
+ if _, err := src(context.Background(), "shop-b.example.com"); err == nil {
+ t.Fatal("an unreadable registry, a host never read, past the expiry: no error")
+ }
+}
+
+// failingPolicyStore is a DirStore whose app-policy reads fail with a
+// transient error once fail is set: a store outage, as the agent sees it.
+type failingPolicyStore struct {
+ *release.DirStore
+ fail atomic.Bool
+}
+
+var errStoreOutage = errors.New("connection reset by peer")
+
+func (s *failingPolicyStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if s.fail.Load() && strings.HasPrefix(key, apppolicy.Prefix) {
+ return nil, "", errStoreOutage
+ }
+ return s.DirStore.Get(ctx, key)
+}
+
+func (s *failingPolicyStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) {
+ if s.fail.Load() && strings.HasPrefix(prefix, apppolicy.Prefix) {
+ return nil, errStoreOutage
+ }
+ return s.DirStore.ListETags(ctx, prefix)
+}
+
+// TestPreClaimAllowClosesWhenAStoreOutageOutlastsTheRecord is Astra plan
+// R1-3 through the agent's real converge: provision.Reconcile writes the
+// row from a policy the release key signed, the store then fails every
+// policy read, and once the clock passes SignedAt + apppolicy.Lifetime
+// root's source closes the allow from the row alone, whether or not the
+// agent ever runs again.
+func TestPreClaimAllowClosesWhenAStoreOutageOutlastsTheRecord(t *testing.T) {
+ t.Parallel()
+ ctx := context.Background()
+ reg, dd := egressRegistry(t)
+ store := &failingPolicyStore{DirStore: release.NewDirStore(t.TempDir())}
+ clock := &testClock{now: time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)}
+ sqid := domains.Sqid(2)
+ manifest, err := json.Marshal(map[string]any{"id": 2, "sqid": sqid, "name": "fixture", "created_at": clock.Now()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.Put(ctx, "accounts/"+sqid+"/account.json", manifest, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutManifest(ctx, store, sqid, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "example.com"}); err != nil {
+ t.Fatal(err)
+ }
+ const host = "shop-a.example.com"
+ if err := provision.CreateRecord(ctx, store, provision.Record{Schema: 1, Host: host, Slug: "shop-a", App: "shop", Account: sqid,
+ Region: "ie", Channel: "stable", CreatedAt: clock.Now().Add(-24 * time.Hour)}); err != nil {
+ t.Fatal(err)
+ }
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ signedAt := clock.Now()
+ if err := apppolicy.PutIfMatch(ctx, store, priv, apppolicy.Policy{V: 1, Account: sqid, App: "shop", Revision: 1,
+ SignedAt: signedAt, EgressAllow: []string{"10.0.5.20"}}, ""); err != nil {
+ t.Fatal(err)
+ }
+ cfg := provision.ReconcileConfig{Region: "ie", DataDir: dd, ReleasePub: pub, Now: clock.Now,
+ Layout: func(context.Context, release.Store) (string, error) { return release.LayoutModeNested, nil }}
+ reconcile := func() {
+ t.Helper()
+ if err := provision.Reconcile(ctx, store, reg, cfg); err != nil {
+ t.Fatal(err)
+ }
+ }
+ reconcile()
+ rt, err := reg.Get(host)
+ if err != nil || rt == nil {
+ t.Fatalf("the converge minted no row: %v", err)
+ }
+ if want := unixText(signedAt.Add(apppolicy.Lifetime)); rt.EgressAllow != "10.0.5.20" || rt.PolicyExpiresAt != want {
+ t.Fatalf("converged row: egress %q expires %q, want %q %q", rt.EgressAllow, rt.PolicyExpiresAt, "10.0.5.20", want)
+ }
+ src := registryEgressSource(dd, clock.Now)
+ wantPolicy(t, readPolicy(t, src, host), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+
+ // The outage: the agent's passes keep the row while its expiry is ahead.
+ store.fail.Store(true)
+ clock.Set(signedAt.Add(apppolicy.Lifetime - time.Hour))
+ reconcile()
+ wantPolicy(t, readPolicy(t, src, host), instancectl.EgressPolicy{Allow: []string{"10.0.5.20"}})
+
+ // The outage outlasts the record, and the agent has not run since.
+ clock.Set(signedAt.Add(apppolicy.Lifetime + time.Second))
+ wantExpired := instancectl.EgressPolicy{Closed: instancectl.EgressExpired,
+ Detail: "the policy expired at " + signedAt.Add(apppolicy.Lifetime).UTC().Format(time.RFC3339)}
+ wantPolicy(t, readPolicy(t, src, host), wantExpired)
+ wantPolicy(t, readPolicy(t, registryEgressSource(dd, clock.Now), host), wantExpired)
+
+ // When the agent does run, it clears the row: still no allow.
+ reconcile()
+ wantPolicy(t, readPolicy(t, src, host), instancectl.EgressPolicy{})
+}
+
+func TestRegistryEgressHostsListsTheRows(t *testing.T) {
+ t.Parallel()
+ reg, dd := egressRegistry(t)
+ upsertRows(t, reg, nestedRow(dd, "shop-b.example.com"), nestedRow(dd, "shop-a.example.com"),
+ registry.Route{Host: "worker.example.com", Kind: "sidecar", App: "shop"})
+ hosts, err := registryEgressHosts(dd)()
+ if err != nil {
+ t.Fatal(err)
+ }
+ slices.Sort(hosts)
+ if want := []string{"shop-a.example.com", "shop-b.example.com", "worker.example.com"}; !slices.Equal(hosts, want) {
+ t.Fatalf("hosts = %v, want %v", hosts, want)
+ }
+ if _, err := registryEgressHosts(filepath.Join(dd, "missing"))(); err == nil {
+ t.Fatal("no registry: no error")
+ }
+}