carlos / platform Public

fix: managed admission discovery, gated publication, trusted reads

Task 3 fix round 1 (Astra R1, Fable R1).
- Ready leg: a ready.json GET only in a tick where root just answered
  managed and not admitted; after any relay and whenever root is
  unreachable the next action is a root query, never a remote read.
- Gated publication (T3-Q3 reversed): bootstrap, system apply,
  ensureSystemUnits, InstallNamedUnits and managed boot install the
  admission drop-ins for the unit set being published, then reload,
  before any unit file; any failure publishes nothing. Classification
  is default-gated: every unit not in MaintenanceUnits.
- Trusted reads/writes: the declaration and drop-in path go through the
  mb* descriptor walk; drop-in installation moves to host.
- Declared names whose drop-in scope reaches a maintenance unit
  (prefix forms) are refused.
- One refused join path (identity error, group admission on a managed
  box), decided before admission is armed; no Fatalf.
- Root tests drop CARLOS_MANAGED_ROOT_TEST (T3-Q1); the control commit
  test makes /run/carlos-control and checks the read-only refusal.
- Production-composition witnesses; once-only boot pass; root door
  answers 5xx for I/O errors.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 82bade12d37ad42b4ed26bb21d544a319f3161b3 parent 2f64ba1
24 files changed, +1,404 −376
  • internal/appconfig/unitsync_test.go +39 −0
  • internal/host/agent.go +17 −23
  • internal/host/bootstrap.go +16 −0
  • internal/host/managedboot.go +17 −13
  • internal/host/managedboot_linux_test.go +20 −11
  • internal/host/managedidentity_fake_test.go +27 −0
  • internal/host/managedjoin.go +158 −82
  • internal/host/managedjoin_fix1_test.go +284 −0
  • internal/host/managedjoin_root_linux_test.go +92 −10
  • internal/host/managedjoin_test.go +77 −44
  • internal/host/managedunits.go +102 −49
  • internal/host/managedunits_fix1_test.go +317 −0
  • internal/host/managedunits_test.go +34 −27
  • internal/host/namedrecovery_pass.go +16 −5
  • internal/host/systemapply.go +20 −0
  • internal/host/systemunits.go +19 −17
  • internal/host/unitops.go +3 −2
  • internal/instancectl/managedadmit.go +9 −2
  • internal/instancectl/managedadmit_linux_test.go +24 −1
  • internal/managedboot/admission.go +20 −3
  • internal/managedboot/admission_linux.go +1 −1
  • internal/managedboot/identity.go +6 −0
  • internal/managedboot/units.go +84 −82
  • internal/managedboot/userdata_rootrunner_linux_test.go +2 −4
diff --git a/internal/appconfig/unitsync_test.go b/internal/appconfig/unitsync_test.go
index 31852d045..add58f392 100644
--- a/internal/appconfig/unitsync_test.go
+++ b/internal/appconfig/unitsync_test.go
@@ -1626,3 +1626,42 @@ func TestSyncUnitsRefusesAnOrdinaryRowWhoseHostIsDeclared(t *testing.T) {
t.Fatalf("the ordinary writer wrote a declared host: restarts=%d", hostRestarts)
}
}
+
+// TestSyncUnitsGatedRestartRetriesAfterAdmission is the real config-sync
+// composition under a managed box's root gate (internal/host
+// managedGatedUnitOps refuses Restart while root has not admitted the box):
+// while joining the named unit's restart is refused, nothing runs and the
+// pending marker stays; once admitted the next pass restarts it and clears.
+func TestSyncUnitsGatedRestartRetriesAfterAdmission(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)
+ joining := true
+ ops := f.ops()
+ restart := ops.Restart
+ ops.Restart = func(unit string) error {
+ if joining {
+ return errors.New("managed box is joining its fleet: root has not admitted it")
+ }
+ return restart(unit)
+ }
+ pass := func() {
+ captureStdout(t, func() {
+ _ = SyncUnits(ctx, reg, s, priv, envDir, noHostRestart(t), nil, ops)
+ })
+ }
+ pass()
+ if len(f.restarted) != 0 || !hasPending(f.root, "relay.service") {
+ t.Fatalf("joining: restarted=%v pending=%v", f.restarted, hasPending(f.root, "relay.service"))
+ }
+ pass()
+ if len(f.restarted) != 0 || !hasPending(f.root, "relay.service") {
+ t.Fatal("joining: a second pass restarted or dropped the owed restart")
+ }
+ joining = false
+ pass()
+ if len(f.restarted) != 1 || f.restarted[0] != "relay.service" || hasPending(f.root, "relay.service") {
+ t.Fatalf("admitted: restarted=%v pending=%v", f.restarted, hasPending(f.root, "relay.service"))
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 25706b076..72ba8a542 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -268,26 +268,22 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if err != nil {
log.Fatal(err)
}
- admission := newFixedAdmission(os.Getenv, lbhealth.Default)
- if err = configureGroupAdmission(agentCtx, admission, groupBoot); err != nil {
- log.Fatal(err)
+ // Managed fleets 2b-2, decided before any admission is armed: a managed
+ // box takes tenant admission from root alone (managedJoin) and never
+ // builds fixed group admission. An identity that fails its checks, or
+ // group admission configured on a managed box, is a refused join: every
+ // admission predicate closed, the agent and edge still running. nil on a
+ // BYO box, where everything below is as on main.
+ join := armManagedJoin("/", instancectl.NewClient(controlsock.Path), os.Getenv, groupBoot != nil, log.Printf)
+ var admission *fixedAdmission
+ if join == nil {
+ admission = newFixedAdmission(os.Getenv, lbhealth.Default)
+ if err = configureGroupAdmission(agentCtx, admission, groupBoot); err != nil {
+ log.Fatal(err)
+ }
}
admissionOption := wireAgentAdmission(admission, nil, nil, nil)
- // Managed fleets 2b-2: a managed box takes tenant admission from root
- // alone (managedJoin); nil on a BYO box, where everything below is as
- // on main.
- join, err := newManagedJoin(instancectl.NewClient(controlsock.Path))
- if err != nil {
- log.Fatalf("agent: managed box identity: %v", err)
- }
if join != nil {
- if admission != nil {
- // A configuration error: no fixed admission on a managed box,
- // and the join never opens.
- log.Print(errManagedGroupAdmission)
- admission = nil
- join.refused = true
- }
armedManagedJoin.Store(join)
admissionOption = join.bind(nil, nil)
}
@@ -905,14 +901,12 @@ func runAgent(args []string, buildClaims ClaimFactory) {
return
}
if join != nil {
- // A managed box runs the boot pass once root admits it
- // (managedJoin.onAdmit), never while joining.
- join.setOnAdmit(func() {
+ // A managed box runs the boot pass exactly once, when root
+ // admits it (now, if it already has), never while joining.
+ join.whenAdmitted(func() {
go runWorkerBootPassAfterAdmission(startupCtx, nil, reg.List, svc.WakeWorker)
})
- if join.Joining() {
- return
- }
+ return
}
runWorkerBootPassAfterAdmission(startupCtx, admission, reg.List, svc.WakeWorker)
}()
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go
index 0d766dd73..49c6ea3fe 100644
--- a/internal/host/bootstrap.go
+++ b/internal/host/bootstrap.go
@@ -552,6 +552,22 @@ func bootstrapWithGroup(root string, consumers []string, planJSON, group bool) e
if err != nil {
return err
}
+ // Managed fleets 2b-2 (decisions rule 12): on a managed box this
+ // binary's units are gated, durably and reloaded, before any of their
+ // files is written; a failure writes no unit. On the live root an
+ // identity that fails its checks fails the bootstrap. A staging tree
+ // (-root <dir>, what system apply stages into) is no box: it is gated
+ // only when it holds a valid managed identity of its own. BYO: no-op.
+ if _, managed, idErr := managedIdentityAt(root); live || (managed && idErr == nil) {
+ if _, err := managedGateUnits(root, names, nil, func() error {
+ if !live {
+ return nil
+ }
+ return systemctl("daemon-reload")
+ }); err != nil {
+ return err
+ }
+ }
for _, name := range names {
if group && groupAutomaticUnit(name) {
continue
diff --git a/internal/host/managedboot.go b/internal/host/managedboot.go
index 328f2c4de..2116aa436 100644
--- a/internal/host/managedboot.go
+++ b/internal/host/managedboot.go
@@ -196,14 +196,9 @@ func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) (err
if err = m.step("key"); err != nil {
return err
}
- // Before any workload unit file exists: bootstrap writes them.
- if _, err = managedboot.InstallAdmissionDropIns(m.p(mbSystemdDir), nil); err != nil {
- return err
- }
- if _, err = managedboot.InstallControlDropIn(m.p(mbSystemdDir)); err != nil {
- return err
- }
- if err = m.systemctl(ctx, "daemon-reload"); err != nil {
+ // Before any workload unit file exists: bootstrap writes them (and the
+ // stable binary's bootstrap gates its own set again before it does).
+ if _, err = m.gateUnits(func() error { return m.systemctl(ctx, "daemon-reload") }); err != nil {
return err
}
sha, err := m.stable(ctx, in, env)
@@ -247,16 +242,25 @@ func (m *managedBoot) completePath(ctx context.Context) error {
if err := m.scrubKnown(); err != nil {
m.logf("managed boot: scrub of cloud-init user-data copies: %v", err)
}
- a, err := managedboot.InstallAdmissionDropIns(m.p(mbSystemdDir), nil)
+ // finish reloads when a drop-in was rewritten (boot loaded the rest).
+ changed, err := m.gateUnits(nil)
if err != nil {
return err
}
- c, err := managedboot.InstallControlDropIn(m.p(mbSystemdDir))
+ _, err = m.finish(ctx, changed)
+ return err
+}
+
+// gateUnits installs the admission drop-ins for this binary's unit set and
+// the declared named units, and the control drop-in, under the box root
+// (managedGateUnitsKnown); reload, when not nil, runs after them.
+func (m *managedBoot) gateUnits(reload func() error) (bool, error) {
+ units, err := unitNames()
if err != nil {
- return err
+ return false, err
}
- _, err = m.finish(ctx, a || c)
- return err
+ changed, _, err := managedGateUnitsKnown(m.root, m.uid, units, nil, reload)
+ return changed, err
}
// finish removes the enrolment drop-in (the box no longer waits for the
diff --git a/internal/host/managedboot_linux_test.go b/internal/host/managedboot_linux_test.go
index 61d20e160..5798fb0e1 100644
--- a/internal/host/managedboot_linux_test.go
+++ b/internal/host/managedboot_linux_test.go
@@ -955,8 +955,10 @@ func TestManagedUnitClassification(t *testing.T) {
t.Fatal(err)
}
embedded := map[string]bool{}
+ var names []string
for _, e := range entries {
embedded[e.Name()] = true
+ names = append(names, e.Name())
n := 0
if slices.Contains(managedboot.WorkloadUnits, e.Name()) {
n++
@@ -968,6 +970,20 @@ func TestManagedUnitClassification(t *testing.T) {
t.Errorf("unit %s is classified %d times, want exactly once (WorkloadUnits or MaintenanceUnits)", e.Name(), n)
}
}
+ // Default-gated: the maintenance list is the allowlist, and what is
+ // gated is everything else. WorkloadUnits documents exactly that set.
+ gated, err := managedboot.GatedUnits(names, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := slices.Clone(managedboot.WorkloadUnits)
+ slices.Sort(want)
+ if !slices.Equal(gated, want) {
+ t.Errorf("gated %v, WorkloadUnits %v", gated, want)
+ }
+ if g, _ := managedboot.GatedUnits([]string{"carlos-future-thing@.service", "carlos-edge.service"}, nil); !slices.Equal(g, []string{"carlos-future-thing@.service"}) {
+ t.Errorf("a template a later binary adds is not gated by default: %v", g)
+ }
for _, u := range managedboot.WorkloadUnits {
if !strings.HasSuffix(u, "@.service") && !strings.HasSuffix(u, "@.socket") {
t.Errorf("workload unit %s is not a template", u)
@@ -981,20 +997,13 @@ func TestManagedUnitClassification(t *testing.T) {
t.Errorf("maintenance unit %s is not embedded", u)
}
}
- dir := t.TempDir()
- for _, u := range []string{"carlos-edge.service", "carlos-instance-control.socket", "../x.service", "a b.service"} {
- if _, err := managedboot.InstallAdmissionDropIns(dir, []string{u}); err == nil {
+ for _, u := range []string{"carlos-edge.service", "carlos-instance-control.socket", "../x.service", "a b.service", "carlos-.service", "carlos-instance-.service", "shop-.socket", "x.timer"} {
+ if _, err := managedboot.GatedUnits(nil, []string{u}); err == nil {
t.Errorf("named unit %q accepted", u)
}
}
- if entries, _ := os.ReadDir(dir); len(entries) != 0 {
- t.Errorf("a refused named unit wrote %d entries", len(entries))
- }
- if _, err := managedboot.InstallAdmissionDropIns(dir, []string{"shop-worker.service"}); err != nil {
- t.Fatal(err)
- }
- if b, err := os.ReadFile(filepath.Join(dir, "shop-worker.service.d", managedboot.AdmissionDropInName)); err != nil || string(b) != managedboot.AdmissionDropIn {
- t.Errorf("named unit drop-in: %q %v", b, err)
+ if g, err := managedboot.GatedUnits(nil, []string{"shop-worker.service"}); err != nil || !slices.Equal(g, []string{"shop-worker.service"}) {
+ t.Fatalf("named unit: %v %v", g, err)
}
}
diff --git a/internal/host/managedidentity_fake_test.go b/internal/host/managedidentity_fake_test.go
new file mode 100644
index 000000000..36f048da9
--- /dev/null
+++ b/internal/host/managedidentity_fake_test.go
@@ -0,0 +1,27 @@
+//go:build linux
+
+package host
+
+import (
+ "os"
+ "path/filepath"
+
+ "github.com/carlosframework/platform/internal/managedboot"
+)
+
+// Every fake root a test lays out is owned by the test's own uid, which
+// the real loader (expecting root) would read as an unsafe /etc: a managed
+// box with an error, refused (ruling T3-Q2). For the package's tests a fake
+// root is a root-owned tree: identity is loaded with the test's uid as the
+// expected owner, so a fake root without the identity file is BYO, as a
+// real root-owned BYO box is. "/" keeps the production loader. Tests of a
+// managed fake root stub managedIdentityAt themselves.
+func init() {
+ uid := os.Getuid()
+ managedIdentityAt = func(root string) (managedboot.Identity, bool, error) {
+ if root == "" || filepath.Clean(root) == "/" {
+ return managedboot.LoadIdentity(root)
+ }
+ return managedboot.LoadIdentityAs(root, managedboot.RootOwner{UID: uid})
+ }
+}
diff --git a/internal/host/managedjoin.go b/internal/host/managedjoin.go
index 7a9bdd2a3..c6633177b 100644
--- a/internal/host/managedjoin.go
+++ b/internal/host/managedjoin.go
@@ -47,77 +47,116 @@ type managedJoin struct {
door managedAdmissionDoor
joining atomic.Bool
logf func(string, ...any)
- // onAdmit runs once, after the flip: one full reconcile and the worker
- // boot pass (wired in runAgent).
- onAdmit func()
- admitMu sync.Mutex
-
- // refused is a configuration error (errManagedGroupAdmission): the box
- // stays joining and reads nothing.
- refused bool
-
- mu sync.Mutex
- read bool // the arming read happened
- lastRead time.Time
- lastSerial int64
- serialSeen bool
- rootAsked bool // root answered GET /managed-admission at least once
+
+ // refused is the one closed path (ruling T3-Q2 restated): an identity
+ // that fails its checks, or fixed group admission configured on a
+ // managed box. Set before the join is armed; every admission predicate
+ // then stays closed whatever root says, and nothing is read or relayed.
+ // The agent, edge, heartbeat and probes keep running.
+ refused bool
+ refusedWhy string
+
+ // onAdmit runs exactly once, at the flip: one full reconcile and the
+ // worker boot pass (wired in runAgent).
+ admitMu sync.Mutex
+ onAdmit func()
+ admitted bool // the flip happened (under admitMu)
+
+ mu sync.Mutex
+ read bool // the arming read happened
+ lastRead time.Time
+ lastSerial int64
+ serialSeen bool
+ rootPending bool // root's answer is owed before any remote read
+ lastRefusal time.Time
}
+// rootAnswer is one GET /managed-admission outcome.
+type rootAnswer int
+
+const (
+ rootUnknown rootAnswer = iota // the door did not answer
+ rootJoining // managed, not admitted
+ rootAdmitted
+ rootNotManaged
+)
+
// armedManagedJoin is the process's managedJoin; nil on a BYO box.
var armedManagedJoin atomic.Pointer[managedJoin]
// newManagedJoin is the agent's managedJoin, or nil on a BYO box (no
-// identity file). A managed box whose identity fails its checks is an
-// error: the agent refuses to arm tenant work rather than guess.
-func newManagedJoin(c *instancectl.Client) (*managedJoin, error) {
+// identity file). A managed box whose identity fails its checks gets a
+// refused join: closed for good, never a crash.
+func newManagedJoin(c *instancectl.Client) *managedJoin {
return newManagedJoinAt("/", c, log.Printf)
}
-func newManagedJoinAt(root string, door managedAdmissionDoor, logf func(string, ...any)) (*managedJoin, error) {
+func newManagedJoinAt(root string, door managedAdmissionDoor, logf func(string, ...any)) *managedJoin {
id, managed, err := managedIdentityAt(root)
if !managed {
- return nil, nil
+ return nil
}
+ j := &managedJoin{door: door, logf: logf}
+ j.joining.Store(true)
if err != nil {
- return nil, err
+ j.refuse("the managed box identity fails its checks (" + err.Error() + ")")
+ return j
}
pub, err := base64.StdEncoding.DecodeString(id.ReleasePubkey)
if err != nil || len(pub) != ed25519.PublicKeySize {
- return nil, errors.New("managed box identity carries no usable release key")
+ j.refuse("the managed box identity carries no usable release key")
+ return j
}
- j := &managedJoin{id: id, pub: pub, door: door, logf: logf}
- j.joining.Store(true)
+ j.id, j.pub = id, pub
ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineControl)
defer cancel()
- if !j.askRoot(ctx) {
+ switch j.askRoot(ctx) {
+ case rootAdmitted:
+ j.markAdmitted()
+ case rootUnknown:
+ j.rootPending = true
+ fallthrough
+ default:
j.logf("agent: this managed box is joining its fleet. tenant work stays closed until root admits it")
}
- return j, nil
+ return j
}
-// askRoot reads root's admission; only an admitted answer changes anything.
-func (j *managedJoin) askRoot(ctx context.Context) bool {
+// armManagedJoin is runAgent's decision, before any admission is armed: a
+// managed box gets a join and never fixed group admission; group
+// admission or group configuration on a managed box refuses the join.
+func armManagedJoin(root string, door managedAdmissionDoor, getenv func(string) string, groupConfigured bool, logf func(string, ...any)) *managedJoin {
+ j := newManagedJoinAt(root, door, logf)
+ if j != nil && (getenv("CARLOS_GROUP_ADMISSION") == "1" || groupConfigured) {
+ j.refuse(errManagedGroupAdmission.Error())
+ }
+ return j
+}
+
+func (j *managedJoin) refuse(why string) {
+ j.refused, j.refusedWhy = true, why
+ j.logf("agent: ERROR managed box admission refused: %s. tenant work stays closed; status, probes and updates keep running", why)
+}
+
+// askRoot is one root-door query; only an admitted answer opens the box.
+func (j *managedJoin) askRoot(ctx context.Context) rootAnswer {
managed, admitted, err := j.door.ManagedAdmission(ctx)
- if err != nil {
+ switch {
+ case err != nil:
j.logf("agent: managed admission: root door: %v", err)
- return false
- }
- j.rootAsked = true
- if !managed {
+ return rootUnknown
+ case !managed:
j.logf("agent: managed admission: root reports no managed identity; staying closed")
- return false
- }
- if admitted {
- j.joining.Store(false)
- return true
+ return rootNotManaged
+ case admitted:
+ return rootAdmitted
}
- return false
+ return rootJoining
}
-// Joining is true until root reports the box admitted. Nil-safe: a BYO
-// box is never joining.
-func (j *managedJoin) Joining() bool { return j != nil && j.joining.Load() }
+// Joining is true until root reports the box admitted, and for good on a
+// refused join. Nil-safe: a BYO box is never joining.
+func (j *managedJoin) Joining() bool { return j != nil && (j.refused || j.joining.Load()) }
// TenantAdmitted is the activator and edge hook: no tenant work while joining.
func (j *managedJoin) TenantAdmitted() bool { return !j.Joining() }
@@ -130,17 +169,28 @@ func (j *managedJoin) TenantAdmissionExempt(registry.Route) bool { return false
func (j *managedJoin) TenantAdmissionStarting() bool { return true }
// readyLeg is the joining box's only ready.json reader, asked every fast
-// tick after the serial read. It returns at once when admitted. While
-// joining it reads at arming, once per changed serial, and otherwise at
-// most once per managedReadyBackstop (a failed serial read leaves only the
-// backstop); a verified object is relayed to root, and only root's 200
-// followed by an admitted answer flips the box. true means it flipped now.
+// tick after the serial read. It returns at once when admitted. Invariant
+// (Astra R1 P1-1): a ready.json GET happens only in a tick where the root
+// door has just answered managed and not admitted. After any relay
+// (accepted, refused or its reply lost) and whenever root's answer is
+// missing, the next action is a root-door query, never a remote read; root
+// unreachable means no remote read that tick. A read is due at arming,
+// once per changed serial, and otherwise at most once per
+// managedReadyBackstop (a failed serial read leaves only the backstop).
+// true means the box flipped to admitted now.
func (j *managedJoin) readyLeg(ctx context.Context, s release.Store, now time.Time, serial int64, serialOK bool) bool {
- if !j.Joining() || j.refused {
+ if j == nil || !j.Joining() {
return false
}
j.mu.Lock()
defer j.mu.Unlock()
+ if j.refused {
+ if now.Sub(j.lastRefusal) >= managedReadyBackstop {
+ j.lastRefusal = now
+ j.logf("agent: managed box admission refused: %s", j.refusedWhy)
+ }
+ return false
+ }
due := !j.read || now.Sub(j.lastRead) >= managedReadyBackstop
if serialOK {
if j.serialSeen && serial != j.lastSerial {
@@ -148,11 +198,22 @@ func (j *managedJoin) readyLeg(ctx context.Context, s release.Store, now time.Ti
}
j.lastSerial, j.serialSeen = serial, true
}
- if !due {
+ if !due && !j.rootPending {
return false
}
- if !j.rootAsked && j.askRoot(ctx) {
- return j.flipped()
+ switch j.askRoot(ctx) {
+ case rootAdmitted:
+ return j.markAdmitted()
+ case rootUnknown:
+ j.rootPending = true
+ return false
+ case rootNotManaged:
+ j.rootPending = false
+ return false
+ }
+ j.rootPending = false
+ if !due {
+ return false
}
j.read, j.lastRead = true, now
wire, _, err := s.Get(ctx, managedReadyKeyFor(j.id))
@@ -166,48 +227,49 @@ func (j *managedJoin) readyLeg(ctx context.Context, s release.Store, now time.Ti
j.logf("agent: managed admission: ready object refused: %v", err)
return false
}
+ // Whatever the relay's reply says, or if it is lost, root decides next.
+ j.rootPending = true
if err = j.door.ManagedAdmit(ctx, wire); err != nil {
- j.logf("agent: managed admission: root refused the relay: %v", err)
- return false
+ j.logf("agent: managed admission: relay to root: %v", err)
}
- if !j.askRoot(ctx) {
+ switch j.askRoot(ctx) {
+ case rootAdmitted:
+ return j.markAdmitted()
+ case rootUnknown:
return false
}
- return j.flipped()
-}
-
-func (j *managedJoin) flipped() bool {
- j.logf("agent: managed box admitted by root. tenant work opens")
- if f := j.onAdmitFunc(); f != nil {
- f()
- }
- return true
+ j.rootPending = false
+ return false
}
-func (j *managedJoin) setOnAdmit(f func()) {
+// markAdmitted flips the join once and runs onAdmit once.
+func (j *managedJoin) markAdmitted() bool {
+ j.joining.Store(false)
j.admitMu.Lock()
- defer j.admitMu.Unlock()
- j.onAdmit = f
+ first := !j.admitted
+ j.admitted = true
+ f := j.onAdmit
+ j.admitMu.Unlock()
+ if first {
+ j.logf("agent: managed box admitted by root. tenant work opens")
+ if f != nil {
+ f()
+ }
+ }
+ return first
}
-func (j *managedJoin) onAdmitFunc() func() {
+// whenAdmitted runs f exactly once, when the box is admitted: now if it
+// already is, else at the flip (Astra R1 P3-1: one boot-pass dispatch).
+func (j *managedJoin) whenAdmitted(f func()) {
j.admitMu.Lock()
- defer j.admitMu.Unlock()
- return j.onAdmit
-}
-
-// managedJoinProvision adds the join's live predicate to the reconcile
-// configuration every provisioning loop keeps (ReconcileConfig.Joining).
-func managedJoinProvision(j *managedJoin, inner func(*provision.ReconcileConfig)) func(*provision.ReconcileConfig) {
- if j == nil {
- return inner
- }
- return func(c *provision.ReconcileConfig) {
- if inner != nil {
- inner(c)
- }
- c.Joining = j.Joining
+ if j.admitted && !j.refused {
+ j.admitMu.Unlock()
+ f()
+ return
}
+ j.onAdmit = f
+ j.admitMu.Unlock()
}
// managedReadyKeyFor is the console's managedReadyKey for this box.
@@ -300,3 +362,17 @@ func managedGatedUnitOps(gate func() error, ops *appconfig.UnitOps) *appconfig.U
// errManagedGroupAdmission: a managed box takes its admission from root
// alone; CARLOS_GROUP_ADMISSION=1 on one is a configuration error.
var errManagedGroupAdmission = errors.New("this managed box is configured with CARLOS_GROUP_ADMISSION=1, which managed boxes do not support. tenant work stays closed. remove CARLOS_GROUP_ADMISSION from host.env")
+
+// managedJoinProvision adds the join's live predicate to the reconcile
+// configuration every provisioning loop keeps (ReconcileConfig.Joining).
+func managedJoinProvision(j *managedJoin, inner func(*provision.ReconcileConfig)) func(*provision.ReconcileConfig) {
+ if j == nil {
+ return inner
+ }
+ return func(c *provision.ReconcileConfig) {
+ if inner != nil {
+ inner(c)
+ }
+ c.Joining = j.Joining
+ }
+}
diff --git a/internal/host/managedjoin_fix1_test.go b/internal/host/managedjoin_fix1_test.go
new file mode 100644
index 000000000..db8396765
--- /dev/null
+++ b/internal/host/managedjoin_fix1_test.go
@@ -0,0 +1,284 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// TestManagedJoinRootFirst (Astra R1 P1-1): a ready.json GET happens only
+// in a tick where root has just answered managed and not admitted. A lost
+// relay reply, a lost follow-up query and a root door down at arming all
+// end in admission discovered from root, with the ready object then gone
+// or mismatched, and zero further ready reads.
+func TestManagedJoinRootFirst(t *testing.T) {
+ ctx := context.Background()
+ t0 := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)
+ spoil := map[string]func(t *testing.T, f *joinFixture){
+ "deleted": func(t *testing.T, f *joinFixture) { _ = f.store.Store.Delete(ctx, managedReadyKeyFor(f.m.ID)) },
+ "mismatched": func(t *testing.T, f *joinFixture) { f.publish(t, []byte(`{"fleet":"other"}`)) },
+ "unreachable": func(t *testing.T, f *joinFixture) { f.store.fail = true },
+ }
+ for name, after := range spoil {
+ t.Run("lost relay reply/"+name, func(t *testing.T) {
+ f := newJoinFixture(t)
+ f.publish(t, f.m.Wire(t))
+ f.door.loseReply, f.door.failAsksAfterCommit = true, 1
+ j := f.join(t)
+ if j.readyLeg(ctx, f.store, t0, 1, true) || !j.Joining() {
+ t.Fatal("flipped on a lost reply")
+ }
+ reads := f.store.readyGets.Load()
+ after(t, f)
+ // Not due by serial or backstop: root's owed answer comes first.
+ if !j.readyLeg(ctx, f.store, t0.Add(2*time.Second), 1, true) || j.Joining() {
+ t.Fatal("admission not discovered from root")
+ }
+ for i := 0; i < 50; i++ {
+ j.readyLeg(ctx, f.store, t0.Add(time.Duration(i)*time.Minute), int64(i+2), true)
+ }
+ if got := f.store.readyGets.Load(); got != reads || reads != 1 {
+ t.Fatalf("ready reads %d after discovery (want 1 in all)", got)
+ }
+ })
+ t.Run("lost follow-up query/"+name, func(t *testing.T) {
+ f := newJoinFixture(t)
+ f.publish(t, f.m.Wire(t))
+ f.door.failAsksAfterCommit = 2
+ j := f.join(t)
+ if j.readyLeg(ctx, f.store, t0, 1, true) || !j.Joining() {
+ t.Fatal("flipped without root's answer")
+ }
+ after(t, f)
+ // Root still down: no remote read in that tick.
+ if j.readyLeg(ctx, f.store, t0.Add(61*time.Second), 2, true) || f.store.readyGets.Load() != 1 {
+ t.Fatalf("read ready.json while root's answer was owed: %d", f.store.readyGets.Load())
+ }
+ if !j.readyLeg(ctx, f.store, t0.Add(63*time.Second), 3, true) || j.Joining() || f.store.readyGets.Load() != 1 {
+ t.Fatalf("admission not discovered from root without a read: %d reads", f.store.readyGets.Load())
+ }
+ })
+ t.Run("root down at arming/"+name, func(t *testing.T) {
+ f := newJoinFixture(t)
+ if err := f.m.Commit(f.m.Wire(t)); err != nil {
+ t.Fatal(err)
+ }
+ after(t, f)
+ f.door.failAsks = 3
+ j := newManagedJoinAt(f.m.Root, f.door, f.logf)
+ if !j.Joining() {
+ t.Fatal("admitted without root's answer")
+ }
+ for i := 0; i < 2; i++ {
+ if j.readyLeg(ctx, f.store, t0.Add(time.Duration(i)*time.Minute), int64(i), true) {
+ t.Fatal("flipped while root was down")
+ }
+ }
+ if !j.readyLeg(ctx, f.store, t0.Add(2*time.Minute), 2, true) || j.Joining() {
+ t.Fatal("admission not discovered from root")
+ }
+ if f.store.readyGets.Load() != 0 {
+ t.Fatalf("%d ready reads on an admitted box", f.store.readyGets.Load())
+ }
+ })
+ }
+}
+
+// TestManagedJoinRefused (ruling T3-Q2 restated): an identity that fails
+// its checks and group admission on a managed box take one refused path,
+// decided before admission is armed: every predicate closed, even over an
+// already-admitted root; nothing read, relayed or asked after arming.
+func TestManagedJoinRefused(t *testing.T) {
+ ctx := context.Background()
+ check := func(t *testing.T, j *managedJoin, f *joinFixture) {
+ t.Helper()
+ if j == nil || !j.refused {
+ t.Fatalf("not refused: %+v", j)
+ }
+ svc, eb := &activator.Service{}, &activator.ExecBackend{}
+ j.bind(svc, eb)
+ rt := registry.Route{Host: "shop.example.com", Platform: true}
+ if !j.Joining() || j.TenantAdmitted() || j.TenantAdmissionExempt(rt) || svc.TenantAdmitted() || svc.TenantAdmissionExempt(rt) || eb.TenantStartAllowed(rt) {
+ t.Fatal("a refused join opened a predicate")
+ }
+ var cfg provision.ReconcileConfig
+ managedJoinProvision(j, nil)(&cfg)
+ if !cfg.Joining() {
+ t.Fatal("reconcile not joining")
+ }
+ ran := false
+ j.whenAdmitted(func() { ran = true })
+ if f != nil {
+ asks, admits := f.door.asks.Load(), f.door.admits.Load()
+ for i := 0; i < 5; i++ {
+ j.readyLeg(ctx, f.store, time.Now().Add(time.Duration(i)*time.Hour), int64(i), true)
+ }
+ if f.store.readyGets.Load() != 0 || f.door.admits.Load() != admits || f.door.asks.Load() != asks {
+ t.Fatal("a refused join read, relayed or asked")
+ }
+ }
+ if ran {
+ t.Fatal("a refused join ran the admit callback")
+ }
+ }
+ for name, env := range map[string]string{"group admission": "1"} {
+ t.Run(name+" over an admitted root", func(t *testing.T) {
+ f := newJoinFixture(t)
+ f.publish(t, f.m.Wire(t))
+ if err := f.m.Commit(f.m.Wire(t)); err != nil {
+ t.Fatal(err)
+ }
+ j := armManagedJoin(f.m.Root, f.door, func(k string) string {
+ if k == "CARLOS_GROUP_ADMISSION" {
+ return env
+ }
+ return ""
+ }, false, f.logf)
+ check(t, j, f)
+ if !strings.Contains(f.logs.String(), "admission refused") {
+ t.Fatalf("refusal not logged: %s", f.logs)
+ }
+ })
+ }
+ t.Run("group configuration", func(t *testing.T) {
+ f := newJoinFixture(t)
+ check(t, armManagedJoin(f.m.Root, f.door, func(string) string { return "" }, true, f.logf), f)
+ })
+ t.Run("identity with an error", func(t *testing.T) {
+ root := t.TempDir()
+ prev := managedIdentityAt
+ managedIdentityAt = func(string) (managedboot.Identity, bool, error) {
+ return managedboot.Identity{}, true, errors.New("managedboot: invalid managed box identity")
+ }
+ defer func() { managedIdentityAt = prev }()
+ // A nil door: a refused join never asks root.
+ check(t, armManagedJoin(root, nil, func(string) string { return "" }, false, t.Logf), nil)
+ })
+}
+
+// TestManagedJoinWhenAdmittedOnce (Astra R1 P3-1): the boot-pass callback
+// runs exactly once, whether admission lands before or after it is
+// registered, or races the registration.
+func TestManagedJoinWhenAdmittedOnce(t *testing.T) {
+ ctx := context.Background()
+ for _, order := range []string{"register first", "admit first", "both"} {
+ t.Run(order, func(t *testing.T) {
+ f := newJoinFixture(t)
+ f.publish(t, f.m.Wire(t))
+ j := f.join(t)
+ runs := 0
+ if order != "admit first" {
+ j.whenAdmitted(func() { runs++ })
+ }
+ j.readyLeg(ctx, f.store, time.Now(), 1, true)
+ j.markAdmitted()
+ if order != "register first" {
+ j.whenAdmitted(func() { runs++ })
+ }
+ want := 1
+ if order == "both" {
+ want = 2 // two registrations, one each
+ }
+ if runs != want {
+ t.Fatalf("callbacks ran %d times, want %d", runs, want)
+ }
+ })
+ }
+}
+
+// TestManagedJoinDrivesSurfaces (Fable R1 P2-3): the bound join refuses the
+// real activator surfaces, not just their hooks: a request through the edge
+// (503 starting), a worker wake, a scheduled delivery, and the exec
+// backend's acquire and one-shot start; after admission the same hooks
+// open.
+func TestManagedJoinDrivesSurfaces(t *testing.T) {
+ f := newJoinFixture(t)
+ j := f.join(t)
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "r.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ rt := registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Account: "bab", Status: "ready", Hibernate: true, Socket: "/run/carlos/shop.example.com.sock"}
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ eb := &activator.ExecBackend{}
+ svc := activator.New(activator.Config{}, eb, reg)
+ opt := j.bind(svc, eb)
+ e, err := edge.New(reg, svc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ opt(e)
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, httptest.NewRequest("GET", "https://"+rt.Host+"/", nil))
+ if w.Code != 503 || w.Body.String() != "This service is starting. Try again later.\n" {
+ t.Fatalf("edge while joining: %d %q", w.Code, w.Body.String())
+ }
+ worker := rt
+ worker.Kind = "worker"
+ if err := svc.WakeWorker(worker); !errors.Is(err, activator.ErrTenantAdmission) {
+ t.Fatalf("worker wake: %v", err)
+ }
+ w = httptest.NewRecorder()
+ svc.ServeScheduled(w, httptest.NewRequest("POST", "https://"+rt.Host+"/", nil), rt, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Fatal("scheduled delivery proxied") }))
+ if w.Code != 503 {
+ t.Fatalf("scheduled delivery: %d", w.Code)
+ }
+ if _, err := eb.Acquire(context.Background(), rt); !errors.Is(err, activator.ErrTenantAdmission) {
+ t.Fatalf("exec acquire: %v", err)
+ }
+ if _, err := eb.StartCmd(context.Background(), rt, activator.CmdSpec{}); !errors.Is(err, activator.ErrTenantAdmission) {
+ t.Fatalf("exec one-shot start: %v", err)
+ }
+ f.publish(t, f.m.Wire(t))
+ if !j.readyLeg(context.Background(), f.store, time.Now(), 1, true) {
+ t.Fatal("no flip")
+ }
+ if !svc.TenantAdmitted() || !eb.TenantStartAllowed(rt) {
+ t.Fatal("hooks still closed after admission")
+ }
+ if _, err := eb.Acquire(context.Background(), rt); errors.Is(err, activator.ErrTenantAdmission) {
+ t.Fatal("exec acquire still refused for admission after the flip")
+ }
+}
+
+// TestManagedNamedRecoveryGate (Fable R1 P2-3): the root pass's named-unit
+// recovery asks root's gate first and recovers nothing while the managed
+// box is joining; once admitted, recovery proceeds; ungated (BYO) as main.
+func TestManagedNamedRecoveryGate(t *testing.T) {
+ f := newJoinFixture(t)
+ rt := registry.Route{Host: "api.shop.example.com", Unit: "shop-api.service"}
+ n := namedUnitRecovery{gate: managedRootGateWith(f.m.Admission)}
+ if !n.refusedByGate(rt) {
+ t.Fatal("joining box: named-unit recovery not refused")
+ }
+ if err := f.m.Commit(f.m.Wire(t)); err != nil {
+ t.Fatal(err)
+ }
+ if n.refusedByGate(rt) {
+ t.Fatal("admitted box: named-unit recovery still refused")
+ }
+ if (namedUnitRecovery{}).refusedByGate(rt) {
+ t.Fatal("ungated recovery refused")
+ }
+ // A root that cannot answer refuses too.
+ doubt := namedUnitRecovery{gate: managedRootGateWith(func() (bool, bool, error) { return true, false, errors.New("doubt") })}
+ if !doubt.refusedByGate(rt) {
+ t.Fatal("root doubt did not refuse")
+ }
+}
diff --git a/internal/host/managedjoin_root_linux_test.go b/internal/host/managedjoin_root_linux_test.go
index 4ebcdb30f..dc12737df 100644
--- a/internal/host/managedjoin_root_linux_test.go
+++ b/internal/host/managedjoin_root_linux_test.go
@@ -23,14 +23,17 @@ import (
// uid with no rights over root's files.
const managedServiceUID = 64000
+// requireManagedRoot: the rootrunner build tag is the gate (ruling T3-Q1);
+// without real uid 0 and a usable second uid the witness fails, never
+// skips.
func requireManagedRoot(t *testing.T) {
t.Helper()
- if os.Getenv("CARLOS_MANAGED_ROOT_TEST") != "1" {
- t.Fatal("CARLOS_MANAGED_ROOT_TEST=1 is required: this witness runs only on the root runner")
- }
if os.Geteuid() != 0 {
t.Fatal("this witness must run as uid 0")
}
+ if !asService(t, "true") {
+ t.Fatalf("the second real uid %d cannot run a command", managedServiceUID)
+ }
}
// asService runs a shell command as managedServiceUID and reports whether
@@ -241,6 +244,18 @@ func TestManagedControlCommitStrict(t *testing.T) {
if _, err := os.Lstat("/etc/carlos"); errors.Is(err, os.ErrNotExist) {
createdCarlos = true
}
+ // The control unit's mandatory ReadWritePaths need their directories,
+ // or namespace setup fails before the helper runs.
+ createdControl := false
+ if _, err := os.Lstat("/run/carlos-control"); errors.Is(err, os.ErrNotExist) {
+ if err := os.Mkdir("/run/carlos-control", 0o755); err != nil {
+ t.Fatal(err)
+ }
+ createdControl = true
+ }
+ if err := os.MkdirAll(runDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
t.Cleanup(func() {
ctl("stop", gateInst, commitUnit)
ctl("reset-failed", gateInst, commitUnit)
@@ -255,6 +270,9 @@ func TestManagedControlCommitStrict(t *testing.T) {
if createdCarlos {
os.Remove("/etc/carlos")
}
+ if createdControl {
+ os.Remove("/run/carlos-control")
+ }
})
// The real managed layout the first boot's commit leaves.
dir := t.TempDir()
@@ -317,21 +335,26 @@ func TestManagedControlCommitStrict(t *testing.T) {
if got := show(gateInst, "ConditionResult"); got != "no" {
t.Fatalf("gated instance ConditionResult=%s", got)
}
- // Without the drop-in, ProtectSystem=strict refuses the write.
+ // Without the drop-in, ProtectSystem=strict refuses the write: the
+ // helper itself ran (its exit status 1, not systemd's 226 namespace
+ // setup failure) and failed on a read-only file system.
ctl("start", commitUnit)
if show(commitUnit, "Result") == "success" {
t.Fatal("committed under ProtectSystem=strict without the ReadWritePaths drop-in: the drop-in is not what makes it work")
}
+ if status := show(commitUnit, "ExecMainStatus"); status != "1" {
+ t.Fatalf("the helper did not run to its own failure (ExecMainStatus=%s): a setup failure, not the write refusal", status)
+ }
+ _ = exec.Command("journalctl", "--sync").Run()
+ journal, _ := exec.Command("journalctl", "-u", commitUnit, "-o", "cat", "--no-pager").CombinedOutput()
+ if !bytes.Contains(bytes.ToLower(journal), []byte("read-only file system")) {
+ t.Fatalf("the helper's failure is not the read-only refusal:\n%s", journal)
+ }
if _, err := os.Lstat(managedboot.AdmittedMarker); err == nil {
t.Fatal("marker written without the drop-in")
}
ctl("reset-failed", commitUnit)
- if _, err := managedboot.InstallControlDropIn(runDir); err != nil {
- t.Fatal(err)
- }
- if err := os.Rename(filepath.Join(runDir, managedboot.ControlUnit+".d"), filepath.Join(runDir, commitUnit+".d")); err != nil {
- t.Fatal(err)
- }
+ writeFileT(t, filepath.Join(runDir, commitUnit+".d", managedboot.ControlDropInName), managedboot.ControlDropIn)
ctl("daemon-reload")
ctl("start", commitUnit)
if got := show(commitUnit, "Result"); got != "success" {
@@ -350,3 +373,62 @@ func TestManagedControlCommitStrict(t *testing.T) {
t.Fatalf("gated instance after admission: ActiveState=%s", got)
}
}
+
+// TestManagedUnitTrustRoot (Astra R1 P1-3, the owner half): as real root,
+// a matching admission drop-in the service uid owns is replaced by a
+// root-owned one, and a service-owned declaration or drop-in directory is
+// refused. Root runner only.
+func TestManagedUnitTrustRoot(t *testing.T) {
+ requireManagedRoot(t)
+ newTree := func(t *testing.T) (string, string) {
+ root, err := os.MkdirTemp("/var/tmp", "carlos-units-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(root) })
+ if err = os.Chmod(root, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ stubManagedIdentity(t, root)
+ etc := filepath.Join(root, "etc")
+ writeFileT(t, filepath.Join(etc, "carlos/named-units.json"), `{"schema":1,"units":[{"host":"api.shop.example.com","app":"shop","unit":"shop-api.service"}]}`)
+ if err = bootstrap(root, nil); err != nil {
+ t.Fatal(err)
+ }
+ return root, etc
+ }
+ gate := func(root string) error {
+ own, _ := unitNames()
+ _, _, err := managedGateUnitsKnown(root, 0, own, nil, nil)
+ return err
+ }
+ t.Run("service-owned matching drop-in is replaced", func(t *testing.T) {
+ root, etc := newTree(t)
+ p := filepath.Join(etc, "systemd/system/carlos-instance@.service.d", managedboot.AdmissionDropInName)
+ if err := os.Chown(p, managedServiceUID, managedServiceUID); err != nil {
+ t.Fatal(err)
+ }
+ if err := gate(root); err != nil {
+ t.Fatal(err)
+ }
+ var st syscall.Stat_t
+ if err := syscall.Lstat(p, &st); err != nil || st.Uid != 0 || st.Nlink != 1 || st.Mode&0o7777 != 0o644 {
+ t.Fatalf("drop-in after the gate: %+v %v", st, err)
+ }
+ })
+ for name, path := range map[string]string{
+ "service-owned declaration": "carlos/named-units.json",
+ "service-owned drop-in directory": "systemd/system/carlos-instance@.service.d",
+ "service-owned unit directory": "systemd/system",
+ } {
+ t.Run(name+" is refused", func(t *testing.T) {
+ root, etc := newTree(t)
+ if err := os.Chown(filepath.Join(etc, path), managedServiceUID, managedServiceUID); err != nil {
+ t.Fatal(err)
+ }
+ if err := gate(root); err == nil {
+ t.Fatal("the gate trusted a service-owned path")
+ }
+ })
+ }
+}
diff --git a/internal/host/managedjoin_test.go b/internal/host/managedjoin_test.go
index 849a51e16..cbea5b322 100644
--- a/internal/host/managedjoin_test.go
+++ b/internal/host/managedjoin_test.go
@@ -37,10 +37,15 @@ import (
// CommitAdmission and RootAdmission semantics, counted, with failures
// injectable.
type fakeRootDoor struct {
- m *roottest.ManagedRoot
- admits, asks atomic.Int64
- failAdmit, failAsk bool
- crashBeforeCommit bool
+ m *roottest.ManagedRoot
+ admits, asks atomic.Int64
+ failAdmit bool
+ // crashBeforeCommit loses the relay before root commits; loseReply
+ // commits, then loses the reply.
+ crashBeforeCommit, loseReply bool
+ // failAsks fails the next n root queries; failAsksAfterCommit arms
+ // failAsks with n once a relay commits.
+ failAsks, failAsksAfterCommit int
}
func (d *fakeRootDoor) ManagedAdmit(_ context.Context, wire []byte) error {
@@ -48,12 +53,22 @@ func (d *fakeRootDoor) ManagedAdmit(_ context.Context, wire []byte) error {
if d.failAdmit || d.crashBeforeCommit {
return errors.New("instance control socket: connection reset")
}
- return d.m.Commit(wire)
+ if err := d.m.Commit(wire); err != nil {
+ return err
+ }
+ if d.failAsksAfterCommit > 0 {
+ d.failAsks, d.failAsksAfterCommit = d.failAsksAfterCommit, 0
+ }
+ if d.loseReply {
+ return errors.New("instance control socket: reply lost")
+ }
+ return nil
}
func (d *fakeRootDoor) ManagedAdmission(context.Context) (bool, bool, error) {
d.asks.Add(1)
- if d.failAsk {
+ if d.failAsks > 0 {
+ d.failAsks--
return false, false, errors.New("instance control socket: connection refused")
}
return d.m.Admission()
@@ -106,9 +121,9 @@ func (f *joinFixture) logf(format string, args ...any) {
func (f *joinFixture) join(t *testing.T) *managedJoin {
t.Helper()
- j, err := newManagedJoinAt(f.m.Root, f.door, f.logf)
- if err != nil || j == nil {
- t.Fatalf("newManagedJoinAt: %v %v", j, err)
+ j := newManagedJoinAt(f.m.Root, f.door, f.logf)
+ if j == nil || j.refused {
+ t.Fatalf("newManagedJoinAt: %+v", j)
}
return j
}
@@ -210,7 +225,7 @@ func TestManagedJoinReadyLeg(t *testing.T) {
f.door.failAdmit = true
j := f.join(t)
admitted := 0
- j.setOnAdmit(func() { admitted++ })
+ j.whenAdmitted(func() { admitted++ })
if j.readyLeg(ctx, f.store, t0, 1, true) || !j.Joining() || f.door.admits.Load() != 1 {
t.Fatal("root refusal flipped or did not relay")
}
@@ -218,11 +233,11 @@ func TestManagedJoinReadyLeg(t *testing.T) {
t.Fatal("retried before due")
}
f.door.failAdmit = false
- f.door.failAsk = true
- if j.readyLeg(ctx, f.store, t0.Add(61*time.Second), 1, true) || !j.Joining() {
- t.Fatal("flipped without root's admitted answer")
+ f.door.failAsks = 1
+ reads := f.store.readyGets.Load()
+ if j.readyLeg(ctx, f.store, t0.Add(61*time.Second), 1, true) || !j.Joining() || f.store.readyGets.Load() != reads {
+ t.Fatal("flipped, or read ready.json, without root's answer")
}
- f.door.failAsk = false
if !j.readyLeg(ctx, f.store, t0.Add(122*time.Second), 1, true) || j.Joining() || admitted != 1 {
t.Fatalf("valid relay did not flip once: joining=%v onAdmit=%d", j.Joining(), admitted)
}
@@ -364,9 +379,9 @@ func TestManagedJoinBYOUnchanged(t *testing.T) {
managedIdentityAt = func(string) (managedboot.Identity, bool, error) { return managedboot.Identity{}, false, nil }
defer func() { managedIdentityAt = prev }()
door := &fakeRootDoor{}
- j, err := newManagedJoinAt(t.TempDir(), door, t.Logf)
- if j != nil || err != nil || door.asks.Load() != 0 {
- t.Fatalf("byo: %v %v asks %d", j, err, door.asks.Load())
+ j := newManagedJoinAt(t.TempDir(), door, t.Logf)
+ if j != nil || door.asks.Load() != 0 {
+ t.Fatalf("byo: %v asks %d", j, door.asks.Load())
}
if j.Joining() || j.bind(&activator.Service{}, &activator.ExecBackend{}) != nil {
t.Fatal("a nil join gates or binds")
@@ -389,15 +404,7 @@ func TestManagedJoinBYOUnchanged(t *testing.T) {
if err := managedGateStart(func(string) error { return nil })("shop.example.com"); err != nil {
t.Fatal(err)
}
- // A managed box configured with CARLOS_GROUP_ADMISSION=1 reads nothing
- // and never opens (runAgent marks the join refused).
- f := newJoinFixture(t)
- f.publish(t, f.m.Wire(t))
- r := f.join(t)
- r.refused = true
- if r.readyLeg(context.Background(), f.store, time.Now(), 1, true) || !r.Joining() || f.store.readyGets.Load() != 0 {
- t.Fatal("a refused join read or opened")
- }
+ // The refused path (ruling T3-Q2 restated) is TestManagedJoinRefused.
}
func TestManagedJoinStartSurfaces(t *testing.T) {
@@ -489,18 +496,17 @@ func (c *conditionedUnits) Restart(unit string) error {
func (c *conditionedUnits) TryRestart(unit string) error { return c.Restart(unit) }
-// conditionTree is the managed unit tree with a named unit unit declared.
+// conditionTree is the managed unit tree, published by bootstrap's gated
+// install plan, with a named unit unit declared.
func conditionTree(t *testing.T, unit string) unitTree {
t.Helper()
root := t.TempDir()
+ stubManagedIdentity(t, root)
+ writeFileT(t, filepath.Join(root, "etc/carlos/named-units.json"), `{"schema":1,"units":[{"host":"`+observedHost+`","account":"bab","app":"console","unit":"`+unit+`"}]}`)
if err := bootstrap(root, nil); err != nil {
t.Fatal(err)
}
- dir := filepath.Join(root, "etc/systemd/system")
- writeFileT(t, filepath.Join(dir, unit), "[Service]\nExecStart=/opt/carlos/live/console\n")
- if _, err := managedboot.InstallAdmissionDropIns(dir, []string{unit}); err != nil {
- t.Fatal(err)
- }
+ writeFileT(t, filepath.Join(root, "etc/systemd/system", unit), "[Service]\nExecStart=/opt/carlos/live/console\n")
return unitTree{root: root}
}
@@ -516,23 +522,42 @@ func TestManagedRestartOnlyPassUnmet(t *testing.T) {
if err := release.PointLive(u.opt, rt.Host, rt.Account, "v1", rt.App); err != nil {
t.Fatal(err)
}
+ ctx := context.Background()
+ marks := filepath.Join(t.TempDir(), "restart-marks.json")
restart := rootRestartRouteWith(e.root.reg, sys, u.opt, func(string) string { return "5s" }, nil, c)
+ // The real -restart-only composition: restart-mark selection over the
+ // registry's routes, then rootRestartRouteWith's dispatch.
+ pass := func() {
+ routes, err := e.root.reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ restartPass(ctx, routes, e.store, marks, restart)
+ }
+ bump := func(n int) {
+ key := release.RestartGenKey(rt.Account, rt.App)
+ _, etag, _ := e.store.Get(ctx, key)
+ if _, err := e.store.Put(ctx, key, []byte(fmt.Sprintf(`{"gen":%d}`, n)), etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ pass() // seeds the marks: cycles nothing
initial := u.props
- // The restart-only pass's dispatch (restartPass -> rootRestartRouteWith).
- _ = restart(rt.Host)
+ bump(1)
+ pass()
if len(sys.skipped) == 0 || len(u.effects) != 0 || u.props.ActiveState == "active" {
- t.Fatalf("joining restart ran a process: skipped=%v effects=%v state=%s", sys.skipped, u.effects, u.props.ActiveState)
+ t.Fatalf("joining restart request ran a process: skipped=%v effects=%v state=%s", sys.skipped, u.effects, u.props.ActiveState)
}
- // Admitted: the same pass over the same unit (as the fixture left it
- // before the skipped job) now starts it.
+ // Admitted: the next restart request, through the same composition,
+ // starts the unit (from the state the fixture left it in before the
+ // skipped job stopped it).
admitTree(t, tree)
u.props = initial
c.started = &sync.Map{}
- if err := restart(rt.Host); err != nil {
- t.Fatalf("admitted restart: %v", err)
- }
+ bump(2)
+ pass()
if u.props.ActiveState != "active" || u.props.MainPID <= 0 || len(u.effects) == 0 {
- t.Fatalf("admitted restart did not start the unit: %+v %v", u.props, u.effects)
+ t.Fatalf("admitted restart request did not start the unit: %+v %v", u.props, u.effects)
}
}
@@ -585,11 +610,19 @@ func TestManagedRollbackRecoveryUnmet(t *testing.T) {
if a, err = readRollbackAttempt(s, rt.Host); err != nil || a.Verified {
t.Fatalf("joining recovery verified a unit that never ran: %+v %v", a, err)
}
- // Admitted, the next root pass's start route brings the unit up.
+ // Admitted: the next production root pass (release.Pass with the root
+ // pass's forward restart and rollback restart over the same systemd)
+ // brings the unit up on the correct bound version: the crashing v2 is
+ // rolled back and v1 runs.
admitTree(t, tree)
u.props.ActiveState, u.props.SubState = "failed", "failed"
- if err := sys.Restart(rt.Unit); err != nil || u.props.MainPID <= 0 || u.props.ActiveState != "active" {
- t.Fatalf("admitted start: %v %+v", err, u.props)
+ c.started = &sync.Map{}
+ forward = rootRestartRouteWith(e.root.reg, sys, u.opt, func(string) string { return "5s" }, nil, c)
+ rollback := rollbackUnitRestart(e.root.reg, sys, u.opt, func(string) string { return "5s" }, c)
+ _ = release.Pass(context.Background(), e.root.reg, e.store, pub, u.opt, forward,
+ release.BakeDir(e.bake), release.WithRestartFailurePropagation(), release.WithRollbackRestart(rollback))
+ if u.props.MainPID <= 0 || u.props.ActiveState != "active" || u.exe != release.VersionPath(u.opt, "bab", "v1", "console") {
+ t.Fatalf("admitted root pass did not run the bound version: %+v exe %s effects %v", u.props, u.exe, u.effects)
}
}
diff --git a/internal/host/managedunits.go b/internal/host/managedunits.go
index 4349a1ccf..e28cf6386 100644
--- a/internal/host/managedunits.go
+++ b/internal/host/managedunits.go
@@ -1,9 +1,10 @@
package host
import (
+ "bytes"
"errors"
"fmt"
- "os"
+ "io/fs"
"path/filepath"
"github.com/carlosframework/platform/internal/appconfig"
@@ -14,86 +15,138 @@ import (
// is a managed box. A var so an unprivileged test can own its fake root.
var managedIdentityAt = managedboot.LoadIdentity
-// namedUnitDropInDir is where InstallNamedUnits writes a declared named
-// unit's admission drop-in (dropInRoot in production).
-var namedUnitDropInDir = dropInRoot
+// managedUnitUID is the owner every file and directory on the admission
+// drop-in path must carry: root. A var so an unprivileged test can own its
+// fake root.
+var managedUnitUID = 0
-// errManagedIdentity is a managed box whose identity file fails its checks:
-// nothing is installed or changed, and existing drop-ins stay.
-var errManagedIdentity = errors.New("managed box identity is unreadable; admission drop-ins left as they are")
+// namedUnitRoot is the box root InstallNamedUnits publishes under.
+var namedUnitRoot = "/"
+
+const (
+ mbUnitDir = "/etc/systemd/system"
+ mbNamedUnitsPath = "/etc/carlos/named-units.json"
+ maxNamedUnitsBytes = 1 << 20
+ managedDropInMode = 0o644
+ managedDropInDirMode = 0o755
+)
// managedRootOf is the filesystem root an etc directory belongs to.
func managedRootOf(etcDir string) string { return filepath.Dir(filepath.Clean(etcDir)) }
-// ensureManagedUnitDropIns installs, on a managed box, the root-owned
-// admission drop-in for every workload template this binary ships and
-// every declared named unit, and the control service's ReadWritePaths
-// drop-in (decisions rule 12). On a BYO box it does nothing. changed says
-// a file was written, so the caller reloads systemd before it starts or
-// enables anything. etcDir is the box's /etc.
-func ensureManagedUnitDropIns(etcDir string) (changed bool, err error) {
- workloads, control, err := ensureManagedUnitDropInsSplit(etcDir, nil)
- return workloads || control, err
+// managedGateEtc is managedGateUnits for a publisher that writes under
+// etcDir: the drop-ins land in <root>/etc/systemd/system, so an etcDir that
+// is not <root>/etc on a managed box is refused rather than gated elsewhere.
+func managedGateEtc(etcDir string, units []string, reload func() error) (control bool, err error) {
+ root := managedRootOf(etcDir)
+ if filepath.Base(filepath.Clean(etcDir)) != "etc" {
+ if _, managed, _ := managedIdentityAt(root); managed {
+ return false, fmt.Errorf("managed admission drop-ins: %s is not a box's /etc", etcDir)
+ }
+ return false, nil
+ }
+ return managedGateUnits(root, units, nil, reload)
}
-// ensureManagedUnitDropInsSplit is ensureManagedUnitDropIns reporting the
-// workload and control changes apart. extraNamed are named units about to
-// be declared (InstallNamedUnits), beside those the live file declares.
-func ensureManagedUnitDropInsSplit(etcDir string, extraNamed []string) (workloads, control bool, err error) {
- _, managed, err := managedIdentityAt(managedRootOf(etcDir))
+// managedGateUnits is the step every unit publication on a managed box
+// takes first (decisions rule 12, ruling T3-Q3 reversed): before any unit
+// file of units is written, every unit of the set being published that is
+// not a maintenance unit, every unit the live declaration names and every
+// extraNamed unit carries the root-owned admission drop-in, the control
+// service carries its ReadWritePaths drop-in, and systemd has reloaded.
+// Any failure (identity, declaration, scope, write, reload) is returned
+// and the caller publishes nothing. A BYO box is a no-op.
+func managedGateUnits(root string, units, extraNamed []string, reload func() error) (control bool, err error) {
+ _, managed, err := managedIdentityAt(root)
if !managed {
- return false, false, nil
+ return false, nil
}
if err != nil {
- return false, false, fmt.Errorf("%w: %v", errManagedIdentity, err)
+ return false, fmt.Errorf("managed box identity is unreadable, so no unit is published: %w", err)
}
- named, err := declaredNamedUnits(filepath.Join(etcDir, "carlos", filepath.Base(appconfig.DefaultNamedUnitsPath)))
+ _, control, err = managedGateUnitsKnown(root, managedUnitUID, units, extraNamed, reload)
+ return control, err
+}
+
+// managedGateUnitsKnown is managedGateUnits for a caller that already knows
+// the box is managed (managed boot, before its identity can be re-read).
+// changed says any drop-in was written; control that the control
+// service's was. reload, when not nil, always runs last.
+func managedGateUnitsKnown(root string, uid int, units, extraNamed []string, reload func() error) (changed, control bool, err error) {
+ named, err := managedDeclaredUnits(root, uid)
if err != nil {
- // An unreadable declaration declares nothing a pass will start
- // (appconfig refuses an invalid file); the templates still get
- // theirs.
- named = nil
+ return false, false, err
}
- named = append(named, extraNamed...)
- unitDir := filepath.Join(etcDir, "systemd", "system")
- if err = os.MkdirAll(unitDir, 0o755); err != nil {
+ gated, err := managedboot.GatedUnits(units, append(named, extraNamed...))
+ if err != nil {
return false, false, err
}
- if workloads, err = managedboot.InstallAdmissionDropIns(unitDir, named); err != nil {
- return workloads, false, err
+ for _, u := range gated {
+ c, err := managedEnsureDropIn(root, uid, u, managedboot.AdmissionDropInName, managedboot.AdmissionDropIn)
+ if err != nil {
+ return changed, false, err
+ }
+ changed = changed || c
+ }
+ if control, err = managedEnsureDropIn(root, uid, managedboot.ControlUnit, managedboot.ControlDropInName, managedboot.ControlDropIn); err != nil {
+ return changed, false, err
}
- control, err = managedboot.InstallControlDropIn(unitDir)
- return workloads, control, err
+ changed = changed || control
+ if reload != nil {
+ if err = reload(); err != nil {
+ return changed, control, fmt.Errorf("managed admission drop-ins: daemon-reload: %w", err)
+ }
+ }
+ return changed, control, nil
}
-// declaredNamedUnits reads the named-unit declaration file's unit names;
-// an absent file declares none.
-func declaredNamedUnits(path string) ([]string, error) {
- raw, err := os.ReadFile(path)
- if errors.Is(err, os.ErrNotExist) {
+// managedDeclaredUnits reads the live named-unit declaration through the
+// trusted descriptor walk (root-owned chain, no link followed, regular,
+// one link, root-owned, not group/other writable). Absent declares none;
+// anything else that fails is a refusal, never an empty set.
+func managedDeclaredUnits(root string, uid int) ([]string, error) {
+ raw, err := mbReadRootFile(root, mbNamedUnitsPath, uid, maxNamedUnitsBytes, 0)
+ if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("named-unit declaration: %w", err)
}
return appconfig.DeclaredUnits(raw)
}
+// managedEnsureDropIn makes <unit>.d/<name> under the unit directory an
+// exact root-owned 0644 single-link file, in a root-owned directory chain
+// with no group/other write. A present exact file is left alone; anything
+// else there (absent, altered, another owner, a link, wrong mode) is
+// replaced by rename. An unsafe directory on the way is a refusal.
+func managedEnsureDropIn(root string, uid int, unit, name, body string) (bool, error) {
+ dir := filepath.Join(mbUnitDir, unit+".d")
+ if err := mbEnsureDir(root, dir, managedDropInDirMode, uid); err != nil {
+ return false, fmt.Errorf("managed admission drop-in %s: %w", unit, err)
+ }
+ path := filepath.Join(dir, name)
+ if got, err := mbReadRootFile(root, path, uid, 4096, managedDropInMode); err == nil && bytes.Equal(got, []byte(body)) {
+ return false, nil
+ }
+ if err := mbWriteRootFile(root, path, []byte(body), managedDropInMode, uid, -1); err != nil {
+ return false, fmt.Errorf("managed admission drop-in %s: %w", unit, err)
+ }
+ return true, nil
+}
+
// managedNamedUnitDropIns is InstallNamedUnits' step before the declaration
-// file is replaced: each unit raw declares gets its admission drop-in on a
-// managed box, and systemd reloads when one was written.
+// file is replaced: the units raw declares, beside the live ones and this
+// binary's own units, are gated and systemd reloaded.
func managedNamedUnitDropIns(raw []byte, reload func() error) error {
units, err := appconfig.DeclaredUnits(raw)
if err != nil {
return err
}
- etc := filepath.Dir(filepath.Dir(filepath.Clean(namedUnitDropInDir)))
- workloads, control, err := ensureManagedUnitDropInsSplit(etc, units)
+ own, err := unitNames()
if err != nil {
return err
}
- if workloads || control {
- return reload()
- }
- return nil
+ _, err = managedGateUnits(namedUnitRoot, own, units, reload)
+ return err
}
diff --git a/internal/host/managedunits_fix1_test.go b/internal/host/managedunits_fix1_test.go
new file mode 100644
index 000000000..ea1852a3b
--- /dev/null
+++ b/internal/host/managedunits_fix1_test.go
@@ -0,0 +1,317 @@
+//go:build linux
+
+package host
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "syscall"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/managedboot"
+)
+
+// managedApplyFixture is the system apply fixture on a managed fake root
+// whose etc directory is <root>/etc, with a staged target build.
+func managedApplyFixture(t *testing.T, staged ...string) (*applyFixture, string, string) {
+ t.Helper()
+ f := newApplyFixture(t, "stable", "v1.0.0")
+ root := t.TempDir()
+ f.a.etcDir = filepath.Join(root, "etc")
+ writeFileT(t, filepath.Join(f.a.etcDir, "systemd/system/.keep"), "")
+ stubManagedIdentity(t, root)
+ stage := t.TempDir()
+ writeFileT(t, filepath.Join(stage, "etc/tmpfiles.d/carlos.conf"), "d /run/carlos\n")
+ writeFileT(t, filepath.Join(stage, "etc/sysusers.d/carlos.conf"), "g carlos-sockets -\n")
+ for _, u := range staged {
+ writeFileT(t, filepath.Join(stage, "etc/systemd/system", u), "[Service]\nExecStart=/opt/carlos/carlos x\n")
+ }
+ return f, root, stage
+}
+
+// TestManagedPublicationGated (Astra R1 P1-2, T3-Q3 reversed): every
+// publication path installs the drop-ins of the unit set it publishes, and
+// reloads, before any unit file of that set exists; any failure publishes
+// nothing.
+func TestManagedPublicationGated(t *testing.T) {
+ newTemplate := "carlos-future-worker@.service"
+ t.Run("apply gates a template the target adds before its file exists", func(t *testing.T) {
+ f, root, stage := managedApplyFixture(t, newTemplate, "carlos-edge.service")
+ unitDir := filepath.Join(root, "etc/systemd/system")
+ ctl := f.a.ops.systemctl
+ reloads := 0
+ f.a.ops.systemctl = func(args ...string) (string, error) {
+ if args[0] == "daemon-reload" && reloads == 0 {
+ reloads++
+ if _, err := os.Stat(filepath.Join(unitDir, newTemplate)); err == nil {
+ t.Error("the new template's file existed at the gate's reload")
+ }
+ if b, err := os.ReadFile(filepath.Join(unitDir, newTemplate+".d", managedboot.AdmissionDropInName)); err != nil || string(b) != managedboot.AdmissionDropIn {
+ t.Errorf("no drop-in for the new template at the gate's reload: %v", err)
+ }
+ }
+ return ctl(args...)
+ }
+ if err := f.a.installUnits(t.Context(), stage, nil); err != nil {
+ t.Fatal(err)
+ }
+ if reloads == 0 {
+ t.Fatal("the gate never reloaded")
+ }
+ if _, err := os.Stat(filepath.Join(unitDir, newTemplate)); err != nil {
+ t.Fatal("the target's template was not published")
+ }
+ if _, err := os.Lstat(filepath.Join(unitDir, "carlos-edge.service.d", managedboot.AdmissionDropInName)); err == nil {
+ t.Fatal("a maintenance unit was gated")
+ }
+ tree := unitTree{root: root}
+ if c := tree.list(t, "carlos-future-worker@x.service", "[Unit]", "ConditionPathExists"); len(c) == 0 || c[len(c)-1] != managedboot.AdmittedMarker {
+ t.Fatalf("instance of the new template: %v", c)
+ }
+ })
+ failures := map[string]func(t *testing.T, f *applyFixture, root string){
+ "reload fails": func(t *testing.T, f *applyFixture, root string) {
+ ctl := f.a.ops.systemctl
+ f.a.ops.systemctl = func(args ...string) (string, error) {
+ if args[0] == "daemon-reload" {
+ return "", errors.New("daemon-reload: connection timed out")
+ }
+ return ctl(args...)
+ }
+ },
+ "drop-in cannot be written": func(t *testing.T, f *applyFixture, root string) {
+ writeFileT(t, filepath.Join(root, "etc/systemd/system", newTemplate+".d"), "not a directory")
+ },
+ "declaration unreadable": func(t *testing.T, f *applyFixture, root string) {
+ elsewhere := filepath.Join(t.TempDir(), "named-units.json")
+ writeFileT(t, elsewhere, `{"schema":1,"units":[]}`)
+ _ = os.MkdirAll(filepath.Join(root, "etc/carlos"), 0o755)
+ if err := os.Symlink(elsewhere, filepath.Join(root, "etc/carlos/named-units.json")); err != nil {
+ t.Fatal(err)
+ }
+ },
+ "declaration names a prefix unit": func(t *testing.T, f *applyFixture, root string) {
+ writeFileT(t, filepath.Join(root, "etc/carlos/named-units.json"), `{"schema":1,"units":[{"host":"x.shop.example.com","app":"shop","unit":"carlos-instance-.service"}]}`)
+ },
+ }
+ for name, inject := range failures {
+ t.Run("apply aborts: "+name, func(t *testing.T) {
+ f, root, stage := managedApplyFixture(t, newTemplate)
+ inject(t, f, root)
+ if err := f.a.installUnits(t.Context(), stage, nil); err == nil {
+ t.Fatal("apply published over a failed gate")
+ }
+ if _, err := os.Stat(filepath.Join(root, "etc/systemd/system", newTemplate)); err == nil {
+ t.Fatal("a unit file was published over a failed gate")
+ }
+ })
+ }
+ t.Run("bootstrap aborts on a refused drop-in directory", func(t *testing.T) {
+ root := t.TempDir()
+ stubManagedIdentity(t, root)
+ unitDir := filepath.Join(root, "etc/systemd/system")
+ _ = os.MkdirAll(unitDir, 0o755)
+ if err := os.Symlink(t.TempDir(), filepath.Join(unitDir, "carlos-instance@.service.d")); err != nil {
+ t.Fatal(err)
+ }
+ if err := bootstrap(root, nil); err == nil {
+ t.Fatal("bootstrap published over a refused drop-in directory")
+ }
+ if _, err := os.Stat(filepath.Join(unitDir, "carlos-instance@.service")); err == nil {
+ t.Fatal("bootstrap wrote a workload unit over a failed gate")
+ }
+ })
+ t.Run("root pass publishes nothing over a failed reload", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ missing := filepath.Join(etc, "systemd/system", "carlos-system-update.path")
+ _ = os.Remove(missing)
+ _ = os.Remove(filepath.Join(etc, "systemd/system/carlos-instance@.service.d", managedboot.AdmissionDropInName))
+ var calls []string
+ ctl := func(args ...string) (string, error) {
+ calls = append(calls, strings.Join(args, " "))
+ if args[0] == "daemon-reload" {
+ return "", errors.New("daemon-reload failed")
+ }
+ return "", nil
+ }
+ ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), ctl, func(...string) (string, error) { return "inactive", nil }, t.Logf)
+ if _, err := os.Stat(missing); err == nil {
+ t.Fatal("the root pass published a unit after its gate's reload failed")
+ }
+ if !slices.Equal(calls, []string{"daemon-reload"}) {
+ t.Fatalf("calls after a failed gate: %v", calls)
+ }
+ _ = tree
+ })
+ t.Run("named-unit install aborts on a failed reload", func(t *testing.T) {
+ tree, _ := managedTree(t)
+ prev := namedUnitRoot
+ namedUnitRoot = tree.root
+ defer func() { namedUnitRoot = prev }()
+ raw := []byte(`{"schema":1,"units":[{"host":"jobs.shop.example.com","app":"shop","unit":"shop-jobs.service"}]}`)
+ if err := managedNamedUnitDropIns(raw, func() error { return errors.New("reload failed") }); err == nil {
+ t.Fatal("a failed reload let the declaration go live")
+ }
+ })
+ t.Run("an etc directory that is not <root>/etc is refused on a managed box", func(t *testing.T) {
+ root := t.TempDir()
+ stubManagedIdentity(t, filepath.Dir(filepath.Join(root, "notetc")))
+ if _, err := managedGateEtc(filepath.Join(root, "notetc"), nil, nil); err == nil {
+ t.Fatal("gated a directory the drop-ins do not live under")
+ }
+ })
+}
+
+// TestManagedUnitTrust (Astra R1 P1-3): root's declaration read and the
+// drop-in path go through the trusted descriptor walk. Unprivileged cases:
+// links, modes and writable directories; another owner is the root
+// runner's (TestManagedUnitTrustRoot).
+func TestManagedUnitTrust(t *testing.T) {
+ gate := func(t *testing.T, root string) error {
+ own, _ := unitNames()
+ _, _, err := managedGateUnitsKnown(root, os.Getuid(), own, nil, nil)
+ return err
+ }
+ t.Run("declaration symlinked into service-owned storage", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ store := filepath.Join(t.TempDir(), "named-units.json")
+ writeFileT(t, store, `{"schema":1,"units":[{"host":"x.shop.example.com","app":"shop","unit":"shop-x.service"}]}`)
+ p := filepath.Join(etc, "carlos/named-units.json")
+ _ = os.Remove(p)
+ if err := os.Symlink(store, p); err != nil {
+ t.Fatal(err)
+ }
+ if err := gate(t, tree.root); err == nil {
+ t.Fatal("a symlinked declaration was read")
+ }
+ if _, err := os.Lstat(filepath.Join(etc, "systemd/system/shop-x.service.d")); err == nil {
+ t.Fatal("a linked declaration influenced root's writes")
+ }
+ })
+ t.Run("hard-linked declaration", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ p := filepath.Join(etc, "carlos/named-units.json")
+ if err := os.Link(p, filepath.Join(t.TempDir(), "second")); err != nil {
+ t.Skip("cross-device temp dir: ", err)
+ }
+ if err := gate(t, tree.root); err == nil {
+ t.Fatal("a hard-linked declaration was read")
+ }
+ })
+ t.Run("group-writable declaration", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ _ = os.Chmod(filepath.Join(etc, "carlos/named-units.json"), 0o664)
+ if err := gate(t, tree.root); err == nil {
+ t.Fatal("a group-writable declaration was read")
+ }
+ })
+ t.Run("absent declaration declares none", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ _ = os.Remove(filepath.Join(etc, "carlos/named-units.json"))
+ if err := gate(t, tree.root); err != nil {
+ t.Fatal(err)
+ }
+ })
+ replaced := map[string]func(t *testing.T, p string){
+ "hard-linked drop-in": func(t *testing.T, p string) {
+ _ = os.Link(p, filepath.Join(filepath.Dir(p), "..", "linked-copy"))
+ },
+ "world-writable drop-in": func(t *testing.T, p string) { _ = os.Chmod(p, 0o666) },
+ "symlinked drop-in": func(t *testing.T, p string) {
+ other := filepath.Join(t.TempDir(), "same.conf")
+ writeFileT(t, other, managedboot.AdmissionDropIn)
+ _ = os.Remove(p)
+ _ = os.Symlink(other, p)
+ },
+ }
+ for name, spoil := range replaced {
+ t.Run(name+" is replaced by a root-owned file", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ p := filepath.Join(etc, "systemd/system/carlos-instance@.service.d", managedboot.AdmissionDropInName)
+ spoil(t, p)
+ if err := gate(t, tree.root); err != nil {
+ t.Fatal(err)
+ }
+ st, err := os.Lstat(p)
+ if err != nil || !st.Mode().IsRegular() || st.Mode().Perm() != 0o644 {
+ t.Fatalf("drop-in after the gate: %v %v", st, err)
+ }
+ if nlink := st.Sys().(*syscall.Stat_t).Nlink; nlink != 1 {
+ t.Fatalf("drop-in still has %d links", nlink)
+ }
+ })
+ }
+ refused := map[string]func(t *testing.T, etc string){
+ "group-writable drop-in directory": func(t *testing.T, etc string) {
+ _ = os.Chmod(filepath.Join(etc, "systemd/system/carlos-instance@.service.d"), 0o775)
+ },
+ "symlinked drop-in directory": func(t *testing.T, etc string) {
+ d := filepath.Join(etc, "systemd/system/carlos-instance@.service.d")
+ _ = os.RemoveAll(d)
+ _ = os.Symlink(t.TempDir(), d)
+ },
+ "group-writable unit directory": func(t *testing.T, etc string) {
+ _ = os.Chmod(filepath.Join(etc, "systemd/system"), 0o775)
+ },
+ "world-writable ancestor": func(t *testing.T, etc string) { _ = os.Chmod(filepath.Join(etc, "systemd"), 0o757) },
+ }
+ for name, spoil := range refused {
+ t.Run(name+" is refused", func(t *testing.T) {
+ tree, etc := managedTree(t)
+ spoil(t, etc)
+ if err := gate(t, tree.root); err == nil {
+ t.Fatal("the gate wrote through an unsafe directory")
+ }
+ })
+ }
+}
+
+// TestManagedDeclaredScope (Astra R1 P2-1): a declared name whose drop-in
+// directory is in a maintenance unit's effective scope is refused; the
+// scope is the systemd rule the unit-tree loader (and systemd-analyze in
+// TestManagedUnitConditionTree) applies.
+func TestManagedDeclaredScope(t *testing.T) {
+ for _, u := range []string{"carlos-.service", "carlos-instance-.service", "carlos-instance-control.service", "carlos-edge.service", "shop-.socket", "carlos-dbread.socket"} {
+ if _, err := managedboot.GatedUnits(nil, []string{u}); !errors.Is(err, managedboot.ErrUnitScope) {
+ t.Errorf("declared %s accepted: %v", u, err)
+ }
+ }
+ // The effective scope: each prefix name's directory reaches a
+ // maintenance unit, by the same rule as the systemd-semantics loader.
+ reaches := func(name string) []string {
+ var hit []string
+ for _, m := range managedboot.MaintenanceUnits {
+ if slices.Contains(dropInDirs(m), name+".d") {
+ hit = append(hit, m)
+ }
+ }
+ return hit
+ }
+ if hit := reaches("carlos-instance-.service"); !slices.Contains(hit, "carlos-instance-control.service") {
+ t.Fatalf("carlos-instance-.service scope %v lacks the control service", hit)
+ }
+ if hit := reaches("carlos-.service"); !slices.Contains(hit, "carlos-edge.service") {
+ t.Fatalf("carlos-.service scope %v lacks the edge", hit)
+ }
+ // managedboot's scope rule is the loader's, for every embedded unit and
+ // an instance of each template.
+ own, _ := unitNames()
+ for _, u := range own {
+ for _, name := range []string{u, instanceOf(u)} {
+ if managedboot.DropInScope(name) == nil {
+ continue
+ }
+ if got, want := managedboot.DropInScope(name), dropInDirs(name); !slices.Equal(got, want) {
+ t.Errorf("%s: managedboot scope %v, loader %v", name, got, want)
+ }
+ }
+ }
+ for _, ok := range []string{"shop-api.service", "shop-jobs.socket", "worker@.service"} {
+ if _, err := managedboot.GatedUnits(nil, []string{ok}); err != nil {
+ t.Errorf("%s refused: %v", ok, err)
+ }
+ }
+}
diff --git a/internal/host/managedunits_test.go b/internal/host/managedunits_test.go
index fa518736c..8429fb64b 100644
--- a/internal/host/managedunits_test.go
+++ b/internal/host/managedunits_test.go
@@ -1,3 +1,5 @@
+//go:build linux
+
package host
import (
@@ -146,41 +148,40 @@ func (u unitTree) conditionMet(t *testing.T, unit string) bool {
return true
}
-// managedTree lays out a managed box's unit tree: bootstrap's install plan
-// over a scratch root, a declared named unit, and the admission drop-ins
-// ensureManagedUnitDropIns installs. The fake root is managed: its
-// identity is answered by a stubbed loader.
+// managedTree lays out a managed box's unit tree: a declared named unit,
+// then bootstrap's install plan over a scratch root, which gates the unit
+// set it publishes first. The fake root is managed: its identity is
+// answered by a stubbed loader, and its owner is the test's uid.
func managedTree(t *testing.T) (unitTree, string) {
t.Helper()
root := t.TempDir()
- if err := bootstrap(root, nil); err != nil {
- t.Fatal(err)
- }
etc := filepath.Join(root, "etc")
stubManagedIdentity(t, root)
- writeFileT(t, filepath.Join(etc, "systemd/system/shop-api.service"), "[Unit]\nDescription=shop api\n[Service]\nExecStart=/usr/bin/true\n")
writeFileT(t, filepath.Join(etc, "carlos/named-units.json"), `{"schema":1,"units":[{"host":"api.shop.example.com","app":"shop","unit":"shop-api.service"}]}`)
- changed, err := ensureManagedUnitDropIns(etc)
- if err != nil || !changed {
- t.Fatalf("first install: changed=%v %v", changed, err)
+ if err := bootstrap(root, nil); err != nil {
+ t.Fatal(err)
}
- if changed, err = ensureManagedUnitDropIns(etc); err != nil || changed {
- t.Fatalf("second install changed=%v %v", changed, err)
+ writeFileT(t, filepath.Join(etc, "systemd/system/shop-api.service"), "[Unit]\nDescription=shop api\n[Service]\nExecStart=/usr/bin/true\n")
+ own, _ := unitNames()
+ if changed, _, err := managedGateUnitsKnown(root, os.Getuid(), own, nil, nil); err != nil || changed {
+ t.Fatalf("bootstrap left the gate incomplete: changed=%v %v", changed, err)
}
return unitTree{root: root}, etc
}
-// stubManagedIdentity makes root (and only root) a managed box.
+// stubManagedIdentity makes root (and only root) a managed box owned by
+// the test's uid.
func stubManagedIdentity(t *testing.T, root string) {
t.Helper()
- prev := managedIdentityAt
+ prev, prevUID := managedIdentityAt, managedUnitUID
managedIdentityAt = func(r string) (managedboot.Identity, bool, error) {
if filepath.Clean(r) == filepath.Clean(root) {
return managedboot.Identity{Fleet: "shop", Label: "box-1"}, true, nil
}
return prev(r)
}
- t.Cleanup(func() { managedIdentityAt = prev })
+ managedUnitUID = os.Getuid()
+ t.Cleanup(func() { managedIdentityAt, managedUnitUID = prev, prevUID })
}
func writeFileT(t *testing.T, p, body string) {
@@ -361,9 +362,6 @@ func TestManagedControlWritable(t *testing.T) {
t.Run("byo gets none", func(t *testing.T) {
root := t.TempDir()
- if err := bootstrap(root, nil); err != nil {
- t.Fatal(err)
- }
etc := filepath.Join(root, "etc")
// The real loader answers a non-root-owned fake /etc as a managed box
// with an error; a BYO box's root-owned /etc without the identity
@@ -371,8 +369,12 @@ func TestManagedControlWritable(t *testing.T) {
prev := managedIdentityAt
managedIdentityAt = func(string) (managedboot.Identity, bool, error) { return managedboot.Identity{}, false, nil }
defer func() { managedIdentityAt = prev }()
- if changed, err := ensureManagedUnitDropIns(etc); changed || err != nil {
- t.Fatalf("byo: changed=%v %v", changed, err)
+ if err := bootstrap(root, nil); err != nil {
+ t.Fatal(err)
+ }
+ own, _ := unitNames()
+ if control, err := managedGateUnits(root, own, nil, func() error { t.Fatal("byo reloaded"); return nil }); control || err != nil {
+ t.Fatalf("byo: control=%v %v", control, err)
}
ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), ctl, probe, t.Logf)
matches, _ := filepath.Glob(filepath.Join(etc, "systemd/system/*.d", "*managed*"))
@@ -381,9 +383,9 @@ func TestManagedControlWritable(t *testing.T) {
}
})
t.Run("named unit before its declaration", func(t *testing.T) {
- prev := namedUnitDropInDir
- namedUnitDropInDir = filepath.Join(etc, "systemd/system")
- defer func() { namedUnitDropInDir = prev }()
+ prev := namedUnitRoot
+ namedUnitRoot = tree.root
+ defer func() { namedUnitRoot = prev }()
reloads := 0
raw := []byte(`{"schema":1,"units":[{"host":"jobs.shop.example.com","app":"shop","unit":"shop-jobs.service"}]}`)
if err := managedNamedUnitDropIns(raw, func() error { reloads++; return nil }); err != nil {
@@ -392,9 +394,14 @@ func TestManagedControlWritable(t *testing.T) {
if reloads != 1 || !slices.Contains(tree.list(t, "shop-jobs.service", "[Unit]", "ConditionPathExists"), managedboot.AdmittedMarker) {
t.Fatalf("named unit drop-in: reloads=%d", reloads)
}
- bad := []byte(`{"schema":1,"units":[{"host":"edge.shop.example.com","app":"shop","unit":"carlos-edge.service"}]}`)
- if err := managedNamedUnitDropIns(bad, func() error { return nil }); err == nil {
- t.Fatal("a maintenance unit was accepted as a named unit")
+ for _, unit := range []string{"carlos-edge.service", "carlos-instance-.service", "carlos-.service"} {
+ bad := []byte(`{"schema":1,"units":[{"host":"edge.shop.example.com","app":"shop","unit":"` + unit + `"}]}`)
+ if err := managedNamedUnitDropIns(bad, func() error { return nil }); err == nil {
+ t.Fatalf("%s was accepted as a named unit", unit)
+ }
+ if _, err := os.Lstat(filepath.Join(etc, "systemd/system", unit+".d")); err == nil {
+ t.Fatalf("a refused named unit %s wrote its drop-in directory", unit)
+ }
}
})
}
diff --git a/internal/host/namedrecovery_pass.go b/internal/host/namedrecovery_pass.go
index 1e24dc98d..58f7fee18 100644
--- a/internal/host/namedrecovery_pass.go
+++ b/internal/host/namedrecovery_pass.go
@@ -12,11 +12,8 @@ import (
func (n namedUnitRecovery) passOption(reg *registry.Registry, checks rootRestartChecks, getenv func(string) string) release.PassOption {
remainingNamed := false
return release.WithRecovery(func(ctx context.Context, rt registry.Route) (bool, error) {
- if n.gate != nil {
- if err := n.gate(); err != nil {
- log.Printf("adopt: named-unit recovery %s: %v", rt.Host, err)
- return true, nil
- }
+ if n.refusedByGate(rt) {
+ return true, nil
}
done, err := n.recover(ctx, rt.Host, checks, getenv, reg)
if err != nil {
@@ -36,3 +33,17 @@ func (n namedUnitRecovery) passOption(reg *registry.Registry, checks rootRestart
return checks.allowLegacy()
})
}
+
+// refusedByGate is the managed-box gate before any recovery work: while
+// root has not admitted the box the route is recovered by nothing (logged,
+// reported handled so the pass moves on). nil gate: never refused.
+func (n namedUnitRecovery) refusedByGate(rt registry.Route) bool {
+ if n.gate == nil {
+ return false
+ }
+ if err := n.gate(); err != nil {
+ log.Printf("adopt: named-unit recovery %s: %v", rt.Host, err)
+ return true
+ }
+ return false
+}
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go
index 9ccb2d87e..fc2f213da 100644
--- a/internal/host/systemapply.go
+++ b/internal/host/systemapply.go
@@ -1478,6 +1478,26 @@ func (a *systemApplier) installUnits(ctx context.Context, stagedRoot string, rem
if err != nil {
return err
}
+ // Managed fleets 2b-2 (decisions rule 12): the TARGET build's units are
+ // gated before any of them is published: every staged unit that is not
+ // a maintenance unit (a template the target adds included), beside this
+ // binary's own and the declared named units, then a reload. A failure
+ // fails the apply with nothing published. BYO: no-op.
+ publish, err := unitNames()
+ if err != nil {
+ return err
+ }
+ for _, e := range entries {
+ if !e.IsDir() {
+ publish = append(publish, e.Name())
+ }
+ }
+ if _, err := managedGateEtc(a.etcDir, publish, func() error {
+ _, err := a.ops.systemctl("daemon-reload")
+ return err
+ }); err != nil {
+ return fmt.Errorf("system apply: managed admission drop-ins: %w", err)
+ }
for _, e := range entries {
if groupMarkerPresent(a.etcDir) && groupAutomaticUnit(e.Name()) {
continue
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index 958ed929b..48484bc4c 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -100,24 +100,26 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
}
}
- // Managed fleets 2b-2 (decisions rule 12): before anything below can
- // reload, enable or start a unit, every workload template this binary
- // ships and every declared named unit carries the admission drop-in,
- // and the control service its ReadWritePaths drop-in. A reload makes a
- // written drop-in effective now; a rewritten control drop-in needs the
- // control service's next start, so it is try-restarted. BYO: no-op.
- if workloads, control, err := ensureManagedUnitDropInsSplit(etcDir, nil); err != nil {
- logf("adopt: managed admission drop-ins: %v", err)
- } else if workloads || control {
- if _, err := systemctl("daemon-reload"); err != nil {
- logf("adopt: managed admission drop-ins: daemon-reload: %v", err)
- }
- if control {
- if _, err := systemctl("try-restart", managedboot.ControlUnit); err != nil {
- logf("adopt: managed admission drop-ins: try-restart %s: %v", managedboot.ControlUnit, err)
- }
+ // Managed fleets 2b-2 (decisions rule 12): every unit this pass can
+ // publish is gated before anything below writes, reloads, enables or
+ // starts a unit: the admission drop-ins of this binary's whole unit set
+ // and the declared named units, the control service's ReadWritePaths
+ // drop-in, then a reload. Any failure publishes nothing this pass. A
+ // rewritten control drop-in takes effect at the control service's next
+ // start, so it is try-restarted. BYO: no-op.
+ if own, err := unitNames(); err != nil {
+ logf("adopt: system units: %v", err)
+ return
+ } else if control, err := managedGateEtc(etcDir, own, func() error {
+ _, err := systemctl("daemon-reload")
+ return err
+ }); err != nil {
+ logf("adopt: managed admission drop-ins: %v; no unit published this pass", err)
+ return
+ } else if control {
+ if _, err := systemctl("try-restart", managedboot.ControlUnit); err != nil {
+ logf("adopt: managed admission drop-ins: try-restart %s: %v", managedboot.ControlUnit, err)
}
- logf("adopt: managed admission drop-ins installed")
}
claimSettings, settingsErr := readClaimUnitSettings(filepath.Join(etcDir, "carlos", "host.env"))
diff --git a/internal/host/unitops.go b/internal/host/unitops.go
index 98dfaa4f7..ad4a49277 100644
--- a/internal/host/unitops.go
+++ b/internal/host/unitops.go
@@ -55,8 +55,9 @@ func InstallNamedUnits(envDir, dst string, raw []byte) error {
}
defer unlock()
// Managed fleets 2b-2: on a managed box each declared unit carries the
- // admission condition before the declaration that lets carlos start it
- // exists (decisions rule 12). No-op on a BYO box.
+ // admission condition, durably and reloaded, before the declaration that
+ // lets carlos start it exists (decisions rule 12); any failure installs
+ // nothing. No-op on a BYO box.
if err := managedNamedUnitDropIns(raw, daemonReload); err != nil {
return fmt.Errorf("managed admission drop-ins: %w", err)
}
diff --git a/internal/instancectl/managedadmit.go b/internal/instancectl/managedadmit.go
index b995f62ee..c4620c962 100644
--- a/internal/instancectl/managedadmit.go
+++ b/internal/instancectl/managedadmit.go
@@ -6,6 +6,8 @@ import (
"errors"
"io"
"net/http"
+
+ "github.com/carlosframework/platform/internal/managedboot"
)
// The root admission door (managed fleets 2b-2). Root alone decides whether
@@ -82,8 +84,13 @@ func (s *Server) handleManagedAdmit(w http.ResponseWriter, r *http.Request) {
return
}
if err = s.ManagedAdmit(wire); err != nil {
- s.logf("instance-control: managed admission refused: %v", err)
- http.Error(w, "managed admission refused", http.StatusForbidden)
+ if errors.Is(err, managedboot.ErrAdmissionRefused) {
+ s.logf("instance-control: managed admission refused: %v", err)
+ http.Error(w, "managed admission refused", http.StatusForbidden)
+ return
+ }
+ s.logf("instance-control: managed admission could not be committed: %v", err)
+ http.Error(w, "managed admission could not be committed", http.StatusInternalServerError)
return
}
s.logf("instance-control: managed box admitted by root")
diff --git a/internal/instancectl/managedadmit_linux_test.go b/internal/instancectl/managedadmit_linux_test.go
index 9c2b51110..541459c14 100644
--- a/internal/instancectl/managedadmit_linux_test.go
+++ b/internal/instancectl/managedadmit_linux_test.go
@@ -9,6 +9,8 @@ import (
"crypto/ed25519"
"encoding/base64"
"encoding/json"
+ "errors"
+ "fmt"
"io/fs"
"net"
"net/http"
@@ -255,7 +257,7 @@ func admissionWitness(t *testing.T) {
}
names := regexp.MustCompile(`AdmittedMarker|RootAdmissionDir|AdmissionPath|carlos-managed-root`)
destroy := regexp.MustCompile(`Remove|Truncate|Unlink|Rename|O_TRUNC|rm -`)
- variants := regexp.MustCompile(`CommitAdmissionAs|RootAdmissionAs`)
+ variants := regexp.MustCompile(`CommitAdmissionAs|RootAdmissionAs|LoadIdentityAs`)
seen := 0
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
@@ -296,3 +298,24 @@ func admissionWitness(t *testing.T) {
t.Fatal("the witness found no reference to the admission paths: wrong root?")
}
}
+
+// TestManagedRootAdmitIOError (Fable R1 P3-6): a commit that fails on I/O,
+// not on its merits, answers 5xx; a refusal answers 403.
+func TestManagedRootAdmitIOError(t *testing.T) {
+ for name, tc := range map[string]struct {
+ err error
+ want int
+ }{
+ "io": {errors.New("write admission.json: no space left on device"), http.StatusInternalServerError},
+ "refused": {fmt.Errorf("%w: signature", managedboot.ErrAdmissionRefused), http.StatusForbidden},
+ } {
+ s := &Server{ManagedAdmit: func([]byte) error { return tc.err }, ManagedAdmission: func() (bool, bool, error) { return true, false, nil }}
+ if w := doRequest(s.Handler(), http.MethodPost, ManagedAdmitPath, []byte(`{}`)); w.Code != tc.want {
+ t.Errorf("%s: %d, want %d", name, w.Code, tc.want)
+ }
+ }
+ m := roottest.NewManagedRoot(t)
+ if err := m.Commit([]byte(`{}`)); !errors.Is(err, managedboot.ErrAdmissionRefused) {
+ t.Fatalf("an unsigned object is not a refusal: %v", err)
+ }
+}
diff --git a/internal/managedboot/admission.go b/internal/managedboot/admission.go
index 289198a22..0da15437c 100644
--- a/internal/managedboot/admission.go
+++ b/internal/managedboot/admission.go
@@ -3,6 +3,7 @@ package managedboot
import (
"encoding/base64"
"errors"
+ "fmt"
"os"
)
@@ -16,11 +17,24 @@ const AdmissionPath = RootAdmissionDir + "/admission.json"
// its own ids for a fake root it owns.
type RootOwner struct{ UID, GID int }
+// ErrAdmissionRefused marks a commit refused on its merits (identity,
+// signature, names, ownership, modes, links): the root door answers 403.
+// Any other CommitAdmission error is I/O, answered 5xx.
+var ErrAdmissionRefused = errors.New("managedboot: admission refused")
+
var (
- errNotManaged = errors.New("managedboot: this is not a managed box")
- errAdmissionRoot = errors.New("managedboot: root admission is root's alone")
+ errNotManaged = fmt.Errorf("%w: this is not a managed box", ErrAdmissionRefused)
+ errAdmissionRoot = fmt.Errorf("%w: root admission is root's alone", ErrAdmissionRefused)
)
+// refused marks err as a refusal on its merits unless it is an I/O error.
+func refused(err error) error {
+ if err == nil || errors.Is(err, ErrAdmissionRefused) {
+ return err
+ }
+ return fmt.Errorf("%w: %v", ErrAdmissionRefused, err)
+}
+
// CommitAdmission is root's verified admission of a managed box: euid 0
// only; the identity is loaded with LoadIdentity's checks; wire must verify
// with the identity's release key and name the identity's fleet, label and
@@ -53,10 +67,13 @@ func RootAdmission(root string) (managed, admitted bool, err error) {
func CommitAdmissionAs(root string, wire []byte, owner RootOwner) error {
id, pub, err := admissionIdentity(root, owner)
if err != nil {
+ if errors.Is(err, errIdentity) {
+ return refused(err)
+ }
return err
}
if _, err = VerifyReady(pub, wire, id); err != nil {
- return err
+ return refused(err)
}
return commitAdmission(root, wire, owner, id, pub)
}
diff --git a/internal/managedboot/admission_linux.go b/internal/managedboot/admission_linux.go
index ed4122a1e..16c9ef9e3 100644
--- a/internal/managedboot/admission_linux.go
+++ b/internal/managedboot/admission_linux.go
@@ -22,7 +22,7 @@ const (
)
func admissionDoubt(what string) error {
- return fmt.Errorf("managedboot: root admission refused: %s", what)
+ return fmt.Errorf("%w: %s", ErrAdmissionRefused, what)
}
// openAdmissionDir opens root+RootAdmissionDir one component at a time
diff --git a/internal/managedboot/identity.go b/internal/managedboot/identity.go
index 458b2fc3a..900eabaaf 100644
--- a/internal/managedboot/identity.go
+++ b/internal/managedboot/identity.go
@@ -87,3 +87,9 @@ func ParseIdentity(b []byte) (Identity, error) {
func LoadIdentity(root string) (Identity, bool, error) {
return loadIdentity(root, 0)
}
+
+// LoadIdentityAs is LoadIdentity with owner.UID as the expected owner in
+// place of root. Only tests call it, for a fake root they own.
+func LoadIdentityAs(root string, owner RootOwner) (Identity, bool, error) {
+ return loadIdentity(root, owner.UID)
+}
diff --git a/internal/managedboot/units.go b/internal/managedboot/units.go
index 24f4c4b43..16b882458 100644
--- a/internal/managedboot/units.go
+++ b/internal/managedboot/units.go
@@ -1,14 +1,11 @@
package managedboot
import (
- "bytes"
- "crypto/rand"
- "encoding/hex"
"errors"
- "os"
- "path/filepath"
+ "fmt"
"regexp"
"slices"
+ "strings"
)
// AdmissionDropInName sorts after every platform drop-in (50-carlos-*,
@@ -29,9 +26,10 @@ const ControlDropIn = "[Service]\nReadWritePaths=" + RootAdmissionDir + "\n"
// ControlUnit is the unit ControlDropInName belongs to.
const ControlUnit = "carlos-instance-control.service"
-// WorkloadUnits are the embedded units that run tenant code or tenant data
-// work. On a managed box each carries the admission drop-in, so systemd
-// itself refuses to start one before root admits the box.
+// WorkloadUnits are today's embedded units that run tenant code or tenant
+// data work. Gating does not read this list: GatedUnits gates every unit
+// that is not a MaintenanceUnits entry. It documents the set, and
+// TestManagedUnitClassification pins it to GatedUnits' answer.
var WorkloadUnits = []string{
"carlos-app@.service",
"carlos-app@.socket",
@@ -51,9 +49,10 @@ var WorkloadUnits = []string{
"carlos-dbread@.service",
}
-// MaintenanceUnits are the platform's own units. They carry no admission
-// condition: a joining box must still bootstrap, report status, take
-// updates and answer probes.
+// MaintenanceUnits are the platform's own units, the allowlist of units
+// that carry no admission condition: a joining box must still bootstrap,
+// report status, take updates and answer probes. A unit missing from it is
+// gated until admission, which fails safe.
var MaintenanceUnits = []string{
"carlos-edge.service",
"carlos-relay.service",
@@ -87,89 +86,92 @@ var MaintenanceUnits = []string{
"carlos-managed-boot.service",
}
-var unitNameRE = regexp.MustCompile(`^[A-Za-z0-9:_.\\@-]{1,200}\.(service|socket)$`)
+// unitSuffixes are the systemd unit types a published unit file can be.
+var unitSuffixes = []string{".service", ".socket", ".timer", ".path", ".mount", ".automount", ".slice", ".target", ".swap"}
-// InstallAdmissionDropIns writes <etcDir>/<unit>.d/AdmissionDropInName for
-// every WorkloadUnits template and every declared named unit. A named unit
-// that is a maintenance unit, or not a service or socket name, is refused
-// before anything is written. Present, exact drop-ins are left alone, so a
-// second call changes nothing; a missing or altered one is rewritten.
-func InstallAdmissionDropIns(etcDir string, namedUnits []string) (changed bool, err error) {
- units := append([]string(nil), WorkloadUnits...)
- for _, u := range namedUnits {
- if slices.Contains(MaintenanceUnits, u) || !unitNameRE.MatchString(u) {
- return false, errors.New("managedboot: a named unit cannot carry the admission condition: " + u)
- }
- if !slices.Contains(units, u) {
- units = append(units, u)
- }
- }
- for _, u := range units {
- c, err := ensureDropIn(etcDir, u, AdmissionDropInName, AdmissionDropIn)
- if err != nil {
- return changed, err
+// namedUnitRE is what a declared named unit may be called: a service or
+// socket name, no path separator.
+var namedUnitRE = regexp.MustCompile(`^[A-Za-z0-9:_.\\@-]{1,200}\.(service|socket)$`)
+
+// ErrUnitScope refuses a unit whose admission drop-in would reach a
+// maintenance unit, or a named unit that is not a plain service or socket.
+var ErrUnitScope = errors.New("managedboot: this unit cannot carry the admission condition")
+
+// unitType is ".service" for "x.service", "" for a name with no unit type.
+func unitType(name string) string {
+ for _, t := range unitSuffixes {
+ if strings.HasSuffix(name, t) && len(name) > len(t) {
+ return t
}
- changed = changed || c
}
- return changed, nil
+ return ""
}
-// InstallControlDropIn writes the control service's ReadWritePaths drop-in.
-func InstallControlDropIn(etcDir string) (bool, error) {
- return ensureDropIn(etcDir, ControlUnit, ControlDropInName, ControlDropIn)
-}
-
-// ensureDropIn makes <etcDir>/<unit>.d/<name> a 0644 regular file holding
-// body: temp file, fsync, rename, directory fsync. Neither the directory
-// nor the file may be a symlink.
-func ensureDropIn(etcDir, unit, name, body string) (bool, error) {
- dir := filepath.Join(etcDir, unit+".d")
- if st, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) {
- if err = os.Mkdir(dir, 0o755); err != nil {
- return false, err
- }
- if err = os.Chmod(dir, 0o755); err != nil {
- return false, err
- }
- } else if err != nil {
- return false, err
- } else if !st.IsDir() {
- return false, errors.New("managedboot: " + dir + " is not a directory")
+// DropInScope is every drop-in directory name whose *.conf systemd applies
+// to unit (systemd.unit(5)): the type-wide <type>.d, one per dash prefix
+// of the name before any "@", the template's <name>@.<type>.d for an
+// instance, and the unit's own <unit>.d.
+func DropInScope(unit string) []string {
+ typ := unitType(unit)
+ if typ == "" {
+ return nil
+ }
+ name := strings.TrimSuffix(unit, typ)
+ dirs := []string{strings.TrimPrefix(typ, ".") + ".d"}
+ base := name
+ if at := strings.IndexByte(name, '@'); at >= 0 {
+ base = name[:at]
}
- path := filepath.Join(dir, name)
- if st, err := os.Lstat(path); err == nil && st.Mode().IsRegular() && st.Mode().Perm() == 0o644 {
- if got, err := os.ReadFile(path); err == nil && bytes.Equal(got, []byte(body)) {
- return false, nil
+ for i := 0; i < len(base); i++ {
+ if base[i] == '-' {
+ dirs = append(dirs, base[:i+1]+typ+".d")
}
}
- var suffix [8]byte
- if _, err := rand.Read(suffix[:]); err != nil {
- return false, err
+ if at := strings.IndexByte(name, '@'); at >= 0 && at+1 < len(name) {
+ dirs = append(dirs, name[:at+1]+typ+".d")
}
- tmp := filepath.Join(dir, "."+name+"."+hex.EncodeToString(suffix[:]))
- f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
- if err != nil {
- return false, err
+ return append(dirs, unit+".d")
+}
+
+// reachesMaintenance reports whether name's own drop-in directory is in
+// the drop-in scope of a maintenance unit: a prefix form such as
+// "carlos-.service" or "carlos-instance-.service" is.
+func reachesMaintenance(name string) bool {
+ if slices.Contains(MaintenanceUnits, name) || strings.HasSuffix(strings.TrimSuffix(name, unitType(name)), "-") {
+ return true
}
- defer os.Remove(tmp)
- if err = f.Chmod(0o644); err == nil {
- if _, err = f.WriteString(body); err == nil {
- err = f.Sync()
+ for _, m := range MaintenanceUnits {
+ if slices.Contains(DropInScope(m), name+".d") {
+ return true
}
}
- if cerr := f.Close(); err == nil {
- err = cerr
- }
- if err != nil {
- return false, err
- }
- if err = os.Rename(tmp, path); err != nil {
- return false, err
+ return false
+}
+
+// GatedUnits is the set of units a managed box conditions on root's
+// admission when units are published beside the declared named units:
+// default-gated, every unit file that is not a MaintenanceUnits entry
+// (the allowlist), so a template a later binary adds is gated without
+// being listed anywhere. A named unit must be a plain service or socket
+// name; any gated name whose drop-in would reach a maintenance unit is
+// refused with ErrUnitScope before anything is written. Sorted, unique.
+func GatedUnits(units, named []string) ([]string, error) {
+ var out []string
+ for _, u := range named {
+ if !namedUnitRE.MatchString(u) || strings.ContainsAny(u, "/") || reachesMaintenance(u) {
+ return nil, fmt.Errorf("%w: %s", ErrUnitScope, u)
+ }
+ out = append(out, u)
}
- d, err := os.Open(dir)
- if err != nil {
- return true, err
+ for _, u := range units {
+ if unitType(u) == "" || strings.ContainsAny(u, "/") || slices.Contains(MaintenanceUnits, u) {
+ continue
+ }
+ if reachesMaintenance(u) {
+ return nil, fmt.Errorf("%w: %s", ErrUnitScope, u)
+ }
+ out = append(out, u)
}
- defer d.Close()
- return true, d.Sync()
+ slices.Sort(out)
+ return slices.Compact(out), nil
}
diff --git a/internal/managedboot/userdata_rootrunner_linux_test.go b/internal/managedboot/userdata_rootrunner_linux_test.go
index 0585b0e8a..47c94c5da 100644
--- a/internal/managedboot/userdata_rootrunner_linux_test.go
+++ b/internal/managedboot/userdata_rootrunner_linux_test.go
@@ -23,11 +23,9 @@ import (
// TestManagedCloudInitRootOwnership runs the rendered script and its
// helpers as real uid 0, where the expected owner is root:root (no owner
// variable), and checks that files owned by the service uid are refused.
-// Root runner only: it fails, never skips, without its capability.
+// Root runner only (the rootrunner build tag): it fails, never skips,
+// without uid 0.
func TestManagedCloudInitRootOwnership(t *testing.T) {
- if os.Getenv("CARLOS_MANAGED_ROOT_TEST") != "1" {
- t.Fatal("CARLOS_MANAGED_ROOT_TEST=1 is required: this witness runs only on the root runner")
- }
if os.Geteuid() != 0 {
t.Fatal("this witness must run as uid 0")
}