carlos / platform Public

Named-unit delivery restructured around three invariants, per Paul's ruling on #114: a root-owned declaration decides, the base file is a strict grammar, one reader does every root read

Stopping rule 2 triggered after review rounds 1 and 2 and the census found
the same two fault families twice. Paul's ruling (2026-10-28, amadan
#114): a root-owned declaration decides. The round-1 Bind seam, its proof
binding adapter and the systemd-grammar parser are gone; three invariants
replace them, each enforced in one place.

Invariant A (declarations.go). declarations.DeclaredBinding(rt) is the
one decider: root writes, replaces, restarts for or removes a carlos
drop-in or env file for unit U only when /etc/carlos/named-units.json has
an entry naming U, host, account and app, and the registry row's host,
account and app equal the entry's. The file is the one the release path
reads (internal/host/proofnamed.go, rootNamedUnits), in its current shape;
this reader takes host, account, app and unit and ignores addr and
health, so nothing was added to it and the release path accepts exactly
what it did. planStamped asks the decider before the probe, prepareStamped
before any write, applyStamped before the restart. Reaping keys on the
declarations alone: a marked drop-in is removed only when no declaration
names its unit; changing, clearing or deleting a registry row removes
nothing, stops delivery and says why (plan.idle). An unreadable
declaration file delivers nothing and reaps nothing. Binding reads no
bucket key (round 2 P2-4): the IndexRecords path is gone from config
delivery.

Invariant B (baseenv.go baseFileNames). The base file must be valid
UTF-8, LF line endings, no CR or NUL, at most 64 KiB and 4096 bytes a
line, each line empty, a '#' comment with no backslash, or NAME=value
with NAME ^[A-Za-z_][A-Za-z0-9_]*$ and nothing before it and a value with
no backslash or quote. Anything else blocks the unit with the line named,
never its content. envFileNamesFrom and its tests are deleted. The
stamped-route carriage-return refusal stays.

Invariant C (rootread_unix.go rootRead). Every root read of the base
file, the declaration and an existing drop-in goes through one helper:
Lstat refuses a symlink at any component below the configured directory,
O_NOFOLLOW on the open, fstat on the descriptor, regular file, owned by
the trusted uid (root in production), not group- or other-writable, read
from that descriptor. Directory enumeration keeps its Lstat checks and
reads through the same helper. A !unix stub keeps the cross-compiles.

Round 2 P2-5: a stamped route's notice loads the default bundle whatever
the environment's exec_delivery says, and reports a failure Unresolved.

Witnesses through the real SyncUnits with the fake systemctl and a
temp filesystem root: registry account/app swap on a declared unit
(refused, nothing written, nothing reloaded); refused re-stamp (old
drop-in survives, no reload); clearing or deleting the row (drop-in
stays, delivery stops with a reason); removing the declaration (reaped,
marker first); unreadable declarations reap nothing; each forbidden base
construct including round 2's backslash-continued comment; a symlinked
base file, a symlinked drop-in and a group-writable base file; and a
store-call count showing a declared delivery reads only apps/<acct>/<app>/
keys. Spec §12 and docs/site/cli.md state the invariants, the ruling and
the declaration's shape.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

Summary

Replaces the proof-binding seam and the systemd-grammar parser with three centrally enforced invariants per Paul's ruling: a root-owned named-units.json declaration is the only authority for delivery and reaping, the base file is a strict NAME=value grammar or delivery blocks, and one descriptor-based reader does every root read of those files.
claude agent, operated by paul@keymail.dev c07d4121fd2887cd2b54d9dbd108ca109c83c308 parent 39f74dc
17 files changed, +935 −413
  • docs/site/cli.md +13 −3
  • docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md +65 −23
  • internal/appconfig/awaitingrestart_test.go +32 −0
  • internal/appconfig/baseenv.go +76 −113
  • internal/appconfig/baseenv_test.go +55 −30
  • internal/appconfig/declarations.go +128 −0
  • internal/appconfig/dropin.go +8 −5
  • internal/appconfig/dropin_test.go +7 −7
  • internal/appconfig/rootread_other.go +16 −0
  • internal/appconfig/rootread_unix.go +93 −0
  • internal/appconfig/sync.go +3 −3
  • internal/appconfig/syncexec.go +11 −0
  • internal/appconfig/unitsync.go +90 −52
  • internal/appconfig/unitsync_test.go +319 −108
  • internal/host/agent.go +1 −1
  • internal/host/unitops.go +12 −36
  • internal/host/unitops_test.go +6 −32

CI cancelled — superseded by a newer push — run details

diff --git a/docs/site/cli.md b/docs/site/cli.md
index 91017d186..64598fbb4 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2162,9 +2162,19 @@ 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. 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
+unit. The box delivers only to a unit that `/etc/carlos/named-units.json`
+(a root-owned file written when the box is set up) declares for the route,
+with the route's host, account and app, never from the route row alone:
+
+```json
+{"schema":1,"units":[
+ {"host":"relay.example.com","account":"bab","app":"relay","unit":"relay.service",
+ "addr":"127.0.0.1:8451","health":{"path":"/ready"}}
+]}
+```
+
+Removing a unit's line is what removes its drop-in; changing or removing
+the route only stops delivery. 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
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 57fb2a267..1d91941bd 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,28 +856,61 @@ 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.
+**Paul's ruling (2026-10-28, amadan #114), after review rounds 1 and 2
+and the census found the same two fault families twice (stopping rule
+2): a root-owned declaration decides.** Three invariants, each enforced in
+one place, replace the round-1 rails 4 and 5 that stood here:
+
+**Invariant A, one decider (`declarations.DeclaredBinding`,
+`internal/appconfig/declarations.go`).** Root writes, replaces, restarts
+for or removes a carlos drop-in or env file for unit U only when the
+root-owned `/etc/carlos/named-units.json` (the file the release path
+already reads, in its current shape; nothing was added to it) has an
+entry naming U, host, account and app, and the registry row's host,
+account and app equal that entry's (an entry with no account is the ops
+account, as the release path reads it). The registry selects which rows
+are considered; it never authorises. Instance records, the console guard
+marker and every other local or bucket evidence authorise nothing here,
+and binding reads no bucket key. `planStamped`, `prepareStamped` and
+`applyStamped` each ask the decider before they act; reaping keys on the
+declarations alone: a marker-bearing drop-in is removed only when no
+declaration names its unit any more, and changing, clearing or deleting a
+registry row removes nothing, only stops delivery and says why. A
+declaration file that cannot be read delivers nothing and reaps nothing.
+
+**Invariant B, refuse up front (`baseFileNames`, `baseenv.go`).** No
+systemd grammar is modelled. The base file must be valid UTF-8 with LF
+line endings, no CR and no NUL, at most 64 KiB and 4096 bytes per line,
+and every line empty, a `#` comment holding no backslash, or `NAME=value`
+with NAME matching `^[A-Za-z_][A-Za-z0-9_]*$` and nothing before it, and
+a value holding no backslash, single quote or double quote. Anything else
+blocks delivery for the unit with the line named. The bundle side is
+already safe (`ValidVarValue` refuses backslash, quotes, newline and NUL
+at render); for a stamped route a carriage return in a value is refused
+at render as well (`carriageReturnVar`).
+
+**Invariant C, one reader (`rootRead`, `rootread_unix.go`).** Every root
+read of the base file, the declaration and an existing drop-in goes
+through one helper: it refuses a symlink at any component below the
+configured directory, opens with `O_NOFOLLOW`, fstat's the descriptor,
+requires a regular file owned by root and writable by neither group nor
+others, and reads from that descriptor. Anything else is refused with the
+reason and blocks the unit. Directory enumeration under
+`/etc/systemd/system/<unit>.d` keeps its `Lstat` checks and reads any
+file through the same helper.
+
+Consequence for the fleet: each stamped unit needs one declaration line
+(the console, each Woodstar unit) before carlos delivers to it:
+
+```json
+{"schema":1,"units":[
+ {"host":"relay.example.com","account":"bab","app":"relay","unit":"relay.service",
+ "addr":"127.0.0.1:8451","health":{"path":"/ready"}}
+]}
+```
+
+`addr` and `health` are the release path's fields and are not read for
+delivery. Round 3 is the last review round.
Tests (console config design §11, first three bullets) run through the
real `SyncUnits` with the faked `UnitOps`:
@@ -886,7 +919,16 @@ real `SyncUnits` with the faked `UnitOps`:
`TestSyncUnitsDropInListsBaseBeforeBundle`,
`TestSyncUnitsRefusesANameInBothLayers`,
`TestSyncUnitsRefusesAnUnreadableBaseFile`, plus `TestEnvFilesMatch` for
-the full mismatch matrix.
+the full mismatch matrix. The invariants' witnesses, through the same
+pass: `TestSyncUnitsRefusesAStampRootCannotBind`,
+`TestSyncUnitsRefusesARegistryAccountOrAppSwap`,
+`TestSyncUnitsReStampMovesTheDropIn` (a refused re-stamp keeps the old
+drop-in and reloads nothing), `TestSyncUnitsReapsOnlyWhenTheDeclarationGoes`,
+`TestSyncUnitsUnreadableDeclarationsReapNothing`,
+`TestSyncUnitsDeclarationAddsNoBucketReads` (A);
+`TestSyncUnitsRefusesABaseFileOutsideTheGrammar` and
+`TestBaseFileNamesGrammar` (B); `TestSyncUnitsRefusesFilesTheOneReaderRefuses`
+(C).
Consequence for §4 and §7: on today's fleet no stamped unit is known to
carry an `EnvironmentFile=` line of its own; where one does, the first
diff --git a/internal/appconfig/awaitingrestart_test.go b/internal/appconfig/awaitingrestart_test.go
index 565aa38a6..5f745f3ff 100644
--- a/internal/appconfig/awaitingrestart_test.go
+++ b/internal/appconfig/awaitingrestart_test.go
@@ -531,3 +531,35 @@ func TestAwaitingRestartStampedRouteWithACorruptOverlayIsUnresolved(t *testing.T
t.Fatalf("a stamped route with a corrupt overlay must be Unresolved, got %+v", got)
}
}
+
+// Round 2 P2-5: a stamped route on a named environment that sets
+// exec_delivery explicitly still needs the default bundle, which delivery
+// reads; a corrupt default is Unresolved, not silence.
+func TestAwaitingRestartStampedRouteNeedsTheDefaultBundleWhateverTheOptIn(t *testing.T) {
+ ctx, s, _, _, _, _ := execKit(t)
+ if err := SetEnv(ctx, s, "bab", "relay", map[string]string{"K": "v"}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ApplyEnvironment(ctx, s, "bab", "relay", "staging", map[string]Var{"S": {Kind: "env", Value: "1"}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetExecDeliveryAt(ctx, s, "bab", "relay", "staging", ExecDeliveryFile); err != nil {
+ t.Fatal(err)
+ }
+ rt := addrRoute("relay.example.com", "relay", "bab", "staging")
+ rt.Unit = "relay.service"
+ if got := AwaitingRestart(ctx, s, []registry.Route{rt}, "bab", "relay", "staging", []string{"S"}); !got.Empty() {
+ t.Fatalf("healthy: %+v", got)
+ }
+ _, etag, err := s.Get(ctx, Key("bab", "relay"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Put(ctx, Key("bab", "relay"), []byte("{"), etag); err != nil {
+ t.Fatal(err)
+ }
+ got := AwaitingRestart(ctx, s, []registry.Route{rt}, "bab", "relay", "staging", []string{"S"})
+ if len(got.Unresolved) != 1 || got.Unresolved[0] != "relay.example.com" {
+ t.Fatalf("a corrupt default bundle must be Unresolved for a stamped route, got %+v", got)
+ }
+}
diff --git a/internal/appconfig/baseenv.go b/internal/appconfig/baseenv.go
index 94b022b2b..1f9957598 100644
--- a/internal/appconfig/baseenv.go
+++ b/internal/appconfig/baseenv.go
@@ -6,14 +6,19 @@
// never resets a file away silently (unmanagedEnvFiles), and no variable
// name may be stated by both layers (overlappingNames). Names only, here
// and in every log line: a value in the base file is never read for
-// anything but its name.
+// anything but its name. The file is read through rootRead (invariant C)
+// and must satisfy baseFileNames' grammar (invariant B).
package appconfig
import (
- "os"
+ "bytes"
+ "errors"
+ "fmt"
"path/filepath"
+ "regexp"
"sort"
"strings"
+ "unicode/utf8"
)
// DefaultUnitBaseDir is where a stamped unit's base file lives in
@@ -25,6 +30,10 @@ func baseEnvPath(baseDir, unit string) string {
return filepath.Join(baseDir, unit+".base.env")
}
+// parentDir is filepath.Dir, named for what rootRead wants: the configured
+// directory a file must lie under.
+func parentDir(path string) string { return filepath.Dir(path) }
+
// unmanagedEnvFiles is the unmanaged-file guard (§4.1): the paths in got
// that are neither the base file nor the bundle, in got's order. A unit
// loading any such file before carlos writes its first drop-in would have
@@ -41,123 +50,74 @@ func unmanagedEnvFiles(got []string, base, bundle string) []string {
return out
}
-// envFileNames reads the variable NAMES of an EnvironmentFile-format file
-// 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)
+// Invariant B (#114 spec §12, Paul's ruling): the base file must be a
+// strict subset systemd and this guard cannot read differently, or delivery
+// for the unit is blocked with the reason. No systemd grammar is modelled
+// here on purpose; whatever is not plainly NAME=value is refused up front.
+const (
+ baseFileLimit = 64 << 10
+ baseFileLineLimit = 4096
+)
+
+var baseNameRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
+
+// envFileNames reads the base file at path (under baseDir) through rootRead
+// (invariant C) and returns its variable NAMES, or the reason the file is
+// not one this pass may deliver beside. A missing file has no names.
+func envFileNames(baseDir, path string, trustedUID int) ([]string, error) {
+ raw, err := rootRead(baseDir, path, trustedUID)
if err != nil {
- if os.IsNotExist(err) {
+ if err == errNoFile {
return nil, nil
}
return nil, err
}
- return envFileNamesFrom(raw), nil
+ return baseFileNames(raw)
}
-// 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
- 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]
+// baseFileNames is the grammar: valid UTF-8, LF line endings only, no CR
+// and no NUL anywhere, at most baseFileLimit bytes and baseFileLineLimit
+// bytes per line; each line empty, a comment starting with '#' holding no
+// backslash, or NAME=value with NAME matching baseNameRe and nothing before
+// it, and a value holding no backslash, single quote or double quote. The
+// error names the line, never its content.
+func baseFileNames(raw []byte) ([]string, error) {
+ if len(raw) > baseFileLimit {
+ return nil, fmt.Errorf("larger than %d bytes", baseFileLimit)
}
- 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
+ if !utf8.Valid(raw) {
+ return nil, errors.New("not valid UTF-8")
+ }
+ if bytes.IndexByte(raw, '\r') >= 0 {
+ return nil, errors.New("holds a carriage return; only LF line endings are read")
+ }
+ if bytes.IndexByte(raw, 0) >= 0 {
+ return nil, errors.New("holds a NUL byte")
+ }
+ var names []string
+ for i, line := range strings.Split(string(raw), "\n") {
+ n := i + 1
+ switch {
+ case len(line) > baseFileLineLimit:
+ return nil, fmt.Errorf("line %d is longer than %d bytes", n, baseFileLineLimit)
+ case line == "":
+ continue
+ case line[0] == '#':
+ if strings.IndexByte(line, '\\') >= 0 {
+ return nil, fmt.Errorf("line %d: a comment may not hold a backslash", n)
}
- case commentEscape:
- state = comment
+ continue
}
+ name, value, ok := strings.Cut(line, "=")
+ if !ok || !baseNameRe.MatchString(name) {
+ return nil, fmt.Errorf("line %d is not NAME=value (NAME of [A-Za-z0-9_], not starting with a digit, nothing before it)", n)
+ }
+ if strings.ContainsAny(value, "\\'\"") {
+ return nil, fmt.Errorf("line %d: the value of %s holds a backslash or a quote", n, name)
+ }
+ names = append(names, name)
}
- switch state {
- case preValue, value, valueEscape, singleQuote, doubleQuote, doubleQuoteEscape:
- emit()
- }
- return names
+ return names, nil
}
// carriageReturnVar is the carriage-return rail for a stamped route
@@ -181,9 +141,11 @@ func carriageReturnVar(rendered []byte) string {
// 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 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.
+// bundle as RenderEnv writes it, KEY=value per line with no backslash,
+// quote, newline or NUL in a value (ValidVarValue) and, for a stamped
+// route, no carriage return (carriageReturnVar, checked first), so a line
+// is one assignment and the name is what precedes '='; agent-owned names
+// are included.
func overlappingNames(base []string, rendered []byte) []string {
inBase := make(map[string]bool, len(base))
for _, n := range base {
@@ -191,8 +153,9 @@ func overlappingNames(base []string, rendered []byte) []string {
}
seen := map[string]bool{}
var out []string
- for _, name := range envFileNamesFrom(rendered) {
- if !inBase[name] || seen[name] {
+ for _, line := range strings.Split(string(rendered), "\n") {
+ name, _, ok := strings.Cut(line, "=")
+ if !ok || !inBase[name] || seen[name] {
continue
}
seen[name] = true
diff --git a/internal/appconfig/baseenv_test.go b/internal/appconfig/baseenv_test.go
index 7e453cd23..46fc54b38 100644
--- a/internal/appconfig/baseenv_test.go
+++ b/internal/appconfig/baseenv_test.go
@@ -1,6 +1,7 @@
package appconfig
import (
+ "bytes"
"os"
"path/filepath"
"strings"
@@ -10,25 +11,75 @@ import (
func TestEnvFileNamesReadsNamesOnly(t *testing.T) {
dir := t.TempDir()
path := baseEnvPath(dir, "console.service")
- if names, err := envFileNames(path); err != nil || names != nil {
+ if names, err := envFileNames(dir, path, os.Getuid()); err != nil || names != nil {
t.Fatalf("absent file: names=%v err=%v, want none and no error", names, err)
}
- body := "# provisioned by root\n\nCONSOLE_DB=/data/console.db\n CARLOS_REGISTRY = /data/registry.db \n;comment\nnot a var\n=novalue\nEMPTY=\n"
+ body := "# provisioned by root\n\nCONSOLE_DB=/data/console.db\nCARLOS_REGISTRY=/data/registry.db\nEMPTY=\n"
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
- names, err := envFileNames(path)
+ names, err := envFileNames(dir, path, os.Getuid())
if err != nil || strings.Join(names, ",") != "CONSOLE_DB,CARLOS_REGISTRY,EMPTY" {
t.Fatalf("names = %v, %v", names, err)
}
if err := os.Mkdir(filepath.Join(dir, "dir.service.base.env"), 0o755); err != nil {
t.Fatal(err)
}
- if _, err := envFileNames(baseEnvPath(dir, "dir.service")); err == nil {
+ if _, err := envFileNames(dir, baseEnvPath(dir, "dir.service"), os.Getuid()); err == nil {
t.Fatal("a base file that cannot be read must be an error, not an empty list")
}
}
+// Invariant B: the grammar is a strict subset systemd and this guard cannot
+// read differently; everything else is refused with the line named and
+// its content never echoed.
+func TestBaseFileNamesGrammar(t *testing.T) {
+ for _, tc := range []struct{ in, names string }{
+ {"", ""},
+ {"A=1\n", "A"},
+ {"A=1", "A"},
+ {"# c\n\nA_1=x y z\n_B=\n", "A_1,_B"},
+ {"A=a=b\n", "A"},
+ {"A=#notacomment\n", "A"},
+ } {
+ got, err := baseFileNames([]byte(tc.in))
+ if err != nil || strings.Join(got, ",") != tc.names {
+ t.Errorf("%q: names=%v err=%v, want %q", tc.in, got, err, tc.names)
+ }
+ }
+ for name, in := range map[string]string{
+ "comment with backslash": "# comment\\\nCONSOLE_DB=/data/base.db\n",
+ "CR line ending": "A=1\r\n",
+ "bare CR": "A=1\rB=2\n",
+ "NUL": "A=1\x00\n",
+ "invalid UTF-8": "A=\xff\n",
+ "export prefix": "export A=1\n",
+ "space before name": " A=1\n",
+ "space before equals": "A =1\n",
+ "digit-leading name": "1A=1\n",
+ "hyphen in name": "A-B=1\n",
+ "no equals": "A\n",
+ "semicolon comment": "; c\n",
+ "double quote in value": "A=\"x\"\n",
+ "single quote in value": "A='x'\n",
+ "backslash in value": "A=x\\y\n",
+ "continued value": "A=x\\\nB=2\n",
+ "line too long": "A=" + strings.Repeat("x", baseFileLineLimit) + "\n",
+ } {
+ got, err := baseFileNames([]byte(in))
+ if err == nil {
+ t.Errorf("%s: %q accepted as %v, want refused", name, in, got)
+ continue
+ }
+ if strings.Contains(err.Error(), "/data/base.db") || strings.Contains(err.Error(), "x\\y") {
+ t.Errorf("%s: the error echoes content: %v", name, err)
+ }
+ }
+ if _, err := baseFileNames(bytes.Repeat([]byte("A=1\n"), baseFileLimit/4+1)); err == nil {
+ t.Error("a file over the size cap was accepted")
+ }
+}
+
func TestOverlappingNames(t *testing.T) {
rendered := []byte("LOG_LEVEL=debug\nTOKEN=x\nCARLOS_PURGE=header\n")
got := overlappingNames([]string{"TOKEN", "CONSOLE_DB", "LOG_LEVEL", "CARLOS_PURGE"}, rendered)
@@ -57,32 +108,6 @@ func TestUnmanagedEnvFiles(t *testing.T) {
}
}
-// 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)
diff --git a/internal/appconfig/declarations.go b/internal/appconfig/declarations.go
new file mode 100644
index 000000000..f4fc79150
--- /dev/null
+++ b/internal/appconfig/declarations.go
@@ -0,0 +1,128 @@
+// Invariant A of named-unit delivery (#114 spec §12, Paul's ruling of
+// 2026-10-28): a root-owned declaration decides. Root writes, replaces or
+// removes a carlos drop-in or env file for a unit only when
+// /etc/carlos/named-units.json has an entry naming that unit, host, account
+// and app, and the registry row's host, account and app equal the entry's.
+// The registry selects which rows to consider; it never authorises. The
+// provisioning record, the console guard marker and every other local or
+// bucket evidence authorise nothing here, and nothing here reads the bucket.
+//
+// The file is the one the release path already reads
+// (internal/host/proofnamed.go, rootNamedUnits), in its current shape:
+// {"schema":1,"units":[{"host","account","app","unit","addr","health"}]}.
+// This reader takes host, account, app and unit and ignores the rest, so a
+// file the release path accepts is accepted as it stands and nothing was
+// added to the shape.
+package appconfig
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+
+ "github.com/carlosframework/platform/internal/controlname"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// DefaultNamedUnitsPath is the declaration file in production; the release
+// path's rootNamedUnits is the same path (pinned by a test in
+// internal/host).
+const DefaultNamedUnitsPath = "/etc/carlos/named-units.json"
+
+// Declaration is one entry of the file: the unit root may deliver to, and
+// the route (host, account, app) whose config it takes. An empty account in
+// the file is the ops account, as the release path reads it.
+type Declaration struct {
+ Host string `json:"host"`
+ Account string `json:"account,omitempty"`
+ App string `json:"app"`
+ Unit string `json:"unit"`
+}
+
+func (d Declaration) account() string {
+ if d.Account == "" {
+ return release.OpsAccount
+ }
+ return d.Account
+}
+
+// declarations is the loaded file: one entry per unit and one per host, or
+// the file is invalid and nothing is declared.
+type declarations struct {
+ path string
+ byUnit map[string]Declaration
+}
+
+// loadDeclarations reads the file through rootRead (invariant C). An
+// absent file declares nothing. An unreadable or invalid file is an error:
+// the caller delivers nothing and reaps nothing, since what is declared is
+// then unknown.
+func loadDeclarations(ops *UnitOps) (*declarations, error) {
+ d := &declarations{path: ops.NamedUnitsPath, byUnit: map[string]Declaration{}}
+ if ops.NamedUnitsPath == "" {
+ return nil, fmt.Errorf("no named-units declaration path on this pass")
+ }
+ raw, err := rootRead(parentDir(ops.NamedUnitsPath), ops.NamedUnitsPath, ops.trustedUID)
+ if err != nil {
+ if err == errNoFile {
+ return d, nil
+ }
+ return nil, fmt.Errorf("declarations: %w", err)
+ }
+ var file struct {
+ Schema int `json:"schema"`
+ Units []Declaration `json:"units"`
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ if err := dec.Decode(&file); err != nil {
+ return nil, fmt.Errorf("declarations: %s: %w", ops.NamedUnitsPath, err)
+ }
+ if file.Schema != 1 {
+ return nil, fmt.Errorf("declarations: %s: schema %d, want 1", ops.NamedUnitsPath, file.Schema)
+ }
+ byHost := map[string]bool{}
+ for _, u := range file.Units {
+ switch {
+ case !controlname.ValidHostShape(u.Host):
+ return nil, fmt.Errorf("declarations: %s: %q is not a hostname", ops.NamedUnitsPath, u.Host)
+ case !release.ValidApp(u.App):
+ return nil, fmt.Errorf("declarations: %s: %q is not an app name", ops.NamedUnitsPath, u.App)
+ case u.Account != "" && !release.ValidAccount(u.Account):
+ return nil, fmt.Errorf("declarations: %s: %q is not an account", ops.NamedUnitsPath, u.Account)
+ case !registry.ValidUnitName(u.Unit):
+ return nil, fmt.Errorf("declarations: %s: %q is not a unit name", ops.NamedUnitsPath, u.Unit)
+ case byHost[u.Host]:
+ return nil, fmt.Errorf("declarations: %s: %s is declared twice", ops.NamedUnitsPath, u.Host)
+ }
+ if _, dup := d.byUnit[u.Unit]; dup {
+ return nil, fmt.Errorf("declarations: %s: %s is declared for two hosts", ops.NamedUnitsPath, u.Unit)
+ }
+ byHost[u.Host] = true
+ d.byUnit[u.Unit] = u
+ }
+ return d, nil
+}
+
+// DeclaredBinding is THE decider: the declaration that authorises root to
+// deliver rt's config to rt.Unit, or the reason there is none. Every path
+// that writes, replaces or restarts for a stamped route asks it (plan,
+// prepare, apply); reaping asks declares.
+func (d *declarations) DeclaredBinding(rt registry.Route) (Declaration, error) {
+ e, ok := d.byUnit[rt.Unit]
+ if !ok {
+ return Declaration{}, fmt.Errorf("no entry in %s names %s", d.path, rt.Unit)
+ }
+ if e.Host != rt.Host || e.App != rt.App || e.account() != release.RouteAccount(rt) {
+ return Declaration{}, fmt.Errorf("%s declares %s for %s (%s/%s), not for this route (%s, %s/%s)",
+ d.path, rt.Unit, e.Host, e.account(), e.App, rt.Host, release.RouteAccount(rt), rt.App)
+ }
+ return e, nil
+}
+
+// declares reports whether any entry names unit: the only authority to keep
+// or remove its drop-in.
+func (d *declarations) declares(unit string) bool {
+ _, ok := d.byUnit[unit]
+ return ok
+}
diff --git a/internal/appconfig/dropin.go b/internal/appconfig/dropin.go
index 1b5183cc2..d91db73f1 100644
--- a/internal/appconfig/dropin.go
+++ b/internal/appconfig/dropin.go
@@ -73,10 +73,13 @@ func dirIsPlain(dir string) bool {
return err == nil && st.IsDir() && st.Mode()&os.ModeSymlink == 0
}
-func readDropIn(root, unit string) (cur []byte, exists, marked bool, err error) {
- cur, err = os.ReadFile(filepath.Join(dropInDir(root, unit), DropInFile))
+// readDropIn reads <unit>.d/zz-carlos-env.conf through rootRead (invariant
+// C): a symlinked directory or file, a file not owned by the trusted uid or
+// writable by others, is an error, never a drop-in.
+func readDropIn(root, unit string, trustedUID int) (cur []byte, exists, marked bool, err error) {
+ cur, err = rootRead(root, filepath.Join(dropInDir(root, unit), DropInFile), trustedUID)
if err != nil {
- if os.IsNotExist(err) {
+ if err == errNoFile {
return nil, false, false, nil
}
return nil, false, false, err
@@ -157,10 +160,10 @@ func unitDirs(root string) (units, skipped []string) {
// keyed to the error that readDropIn returned: those units are neither
// listed nor silently dropped — the caller decides what "unreadable" means
// for its own pass (reapDropIns: not reaped).
-func listMarkedDropIns(root string) (units, skipped []string, unreadable map[string]error) {
+func listMarkedDropIns(root string, trustedUID int) (units, skipped []string, unreadable map[string]error) {
dirs, skipped := unitDirs(root)
for _, u := range dirs {
- _, exists, marked, err := readDropIn(root, u)
+ _, exists, marked, err := readDropIn(root, u, trustedUID)
if err != nil {
if unreadable == nil {
unreadable = map[string]error{}
diff --git a/internal/appconfig/dropin_test.go b/internal/appconfig/dropin_test.go
index 182c41579..7300c4190 100644
--- a/internal/appconfig/dropin_test.go
+++ b/internal/appconfig/dropin_test.go
@@ -25,14 +25,14 @@ func TestWriteReadAndMarkDropIn(t *testing.T) {
if err := ensureDropInDir(root, "relay.service"); err != nil {
t.Fatalf("ensureDropInDir: %v", err)
}
- if _, exists, _, err := readDropIn(root, "relay.service"); err != nil || exists {
+ if _, exists, _, err := readDropIn(root, "relay.service", os.Getuid()); err != nil || exists {
t.Fatalf("readDropIn before write: exists=%v err=%v", exists, err)
}
body := renderDropIn("/etc/carlos/apps", "/etc/carlos/units", "relay.service", "relay.example.com")
if err := writeDropIn(root, "relay.service", body); err != nil {
t.Fatalf("writeDropIn: %v", err)
}
- cur, exists, marked, err := readDropIn(root, "relay.service")
+ cur, exists, marked, err := readDropIn(root, "relay.service", os.Getuid())
if err != nil || !exists || !marked || string(cur) != string(body) {
t.Fatalf("readDropIn after write: exists=%v marked=%v err=%v", exists, marked, err)
}
@@ -65,11 +65,11 @@ func TestReadDropInSeesAnUnmarkedFile(t *testing.T) {
dir := filepath.Join(root, "relay.service.d")
os.MkdirAll(dir, 0o755)
os.WriteFile(filepath.Join(dir, DropInFile), []byte("[Service]\nEnvironmentFile=/x\n"), 0o644)
- _, exists, marked, err := readDropIn(root, "relay.service")
+ _, exists, marked, err := readDropIn(root, "relay.service", os.Getuid())
if err != nil || !exists || marked {
t.Fatalf("exists=%v marked=%v err=%v, want an existing unmarked file", exists, marked, err)
}
- units, _, unreadable := listMarkedDropIns(root)
+ units, _, unreadable := listMarkedDropIns(root, os.Getuid())
if len(units) != 0 {
t.Fatalf("listMarkedDropIns = %v, want none for an unmarked file", units)
}
@@ -105,7 +105,7 @@ func TestListMarkedDropInsSkipsSymlinkedDirs(t *testing.T) {
os.Symlink(elsewhere, filepath.Join(root, "retired.service.d"))
os.MkdirAll(filepath.Join(root, "real.service.d"), 0o755)
os.WriteFile(filepath.Join(root, "real.service.d", DropInFile), renderDropIn("/e", "/b", "x.service", "h"), 0o644)
- units, skipped, unreadable := listMarkedDropIns(root)
+ units, skipped, unreadable := listMarkedDropIns(root, os.Getuid())
if len(units) != 1 || units[0] != "real.service" {
t.Fatalf("units = %v, want [real.service]", units)
}
@@ -128,7 +128,7 @@ func TestListMarkedDropInsReportsAnUnreadableFile(t *testing.T) {
// something other than IsNotExist, which is the shape this covers —
// permission-denied on a real box reads the same way to the caller.
os.MkdirAll(filepath.Join(dir, DropInFile), 0o755)
- units, skipped, unreadable := listMarkedDropIns(root)
+ units, skipped, unreadable := listMarkedDropIns(root, os.Getuid())
if len(units) != 0 {
t.Fatalf("units = %v, want none for an unreadable drop-in", units)
}
@@ -147,7 +147,7 @@ func TestRemoveDropIn(t *testing.T) {
if err := removeDropIn(root, "relay.service"); err != nil {
t.Fatalf("removeDropIn: %v", err)
}
- if _, exists, _, _ := readDropIn(root, "relay.service"); exists {
+ if _, exists, _, _ := readDropIn(root, "relay.service", os.Getuid()); exists {
t.Fatal("drop-in still present")
}
if _, err := os.Stat(filepath.Join(root, "relay.service.d")); err != nil {
diff --git a/internal/appconfig/rootread_other.go b/internal/appconfig/rootread_other.go
new file mode 100644
index 000000000..1caeca9a2
--- /dev/null
+++ b/internal/appconfig/rootread_other.go
@@ -0,0 +1,16 @@
+//go:build !unix
+
+package appconfig
+
+import (
+ "errors"
+ "fmt"
+)
+
+var errNoFile = errors.New("no such file")
+
+// rootRead needs fstat ownership and O_NOFOLLOW; the root pass runs on
+// Linux only, and this stub keeps the cross-compile gate honest.
+func rootRead(root, path string, trustedUID int) ([]byte, error) {
+ return nil, fmt.Errorf("root read of %s: unsupported on this platform", path)
+}
diff --git a/internal/appconfig/rootread_unix.go b/internal/appconfig/rootread_unix.go
new file mode 100644
index 000000000..07df58d29
--- /dev/null
+++ b/internal/appconfig/rootread_unix.go
@@ -0,0 +1,93 @@
+//go:build unix
+
+// Invariant C of named-unit delivery (#114 spec §12, Paul's ruling of
+// 2026-10-28): ONE reader does every root read of the base file, the
+// named-units declaration and an existing drop-in. It opens the last
+// component with O_NOFOLLOW after refusing a symlink at any component below
+// the configured root, fstat's the descriptor, requires a regular file owned
+// by the trusted uid and writable by neither group nor others, and reads
+// from that descriptor. Anything else is refused with the reason, and the
+// caller blocks the unit.
+package appconfig
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+)
+
+// rootReadLimit caps what one read returns; every file this reader is for
+// is small, and a cap keeps a bad file from being a memory cost.
+const rootReadLimit = 1 << 20
+
+// errNoFile is rootRead's answer for a path with nothing at it, the one
+// refusal a caller may treat as "absent" rather than "blocked".
+var errNoFile = errors.New("no such file")
+
+// rootRead reads path, which must lie under root, through the checks above.
+// trustedUID is 0 in production (UnitOps leaves it zero); a test sets it to
+// its own uid.
+func rootRead(root, path string, trustedUID int) ([]byte, error) {
+ rel, err := filepath.Rel(root, path)
+ if err != nil || rel == "." || strings.HasPrefix(rel, "..") || filepath.IsAbs(rel) {
+ return nil, fmt.Errorf("%s is not under %s", path, root)
+ }
+ // Every component from the root down to the parent is a plain
+ // directory; a symlink anywhere would let the open land elsewhere.
+ cur := root
+ parts := strings.Split(rel, string(filepath.Separator))
+ for i, part := range append([]string{""}, parts[:len(parts)-1]...) {
+ if i > 0 {
+ cur = filepath.Join(cur, part)
+ }
+ st, err := os.Lstat(cur)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, errNoFile
+ }
+ return nil, err
+ }
+ if st.Mode()&os.ModeSymlink != 0 {
+ return nil, fmt.Errorf("%s is a symlink; refusing to read through it", cur)
+ }
+ if !st.IsDir() {
+ return nil, fmt.Errorf("%s is not a directory", cur)
+ }
+ }
+ fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0)
+ if err != nil {
+ if errors.Is(err, syscall.ENOENT) {
+ return nil, errNoFile
+ }
+ if errors.Is(err, syscall.ELOOP) {
+ return nil, fmt.Errorf("%s is a symlink; refusing to read through it", path)
+ }
+ return nil, fmt.Errorf("open %s: %w", path, err)
+ }
+ f := os.NewFile(uintptr(fd), path)
+ defer f.Close()
+ var st syscall.Stat_t
+ if err := syscall.Fstat(fd, &st); err != nil {
+ return nil, fmt.Errorf("fstat %s: %w", path, err)
+ }
+ switch {
+ case st.Mode&syscall.S_IFMT != syscall.S_IFREG:
+ return nil, fmt.Errorf("%s is not a regular file", path)
+ case int(st.Uid) != trustedUID:
+ return nil, fmt.Errorf("%s is owned by uid %d, not %d", path, st.Uid, trustedUID)
+ case st.Mode&0o022 != 0:
+ return nil, fmt.Errorf("%s is writable by its group or others (mode %04o)", path, st.Mode&0o7777)
+ }
+ raw, err := io.ReadAll(io.LimitReader(f, rootReadLimit+1))
+ if err != nil {
+ return nil, fmt.Errorf("read %s: %w", path, err)
+ }
+ if len(raw) > rootReadLimit {
+ return nil, fmt.Errorf("%s is larger than %d bytes", path, rootReadLimit)
+ }
+ return raw, nil
+}
diff --git a/internal/appconfig/sync.go b/internal/appconfig/sync.go
index ad22f8e8f..4417bd8b1 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(ctx, routes, envDir, ops)
+ plan = planStamped(routes, envDir, ops)
}
work := map[string]unitWork{} // by unit
type groupKey struct{ acct, app, env string }
@@ -328,7 +328,7 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St
fmt.Printf(" %s: stamped but planned no unit; skipped\n", rt.Host)
continue
}
- work[unit] = prepareStamped(rt, unit, m, defaultMissing, priv, envDir, ops)
+ work[unit] = prepareStamped(rt, unit, m, defaultMissing, priv, envDir, ops, plan)
continue
}
// Only unit-backed routes read /etc/carlos/apps — an exec-backed
@@ -348,7 +348,7 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St
}
}
if ops != nil {
- reapDropIns(routes, ops)
+ reapDropIns(plan, ops)
applyStamped(envDir, ops, plan, work)
}
// An empty route list is never authority to delete anything:
diff --git a/internal/appconfig/syncexec.go b/internal/appconfig/syncexec.go
index 55669f900..edc85b0fa 100644
--- a/internal/appconfig/syncexec.go
+++ b/internal/appconfig/syncexec.go
@@ -1269,6 +1269,17 @@ func AwaitingRestart(ctx context.Context, s release.Store, routes []registry.Rou
// root pass loads it for a stamped route and refuses delivery when
// it will not read (sync.go; review round 1 P2-6).
if stamped {
+ // The default bundle is required by delivery whatever the
+ // exec-delivery opt-in says (round 2 P2-5: resolveExecDelivery
+ // returns before reading it when the environment sets
+ // exec_delivery explicitly); only an owned environment stands
+ // alone without it.
+ if def != nil && !(eb.found && eb.m != nil && eb.m.Owned()) {
+ if _, _, defErr := loadDefault(); defErr != nil {
+ out.Unresolved = append(out.Unresolved, rt.Host)
+ continue
+ }
+ }
if _, _, instErr := overlayFor(acct, app, rt.Host); instErr != nil {
out.Unresolved = append(out.Unresolved, rt.Host)
}
diff --git a/internal/appconfig/unitsync.go b/internal/appconfig/unitsync.go
index 66efd6dde..e854ac0bd 100644
--- a/internal/appconfig/unitsync.go
+++ b/internal/appconfig/unitsync.go
@@ -8,7 +8,6 @@ package appconfig
import (
"bytes"
- "context"
"crypto/ecdh"
"fmt"
"path/filepath"
@@ -42,17 +41,15 @@ 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
+ // NamedUnitsPath is the root-owned declaration file (invariant A,
+ // declarations.go; DefaultNamedUnitsPath in production). A stamped
+ // route is delivered to, and a drop-in kept or removed, only on what
+ // this file declares; the registry never authorises.
+ NamedUnitsPath string
+ // trustedUID is the owner every file this pass reads must have
+ // (invariant C, rootRead): zero, root, in production; a test sets its
+ // own uid.
+ trustedUID int
// 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
@@ -75,19 +72,28 @@ type stampedPlan struct {
refused map[string]string
// probe is the pre-mutation probe answer for every delivered unit.
probe map[string]UnitState
+ // decls is the declaration file as loaded this pass, the authority for
+ // every write, restart and removal below; nil when it could not be read,
+ // in which case nothing is delivered and nothing is reaped.
+ decls *declarations
+ // idle are the declared units no delivering route names this pass: their
+ // drop-ins stay, and the pass says so.
+ idle []string
}
// planStamped applies the rail (spec §3.2) to every stamped route in
// routes, in this order: shape, unit name, hostname, one-route-per-unit,
-// 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 {
+// the declaration (invariant A, DeclaredBinding), 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 declaration 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(routes []registry.Route, envDir string, ops *UnitOps) stampedPlan {
p := stampedPlan{unitOf: map[string]string{}, refused: map[string]string{}, probe: map[string]UnitState{}}
+ decls, declErr := loadDeclarations(ops)
+ p.decls = decls
byUnit := map[string][]string{}
rowOf := map[string]registry.Route{}
for _, rt := range routes {
@@ -119,17 +125,31 @@ func planStamped(ctx context.Context, routes []registry.Route, envDir string, op
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)
+ if declErr != nil {
+ p.refused[host] = fmt.Sprintf("the declaration file could not be read (%v); a registry row alone never authorises delivery", declErr)
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)
+ if _, err := decls.DeclaredBinding(rowOf[host]); err != nil {
+ p.refused[host] = fmt.Sprintf("not declared: %v; a registry row alone never authorises delivery. Declare the unit for this route in %s and the route converges on the next pass", err, ops.NamedUnitsPath)
continue
}
units = append(units, unit)
}
sort.Strings(units)
+ // Declared units no delivering route names: their drop-ins stay
+ // (reaping keys on declarations), and the pass says so every time.
+ if decls != nil {
+ delivering := map[string]bool{}
+ for _, unit := range units {
+ delivering[unit] = true
+ }
+ for unit, d := range decls.byUnit {
+ if !delivering[unit] {
+ p.idle = append(p.idle, fmt.Sprintf("%s: declared for %s (%s/%s) but no deliverable route names it; nothing delivered and its drop-in stays", unit, d.Host, d.account(), d.App))
+ }
+ }
+ sort.Strings(p.idle)
+ }
if len(units) == 0 {
return p
}
@@ -158,7 +178,7 @@ func planStamped(ctx context.Context, routes []registry.Route, envDir string, op
// watches it; an unmarked file at the path is prepareStamped's
// refusal. A drop-in that cannot be read is refused here too:
// whether the list is ours is then unknown.
- _, exists, marked, err := readDropIn(ops.DropInRoot, unit)
+ _, exists, marked, err := readDropIn(ops.DropInRoot, unit, ops.trustedUID)
if err != nil {
p.refused[host] = fmt.Sprintf("read drop-in for %s: %v", unit, err)
continue
@@ -182,6 +202,7 @@ func planStamped(ctx context.Context, routes []registry.Route, envDir string, op
// reload/restart half to act on.
type unitWork struct {
host string
+ rt registry.Route
// ok: both files converged this pass (changed or unchanged). False
// means a refusal or write failure was printed and this unit may be
// reloaded but must not be restarted this pass. Three states, not two
@@ -196,8 +217,17 @@ type unitWork struct {
// (spec §3.2 step 1): compare both first, write the pending marker before
// any mutation, then the env file, then the drop-in. Returns ok as
// unitWork.ok describes.
-func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing bool, priv *ecdh.PrivateKey, envDir string, ops *UnitOps) unitWork {
- w := unitWork{host: rt.Host}
+func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing bool, priv *ecdh.PrivateKey, envDir string, ops *UnitOps, plan stampedPlan) unitWork {
+ w := unitWork{host: rt.Host, rt: rt}
+ // The decider, again, at the write (invariant A): nothing is rendered
+ // for a route the declaration does not bind to this unit.
+ if plan.decls == nil {
+ return w
+ }
+ if _, err := plan.decls.DeclaredBinding(rt); err != nil || rt.Unit != unit {
+ fmt.Printf(" %s: delivery blocked: not declared: %v\n", rt.Host, err)
+ return w
+ }
hr, _ := prepareHost(rt, m, defaultMissing, priv, envDir)
if hr == nil {
return w
@@ -214,9 +244,9 @@ func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing
// and the bundle is refused, every pass, before anything is written.
// Names only; no value from either layer is read for this or printed.
base := baseEnvPath(ops.BaseEnvDir, unit)
- baseNames, err := envFileNames(base)
+ baseNames, err := envFileNames(ops.BaseEnvDir, base, ops.trustedUID)
if err != nil {
- fmt.Printf(" %s: delivery blocked: read %s: %v; cannot rule out a name owned by both layers\n", rt.Host, base, err)
+ fmt.Printf(" %s: delivery blocked: %s: %v; the base file must be root's, plain NAME=value lines, and readable without following a link\n", rt.Host, base, err)
return w
}
if both := overlappingNames(baseNames, rendered); len(both) > 0 {
@@ -228,9 +258,9 @@ func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing
fmt.Printf(" %s: drop-in directory for %s: %v\n", rt.Host, unit, err)
return w
}
- curDrop, dropExists, marked, err := readDropIn(ops.DropInRoot, unit)
+ curDrop, dropExists, marked, err := readDropIn(ops.DropInRoot, unit, ops.trustedUID)
if err != nil {
- fmt.Printf(" %s: read drop-in for %s: %v\n", rt.Host, unit, err)
+ fmt.Printf(" %s: delivery blocked: read drop-in for %s: %v\n", rt.Host, unit, err)
return w
}
if dropExists && !marked {
@@ -266,30 +296,27 @@ func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing
return w
}
-// reapDropIns (spec §3.2 reaping, step 2): for every marker-bearing drop-in
-// whose unit is named by no route row on the box, record the reload it
-// owes FIRST, then remove the drop-in (codex R3-2). Keyed off the full
-// route list, never the delivered subset; an empty list is never authority
-// to delete anything (the same rule as reap for env files). Unmarked files
-// and symlinked directories are never touched.
-func reapDropIns(routes []registry.Route, ops *UnitOps) {
- if len(routes) == 0 {
+// reapDropIns (spec §3.2 reaping, step 2, as ruled in §12): for every
+// marker-bearing drop-in whose unit NO DECLARATION names any more, record
+// the reload it owes FIRST, then remove the drop-in (codex R3-2). Keyed on
+// the declaration file, never on registry rows: changing, clearing or
+// deleting a row stops delivery and is reported, and removes nothing. A
+// declaration file that could not be read is no authority to remove
+// anything. Unmarked files and symlinked directories are never touched.
+func reapDropIns(plan stampedPlan, ops *UnitOps) {
+ if plan.decls == nil {
+ fmt.Printf(" drop-ins: the declaration file could not be read; nothing reaped this pass\n")
return
}
- named := map[string]bool{}
- for _, rt := range routes {
- if rt.Unit != "" {
- named[rt.Unit] = true
- }
- }
- units, skipped, unreadable := listMarkedDropIns(ops.DropInRoot)
+ units, skipped, unreadable := listMarkedDropIns(ops.DropInRoot, ops.trustedUID)
for _, unit := range skipped {
fmt.Printf(" %s: %s is not a plain directory; not entered\n", unit, dropInDir(ops.DropInRoot, unit))
}
// Unreadable, not skipped: the directory is fine but its drop-in file
- // could not be read (permission denied, a directory where the file
- // should be, ...), so whether it is ours and whether it is marked is
- // unknown — printed and left exactly as it is, never reaped on a guess.
+ // could not be read through rootRead (a symlink, a foreign owner, a
+ // writable mode, a directory where the file should be, ...), so whether
+ // it is ours and whether it is marked is unknown — printed and left
+ // exactly as it is, never reaped on a guess.
unreadableUnits := make([]string, 0, len(unreadable))
for unit := range unreadable {
unreadableUnits = append(unreadableUnits, unit)
@@ -299,7 +326,7 @@ func reapDropIns(routes []registry.Route, ops *UnitOps) {
fmt.Printf(" %s: drop-in unreadable (%v); not reaped\n", unit, unreadable[unit])
}
for _, unit := range units {
- if named[unit] {
+ if plan.decls.declares(unit) {
continue
}
if err := writePending(ops.DropInRoot, unit); err != nil {
@@ -310,7 +337,7 @@ func reapDropIns(routes []registry.Route, ops *UnitOps) {
fmt.Printf(" %s: remove drop-in: %v\n", unit, err)
continue
}
- fmt.Printf(" %s: no route names this unit, removed its drop-in; reload owed\n", unit)
+ fmt.Printf(" %s: no declaration names this unit, removed its drop-in; reload owed\n", unit)
}
}
@@ -331,6 +358,9 @@ func envFilesMatch(got []string, base, bundle string) bool {
// before any restart, and a unit that failed or was refused this pass is
// never restarted however old its marker.
func applyStamped(envDir string, ops *UnitOps, plan stampedPlan, work map[string]unitWork) {
+ for _, line := range plan.idle {
+ fmt.Printf(" %s\n", line)
+ }
pending := listPending(ops.DropInRoot)
if len(pending) > 0 {
if err := ops.Reload(); err != nil {
@@ -344,7 +374,7 @@ func applyStamped(envDir string, ops *UnitOps, plan stampedPlan, work map[string
for _, unit := range pending {
marked[unit] = true
w, prepared := work[unit]
- _, exists, isMarked, err := readDropIn(ops.DropInRoot, unit)
+ _, exists, isMarked, err := readDropIn(ops.DropInRoot, unit, ops.trustedUID)
if err != nil {
fmt.Printf(" %s: read drop-in: %v; restart still owed\n", unit, err)
continue
@@ -382,6 +412,14 @@ func applyStamped(envDir string, ops *UnitOps, plan stampedPlan, work map[string
w.host, unit, states[unit].EnvFiles, base, want)
continue
}
+ // The decider, again, before the restart (invariant A).
+ if plan.decls == nil {
+ continue
+ }
+ if _, err := plan.decls.DeclaredBinding(w.rt); err != nil {
+ fmt.Printf(" %s: restart of %s refused: not declared: %v\n", w.host, unit, err)
+ continue
+ }
if err := ops.Restart(unit); err != nil {
fmt.Printf(" %s: config updated but restart of %s failed: %v; restart still owed\n", w.host, unit, err)
continue
diff --git a/internal/appconfig/unitsync_test.go b/internal/appconfig/unitsync_test.go
index 84c62913b..cf220ad6a 100644
--- a/internal/appconfig/unitsync_test.go
+++ b/internal/appconfig/unitsync_test.go
@@ -17,10 +17,12 @@ import (
// fakeUnits is the UnitOps seam with everything recorded: what was probed,
// reloaded and restarted, and what the probe answers.
type fakeUnits struct {
- root string
- base string
- bound map[string]string // host -> unit root's evidence binds it to
- states map[string]UnitState
+ root string
+ base string
+ decl string // the named-units.json this pass reads
+ states map[string]UnitState
+ // declared accumulates stampDeclared's entries.
+ declared []Declaration
probeErr error
reloadErr error
restartErr map[string]error
@@ -32,12 +34,51 @@ type fakeUnits struct {
func newFakeUnits(t *testing.T) *fakeUnits {
t.Helper()
- return &fakeUnits{root: t.TempDir(), base: t.TempDir(), bound: map[string]string{}, states: map[string]UnitState{}, restartErr: map[string]error{}}
+ return &fakeUnits{root: t.TempDir(), base: t.TempDir(), decl: filepath.Join(t.TempDir(), "named-units.json"), 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 }
+// declare writes the declaration file as root would at provisioning, in
+// the shape the release path reads (internal/host/proofnamed.go): one
+// entry per host/account/app/unit, with the fields this reader ignores
+// (addr, health) present on the first so the shape is the one on main.
+func (f *fakeUnits) declare(t *testing.T, entries ...Declaration) {
+ t.Helper()
+ f.declRaw(t, declarationsJSON(entries...))
+}
+
+func declarationsJSON(entries ...Declaration) string {
+ var b strings.Builder
+ b.WriteString(`{"schema":1,"units":[`)
+ for i, e := range entries {
+ if i > 0 {
+ b.WriteString(",")
+ }
+ fmt.Fprintf(&b, `{"host":%q,"app":%q,"unit":%q`, e.Host, e.App, e.Unit)
+ if e.Account != "" {
+ fmt.Fprintf(&b, `,"account":%q`, e.Account)
+ }
+ if i == 0 {
+ b.WriteString(`,"addr":"127.0.0.1:8451","health":{"path":"/ready"}`)
+ }
+ b.WriteString("}")
+ }
+ b.WriteString("]}")
+ return b.String()
+}
+
+func (f *fakeUnits) declRaw(t *testing.T, body string) {
+ t.Helper()
+ if err := os.WriteFile(f.decl, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (f *fakeUnits) undeclare(t *testing.T) {
+ t.Helper()
+ if err := os.Remove(f.decl); err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+}
// 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
@@ -56,16 +97,10 @@ func (f *fakeUnits) writeBase(t *testing.T, unit, body string) {
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
- },
+ DropInRoot: f.root,
+ BaseEnvDir: f.base,
+ NamedUnitsPath: f.decl,
+ trustedUID: os.Getuid(),
Lock: func() (func(), error) {
if f.lockErr != nil {
return nil, f.lockErr
@@ -129,13 +164,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)) {
+// stampDeclared upserts a stamped route AND declares it (bab/relay), the
+// state every delivery test needs; a test of the declaration itself uses
+// upsertStamped alone. Each call rewrites the declaration file with every
+// host declared so far.
+func stampDeclared(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)
+ f.declared = append(f.declared, Declaration{Host: host, Account: "bab", App: "relay", Unit: unit})
+ f.declare(t, f.declared...)
}
func noHostRestart(t *testing.T) func(string) error {
@@ -149,7 +186,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"}
- stampBound(t, f, reg, "relay.example.com", "relay.service", nil)
+ stampDeclared(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)
@@ -158,7 +195,7 @@ func TestSyncUnitsPreparesAStampedRoute(t *testing.T) {
if err != nil || string(got) != "LOG_LEVEL=debug\nCARLOS_PURGE=header\n" {
t.Fatalf("env file = %q, %v", got, err)
}
- cur, exists, marked, _ := readDropIn(f.root, "relay.service")
+ cur, exists, marked, _ := readDropIn(f.root, "relay.service", os.Getuid())
if !exists || !marked || string(cur) != string(renderDropIn(envDir, f.base, "relay.service", "relay.example.com")) {
t.Fatalf("drop-in exists=%v marked=%v body=%q", exists, marked, cur)
}
@@ -187,7 +224,7 @@ func TestSyncUnitsDoesNothingWithoutTheLock(t *testing.T) {
ctx, s, reg, envDir, priv := unitKit(t)
f := newFakeUnits(t)
f.lockErr = errors.New("held elsewhere")
- stampBound(t, f, reg, "relay.example.com", "relay.service", nil)
+ stampDeclared(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)
@@ -210,12 +247,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"}
- 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)
+ stampDeclared(t, f, reg, "sock.example.com", "sock.service", func(r *registry.Route) { r.Socket = "/run/x.sock"; r.Addr = "" })
+ stampDeclared(t, f, reg, "hib.example.com", "hib.service", func(r *registry.Route) { r.Hibernate = true })
+ stampDeclared(t, f, reg, "tmpl.example.com", "carlos-app@.service", nil)
+ stampDeclared(t, f, reg, "pref.example.com", "carlos-.service", nil)
+ stampDeclared(t, f, reg, "alias.example.com", "alias.service", nil)
+ stampDeclared(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 {
@@ -245,8 +282,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"}
- stampBound(t, f, reg, "a.example.com", "relay.service", nil)
- stampBound(t, f, reg, "b.example.com", "relay.service", nil)
+ stampDeclared(t, f, reg, "a.example.com", "relay.service", nil)
+ stampDeclared(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)
@@ -264,7 +301,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"}
- stampBound(t, f, reg, "relay.example.com", "relay.service", nil)
+ stampDeclared(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)
@@ -273,7 +310,7 @@ func TestSyncUnitsRefusesAnUnmarkedDropIn(t *testing.T) {
t.Fatalf("SyncUnits: %v", err)
}
})
- cur, _, _, _ := readDropIn(f.root, "relay.service")
+ cur, _, _, _ := readDropIn(f.root, "relay.service", os.Getuid())
if string(cur) != string(foreign) {
t.Fatal("an unmarked file must never be replaced")
}
@@ -289,7 +326,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"}
- stampBound(t, f, reg, "relay.example.com", "relay.service", nil)
+ stampDeclared(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")
@@ -345,7 +382,7 @@ func TestSyncUnitsReloadsVerifiesRestartsAndClears(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)
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
syncOnce(t, ctx, reg, s, priv, envDir, f)
if f.reloads != 1 {
@@ -383,7 +420,7 @@ func TestSyncUnitsReloadFailureKeepsMarkerAndRetries(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)
+ stampDeclared(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") {
@@ -400,7 +437,7 @@ func TestSyncUnitsRestartFailureKeepsMarkerAndRetries(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)
+ stampDeclared(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") {
@@ -418,7 +455,7 @@ func TestSyncUnitsVerificationMismatchBlocks(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)
+ stampDeclared(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
@@ -442,7 +479,7 @@ func TestSyncUnitsDriftIsReportedEveryPassAndNeverRestarted(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)
+ stampDeclared(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.
@@ -463,12 +500,12 @@ func TestSyncUnitsRefusedRouteKeepsAnEarlierMarker(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)
+ stampDeclared(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).
- stampBound(t, f, reg, "b.example.com", "relay.service", nil)
+ stampDeclared(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"))
@@ -479,7 +516,7 @@ func TestSyncUnitsUnreadableDropInKeepsMarker(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)
+ stampDeclared(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
@@ -500,7 +537,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.
- stampBound(t, f, reg, "b.example.com", "relay.service", nil)
+ stampDeclared(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"))
@@ -510,27 +547,55 @@ func TestSyncUnitsUnreadableDropInKeepsMarker(t *testing.T) {
}
}
-func TestSyncUnitsReapsDropInForAnUnstampedRouteWithMarkerFirst(t *testing.T) {
+// Invariant A, reaping: a drop-in is removed only when no declaration
+// names its unit any more, with the reload owed recorded first (codex
+// R3-2). Clearing the registry stamp, or deleting the row, stops delivery
+// with a reason and removes nothing.
+func TestSyncUnitsReapsOnlyWhenTheDeclarationGoes(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)
+ stampDeclared(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.
+ f.reloads, f.restarted = 0, nil
+
+ // Clear the stamp: the drop-in stays, nothing reloads, the pass says
+ // the declared unit has no deliverable route.
if err := reg.SetUnit("relay.example.com", ""); err != nil {
t.Fatal(err)
}
- f.reloads, f.restarted = 0, nil
+ out := syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if _, exists, marked, _ := readDropIn(f.root, "relay.service", os.Getuid()); !exists || !marked {
+ t.Fatal("clearing the registry stamp removed a declared unit's drop-in")
+ }
+ if f.reloads != 0 || len(f.restarted) != 0 || hasPending(f.root, "relay.service") {
+ t.Fatalf("clearing the stamp: reloads=%d restarted=%v pending=%v", f.reloads, f.restarted, hasPending(f.root, "relay.service"))
+ }
+ if !strings.Contains(out, "relay.service") || !strings.Contains(out, "drop-in stays") {
+ t.Fatalf("expected the declared-but-unrouted line, got %q", out)
+ }
+ // Delete the row: the same.
+ if err := reg.Delete("relay.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ out = syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if _, exists, _, _ := readDropIn(f.root, "relay.service", os.Getuid()); !exists || f.reloads != 0 || !strings.Contains(out, "drop-in stays") {
+ t.Fatalf("deleting the row: exists=%v reloads=%d out=%q", exists, f.reloads, out)
+ }
+
+ // Remove the declaration: reaped, marker first, reload owed; a failed
+ // reload keeps the marker; a good one clears it without a restart.
+ f.undeclare(t)
f.reloadErr = errors.New("busy")
syncOnce(t, ctx, reg, s, priv, envDir, f)
- if _, exists, _, _ := readDropIn(f.root, "relay.service"); exists {
- t.Fatal("drop-in must be removed for a unit no route names")
+ if _, exists, _, _ := readDropIn(f.root, "relay.service", os.Getuid()); exists {
+ t.Fatal("drop-in must be removed once no declaration names the unit")
}
if !hasPending(f.root, "relay.service") {
t.Fatal("the reload owed must be recorded when the reload fails")
}
if len(f.restarted) != 0 {
- t.Fatal("an unowned unit is never restarted")
+ t.Fatal("an undeclared unit is never restarted")
}
f.reloadErr = nil
syncOnce(t, ctx, reg, s, priv, envDir, f)
@@ -540,9 +605,19 @@ func TestSyncUnitsReapsDropInForAnUnstampedRouteWithMarkerFirst(t *testing.T) {
if _, err := os.Stat(dropInDir(f.root, "relay.service")); err != nil {
t.Fatal("the directory is never removed")
}
- // The env file stays while the row exists (today's reap policy).
- if _, err := os.Stat(filepath.Join(envDir, "relay.example.com.env")); err != nil {
- t.Fatal("env file must stay while the route row exists")
+}
+
+// A declaration file that cannot be read is no authority to remove
+// anything.
+func TestSyncUnitsUnreadableDeclarationsReapNothing(t *testing.T) {
+ ctx, s, reg, envDir, priv := unitKit(t)
+ f := newFakeUnits(t)
+ ensureDropInDir(f.root, "relay.service")
+ writeDropIn(f.root, "relay.service", renderDropIn(envDir, f.base, "relay.service", "relay.example.com"))
+ f.declRaw(t, "not json")
+ out := syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if _, exists, _, _ := readDropIn(f.root, "relay.service", os.Getuid()); !exists || !strings.Contains(out, "nothing reaped") {
+ t.Fatalf("exists=%v out=%q", exists, out)
}
}
@@ -563,7 +638,7 @@ func TestSyncUnitsReaperNeverRemovesUnmarkedOrSymlinked(t *testing.T) {
if err := SyncUnits(ctx, reg, s, priv, envDir, func(string) error { return nil }, nil, f.ops()); err != nil {
t.Fatal(err)
}
- if cur, _, _, _ := readDropIn(f.root, "foreign.service"); string(cur) != string(foreign) {
+ if cur, _, _, _ := readDropIn(f.root, "foreign.service", os.Getuid()); string(cur) != string(foreign) {
t.Fatal("unmarked file touched")
}
if _, err := os.Stat(filepath.Join(elsewhere, DropInFile)); err != nil {
@@ -574,16 +649,17 @@ func TestSyncUnitsReaperNeverRemovesUnmarkedOrSymlinked(t *testing.T) {
}
}
-func TestSyncUnitsEmptyRegistryReapsNoDropIns(t *testing.T) {
+func TestSyncUnitsEmptyRegistryReapsNoDeclaredDropIn(t *testing.T) {
ctx, s, reg, envDir, priv := unitKit(t)
f := newFakeUnits(t)
ensureDropInDir(f.root, "relay.service")
writeDropIn(f.root, "relay.service", renderDropIn(envDir, f.base, "relay.service", "relay.example.com"))
+ f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "relay.service"})
if err := SyncUnits(ctx, reg, s, priv, envDir, func(string) error { return nil }, nil, f.ops()); err != nil {
t.Fatal(err)
}
- if _, exists, _, _ := readDropIn(f.root, "relay.service"); !exists {
- t.Fatal("an empty route list is never authority to delete")
+ if _, exists, _, _ := readDropIn(f.root, "relay.service", os.Getuid()); !exists {
+ t.Fatal("a declared unit's drop-in stays whatever the registry says")
}
}
@@ -592,24 +668,32 @@ func TestSyncUnitsReStampMovesTheDropIn(t *testing.T) {
f := newFakeUnits(t)
f.loaded("a.service", envDir, "relay.example.com")
f.loaded("b.service", envDir, "relay.example.com")
- stampBound(t, f, reg, "relay.example.com", "a.service", nil)
+ stampDeclared(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.
+ // A re-stamp needs a declaration too (invariant A): the row alone is
+ // refused, the OLD unit's drop-in survives (round 2 P1-2), and nothing
+ // reloads.
+ f.reloads = 0
out := syncOnce(t, ctx, reg, s, priv, envDir, f)
- if _, exists, _, _ := readDropIn(f.root, "b.service"); exists || !strings.Contains(out, "registry row alone") {
+ if _, exists, _, _ := readDropIn(f.root, "b.service", os.Getuid()); 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")
+ if _, exists, marked, _ := readDropIn(f.root, "a.service", os.Getuid()); !exists || !marked {
+ t.Fatal("a refused re-stamp removed the old unit's drop-in")
+ }
+ if f.reloads != 0 || hasPending(f.root, "a.service") {
+ t.Fatalf("a refused re-stamp reloaded: reloads=%d pending=%v", f.reloads, hasPending(f.root, "a.service"))
+ }
+ f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "b.service"})
f.restarted = nil
syncOnce(t, ctx, reg, s, priv, envDir, f)
- if _, exists, _, _ := readDropIn(f.root, "a.service"); exists {
+ if _, exists, _, _ := readDropIn(f.root, "a.service", os.Getuid()); exists {
t.Fatal("old unit's drop-in must be reaped")
}
- if _, exists, marked, _ := readDropIn(f.root, "b.service"); !exists || !marked {
+ if _, exists, marked, _ := readDropIn(f.root, "b.service", os.Getuid()); !exists || !marked {
t.Fatal("new unit's drop-in must be written")
}
if len(f.restarted) != 1 || f.restarted[0] != "b.service" {
@@ -648,7 +732,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")}}
- stampBound(t, f, reg, "console.example.com", "console.service", nil)
+ stampDeclared(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") {
@@ -673,7 +757,7 @@ func TestSyncUnitsRefusesToResetAnUnmanagedEnvFileAway(t *testing.T) {
f.writeBase(t, "console.service", "CONSOLE_DB=/data/console.db\n")
f.loaded("console.service", envDir, "console.example.com")
syncOnce(t, ctx, reg, s, priv, envDir, f)
- if _, exists, marked, _ := readDropIn(f.root, "console.service"); !exists || !marked {
+ if _, exists, marked, _ := readDropIn(f.root, "console.service", os.Getuid()); !exists || !marked {
t.Fatal("drop-in not written once the unit loads only managed files")
}
if len(f.restarted) != 1 || f.restarted[0] != "console.service" || hasPending(f.root, "console.service") {
@@ -689,11 +773,11 @@ 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"}
- stampBound(t, f, reg, "a.example.com", "a.service", nil)
- stampBound(t, f, reg, "b.example.com", "b.service", nil)
+ stampDeclared(t, f, reg, "a.example.com", "a.service", nil)
+ stampDeclared(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 {
+ if _, exists, marked, _ := readDropIn(f.root, unit, os.Getuid()); !exists || !marked {
t.Fatalf("%s: drop-in not written for a unit loading only managed paths", unit)
}
}
@@ -708,12 +792,12 @@ func TestSyncUnitsDropInListsBaseBeforeBundle(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)
+ stampDeclared(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)
}
syncOnce(t, ctx, reg, s, priv, envDir, f)
- cur, exists, marked, _ := readDropIn(f.root, "relay.service")
+ cur, exists, marked, _ := readDropIn(f.root, "relay.service", os.Getuid())
if !exists || !marked {
t.Fatal("drop-in not written")
}
@@ -757,8 +841,8 @@ func TestSyncUnitsRefusesANameInBothLayers(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", "# provisioned\nCARLOS_DEPLOYMENT_BUCKET=bkt-value\n LOG_LEVEL = base-value\n;x\n")
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
+ f.writeBase(t, "relay.service", "# provisioned\nCARLOS_DEPLOYMENT_BUCKET=bkt-value\n\nLOG_LEVEL=base-value\n")
for pass := 1; pass <= 2; pass++ {
out := syncOnce(t, ctx, reg, s, priv, envDir, f)
if !strings.Contains(out, "relay.example.com") || !strings.Contains(out, "blocked") || !strings.Contains(out, "LOG_LEVEL") {
@@ -773,7 +857,7 @@ func TestSyncUnitsRefusesANameInBothLayers(t *testing.T) {
if ents, _ := os.ReadDir(envDir); len(ents) != 0 {
t.Fatalf("pass %d: blocked route rendered %v", pass, ents)
}
- if _, exists, _, _ := readDropIn(f.root, "relay.service"); exists || hasPending(f.root, "relay.service") {
+ if _, exists, _, _ := readDropIn(f.root, "relay.service", os.Getuid()); exists || hasPending(f.root, "relay.service") {
t.Fatalf("pass %d: blocked route wrote a drop-in or a marker", pass)
}
if f.reloads != 0 || len(f.restarted) != 0 {
@@ -804,7 +888,7 @@ func TestSyncUnitsRefusesAnUnreadableBaseFile(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)
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
if err := os.Mkdir(baseEnvPath(f.base, "relay.service"), 0o755); err != nil {
t.Fatal(err)
}
@@ -826,7 +910,7 @@ func TestSyncUnitsUnitBackedRowWithAStampStaysOnTheCarlosAppPath(t *testing.T) {
ctx, s, reg, envDir, priv := unitKit(t)
f := newFakeUnits(t)
f.loaded("console.service", envDir, "console.example.com")
- stampBound(t, f, reg, "console.example.com", "console.service", func(r *registry.Route) { r.Backing = registry.BackingUnit })
+ stampDeclared(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)
@@ -845,21 +929,34 @@ func TestSyncUnitsUnitBackedRowWithAStampStaysOnTheCarlosAppPath(t *testing.T) {
}
}
-// 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.
+// TestSyncUnitsRefusesAStampRootCannotBind is invariant A's witness
+// (#114 spec §12, Paul's ruling): the registry is the service user's, so a
+// row alone never authorises delivery to the unit it names. With only the
+// registry row, with a declaration for another unit, host, app or account,
+// with an unreadable declaration file, and with no declaration path 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 }},
+ {"declared for another unit", func(f *fakeUnits, _ *UnitOps) {
+ f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "other.service"})
+ }},
+ {"declared for another host", func(f *fakeUnits, _ *UnitOps) {
+ f.declare(t, Declaration{Host: "other.example.com", Account: "bab", App: "relay", Unit: "relay.service"})
+ }},
+ {"declared for another app", func(f *fakeUnits, _ *UnitOps) {
+ f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "shop", Unit: "relay.service"})
+ }},
+ {"declared for another account", func(f *fakeUnits, _ *UnitOps) {
+ f.declare(t, Declaration{Host: "relay.example.com", Account: "bae", App: "relay", Unit: "relay.service"})
+ }},
+ {"declaration file unreadable", func(f *fakeUnits, _ *UnitOps) { f.declRaw(t, "{") }},
+ {"no declaration path on this pass", func(_ *fakeUnits, ops *UnitOps) { ops.NamedUnitsPath = "" }},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, s, reg, envDir, priv := unitKit(t)
@@ -891,7 +988,7 @@ func TestSyncUnitsRefusesAStampRootCannotBind(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)
+ stampDeclared(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"))
@@ -907,7 +1004,7 @@ 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)
+ stampDeclared(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.
@@ -941,27 +1038,141 @@ func TestSyncUnitsRefusesACarriageReturnInAValue(t *testing.T) {
}
}
-// 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)
+// Invariant A: the registry selects, it never authorises. A row whose
+// account or app differs from the declaration's, with the host and unit
+// unchanged, is refused with nothing written and nothing reloaded.
+func TestSyncUnitsRefusesARegistryAccountOrAppSwap(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ mut func(*registry.Route)
+ }{
+ {"app", func(r *registry.Route) { r.App = "shop" }},
+ {"account", func(r *registry.Route) { r.Account = "bae" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx, s, reg, envDir, priv := unitKit(t)
+ if err := SetEnv(ctx, s, "bab", "shop", map[string]string{"STOLEN": "x"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetEnv(ctx, s, "bae", "relay", map[string]string{"STOLEN": "x"}); err != nil {
+ t.Fatal(err)
+ }
+ f := newFakeUnits(t)
+ f.loaded("relay.service", envDir, "relay.example.com")
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
+ syncOnce(t, ctx, reg, s, priv, envDir, f) // delivered as declared
+ before, _ := os.ReadFile(filepath.Join(envDir, "relay.example.com.env"))
+ f.reloads, f.restarted, f.probed = 0, nil, nil
+ upsertStamped(t, reg, "relay.example.com", "relay.service", tc.mut)
+ out := syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if !strings.Contains(out, "blocked") || !strings.Contains(out, "not declared") {
+ t.Fatalf("expected a not-declared refusal, got %q", out)
+ }
+ after, _ := os.ReadFile(filepath.Join(envDir, "relay.example.com.env"))
+ if string(after) != string(before) || strings.Contains(string(after), "STOLEN") {
+ t.Fatalf("env file changed on a swapped row: %q", after)
+ }
+ if f.reloads != 0 || len(f.restarted) != 0 || len(f.probed) != 0 || hasPending(f.root, "relay.service") {
+ t.Fatalf("swapped row touched the unit: reloads=%d restarted=%v probed=%v", f.reloads, f.restarted, f.probed)
+ }
+ if _, exists, marked, _ := readDropIn(f.root, "relay.service", os.Getuid()); !exists || !marked {
+ t.Fatal("the declared unit's drop-in must survive a swapped row")
+ }
+ })
+ }
+}
+
+// Invariant C: a symlinked base file, a symlinked drop-in and a
+// group-writable base file each block the unit, through the real pass.
+func TestSyncUnitsRefusesFilesTheOneReaderRefuses(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ arm func(t *testing.T, f *fakeUnits, envDir string)
+ want string
+ }{
+ {"symlinked base file", func(t *testing.T, f *fakeUnits, _ string) {
+ target := filepath.Join(t.TempDir(), "elsewhere.env")
+ os.WriteFile(target, []byte("A=1\n"), 0o600)
+ os.Symlink(target, baseEnvPath(f.base, "relay.service"))
+ }, "symlink"},
+ {"group-writable base file", func(t *testing.T, f *fakeUnits, _ string) {
+ os.WriteFile(baseEnvPath(f.base, "relay.service"), []byte("A=1\n"), 0o664)
+ }, "writable"},
+ {"symlinked drop-in", func(t *testing.T, f *fakeUnits, envDir string) {
+ target := filepath.Join(t.TempDir(), "zz.conf")
+ os.WriteFile(target, renderDropIn(envDir, f.base, "relay.service", "relay.example.com"), 0o644)
+ ensureDropInDir(f.root, "relay.service")
+ os.Symlink(target, filepath.Join(dropInDir(f.root, "relay.service"), DropInFile))
+ }, "symlink"},
+ } {
+ 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")
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
+ tc.arm(t, f, envDir)
+ out := syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if !strings.Contains(out, "blocked") || !strings.Contains(out, tc.want) {
+ t.Fatalf("expected a blocked line mentioning %q, got %q", tc.want, out)
+ }
+ if ents, _ := os.ReadDir(envDir); len(ents) != 0 {
+ t.Fatalf("rendered %v", ents)
+ }
+ if len(f.restarted) != 0 || f.reloads != 0 {
+ t.Fatalf("restarted=%v reloads=%d", f.restarted, f.reloads)
+ }
+ })
+ }
+}
+
+// Invariant B through the real pass: each forbidden base-file construct
+// blocks delivery, round 2's backslash-continued comment among them.
+func TestSyncUnitsRefusesABaseFileOutsideTheGrammar(t *testing.T) {
+ for name, body := range map[string]string{
+ "comment continued by a backslash": "# comment\\\nCONSOLE_DB=/data/base.db\n",
+ "export prefix": "export CONSOLE_DB=/data/base.db\n",
+ "quoted value": "CONSOLE_DB=\"/data/base.db\"\n",
+ "CR line ending": "CONSOLE_DB=/data/base.db\r\n",
+ "NUL": "CONSOLE_DB=/data\x00/base.db\n",
+ "invalid UTF-8": "CONSOLE_DB=/data/\xff\n",
+ } {
+ t.Run(name, func(t *testing.T) {
+ ctx, s, reg, envDir, priv := unitKit(t)
+ f := newFakeUnits(t)
+ f.loaded("relay.service", envDir, "relay.example.com")
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
+ f.writeBase(t, "relay.service", body)
+ out := syncOnce(t, ctx, reg, s, priv, envDir, f)
+ if !strings.Contains(out, "blocked") || strings.Contains(out, "/data/base.db") {
+ t.Fatalf("want a blocked line without the content, got %q", out)
+ }
+ if ents, _ := os.ReadDir(envDir); len(ents) != 0 || len(f.restarted) != 0 {
+ t.Fatalf("rendered=%v restarted=%v", ents, f.restarted)
+ }
+ })
+ }
+}
+
+// Invariant A reads one local file: a declared delivery reads only the
+// app's own keys in the bucket, never an account or record listing.
+func TestSyncUnitsDeclarationAddsNoBucketReads(t *testing.T) {
+ ctx, base, 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 {
+ stampDeclared(t, f, reg, "relay.example.com", "relay.service", nil)
+ s := &keyReadStore{Store: base}
+ if err := SyncUnits(ctx, reg, s, priv, envDir, noHostRestart(t), nil, f.ops()); 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)
+ if len(f.restarted) != 1 {
+ t.Fatalf("restarted = %v, want the declared unit", f.restarted)
+ }
+ for _, k := range s.read {
+ if !strings.HasPrefix(k, "apps/bab/relay/") {
+ t.Errorf("the pass read %s, outside the app's own keys", k)
+ }
+ }
+ if len(s.read) == 0 {
+ t.Fatal("the witness pinned nothing")
}
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index b54f69042..c03e81537 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, restartChecks.resolve), claims.Writes); err != nil {
+ } else if err := appconfig.SyncUnits(ctx, reg, store, secretsPriv, appconfig.DefaultEnvDir, restart, configAckFunc(ctx, store, "adopt"), productionUnitOps(appconfig.DefaultEnvDir), claims.Writes); err != nil {
log.Printf("adopt: config sync: %v", err)
}
}
diff --git a/internal/host/unitops.go b/internal/host/unitops.go
index 20f40434d..c892ea0a6 100644
--- a/internal/host/unitops.go
+++ b/internal/host/unitops.go
@@ -6,8 +6,6 @@ package host
import (
"bytes"
- "context"
- "errors"
"fmt"
"log"
"os"
@@ -15,47 +13,25 @@ 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"
-// 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 {
+// productionUnitOps: the declaration file is the one the release path
+// reads (rootNamedUnits); here it is the only authority for config
+// delivery (invariant A, appconfig/declarations.go). No proof binding and
+// no bucket read: the decider is appconfig's, over one root-read file.
+func productionUnitOps(envDir string) *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
+ DropInRoot: dropInRoot,
+ BaseEnvDir: appconfig.DefaultUnitBaseDir,
+ NamedUnitsPath: appconfig.DefaultNamedUnitsPath,
+ Lock: func() (func(), error) { return lockConfigSync(envDir + "/.sync") },
+ Probe: probeUnits,
+ Reload: daemonReload,
+ Restart: systemctlRestartUnit,
}
}
diff --git a/internal/host/unitops_test.go b/internal/host/unitops_test.go
index a71cec171..27c6452c1 100644
--- a/internal/host/unitops_test.go
+++ b/internal/host/unitops_test.go
@@ -1,12 +1,8 @@
package host
import (
- "context"
- "errors"
"strings"
"testing"
-
- "github.com/carlosframework/platform/internal/registry"
)
func TestParseSystemctlShowBatched(t *testing.T) {
@@ -55,38 +51,16 @@ 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", nil)
+ ops := productionUnitOps("/etc/carlos/apps")
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")
+// Invariant A reads one file, and it is the file the release path reads.
+func TestProductionUnitOpsDeclarationIsTheReleasePathsFile(t *testing.T) {
+ ops := productionUnitOps("/etc/carlos/apps")
+ if ops.NamedUnitsPath != rootNamedUnits || rootNamedUnits != "/etc/carlos/named-units.json" {
+ t.Fatalf("NamedUnitsPath = %q, want %q", ops.NamedUnitsPath, rootNamedUnits)
}
}