Named-unit delivery: root binds a stamped route to its unit from its own evidence, and a carriage return in a value is refused (review round 1 P1-1, P1-2)
P1-1. planStamped trusted registry.Route.Unit, and the registry is the service user's: a box agent could name any loaded root service in a row and have root write an environment into it and restart it. UnitOps gains Bind, asked for every stamped route after the one-per-unit rule and before the probe; an error refuses the route this pass and a nil Bind refuses every stamped route, so the registry alone is never enough. Production's Bind (internal/host/unitops.go unitOpsBind) is the release pass's own decider, rootRestartChecks.resolve (proofBindingSource.resolve): a provisioning record, the root-owned /etc/carlos/named-units.json or the console guard marker names host, account, app and unit, the unit's ExecStart is the proven executable, and the evidence must name the unit the row names. One function now decides the binding for the release restart and for config delivery. A hand-built unit (Woodstar's) needs a record or a named-units.json entry and must exec the route's live link before carlos delivers to it; that is reported, not relaxed. Witness: TestSyncUnitsRefusesAStampRootCannotBind (registry only, evidence for another unit, no Bind: refused before the probe, nothing written, nothing restarted; bound: delivered), TestUnitOpsBindRefusesWhatRootCannotProve; TestSyncUnitsReStampMovesTheDropIn now proves the re-stamp too. P1-2. overlappingNames split on '\n' only and ValidVarValue admits '\r', which systemd reads as a line break, so a bundle value could carry a second assignment to a base-owned name. For a stamped route a value with '\r' is refused at render by name (carriageReturnVar, prepareStamped), before either layer is compared; ValidVarValue is unchanged for every tenant. The base file and the rendered bundle are both read with systemd's env-file grammar (envFileNamesFrom, after src/basic/env-file.c): '\r' and '\n' break lines, quotes span lines so a KEY=value inside a quoted value is never a name, a backslash continues a bare value, '#' and ';' comment. Witnesses through SyncUnits: TestSyncUnitsRefusesACarriageReturnInAValue (with and without a base file, the value never logged) and TestSyncUnitsBaseFileNamesReadAsSystemdReadsThem; the grammar's cases in TestEnvFileNamesFromAgreesWithSystemd. The #114 spec's §12 records both; docs/site/cli.md's carlos route paragraph says delivery needs the record or the declaration. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Summary
Root config delivery to a stamped unit now requires root-observable evidence binding the route to the unit (the release pass's proof), and a carriage return in a stamped route's value is refused at render while both layers are parsed with systemd's env-file grammar.
10 files changed,
+476
−61
docs/site/cli.md+5 −3docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md+23 −0internal/appconfig/baseenv.go+126 −17internal/appconfig/baseenv_test.go+35 −0internal/appconfig/sync.go+1 −1internal/appconfig/unitsync.go+38 −6internal/appconfig/unitsync_test.go+182 −31internal/host/agent.go+1 −1internal/host/unitops.go+30 −1internal/host/unitops_test.go+35 −1
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 52b4c2c86..91017d186 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2162,9 +2162,11 @@ write the pass renders the route's bundle to `/etc/carlos/apps/<host>.env`, |
| keeps a drop-in under `/etc/systemd/system/<unit>.d/` that makes the box's |
| `/etc/carlos/units/<unit>.base.env` (if there is one) and that file the |
| unit's only `EnvironmentFile=` sources, reloads systemd and restarts the |
| -unit. A unit that loads any other environment file, or a variable named in |
| -both the base file and the route's config, is refused and the reason is |
| -logged on the box until one of them is changed. |
| +unit. The box delivers only to a unit it can tie to the route from its own |
| +records (the route's instance record or `/etc/carlos/named-units.json`), |
| +never from the route row alone. A unit that loads any other environment |
| +file, or a variable named in both the base file and the route's config, is |
| +refused and the reason is logged on the box until one of them is changed. |
| A stamp needs an addr upstream and no hibernation; `--unit` refuses a |
| socket or hibernating row, `--hibernate` refuses a stamped one, and |
| `--unit -` always clears. |
diff --git a/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md b/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md| index b4fa82429..57fb2a267 100644 |
| --- a/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md |
| +++ b/docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md |
| @@ -856,6 +856,29 @@ work are later plans. |
| the route too, since its names cannot be ruled out. Removing the name |
| from either layer unblocks the route on the next pass. |
| +Two rails from the branch's review round 1 (Astra, 2026-10-28) sit with |
| +these: |
| + |
| +4. **Root binds the route to its unit from its own evidence (P1-1).** The |
| + registry is the service user's, so a row naming a unit is never |
| + authority to write an environment into that unit and restart it. |
| + Before the probe, `planStamped` asks `UnitOps.Bind`, which in |
| + production is the release pass's own decider |
| + (`proofBindingSource.resolve`, `internal/host/proofbinding.go`): a |
| + provisioning record, the root-owned `/etc/carlos/named-units.json` |
| + or the console guard marker names the host, account, app and unit, |
| + and the unit's `ExecStart` is the proven executable. A route root |
| + cannot bind is refused every pass with the reason, nothing written. |
| + A hand-built unit therefore needs a record or a `named-units.json` |
| + entry, and must exec the route's live link, before carlos delivers to |
| + it. |
| + |
| +5. **A carriage return is a line break to systemd (P1-2).** For a stamped |
| + route a value carrying `\r` is refused at render, by name; the base |
| + file and the rendered bundle are both read with systemd's own env-file |
| + grammar (`envFileNamesFrom`), so a quoted multiline value is never a |
| + name and an assignment after a bare `\r` always is. |
| + |
| Tests (console config design §11, first three bullets) run through the |
| real `SyncUnits` with the faked `UnitOps`: |
| `TestSyncUnitsRefusesToResetAnUnmanagedEnvFileAway`, |
diff --git a/internal/appconfig/baseenv.go b/internal/appconfig/baseenv.go| index 19aae2e4a..94b022b2b 100644 |
| --- a/internal/appconfig/baseenv.go |
| +++ b/internal/appconfig/baseenv.go |
| @@ -42,10 +42,9 @@ func unmanagedEnvFiles(got []string, base, bundle string) []string { |
| } |
| // envFileNames reads the variable NAMES of an EnvironmentFile-format file |
| -// and nothing else: KEY=value per line, blank lines and lines starting |
| -// with # or ; skipped, as systemd reads them. A missing file has no names. |
| -// Any other read error is returned, because a base file the pass cannot |
| -// read is a base file whose names it cannot rule out. |
| +// and nothing else, as systemd reads it (envFileNamesFrom). A missing file |
| +// has no names. Any other read error is returned, because a base file the |
| +// pass cannot read is a base file whose names it cannot rule out. |
| func envFileNames(path string) ([]string, error) { |
| raw, err := os.ReadFile(path) |
| if err != nil { |
| @@ -54,25 +53,136 @@ func envFileNames(path string) ([]string, error) { |
| } |
| return nil, err |
| } |
| + return envFileNamesFrom(raw), nil |
| +} |
| + |
| +// envFileNamesFrom is the name half of systemd's env-file parser |
| +// (src/basic/env-file.c, parse_env_file_internal), state for state, so |
| +// the overlap rail and systemd agree on what is an assignment: '\n' AND |
| +// '\r' end a line; '#' and ';' start a comment; a key ends at '='; a value |
| +// may be bare, single-quoted or double-quoted, and a quoted value runs |
| +// across line breaks, so KEY=value text inside quotes is a value, not a |
| +// name; a backslash escapes the next byte, a line break included, in a |
| +// bare or double-quoted value. A key with no '=' before its line ends is |
| +// dropped, as systemd drops it. Values are never kept: only the names come |
| +// out, in file order, with repeats kept (a repeat is still a name). |
| +func envFileNamesFrom(raw []byte) []string { |
| + const ( |
| + preKey = iota |
| + key |
| + preValue |
| + value |
| + valueEscape |
| + singleQuote |
| + doubleQuote |
| + doubleQuoteEscape |
| + comment |
| + commentEscape |
| + ) |
| + isNewline := func(c byte) bool { return c == '\n' || c == '\r' } |
| + isSpace := func(c byte) bool { return c == ' ' || c == '\t' || isNewline(c) } |
| var names []string |
| - for _, line := range strings.Split(string(raw), "\n") { |
| - s := strings.TrimSpace(line) |
| - if s == "" || strings.HasPrefix(s, "#") || strings.HasPrefix(s, ";") { |
| - continue |
| + var k []byte |
| + emit := func() { |
| + // systemd strips the key's trailing whitespace; leading whitespace |
| + // never enters it (preKey skips it). |
| + names = append(names, strings.TrimRight(string(k), " \t")) |
| + k = k[:0] |
| + } |
| + state := preKey |
| + for _, c := range raw { |
| + switch state { |
| + case preKey: |
| + if c == '#' || c == ';' { |
| + state = comment |
| + } else if !isSpace(c) { |
| + state = key |
| + k = append(k, c) |
| + } |
| + case key: |
| + if isNewline(c) { |
| + state = preKey |
| + k = k[:0] |
| + } else if c == '=' { |
| + state = preValue |
| + } else { |
| + k = append(k, c) |
| + } |
| + case preValue: |
| + switch { |
| + case isNewline(c): |
| + state = preKey |
| + emit() |
| + case c == '\'': |
| + state = singleQuote |
| + case c == '"': |
| + state = doubleQuote |
| + case c == '\\': |
| + state = valueEscape |
| + case !isSpace(c): |
| + state = value |
| + } |
| + case value: |
| + if isNewline(c) { |
| + state = preKey |
| + emit() |
| + } else if c == '\\' { |
| + state = valueEscape |
| + } |
| + case valueEscape: |
| + state = value |
| + case singleQuote: |
| + if c == '\'' { |
| + state = value |
| + } |
| + case doubleQuote: |
| + if c == '"' { |
| + state = value |
| + } else if c == '\\' { |
| + state = doubleQuoteEscape |
| + } |
| + case doubleQuoteEscape: |
| + state = doubleQuote |
| + case comment: |
| + if c == '\\' { |
| + state = commentEscape |
| + } else if isNewline(c) { |
| + state = preKey |
| + } |
| + case commentEscape: |
| + state = comment |
| } |
| - name, _, ok := strings.Cut(s, "=") |
| - name = strings.TrimSpace(name) |
| - if !ok || name == "" { |
| + } |
| + switch state { |
| + case preValue, value, valueEscape, singleQuote, doubleQuote, doubleQuoteEscape: |
| + emit() |
| + } |
| + return names |
| +} |
| + |
| +// carriageReturnVar is the carriage-return rail for a stamped route |
| +// (console config design §4.1, review round 1 P1-2): the first variable of |
| +// the rendered bundle whose line holds a '\r', or "". systemd reads '\r' as |
| +// a line break, so a value carrying one is a second assignment the |
| +// overlap rail would never see as a name. ValidVarValue admits '\r' for |
| +// every tenant and is left alone; for a stamped route the value is refused |
| +// at render, by name, never by value. Rendered lines are KEY=value with no |
| +// '\n' in a value (ValidVarValue), so a line is one variable. |
| +func carriageReturnVar(rendered []byte) string { |
| + for _, line := range strings.Split(string(rendered), "\n") { |
| + if strings.IndexByte(line, '\r') < 0 { |
| continue |
| } |
| - names = append(names, name) |
| + name, _, _ := strings.Cut(line, "=") |
| + return name |
| } |
| - return names, nil |
| + return "" |
| } |
| // overlappingNames is the overlap rail (§4.1, Paul's "one owner per |
| // variable"): the names in both base and rendered, sorted. rendered is the |
| -// bundle as it would be written, so the comparison is against what the |
| +// bundle as it would be written and is read with the same parser as the |
| +// base file (envFileNamesFrom), so the comparison is against what the |
| // unit would actually load, agent-owned names included. |
| func overlappingNames(base []string, rendered []byte) []string { |
| inBase := make(map[string]bool, len(base)) |
| @@ -81,9 +191,8 @@ func overlappingNames(base []string, rendered []byte) []string { |
| } |
| seen := map[string]bool{} |
| var out []string |
| - for _, line := range strings.Split(string(rendered), "\n") { |
| - name, _, ok := strings.Cut(line, "=") |
| - if !ok || !inBase[name] || seen[name] { |
| + for _, name := range envFileNamesFrom(rendered) { |
| + if !inBase[name] || seen[name] { |
| continue |
| } |
| seen[name] = true |
diff --git a/internal/appconfig/baseenv_test.go b/internal/appconfig/baseenv_test.go| index 7aebe22b3..7e453cd23 100644 |
| --- a/internal/appconfig/baseenv_test.go |
| +++ b/internal/appconfig/baseenv_test.go |
| @@ -56,3 +56,38 @@ func TestUnmanagedEnvFiles(t *testing.T) { |
| t.Fatalf("foreign = %v", got) |
| } |
| } |
| + |
| +// envFileNamesFrom follows systemd's env-file parser: '\r' breaks a line, |
| +// quotes span lines, a backslash continues a bare value, '#' and ';' |
| +// comment, a key without '=' is dropped, key whitespace is trimmed. |
| +func TestEnvFileNamesFromAgreesWithSystemd(t *testing.T) { |
| + for _, tc := range []struct{ in, want string }{ |
| + {"A=1\nB=2\n", "A,B"}, |
| + {"A=1\rB=2\r\nC=3", "A,B,C"}, |
| + {"A=\"x\nB=2\ny\"\nC=3\n", "A,C"}, |
| + {"A='x\rB=2'\nC=3\n", "A,C"}, |
| + {"A=x\\\nB=2\nC=3\n", "A,C"}, |
| + {"A=\"x\\\"B=2\"\nC=3\n", "A,C"}, |
| + {"# c\\\nA=1\nB=2\n", "B"}, |
| + {"; c\nA=1\n", "A"}, |
| + {" A = 1\n", "A"}, |
| + {"NOEQ\nA=1\n", "A"}, |
| + {"A=\n", "A"}, |
| + {"A=1", "A"}, |
| + {"A=\"unterminated\nB=2", "A"}, |
| + {"", ""}, |
| + } { |
| + if got := strings.Join(envFileNamesFrom([]byte(tc.in)), ","); got != tc.want { |
| + t.Errorf("%q: names = %q, want %q", tc.in, got, tc.want) |
| + } |
| + } |
| +} |
| + |
| +func TestCarriageReturnVar(t *testing.T) { |
| + if got := carriageReturnVar([]byte("A=1\nEXTRA=ok\rB=2\nC=3\n")); got != "EXTRA" { |
| + t.Fatalf("got %q, want EXTRA", got) |
| + } |
| + if got := carriageReturnVar([]byte("A=1\nB=2\n")); got != "" { |
| + t.Fatalf("got %q, want none", got) |
| + } |
| +} |
diff --git a/internal/appconfig/sync.go b/internal/appconfig/sync.go| index f782d452d..ad22f8e8f 100644 |
| --- a/internal/appconfig/sync.go |
| +++ b/internal/appconfig/sync.go |
| @@ -106,7 +106,7 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St |
| // behind, for the reload/restart half after the loop. |
| var plan stampedPlan |
| if ops != nil { |
| - plan = planStamped(routes, envDir, ops) |
| + plan = planStamped(ctx, routes, envDir, ops) |
| } |
| work := map[string]unitWork{} // by unit |
| type groupKey struct{ acct, app, env string } |
diff --git a/internal/appconfig/unitsync.go b/internal/appconfig/unitsync.go| index 2171591ba..66efd6dde 100644 |
| --- a/internal/appconfig/unitsync.go |
| +++ b/internal/appconfig/unitsync.go |
| @@ -8,6 +8,7 @@ package appconfig |
| import ( |
| "bytes" |
| + "context" |
| "crypto/ecdh" |
| "fmt" |
| "path/filepath" |
| @@ -41,6 +42,17 @@ type UnitOps struct { |
| // Lock serialises config passes across processes (spec §3.2, codex |
| // R2-3). An error means another pass holds it: do nothing this pass. |
| Lock func() (unlock func(), err error) |
| + // Bind proves, from evidence root reads and the box agent cannot |
| + // write, that rt's process IS the unit rt names: the provisioning |
| + // record, the root-owned /etc/carlos/named-units.json or the console |
| + // guard marker, with the unit's ExecStart matched against the proven |
| + // executable (internal/host proofBindingSource.resolve, the release |
| + // pass's own decider). The registry is the service user's |
| + // (internal/host/registryowner.go), so a row alone is never enough: |
| + // an agent that could name any loaded root service in a row would have |
| + // root write an environment into it and restart it. An error refuses |
| + // the route this pass; a nil Bind refuses every stamped route. |
| + Bind func(ctx context.Context, rt registry.Route) error |
| // Probe answers Id, LoadState and EnvironmentFiles for every unit in |
| // one systemctl invocation. A missing unit answers LoadState |
| // "not-found". An error means the probe itself failed and nothing |
| @@ -67,18 +79,22 @@ type stampedPlan struct { |
| // planStamped applies the rail (spec §3.2) to every stamped route in |
| // routes, in this order: shape, unit name, hostname, one-route-per-unit, |
| -// then the batched systemd probe (loaded, and the stamp is the canonical |
| -// name), then the unmanaged-file guard (console config design §4.1) for a |
| -// unit that has no carlos drop-in yet. Refusals are collected, never |
| -// printed here: the route loop prints them beside the route so a log reads |
| -// in one place. |
| -func planStamped(routes []registry.Route, envDir string, ops *UnitOps) stampedPlan { |
| +// the root-side binding proof (UnitOps.Bind; review round 1 P1-1), then |
| +// the batched systemd probe (loaded, and the stamp is the canonical name), |
| +// then the unmanaged-file guard (console config design §4.1) for a unit |
| +// that has no carlos drop-in yet. The binding comes before the probe so |
| +// that a unit the registry alone names is never even asked about. |
| +// Refusals are collected, never printed here: the route loop prints them |
| +// beside the route so a log reads in one place. |
| +func planStamped(ctx context.Context, routes []registry.Route, envDir string, ops *UnitOps) stampedPlan { |
| p := stampedPlan{unitOf: map[string]string{}, refused: map[string]string{}, probe: map[string]UnitState{}} |
| byUnit := map[string][]string{} |
| + rowOf := map[string]registry.Route{} |
| for _, rt := range routes { |
| if !stampedForDelivery(rt) { |
| continue |
| } |
| + rowOf[rt.Host] = rt |
| if r := stampShapeReason(rt); r != "" { |
| p.refused[rt.Host] = r |
| continue |
| @@ -102,6 +118,15 @@ func planStamped(routes []registry.Route, envDir string, ops *UnitOps) stampedPl |
| } |
| continue |
| } |
| + host := hosts[0] |
| + if ops.Bind == nil { |
| + p.refused[host] = fmt.Sprintf("this pass has no root-side binding check for %s; a registry row alone never authorises delivery to a unit", unit) |
| + continue |
| + } |
| + if err := ops.Bind(ctx, rowOf[host]); err != nil { |
| + p.refused[host] = fmt.Sprintf("root cannot bind this route to %s from its own evidence (%v); a registry row alone never authorises delivery. Provision the route with a record naming the unit, or declare it in /etc/carlos/named-units.json, and the route converges on the next pass", unit, err) |
| + continue |
| + } |
| units = append(units, unit) |
| } |
| sort.Strings(units) |
| @@ -178,6 +203,13 @@ func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing |
| return w |
| } |
| path, rendered, cur, existed := hr.path, hr.rendered, hr.cur, hr.existed |
| + // A carriage return in a value is a second assignment to systemd |
| + // (review round 1 P1-2): refused for a stamped route at render, by |
| + // name, before either layer is compared. |
| + if name := carriageReturnVar(rendered); name != "" { |
| + fmt.Printf(" %s: delivery blocked: the value of %s contains a carriage return, which systemd reads as a line break; set it without one and the route converges on the next pass\n", rt.Host, name) |
| + return w |
| + } |
| // One owner per variable (§4.1): a name stated by both the base file |
| // and the bundle is refused, every pass, before anything is written. |
| // Names only; no value from either layer is read for this or printed. |
diff --git a/internal/appconfig/unitsync_test.go b/internal/appconfig/unitsync_test.go| index fcfb45fb1..84c62913b 100644 |
| --- a/internal/appconfig/unitsync_test.go |
| +++ b/internal/appconfig/unitsync_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "crypto/ecdh" |
| "errors" |
| + "fmt" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -18,6 +19,7 @@ import ( |
| type fakeUnits struct { |
| root string |
| base string |
| + bound map[string]string // host -> unit root's evidence binds it to |
| states map[string]UnitState |
| probeErr error |
| reloadErr error |
| @@ -30,9 +32,13 @@ type fakeUnits struct { |
| func newFakeUnits(t *testing.T) *fakeUnits { |
| t.Helper() |
| - return &fakeUnits{root: t.TempDir(), base: t.TempDir(), states: map[string]UnitState{}, restartErr: map[string]error{}} |
| + return &fakeUnits{root: t.TempDir(), base: t.TempDir(), bound: map[string]string{}, states: map[string]UnitState{}, restartErr: map[string]error{}} |
| } |
| +// bind records root's evidence for a host: the fake Bind admits a route |
| +// whose Unit is what bound says, and refuses every other. |
| +func (f *fakeUnits) bind(host, unit string) { f.bound[host] = unit } |
| + |
| // loaded answers the probe for a healthy unit whose effective env list is |
| // exactly carlos's two files, the base file then the bundle — the steady |
| // state after a successful pass (console config design §4.1). |
| @@ -52,6 +58,14 @@ func (f *fakeUnits) ops() *UnitOps { |
| return &UnitOps{ |
| DropInRoot: f.root, |
| BaseEnvDir: f.base, |
| + Bind: func(_ context.Context, rt registry.Route) error { |
| + if u, ok := f.bound[rt.Host]; !ok { |
| + return errors.New("no record or declaration names this host") |
| + } else if u != rt.Unit { |
| + return fmt.Errorf("evidence binds %s to %s", rt.Host, u) |
| + } |
| + return nil |
| + }, |
| Lock: func() (func(), error) { |
| if f.lockErr != nil { |
| return nil, f.lockErr |
| @@ -115,6 +129,15 @@ func upsertStamped(t *testing.T, reg *registry.Registry, host, unit string, mut |
| } |
| } |
| +// stampBound upserts a stamped route AND records root's evidence for it, |
| +// the state every delivery test needs; a test of the binding itself uses |
| +// upsertStamped alone. |
| +func stampBound(t *testing.T, f *fakeUnits, reg *registry.Registry, host, unit string, mut func(*registry.Route)) { |
| + t.Helper() |
| + upsertStamped(t, reg, host, unit, mut) |
| + f.bind(host, unit) |
| +} |
| + |
| func noHostRestart(t *testing.T) func(string) error { |
| return func(h string) error { |
| t.Fatalf("host-keyed restart called for %s; a stamped route restarts by unit", h) |
| @@ -126,7 +149,7 @@ func TestSyncUnitsPreparesAStampedRoute(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.states["relay.service"] = UnitState{ID: "relay.service", LoadState: "loaded"} |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| if err := SyncUnits(ctx, reg, s, priv, envDir, noHostRestart(t), nil, f.ops()); err != nil { |
| t.Fatalf("SyncUnits: %v", err) |
| @@ -164,7 +187,7 @@ func TestSyncUnitsDoesNothingWithoutTheLock(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.lockErr = errors.New("held elsewhere") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| if err := reg.Upsert(registry.Route{Host: "km.example.com", Kind: "instance", App: "relay", Account: "bab", |
| Status: "ready", Backing: registry.BackingUnit}); err != nil { |
| t.Fatal(err) |
| @@ -187,12 +210,12 @@ func TestSyncUnitsRefusesBadShapesNamesAndHosts(t *testing.T) { |
| } |
| f.states["alias.service"] = UnitState{ID: "real.service", LoadState: "loaded"} |
| f.states["gone.service"] = UnitState{ID: "gone.service", LoadState: "not-found"} |
| - upsertStamped(t, reg, "sock.example.com", "sock.service", func(r *registry.Route) { r.Socket = "/run/x.sock"; r.Addr = "" }) |
| - upsertStamped(t, reg, "hib.example.com", "hib.service", func(r *registry.Route) { r.Hibernate = true }) |
| - upsertStamped(t, reg, "tmpl.example.com", "carlos-app@.service", nil) |
| - upsertStamped(t, reg, "pref.example.com", "carlos-.service", nil) |
| - upsertStamped(t, reg, "alias.example.com", "alias.service", nil) |
| - upsertStamped(t, reg, "gone.example.com", "gone.service", nil) |
| + stampBound(t, f, reg, "sock.example.com", "sock.service", func(r *registry.Route) { r.Socket = "/run/x.sock"; r.Addr = "" }) |
| + stampBound(t, f, reg, "hib.example.com", "hib.service", func(r *registry.Route) { r.Hibernate = true }) |
| + stampBound(t, f, reg, "tmpl.example.com", "carlos-app@.service", nil) |
| + stampBound(t, f, reg, "pref.example.com", "carlos-.service", nil) |
| + stampBound(t, f, reg, "alias.example.com", "alias.service", nil) |
| + stampBound(t, f, reg, "gone.example.com", "gone.service", nil) |
| out := captureStdout(t, func() { |
| if err := SyncUnits(ctx, reg, s, priv, envDir, noHostRestart(t), nil, f.ops()); err != nil { |
| @@ -222,8 +245,8 @@ func TestSyncUnitsRefusesTwoRoutesOnOneUnit(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.states["relay.service"] = UnitState{ID: "relay.service", LoadState: "loaded"} |
| - upsertStamped(t, reg, "a.example.com", "relay.service", nil) |
| - upsertStamped(t, reg, "b.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "a.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "b.example.com", "relay.service", nil) |
| out := captureStdout(t, func() { |
| if err := SyncUnits(ctx, reg, s, priv, envDir, noHostRestart(t), nil, f.ops()); err != nil { |
| t.Fatalf("SyncUnits: %v", err) |
| @@ -241,7 +264,7 @@ func TestSyncUnitsRefusesAnUnmarkedDropIn(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.states["relay.service"] = UnitState{ID: "relay.service", LoadState: "loaded"} |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| os.MkdirAll(dropInDir(f.root, "relay.service"), 0o755) |
| foreign := []byte("[Service]\nEnvironmentFile=/x\n") |
| os.WriteFile(filepath.Join(dropInDir(f.root, "relay.service"), DropInFile), foreign, 0o644) |
| @@ -266,7 +289,7 @@ func TestSyncUnitsWritesMarkerBeforeFiles(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.states["relay.service"] = UnitState{ID: "relay.service", LoadState: "loaded"} |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| // Make the env dir unwritable so the env write fails after the marker. |
| if os.Geteuid() == 0 { |
| t.Skip("root ignores directory modes") |
| @@ -322,7 +345,7 @@ func TestSyncUnitsReloadsVerifiesRestartsAndClears(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if f.reloads != 1 { |
| @@ -360,7 +383,7 @@ func TestSyncUnitsReloadFailureKeepsMarkerAndRetries(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| f.reloadErr = errors.New("busy") |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if len(f.restarted) != 0 || !hasPending(f.root, "relay.service") { |
| @@ -377,7 +400,7 @@ func TestSyncUnitsRestartFailureKeepsMarkerAndRetries(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| f.restartErr["relay.service"] = errors.New("exit 1") |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if !hasPending(f.root, "relay.service") { |
| @@ -395,7 +418,7 @@ func TestSyncUnitsVerificationMismatchBlocks(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) // delivered, cleared: the unit is carlos's now |
| f.restarted = nil |
| // A config change marks the unit; after the reload the effective list |
| @@ -419,7 +442,7 @@ func TestSyncUnitsDriftIsReportedEveryPassAndNeverRestarted(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) // delivered, cleared |
| f.restarted, f.reloads = nil, 0 |
| // An operator's later drop-in took the list back. |
| @@ -440,12 +463,12 @@ func TestSyncUnitsRefusedRouteKeepsAnEarlierMarker(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| f.reloadErr = errors.New("busy") |
| syncOnce(t, ctx, reg, s, priv, envDir, f) // marker left behind |
| f.reloadErr = nil |
| // Now the route is refused (a second route names the unit). |
| - upsertStamped(t, reg, "b.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "b.example.com", "relay.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if len(f.restarted) != 0 || !hasPending(f.root, "relay.service") { |
| t.Fatalf("refused route: restarted=%v pending=%v, want no restart and the marker kept", f.restarted, hasPending(f.root, "relay.service")) |
| @@ -456,7 +479,7 @@ func TestSyncUnitsUnreadableDropInKeepsMarker(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) // delivered, cleared |
| // Make the drop-in unreadable with something other than not-exist: a |
| @@ -477,7 +500,7 @@ func TestSyncUnitsUnreadableDropInKeepsMarker(t *testing.T) { |
| // The route is refused this pass (a second route names the unit), so |
| // the only path that could clear or keep the marker is the drop-in |
| // read at the top of the loop. |
| - upsertStamped(t, reg, "b.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "b.example.com", "relay.service", nil) |
| out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if len(f.restarted) != 0 || !hasPending(f.root, "relay.service") { |
| t.Fatalf("unreadable drop-in: restarted=%v pending=%v, want no restart and the marker kept", f.restarted, hasPending(f.root, "relay.service")) |
| @@ -491,7 +514,7 @@ func TestSyncUnitsReapsDropInForAnUnstampedRouteWithMarkerFirst(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| // Unstamp: the row stays, the unit is no longer named by any route. |
| if err := reg.SetUnit("relay.example.com", ""); err != nil { |
| @@ -569,11 +592,18 @@ func TestSyncUnitsReStampMovesTheDropIn(t *testing.T) { |
| f := newFakeUnits(t) |
| f.loaded("a.service", envDir, "relay.example.com") |
| f.loaded("b.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "a.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "a.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if err := reg.SetUnit("relay.example.com", "b.service"); err != nil { |
| t.Fatal(err) |
| } |
| + // A re-stamp needs root's evidence too (P1-1): the row alone is |
| + // refused, and the old unit's drop-in stays until the stamp is proven. |
| + out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if _, exists, _, _ := readDropIn(f.root, "b.service"); exists || !strings.Contains(out, "registry row alone") { |
| + t.Fatalf("a re-stamp root cannot bind was delivered: exists=%v out=%q", exists, out) |
| + } |
| + f.bind("relay.example.com", "b.service") |
| f.restarted = nil |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if _, exists, _, _ := readDropIn(f.root, "a.service"); exists { |
| @@ -618,7 +648,7 @@ func TestSyncUnitsRefusesToResetAnUnmanagedEnvFileAway(t *testing.T) { |
| // files, one of which is also carlos's bundle path. |
| f.states["console.service"] = UnitState{ID: "console.service", LoadState: "loaded", |
| EnvFiles: []string{"/etc/console/hand.env", filepath.Join(envDir, "console.example.com.env")}} |
| - upsertStamped(t, reg, "console.example.com", "console.service", nil) |
| + stampBound(t, f, reg, "console.example.com", "console.service", nil) |
| for pass := 1; pass <= 2; pass++ { |
| out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| if !strings.Contains(out, "console.example.com") || !strings.Contains(out, "blocked") || !strings.Contains(out, "/etc/console/hand.env") { |
| @@ -659,8 +689,8 @@ func TestSyncUnitsGuardAdmitsAUnitLoadingOnlyManagedPaths(t *testing.T) { |
| f := newFakeUnits(t) |
| f.states["a.service"] = UnitState{ID: "a.service", LoadState: "loaded", EnvFiles: []string{filepath.Join(envDir, "a.example.com.env")}} |
| f.states["b.service"] = UnitState{ID: "b.service", LoadState: "loaded"} |
| - upsertStamped(t, reg, "a.example.com", "a.service", nil) |
| - upsertStamped(t, reg, "b.example.com", "b.service", nil) |
| + stampBound(t, f, reg, "a.example.com", "a.service", nil) |
| + stampBound(t, f, reg, "b.example.com", "b.service", nil) |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| for _, unit := range []string{"a.service", "b.service"} { |
| if _, exists, marked, _ := readDropIn(f.root, unit); !exists || !marked { |
| @@ -678,7 +708,7 @@ func TestSyncUnitsDropInListsBaseBeforeBundle(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| if _, err := os.Stat(baseEnvPath(f.base, "relay.service")); !os.IsNotExist(err) { |
| t.Fatalf("precondition: no base file, stat err = %v", err) |
| } |
| @@ -727,7 +757,7 @@ func TestSyncUnitsRefusesANameInBothLayers(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| f.writeBase(t, "relay.service", "# provisioned\nCARLOS_DEPLOYMENT_BUCKET=bkt-value\n LOG_LEVEL = base-value\n;x\n") |
| for pass := 1; pass <= 2; pass++ { |
| out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| @@ -774,7 +804,7 @@ func TestSyncUnitsRefusesAnUnreadableBaseFile(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("relay.service", envDir, "relay.example.com") |
| - upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| if err := os.Mkdir(baseEnvPath(f.base, "relay.service"), 0o755); err != nil { |
| t.Fatal(err) |
| } |
| @@ -796,7 +826,7 @@ func TestSyncUnitsUnitBackedRowWithAStampStaysOnTheCarlosAppPath(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("console.service", envDir, "console.example.com") |
| - upsertStamped(t, reg, "console.example.com", "console.service", func(r *registry.Route) { r.Backing = registry.BackingUnit }) |
| + stampBound(t, f, reg, "console.example.com", "console.service", func(r *registry.Route) { r.Backing = registry.BackingUnit }) |
| var restarted []string |
| if err := SyncUnits(ctx, reg, s, priv, envDir, func(h string) error { restarted = append(restarted, h); return nil }, nil, f.ops()); err != nil { |
| t.Fatalf("SyncUnits: %v", err) |
| @@ -814,3 +844,124 @@ func TestSyncUnitsUnitBackedRowWithAStampStaysOnTheCarlosAppPath(t *testing.T) { |
| t.Fatalf("a drop-in directory was made: %v", dirs) |
| } |
| } |
| + |
| +// TestSyncUnitsRefusesAStampRootCannotBind is the witness for review |
| +// round 1 P1-1: the registry is the service user's, so a row alone never |
| +// authorises delivery to the unit it names. With only the registry |
| +// changed, with evidence binding the host to another unit, and with no |
| +// Bind at all, delivery is refused before the probe: nothing rendered, no |
| +// drop-in directory, no marker, no reload, no restart, and the unit is |
| +// never even asked about. |
| +func TestSyncUnitsRefusesAStampRootCannotBind(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + arm func(f *fakeUnits, ops *UnitOps) |
| + }{ |
| + {"registry only", func(*fakeUnits, *UnitOps) {}}, |
| + {"evidence names another unit", func(f *fakeUnits, _ *UnitOps) { f.bind("relay.example.com", "other.service") }}, |
| + {"no bind on this pass", func(_ *fakeUnits, ops *UnitOps) { ops.Bind = nil }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + ctx, s, reg, envDir, priv := unitKit(t) |
| + f := newFakeUnits(t) |
| + f.loaded("relay.service", envDir, "relay.example.com") |
| + upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + ops := f.ops() |
| + tc.arm(f, ops) |
| + out := captureStdout(t, func() { |
| + if err := SyncUnits(ctx, reg, s, priv, envDir, noHostRestart(t), nil, ops); err != nil { |
| + t.Fatalf("SyncUnits: %v", err) |
| + } |
| + }) |
| + if !strings.Contains(out, "relay.example.com") || !strings.Contains(out, "blocked") || !strings.Contains(out, "registry row alone") { |
| + t.Fatalf("expected a blocked line about the binding, got %q", out) |
| + } |
| + if ents, _ := os.ReadDir(envDir); len(ents) != 0 { |
| + t.Fatalf("rendered %v for an unbound stamp", ents) |
| + } |
| + if dirs, _ := os.ReadDir(f.root); len(dirs) != 0 { |
| + t.Fatalf("drop-in directory made for an unbound stamp: %v", dirs) |
| + } |
| + if len(f.probed) != 0 || f.reloads != 0 || len(f.restarted) != 0 { |
| + t.Fatalf("unit touched: probed=%v reloads=%d restarted=%v", f.probed, f.reloads, f.restarted) |
| + } |
| + }) |
| + } |
| + // The same row, once root's evidence names the unit: delivered. |
| + ctx, s, reg, envDir, priv := unitKit(t) |
| + f := newFakeUnits(t) |
| + f.loaded("relay.service", envDir, "relay.example.com") |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| + syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if len(f.restarted) != 1 || hasPending(f.root, "relay.service") { |
| + t.Fatalf("bound: restarted=%v pending=%v", f.restarted, hasPending(f.root, "relay.service")) |
| + } |
| +} |
| + |
| +// TestSyncUnitsRefusesACarriageReturnInAValue is the witness for review |
| +// round 1 P1-2: a bundle value carrying '\r' is a second assignment to |
| +// systemd. It is refused at render for a stamped route, by name, whether |
| +// or not a base file exists, and nothing is written; a value without it |
| +// converges on the next pass. |
| +func TestSyncUnitsRefusesACarriageReturnInAValue(t *testing.T) { |
| + ctx, s, reg, envDir, priv := unitKit(t) |
| + f := newFakeUnits(t) |
| + f.loaded("relay.service", envDir, "relay.example.com") |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| + f.writeBase(t, "relay.service", "CONSOLE_DB=/data/console.db\n") |
| + // The smuggled line names a base-owned variable; the overlap rail |
| + // alone would never see it as a name. |
| + if err := SetEnv(ctx, s, "bab", "relay", map[string]string{"EXTRA": "ok\rCONSOLE_DB=/data/other.db"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if !strings.Contains(out, "blocked") || !strings.Contains(out, "EXTRA") || !strings.Contains(out, "carriage return") { |
| + t.Fatalf("expected a blocked line naming EXTRA, got %q", out) |
| + } |
| + if strings.Contains(out, "/data/other.db") || strings.Contains(out, "ok\r") { |
| + t.Fatalf("a value was logged: %q", out) |
| + } |
| + if ents, _ := os.ReadDir(envDir); len(ents) != 0 || len(f.restarted) != 0 || hasPending(f.root, "relay.service") { |
| + t.Fatalf("something was written or restarted: files=%v restarted=%v pending=%v", ents, f.restarted, hasPending(f.root, "relay.service")) |
| + } |
| + // No base file at all: still refused, the rail is not conditional on |
| + // an overlap. |
| + if err := os.Remove(baseEnvPath(f.base, "relay.service")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out := syncOnce(t, ctx, reg, s, priv, envDir, f); !strings.Contains(out, "carriage return") || len(f.restarted) != 0 { |
| + t.Fatalf("without a base file: restarted=%v out=%q", f.restarted, out) |
| + } |
| + if err := SetEnv(ctx, s, "bab", "relay", map[string]string{"EXTRA": "ok"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if len(f.restarted) != 1 || hasPending(f.root, "relay.service") { |
| + t.Fatalf("after the fix: restarted=%v pending=%v", f.restarted, hasPending(f.root, "relay.service")) |
| + } |
| +} |
| + |
| +// The base-file parser agrees with systemd (review round 1 P1-2): a |
| +// KEY=value line inside a quoted multiline value is a value, not a name, |
| +// so it does not block; an assignment after a bare '\r' IS a name, and |
| +// blocks. |
| +func TestSyncUnitsBaseFileNamesReadAsSystemdReadsThem(t *testing.T) { |
| + ctx, s, reg, envDir, priv := unitKit(t) |
| + f := newFakeUnits(t) |
| + f.loaded("relay.service", envDir, "relay.example.com") |
| + stampBound(t, f, reg, "relay.example.com", "relay.service", nil) |
| + f.writeBase(t, "relay.service", "BANNER=\"first line\nLOG_LEVEL=inside-quotes\nlast\"\n") |
| + syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if len(f.restarted) != 1 || hasPending(f.root, "relay.service") { |
| + t.Fatalf("a quoted multiline value was read as a name: restarted=%v pending=%v", f.restarted, hasPending(f.root, "relay.service")) |
| + } |
| + f.restarted = nil |
| + f.writeBase(t, "relay.service", "BANNER=first\rLOG_LEVEL=after-cr\n") |
| + if err := SetEnv(ctx, s, "bab", "relay", map[string]string{"LOG_LEVEL": "info"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if !strings.Contains(out, "blocked") || !strings.Contains(out, "LOG_LEVEL") || len(f.restarted) != 0 { |
| + t.Fatalf("an assignment after a carriage return in the base file was not read as a name: restarted=%v out=%q", f.restarted, out) |
| + } |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index c03e81537..b54f69042 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -5272,7 +5272,7 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni |
| secretsPriv, err := appconfig.ParsePrivateKey(raw, "CARLOS_SECRETS_KEY") |
| if err != nil { |
| log.Printf("adopt: config sync disabled: %v", err) |
| - } else if err := appconfig.SyncUnits(ctx, reg, store, secretsPriv, appconfig.DefaultEnvDir, restart, configAckFunc(ctx, store, "adopt"), productionUnitOps(appconfig.DefaultEnvDir), claims.Writes); err != nil { |
| + } else if err := appconfig.SyncUnits(ctx, reg, store, secretsPriv, appconfig.DefaultEnvDir, restart, configAckFunc(ctx, store, "adopt"), productionUnitOps(appconfig.DefaultEnvDir, restartChecks.resolve), claims.Writes); err != nil { |
| log.Printf("adopt: config sync: %v", err) |
| } |
| } |
diff --git a/internal/host/unitops.go b/internal/host/unitops.go| index bb20dcfcf..20f40434d 100644 |
| --- a/internal/host/unitops.go |
| +++ b/internal/host/unitops.go |
| @@ -6,6 +6,8 @@ package host |
| import ( |
| "bytes" |
| + "context" |
| + "errors" |
| "fmt" |
| "log" |
| "os" |
| @@ -13,23 +15,50 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| // dropInRoot is where systemd looks for a unit's drop-ins whichever tree |
| // the unit file itself lives in. |
| const dropInRoot = "/etc/systemd/system" |
| -func productionUnitOps(envDir string) *appconfig.UnitOps { |
| +// productionUnitOps: resolve is the release pass's proof-binding decider |
| +// (rootRestartChecks.resolve, proofBindingSource.resolve), handed in so |
| +// that one function decides route-to-unit binding for both the release |
| +// restart and config delivery (review round 1 P1-1). |
| +func productionUnitOps(envDir string, resolve func(context.Context, registry.Route) (proofBinding, error)) *appconfig.UnitOps { |
| return &appconfig.UnitOps{ |
| DropInRoot: dropInRoot, |
| BaseEnvDir: appconfig.DefaultUnitBaseDir, |
| Lock: func() (func(), error) { return lockConfigSync(envDir + "/.sync") }, |
| + Bind: unitOpsBind(resolve), |
| Probe: probeUnits, |
| Reload: daemonReload, |
| Restart: systemctlRestartUnit, |
| } |
| } |
| +// unitOpsBind is UnitOps.Bind over the proof binding: the route resolves |
| +// to root-observable evidence (a provisioning record, the root-owned |
| +// named-units declaration or the console guard, with the unit's ExecStart |
| +// matched against the proven executable; proofbinding.go), and that |
| +// evidence names the unit the row names. A nil resolve binds nothing. |
| +func unitOpsBind(resolve func(context.Context, registry.Route) (proofBinding, error)) func(context.Context, registry.Route) error { |
| + return func(ctx context.Context, rt registry.Route) error { |
| + if resolve == nil { |
| + return errors.New("no proof binding source") |
| + } |
| + b, err := resolve(ctx, rt) |
| + if err != nil { |
| + return err |
| + } |
| + if b.Route.Unit == "" || b.Route.Unit != rt.Unit { |
| + return fmt.Errorf("root's evidence binds %s to unit %q, not %s", rt.Host, b.Route.Unit, rt.Unit) |
| + } |
| + return nil |
| + } |
| +} |
| + |
| // lockConfigSync is lockRestartMarks's shape for the config pass: an |
| // exclusive flock on <path>.lock held for the whole of one SyncUnits, so |
| // carlos-adopt.service and carlos-config-sync.service queue rather than |
diff --git a/internal/host/unitops_test.go b/internal/host/unitops_test.go| index 8c6afbb8c..a71cec171 100644 |
| --- a/internal/host/unitops_test.go |
| +++ b/internal/host/unitops_test.go |
| @@ -1,8 +1,12 @@ |
| package host |
| import ( |
| + "context" |
| + "errors" |
| "strings" |
| "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| ) |
| func TestParseSystemctlShowBatched(t *testing.T) { |
| @@ -51,8 +55,38 @@ func TestParseSystemctlShowSpaceSeparatedEnvFiles(t *testing.T) { |
| // design §4.1): without it every drop-in would list a base file under the |
| // empty path. |
| func TestProductionUnitOpsNameTheBaseDir(t *testing.T) { |
| - ops := productionUnitOps("/etc/carlos/apps") |
| + ops := productionUnitOps("/etc/carlos/apps", nil) |
| if ops.BaseEnvDir != "/etc/carlos/units" || ops.DropInRoot != "/etc/systemd/system" { |
| t.Fatalf("BaseEnvDir=%q DropInRoot=%q", ops.BaseEnvDir, ops.DropInRoot) |
| } |
| } |
| + |
| +// The config pass binds a route to its unit through the release pass's |
| +// proof (review round 1 P1-1): no evidence, evidence for another unit, or |
| +// no source at all each refuse; evidence naming the row's unit admits. |
| +func TestUnitOpsBindRefusesWhatRootCannotProve(t *testing.T) { |
| + rt := registry.Route{Host: "relay.example.com", App: "relay", Account: "bab", Kind: "instance", Status: "ready", Addr: "127.0.0.1:8451", Unit: "relay.service"} |
| + if err := unitOpsBind(nil)(context.Background(), rt); err == nil { |
| + t.Fatal("no proof source must refuse") |
| + } |
| + failing := func(context.Context, registry.Route) (proofBinding, error) { |
| + return proofBinding{}, errors.New("no record") |
| + } |
| + if err := unitOpsBind(failing)(context.Background(), rt); err == nil || !strings.Contains(err.Error(), "no record") { |
| + t.Fatalf("unproven: %v", err) |
| + } |
| + other := func(_ context.Context, r registry.Route) (proofBinding, error) { |
| + r.Unit = "other.service" |
| + return proofBinding{Route: r}, nil |
| + } |
| + if err := unitOpsBind(other)(context.Background(), rt); err == nil || !strings.Contains(err.Error(), "other.service") { |
| + t.Fatalf("evidence for another unit: %v", err) |
| + } |
| + same := func(_ context.Context, r registry.Route) (proofBinding, error) { return proofBinding{Route: r}, nil } |
| + if err := unitOpsBind(same)(context.Background(), rt); err != nil { |
| + t.Fatalf("proven: %v", err) |
| + } |
| + if ops := productionUnitOps("/etc/carlos/apps", nil); ops.Bind == nil { |
| + t.Fatal("production ops must carry a Bind") |
| + } |
| +} |