carlos / platform Public

host: named-units install takes the strict gate and guard rule

InstallNamedUnits now runs validateForInstall (appconfig and the strict
namedunits reading), then the console guard rule against a trusted read
of the guard marker, then the lock, then installNamedUnitsLocked, which
Task 4 reuses under the lock. proofnamed.go keeps its own marker read and
binding evidence and shares only the pure guardNames match.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f72067672c1b8136abe3132d36da9d3ac906620a parent 0f4da53
5 files changed, +409 −12
  • internal/host/proofnamed.go +2 −3
  • internal/host/proofnamed_linux_test.go +45 −0
  • internal/host/unitops.go +122 −9
  • internal/host/unitops_guard_linux_test.go +176 −0
  • internal/host/unitops_test.go +64 −0
diff --git a/internal/host/proofnamed.go b/internal/host/proofnamed.go
index afe94c626..446f6cfed 100644
--- a/internal/host/proofnamed.go
+++ b/internal/host/proofnamed.go
@@ -107,12 +107,11 @@ func (s *proofBindingSource) record(ctx context.Context, host string) (proofReco
} else if !errors.Is(err, os.ErrNotExist) {
return proofRecord{}, err
}
- marker := filepath.Join(s.optDir, "system", "guard", "console-ready.json")
- console, consoleErr := add(marker)
+ console, consoleErr := add(consoleReadyMarker(s.optDir))
if consoleErr != nil && !errors.Is(consoleErr, os.ErrNotExist) {
return proofRecord{}, consoleErr
}
- guarded := consoleErr == nil && string(console) == release.LiveLink(s.optDir, host)
+ guarded := consoleErr == nil && guardNames(console, s.optDir, host)
execPath := release.LiveLink(s.optDir, host)
if guarded {
dropin := filepath.Join(s.unitDirs[0], "console.service.d", "90-host-floor.conf")
diff --git a/internal/host/proofnamed_linux_test.go b/internal/host/proofnamed_linux_test.go
index 153115735..f941ed153 100644
--- a/internal/host/proofnamed_linux_test.go
+++ b/internal/host/proofnamed_linux_test.go
@@ -207,3 +207,48 @@ func TestPlan14NamedUnitsWithoutDeploymentRecord(t *testing.T) {
})
}
}
+
+// proofnamed keeps its own read of the console guard marker: the marker's
+// file identity feeds the binding source, so a marker replaced by a new
+// inode with the same bytes still changes the revision (Astra plan R2 #1).
+func TestProofNamedMarkerNewInodeChangesBindingSource(t *testing.T) {
+ opt, units := t.TempDir(), t.TempDir()
+ const host = "console.example.com"
+ s := &proofBindingSource{store: release.NewDirStore(t.TempDir()), namedPath: filepath.Join(t.TempDir(), "named-units.json"), optDir: opt, openFile: os.Open, unitDirs: []string{units}}
+ live := release.LiveLink(opt, host)
+ marker := filepath.Join(opt, "system", "guard", "console-ready.json")
+ dropin := filepath.Join(units, "console.service.d", "90-host-floor.conf")
+ for path, body := range map[string]string{marker: live, dropin: hostfloor.ConsoleGuardDropIn(live)} {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before, err := s.record(t.Context(), host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !before.local || before.record.Unit != "console.service" || before.execPath != "/opt/carlos/system/guard/carlos" {
+ t.Fatalf("the marker did not guard the host: %+v", before)
+ }
+ again, err := s.record(t.Context(), host)
+ if err != nil || again.revision != before.revision {
+ t.Fatalf("an unchanged marker changed the revision: %v", err)
+ }
+ tmp := marker + ".new"
+ if err := os.WriteFile(tmp, []byte(live), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(tmp, marker); err != nil {
+ t.Fatal(err)
+ }
+ after, err := s.record(t.Context(), host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if after.revision == before.revision {
+ t.Fatal("a marker with the same bytes on a new inode left the binding source unchanged")
+ }
+}
diff --git a/internal/host/unitops.go b/internal/host/unitops.go
index 4c960b3ba..e6c4477dc 100644
--- a/internal/host/unitops.go
+++ b/internal/host/unitops.go
@@ -7,13 +7,18 @@ package host
import (
"bytes"
"context"
+ "errors"
"fmt"
+ "io"
"log"
"os"
"path/filepath"
"strings"
"github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/namedunits"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rootstate"
"github.com/carlosframework/platform/internal/systemd"
)
@@ -38,16 +43,19 @@ func productionUnitOps(envDir string) *appconfig.UnitOps {
}
// InstallNamedUnits is the one carlos writer of the declaration file
-// (Paul's ruling of 2026-10-28, serialisation): it validates raw with the
-// decoder the pass reads with, takes the same config-sync flock SyncUnits
-// holds for a whole pass, and replaces the file atomically: a temp file
-// in the same directory, mode 0644 (root-owned, since the verb runs as
-// root), fsync, rename, fsync of the directory. A pass and an install
-// therefore never interleave: the pass's snapshot is the file for the
-// whole pass. envDir is where the lock lives (appconfig.DefaultEnvDir in
-// production); dst is the declaration path.
+// (Paul's ruling of 2026-10-28, serialisation). It refuses raw unless both
+// readers accept it (validateForInstall) and, on a box whose console guard
+// names a host, unless that host stays console's (checkGuardRule); then it
+// takes the same config-sync flock SyncUnits holds for a whole pass and
+// replaces the file atomically (installNamedUnitsLocked). A pass and an
+// install therefore never interleave: the pass's snapshot is the file for
+// the whole pass. envDir is where the lock lives (appconfig.DefaultEnvDir
+// in production); dst is the declaration path.
func InstallNamedUnits(envDir, dst string, raw []byte) error {
- if err := appconfig.ValidateDeclarations(raw); err != nil {
+ if err := validateForInstall(raw); err != nil {
+ return err
+ }
+ if err := checkInstallGuard(release.OptDir(), dst, raw); err != nil {
return err
}
unlock, err := lockConfigSync(envDir + "/.sync")
@@ -55,6 +63,47 @@ func InstallNamedUnits(envDir, dst string, raw []byte) error {
return fmt.Errorf("config-sync lock: %w", err)
}
defer unlock()
+ return installNamedUnitsLocked(dst, raw)
+}
+
+// validateForInstall: both readers of the declaration file must accept
+// raw, config delivery's (appconfig) and the release path's strict one
+// (namedunits). The operator's off-box put runs this alone; the guard
+// rule needs the box.
+func validateForInstall(raw []byte) error {
+ if err := appconfig.ValidateDeclarations(raw); err != nil {
+ return err
+ }
+ return namedunits.ValidateStrict(raw)
+}
+
+// checkInstallGuard is the box's console guard rule for an install of raw
+// (already validated) over dst. The guarded host is looked for among the
+// hosts of the candidate and of the current file; the current file is read
+// best-effort, since only the candidate's entries can break the rule.
+func checkInstallGuard(optDir, dst string, raw []byte) error {
+ entries, err := namedunits.Decode(raw)
+ if err != nil {
+ return err
+ }
+ candidates := namedunits.Hosts(entries)
+ if current, err := os.ReadFile(dst); err == nil {
+ if prior, err := namedunits.Decode(current); err == nil {
+ candidates = append(candidates, namedunits.Hosts(prior)...)
+ }
+ }
+ host, guarded, err := consoleGuardHost(optDir, candidates)
+ if err != nil {
+ return fmt.Errorf("console guard marker: %w", err)
+ }
+ return checkGuardRule(entries, host, guarded)
+}
+
+// installNamedUnitsLocked writes raw to dst atomically: a temp file in the
+// same directory, mode 0644 (root-owned, since the verb runs as root),
+// fsync, rename, fsync of the directory. The caller holds the config-sync
+// lock and has validated raw.
+func installNamedUnitsLocked(dst string, raw []byte) error {
tmp := dst + ".tmp"
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
if err != nil {
@@ -90,6 +139,70 @@ func InstallNamedUnits(envDir, dst string, raw []byte) error {
return dir.Sync()
}
+// consoleReadyMarker is the console guard's marker: its bytes are the
+// LiveLink of the host the guard serves console for.
+func consoleReadyMarker(optDir string) string {
+ return filepath.Join(optDir, "system", "guard", "console-ready.json")
+}
+
+// guardNames is the pure match proofnamed.go does over marker bytes it has
+// already read: the marker names host when it is host's LiveLink.
+func guardNames(marker []byte, optDir, host string) bool {
+ return string(marker) == release.LiveLink(optDir, host)
+}
+
+// openConsoleGuardMarker is the trusted opener consoleGuardHost reads the
+// marker with; a variable so tests can anchor the trust checks at a
+// directory they own.
+var openConsoleGuardMarker = rootstate.OpenTrustedFile
+
+// consoleGuardHost is for the install callers only; proofnamed.go keeps its
+// own read, its error handling and its binding evidence. A trusted read of
+// the marker: absent is ok=false with no error; any other failure (a
+// symlink, a wrong owner, a group-writable file or directory) is err, and
+// the caller refuses the install. Present, the host is the candidate whose
+// LiveLink the marker equals; ok=false when none does.
+func consoleGuardHost(optDir string, candidates []string) (host string, ok bool, err error) {
+ f, err := openConsoleGuardMarker(consoleReadyMarker(optDir))
+ if errors.Is(err, os.ErrNotExist) {
+ return "", false, nil
+ }
+ if err != nil {
+ return "", false, err
+ }
+ defer f.Close()
+ marker, err := io.ReadAll(io.LimitReader(f, rootstate.MaxRecord+1))
+ if err != nil {
+ return "", false, err
+ }
+ if len(marker) > rootstate.MaxRecord {
+ return "", false, os.ErrPermission
+ }
+ for _, h := range candidates {
+ if guardNames(marker, optDir, h) {
+ return h, true, nil
+ }
+ }
+ return "", false, nil
+}
+
+// checkGuardRule: on a guarded box the guarded host's entry, when the file
+// has one, must be console's own (proofnamed.go refuses anything else).
+func checkGuardRule(entries []namedunits.Entry, guardHost string, guarded bool) error {
+ if !guarded {
+ return nil
+ }
+ for _, u := range entries {
+ if u.Host != guardHost {
+ continue
+ }
+ if u.Unit != "console.service" || u.App != "console" || u.Account != "" {
+ return fmt.Errorf("named units: host %s is the console guard's host and must be app console, unit console.service, no account", u.Host)
+ }
+ }
+ return nil
+}
+
// RunSystemNamedUnits is `carlos system named-units install <file>`: the
// root-only verb that installs a validated declaration file under the
// config-sync lock. Provisioning writes the file before the agent starts,
diff --git a/internal/host/unitops_guard_linux_test.go b/internal/host/unitops_guard_linux_test.go
new file mode 100644
index 000000000..69915691d
--- /dev/null
+++ b/internal/host/unitops_guard_linux_test.go
@@ -0,0 +1,176 @@
+package host
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rootstate"
+)
+
+// consoleGuardAt points the install path at a fresh opt directory and
+// reads the marker with the trusted opener anchored there, so the real
+// symlink, owner and mode checks run without root. Not parallel: it sets
+// CARLOS_OPT_DIR and the opener variable.
+func consoleGuardAt(t *testing.T) string {
+ t.Helper()
+ opt := t.TempDir()
+ // t.TempDir honours the umask; the trust checks refuse a
+ // group-writable anchor, so set the mode explicitly.
+ if err := os.Chmod(opt, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("CARLOS_OPT_DIR", opt)
+ prior := openConsoleGuardMarker
+ openConsoleGuardMarker = func(path string) (*os.File, error) { return rootstate.OpenTrustedFileFrom(opt, path) }
+ t.Cleanup(func() { openConsoleGuardMarker = prior })
+ return opt
+}
+
+func writeConsoleGuardMarker(t *testing.T, opt string, body []byte) string {
+ t.Helper()
+ marker := filepath.Join(opt, "system", "guard", "console-ready.json")
+ if err := os.MkdirAll(filepath.Dir(marker), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(marker, body, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range []string{filepath.Dir(filepath.Dir(marker)), filepath.Dir(marker)} {
+ if err := os.Chmod(p, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.Chmod(marker, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return marker
+}
+
+func TestConsoleGuardHostRefusesUntrustedMarker(t *testing.T) {
+ candidates := []string{"a.example.com", "b.example.com"}
+ t.Run("absent", func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ host, ok, err := consoleGuardHost(opt, candidates)
+ if err != nil || ok || host != "" {
+ t.Fatalf("absent marker: %q %v %v", host, ok, err)
+ }
+ })
+ t.Run("names a candidate", func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ writeConsoleGuardMarker(t, opt, []byte(release.LiveLink(opt, "b.example.com")))
+ host, ok, err := consoleGuardHost(opt, candidates)
+ if err != nil || !ok || host != "b.example.com" {
+ t.Fatalf("matching marker: %q %v %v", host, ok, err)
+ }
+ })
+ t.Run("names no candidate", func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ writeConsoleGuardMarker(t, opt, []byte(release.LiveLink(opt, "c.example.com")))
+ host, ok, err := consoleGuardHost(opt, candidates)
+ if err != nil || ok || host != "" {
+ t.Fatalf("unmatched marker: %q %v %v", host, ok, err)
+ }
+ })
+ for _, attack := range []string{"symlink", "group-writable", "hard link", "group-writable directory"} {
+ t.Run(attack, func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ body := []byte(release.LiveLink(opt, "a.example.com"))
+ marker := writeConsoleGuardMarker(t, opt, body)
+ switch attack {
+ case "symlink":
+ real := filepath.Join(opt, "real.json")
+ if err := os.WriteFile(real, body, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(marker); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(real, marker); err != nil {
+ t.Fatal(err)
+ }
+ case "group-writable":
+ if err := os.Chmod(marker, 0o664); err != nil {
+ t.Fatal(err)
+ }
+ case "hard link":
+ if err := os.Link(marker, filepath.Join(opt, "second-name")); err != nil {
+ t.Fatal(err)
+ }
+ case "group-writable directory":
+ if err := os.Chmod(filepath.Dir(marker), 0o775); err != nil {
+ t.Fatal(err)
+ }
+ }
+ host, ok, err := consoleGuardHost(opt, []string{"a.example.com"})
+ if err == nil || errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("an untrusted marker read as %q ok=%v err=%v; want a refusing error", host, ok, err)
+ }
+ })
+ }
+}
+
+// The install path applies the guard rule to the candidate file: a box
+// whose console guard names a host keeps that host on console.service.
+func TestInstallNamedUnitsKeepsTheConsoleGuard(t *testing.T) {
+ const shopA = `{"host":"a.example.com","app":"shop","unit":"shop.service","addr":"127.0.0.1:1","health":{"path":"/"}}`
+ const consoleA = `{"host":"a.example.com","app":"console","unit":"console.service","addr":"127.0.0.1:8090","health":{"path":"/healthz"}}`
+ const shopB = `{"host":"b.example.com","app":"shop","unit":"shop-b.service","addr":"127.0.0.1:2","health":{"path":"/"}}`
+ file := func(entries ...string) []byte {
+ raw := `{"schema":1,"units":[`
+ for i, e := range entries {
+ if i > 0 {
+ raw += ","
+ }
+ raw += e
+ }
+ return []byte(raw + `]}`)
+ }
+ refused := func(t *testing.T, dir, dst string, raw []byte) {
+ t.Helper()
+ if err := InstallNamedUnits(dir, dst, raw); err == nil {
+ t.Fatal("install succeeded")
+ }
+ if _, err := os.Stat(dst); !os.IsNotExist(err) {
+ t.Fatalf("dst exists after a refused install: %v", err)
+ }
+ }
+ t.Run("guarded host as shop", func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ writeConsoleGuardMarker(t, opt, []byte(release.LiveLink(opt, "a.example.com")))
+ dir := t.TempDir()
+ refused(t, dir, filepath.Join(dir, "named-units.json"), file(shopA, shopB))
+ })
+ t.Run("guarded host as console", func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ writeConsoleGuardMarker(t, opt, []byte(release.LiveLink(opt, "a.example.com")))
+ dir := t.TempDir()
+ dst := filepath.Join(dir, "named-units.json")
+ if err := InstallNamedUnits(dir, dst, file(consoleA, shopB)); err != nil {
+ t.Fatal(err)
+ }
+ })
+ t.Run("guarded host only in the current file", func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ writeConsoleGuardMarker(t, opt, []byte(release.LiveLink(opt, "a.example.com")))
+ dir := t.TempDir()
+ dst := filepath.Join(dir, "named-units.json")
+ if err := os.WriteFile(dst, file(consoleA), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := InstallNamedUnits(dir, dst, file(shopB)); err != nil {
+ t.Fatal(err)
+ }
+ })
+ t.Run("untrusted marker", func(t *testing.T) {
+ opt := consoleGuardAt(t)
+ marker := writeConsoleGuardMarker(t, opt, []byte(release.LiveLink(opt, "a.example.com")))
+ if err := os.Chmod(marker, 0o666); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ refused(t, dir, filepath.Join(dir, "named-units.json"), file(consoleA, shopB))
+ })
+}
diff --git a/internal/host/unitops_test.go b/internal/host/unitops_test.go
index 03fe5fa1d..c38c61a75 100644
--- a/internal/host/unitops_test.go
+++ b/internal/host/unitops_test.go
@@ -8,6 +8,8 @@ import (
"time"
"github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/namedunits"
+ "github.com/carlosframework/platform/internal/provision"
)
func TestParseSystemctlShowBatched(t *testing.T) {
@@ -74,6 +76,7 @@ func TestProductionUnitOpsDeclarationIsTheReleasePathsFile(t *testing.T) {
// an install blocks until the pass releases it; it validates before it
// takes the lock, and the file lands atomically at 0644.
func TestInstallNamedUnitsWaitsForTheConfigSyncLock(t *testing.T) {
+ noConsoleGuard(t)
dir := t.TempDir()
dst := filepath.Join(dir, "named-units.json")
body := []byte(`{"schema":1,"units":[{"host":"relay.example.com","account":"bab","app":"relay","unit":"relay.service","addr":"127.0.0.1:8451","health":{"path":"/ready"}}]}`)
@@ -117,3 +120,64 @@ func TestInstallNamedUnitsWaitsForTheConfigSyncLock(t *testing.T) {
t.Fatal("temp file left behind")
}
}
+
+// The installer refuses what the release path's strict reading refuses:
+// appconfig alone tolerates an unknown field and an entry without addr,
+// and a file root then installed would cost the host its proof binding.
+func TestInstallNamedUnitsRefusesWhatTheReleasePathRefuses(t *testing.T) {
+ for name, body := range map[string]string{
+ "unknown field": `{"schema":1,"units":[{"host":"a.example.com","app":"shop","unit":"shop.service","addr":"127.0.0.1:1","health":{"path":"/"},"extra":1}]}`,
+ "no addr": `{"schema":1,"units":[{"host":"a.example.com","app":"shop","unit":"shop.service","health":{"path":"/"}}]}`,
+ } {
+ t.Run(name, func(t *testing.T) {
+ noConsoleGuard(t)
+ dir := t.TempDir()
+ dst := filepath.Join(dir, "named-units.json")
+ if err := InstallNamedUnits(dir, dst, []byte(body)); err == nil {
+ t.Fatal("installed a file the release path refuses")
+ }
+ if _, err := os.Stat(dst); !os.IsNotExist(err) {
+ t.Fatalf("dst exists after a refused install: %v", err)
+ }
+ })
+ }
+}
+
+// noConsoleGuard makes the box's console-guard marker absent for one test,
+// so an install never reads the machine's real /opt/carlos. The opener is
+// a package variable: tests using it must not run in parallel.
+func noConsoleGuard(t *testing.T) {
+ t.Helper()
+ prior := openConsoleGuardMarker
+ openConsoleGuardMarker = func(string) (*os.File, error) { return nil, os.ErrNotExist }
+ t.Cleanup(func() { openConsoleGuardMarker = prior })
+}
+
+func TestCheckGuardRuleRefusesNonConsoleForGuardedHost(t *testing.T) {
+ shopA := namedunits.Entry{Host: "a.example.com", App: "shop", Unit: "shop.service", Addr: "127.0.0.1:1", Health: &provision.Health{Path: "/"}}
+ consoleA := namedunits.Entry{Host: "a.example.com", App: "console", Unit: "console.service", Addr: "127.0.0.1:8090", Health: &provision.Health{Path: "/healthz"}}
+ shopB := namedunits.Entry{Host: "b.example.com", App: "shop", Unit: "shop-b.service", Addr: "127.0.0.1:2", Health: &provision.Health{Path: "/"}}
+ if err := checkGuardRule([]namedunits.Entry{shopA, shopB}, "a.example.com", true); err == nil {
+ t.Fatal("the guarded host was mapped to a non-console unit")
+ }
+ if err := checkGuardRule([]namedunits.Entry{consoleA, shopB}, "a.example.com", true); err != nil {
+ t.Fatalf("the guarded host as console: %v", err)
+ }
+ accounted := consoleA
+ accounted.Account = "bab"
+ if err := checkGuardRule([]namedunits.Entry{accounted}, "a.example.com", true); err == nil {
+ t.Fatal("the guarded console entry carried an account")
+ }
+ otherApp := consoleA
+ otherApp.App = "shop"
+ if err := checkGuardRule([]namedunits.Entry{otherApp}, "a.example.com", true); err == nil {
+ t.Fatal("console.service under another app passed for the guarded host")
+ }
+ // Other hosts are not the guard's business, and an unguarded box has no rule.
+ if err := checkGuardRule([]namedunits.Entry{shopB}, "a.example.com", true); err != nil {
+ t.Fatalf("guarded host absent: %v", err)
+ }
+ if err := checkGuardRule([]namedunits.Entry{shopA, shopB}, "", false); err != nil {
+ t.Fatalf("unguarded box: %v", err)
+ }
+}