Named-unit delivery round 4: every gap closed by a refusal up front (declared hosts gated before either writer, env reaping keyed on declarations, the declaration re-read before each mutation, ASCII-only base file, the release path's trusted walk for every read and the drop-in directory, EOF after the declaration)
Paul's one extra round, each gap closed by refusing it up front. 1. A declared host is written ONLY through its declaration's own stamp (stampedPlan.declaredHostRefusal, unitsync.go). Before any bundle is read for it and before either writer, a row for a declared host that is not a deliverable stamp bound by DeclaredBinding (unit backing, a cleared stamp, another unit, account or app) is refused with the reason and its env file left untouched. With the declaration file unreadable nothing is delivered to any host and nothing reaped (which hosts are declared is then unknown); stamped rows still print their own refusal. 2. The env-file reaper keeps every declared host (reap's declared set) and reaps nothing when the declarations cannot be read or changed since planning. 3. declGuard (declarations.go): the declaration file is re-read through the trusted reader and a sha256 of its bytes compared with planning's before each mutation: the pending marker, the env write, the drop-in write, each drop-in removal, the daemon-reload, each restart, the env reap. A difference or a failed read abandons the rest of the pass; the next pass plans afresh. 4. The base file is printable ASCII (0x20-0x7E) and LF only: no tab, no CR, no NUL, no Unicode, since systemd rejects a whole file over a noncharacter and the unit would start without it. Refused with the line number; the grammar cases stay. 5. rootstate gains OpenTrustedDirFrom and OpenTrustedFileFrom: Open's descriptor walk (descend) anchored at a caller-held directory whose owner is the trusted owner, every component O_NOFOLLOW|O_DIRECTORY and trusted() (owner, type, no group/other write), the file a one-link regular file with the same checks, read from its descriptor. Production anchors at "/" (UnitOps.trustedRoot empty), the chain OpenTrustedFile walks; the fixture anchors at a 0755 directory it owns. OpenTrustedFile could not express a faked filesystem root (its owner is fixed at uid 0), which is the one thing the witnesses needed; the walk itself is reused, not re-rolled. appconfig's rootRead and trustedDir are thin wrappers; ensureDropInDir vets the drop-in directory through the same walk before any write. The hand-rolled walker (rootread_unix.go) is deleted; the !linux stub keeps the cross-compiles. 6. The declaration must be one JSON document with nothing after it, as the release path reads it; trailing bytes or a second document mean no delivery and no reaping. Witnesses through the real SyncUnits: TestSyncUnitsRefusesABackingChangeOnADeclaredHost, TestSyncUnitsKeepsADeclaredHostsEnvFileWhenItsRowGoes (declared, and declarations unreadable), TestSyncUnitsAbortsWhenTheDeclarationChangesMidPass (after the first probe; before the restart), TestSyncUnitsRefusesANonASCIIBaseFile (U+FDD0, U+FFFF, U+FFFE, tab, a non-ASCII letter) plus the grammar cases, TestSyncUnitsRefusesUntrustedDirectories (writable base directory, symlinked ancestor, writable drop-in directory), TestSyncUnitsRefusesTrailingBytesInTheDeclaration. A unit-backed row with a stamp stays on main's carlos-app@ path only for an undeclared host. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Summary
Round 4 of named-unit delivery: declared hosts are gated before either writer, env reaping and reaping authority follow the declaration file, the declaration is re-read before every mutation, the base file is ASCII-only, every trusted read and the drop-in directory use rootstate's descriptor walk anchored at /, and the declaration must end at its JSON document.
15 files changed,
+750
−208
docs/site/cli.md+3 −1docs/superpowers/specs/2026-09-07-named-unit-config-delivery-design.md+19 −1internal/appconfig/baseenv.go+20 −23internal/appconfig/baseenv_test.go+18 −3internal/appconfig/declarations.go+69 −8internal/appconfig/dropin.go+14 −9internal/appconfig/dropin_test.go+19 −12internal/appconfig/rootread.go+81 −0internal/appconfig/rootread_other.go+0 −16internal/appconfig/rootread_unix.go+0 −93internal/appconfig/sync.go+55 −3internal/appconfig/unitsync.go+71 −13internal/appconfig/unitsync_test.go+313 −26internal/rootstate/file_linux.go+64 −0internal/rootstate/file_other.go+4 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 64598fbb4..d2990059f 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2174,7 +2174,9 @@ with the route's host, account and app, never from the route row alone: |
| ``` |
| 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 |
| +the route only stops delivery. The box's own file for the unit, |
| +`/etc/carlos/units/<unit>.base.env`, must be plain ASCII `NAME=value` |
| +lines and `#` comments. 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 1d91941bd..e674c4842 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 |
| @@ -910,7 +910,25 @@ Consequence for the fleet: each stamped unit needs one declaration line |
| ``` |
| `addr` and `health` are the release path's fields and are not read for |
| -delivery. Round 3 is the last review round. |
| +delivery. |
| + |
| +**Round 4 (Paul's one extra round, 2026-10-28), each gap closed by a |
| +refusal up front:** a host a declaration names is written only through |
| +that declaration's own stamp, so a row with unit backing, a cleared stamp |
| +or another unit, account or app is refused before either writer and its |
| +env file left untouched (`stampedPlan.declaredHostRefusal`); the env-file |
| +reaper keeps every declared host and reaps nothing when the declarations |
| +cannot be read; the declaration file is re-read through the trusted reader |
| +and its digest compared before every mutation (env write, drop-in write or |
| +removal, daemon-reload, restart, reap), and a change abandons the rest of |
| +the pass (`declGuard`); the base file is printable ASCII and LF only (no |
| +tab, no Unicode at all), since systemd rejects a whole file over a |
| +noncharacter; every trusted read and the drop-in directory go through |
| +`rootstate.OpenTrustedFileFrom` / `OpenTrustedDirFrom`, the release path's |
| +descriptor walk anchored at `/` (every ancestor root-owned, not group- or |
| +other-writable, no symlink), so a writable parent, a symlinked ancestor or |
| +a writable drop-in directory blocks the unit; and the declaration must be |
| +one JSON document with nothing after it, as the release path reads it. |
| Tests (console config design §11, first three bullets) run through the |
| real `SyncUnits` with the faked `UnitOps`: |
diff --git a/internal/appconfig/baseenv.go b/internal/appconfig/baseenv.go| index 1f9957598..33d1b1800 100644 |
| --- a/internal/appconfig/baseenv.go |
| +++ b/internal/appconfig/baseenv.go |
| @@ -11,14 +11,11 @@ |
| package appconfig |
| import ( |
| - "bytes" |
| - "errors" |
| "fmt" |
| "path/filepath" |
| "regexp" |
| "sort" |
| "strings" |
| - "unicode/utf8" |
| ) |
| // DefaultUnitBaseDir is where a stamped unit's base file lives in |
| @@ -30,10 +27,6 @@ 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 |
| @@ -64,8 +57,8 @@ 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) |
| +func envFileNames(ops *UnitOps, path string) ([]string, error) { |
| + raw, err := rootRead(ops, path) |
| if err != nil { |
| if err == errNoFile { |
| return nil, nil |
| @@ -75,24 +68,28 @@ func envFileNames(baseDir, path string, trustedUID int) ([]string, error) { |
| return baseFileNames(raw) |
| } |
| -// 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. |
| +// baseFileNames is the grammar: printable ASCII only, every byte 0x20 to |
| +// 0x7E or LF as the line terminator (no tab, no CR, no NUL, nothing above |
| +// 0x7E, so no Unicode at all; round 3 P1-4: systemd rejects a whole file |
| +// over a noncharacter and the unit would start without its base file), 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) |
| } |
| - 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") |
| + line := 1 |
| + for _, c := range raw { |
| + if c == '\n' { |
| + line++ |
| + continue |
| + } |
| + if c < 0x20 || c > 0x7e { |
| + return nil, fmt.Errorf("line %d holds a byte that is not printable ASCII (0x%02x); the base file is printable ASCII and LF only", line, c) |
| + } |
| } |
| var names []string |
| for i, line := range strings.Split(string(raw), "\n") { |
diff --git a/internal/appconfig/baseenv_test.go b/internal/appconfig/baseenv_test.go| index 46fc54b38..f4cc59f48 100644 |
| --- a/internal/appconfig/baseenv_test.go |
| +++ b/internal/appconfig/baseenv_test.go |
| @@ -10,22 +10,25 @@ import ( |
| func TestEnvFileNamesReadsNamesOnly(t *testing.T) { |
| dir := t.TempDir() |
| + if err := os.Chmod(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| path := baseEnvPath(dir, "console.service") |
| - if names, err := envFileNames(dir, path, os.Getuid()); err != nil || names != nil { |
| + if names, err := envFileNames(&UnitOps{BaseEnvDir: dir, trustedRoot: dir}, path); 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\nCARLOS_REGISTRY=/data/registry.db\nEMPTY=\n" |
| if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| t.Fatal(err) |
| } |
| - names, err := envFileNames(dir, path, os.Getuid()) |
| + names, err := envFileNames(&UnitOps{BaseEnvDir: dir, trustedRoot: dir}, path) |
| 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(dir, baseEnvPath(dir, "dir.service"), os.Getuid()); err == nil { |
| + if _, err := envFileNames(&UnitOps{BaseEnvDir: dir, trustedRoot: dir}, baseEnvPath(dir, "dir.service")); err == nil { |
| t.Fatal("a base file that cannot be read must be an error, not an empty list") |
| } |
| } |
| @@ -65,12 +68,24 @@ func TestBaseFileNamesGrammar(t *testing.T) { |
| "backslash in value": "A=x\\y\n", |
| "continued value": "A=x\\\nB=2\n", |
| "line too long": "A=" + strings.Repeat("x", baseFileLineLimit) + "\n", |
| + // Printable ASCII only (round 3 P1-4): systemd rejects a whole file |
| + // over a Unicode noncharacter, and a tab is not in the subset. |
| + "U+FDD0 noncharacter": "A=1\nB=\xef\xb7\x90\n", |
| + "U+FFFE noncharacter": "A=\xef\xbf\xbe\n", |
| + "U+FFFF noncharacter": "A=\xef\xbf\xbf\n", |
| + "U+1FFFF noncharacter": "A=\xf0\x9f\xbf\xbf\n", |
| + "tab": "A=x\ty\n", |
| + "non-ASCII letter": "A=caf\xc3\xa9\n", |
| + "DEL": "A=x\x7fy\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(), "line ") && !strings.Contains(err.Error(), "larger") { |
| + t.Errorf("%s: the error names no line: %v", name, err) |
| + } |
| if strings.Contains(err.Error(), "/data/base.db") || strings.Contains(err.Error(), "x\\y") { |
| t.Errorf("%s: the error echoes content: %v", name, err) |
| } |
diff --git a/internal/appconfig/declarations.go b/internal/appconfig/declarations.go| index f4fc79150..5719d1b17 100644 |
| --- a/internal/appconfig/declarations.go |
| +++ b/internal/appconfig/declarations.go |
| @@ -17,8 +17,10 @@ package appconfig |
| import ( |
| "bytes" |
| + "crypto/sha256" |
| "encoding/json" |
| "fmt" |
| + "io" |
| "github.com/carlosframework/platform/internal/controlname" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -52,24 +54,41 @@ func (d Declaration) account() string { |
| type declarations struct { |
| path string |
| byUnit map[string]Declaration |
| + byHost map[string]Declaration |
| + // digest is sha256 of the bytes the file held when it was read; the |
| + // guard re-reads and compares before every mutation (declGuard). |
| + digest [32]byte |
| } |
| -// 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{}} |
| +// readDeclarationBytes is the one read of the file: absent is no bytes. |
| +func readDeclarationBytes(ops *UnitOps) ([]byte, error) { |
| 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) |
| + raw, err := rootRead(ops, ops.NamedUnitsPath) |
| if err != nil { |
| if err == errNoFile { |
| - return d, nil |
| + return nil, nil |
| } |
| return nil, fmt.Errorf("declarations: %w", err) |
| } |
| + return raw, nil |
| +} |
| + |
| +// 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{}, byHost: map[string]Declaration{}} |
| + raw, err := readDeclarationBytes(ops) |
| + if err != nil { |
| + return nil, err |
| + } |
| + d.digest = sha256.Sum256(raw) |
| + if raw == nil { |
| + return d, nil |
| + } |
| var file struct { |
| Schema int `json:"schema"` |
| Units []Declaration `json:"units"` |
| @@ -78,6 +97,12 @@ func loadDeclarations(ops *UnitOps) (*declarations, error) { |
| if err := dec.Decode(&file); err != nil { |
| return nil, fmt.Errorf("declarations: %s: %w", ops.NamedUnitsPath, err) |
| } |
| + // One document and nothing after it, as the release path reads the |
| + // file (round 3 P2-6): trailing bytes make the file invalid, and an |
| + // invalid file authorises nothing, reaping included. |
| + if dec.Decode(new(any)) != io.EOF { |
| + return nil, fmt.Errorf("declarations: %s: bytes after the JSON document", ops.NamedUnitsPath) |
| + } |
| if file.Schema != 1 { |
| return nil, fmt.Errorf("declarations: %s: schema %d, want 1", ops.NamedUnitsPath, file.Schema) |
| } |
| @@ -100,10 +125,46 @@ func loadDeclarations(ops *UnitOps) (*declarations, error) { |
| } |
| byHost[u.Host] = true |
| d.byUnit[u.Unit] = u |
| + d.byHost[u.Host] = u |
| } |
| return d, nil |
| } |
| +// declGuard is round 3 P1-3's refusal: authorisation must stay valid |
| +// through the effect it permits. Before each mutation (env-file write, |
| +// drop-in write or removal, daemon-reload, restart, env reap) the pass |
| +// re-reads the declaration file through the trusted reader and compares a |
| +// digest of its bytes with what planning read. A difference, or a read |
| +// that fails, aborts every remaining mutation of the pass; the next pass |
| +// plans afresh. |
| +type declGuard struct { |
| + digest [32]byte |
| + stale bool |
| + reason string |
| + said bool |
| +} |
| + |
| +// check reports nil when the file still holds the bytes planning read. |
| +// Once stale, every later check is stale without another read. |
| +func (g *declGuard) check(ops *UnitOps) error { |
| + if g == nil { |
| + return fmt.Errorf("no declaration guard on this pass") |
| + } |
| + if g.stale { |
| + return fmt.Errorf("%s", g.reason) |
| + } |
| + raw, err := readDeclarationBytes(ops) |
| + if err != nil { |
| + g.stale, g.reason = true, fmt.Sprintf("the declaration file could not be re-read (%v); remaining mutations of this pass abandoned", err) |
| + return fmt.Errorf("%s", g.reason) |
| + } |
| + if sha256.Sum256(raw) != g.digest { |
| + g.stale, g.reason = true, "the declaration file changed during this pass; remaining mutations of this pass abandoned, the next pass plans afresh" |
| + return fmt.Errorf("%s", g.reason) |
| + } |
| + return 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, |
diff --git a/internal/appconfig/dropin.go b/internal/appconfig/dropin.go| index d91db73f1..27bf48034 100644 |
| --- a/internal/appconfig/dropin.go |
| +++ b/internal/appconfig/dropin.go |
| @@ -48,8 +48,8 @@ func renderDropIn(envDir, baseDir, unit, host string) []byte { |
| // ensureDropInDir creates <unit>.d if absent and refuses to use it if it |
| // is not a plain directory: a symlinked drop-in directory would let a root |
| // write land somewhere else (spec §3.2 rail; codex R1-2, R2-1). |
| -func ensureDropInDir(root, unit string) error { |
| - dir := dropInDir(root, unit) |
| +func ensureDropInDir(ops *UnitOps, unit string) error { |
| + dir := dropInDir(ops.DropInRoot, unit) |
| st, err := os.Lstat(dir) |
| switch { |
| case err == nil: |
| @@ -59,12 +59,17 @@ func ensureDropInDir(root, unit string) error { |
| if !st.IsDir() { |
| return fmt.Errorf("%s exists and is not a directory", dir) |
| } |
| - return nil |
| case os.IsNotExist(err): |
| - return os.Mkdir(dir, 0o755) |
| + if err := os.Mkdir(dir, 0o755); err != nil { |
| + return err |
| + } |
| default: |
| return err |
| } |
| + // Before any write into it: the directory and every directory above |
| + // it root-owned and not group- or other-writable, no symlink on the |
| + // path (invariant C; census E3). |
| + return trustedDir(ops, dir) |
| } |
| // dirIsPlain is ensureDropInDir's check without the mkdir, for readers. |
| @@ -76,8 +81,8 @@ func dirIsPlain(dir string) bool { |
| // 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) |
| +func readDropIn(ops *UnitOps, unit string) (cur []byte, exists, marked bool, err error) { |
| + cur, err = rootRead(ops, filepath.Join(dropInDir(ops.DropInRoot, unit), DropInFile)) |
| if err != nil { |
| if err == errNoFile { |
| return nil, false, false, nil |
| @@ -160,10 +165,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, trustedUID int) (units, skipped []string, unreadable map[string]error) { |
| - dirs, skipped := unitDirs(root) |
| +func listMarkedDropIns(ops *UnitOps) (units, skipped []string, unreadable map[string]error) { |
| + dirs, skipped := unitDirs(ops.DropInRoot) |
| for _, u := range dirs { |
| - _, exists, marked, err := readDropIn(root, u, trustedUID) |
| + _, exists, marked, err := readDropIn(ops, u) |
| 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 7300c4190..69efdadbb 100644 |
| --- a/internal/appconfig/dropin_test.go |
| +++ b/internal/appconfig/dropin_test.go |
| @@ -20,19 +20,26 @@ func TestRenderDropInHasMarkerResetAndFile(t *testing.T) { |
| } |
| } |
| +// dropInOps anchors the trusted reader at root, which the test owns; the |
| +// anchor is 0755 as provisioning leaves "/". |
| +func dropInOps(root string) *UnitOps { |
| + _ = os.Chmod(root, 0o755) |
| + return &UnitOps{DropInRoot: root, trustedRoot: root} |
| +} |
| + |
| func TestWriteReadAndMarkDropIn(t *testing.T) { |
| root := t.TempDir() |
| - if err := ensureDropInDir(root, "relay.service"); err != nil { |
| + if err := ensureDropInDir(dropInOps(root), "relay.service"); err != nil { |
| t.Fatalf("ensureDropInDir: %v", err) |
| } |
| - if _, exists, _, err := readDropIn(root, "relay.service", os.Getuid()); err != nil || exists { |
| + if _, exists, _, err := readDropIn(dropInOps(root), "relay.service"); 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", os.Getuid()) |
| + cur, exists, marked, err := readDropIn(dropInOps(root), "relay.service") |
| 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 +72,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", os.Getuid()) |
| + _, exists, marked, err := readDropIn(dropInOps(root), "relay.service") |
| 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, os.Getuid()) |
| + units, _, unreadable := listMarkedDropIns(dropInOps(root)) |
| if len(units) != 0 { |
| t.Fatalf("listMarkedDropIns = %v, want none for an unmarked file", units) |
| } |
| @@ -82,14 +89,14 @@ func TestEnsureDropInDirRefusesSymlinkAndFile(t *testing.T) { |
| root := t.TempDir() |
| elsewhere := t.TempDir() |
| os.Symlink(elsewhere, filepath.Join(root, "linked.service.d")) |
| - if err := ensureDropInDir(root, "linked.service"); err == nil || !strings.Contains(err.Error(), "symlink") { |
| + if err := ensureDropInDir(dropInOps(root), "linked.service"); err == nil || !strings.Contains(err.Error(), "symlink") { |
| t.Fatalf("ensureDropInDir(symlink) = %v, want a symlink refusal", err) |
| } |
| os.WriteFile(filepath.Join(root, "file.service.d"), []byte("x"), 0o644) |
| - if err := ensureDropInDir(root, "file.service"); err == nil { |
| + if err := ensureDropInDir(dropInOps(root), "file.service"); err == nil { |
| t.Fatal("ensureDropInDir(regular file) accepted") |
| } |
| - if err := ensureDropInDir(root, "fresh.service"); err != nil { |
| + if err := ensureDropInDir(dropInOps(root), "fresh.service"); err != nil { |
| t.Fatalf("ensureDropInDir(fresh) = %v", err) |
| } |
| st, _ := os.Lstat(filepath.Join(root, "fresh.service.d")) |
| @@ -105,7 +112,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, os.Getuid()) |
| + units, skipped, unreadable := listMarkedDropIns(dropInOps(root)) |
| if len(units) != 1 || units[0] != "real.service" { |
| t.Fatalf("units = %v, want [real.service]", units) |
| } |
| @@ -128,7 +135,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, os.Getuid()) |
| + units, skipped, unreadable := listMarkedDropIns(dropInOps(root)) |
| if len(units) != 0 { |
| t.Fatalf("units = %v, want none for an unreadable drop-in", units) |
| } |
| @@ -142,12 +149,12 @@ func TestListMarkedDropInsReportsAnUnreadableFile(t *testing.T) { |
| func TestRemoveDropIn(t *testing.T) { |
| root := t.TempDir() |
| - ensureDropInDir(root, "relay.service") |
| + ensureDropInDir(dropInOps(root), "relay.service") |
| writeDropIn(root, "relay.service", renderDropIn("/e", "/b", "x.service", "h")) |
| if err := removeDropIn(root, "relay.service"); err != nil { |
| t.Fatalf("removeDropIn: %v", err) |
| } |
| - if _, exists, _, _ := readDropIn(root, "relay.service", os.Getuid()); exists { |
| + if _, exists, _, _ := readDropIn(dropInOps(root), "relay.service"); 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.go b/internal/appconfig/rootread.go| new file mode 100644 |
| index 000000000..2ab145af5 |
| --- /dev/null |
| +++ b/internal/appconfig/rootread.go |
| @@ -0,0 +1,81 @@ |
| +// 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, and one check vets a |
| +// drop-in directory before any write into it. Both are |
| +// rootstate.OpenTrustedFileFrom / OpenTrustedDirFrom, the release path's |
| +// own descriptor walk (internal/rootstate/state_linux.go, descend): every |
| +// component from the anchor down is opened by directory descriptor with |
| +// O_NOFOLLOW and must be a directory owned by the anchor's owner and |
| +// writable by neither group nor others; the file is a regular file with one |
| +// link, the same owner, the same mode rule, read from its descriptor. The |
| +// anchor is "/" in production (UnitOps.trustedRoot empty), so the chain is |
| +// exactly OpenTrustedFile's; a test anchors at a directory it owns. |
| +// Anything else is refused with the reason, and the caller blocks the unit. |
| +package appconfig |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "syscall" |
| + |
| + "github.com/carlosframework/platform/internal/rootstate" |
| +) |
| + |
| +// 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") |
| + |
| +func (ops *UnitOps) anchor() string { |
| + if ops.trustedRoot == "" { |
| + return "/" |
| + } |
| + return ops.trustedRoot |
| +} |
| + |
| +// trustedErr turns the opener's answer into the reason a log line gives. |
| +func trustedErr(path string, err error) error { |
| + switch { |
| + case errors.Is(err, syscall.ELOOP): |
| + return fmt.Errorf("%s: a symlink on the path; refusing to read through it", path) |
| + case errors.Is(err, os.ErrPermission): |
| + return fmt.Errorf("%s: not root-owned, or writable by its group or others, or a directory on the path is", path) |
| + } |
| + return fmt.Errorf("%s: %w", path, err) |
| +} |
| + |
| +// rootRead reads path through the trusted opener. |
| +func rootRead(ops *UnitOps, path string) ([]byte, error) { |
| + f, err := rootstate.OpenTrustedFileFrom(ops.anchor(), path) |
| + if err != nil { |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil, errNoFile |
| + } |
| + return nil, trustedErr(path, err) |
| + } |
| + defer f.Close() |
| + 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 |
| +} |
| + |
| +// trustedDir vets a directory the pass is about to write into, through the |
| +// same chain: every component from the anchor down, the directory included, |
| +// root-owned and not group- or other-writable, no symlink anywhere. |
| +func trustedDir(ops *UnitOps, dir string) error { |
| + d, err := rootstate.OpenTrustedDirFrom(ops.anchor(), dir) |
| + if err != nil { |
| + return trustedErr(dir, err) |
| + } |
| + return d.Close() |
| +} |
diff --git a/internal/appconfig/rootread_other.go b/internal/appconfig/rootread_other.go| deleted file mode 100644 |
| index 1caeca9a2..000000000 |
| --- a/internal/appconfig/rootread_other.go |
| +++ /dev/null |
| @@ -1,16 +0,0 @@ |
| -//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| deleted file mode 100644 |
| index 07df58d29..000000000 |
| --- a/internal/appconfig/rootread_unix.go |
| +++ /dev/null |
| @@ -1,93 +0,0 @@ |
| -//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 4417bd8b1..c9fec22b2 100644 |
| --- a/internal/appconfig/sync.go |
| +++ b/internal/appconfig/sync.go |
| @@ -109,6 +109,24 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St |
| plan = planStamped(routes, envDir, ops) |
| } |
| work := map[string]unitWork{} // by unit |
| + // Invariant A at the dispatch (round 3 P1-1, census E1): a declared |
| + // host is written only through the stamped path by its declaration's |
| + // own stamp; every other row for it is refused here, before any bundle |
| + // is read for it and before either writer. With the declaration file |
| + // unreadable nothing is delivered to any host this pass (which hosts |
| + // are declared is then unknown) and nothing is reaped. |
| + declaredRefusal := map[string]string{} |
| + declarationsUnknown := ops != nil && plan.decls == nil |
| + if ops != nil && !declarationsUnknown { |
| + for _, rt := range routes { |
| + if reason := plan.declaredHostRefusal(rt); reason != "" { |
| + declaredRefusal[rt.Host] = reason |
| + } |
| + } |
| + } |
| + if declarationsUnknown { |
| + fmt.Printf(" config sync: the declaration file could not be read; nothing delivered and nothing reaped this pass\n") |
| + } |
| type groupKey struct{ acct, app, env string } |
| // A resolution is one of three states, and they are NOT interchangeable: |
| // a manifest to converge to; "this app was never configured" (nil, nil), |
| @@ -168,6 +186,9 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St |
| if !(syncable(rt) || Stamped(rt)) { |
| continue |
| } |
| + if _, refused := declaredRefusal[rt.Host]; refused || (declarationsUnknown && !stampedForDelivery(rt)) { |
| + continue // nothing is read for a row that will not be written |
| + } |
| k := groupKey{release.RouteAccount(rt), rt.App, rt.Environment} |
| if _, done := resolved[k]; done { |
| continue |
| @@ -220,6 +241,13 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St |
| if !(syncable(rt) || Stamped(rt)) { |
| continue |
| } |
| + if reason, refused := declaredRefusal[rt.Host]; refused { |
| + fmt.Printf(" %s: delivery blocked: %s\n", rt.Host, reason) |
| + continue |
| + } |
| + if declarationsUnknown && !stampedForDelivery(rt) { |
| + continue // said once above; stamped rows print their own refusal below |
| + } |
| k := groupKey{release.RouteAccount(rt), rt.App, rt.Environment} |
| r := resolved[k] |
| if r.err != nil { |
| @@ -360,7 +388,24 @@ func SyncWithCallbacks(ctx context.Context, reg *registry.Registry, s release.St |
| return nil |
| } |
| if !hostWrites.Enabled { |
| - reap(routes, envDir) |
| + // Invariant A, env files (round 3 P1-2, census E2): a declared |
| + // host's env file is kept whatever the registry says, and with the |
| + // declarations unknown or changed nothing is reaped. |
| + var keep map[string]bool |
| + if ops != nil { |
| + if plan.decls == nil { |
| + return nil |
| + } |
| + if err := plan.guard.check(ops); err != nil { |
| + fmt.Printf(" env files: not reaped: %v\n", err) |
| + return nil |
| + } |
| + keep = map[string]bool{} |
| + for host := range plan.decls.byHost { |
| + keep[host] = true |
| + } |
| + } |
| + reap(routes, envDir, keep) |
| } else { |
| reapSelectedEnvTemps(ctx, envDir, selected) |
| } |
| @@ -403,15 +448,22 @@ func reapSelectedEnvTemps(ctx context.Context, envDir string, selected map[strin |
| // bucket, has no bearing on whether its file is orphaned. Deleting an |
| // environment bundle must never delete a live route's env file — that route |
| // keeps its last-good file and Sync logs the unresolved binding instead. |
| -func reap(routes []registry.Route, envDir string) { |
| +// |
| +// declared are the hosts the named-units declaration names (invariant A): |
| +// their files are kept whether or not a row names them, since a declared |
| +// unit's drop-in loads the file on its next start. |
| +func reap(routes []registry.Route, envDir string, declared map[string]bool) { |
| ents, err := os.ReadDir(envDir) |
| if err != nil { |
| return |
| } |
| - live := make(map[string]bool, len(routes)) |
| + live := make(map[string]bool, len(routes)+len(declared)) |
| for _, rt := range routes { |
| live[rt.Host] = true |
| } |
| + for host := range declared { |
| + live[host] = true |
| + } |
| for _, e := range ents { |
| if e.IsDir() { |
| continue |
diff --git a/internal/appconfig/unitsync.go b/internal/appconfig/unitsync.go| index e854ac0bd..8dcc70f10 100644 |
| --- a/internal/appconfig/unitsync.go |
| +++ b/internal/appconfig/unitsync.go |
| @@ -46,10 +46,11 @@ type UnitOps struct { |
| // 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 |
| + // trustedRoot anchors every trusted read and directory check |
| + // (invariant C, rootRead, trustedDir): "/" in production (left empty), |
| + // whose owner root is then the owner every component must have; a |
| + // test sets a directory it owns. |
| + trustedRoot string |
| // 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 |
| @@ -79,6 +80,32 @@ type stampedPlan struct { |
| // idle are the declared units no delivering route names this pass: their |
| // drop-ins stay, and the pass says so. |
| idle []string |
| + // guard re-reads the declaration file before each mutation (round 3 |
| + // P1-3); nil when the file could not be read, which mutates nothing. |
| + guard *declGuard |
| +} |
| + |
| +// declaredHostRefusal is invariant A at the dispatch (round 3 P1-1, census |
| +// E1): a host a declaration names is written ONLY through the |
| +// declaration-gated stamped path, by the row that is exactly that |
| +// declaration's stamp. Any other row for that host (unit backing, a |
| +// cleared stamp, another unit, another account or app) is refused with the |
| +// reason and its env file left untouched. "" admits the row. |
| +func (p stampedPlan) declaredHostRefusal(rt registry.Route) string { |
| + if p.decls == nil { |
| + return "" |
| + } |
| + d, declared := p.decls.byHost[rt.Host] |
| + if !declared { |
| + return "" |
| + } |
| + if !stampedForDelivery(rt) { |
| + return fmt.Sprintf("%s is declared for %s (%s/%s) and is written only through that declaration; this row is not a deliverable stamp (backing %q, unit %q), and a registry row alone never authorises delivery; env file left untouched", rt.Host, d.Unit, d.account(), d.App, rt.Backing, rt.Unit) |
| + } |
| + if _, err := p.decls.DeclaredBinding(rt); err != nil { |
| + return fmt.Sprintf("%s is declared for %s (%s/%s) and is written only through that declaration; not declared for this row: %v; a registry row alone never authorises delivery; env file left untouched", rt.Host, d.Unit, d.account(), d.App, err) |
| + } |
| + return "" |
| } |
| // planStamped applies the rail (spec §3.2) to every stamped route in |
| @@ -94,6 +121,9 @@ func planStamped(routes []registry.Route, envDir string, ops *UnitOps) stampedPl |
| p := stampedPlan{unitOf: map[string]string{}, refused: map[string]string{}, probe: map[string]UnitState{}} |
| decls, declErr := loadDeclarations(ops) |
| p.decls = decls |
| + if decls != nil { |
| + p.guard = &declGuard{digest: decls.digest} |
| + } |
| byUnit := map[string][]string{} |
| rowOf := map[string]registry.Route{} |
| for _, rt := range routes { |
| @@ -178,7 +208,7 @@ func planStamped(routes []registry.Route, envDir string, ops *UnitOps) stampedPl |
| // 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, ops.trustedUID) |
| + _, exists, marked, err := readDropIn(ops, unit) |
| if err != nil { |
| p.refused[host] = fmt.Sprintf("read drop-in for %s: %v", unit, err) |
| continue |
| @@ -244,7 +274,7 @@ 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(ops.BaseEnvDir, base, ops.trustedUID) |
| + baseNames, err := envFileNames(ops, base) |
| if err != nil { |
| 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 |
| @@ -254,11 +284,11 @@ func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing |
| rt.Host, base, strings.Join(both, ", ")) |
| return w |
| } |
| - if err := ensureDropInDir(ops.DropInRoot, unit); err != nil { |
| - fmt.Printf(" %s: drop-in directory for %s: %v\n", rt.Host, unit, err) |
| + if err := ensureDropInDir(ops, unit); err != nil { |
| + fmt.Printf(" %s: delivery blocked: drop-in directory for %s: %v\n", rt.Host, unit, err) |
| return w |
| } |
| - curDrop, dropExists, marked, err := readDropIn(ops.DropInRoot, unit, ops.trustedUID) |
| + curDrop, dropExists, marked, err := readDropIn(ops, unit) |
| if err != nil { |
| fmt.Printf(" %s: delivery blocked: read drop-in for %s: %v\n", rt.Host, unit, err) |
| return w |
| @@ -275,14 +305,30 @@ func prepareStamped(rt registry.Route, unit string, m *Manifest, defaultMissing |
| w.ok = true |
| return w |
| } |
| + // Before each mutation: the declaration file still holds what planning |
| + // read (round 3 P1-3). |
| + if err := plan.guard.check(ops); err != nil { |
| + fmt.Printf(" %s: delivery blocked: %v\n", rt.Host, err) |
| + return w |
| + } |
| if err := writePending(ops.DropInRoot, unit); err != nil { |
| fmt.Printf(" %s: record pending restart for %s: %v (nothing written)\n", rt.Host, unit, err) |
| return w |
| } |
| - if envChanged && !commitHost(rt.Host, path, rendered) { |
| - return w |
| + if envChanged { |
| + if err := plan.guard.check(ops); err != nil { |
| + fmt.Printf(" %s: delivery blocked: %v\n", rt.Host, err) |
| + return w |
| + } |
| + if !commitHost(rt.Host, path, rendered) { |
| + return w |
| + } |
| } |
| if dropChanged { |
| + if err := plan.guard.check(ops); err != nil { |
| + fmt.Printf(" %s: delivery blocked: %v\n", rt.Host, err) |
| + return w |
| + } |
| if err := writeDropIn(ops.DropInRoot, unit, wantDrop); err != nil { |
| fmt.Printf(" %s: write drop-in for %s: %v\n", rt.Host, unit, err) |
| return w |
| @@ -308,7 +354,7 @@ func reapDropIns(plan stampedPlan, ops *UnitOps) { |
| fmt.Printf(" drop-ins: the declaration file could not be read; nothing reaped this pass\n") |
| return |
| } |
| - units, skipped, unreadable := listMarkedDropIns(ops.DropInRoot, ops.trustedUID) |
| + units, skipped, unreadable := listMarkedDropIns(ops) |
| for _, unit := range skipped { |
| fmt.Printf(" %s: %s is not a plain directory; not entered\n", unit, dropInDir(ops.DropInRoot, unit)) |
| } |
| @@ -329,6 +375,10 @@ func reapDropIns(plan stampedPlan, ops *UnitOps) { |
| if plan.decls.declares(unit) { |
| continue |
| } |
| + if err := plan.guard.check(ops); err != nil { |
| + fmt.Printf(" %s: not reaped: %v\n", unit, err) |
| + return |
| + } |
| if err := writePending(ops.DropInRoot, unit); err != nil { |
| fmt.Printf(" %s: record reload owed: %v (drop-in kept)\n", unit, err) |
| continue |
| @@ -363,6 +413,10 @@ func applyStamped(envDir string, ops *UnitOps, plan stampedPlan, work map[string |
| } |
| pending := listPending(ops.DropInRoot) |
| if len(pending) > 0 { |
| + if err := plan.guard.check(ops); err != nil { |
| + fmt.Printf(" daemon-reload not run: %v\n", err) |
| + return |
| + } |
| if err := ops.Reload(); err != nil { |
| for _, unit := range pending { |
| fmt.Printf(" %s: daemon-reload failed (%v); reload and restart still owed\n", unit, err) |
| @@ -374,7 +428,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, ops.trustedUID) |
| + _, exists, isMarked, err := readDropIn(ops, unit) |
| if err != nil { |
| fmt.Printf(" %s: read drop-in: %v; restart still owed\n", unit, err) |
| continue |
| @@ -420,6 +474,10 @@ func applyStamped(envDir string, ops *UnitOps, plan stampedPlan, work map[string |
| fmt.Printf(" %s: restart of %s refused: not declared: %v\n", w.host, unit, err) |
| continue |
| } |
| + if err := plan.guard.check(ops); err != nil { |
| + fmt.Printf(" %s: restart of %s not run: %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 9d25753fa..d573b4c46 100644 |
| --- a/internal/appconfig/unitsync_test.go |
| +++ b/internal/appconfig/unitsync_test.go |
| @@ -17,10 +17,15 @@ import ( |
| // fakeUnits is the UnitOps seam with everything recorded: what was probed, |
| // reloaded and restarted, and what the probe answers. |
| type fakeUnits struct { |
| + anchor string // the faked filesystem root the trusted reader walks from |
| root string |
| base string |
| decl string // the named-units.json this pass reads |
| states map[string]UnitState |
| + // onProbe, when set, runs after each probe with its ordinal (1 for the |
| + // rail probe, 2 for the post-reload probe): the hook a mid-pass |
| + // witness changes the declaration file from. |
| + onProbe func(call int) |
| // declared accumulates stampDeclared's entries. |
| declared []Declaration |
| probeErr error |
| @@ -34,7 +39,22 @@ type fakeUnits struct { |
| func newFakeUnits(t *testing.T) *fakeUnits { |
| t.Helper() |
| - return &fakeUnits{root: t.TempDir(), base: t.TempDir(), decl: filepath.Join(t.TempDir(), "named-units.json"), states: map[string]UnitState{}, restartErr: map[string]error{}} |
| + // The anchor as provisioning leaves "/": 0755 (t.TempDir follows the |
| + // umask, and a group-writable anchor is rightly refused). |
| + anchor := t.TempDir() |
| + if err := os.Chmod(anchor, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + f := &fakeUnits{anchor: anchor, root: filepath.Join(anchor, "systemd", "system"), base: filepath.Join(anchor, "carlos", "units"), |
| + decl: filepath.Join(anchor, "carlos", "named-units.json"), states: map[string]UnitState{}, restartErr: map[string]error{}} |
| + // The directories as provisioning makes them: 0755, owned by the |
| + // owner of the anchor (root in production, the test user here). |
| + for _, d := range []string{f.root, f.base} { |
| + if err := os.MkdirAll(d, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return f |
| } |
| // declare writes the declaration file as root would at provisioning, in |
| @@ -100,7 +120,7 @@ func (f *fakeUnits) ops() *UnitOps { |
| DropInRoot: f.root, |
| BaseEnvDir: f.base, |
| NamedUnitsPath: f.decl, |
| - trustedUID: os.Getuid(), |
| + trustedRoot: f.anchor, |
| Lock: func() (func(), error) { |
| if f.lockErr != nil { |
| return nil, f.lockErr |
| @@ -109,6 +129,9 @@ func (f *fakeUnits) ops() *UnitOps { |
| }, |
| Probe: func(units []string) (map[string]UnitState, error) { |
| f.probed = append(f.probed, append([]string(nil), units...)) |
| + if f.onProbe != nil { |
| + f.onProbe(len(f.probed)) |
| + } |
| if f.probeErr != nil { |
| return nil, f.probeErr |
| } |
| @@ -195,7 +218,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", os.Getuid()) |
| + cur, exists, marked, _ := readDropIn(f.ops(), "relay.service") |
| 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) |
| } |
| @@ -283,7 +306,7 @@ func TestSyncUnitsRefusesTwoRoutesOnOneUnit(t *testing.T) { |
| f := newFakeUnits(t) |
| f.states["relay.service"] = UnitState{ID: "relay.service", LoadState: "loaded"} |
| stampDeclared(t, f, reg, "a.example.com", "relay.service", nil) |
| - stampDeclared(t, f, reg, "b.example.com", "relay.service", nil) |
| + upsertStamped(t, 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) |
| @@ -310,7 +333,7 @@ func TestSyncUnitsRefusesAnUnmarkedDropIn(t *testing.T) { |
| t.Fatalf("SyncUnits: %v", err) |
| } |
| }) |
| - cur, _, _, _ := readDropIn(f.root, "relay.service", os.Getuid()) |
| + cur, _, _, _ := readDropIn(f.ops(), "relay.service") |
| if string(cur) != string(foreign) { |
| t.Fatal("an unmarked file must never be replaced") |
| } |
| @@ -505,7 +528,7 @@ func TestSyncUnitsRefusedRouteKeepsAnEarlierMarker(t *testing.T) { |
| 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). |
| - stampDeclared(t, f, reg, "b.example.com", "relay.service", nil) |
| + upsertStamped(t, 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")) |
| @@ -537,7 +560,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. |
| - stampDeclared(t, f, reg, "b.example.com", "relay.service", nil) |
| + upsertStamped(t, 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")) |
| @@ -565,7 +588,7 @@ func TestSyncUnitsReapsOnlyWhenTheDeclarationGoes(t *testing.T) { |
| t.Fatal(err) |
| } |
| out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| - if _, exists, marked, _ := readDropIn(f.root, "relay.service", os.Getuid()); !exists || !marked { |
| + if _, exists, marked, _ := readDropIn(f.ops(), "relay.service"); !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") { |
| @@ -579,7 +602,7 @@ func TestSyncUnitsReapsOnlyWhenTheDeclarationGoes(t *testing.T) { |
| 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") { |
| + if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); !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) |
| } |
| @@ -588,7 +611,7 @@ func TestSyncUnitsReapsOnlyWhenTheDeclarationGoes(t *testing.T) { |
| f.undeclare(t) |
| f.reloadErr = errors.New("busy") |
| syncOnce(t, ctx, reg, s, priv, envDir, f) |
| - if _, exists, _, _ := readDropIn(f.root, "relay.service", os.Getuid()); exists { |
| + if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); exists { |
| t.Fatal("drop-in must be removed once no declaration names the unit") |
| } |
| if !hasPending(f.root, "relay.service") { |
| @@ -612,11 +635,11 @@ func TestSyncUnitsReapsOnlyWhenTheDeclarationGoes(t *testing.T) { |
| func TestSyncUnitsUnreadableDeclarationsReapNothing(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| - ensureDropInDir(f.root, "relay.service") |
| + ensureDropInDir(f.ops(), "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") { |
| + if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); !exists || !strings.Contains(out, "nothing reaped") { |
| t.Fatalf("exists=%v out=%q", exists, out) |
| } |
| } |
| @@ -638,7 +661,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", os.Getuid()); string(cur) != string(foreign) { |
| + if cur, _, _, _ := readDropIn(f.ops(), "foreign.service"); string(cur) != string(foreign) { |
| t.Fatal("unmarked file touched") |
| } |
| if _, err := os.Stat(filepath.Join(elsewhere, DropInFile)); err != nil { |
| @@ -652,13 +675,13 @@ func TestSyncUnitsReaperNeverRemovesUnmarkedOrSymlinked(t *testing.T) { |
| func TestSyncUnitsEmptyRegistryReapsNoDeclaredDropIn(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| - ensureDropInDir(f.root, "relay.service") |
| + ensureDropInDir(f.ops(), "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", os.Getuid()); !exists { |
| + if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); !exists { |
| t.Fatal("a declared unit's drop-in stays whatever the registry says") |
| } |
| } |
| @@ -678,10 +701,10 @@ func TestSyncUnitsReStampMovesTheDropIn(t *testing.T) { |
| // reloads. |
| f.reloads = 0 |
| out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| - if _, exists, _, _ := readDropIn(f.root, "b.service", os.Getuid()); exists || !strings.Contains(out, "registry row alone") { |
| + if _, exists, _, _ := readDropIn(f.ops(), "b.service"); exists || !strings.Contains(out, "registry row alone") { |
| t.Fatalf("a re-stamp root cannot bind was delivered: exists=%v out=%q", exists, out) |
| } |
| - if _, exists, marked, _ := readDropIn(f.root, "a.service", os.Getuid()); !exists || !marked { |
| + if _, exists, marked, _ := readDropIn(f.ops(), "a.service"); !exists || !marked { |
| t.Fatal("a refused re-stamp removed the old unit's drop-in") |
| } |
| if f.reloads != 0 || hasPending(f.root, "a.service") { |
| @@ -690,10 +713,10 @@ func TestSyncUnitsReStampMovesTheDropIn(t *testing.T) { |
| 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", os.Getuid()); exists { |
| + if _, exists, _, _ := readDropIn(f.ops(), "a.service"); exists { |
| t.Fatal("old unit's drop-in must be reaped") |
| } |
| - if _, exists, marked, _ := readDropIn(f.root, "b.service", os.Getuid()); !exists || !marked { |
| + if _, exists, marked, _ := readDropIn(f.ops(), "b.service"); !exists || !marked { |
| t.Fatal("new unit's drop-in must be written") |
| } |
| if len(f.restarted) != 1 || f.restarted[0] != "b.service" { |
| @@ -757,7 +780,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", os.Getuid()); !exists || !marked { |
| + if _, exists, marked, _ := readDropIn(f.ops(), "console.service"); !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") { |
| @@ -777,7 +800,7 @@ func TestSyncUnitsGuardAdmitsAUnitLoadingOnlyManagedPaths(t *testing.T) { |
| 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, os.Getuid()); !exists || !marked { |
| + if _, exists, marked, _ := readDropIn(f.ops(), unit); !exists || !marked { |
| t.Fatalf("%s: drop-in not written for a unit loading only managed paths", unit) |
| } |
| } |
| @@ -797,7 +820,7 @@ func TestSyncUnitsDropInListsBaseBeforeBundle(t *testing.T) { |
| 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", os.Getuid()) |
| + cur, exists, marked, _ := readDropIn(f.ops(), "relay.service") |
| if !exists || !marked { |
| t.Fatal("drop-in not written") |
| } |
| @@ -857,7 +880,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", os.Getuid()); exists || hasPending(f.root, "relay.service") { |
| + if _, exists, _, _ := readDropIn(f.ops(), "relay.service"); 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 { |
| @@ -910,7 +933,10 @@ func TestSyncUnitsUnitBackedRowWithAStampStaysOnTheCarlosAppPath(t *testing.T) { |
| ctx, s, reg, envDir, priv := unitKit(t) |
| f := newFakeUnits(t) |
| f.loaded("console.service", envDir, "console.example.com") |
| - stampDeclared(t, f, reg, "console.example.com", "console.service", func(r *registry.Route) { r.Backing = registry.BackingUnit }) |
| + // Not declared: a declared host is written only through its |
| + // declaration's stamp (round 3 P1-1), so this shape stays main's only |
| + // for a host no declaration names. |
| + upsertStamped(t, 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) |
| @@ -1075,7 +1101,7 @@ func TestSyncUnitsRefusesARegistryAccountOrAppSwap(t *testing.T) { |
| 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 { |
| + if _, exists, marked, _ := readDropIn(f.ops(), "relay.service"); !exists || !marked { |
| t.Fatal("the declared unit's drop-in must survive a swapped row") |
| } |
| }) |
| @@ -1107,7 +1133,7 @@ func TestSyncUnitsRefusesFilesTheOneReaderRefuses(t *testing.T) { |
| {"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") |
| + ensureDropInDir(f.ops(), "relay.service") |
| os.Symlink(target, filepath.Join(dropInDir(f.root, "relay.service"), DropInFile)) |
| }, "symlink"}, |
| } { |
| @@ -1182,3 +1208,264 @@ func TestSyncUnitsDeclarationAddsNoBucketReads(t *testing.T) { |
| t.Fatal("the witness pinned nothing") |
| } |
| } |
| + |
| +// Round 3 P1-1, census E1: a declared host is written only through its |
| +// declaration's own stamp. After a successful delivery, a row that moves |
| +// the host onto unit backing, clears its stamp or changes its account or |
| +// app is refused before either writer, the env file byte for byte as it |
| +// was, nothing reloaded or restarted. |
| +func TestSyncUnitsRefusesABackingChangeOnADeclaredHost(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + mut func(*registry.Route) |
| + }{ |
| + {"unit backing and another app", func(r *registry.Route) { r.Backing = registry.BackingUnit; r.App = "shop" }}, |
| + {"unit backing and another account", func(r *registry.Route) { r.Backing = registry.BackingUnit; r.Account = "bae" }}, |
| + {"unit backing, same app", func(r *registry.Route) { r.Backing = registry.BackingUnit }}, |
| + {"cleared stamp and another app", func(r *registry.Route) { r.Unit = ""; r.Backing = registry.BackingUnit; r.App = "shop" }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + ctx, s, reg, envDir, priv := unitKit(t) |
| + for _, acctApp := range [][2]string{{"bab", "shop"}, {"bae", "relay"}} { |
| + if err := SetEnv(ctx, s, acctApp[0], acctApp[1], 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) |
| + var restarted []string |
| + hostRestart := func(h string) error { restarted = append(restarted, h); return nil } |
| + if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil { |
| + t.Fatal(err) |
| + } |
| + before, err := os.ReadFile(filepath.Join(envDir, "relay.example.com.env")) |
| + if err != nil || len(f.restarted) != 1 { |
| + t.Fatalf("precondition: delivered? err=%v restarted=%v", err, f.restarted) |
| + } |
| + f.reloads, f.restarted, f.probed = 0, nil, nil |
| + upsertStamped(t, reg, "relay.example.com", "relay.service", tc.mut) |
| + if err := SetEnv(ctx, s, "bab", "relay", map[string]string{"LOG_LEVEL": "info"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + out := captureStdout(t, func() { |
| + if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + if !strings.Contains(out, "written only through that declaration") { |
| + t.Fatalf("expected the declared-host refusal, got %q", out) |
| + } |
| + after, _ := os.ReadFile(filepath.Join(envDir, "relay.example.com.env")) |
| + if string(after) != string(before) { |
| + t.Fatalf("env file changed: %q -> %q", before, after) |
| + } |
| + if len(restarted) != 0 || len(f.restarted) != 0 || f.reloads != 0 || len(f.probed) != 0 { |
| + t.Fatalf("something ran: host restarts=%v unit restarts=%v reloads=%d probes=%v", restarted, f.restarted, f.reloads, f.probed) |
| + } |
| + if _, exists, marked, _ := readDropIn(f.ops(), "relay.service"); !exists || !marked { |
| + t.Fatal("the drop-in must survive") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Round 3 P1-2, census E2: a declared host's env file is kept whatever |
| +// the registry says. Its row deleted while an unrelated row remains: the |
| +// env file and the drop-in survive. With the declaration file unreadable, |
| +// nothing is reaped and nothing delivered for any host. |
| +func TestSyncUnitsKeepsADeclaredHostsEnvFileWhenItsRowGoes(t *testing.T) { |
| + for _, unreadable := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "declared", true: "declarations unreadable"}[unreadable], 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) |
| + // The unrelated row: a carlos-app@ tenant of the same app. |
| + 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) |
| + } |
| + hostRestarts := 0 |
| + hostRestart := func(string) error { hostRestarts++; return nil } |
| + if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(f.restarted) != 1 || hostRestarts != 1 { |
| + t.Fatalf("precondition: unit restarts=%v host restarts=%d", f.restarted, hostRestarts) |
| + } |
| + if err := reg.Delete("relay.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if unreadable { |
| + f.declRaw(t, "{") |
| + } |
| + f.reloads, f.restarted = 0, nil |
| + out := captureStdout(t, func() { |
| + if err := SyncUnits(ctx, reg, s, priv, envDir, hostRestart, nil, f.ops()); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + if _, err := os.Stat(filepath.Join(envDir, "relay.example.com.env")); err != nil { |
| + t.Fatalf("a declared host's env file was reaped on its row's deletion: %v", err) |
| + } |
| + if _, exists, marked, _ := readDropIn(f.ops(), "relay.service"); !exists || !marked { |
| + t.Fatal("the drop-in must survive") |
| + } |
| + if f.reloads != 0 || len(f.restarted) != 0 { |
| + t.Fatalf("reloads=%d restarted=%v", f.reloads, f.restarted) |
| + } |
| + if unreadable && !strings.Contains(out, "nothing delivered and nothing reaped") { |
| + t.Fatalf("expected the unreadable-declarations line, got %q", out) |
| + } |
| + if _, err := os.Stat(filepath.Join(envDir, "km.example.com.env")); err != nil { |
| + t.Fatal("the unrelated row's file must stay too") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Round 3 P1-3: the declaration file is re-read before each mutation. |
| +// Changed after the first probe, nothing is written, reloaded or |
| +// restarted; changed after the post-reload probe, the files and the |
| +// reload stand but the restart does not run and the marker stays. |
| +func TestSyncUnitsAbortsWhenTheDeclarationChangesMidPass(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + probe int |
| + }{{"after the first probe", 1}, {"before the restart", 2}} { |
| + 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) |
| + f.onProbe = func(call int) { |
| + if call == tc.probe { |
| + f.declare(t, Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "other.service"}) |
| + } |
| + } |
| + out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if !strings.Contains(out, "changed during this pass") { |
| + t.Fatalf("expected the mid-pass abort, got %q", out) |
| + } |
| + if len(f.restarted) != 0 { |
| + t.Fatalf("restarted = %v", f.restarted) |
| + } |
| + _, envErr := os.Stat(filepath.Join(envDir, "relay.example.com.env")) |
| + _, dropExists, _, _ := readDropIn(f.ops(), "relay.service") |
| + switch tc.probe { |
| + case 1: |
| + if envErr == nil || dropExists || hasPending(f.root, "relay.service") || f.reloads != 0 { |
| + t.Fatalf("mutated after an early change: env=%v drop=%v pending=%v reloads=%d", envErr == nil, dropExists, hasPending(f.root, "relay.service"), f.reloads) |
| + } |
| + case 2: |
| + if envErr != nil || !dropExists || !hasPending(f.root, "relay.service") || f.reloads != 1 { |
| + t.Fatalf("after a change before the restart: env=%v drop=%v pending=%v reloads=%d", envErr == nil, dropExists, hasPending(f.root, "relay.service"), f.reloads) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Round 3 P1-4: the base file is printable ASCII and LF only, through the |
| +// real pass, with the line named. |
| +func TestSyncUnitsRefusesANonASCIIBaseFile(t *testing.T) { |
| + for name, body := range map[string]string{ |
| + "U+FDD0": "A=1\nB=\xef\xb7\x90\n", |
| + "U+FFFF": "A=1\nB=\xef\xbf\xbf\n", |
| + "U+FFFE": "A=1\nB=\xef\xbf\xbe\n", |
| + "tab": "A=1\nB=x\ty\n", |
| + "non-ASCII letter": "A=1\nB=caf\xc3\xa9\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, "line 2") { |
| + t.Fatalf("want a blocked line naming line 2, got %q", out) |
| + } |
| + if ents, _ := os.ReadDir(envDir); len(ents) != 0 || len(f.restarted) != 0 { |
| + t.Fatalf("rendered=%v restarted=%v", ents, f.restarted) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Round 3 P2-5, census E3: a writable parent, a symlinked ancestor and a |
| +// writable drop-in directory each block the unit before any write. |
| +func TestSyncUnitsRefusesUntrustedDirectories(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + arm func(t *testing.T, f *fakeUnits) |
| + want string |
| + }{ |
| + {"writable base directory", func(t *testing.T, f *fakeUnits) { |
| + if err := os.Chmod(f.base, 0o777); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "writable"}, |
| + {"symlinked ancestor of the base file", func(t *testing.T, f *fakeUnits) { |
| + real := f.base + ".real" |
| + if err := os.Rename(f.base, real); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(real, f.base); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "symlink"}, |
| + {"writable drop-in directory", func(t *testing.T, f *fakeUnits) { |
| + if err := ensureDropInDir(f.ops(), "relay.service"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(dropInDir(f.root, "relay.service"), 0o777); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "writable"}, |
| + } { |
| + 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) |
| + 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 || len(f.restarted) != 0 || f.reloads != 0 || hasPending(f.root, "relay.service") { |
| + t.Fatalf("something was written or run: files=%v restarted=%v reloads=%d pending=%v", ents, f.restarted, f.reloads, hasPending(f.root, "relay.service")) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Round 3 P2-6: bytes after the declaration's JSON document, or a second |
| +// document, make the file invalid: no delivery and no reaping. |
| +func TestSyncUnitsRefusesTrailingBytesInTheDeclaration(t *testing.T) { |
| + for name, suffix := range map[string]string{"trailing garbage": "garbage", "second document": `{"schema":1,"units":[]}`} { |
| + 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") |
| + upsertStamped(t, reg, "relay.example.com", "relay.service", nil) |
| + // A marked drop-in for a unit the (valid part of the) file does |
| + // not name: reapable if the file were read as valid. |
| + ensureDropInDir(f.ops(), "old.service") |
| + writeDropIn(f.root, "old.service", renderDropIn(envDir, f.base, "old.service", "old.example.com")) |
| + f.declRaw(t, declarationsJSON(Declaration{Host: "relay.example.com", Account: "bab", App: "relay", Unit: "relay.service"})+suffix) |
| + out := syncOnce(t, ctx, reg, s, priv, envDir, f) |
| + if !strings.Contains(out, "bytes after the JSON document") { |
| + t.Fatalf("expected the trailing-bytes refusal, got %q", out) |
| + } |
| + if ents, _ := os.ReadDir(envDir); len(ents) != 0 || len(f.restarted) != 0 || f.reloads != 0 { |
| + t.Fatalf("delivered on an invalid declaration file: files=%v restarted=%v reloads=%d", ents, f.restarted, f.reloads) |
| + } |
| + if _, exists, _, _ := readDropIn(f.ops(), "old.service"); !exists { |
| + t.Fatal("reaped on an invalid declaration file") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/rootstate/file_linux.go b/internal/rootstate/file_linux.go| index 2c5790086..34a2db4ac 100644 |
| --- a/internal/rootstate/file_linux.go |
| +++ b/internal/rootstate/file_linux.go |
| @@ -3,6 +3,7 @@ package rootstate |
| import ( |
| "os" |
| "path/filepath" |
| + "strings" |
| "github.com/carlosframework/platform/internal/safefile" |
| "golang.org/x/sys/unix" |
| @@ -29,6 +30,69 @@ func OpenTrustedFile(path string) (*os.File, error) { |
| return f, nil |
| } |
| +// OpenTrustedDirFrom is Open's walk from anchor to dir, trusting the |
| +// ANCHOR's owner: every component below the anchor is opened by directory |
| +// descriptor with O_NOFOLLOW, and each, the anchor included, must be a |
| +// directory owned by that owner and writable by neither group nor others |
| +// (trusted). Production anchors at "/" (owner root), which is exactly |
| +// OpenTrustedFile's chain; a test anchors at a directory it owns. The |
| +// returned descriptor is dir's. |
| +func OpenTrustedDirFrom(anchor, dir string) (*os.File, error) { |
| + if !filepath.IsAbs(anchor) || filepath.Clean(anchor) != anchor || !filepath.IsAbs(dir) || filepath.Clean(dir) != dir { |
| + return nil, os.ErrPermission |
| + } |
| + rel, err := filepath.Rel(anchor, dir) |
| + if err != nil || rel == ".." || strings.HasPrefix(rel, "../") { |
| + return nil, os.ErrPermission |
| + } |
| + root, err := os.OpenFile(anchor, os.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW, 0) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer root.Close() |
| + var st unix.Stat_t |
| + if err := unix.Fstat(int(root.Fd()), &st); err != nil { |
| + return nil, err |
| + } |
| + var parts []string |
| + if rel != "." { |
| + parts = strings.Split(rel, "/") |
| + } |
| + s, err := descend(root, parts, false, true, st.Uid) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return s.(*directory).file, nil |
| +} |
| + |
| +// OpenTrustedFileFrom is OpenTrustedFile anchored at anchor: the file's |
| +// directory through OpenTrustedDirFrom, then the file itself opened by |
| +// descriptor, a regular file with one link owned by the anchor's owner |
| +// and writable by neither group nor others. |
| +func OpenTrustedFileFrom(anchor, path string) (*os.File, error) { |
| + if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" { |
| + return nil, os.ErrPermission |
| + } |
| + d, err := OpenTrustedDirFrom(anchor, filepath.Dir(path)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer d.Close() |
| + var st unix.Stat_t |
| + if err := unix.Fstat(int(d.Fd()), &st); err != nil { |
| + return nil, err |
| + } |
| + f, err := safefile.OpenFileAt(int(d.Fd()), filepath.Base(path), os.O_RDONLY, 0) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err := trusted(int(f.Fd()), st.Uid, unix.S_IFREG); err != nil { |
| + f.Close() |
| + return nil, err |
| + } |
| + return f, nil |
| +} |
| + |
| func Identity(f *os.File) (FileIdentity, error) { |
| var st unix.Stat_t |
| if err := unix.Fstat(int(f.Fd()), &st); err != nil { |
diff --git a/internal/rootstate/file_other.go b/internal/rootstate/file_other.go| index abc11ebca..326be62a1 100644 |
| --- a/internal/rootstate/file_other.go |
| +++ b/internal/rootstate/file_other.go |
| @@ -6,6 +6,10 @@ import "os" |
| func OpenTrustedFile(string) (*os.File, error) { return nil, os.ErrPermission } |
| +func OpenTrustedDirFrom(string, string) (*os.File, error) { return nil, os.ErrPermission } |
| + |
| +func OpenTrustedFileFrom(string, string) (*os.File, error) { return nil, os.ErrPermission } |
| + |
| func Identity(*os.File) (FileIdentity, error) { return FileIdentity{}, os.ErrPermission } |
| func CheckPublicConfig(*os.File) error { return os.ErrPermission } |