feat: systemd-enforced admission gate for managed boxes
Root owns admission on a managed box. The console signs ready.json with its release key (managedboot.SignReady); the agent only relays it to the root door's POST /managed-admit, which verifies it against the box's root-owned identity and commits admission.json then the admitted marker in the root:root 0700 /var/lib/carlos-managed-root. RootAdmission re-verifies on every read; the root door refuses workload start routes with 409 while a managed box is not admitted. Every workload template and declared named unit carries the root-owned ConditionPathExists drop-in (ensureSystemUnits and InstallNamedUnits), and carlos-instance-control gets ReadWritePaths for the admission dir. Agent-side gates (activator, exec backend, edge 503, start routes, config sync bounces, reconcile Joining, worker boot pass) and the root pass's round-1 callbacks are a second layer. A joining box reads ready.json at arming, per serial change, else once a minute, and never after admission. Root-only witnesses are under the rootrunner tag (ledger R1); no CI job.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
30 files changed,
+3,542
−75
internal/appconfig/declarations.go+18 −0internal/console/managed_e2e_test.go+8 −8internal/console/managedbudget_test.go+1 −2internal/console/managedready_test.go+9 −7internal/console/managedreadysigned_test.go+111 −0internal/console/managedworker.go+28 −16internal/console/managedworker_test.go+2 −3internal/host/agent.go+71 −9internal/host/managedjoin.go+302 −0internal/host/managedjoin_root_linux_test.go+352 −0internal/host/managedjoin_test.go+649 −0internal/host/managedunits.go+99 −0internal/host/managedunits_test.go+400 −0internal/host/namedrecovery.go+3 −0internal/host/namedrecovery_pass.go+6 −0internal/host/systemunits.go+21 −0internal/host/unitops.go+6 −0internal/instancectl/managedadmit.go+127 −0internal/instancectl/managedadmit_linux_test.go+298 −0internal/instancectl/server.go+47 −30internal/managedboot/admission.go+95 −0internal/managedboot/admission_linux.go+212 −0internal/managedboot/admission_linux_test.go+231 −0internal/managedboot/admission_other.go+18 −0internal/managedboot/ready.go+107 −0internal/managedboot/ready_test.go+90 −0internal/managedboot/roottest/roottest.go+113 −0internal/provision/reconcile.go+14 −0internal/provision/reconcile_joining_test.go+100 −0internal/provision/sidecar_reconcile.go+4 −0
diff --git a/internal/appconfig/declarations.go b/internal/appconfig/declarations.go| index 540cf3cfc..7d1293c33 100644 |
| --- a/internal/appconfig/declarations.go |
| +++ b/internal/appconfig/declarations.go |
| @@ -21,6 +21,7 @@ import ( |
| "encoding/json" |
| "fmt" |
| "io" |
| + "sort" |
| "github.com/carlosframework/platform/internal/controlname" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -108,6 +109,23 @@ func ValidateDeclarations(raw []byte) error { |
| return err |
| } |
| +// DeclaredUnits is the unit names a declaration file declares, read with |
| +// the same decoder the pass uses; nil raw (an absent file) declares none. |
| +// A managed box conditions each of them on root's admission before the |
| +// file goes live (internal/host ensureManagedUnitDropIns). |
| +func DeclaredUnits(raw []byte) ([]string, error) { |
| + d, err := parseDeclarations("declarations", raw) |
| + if err != nil { |
| + return nil, err |
| + } |
| + units := make([]string, 0, len(d.byUnit)) |
| + for u := range d.byUnit { |
| + units = append(units, u) |
| + } |
| + sort.Strings(units) |
| + return units, nil |
| +} |
| + |
| // parseDeclarations is the one decoder: schema 1, one JSON document with |
| // nothing after it (as the release path reads the file), valid names, |
| // one entry per host and one per unit. raw nil is an absent file and |
diff --git a/internal/console/managed_e2e_test.go b/internal/console/managed_e2e_test.go| index 9960dd9ce..9beeeef85 100644 |
| --- a/internal/console/managed_e2e_test.go |
| +++ b/internal/console/managed_e2e_test.go |
| @@ -24,6 +24,7 @@ import ( |
| "github.com/carlosframework/platform/internal/compute" |
| "github.com/carlosframework/platform/internal/fleetstore" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| "github.com/carlosframework/platform/internal/objstore" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/status" |
| @@ -120,14 +121,14 @@ func e2eReady(t *testing.T, s *Server, now time.Time) { |
| // This models the deferred box contract only. Console readiness and persistence |
| // are real; production bootstrap and workload enforcement are not exercised. |
| type joiningFakeBox struct { |
| - marker string |
| - fleet, label string |
| + marker string |
| + fleet, label, op string |
| + pub ed25519.PublicKey |
| } |
| func (b joiningFakeBox) reconcile(raw []byte) []string { |
| if _, err := os.Stat(b.marker); err == nil { |
| - var ready managedReadyObject |
| - if json.Unmarshal(raw, &ready) != nil || ready.Fleet != b.fleet || ready.Label != b.label || ready.ReadyAt.IsZero() || ready.Op == "" { |
| + if _, err := managedboot.VerifyReady(b.pub, raw, managedboot.Identity{Fleet: b.fleet, Label: b.label, Op: b.op}); err != nil { |
| return nil |
| } |
| if os.Remove(b.marker) != nil { |
| @@ -146,9 +147,9 @@ func TestManagedFleetFakeEndToEnd(t *testing.T) { |
| if err := os.WriteFile(marker, []byte("joining"), 0600); err != nil { |
| t.Fatal(err) |
| } |
| - locals[b.Label] = joiningFakeBox{marker, b.Fleet, b.Label} |
| + locals[b.Label] = joiningFakeBox{marker, b.Fleet, b.Label, b.OpID, s.cfg.ReleasePub} |
| for _, raw := range []string{"", `{`, `{"fleet":"wrong","label":"box-1","op":"op","ready_at":"2026-11-01T00:00:00Z"}`, `{"fleet":"production","label":"wrong","op":"op","ready_at":"2026-11-01T00:00:00Z"}`} { |
| - rebooted := joiningFakeBox{marker, b.Fleet, b.Label} |
| + rebooted := joiningFakeBox{marker, b.Fleet, b.Label, b.OpID, s.cfg.ReleasePub} |
| if len(rebooted.reconcile([]byte(raw))) != 0 { |
| t.Fatal("joining box started work") |
| } |
| @@ -836,8 +837,7 @@ func TestManaged2B1SecretSurfaces(t *testing.T) { |
| raw, _ := json.Marshal(b) |
| surfaces["box "+b.Label] = raw |
| obj, _, err := s.cfg.Releases.Get(ctx, managedReadyKey(b)) |
| - var ready managedReadyObject |
| - if err != nil || json.Unmarshal(obj, &ready) != nil || ready.Fleet != b.Fleet || ready.Label != b.Label || ready.ReadyAt.IsZero() { |
| + if err != nil || !s.managedReadyMatches(obj, b) { |
| t.Fatalf("ready object for %s: %q %v", b.Label, obj, err) |
| } |
| surfaces["ready "+b.Label] = obj |
diff --git a/internal/console/managedbudget_test.go b/internal/console/managedbudget_test.go| index 2552efb86..17d46677a 100644 |
| --- a/internal/console/managedbudget_test.go |
| +++ b/internal/console/managedbudget_test.go |
| @@ -3,7 +3,6 @@ package console |
| import ( |
| "context" |
| "database/sql" |
| - "encoding/json" |
| "fmt" |
| "go/ast" |
| "go/parser" |
| @@ -237,7 +236,7 @@ func TestManagedPublicationRefreshBudget(t *testing.T) { |
| st := countReadiness(s) |
| st.failPut = true |
| b = workerStep(t, s, now) |
| - raw, _ := json.Marshal(managedReadyObject{b.Fleet, b.Label, b.ReadyAt, b.OpID}) |
| + raw, _ := s.managedReadyWire(b) |
| if _, err := st.Store.Put(context.Background(), managedReadyKey(b), raw, ""); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/managedready_test.go b/internal/console/managedready_test.go| index d724ee060..485c89555 100644 |
| --- a/internal/console/managedready_test.go |
| +++ b/internal/console/managedready_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/compute" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/status" |
| @@ -86,8 +87,9 @@ func TestManagedReadinessSixChecks(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - var object map[string]any |
| - if err = json.Unmarshal(raw, &object); err != nil || len(object) != 4 || object["op"] != b.OpID { |
| + // 2b-2: the object is the record signed with the console's release key. |
| + object, err := managedboot.VerifyReady(s.cfg.ReleasePub, raw, managedboot.Identity{Fleet: b.Fleet, Label: b.Label, Op: b.OpID}) |
| + if err != nil || object.Op != b.OpID || !object.ReadyAt.Equal(b.ReadyAt) { |
| t.Fatal(string(raw), err) |
| } |
| reg, _ := openRegistry(s.cfg.Registry) |
| @@ -402,7 +404,7 @@ func TestManagedReadinessDrainRecovery(t *testing.T) { |
| st.failPut = false |
| at := b.ReadyAt |
| if stage != "before-put" { |
| - raw, _ := json.Marshal(managedReadyObject{b.Fleet, b.Label, b.ReadyAt, b.OpID}) |
| + raw, _ := s.managedReadyWire(b) |
| if _, err := s.cfg.Releases.Put(context.Background(), managedReadyKey(b), raw, ""); err != nil { |
| t.Fatal(err) |
| } |
| @@ -470,7 +472,7 @@ func TestManagedJoiningPlacement(t *testing.T) { |
| } |
| st.failPut = false |
| // Simulate a crash after ready was persisted, before the conditional clear. |
| - raw, _ := json.Marshal(managedReadyObject{b.Fleet, b.Label, b.ReadyAt, b.OpID}) |
| + raw, _ := s.managedReadyWire(b) |
| s.cfg.Releases.Put(context.Background(), managedReadyKey(b), raw, "") |
| b = workerAdvance(t, s, b, func(b *managedBox) { b.State = "ready" }) |
| if _, err := s.drainBox(context.Background(), b.Fleet, b.Label); err != nil { |
| @@ -544,7 +546,7 @@ func TestManagedDelayedPublicationFreshness(t *testing.T) { |
| s.managedExtra = readyExtras{managedCheck{State: "pass"}, managedCheck{State: "pending"}} |
| case "matching": |
| beat.GeneratedAt = now.Add(-time.Hour) |
| - raw, _ := json.Marshal(managedReadyObject{b.Fleet, b.Label, b.ReadyAt, b.OpID}) |
| + raw, _ := s.managedReadyWire(b) |
| if _, err := st.Store.Put(context.Background(), managedReadyKey(b), raw, ""); err != nil { |
| t.Fatal(err) |
| } |
| @@ -575,8 +577,8 @@ func TestManagedDelayedPublicationFreshness(t *testing.T) { |
| t.Fatalf("fresh passes did not publish: %d %+v", st.puts, b) |
| } |
| raw, _, err := s.cfg.Releases.Get(context.Background(), managedReadyKey(b)) |
| - var got managedReadyObject |
| - if err != nil || json.Unmarshal(raw, &got) != nil || !got.ReadyAt.Equal(readyAt) || got.Op != b.OpID { |
| + got, verr := managedboot.VerifyReady(s.cfg.ReleasePub, raw, managedboot.Identity{Fleet: b.Fleet, Label: b.Label, Op: b.OpID}) |
| + if err != nil || verr != nil || !got.ReadyAt.Equal(readyAt) || got.Op != b.OpID { |
| t.Fatal("published object", string(raw), err) |
| } |
| case "matching": |
diff --git a/internal/console/managedreadysigned_test.go b/internal/console/managedreadysigned_test.go| new file mode 100644 |
| index 000000000..eeb18241b |
| --- /dev/null |
| +++ b/internal/console/managedreadysigned_test.go |
| @@ -0,0 +1,111 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot" |
| +) |
| + |
| +// TestManagedReadySigned: the published ready object is the record signed |
| +// with Config.Key, verifiable with Config.ReleasePub; anything else at the |
| +// key is 2a's mismatch (uncertainty: no PUT, no revoke, no terminate); with |
| +// no signing key nothing is written and the box waits with a reason. |
| +func TestManagedReadySigned(t *testing.T) { |
| + t.Run("published object is signed", func(t *testing.T) { |
| + s, b, now := readyFixture(t) |
| + st := countReadiness(s) |
| + b = workerStep(t, s, now) |
| + if b.State != "ready" || st.puts != 1 { |
| + t.Fatalf("state %s puts %d", b.State, st.puts) |
| + } |
| + raw, _, err := st.Store.Get(context.Background(), managedReadyKey(b)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := managedboot.VerifyReady(s.cfg.ReleasePub, raw, managedboot.Identity{Fleet: b.Fleet, Label: b.Label, Op: b.OpID}) |
| + if err != nil || !got.ReadyAt.Equal(b.ReadyAt) || got.Kind != managedboot.ReadyKind { |
| + t.Fatalf("published object does not verify: %s %v", raw, err) |
| + } |
| + want, _ := s.managedReadyWire(b) |
| + if !bytes.Equal(raw, want) { |
| + t.Fatal("published bytes are not the deterministic signed wire") |
| + } |
| + }) |
| + sign := func(priv ed25519.PrivateKey, payload any, extra map[string]any) []byte { |
| + p, _ := json.Marshal(payload) |
| + b64 := base64.StdEncoding.EncodeToString(p) |
| + w := map[string]any{"payload": b64, "sig": base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(b64)))} |
| + for k, v := range extra { |
| + w[k] = v |
| + } |
| + out, _ := json.Marshal(w) |
| + return out |
| + } |
| + _, foreign, _ := ed25519.GenerateKey(nil) |
| + bad := map[string]func(s *Server, b managedBox) []byte{ |
| + "foreign key": func(s *Server, b managedBox) []byte { |
| + raw, _ := managedboot.SignReady(foreign, managedboot.ReadyRecord{Schema: 1, Kind: managedboot.ReadyKind, Fleet: b.Fleet, Label: b.Label, Op: b.OpID, ReadyAt: b.ReadyAt}) |
| + return raw |
| + }, |
| + "unsigned 2a object": func(s *Server, b managedBox) []byte { |
| + raw, _ := json.Marshal(map[string]any{"fleet": b.Fleet, "label": b.Label, "ready_at": b.ReadyAt, "op": b.OpID}) |
| + return raw |
| + }, |
| + "other kind": func(s *Server, b managedBox) []byte { |
| + return sign(s.cfg.Key, managedboot.ReadyRecord{Schema: 1, Kind: "channel-pointer", Fleet: b.Fleet, Label: b.Label, Op: b.OpID, ReadyAt: b.ReadyAt}, nil) |
| + }, |
| + "mismatched op": func(s *Server, b managedBox) []byte { |
| + return sign(s.cfg.Key, managedboot.ReadyRecord{Schema: 1, Kind: managedboot.ReadyKind, Fleet: b.Fleet, Label: b.Label, Op: "ffffffffffffffffffffffffffffffff", ReadyAt: b.ReadyAt}, nil) |
| + }, |
| + "scoped grant": func(s *Server, b managedBox) []byte { |
| + return sign(s.cfg.Key, managedboot.ReadyRecord{Schema: 1, Kind: managedboot.ReadyKind, Fleet: b.Fleet, Label: b.Label, Op: b.OpID, ReadyAt: b.ReadyAt.UTC()}, map[string]any{"grant": map[string]string{"pub": "x"}}) |
| + }, |
| + } |
| + for name, object := range bad { |
| + t.Run(name, func(t *testing.T) { |
| + s, b, now := readyFixture(t) |
| + st := countReadiness(s) |
| + st.failPut = true |
| + b = workerStep(t, s, now) |
| + st.failPut = false |
| + if b.State != "publishing" { |
| + t.Fatal(b.State) |
| + } |
| + raw := object(s, b) |
| + if _, err := st.Store.Put(context.Background(), managedReadyKey(b), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + puts := st.puts |
| + b = workerStep(t, s, now.Add(time.Second)) |
| + if b.State != "publishing" || st.puts != puts || st.deletes != 0 { |
| + t.Fatalf("%s accepted or modified: %+v puts %d", name, b, st.puts-puts) |
| + } |
| + b = workerStep(t, s, now.Add(20*time.Minute)) |
| + if b.State != "publishing" || b.LastError != "uncertain" || b.TokenRevoked || !b.TerminateAttemptedAt.IsZero() || st.deletes != 0 || st.puts != puts { |
| + t.Fatalf("unsafe handling of %s: %+v", name, b) |
| + } |
| + if got, _, _ := st.Store.Get(context.Background(), managedReadyKey(b)); !bytes.Equal(got, raw) { |
| + t.Fatal("the object at the key was replaced") |
| + } |
| + }) |
| + } |
| + t.Run("no signing key", func(t *testing.T) { |
| + s, b, now := readyFixture(t) |
| + st := countReadiness(s) |
| + s.cfg.Key = nil |
| + b = workerStep(t, s, now) |
| + b = workerStep(t, s, now.Add(time.Second)) |
| + if b.State != "publishing" || st.puts != 0 { |
| + t.Fatalf("state %s puts %d", b.State, st.puts) |
| + } |
| + if got := b.Checks["recovery"]; got.State != "pending" || got.Reason != managedReadyKeyMissing { |
| + t.Fatalf("no reason shown: %+v", b.Checks) |
| + } |
| + }) |
| +} |
diff --git a/internal/console/managedworker.go b/internal/console/managedworker.go| index 0465d8ee1..b001a48a1 100644 |
| --- a/internal/console/managedworker.go |
| +++ b/internal/console/managedworker.go |
| @@ -1,7 +1,6 @@ |
| package console |
| import ( |
| - "bytes" |
| "context" |
| "crypto/ed25519" |
| "crypto/rand" |
| @@ -9,9 +8,7 @@ import ( |
| "database/sql" |
| "encoding/base64" |
| "encoding/hex" |
| - "encoding/json" |
| "errors" |
| - "io" |
| "log" |
| "os" |
| "sync" |
| @@ -786,13 +783,24 @@ func managedReadyKey(b managedBox) string { |
| return "fleets/" + b.Fleet + "/boxes/" + b.Label + "/ready.json" |
| } |
| -type managedReadyObject struct { |
| - Fleet string `json:"fleet"` |
| - Label string `json:"label"` |
| - ReadyAt time.Time `json:"ready_at"` |
| - Op string `json:"op"` |
| +// managedReadyWire is the box's ready object: the record signed with the |
| +// console's release key (Config.Key), which the box's root verifies with |
| +// the identity's release key before admitting anything. Deterministic, so |
| +// a re-issued create-only PUT carries identical bytes. |
| +func (s *Server) managedReadyWire(b managedBox) ([]byte, error) { |
| + return managedboot.SignReady(s.cfg.Key, managedboot.ReadyRecord{Schema: 1, Kind: managedboot.ReadyKind, Fleet: b.Fleet, Label: b.Label, Op: b.OpID, ReadyAt: b.ReadyAt}) |
| } |
| +// managedReadyMatches reports whether raw is b's own signed ready object. |
| +func (s *Server) managedReadyMatches(raw []byte, b managedBox) bool { |
| + got, err := managedboot.VerifyReady(s.cfg.ReleasePub, raw, managedboot.Identity{Fleet: b.Fleet, Label: b.Label, Op: b.OpID}) |
| + return err == nil && !b.ReadyAt.IsZero() && got.ReadyAt.Equal(b.ReadyAt) |
| +} |
| + |
| +// managedReadyKeyMissing is the publishing box's reason while the console |
| +// has no signing key: no ready object can be written, so none is. |
| +const managedReadyKeyMissing = "waiting for the console's release signing key to publish the ready record" // COPY |
| + |
| // managedPublicationFreshFor is how long completed checks may authorize a |
| // first ready-object PUT. Older or missing ReadinessCheckedAt needs a refresh. |
| const managedPublicationFreshFor = time.Minute |
| @@ -814,7 +822,8 @@ func (s *Server) verifyManagedPublication(ctx context.Context, b managedBox, now |
| if err = s.managedOutsideLock(ctx, b, func(c context.Context) { raw, _, getErr = s.cfg.Releases.Get(c, key) }); err != nil { |
| return err |
| } |
| - if errors.Is(getErr, os.ErrNotExist) && !b.ReadyAt.IsZero() && b.ReadyAt.Before(b.LaunchStartedAt.Add(20*time.Minute)) { |
| + keyMissing := len(s.cfg.Key) != ed25519.PrivateKeySize |
| + if errors.Is(getErr, os.ErrNotExist) && !keyMissing && !b.ReadyAt.IsZero() && b.ReadyAt.Before(b.LaunchStartedAt.Add(20*time.Minute)) { |
| read, published, err := s.managedPublishFresh(ctx, b, now) |
| if err != nil { |
| return err |
| @@ -837,6 +846,9 @@ func (s *Server) verifyManagedPublication(ctx context.Context, b managedBox, now |
| err = getErr |
| if errors.Is(err, os.ErrNotExist) { |
| if now.Before(b.LaunchStartedAt.Add(20 * time.Minute)) { |
| + if keyMissing && b.Checks["recovery"].Reason != managedReadyKeyMissing { |
| + return s.managedRetry(ctx, b, managedReadyKeyMissing, now, false) |
| + } |
| return nil |
| } |
| next := clearManagedPublicationUncertainty(b) |
| @@ -848,12 +860,9 @@ func (s *Server) verifyManagedPublication(ctx context.Context, b managedBox, now |
| if err != nil { |
| return s.managedPublicationUncertain(ctx, b, now) |
| } |
| - var got managedReadyObject |
| - decoder := json.NewDecoder(bytes.NewReader(raw)) |
| - decoder.DisallowUnknownFields() |
| - decodeErr := decoder.Decode(&got) |
| - var extra any |
| - if decodeErr != nil || decoder.Decode(&extra) != io.EOF || got.Fleet != b.Fleet || got.Label != b.Label || got.Op != b.OpID || !got.ReadyAt.Equal(b.ReadyAt) || b.ReadyAt.IsZero() { |
| + // Unsigned, foreign-key, other-kind or mismatched: uncertainty, exactly |
| + // as a mismatched plain object was (no PUT, no revoke, no terminate). |
| + if !s.managedReadyMatches(raw, b) { |
| return s.managedPublicationUncertain(ctx, b, now) |
| } |
| next := clearManagedPublicationUncertainty(b) |
| @@ -884,7 +893,10 @@ type managedReadyRead struct { |
| // time read inside the observation. A timeout may hide a successful write, so |
| // only the following GET decides. published false means no PUT was issued. |
| func (s *Server) managedPublishFresh(ctx context.Context, b managedBox, now time.Time) (managedReadyRead, bool, error) { |
| - body, err := json.Marshal(managedReadyObject{Fleet: b.Fleet, Label: b.Label, ReadyAt: b.ReadyAt, Op: b.OpID}) |
| + if len(s.cfg.Key) != ed25519.PrivateKeySize { |
| + return managedReadyRead{}, false, nil |
| + } |
| + body, err := s.managedReadyWire(b) |
| if err != nil { |
| return managedReadyRead{}, false, errManagedWorker |
| } |
diff --git a/internal/console/managedworker_test.go b/internal/console/managedworker_test.go| index 777a6f8a4..360cbfb5a 100644 |
| --- a/internal/console/managedworker_test.go |
| +++ b/internal/console/managedworker_test.go |
| @@ -2,7 +2,6 @@ package console |
| import ( |
| "context" |
| - "encoding/json" |
| "errors" |
| "github.com/carlosframework/platform/internal/release" |
| "os" |
| @@ -455,7 +454,7 @@ func TestManagedPartialFailurePublication(t *testing.T) { |
| } |
| b = workerStep(t, s, now) |
| b = workerAdvance(t, s, b, func(b *managedBox) { b.State = "publishing"; b.ReadyAt = now.Add(time.Minute); b.EnrolDrainStart = 123 }) |
| - raw, err := json.Marshal(managedReadyObject{Fleet: b.Fleet, Label: b.Label, Op: b.OpID, ReadyAt: b.ReadyAt}) |
| + raw, err := s.managedReadyWire(b) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -895,7 +894,7 @@ func TestManagedPublicationUncertaintyResolves(t *testing.T) { |
| } |
| st.getErr = nil |
| if published { |
| - raw, _ := json.Marshal(managedReadyObject{Fleet: b.Fleet, Label: b.Label, ReadyAt: b.ReadyAt, Op: b.OpID}) |
| + raw, _ := s.managedReadyWire(b) |
| if _, err = st.Put(context.Background(), managedReadyKey(b), raw, ""); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 5dd252a99..25706b076 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -273,6 +273,24 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| 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) |
| + } |
| if admission != nil { |
| armedFixedAdmission.Store(admission) |
| armedBoxRolePublisher.Store(&boxRolePublisher{Source: admission}) |
| @@ -656,6 +674,9 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| } |
| return departureLife |
| }) |
| + if join != nil { |
| + admissionOption = join.bind(svc, eb) |
| + } |
| armHAPlacement(svc, PageOperator) |
| // Sizes (#329): the provisioning passes' PolicyChanged tells this |
| // Service a row's size column moved, and the status tick reads each |
| @@ -883,6 +904,16 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| case <-startupCtx.Done(): |
| return |
| } |
| + if join != nil { |
| + // A managed box runs the boot pass once root admits it |
| + // (managedJoin.onAdmit), never while joining. |
| + join.setOnAdmit(func() { |
| + go runWorkerBootPassAfterAdmission(startupCtx, nil, reg.List, svc.WakeWorker) |
| + }) |
| + if join.Joining() { |
| + return |
| + } |
| + } |
| runWorkerBootPassAfterAdmission(startupCtx, admission, reg.List, svc.WakeWorker) |
| }() |
| } |
| @@ -1028,7 +1059,8 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| servingWorker.Store(w) |
| }) |
| go adoptLoop(reg, svc, sd, claims.Writes) |
| - go fastConvergeLoop(reg, svc, sd, claims.Writes, serialClaims, bs, boxJudge, claims.Providers.Provision) |
| + provisionConfigure := managedJoinProvision(join, claims.Providers.Provision) |
| + go fastConvergeLoop(reg, svc, sd, claims.Writes, serialClaims, bs, boxJudge, provisionConfigure) |
| if logSink != nil { |
| go logshipLoop(logSink, status.Label(readMachineID())) |
| } |
| @@ -1045,7 +1077,7 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // by CARLOS_HOST_METRICS โ one log line and nothing else where unset. |
| go memwatchLoop() |
| go domainsLoop(reg, peekAcmeCache(args), claims.Writes.Enabled) |
| - go instancesLoop(reg, claims.Writes, bs, boxJudge, claims.Providers.Provision) |
| + go instancesLoop(reg, claims.Writes, bs, boxJudge, provisionConfigure) |
| // The deployment-global election, armed BEFORE the loops it gates so a |
| // single-box deployment is holding well before their first tick (a |
| // minute away) โ see housekeeper.go. Not a `go` of its own: it publishes |
| @@ -1864,10 +1896,12 @@ func syncExecSerializedFiltered(ctx context.Context, keep func(registry.Route) b |
| // revision once it is active; refusing: no restart. configSyncMu above |
| // is what makes ConfigDelivered serial per host. |
| var err error |
| - if cb, ok := rolloutConfigCallbacks(ctx, store, configLegs{awake: managedAwake(svc, reg), restart: bounce(svc)}); ok { |
| + // A joining managed box bounces nothing (managedGateStart). |
| + restartHost := managedGateStart(bounce(svc)) |
| + if cb, ok := rolloutConfigCallbacks(ctx, store, configLegs{awake: managedAwake(svc, reg), restart: restartHost}); ok { |
| err = appconfig.SyncExecWithCallbacks(ctx, reg, store, priv, dd, os.Getenv("PLATFORM_APPS_DOMAIN"), cb, opts...) |
| } else { |
| - err = appconfig.SyncExec(ctx, reg, store, priv, dd, bounce(svc), os.Getenv("PLATFORM_APPS_DOMAIN"), configAckFunc(ctx, store, "agent"), opts...) |
| + err = appconfig.SyncExec(ctx, reg, store, priv, dd, restartHost, os.Getenv("PLATFORM_APPS_DOMAIN"), configAckFunc(ctx, store, "agent"), opts...) |
| } |
| // A filtered pass names only the routes it kept, so it is never |
| // complete: a host it left out keeps its wait (pendingDirs.record). |
| @@ -2716,6 +2750,10 @@ type fastDeps struct { |
| // the agent armed (restartGainSeed), so the first restart request after |
| // a fresh box comes up is acted on. nil = not armed. |
| restartGain func(ctx context.Context, now time.Time) |
| + |
| + // managedReady is a joining managed box's ready leg (managedJoin.readyLeg), |
| + // asked after the serial read on every tick; nil on a BYO box. |
| + managedReady func(ctx context.Context, now time.Time, serial int64, serialOK bool) |
| } |
| // canaryRead is one canary group's last good pointer read: the head it |
| @@ -3181,6 +3219,12 @@ func fastTick(ctx context.Context, d *fastDeps, now time.Time) { |
| } |
| fullRan := false |
| doc, _, err := release.ReadSerial(ctx, d.store) |
| + // Every tick, whatever the serial did: the leg tracks its own last-seen |
| + // serial, so the full pass's clamp below never suppresses or repeats |
| + // a ready read. It returns at once on an admitted or BYO box. |
| + if d.managedReady != nil { |
| + d.managedReady(ctx, now, doc.Serial, err == nil) |
| + } |
| switch { |
| case err != nil: |
| if !d.serialBroken { |
| @@ -3487,6 +3531,14 @@ func fastConvergeLoop(reg *registry.Registry, svc *activator.Service, sd *schedu |
| // sweep instead of the sweep re-cycling the service every tick. The |
| // remaining fields are filled in right below. |
| d := &fastDeps{reg: reg, store: store, pub: pub, optDir: optDir, serialNotify: serialNotify, fullDue: &backstopFullDue} |
| + if join := armedManagedJoin.Load(); join != nil { |
| + d.managedReady = func(ctx context.Context, now time.Time, serial int64, serialOK bool) { |
| + // Root's 200 flipped the box: one full reconcile now. |
| + if join.readyLeg(ctx, d.store, now, serial, serialOK) && d.fullDue != nil { |
| + d.fullDue.Store(true) |
| + } |
| + } |
| + } |
| if svc != nil { |
| d.coordinator, _ = svc.Coordinator.(interface{ SignalTick() }) |
| } |
| @@ -5167,6 +5219,10 @@ func makeRestartRoute(reg *registry.Registry, tryRestart func(host string), tryR |
| // of the code's shape rather than of an argument about systemd exit codes. |
| func makeStartRoute(reg *registry.Registry, startUnit func(unit string) error) func(host string) error { |
| return func(host string) error { |
| + // A joining managed box starts nothing (managedJoin, second layer). |
| + if managedJoiningNow() { |
| + return errManagedJoining |
| + } |
| rt, err := reg.Get(host) |
| // Left on Hibernate: unit-only (rt.Unit == "" returns first for an |
| // exec row, a resident rootfs instance included). |
| @@ -5772,6 +5828,11 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni |
| observer.resolve = restartChecks.resolve |
| settled := observer.recordSettled(release.RootHealthyDir) |
| restart := rootRestartRouteWith(reg, systemdUnits{}, release.OptDir(), os.Getenv, settled, restartChecks) |
| + // Managed fleets 2b-2: root's own admission answer, the second layer on |
| + // the round-1 start and restart callbacks below. The restart-only pass |
| + // and persisted rollback recovery get no wrapper: the systemd condition |
| + // on every workload unit covers them (decisions rule 12). |
| + managedGate := managedRootGate("/") |
| // The restart-request half, and the ONE place it dispatches from โ |
| // including for exec-backed routes, whose children belong to the agent: |
| // rootRestartRoute's try-restart arm reaches a carlos-app@ unit, and an |
| @@ -5814,7 +5875,7 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni |
| secretsPriv, err := appconfig.ParsePrivateKey(raw, "CARLOS_SECRETS_KEY") |
| if err != nil { |
| log.Printf("adopt: config sync disabled: %v", err) |
| - } else if err := appconfig.SyncUnits(ctx, reg, store, secretsPriv, appconfig.DefaultEnvDir, restart, configAckFunc(ctx, store, "adopt"), productionUnitOps(appconfig.DefaultEnvDir), claims.Writes); err != nil { |
| + } else if err := appconfig.SyncUnits(ctx, reg, store, secretsPriv, appconfig.DefaultEnvDir, restart, configAckFunc(ctx, store, "adopt"), managedGatedUnitOps(managedGate, productionUnitOps(appconfig.DefaultEnvDir)), claims.Writes); err != nil { |
| log.Printf("adopt: config sync: %v", err) |
| } |
| } |
| @@ -5915,14 +5976,15 @@ func runAdoptUnderRootRelease(args []string, buildClaims ClaimFactory, ensureUni |
| linkRootHistory(history, restartChecks, release.OptDir(), os.Getenv) |
| } |
| recovery := productionNamedUnitRecovery(store, pub, release.OptDir(), claims.Writes) |
| + recovery.gate = managedGate |
| passOpts := []release.PassOption{release.WithRootGenerationPins(generationPins), release.WithCapabilities(productionClaimCapsOps(caps.Ops{}, restartChecks.allowLegacy)), release.BakeDir(dataDir()), release.WithRestartAttemptSettled(restartChecks.finish), |
| release.WithRunningVersion(restartChecks.runningVersion), |
| release.WithSelectedRestarts( |
| - rootSelectedRestart(reg, systemdUnits{}, release.OptDir(), os.Getenv, settled, restartChecks, false), |
| - rootSelectedRestart(reg, systemdUnits{}, release.OptDir(), os.Getenv, nil, restartChecks, true)), |
| - release.WithStartUnit(rootStartRoute(reg, release.OptDir(), restartChecks)), release.WithHostWrites(claims.Writes), |
| + managedGateCallback(managedGate, rootSelectedRestart(reg, systemdUnits{}, release.OptDir(), os.Getenv, settled, restartChecks, false)), |
| + managedGateCallback(managedGate, rootSelectedRestart(reg, systemdUnits{}, release.OptDir(), os.Getenv, nil, restartChecks, true))), |
| + release.WithStartUnit(managedGateErr(managedGate, rootStartRoute(reg, release.OptDir(), restartChecks))), release.WithHostWrites(claims.Writes), |
| release.WithDigestRatchet(pointerRatchet(true, release.OptDir(), dataDir(), os.Getenv)), |
| - release.WithRollbackRestart(rollbackUnitRestart(reg, systemdUnits{}, release.OptDir(), os.Getenv, restartChecks)), |
| + release.WithRollbackRestart(managedGateErr(managedGate, rollbackUnitRestart(reg, systemdUnits{}, release.OptDir(), os.Getenv, restartChecks))), |
| // D3's gate: a fresh gate per root pass, so the policy file is read |
| // at the start of this pass (BeginPass) like every other. Healthy |
| // history is root-owned; diagnostic refusals still use BakeDir. |
diff --git a/internal/host/managedjoin.go b/internal/host/managedjoin.go| new file mode 100644 |
| index 000000000..7a9bdd2a3 |
| --- /dev/null |
| +++ b/internal/host/managedjoin.go |
| @@ -0,0 +1,302 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "errors" |
| + "log" |
| + "os" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hostwrite" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// managedReadyBackstop bounds a joining box's ready.json reads when the |
| +// serial does not move: at most one per minute. |
| +const managedReadyBackstop = 60 * time.Second |
| + |
| +// managedAdmissionDoor is the root door's admission half |
| +// (*instancectl.Client in production). |
| +type managedAdmissionDoor interface { |
| + ManagedAdmit(ctx context.Context, wire []byte) error |
| + ManagedAdmission(ctx context.Context) (managed, admitted bool, err error) |
| +} |
| + |
| +// errManagedJoining refuses agent-side tenant work on a joining managed box. |
| +var errManagedJoining = errors.New("managed box is joining its fleet: root has not admitted it") |
| + |
| +// managedJoin is the agent's advisory view of root's admission on a managed |
| +// box (managed fleets 2b-2). It never writes admission state: it relays the |
| +// console's signed ready object to the root door and believes root's |
| +// answer. Its predicate gates agent-side surfaces as a second layer; the |
| +// systemd condition on every workload unit is the guarantee. |
| +type managedJoin struct { |
| + id managedboot.Identity |
| + pub ed25519.PublicKey |
| + 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 |
| +} |
| + |
| +// 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) { |
| + return newManagedJoinAt("/", c, log.Printf) |
| +} |
| + |
| +func newManagedJoinAt(root string, door managedAdmissionDoor, logf func(string, ...any)) (*managedJoin, error) { |
| + id, managed, err := managedIdentityAt(root) |
| + if !managed { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + 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 := &managedJoin{id: id, pub: pub, door: door, logf: logf} |
| + j.joining.Store(true) |
| + ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineControl) |
| + defer cancel() |
| + if !j.askRoot(ctx) { |
| + j.logf("agent: this managed box is joining its fleet. tenant work stays closed until root admits it") |
| + } |
| + return j, nil |
| +} |
| + |
| +// askRoot reads root's admission; only an admitted answer changes anything. |
| +func (j *managedJoin) askRoot(ctx context.Context) bool { |
| + managed, admitted, err := j.door.ManagedAdmission(ctx) |
| + if err != nil { |
| + j.logf("agent: managed admission: root door: %v", err) |
| + return false |
| + } |
| + j.rootAsked = true |
| + if !managed { |
| + j.logf("agent: managed admission: root reports no managed identity; staying closed") |
| + return false |
| + } |
| + if admitted { |
| + j.joining.Store(false) |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// 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() } |
| + |
| +// TenantAdmitted is the activator and edge hook: no tenant work while joining. |
| +func (j *managedJoin) TenantAdmitted() bool { return !j.Joining() } |
| + |
| +// TenantAdmissionExempt: nothing is exempt on a managed box, platform or |
| +// named-unit routes included, so group exemptions never apply. |
| +func (j *managedJoin) TenantAdmissionExempt(registry.Route) bool { return false } |
| + |
| +// TenantAdmissionStarting makes the edge answer "starting" while joining. |
| +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. |
| +func (j *managedJoin) readyLeg(ctx context.Context, s release.Store, now time.Time, serial int64, serialOK bool) bool { |
| + if !j.Joining() || j.refused { |
| + return false |
| + } |
| + j.mu.Lock() |
| + defer j.mu.Unlock() |
| + due := !j.read || now.Sub(j.lastRead) >= managedReadyBackstop |
| + if serialOK { |
| + if j.serialSeen && serial != j.lastSerial { |
| + due = true |
| + } |
| + j.lastSerial, j.serialSeen = serial, true |
| + } |
| + if !due { |
| + return false |
| + } |
| + if !j.rootAsked && j.askRoot(ctx) { |
| + return j.flipped() |
| + } |
| + j.read, j.lastRead = true, now |
| + wire, _, err := s.Get(ctx, managedReadyKeyFor(j.id)) |
| + if err != nil { |
| + if !errors.Is(err, os.ErrNotExist) { |
| + j.logf("agent: managed admission: ready read: %v", err) |
| + } |
| + return false |
| + } |
| + if _, err = managedboot.VerifyReady(j.pub, wire, j.id); err != nil { |
| + j.logf("agent: managed admission: ready object refused: %v", err) |
| + return false |
| + } |
| + if err = j.door.ManagedAdmit(ctx, wire); err != nil { |
| + j.logf("agent: managed admission: root refused the relay: %v", err) |
| + return false |
| + } |
| + if !j.askRoot(ctx) { |
| + 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 |
| +} |
| + |
| +func (j *managedJoin) setOnAdmit(f func()) { |
| + j.admitMu.Lock() |
| + defer j.admitMu.Unlock() |
| + j.onAdmit = f |
| +} |
| + |
| +func (j *managedJoin) onAdmitFunc() 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 |
| + } |
| +} |
| + |
| +// managedReadyKeyFor is the console's managedReadyKey for this box. |
| +func managedReadyKeyFor(id managedboot.Identity) string { |
| + return "fleets/" + id.Fleet + "/boxes/" + id.Label + "/ready.json" |
| +} |
| + |
| +// bind hands the activator, the exec backend and the edge the join as their |
| +// tenant admission. A managed box never builds fixedAdmission. |
| +func (j *managedJoin) bind(s *activator.Service, b *activator.ExecBackend) edge.RunOption { |
| + if j == nil { |
| + return nil |
| + } |
| + if s != nil { |
| + s.TenantAdmittedFunc = j.TenantAdmitted |
| + s.TenantAdmissionStartingFunc = j.TenantAdmissionStarting |
| + s.TenantStartAllowed = j.TenantAdmitted |
| + s.TenantExempt = j.TenantAdmissionExempt |
| + } |
| + if b != nil { |
| + b.TenantStartAllowed = func(registry.Route) bool { return j.TenantAdmitted() } |
| + } |
| + return edge.WithHAAdmission(j) |
| +} |
| + |
| +// managedJoiningNow is the armed join's answer; false on a BYO box. |
| +func managedJoiningNow() bool { return armedManagedJoin.Load().Joining() } |
| + |
| +// managedGateStart wraps an agent-side unit start: refused while joining. |
| +func managedGateStart(start func(string) error) func(string) error { |
| + return func(host string) error { |
| + if managedJoiningNow() { |
| + return errManagedJoining |
| + } |
| + return start(host) |
| + } |
| +} |
| + |
| +// managedRootGate is root's second-layer refusal on the root pass's start |
| +// and restart callbacks: an error while root has not admitted this managed |
| +// box (or cannot tell), nil on a BYO box and once admitted. The systemd |
| +// condition is the guarantee; this only makes the refusal loud. |
| +func managedRootGate(root string) func() error { |
| + return managedRootGateWith(func() (bool, bool, error) { return managedboot.RootAdmission(root) }) |
| +} |
| + |
| +// managedRootGateWith is managedRootGate over an admission answer. |
| +func managedRootGateWith(admission func() (managed, admitted bool, err error)) func() error { |
| + return func() error { |
| + managed, admitted, err := admission() |
| + if err != nil { |
| + return errors.Join(errManagedJoining, err) |
| + } |
| + if managed && !admitted { |
| + return errManagedJoining |
| + } |
| + return nil |
| + } |
| +} |
| + |
| +// managedGateErr wraps a root-pass func(string) error with gate. |
| +func managedGateErr(gate func() error, f func(string) error) func(string) error { |
| + return func(s string) error { |
| + if err := gate(); err != nil { |
| + return err |
| + } |
| + return f(s) |
| + } |
| +} |
| + |
| +// managedGateCallback wraps a root-pass selected restart with gate. |
| +func managedGateCallback(gate func() error, cb hostwrite.Callback) hostwrite.Callback { |
| + return func(ctx context.Context, sel hostwrite.Selection) error { |
| + if err := gate(); err != nil { |
| + return err |
| + } |
| + return cb(ctx, sel) |
| + } |
| +} |
| + |
| +// managedGatedUnitOps gates config sync's named-unit restarts (SyncUnits' |
| +// UnitOps.Restart) with gate. |
| +func managedGatedUnitOps(gate func() error, ops *appconfig.UnitOps) *appconfig.UnitOps { |
| + if ops != nil && ops.Restart != nil { |
| + ops.Restart = managedGateErr(gate, ops.Restart) |
| + } |
| + return ops |
| +} |
| + |
| +// 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") |
diff --git a/internal/host/managedjoin_root_linux_test.go b/internal/host/managedjoin_root_linux_test.go| new file mode 100644 |
| index 000000000..4ebcdb30f |
| --- /dev/null |
| +++ b/internal/host/managedjoin_root_linux_test.go |
| @@ -0,0 +1,352 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/managedboot/roottest" |
| +) |
| + |
| +// managedServiceUID stands in for the carlos service user: a second real |
| +// uid with no rights over root's files. |
| +const managedServiceUID = 64000 |
| + |
| +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") |
| + } |
| +} |
| + |
| +// asService runs a shell command as managedServiceUID and reports whether |
| +// it succeeded. |
| +func asService(t *testing.T, script string) bool { |
| + t.Helper() |
| + cmd := exec.Command("/bin/sh", "-c", script) |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Credential: &syscall.Credential{Uid: managedServiceUID, Gid: managedServiceUID}} |
| + out, err := cmd.CombinedOutput() |
| + t.Logf("as uid %d: %s: err=%v %s", managedServiceUID, script, err, bytes.TrimSpace(out)) |
| + return err == nil |
| +} |
| + |
| +// productionDoor is the root door with production's hooks over root. |
| +func productionDoor(root string) http.Handler { |
| + s := &instancectl.Server{ |
| + ManagedAdmit: func(w []byte) error { return managedboot.CommitAdmission(root, w) }, |
| + ManagedAdmission: func() (bool, bool, error) { return managedboot.RootAdmission(root) }, |
| + } |
| + return s.Handler() |
| +} |
| + |
| +func startsRefused(t *testing.T, root string) bool { |
| + t.Helper() |
| + h := productionDoor(root) |
| + for _, p := range []string{"/start?host=shop.example.com", "/cmd?host=shop.example.com"} { |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, httptest.NewRequest(http.MethodPost, p, nil)) |
| + if w.Code != http.StatusConflict { |
| + return false |
| + } |
| + } |
| + return managedRootGate(root)() != nil |
| +} |
| + |
| +// TestManagedRootAdmissionForgery: with real uid 0 as root and a second |
| +// real uid as the service user, the service uid cannot create, replace, |
| +// rename into or link root's admission files; pre-placed forgeries are |
| +// doubt; a service-owned file elsewhere has no effect; and the root door |
| +// and the root pass's gate refuse in every such case. Root runner only. |
| +func TestManagedRootAdmissionForgery(t *testing.T) { |
| + requireManagedRoot(t) |
| + newRoot := func(t *testing.T) *roottest.ManagedRoot { |
| + dir, err := os.MkdirTemp("/var/tmp", "carlos-forgery-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + if err = os.Chmod(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + m := roottest.NewManagedRootIn(t, dir) |
| + if m.Owner != (managedboot.RootOwner{}) { |
| + t.Fatalf("fake root not root:root: %+v", m.Owner) |
| + } |
| + return m |
| + } |
| + t.Run("the service uid cannot write admission", func(t *testing.T) { |
| + m := newRoot(t) |
| + scratch, err := os.MkdirTemp("/var/tmp", "carlos-service-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer os.RemoveAll(scratch) |
| + if err = os.Chown(scratch, managedServiceUID, managedServiceUID); err != nil { |
| + t.Fatal(err) |
| + } |
| + forged := filepath.Join(scratch, "forged") |
| + if !asService(t, "printf x > "+forged) { |
| + t.Fatal("the service uid cannot write its own scratch: the witness proves nothing") |
| + } |
| + dir := m.Path(managedboot.RootAdmissionDir) |
| + for _, attempt := range []string{ |
| + "printf x > " + m.Path(managedboot.AdmissionPath), |
| + "printf x > " + m.Path(managedboot.AdmittedMarker), |
| + "ln -s " + forged + " " + m.Path(managedboot.AdmittedMarker), |
| + "ln " + forged + " " + m.Path(managedboot.AdmissionPath), |
| + "mv " + forged + " " + m.Path(managedboot.AdmissionPath), |
| + "mv " + dir + " " + dir + ".gone", |
| + "ls " + dir, |
| + } { |
| + if asService(t, attempt) { |
| + t.Errorf("service uid succeeded: %s", attempt) |
| + } |
| + } |
| + if managed, admitted, err := managedboot.RootAdmission(m.Root); !managed || admitted || err != nil { |
| + t.Fatalf("after service attempts: %v %v %v", managed, admitted, err) |
| + } |
| + if !startsRefused(t, m.Root) { |
| + t.Fatal("starts allowed on a joining box") |
| + } |
| + // The service uid's own files elsewhere claim nothing. |
| + for _, p := range []string{"admitted", "admission.json"} { |
| + _ = os.WriteFile(filepath.Join(scratch, p), m.Wire(t), 0o600) |
| + } |
| + if _, admitted, _ := managedboot.RootAdmission(m.Root); admitted { |
| + t.Fatal("a service-owned file elsewhere admitted the box") |
| + } |
| + // Root's verified commit admits. |
| + if err := managedboot.CommitAdmission(m.Root, m.Wire(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if managed, admitted, err := managedboot.RootAdmission(m.Root); !managed || !admitted || err != nil { |
| + t.Fatalf("after commit: %v %v %v", managed, admitted, err) |
| + } |
| + if startsRefused(t, m.Root) { |
| + t.Fatal("starts refused after admission") |
| + } |
| + for _, attempt := range []string{"rm -f " + m.Path(managedboot.AdmittedMarker), "printf x >> " + m.Path(managedboot.AdmissionPath)} { |
| + if asService(t, attempt) { |
| + t.Errorf("service uid succeeded after admission: %s", attempt) |
| + } |
| + } |
| + }) |
| + forgeries := map[string]func(t *testing.T, m *roottest.ManagedRoot){ |
| + "symlinked record": func(t *testing.T, m *roottest.ManagedRoot) { |
| + p := m.Path(managedboot.AdmissionPath) |
| + _ = os.Rename(p, p+".real") |
| + _ = os.Symlink("admission.json.real", p) |
| + }, |
| + "hard-linked record": func(t *testing.T, m *roottest.ManagedRoot) { |
| + _ = os.Link(m.Path(managedboot.AdmissionPath), m.Path(managedboot.RootAdmissionDir+"/second")) |
| + }, |
| + "service-owned record": func(t *testing.T, m *roottest.ManagedRoot) { |
| + _ = os.Chown(m.Path(managedboot.AdmissionPath), managedServiceUID, managedServiceUID) |
| + }, |
| + "service-owned marker": func(t *testing.T, m *roottest.ManagedRoot) { |
| + _ = os.Chown(m.Path(managedboot.AdmittedMarker), managedServiceUID, managedServiceUID) |
| + }, |
| + "service-owned dir": func(t *testing.T, m *roottest.ManagedRoot) { |
| + _ = os.Chown(m.Path(managedboot.RootAdmissionDir), managedServiceUID, managedServiceUID) |
| + }, |
| + "record mode 0644": func(t *testing.T, m *roottest.ManagedRoot) { _ = os.Chmod(m.Path(managedboot.AdmissionPath), 0o644) }, |
| + "dir mode 0770": func(t *testing.T, m *roottest.ManagedRoot) { _ = os.Chmod(m.Path(managedboot.RootAdmissionDir), 0o770) }, |
| + "service-owned identity": func(t *testing.T, m *roottest.ManagedRoot) { |
| + _ = os.Chown(m.Path(managedboot.IdentityPath), managedServiceUID, managedServiceUID) |
| + }, |
| + } |
| + for name, forge := range forgeries { |
| + t.Run(name, func(t *testing.T) { |
| + m := newRoot(t) |
| + if err := managedboot.CommitAdmission(m.Root, m.Wire(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + forge(t, m) |
| + if managed, admitted, err := managedboot.RootAdmission(m.Root); !managed || admitted || err == nil { |
| + t.Fatalf("forgery: managed %v admitted %v err %v", managed, admitted, err) |
| + } |
| + if !startsRefused(t, m.Root) { |
| + t.Fatal("a start was allowed over a forgery") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestManagedControlCommitHelper is the process TestManagedControlCommitStrict |
| +// starts inside a unit carrying carlos-instance-control.service's sandbox. |
| +// It fails unless that test started it. |
| +func TestManagedControlCommitHelper(t *testing.T) { |
| + path := os.Getenv("CARLOS_MANAGED_COMMIT_WIRE") |
| + if os.Getenv("CARLOS_MANAGED_COMMIT_HELPER") != "1" || path == "" { |
| + t.Fatal("helper only: started by TestManagedControlCommitStrict") |
| + } |
| + wire, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = managedboot.CommitAdmission("/", wire); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestManagedControlCommitStrict: under real systemd as PID 1, a unit with |
| +// carlos-instance-control.service's own [Service] sandbox |
| +// (ProtectSystem=strict and the rest) commits admission at the real |
| +// RootAdmissionDir only with the 60-carlos-managed-root.conf drop-in; the |
| +// directory stays root:root 0700; a gated template instance started before |
| +// the commit is condition-skipped and runs after it. Root runner only, on |
| +// a throwaway instance: it writes the real /etc/carlos/managed-box.json and |
| +// /var/lib/carlos-managed-root and removes both. |
| +func TestManagedControlCommitStrict(t *testing.T) { |
| + requireManagedRoot(t) |
| + if comm, err := os.ReadFile("/proc/1/comm"); err != nil || strings.TrimSpace(string(comm)) != "systemd" { |
| + t.Fatalf("systemd must be PID 1: %q %v", comm, err) |
| + } |
| + for _, p := range []string{managedboot.IdentityPath, managedboot.RootAdmissionDir} { |
| + if _, err := os.Lstat(p); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("%s already exists: not a throwaway runner (%v)", p, err) |
| + } |
| + } |
| + ctl := func(args ...string) string { |
| + t.Helper() |
| + out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + t.Logf("systemctl %s: %v %s", strings.Join(args, " "), err, bytes.TrimSpace(out)) |
| + return strings.TrimSpace(string(out)) |
| + } |
| + show := func(unit, prop string) string { |
| + return strings.TrimPrefix(ctl("show", "-p", prop, unit), prop+"=") |
| + } |
| + const ( |
| + commitUnit = "carlos-managed-commit-test.service" |
| + gateUnit = "carlos-managed-gate-test@.service" |
| + gateInst = "carlos-managed-gate-test@shop.service" |
| + runDir = "/run/systemd/system" |
| + work = "/opt/carlos-managed-commit-test" |
| + ) |
| + createdCarlos := false |
| + if _, err := os.Lstat("/etc/carlos"); errors.Is(err, os.ErrNotExist) { |
| + createdCarlos = true |
| + } |
| + t.Cleanup(func() { |
| + ctl("stop", gateInst, commitUnit) |
| + ctl("reset-failed", gateInst, commitUnit) |
| + os.RemoveAll(filepath.Join(runDir, commitUnit)) |
| + os.RemoveAll(filepath.Join(runDir, commitUnit+".d")) |
| + os.RemoveAll(filepath.Join(runDir, gateUnit)) |
| + os.RemoveAll(filepath.Join(runDir, gateUnit+".d")) |
| + ctl("daemon-reload") |
| + os.RemoveAll(work) |
| + os.RemoveAll(managedboot.RootAdmissionDir) |
| + os.Remove(managedboot.IdentityPath) |
| + if createdCarlos { |
| + os.Remove("/etc/carlos") |
| + } |
| + }) |
| + // The real managed layout the first boot's commit leaves. |
| + dir := t.TempDir() |
| + m := roottest.NewManagedRootIn(t, dir) |
| + body, err := managedboot.EncodeIdentity(m.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.MkdirAll("/etc/carlos", 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.WriteFile(managedboot.IdentityPath, body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.Mkdir(managedboot.RootAdmissionDir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The test binary and the wire where the sandbox can read them. |
| + exe, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.MkdirAll(work, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + bin, _ := os.ReadFile(exe) |
| + if err = os.WriteFile(filepath.Join(work, "x.test"), bin, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.WriteFile(filepath.Join(work, "wire"), m.Wire(t), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The commit unit: the installed control unit's [Service] section, its |
| + // ExecStart replaced by the helper, Restart off. |
| + control, err := unitsFS.ReadFile("units/" + managedboot.ControlUnit) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + section := string(control[bytes.Index(control, []byte("[Service]")):]) |
| + var service []string |
| + for _, line := range strings.Split(section, "\n") { |
| + if strings.HasPrefix(line, "ExecStart=") || strings.HasPrefix(line, "Restart") { |
| + continue |
| + } |
| + service = append(service, line) |
| + } |
| + unit := "[Unit]\nDescription=managed admission commit under the control sandbox\n\n" + strings.Join(service, "\n") + |
| + "\nType=oneshot\nExecStart=" + filepath.Join(work, "x.test") + " -test.run=^TestManagedControlCommitHelper$ -test.count=1\n" + |
| + "Environment=CARLOS_MANAGED_COMMIT_HELPER=1 CARLOS_MANAGED_COMMIT_WIRE=" + filepath.Join(work, "wire") + "\n" |
| + writeFileT(t, filepath.Join(runDir, commitUnit), unit) |
| + writeFileT(t, filepath.Join(runDir, gateUnit), "[Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart=/bin/true\n") |
| + writeFileT(t, filepath.Join(runDir, gateUnit+".d", managedboot.AdmissionDropInName), managedboot.AdmissionDropIn) |
| + ctl("daemon-reload") |
| + |
| + // Before the commit: the gated instance is condition-skipped. |
| + ctl("start", gateInst) |
| + if got := show(gateInst, "ActiveState"); got == "active" { |
| + t.Fatal("gated instance ran before admission") |
| + } |
| + if got := show(gateInst, "ConditionResult"); got != "no" { |
| + t.Fatalf("gated instance ConditionResult=%s", got) |
| + } |
| + // Without the drop-in, ProtectSystem=strict refuses the write. |
| + 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 _, 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) |
| + } |
| + ctl("daemon-reload") |
| + ctl("start", commitUnit) |
| + if got := show(commitUnit, "Result"); got != "success" { |
| + t.Fatalf("commit under the control sandbox with the drop-in: Result=%s", got) |
| + } |
| + var st syscall.Stat_t |
| + if err := syscall.Stat(managedboot.RootAdmissionDir, &st); err != nil || st.Uid != 0 || st.Gid != 0 || st.Mode&0o7777 != 0o700 { |
| + t.Fatalf("admission dir after commit: %+v %v", st, err) |
| + } |
| + if managed, admitted, err := managedboot.RootAdmission("/"); !managed || !admitted || err != nil { |
| + t.Fatalf("RootAdmission after commit: %v %v %v", managed, admitted, err) |
| + } |
| + // After the commit the same gated instance runs, with no reload. |
| + ctl("start", gateInst) |
| + if got := show(gateInst, "ActiveState"); got != "active" { |
| + t.Fatalf("gated instance after admission: ActiveState=%s", got) |
| + } |
| +} |
diff --git a/internal/host/managedjoin_test.go b/internal/host/managedjoin_test.go| new file mode 100644 |
| index 000000000..849a51e16 |
| --- /dev/null |
| +++ b/internal/host/managedjoin_test.go |
| @@ -0,0 +1,649 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "errors" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "io/fs" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/hostwrite" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/managedboot/roottest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// fakeRootDoor is the root door over a fake managed root: real |
| +// CommitAdmission and RootAdmission semantics, counted, with failures |
| +// injectable. |
| +type fakeRootDoor struct { |
| + m *roottest.ManagedRoot |
| + admits, asks atomic.Int64 |
| + failAdmit, failAsk bool |
| + crashBeforeCommit bool |
| +} |
| + |
| +func (d *fakeRootDoor) ManagedAdmit(_ context.Context, wire []byte) error { |
| + d.admits.Add(1) |
| + if d.failAdmit || d.crashBeforeCommit { |
| + return errors.New("instance control socket: connection reset") |
| + } |
| + return d.m.Commit(wire) |
| +} |
| + |
| +func (d *fakeRootDoor) ManagedAdmission(context.Context) (bool, bool, error) { |
| + d.asks.Add(1) |
| + if d.failAsk { |
| + return false, false, errors.New("instance control socket: connection refused") |
| + } |
| + return d.m.Admission() |
| +} |
| + |
| +// readyCountStore counts the ready object's reads. |
| +type readyCountStore struct { |
| + release.Store |
| + readyGets atomic.Int64 |
| + fail bool |
| +} |
| + |
| +func (s *readyCountStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if strings.HasSuffix(key, "/ready.json") { |
| + s.readyGets.Add(1) |
| + if s.fail { |
| + return nil, "", errors.New("store door unavailable") |
| + } |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +type joinFixture struct { |
| + m *roottest.ManagedRoot |
| + door *fakeRootDoor |
| + store *readyCountStore |
| + logs *strings.Builder |
| + mu *sync.Mutex |
| +} |
| + |
| +func newJoinFixture(t *testing.T) *joinFixture { |
| + t.Helper() |
| + m := roottest.NewManagedRoot(t) |
| + prev := managedIdentityAt |
| + managedIdentityAt = func(r string) (managedboot.Identity, bool, error) { |
| + if r == m.Root { |
| + return m.ID, true, nil |
| + } |
| + return prev(r) |
| + } |
| + t.Cleanup(func() { managedIdentityAt = prev }) |
| + return &joinFixture{m: m, door: &fakeRootDoor{m: m}, store: &readyCountStore{Store: release.NewDirStore(t.TempDir())}, logs: &strings.Builder{}, mu: &sync.Mutex{}} |
| +} |
| + |
| +func (f *joinFixture) logf(format string, args ...any) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + fmt.Fprintf(f.logs, format+"\n", args...) |
| +} |
| + |
| +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) |
| + } |
| + return j |
| +} |
| + |
| +func (f *joinFixture) publish(t *testing.T, wire []byte) { |
| + t.Helper() |
| + key := managedReadyKeyFor(f.m.ID) |
| + _, etag, _ := f.store.Store.Get(context.Background(), key) |
| + if _, err := f.store.Store.Put(context.Background(), key, wire, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (f *joinFixture) admissionFiles(t *testing.T) int { |
| + t.Helper() |
| + e, err := os.ReadDir(f.m.Path(managedboot.RootAdmissionDir)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return len(e) |
| +} |
| + |
| +func TestManagedJoinReadyLeg(t *testing.T) { |
| + ctx := context.Background() |
| + t0 := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) |
| + t.Run("read cadence", func(t *testing.T) { |
| + f := newJoinFixture(t) |
| + j := f.join(t) |
| + reads := func() int64 { return f.store.readyGets.Load() } |
| + steps := []struct { |
| + at time.Duration |
| + serial int64 |
| + ok bool |
| + want int64 |
| + }{ |
| + {0, 1, true, 1}, // arming |
| + {2 * time.Second, 1, true, 1}, // same serial |
| + {30 * time.Second, 1, true, 1}, // still inside the backstop |
| + {32 * time.Second, 2, true, 2}, // changed serial |
| + {34 * time.Second, 2, true, 2}, // same again |
| + {60 * time.Second, 9, false, 2}, // serial read failed: backstop only |
| + {92 * time.Second, 9, false, 3}, // backstop |
| + {94 * time.Second, 2, true, 3}, // first good read after errors is the same serial |
| + {96 * time.Second, 3, true, 4}, // changed |
| + } |
| + for _, s := range steps { |
| + if j.readyLeg(ctx, f.store, t0.Add(s.at), s.serial, s.ok) { |
| + t.Fatal("flipped with no ready object") |
| + } |
| + if reads() != s.want { |
| + t.Fatalf("at %v: %d reads, want %d", s.at, reads(), s.want) |
| + } |
| + } |
| + if !j.Joining() || f.door.admits.Load() != 0 { |
| + t.Fatal("absent object relayed or flipped") |
| + } |
| + }) |
| + t.Run("refused objects stay joining", func(t *testing.T) { |
| + f := newJoinFixture(t) |
| + _, foreign, _ := ed25519.GenerateKey(nil) |
| + other := func(mut func(*managedboot.ReadyRecord), key ed25519.PrivateKey) []byte { |
| + r := f.m.Ready |
| + mut(&r) |
| + w, err := managedboot.SignReady(key, r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return w |
| + } |
| + cases := map[string][]byte{ |
| + "malformed": []byte("{"), |
| + "unsigned": []byte(`{"fleet":"shop","label":"box-1","op":"0123456789abcdef0123456789abcdef","ready_at":"2026-11-09T12:00:00Z"}`), |
| + "wrong key": other(func(*managedboot.ReadyRecord) {}, foreign), |
| + "wrong fleet": other(func(r *managedboot.ReadyRecord) { r.Fleet = "other" }, f.m.Key), |
| + "wrong label": other(func(r *managedboot.ReadyRecord) { r.Label = "box-2" }, f.m.Key), |
| + "wrong op": other(func(r *managedboot.ReadyRecord) { r.Op = strings.Repeat("a", 32) }, f.m.Key), |
| + } |
| + n := 0 |
| + for name, wire := range cases { |
| + f.publish(t, wire) |
| + j := f.join(t) |
| + if j.readyLeg(ctx, f.store, t0.Add(time.Duration(n)*time.Hour), 1, true) || !j.Joining() { |
| + t.Fatalf("%s flipped", name) |
| + } |
| + n++ |
| + } |
| + if f.door.admits.Load() != 0 || f.admissionFiles(t) != 0 { |
| + t.Fatalf("refused objects relayed %d times, %d files", f.door.admits.Load(), f.admissionFiles(t)) |
| + } |
| + f.store.fail = true |
| + j := f.join(t) |
| + if j.readyLeg(ctx, f.store, t0, 1, true) || !j.Joining() { |
| + t.Fatal("5xx flipped") |
| + } |
| + }) |
| + t.Run("root refusal and socket errors retry next due", func(t *testing.T) { |
| + f := newJoinFixture(t) |
| + f.publish(t, f.m.Wire(t)) |
| + f.door.failAdmit = true |
| + j := f.join(t) |
| + admitted := 0 |
| + j.setOnAdmit(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") |
| + } |
| + if j.readyLeg(ctx, f.store, t0.Add(10*time.Second), 1, true) || f.door.admits.Load() != 1 { |
| + 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.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) |
| + } |
| + if f.admissionFiles(t) != 2 { |
| + t.Fatal("root did not commit") |
| + } |
| + if j.readyLeg(ctx, f.store, t0.Add(time.Hour), 2, true) || admitted != 1 { |
| + t.Fatal("admitted box read again or re-ran onAdmit") |
| + } |
| + }) |
| + t.Run("only root's 200 flips the agent", func(t *testing.T) { |
| + f := newJoinFixture(t) |
| + f.publish(t, f.m.Wire(t)) |
| + f.door.crashBeforeCommit = true |
| + j := f.join(t) |
| + if j.readyLeg(ctx, f.store, t0, 1, true) || !j.Joining() { |
| + t.Fatal("agent flipped before root committed") |
| + } |
| + if f.admissionFiles(t) != 0 { |
| + t.Fatal("files written") |
| + } |
| + }) |
| +} |
| + |
| +func TestManagedAdmissionOneWay(t *testing.T) { |
| + ctx := context.Background() |
| + t0 := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) |
| + f := newJoinFixture(t) |
| + f.publish(t, f.m.Wire(t)) |
| + j := f.join(t) |
| + if !j.readyLeg(ctx, f.store, t0, 1, true) { |
| + t.Fatal("not admitted") |
| + } |
| + reads := f.store.readyGets.Load() |
| + for i := 0; i < 1000; i++ { |
| + j.readyLeg(ctx, f.store, t0.Add(time.Duration(i)*2*time.Second), int64(i+2), i%7 != 0) |
| + } |
| + if f.store.readyGets.Load() != reads { |
| + t.Fatalf("admitted box read ready.json %d more times", f.store.readyGets.Load()-reads) |
| + } |
| + // The ready object later deleted, rewritten, or the store gone: root's |
| + // record is the authority. |
| + _ = f.store.Store.Delete(ctx, managedReadyKeyFor(f.m.ID)) |
| + f.publish(t, []byte(`{"fleet":"shop"}`)) |
| + f.store.fail = true |
| + if j.Joining() { |
| + t.Fatal("box returned to joining") |
| + } |
| + if managed, admitted, err := f.m.Admission(); !managed || !admitted || err != nil { |
| + t.Fatalf("root record changed: %v %v %v", managed, admitted, err) |
| + } |
| + // Agent restart (and reboot: the same files): root's answer, no reads. |
| + asks := f.door.asks.Load() |
| + j2 := f.join(t) |
| + if j2.Joining() || f.door.asks.Load() != asks+1 { |
| + t.Fatal("restart did not take root's answer") |
| + } |
| + for i := 0; i < 100; i++ { |
| + j2.readyLeg(ctx, f.store, t0.Add(time.Duration(i)*time.Minute), int64(i), true) |
| + } |
| + if f.store.readyGets.Load() != reads { |
| + t.Fatal("restarted admitted agent read ready.json") |
| + } |
| + // Root-level tampering removes the record: joining again, reported. |
| + _ = os.Remove(f.m.Path(managedboot.AdmittedMarker)) |
| + _ = os.Remove(f.m.Path(managedboot.AdmissionPath)) |
| + j3 := f.join(t) |
| + if !j3.Joining() || !strings.Contains(f.logs.String(), "joining its fleet") { |
| + t.Fatalf("tampered box: joining=%v logs=%s", j3.Joining(), f.logs) |
| + } |
| + if managed, admitted, _ := f.m.Admission(); !managed || admitted { |
| + t.Fatal("root reports a tampered box admitted") |
| + } |
| +} |
| + |
| +func TestManagedJoinRebootMatrix(t *testing.T) { |
| + ctx := context.Background() |
| + t0 := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) |
| + startRefused := func(t *testing.T, f *joinFixture) bool { |
| + t.Helper() |
| + s := &instancectl.Server{ManagedAdmission: f.m.Admission, ManagedAdmit: f.m.Commit} |
| + w := httptest.NewRecorder() |
| + s.Handler().ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/start?host=shop.example.com", nil)) |
| + gate := managedRootGateWith(f.m.Admission) |
| + return w.Code == http.StatusConflict && gate() != nil |
| + } |
| + for _, boundary := range []string{"before ready", "after ready read, before relay", "after root commit, before flip", "after flip, before reconcile"} { |
| + t.Run(boundary, func(t *testing.T) { |
| + f := newJoinFixture(t) |
| + j := f.join(t) |
| + switch boundary { |
| + case "before ready": |
| + case "after ready read, before relay": |
| + f.publish(t, f.m.Wire(t)) |
| + f.door.crashBeforeCommit = true |
| + j.readyLeg(ctx, f.store, t0, 1, true) |
| + f.door.crashBeforeCommit = false |
| + case "after root commit, before flip": |
| + f.publish(t, f.m.Wire(t)) |
| + if err := f.m.Commit(f.m.Wire(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "after flip, before reconcile": |
| + f.publish(t, f.m.Wire(t)) |
| + if !j.readyLeg(ctx, f.store, t0, 1, true) { |
| + t.Fatal("no flip") |
| + } |
| + } |
| + committed := f.admissionFiles(t) == 2 |
| + if !committed && !startRefused(t, f) { |
| + t.Fatal("a start was allowed before root's durable record") |
| + } |
| + // The restart: a fresh agent over the same root. |
| + reads := f.store.readyGets.Load() |
| + r := f.join(t) |
| + var cfg provision.ReconcileConfig |
| + managedJoinProvision(r, nil)(&cfg) |
| + if committed { |
| + if r.Joining() || cfg.Joining() || f.store.readyGets.Load() != reads || startRefused(t, f) { |
| + t.Fatal("admission lost across the restart") |
| + } |
| + return |
| + } |
| + if !r.Joining() || !cfg.Joining() { |
| + t.Fatal("restart before root's record is not joining") |
| + } |
| + if boundary == "before ready" { |
| + f.publish(t, f.m.Wire(t)) |
| + } |
| + if !r.readyLeg(ctx, f.store, t0.Add(time.Hour), 1, true) || r.Joining() || cfg.Joining() || startRefused(t, f) { |
| + t.Fatal("restarted agent did not reach admission") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestManagedJoinBYOUnchanged(t *testing.T) { |
| + prev := managedIdentityAt |
| + 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()) |
| + } |
| + if j.Joining() || j.bind(&activator.Service{}, &activator.ExecBackend{}) != nil { |
| + t.Fatal("a nil join gates or binds") |
| + } |
| + svc, eb := &activator.Service{}, &activator.ExecBackend{} |
| + j.bind(svc, eb) |
| + if svc.TenantAdmittedFunc != nil || svc.TenantExempt != nil || eb.TenantStartAllowed != nil { |
| + t.Fatal("a nil join replaced the admission hooks") |
| + } |
| + called := false |
| + inner := func(*provision.ReconcileConfig) { called = true } |
| + var cfg provision.ReconcileConfig |
| + managedJoinProvision(nil, inner)(&cfg) |
| + if !called || cfg.Joining != nil { |
| + t.Fatal("byo provisioning changed") |
| + } |
| + if err := managedRootGateWith(func() (bool, bool, error) { return false, true, nil })(); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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") |
| + } |
| +} |
| + |
| +func TestManagedJoinStartSurfaces(t *testing.T) { |
| + f := newJoinFixture(t) |
| + j := f.join(t) |
| + armedManagedJoin.Store(j) |
| + defer armedManagedJoin.Store(nil) |
| + svc, eb := &activator.Service{}, &activator.ExecBackend{} |
| + opt := j.bind(svc, eb) |
| + if opt == nil { |
| + t.Fatal("no edge admission option") |
| + } |
| + routes := []registry.Route{ |
| + {Host: "shop.example.com", Kind: "instance"}, |
| + {Host: "rootfs.shop.example.com", Kind: "instance", Runtime: registry.RuntimeRootfsV1}, |
| + {Host: "side.shop.example.com", Kind: "sidecar"}, |
| + {Host: "api.shop.example.com", Unit: "shop-api.service", Backing: registry.BackingUnit}, |
| + {Host: "static.shop.example.com", Kind: "static"}, |
| + {Host: "console.example.com", Platform: true}, |
| + } |
| + starts := 0 |
| + start := makeStartRoute(nil, func(string) error { starts++; return nil }) |
| + gateErr := managedRootGateWith(f.m.Admission) |
| + unitOps := managedGatedUnitOps(gateErr, &appconfig.UnitOps{Restart: func(string) error { starts++; return nil }}) |
| + selected := managedGateCallback(gateErr, func(context.Context, hostwrite.Selection) error { starts++; return nil }) |
| + rootStart := managedGateErr(gateErr, func(string) error { starts++; return nil }) |
| + bounceHost := managedGateStart(func(string) error { starts++; return nil }) |
| + var cfg provision.ReconcileConfig |
| + managedJoinProvision(j, nil)(&cfg) |
| + check := func(open bool) { |
| + t.Helper() |
| + for _, rt := range routes { |
| + if svc.TenantAdmitted() != open || svc.TenantAdmissionExempt(rt) || eb.TenantStartAllowed(rt) != open { |
| + t.Errorf("%s: activator admitted=%v exempt=%v exec=%v, want open=%v", rt.Host, svc.TenantAdmitted(), svc.TenantAdmissionExempt(rt), eb.TenantStartAllowed(rt), open) |
| + } |
| + } |
| + // The edge's three questions: admitted, exempt, starting. |
| + if j.TenantAdmitted() != open || !j.TenantAdmissionStarting() { |
| + t.Error("edge would not answer 503 starting while joining") |
| + } |
| + if cfg.Joining() == open { |
| + t.Error("reconcile Joining wrong") |
| + } |
| + errs := []error{bounceHost("shop.example.com"), rootStart("console.service"), selected(context.Background(), hostwrite.Selection{}), unitOps.Restart("shop-api.service")} |
| + for i, err := range errs { |
| + if (err == nil) != open { |
| + t.Errorf("surface %d: err %v, want open=%v", i, err, open) |
| + } |
| + } |
| + if !open { |
| + if err := start("shop.example.com"); !errors.Is(err, errManagedJoining) { |
| + t.Errorf("makeStartRoute while joining: %v", err) |
| + } |
| + } |
| + } |
| + check(false) |
| + if starts != 0 { |
| + t.Fatalf("%d starts while joining", starts) |
| + } |
| + f.publish(t, f.m.Wire(t)) |
| + if !j.readyLeg(context.Background(), f.store, time.Now(), 1, true) { |
| + t.Fatal("no flip") |
| + } |
| + check(true) |
| + if starts != 4 { |
| + t.Fatalf("%d starts after admission, want 4", starts) |
| + } |
| +} |
| + |
| +// conditionedUnits is plan14's fake systemd with the unit condition |
| +// applied from a real installed unit tree: a start or restart job of a |
| +// unit whose ConditionPathExists= is unmet is skipped, as systemd does it |
| +// (exit 0, the unit left inactive, nothing runs). |
| +type conditionedUnits struct { |
| + *plan14RestartUnits |
| + tree unitTree |
| + t *testing.T |
| + skipped []string |
| +} |
| + |
| +func (c *conditionedUnits) Restart(unit string) error { |
| + if !c.tree.conditionMet(c.t, unit) { |
| + c.skipped = append(c.skipped, unit) |
| + c.props.ActiveState, c.props.SubState, c.props.MainPID = "inactive", "dead", 0 |
| + return nil |
| + } |
| + return c.plan14RestartUnits.Restart(unit) |
| +} |
| + |
| +func (c *conditionedUnits) TryRestart(unit string) error { return c.Restart(unit) } |
| + |
| +// conditionTree is the managed unit tree with a named unit unit declared. |
| +func conditionTree(t *testing.T, unit string) unitTree { |
| + t.Helper() |
| + root := t.TempDir() |
| + 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) |
| + } |
| + return unitTree{root: root} |
| +} |
| + |
| +func admitTree(t *testing.T, tree unitTree) { |
| + t.Helper() |
| + writeFileT(t, filepath.Join(tree.root, managedboot.AdmittedMarker), "") |
| +} |
| + |
| +func TestManagedRestartOnlyPassUnmet(t *testing.T) { |
| + e, rt, u, c, _ := plan14AdoptionFixture(t) |
| + tree := conditionTree(t, rt.Unit) |
| + sys := &conditionedUnits{plan14RestartUnits: u, tree: tree, t: t} |
| + if err := release.PointLive(u.opt, rt.Host, rt.Account, "v1", rt.App); err != nil { |
| + t.Fatal(err) |
| + } |
| + restart := rootRestartRouteWith(e.root.reg, sys, u.opt, func(string) string { return "5s" }, nil, c) |
| + initial := u.props |
| + // The restart-only pass's dispatch (restartPass -> rootRestartRouteWith). |
| + _ = restart(rt.Host) |
| + 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) |
| + } |
| + // Admitted: the same pass over the same unit (as the fixture left it |
| + // before the skipped job) now starts it. |
| + admitTree(t, tree) |
| + u.props = initial |
| + c.started = &sync.Map{} |
| + if err := restart(rt.Host); err != nil { |
| + t.Fatalf("admitted restart: %v", err) |
| + } |
| + 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) |
| + } |
| +} |
| + |
| +func TestManagedRollbackRecoveryUnmet(t *testing.T) { |
| + e, rt, u, c, pub := plan14AdoptionFixture(t) |
| + u.crashNew = true |
| + forward := rootRestartRouteWith(e.root.reg, u, u.opt, func(string) string { return "5s" }, nil, c) |
| + crashed := errors.New("root process exited") |
| + func() { |
| + defer func() { |
| + if got := recover(); got != crashed { |
| + t.Fatalf("crash boundary: %v", got) |
| + } |
| + }() |
| + _ = release.Pass(t.Context(), e.root.reg, e.store, pub, u.opt, func(host string) error { |
| + _ = forward(host) |
| + panic(crashed) |
| + }, release.BakeDir(e.bake), release.WithRestartFailurePropagation()) |
| + }() |
| + s, err := c.attempts() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a, err := readRollbackAttempt(s, rt.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a.Recovering = true |
| + if err := writeRollbackState(s, rollbackJournalKey(rt.Host), a); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.PointLive(u.opt, rt.Host, rt.Account, "v1", rt.App); err != nil { |
| + t.Fatal(err) |
| + } |
| + tree := conditionTree(t, rt.Unit) |
| + sys := &conditionedUnits{plan14RestartUnits: u, tree: tree, t: t} |
| + before := len(u.effects) |
| + c.started = &sync.Map{} |
| + _ = recoverRootRestarts(context.Background(), sys, u.opt, func(string) string { return "5s" }, c, hostwrite.Config{}) |
| + for _, eff := range u.effects[before:] { |
| + if strings.HasPrefix(eff, "restart ") { |
| + t.Fatalf("joining recovery restarted the unit: %v", u.effects[before:]) |
| + } |
| + } |
| + if len(sys.skipped) == 0 || u.props.MainPID > 0 { |
| + t.Fatalf("joining recovery ran the unit: skipped=%v effects=%v pid=%d", sys.skipped, u.effects[before:], u.props.MainPID) |
| + } |
| + // The resume ends the attempt (settleRollbackAttempt runs on every |
| + // resume, as on main) without verifying anything: the unit never ran. |
| + 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. |
| + 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) |
| + } |
| +} |
| + |
| +// TestManagedJoinLiveServices: the join gates only the tenant start |
| +// surfaces. The status heartbeat, tunnel dial, store-door reads, system |
| +// pointer leg and probe paths never consult it, so they run while joining. |
| +// A syntax witness over the package: every function that asks the join is |
| +// one of the listed gates. |
| +func TestManagedJoinLiveServices(t *testing.T) { |
| + allowed := map[string]bool{ |
| + // agent.go |
| + "runAgent": true, "makeStartRoute": true, "syncExecSerializedFiltered": true, "fastConvergeLoop": true, "fastTick": false, |
| + // managedjoin.go |
| + "managedJoiningNow": true, "managedGateStart": true, "newManagedJoin": true, "newManagedJoinAt": true, |
| + } |
| + fset := token.NewFileSet() |
| + pkgs, err := parser.ParseDir(fset, ".", func(fi fs.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + asks := regexp.MustCompile(`^(managedJoiningNow|armedManagedJoin|managedGateStart|newManagedJoin)$`) |
| + found := map[string]bool{} |
| + for _, p := range pkgs { |
| + for name, file := range p.Files { |
| + for _, decl := range file.Decls { |
| + fn, ok := decl.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + if id, ok := n.(*ast.Ident); ok && asks.MatchString(id.Name) { |
| + found[fn.Name.Name] = true |
| + if !allowed[fn.Name.Name] { |
| + t.Errorf("%s: %s asks the managed join (%s); only tenant start gates may", name, fn.Name.Name, id.Name) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + } |
| + for _, want := range []string{"runAgent", "makeStartRoute", "syncExecSerializedFiltered", "fastConvergeLoop"} { |
| + if !found[want] { |
| + t.Errorf("%s no longer asks the join", want) |
| + } |
| + } |
| + // fastTick asks only through d.managedReady, after the serial read, and |
| + // runs every other leg whatever it answers. |
| + d := newFastFixture(t).deps(nil) |
| + legs := 0 |
| + d.managedReady = func(context.Context, time.Time, int64, bool) { legs++ } |
| + d.restartGain = func(context.Context, time.Time) { legs++ } |
| + fastTick(context.Background(), d, time.Now()) |
| + if legs != 2 { |
| + t.Fatalf("fastTick ran %d of the 2 legs", legs) |
| + } |
| +} |
diff --git a/internal/host/managedunits.go b/internal/host/managedunits.go| new file mode 100644 |
| index 000000000..4349a1ccf |
| --- /dev/null |
| +++ b/internal/host/managedunits.go |
| @@ -0,0 +1,99 @@ |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| +) |
| + |
| +// managedIdentityAt is managedboot.LoadIdentity: whether the root at root |
| +// 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 |
| + |
| +// 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") |
| + |
| +// 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 |
| +} |
| + |
| +// 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)) |
| + if !managed { |
| + return false, false, nil |
| + } |
| + if err != nil { |
| + return false, false, fmt.Errorf("%w: %v", errManagedIdentity, err) |
| + } |
| + named, err := declaredNamedUnits(filepath.Join(etcDir, "carlos", filepath.Base(appconfig.DefaultNamedUnitsPath))) |
| + if err != nil { |
| + // An unreadable declaration declares nothing a pass will start |
| + // (appconfig refuses an invalid file); the templates still get |
| + // theirs. |
| + named = nil |
| + } |
| + named = append(named, extraNamed...) |
| + unitDir := filepath.Join(etcDir, "systemd", "system") |
| + if err = os.MkdirAll(unitDir, 0o755); err != nil { |
| + return false, false, err |
| + } |
| + if workloads, err = managedboot.InstallAdmissionDropIns(unitDir, named); err != nil { |
| + return workloads, false, err |
| + } |
| + control, err = managedboot.InstallControlDropIn(unitDir) |
| + return workloads, control, err |
| +} |
| + |
| +// 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) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return appconfig.DeclaredUnits(raw) |
| +} |
| + |
| +// 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. |
| +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) |
| + if err != nil { |
| + return err |
| + } |
| + if workloads || control { |
| + return reload() |
| + } |
| + return nil |
| +} |
diff --git a/internal/host/managedunits_test.go b/internal/host/managedunits_test.go| new file mode 100644 |
| index 000000000..fa518736c |
| --- /dev/null |
| +++ b/internal/host/managedunits_test.go |
| @@ -0,0 +1,400 @@ |
| +package host |
| + |
| +import ( |
| + "bufio" |
| + "io/fs" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "sort" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/caps" |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| +) |
| + |
| +// unitTree is a box's unit configuration under a scratch root, read with |
| +// systemd's own drop-in rules (systemd.unit(5)): the unit file from the |
| +// first layer that has it (an instance falls back to its template), then |
| +// every *.conf from <type>.d, each dash-prefix directory, the template's |
| +// and the unit's own .d directory in every layer; one file name is taken |
| +// from the highest-priority layer (/etc over /run), and all are applied in |
| +// lexical order of file name, whatever directory they came from. An empty |
| +// assignment of a list setting resets the list. |
| +type unitTree struct{ root string } |
| + |
| +var unitLayers = []string{"etc/systemd/system", "run/systemd/system"} |
| + |
| +// templateOf is foo@.service for foo@bar.service, "" for a plain unit. |
| +func templateOf(unit string) string { |
| + at := strings.IndexByte(unit, '@') |
| + dot := strings.LastIndexByte(unit, '.') |
| + if at < 0 || dot < at || at+1 == dot { |
| + return "" |
| + } |
| + return unit[:at+1] + unit[dot:] |
| +} |
| + |
| +// dropInDirs is every directory name whose *.conf apply to unit. |
| +func dropInDirs(unit string) []string { |
| + dot := strings.LastIndexByte(unit, '.') |
| + typ := unit[dot+1:] |
| + name := unit[:dot] |
| + dirs := []string{typ + ".d"} |
| + base := name |
| + if at := strings.IndexByte(name, '@'); at >= 0 { |
| + base = name[:at] |
| + } |
| + for i := 0; i < len(base); i++ { |
| + if base[i] == '-' { |
| + dirs = append(dirs, base[:i+1]+"."+typ+".d") |
| + } |
| + } |
| + if t := templateOf(unit); t != "" { |
| + dirs = append(dirs, t+".d") |
| + } |
| + return append(dirs, unit+".d") |
| +} |
| + |
| +// files is the unit file then its drop-ins, in the order systemd applies them. |
| +func (u unitTree) files(t *testing.T, unit string) []string { |
| + t.Helper() |
| + var out []string |
| + for _, name := range []string{unit, templateOf(unit)} { |
| + if name == "" || len(out) > 0 { |
| + continue |
| + } |
| + for _, l := range unitLayers { |
| + p := filepath.Join(u.root, l, name) |
| + if st, err := os.Stat(p); err == nil && st.Mode().IsRegular() { |
| + out = append(out, p) |
| + break |
| + } |
| + } |
| + } |
| + byName := map[string]string{} |
| + for _, dir := range dropInDirs(unit) { |
| + for i := len(unitLayers) - 1; i >= 0; i-- { // lower priority first, overwritten by higher |
| + entries, _ := os.ReadDir(filepath.Join(u.root, unitLayers[i], dir)) |
| + for _, e := range entries { |
| + if strings.HasSuffix(e.Name(), ".conf") { |
| + byName[e.Name()] = filepath.Join(u.root, unitLayers[i], dir, e.Name()) |
| + } |
| + } |
| + } |
| + } |
| + names := make([]string, 0, len(byName)) |
| + for n := range byName { |
| + names = append(names, n) |
| + } |
| + sort.Strings(names) |
| + for _, n := range names { |
| + out = append(out, byName[n]) |
| + } |
| + return out |
| +} |
| + |
| +// list is the effective value of a list setting key in section. |
| +func (u unitTree) list(t *testing.T, unit, section, key string) []string { |
| + t.Helper() |
| + var vals []string |
| + for _, p := range u.files(t, unit) { |
| + f, err := os.Open(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cur := "" |
| + sc := bufio.NewScanner(f) |
| + for sc.Scan() { |
| + line := strings.TrimSpace(sc.Text()) |
| + if strings.HasPrefix(line, "[") { |
| + cur = line |
| + continue |
| + } |
| + k, v, ok := strings.Cut(line, "=") |
| + if !ok || cur != section || strings.TrimSpace(k) != key { |
| + continue |
| + } |
| + if v = strings.TrimSpace(v); v == "" { |
| + vals = nil |
| + } else { |
| + vals = append(vals, strings.Fields(v)...) |
| + } |
| + } |
| + f.Close() |
| + } |
| + return vals |
| +} |
| + |
| +// conditionMet is systemd's ConditionPathExists= verdict for unit, with |
| +// paths read under the tree's root. |
| +func (u unitTree) conditionMet(t *testing.T, unit string) bool { |
| + t.Helper() |
| + for _, p := range u.list(t, unit, "[Unit]", "ConditionPathExists") { |
| + neg := strings.HasPrefix(p, "!") |
| + _, err := os.Stat(filepath.Join(u.root, strings.TrimPrefix(p, "!"))) |
| + if (err == nil) == neg { |
| + return false |
| + } |
| + } |
| + 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. |
| +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 changed, err = ensureManagedUnitDropIns(etc); err != nil || changed { |
| + t.Fatalf("second install changed=%v %v", changed, err) |
| + } |
| + return unitTree{root: root}, etc |
| +} |
| + |
| +// stubManagedIdentity makes root (and only root) a managed box. |
| +func stubManagedIdentity(t *testing.T, root string) { |
| + t.Helper() |
| + prev := managedIdentityAt |
| + 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 }) |
| +} |
| + |
| +func writeFileT(t *testing.T, p, body string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// instanceOf names an instance of a workload template. |
| +func instanceOf(template string) string { |
| + return strings.Replace(template, "@.", "@shop.example.com.", 1) |
| +} |
| + |
| +func TestManagedUnitConditionTree(t *testing.T) { |
| + tree, etc := managedTree(t) |
| + run := filepath.Join(tree.root, "run/systemd/system") |
| + // The platform's runtime and config drop-ins, as their writers name and |
| + // fill them: generation, rootfs generation, worker, jit, egress allow, |
| + // config-sync env, capabilities. |
| + host := "shop.example.com" |
| + tier := cgroup.Limit{} |
| + writeFileT(t, filepath.Join(run, instancectl.GenUnitName(host, 3)+".d", instancectl.DropInName), instancectl.GenDropIn(host, 3, tier)) |
| + writeFileT(t, filepath.Join(run, "carlos-instance-rootfs-gen@"+host+"-3.service.d", instancectl.DropInName), instancectl.RootfsGenDropIn(host, 3, tier)) |
| + writeFileT(t, filepath.Join(run, "carlos-instance-rootfs-worker@"+host+".service.d", instancectl.DropInName), instancectl.WorkerDropIn(host, "jobs", tier)) |
| + writeFileT(t, filepath.Join(run, "carlos-instance-rootfs@"+host+".service.d", instancectl.JITDropInName), instancectl.JITDropIn) |
| + writeFileT(t, filepath.Join(run, "carlos-instance@"+host+".service.d", "50-IPAddressAllow.conf"), "[Service]\nIPAddressAllow=192.0.2.1\n") |
| + writeFileT(t, filepath.Join(etc, "systemd/system/shop-api.service.d", appconfig.DropInFile), "[Service]\nEnvironmentFile=-/etc/carlos/apps/shop-api.env\n") |
| + writeFileT(t, filepath.Join(etc, "systemd/system/carlos-app@"+host+".service.d", caps.DropInName), "[Service]\nAmbientCapabilities=CAP_NET_BIND_SERVICE\n") |
| + // An earlier reset, as any drop-in sorting before ours could write: the |
| + // admission assignment must still be the effective last. |
| + writeFileT(t, filepath.Join(etc, "systemd/system/carlos-instance@.service.d/50-carlos-reset.conf"), "[Unit]\nConditionPathExists=\n") |
| + |
| + gated := []string{"shop-api.service", instancectl.GenUnitName(host, 3), "carlos-instance-rootfs-gen@" + host + "-3.service"} |
| + for _, u := range managedboot.WorkloadUnits { |
| + gated = append(gated, u, instanceOf(u)) |
| + } |
| + for _, u := range gated { |
| + conds := tree.list(t, u, "[Unit]", "ConditionPathExists") |
| + if len(conds) == 0 || conds[len(conds)-1] != managedboot.AdmittedMarker { |
| + t.Errorf("%s: effective ConditionPathExists %v, want the admission marker last", u, conds) |
| + } |
| + if tree.conditionMet(t, u) { |
| + t.Errorf("%s: condition met before admission", u) |
| + } |
| + } |
| + var maintenance []string |
| + for _, u := range managedboot.MaintenanceUnits { |
| + if _, err := os.Stat(filepath.Join(etc, "systemd/system", u)); err == nil { |
| + maintenance = append(maintenance, u) |
| + } |
| + if slices.Contains(tree.list(t, u, "[Unit]", "ConditionPathExists"), managedboot.AdmittedMarker) { |
| + t.Errorf("maintenance unit %s carries the admission condition", u) |
| + } |
| + } |
| + if len(maintenance) < 10 { |
| + t.Fatalf("only %d maintenance units installed: %v", len(maintenance), maintenance) |
| + } |
| + // Every unit bootstrap installs is classified one way or the other. |
| + entries, _ := os.ReadDir(filepath.Join(etc, "systemd/system")) |
| + for _, e := range entries { |
| + n := e.Name() |
| + if e.IsDir() || !strings.HasPrefix(n, "carlos") && !strings.HasSuffix(n, ".mount") { |
| + continue |
| + } |
| + if !slices.Contains(managedboot.WorkloadUnits, n) && !slices.Contains(managedboot.MaintenanceUnits, n) { |
| + t.Errorf("installed unit %s is neither a workload nor a maintenance unit", n) |
| + } |
| + } |
| + // The marker appears: every gated unit's condition is met, with no |
| + // reload (systemd evaluates conditions at job start). |
| + if err := os.MkdirAll(filepath.Join(tree.root, managedboot.RootAdmissionDir), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + writeFileT(t, filepath.Join(tree.root, managedboot.AdmittedMarker), "") |
| + for _, u := range gated { |
| + if !tree.conditionMet(t, u) { |
| + t.Errorf("%s: condition unmet after admission", u) |
| + } |
| + } |
| + // None of the platform's drop-ins is named like ours, and no Go string |
| + // outside managedboot writes a Condition directive into a unit. |
| + for _, n := range []string{instancectl.DropInName, instancectl.JITDropInName, appconfig.DropInFile, caps.DropInName, "50-IPAddressAllow.conf", "60-claim-launch.conf"} { |
| + if n == managedboot.AdmissionDropInName || n >= managedboot.AdmissionDropInName { |
| + t.Errorf("platform drop-in %s does not sort before %s", n, managedboot.AdmissionDropInName) |
| + } |
| + } |
| + conditionWitness(t) |
| + if path, err := exec.LookPath("systemd-analyze"); err == nil { |
| + // systemd's own loader over the same tree. It evaluates paths on the |
| + // running host, so only which conditions a unit carries is compared. |
| + for _, u := range append(gated, maintenance...) { |
| + out, _ := exec.Command(path, "--root="+tree.root, "condition", "--unit="+u).CombinedOutput() |
| + has := strings.Contains(string(out), "ConditionPathExists="+managedboot.AdmittedMarker) |
| + if has != !slices.Contains(maintenance, u) { |
| + t.Errorf("systemd-analyze condition %s: carries admission=%v:\n%s", u, has, out) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// conditionWitness: only managedboot's own sources put a Condition |
| +// directive in a string, so no runtime drop-in can reset or add one. |
| +func conditionWitness(t *testing.T) { |
| + t.Helper() |
| + root, err := filepath.Abs("../..") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + re := regexp.MustCompile(`"[^"\n]*Condition[A-Za-z]+=`) |
| + err = filepath.WalkDir(filepath.Join(root, "internal"), func(p string, d fs.DirEntry, err error) error { |
| + if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { |
| + return err |
| + } |
| + if filepath.Dir(p) == filepath.Join(root, "internal", "managedboot") { |
| + return nil |
| + } |
| + b, err := os.ReadFile(p) |
| + if err != nil { |
| + return err |
| + } |
| + if loc := re.FindIndex(b); loc != nil { |
| + rel, _ := filepath.Rel(root, p) |
| + t.Errorf("%s writes a Condition directive: %s", rel, b[loc[0]:loc[1]]) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestManagedControlWritable(t *testing.T) { |
| + tree, etc := managedTree(t) |
| + check := func(t *testing.T) { |
| + t.Helper() |
| + if got := tree.list(t, managedboot.ControlUnit, "[Service]", "ProtectSystem"); len(got) == 0 || got[len(got)-1] != "strict" { |
| + t.Fatalf("ProtectSystem %v", got) |
| + } |
| + paths := tree.list(t, managedboot.ControlUnit, "[Service]", "ReadWritePaths") |
| + for _, want := range []string{"/run/carlos-control", "/run/systemd/system", managedboot.RootAdmissionDir} { |
| + if !slices.Contains(paths, want) { |
| + t.Fatalf("ReadWritePaths %v lacks %s", paths, want) |
| + } |
| + } |
| + } |
| + check(t) |
| + |
| + // A system update reruns bootstrap's install plan: both drop-in sets |
| + // survive it. |
| + if err := bootstrap(tree.root, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + check(t) |
| + for _, u := range managedboot.WorkloadUnits { |
| + if _, err := os.Stat(filepath.Join(etc, "systemd/system", u+".d", managedboot.AdmissionDropInName)); err != nil { |
| + t.Fatalf("bootstrap lost %s's drop-in: %v", u, err) |
| + } |
| + } |
| + |
| + // The root pass restores a lost drop-in and reloads before anything else. |
| + _ = os.Remove(filepath.Join(etc, "systemd/system", managedboot.ControlUnit+".d", managedboot.ControlDropInName)) |
| + _ = 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, " ")); return "", nil } |
| + probe := func(args ...string) (string, error) { return "active", nil } |
| + ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), ctl, probe, t.Logf) |
| + check(t) |
| + if _, err := os.Stat(filepath.Join(etc, "systemd/system/carlos-instance@.service.d", managedboot.AdmissionDropInName)); err != nil { |
| + t.Fatal("the root pass did not restore a workload drop-in") |
| + } |
| + if len(calls) < 2 || calls[0] != "daemon-reload" || calls[1] != "try-restart "+managedboot.ControlUnit { |
| + t.Fatalf("root pass calls %v: want daemon-reload then the control try-restart first", calls) |
| + } |
| + |
| + 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 |
| + // file is "not managed". |
| + 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) |
| + } |
| + ensureSystemUnits(etc, filepath.Join(t.TempDir(), "lock"), ctl, probe, t.Logf) |
| + matches, _ := filepath.Glob(filepath.Join(etc, "systemd/system/*.d", "*managed*")) |
| + if len(matches) != 0 { |
| + t.Fatalf("byo box got managed drop-ins: %v", matches) |
| + } |
| + }) |
| + t.Run("named unit before its declaration", func(t *testing.T) { |
| + prev := namedUnitDropInDir |
| + namedUnitDropInDir = filepath.Join(etc, "systemd/system") |
| + defer func() { namedUnitDropInDir = 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 { |
| + t.Fatal(err) |
| + } |
| + 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") |
| + } |
| + }) |
| +} |
diff --git a/internal/host/namedrecovery.go b/internal/host/namedrecovery.go| index 015d1e3e0..0e92bcb15 100644 |
| --- a/internal/host/namedrecovery.go |
| +++ b/internal/host/namedrecovery.go |
| @@ -26,6 +26,9 @@ type namedUnitRecovery struct { |
| ratchet *release.DigestRatchet |
| writes hostwrite.Config |
| readLive func(string) (string, error) |
| + // gate is managedRootGate on a root pass: a joining managed box |
| + // recovers nothing. nil is ungated. |
| + gate func() error |
| } |
| func productionNamedUnitRecovery(store release.Store, pub ed25519.PublicKey, optDir string, writes hostwrite.Config) namedUnitRecovery { |
diff --git a/internal/host/namedrecovery_pass.go b/internal/host/namedrecovery_pass.go| index fb57ae96f..1e24dc98d 100644 |
| --- a/internal/host/namedrecovery_pass.go |
| +++ b/internal/host/namedrecovery_pass.go |
| @@ -12,6 +12,12 @@ 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 |
| + } |
| + } |
| done, err := n.recover(ctx, rt.Host, checks, getenv, reg) |
| if err != nil { |
| log.Printf("adopt: %v", err) |
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go| index edae092d9..958ed929b 100644 |
| --- a/internal/host/systemunits.go |
| +++ b/internal/host/systemunits.go |
| @@ -10,6 +10,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| ) |
| // systemRecoverUnit is carlos-system-recover.service, spelled out once |
| @@ -99,6 +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) |
| + } |
| + } |
| + logf("adopt: managed admission drop-ins installed") |
| + } |
| + |
| claimSettings, settingsErr := readClaimUnitSettings(filepath.Join(etcDir, "carlos", "host.env")) |
| if settingsErr != nil { |
| logf("adopt: instance-control unit settings: %v", settingsErr) |
diff --git a/internal/host/unitops.go b/internal/host/unitops.go| index 1e8cf7200..98dfaa4f7 100644 |
| --- a/internal/host/unitops.go |
| +++ b/internal/host/unitops.go |
| @@ -54,6 +54,12 @@ func InstallNamedUnits(envDir, dst string, raw []byte) error { |
| return fmt.Errorf("config-sync lock: %w", err) |
| } |
| 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. |
| + if err := managedNamedUnitDropIns(raw, daemonReload); err != nil { |
| + return fmt.Errorf("managed admission drop-ins: %w", err) |
| + } |
| tmp := dst + ".tmp" |
| f, err := os.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) |
| if err != nil { |
diff --git a/internal/instancectl/managedadmit.go b/internal/instancectl/managedadmit.go| new file mode 100644 |
| index 000000000..b995f62ee |
| --- /dev/null |
| +++ b/internal/instancectl/managedadmit.go |
| @@ -0,0 +1,127 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| +) |
| + |
| +// The root admission door (managed fleets 2b-2). Root alone decides whether |
| +// a managed box may run workloads: the agent only relays the console's |
| +// signed ready object here, and root verifies it against the box's own |
| +// root-owned identity before it writes anything (managedboot.CommitAdmission). |
| +const ( |
| + ManagedAdmitPath = "/managed-admit" |
| + ManagedAdmissionPath = "/managed-admission" |
| + // maxManagedAdmitBody bounds the relayed ready object. |
| + maxManagedAdmitBody = 4 << 10 |
| +) |
| + |
| +// managedJoiningText is root's refusal of a workload start on a managed |
| +// box that root has not admitted. |
| +const managedJoiningText = "box is joining its fleet" // COPY |
| + |
| +// ManagedAdmissionState is GET ManagedAdmissionPath's answer. |
| +type ManagedAdmissionState struct { |
| + Managed bool `json:"managed"` |
| + Admitted bool `json:"admitted"` |
| +} |
| + |
| +// managedGatedStarts are the POST routes that start workload units. While |
| +// root has not admitted a managed box each answers 409 before any handler |
| +// runs; stop, sweep, reset, size, ready and egress keep working. |
| +var managedGatedStarts = map[string]bool{ |
| + "/start": true, "/seed": true, "/cmd": true, "/tty": true, "/parent": true, |
| + "/demo-build": true, "/demo-snapshot": true, |
| +} |
| + |
| +// managedState asks ManagedAdmission. A nil hook is a service with no |
| +// managed door (tests of other verbs): BYO, admitted. |
| +func (s *Server) managedState() (managed, admitted bool, err error) { |
| + if s.ManagedAdmission == nil { |
| + return false, true, nil |
| + } |
| + return s.ManagedAdmission() |
| +} |
| + |
| +// managedGate refuses the workload start routes while root has not admitted |
| +// this managed box. Any doubt from RootAdmission refuses too. |
| +func (s *Server) managedGate(next http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method == http.MethodPost && managedGatedStarts[r.URL.Path] { |
| + managed, admitted, err := s.managedState() |
| + if err != nil || (managed && !admitted) { |
| + if err != nil { |
| + s.logf("instance-control: managed admission: %v", err) |
| + } |
| + http.Error(w, managedJoiningText, http.StatusConflict) |
| + return |
| + } |
| + } |
| + next.ServeHTTP(w, r) |
| + }) |
| +} |
| + |
| +// handleManagedAdmit relays one ready object to root's verified commit. |
| +// Every refusal writes nothing; 200 means admission is durable. |
| +func (s *Server) handleManagedAdmit(w http.ResponseWriter, r *http.Request) { |
| + if s.ManagedAdmit == nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + wire, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxManagedAdmitBody)) |
| + if err != nil { |
| + var tooBig *http.MaxBytesError |
| + if errors.As(err, &tooBig) { |
| + http.Error(w, "ready object too large", http.StatusRequestEntityTooLarge) |
| + return |
| + } |
| + http.Error(w, "could not read the ready object", http.StatusBadRequest) |
| + 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) |
| + return |
| + } |
| + s.logf("instance-control: managed box admitted by root") |
| + s.writeManagedState(w) |
| +} |
| + |
| +func (s *Server) handleManagedAdmission(w http.ResponseWriter, _ *http.Request) { |
| + s.writeManagedState(w) |
| +} |
| + |
| +func (s *Server) writeManagedState(w http.ResponseWriter) { |
| + managed, admitted, err := s.managedState() |
| + if err != nil { |
| + s.logf("instance-control: managed admission: %v", err) |
| + managed, admitted = true, false |
| + } |
| + w.Header().Set("Content-Type", "application/json") |
| + _ = json.NewEncoder(w).Encode(ManagedAdmissionState{Managed: managed, Admitted: admitted}) |
| +} |
| + |
| +// ManagedAdmit relays wire, the console's signed ready object, to root. nil |
| +// means root verified it and admission is durable. |
| +func (c *Client) ManagedAdmit(ctx context.Context, wire []byte) error { |
| + var out ManagedAdmissionState |
| + if _, _, err := c.doBody(ctx, DeadlineControl, http.MethodPost, ManagedAdmitPath, nil, wire, &out); err != nil { |
| + return err |
| + } |
| + if !out.Managed || !out.Admitted { |
| + return errors.New("instance control: root did not report the box admitted") |
| + } |
| + return nil |
| +} |
| + |
| +// ManagedAdmission is root's current answer: managed false is a BYO box. |
| +func (c *Client) ManagedAdmission(ctx context.Context) (managed, admitted bool, err error) { |
| + var out ManagedAdmissionState |
| + if _, _, err = c.do(ctx, DeadlineControl, http.MethodGet, ManagedAdmissionPath, nil, &out); err != nil { |
| + return false, false, err |
| + } |
| + return out.Managed, out.Admitted, nil |
| +} |
diff --git a/internal/instancectl/managedadmit_linux_test.go b/internal/instancectl/managedadmit_linux_test.go| new file mode 100644 |
| index 000000000..9c2b51110 |
| --- /dev/null |
| +++ b/internal/instancectl/managedadmit_linux_test.go |
| @@ -0,0 +1,298 @@ |
| +//go:build linux |
| + |
| +package instancectl |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + "io/fs" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/managedboot/roottest" |
| +) |
| + |
| +// managedServer is a root door wired to a fake managed root, with a |
| +// systemctl that counts every call. |
| +func managedServer(t *testing.T, m *roottest.ManagedRoot) (*Server, *atomic.Int64) { |
| + t.Helper() |
| + var calls atomic.Int64 |
| + s := &Server{ |
| + ManagedAdmit: m.Commit, |
| + ManagedAdmission: m.Admission, |
| + Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + calls.Add(1) |
| + return "", nil |
| + }, |
| + Logf: t.Logf, |
| + } |
| + return s, &calls |
| +} |
| + |
| +func doRequest(h http.Handler, method, path string, body []byte) *httptest.ResponseRecorder { |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, httptest.NewRequest(method, path, bytes.NewReader(body))) |
| + return w |
| +} |
| + |
| +func admissionState(t *testing.T, h http.Handler) ManagedAdmissionState { |
| + t.Helper() |
| + w := doRequest(h, http.MethodGet, ManagedAdmissionPath, nil) |
| + var st ManagedAdmissionState |
| + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &st) != nil { |
| + t.Fatalf("GET %s: %d %s", ManagedAdmissionPath, w.Code, w.Body) |
| + } |
| + return st |
| +} |
| + |
| +func dirEntries(t *testing.T, m *roottest.ManagedRoot) int { |
| + t.Helper() |
| + e, err := os.ReadDir(m.Path(managedboot.RootAdmissionDir)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return len(e) |
| +} |
| + |
| +// gatedStarts are every workload start route, with a plausible query. |
| +var gatedStarts = []string{"/start?host=shop.example.com", "/start?host=shop.example.com&gen=1", "/start?host=shop.example.com&role=rootfs", |
| + "/seed?host=shop.example.com", "/cmd?host=shop.example.com", "/tty?host=shop.example.com", "/parent?host=shop.example.com", |
| + "/demo-build", "/demo-snapshot"} |
| + |
| +func TestManagedRootAdmitVerify(t *testing.T) { |
| + sign := func(priv ed25519.PrivateKey, rec any, extra map[string]any) []byte { |
| + p, _ := json.Marshal(rec) |
| + b64 := base64.StdEncoding.EncodeToString(p) |
| + w := map[string]any{"payload": b64, "sig": base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(b64)))} |
| + for k, v := range extra { |
| + w[k] = v |
| + } |
| + out, _ := json.Marshal(w) |
| + return out |
| + } |
| + t.Run("refused objects write nothing", func(t *testing.T) { |
| + m := roottest.NewManagedRoot(t) |
| + s, _ := managedServer(t, m) |
| + h := s.Handler() |
| + _, foreign, _ := ed25519.GenerateKey(nil) |
| + other := func(f func(r *managedboot.ReadyRecord)) []byte { |
| + r := m.Ready |
| + f(&r) |
| + return sign(m.Key, r, nil) |
| + } |
| + valid := m.Wire(t) |
| + refused := map[string][]byte{ |
| + "unsigned": []byte(`{"fleet":"shop","label":"box-1"}`), |
| + "wrong key": sign(foreign, m.Ready, nil), |
| + "scoped grant": sign(m.Key, m.Ready, map[string]any{"grant": map[string]string{"pub": "x", "sig": "y"}}), |
| + "other kind": other(func(r *managedboot.ReadyRecord) { r.Kind = "channel-pointer" }), |
| + "other fleet": other(func(r *managedboot.ReadyRecord) { r.Fleet = "other" }), |
| + "other label": other(func(r *managedboot.ReadyRecord) { r.Label = "box-2" }), |
| + "other op": other(func(r *managedboot.ReadyRecord) { r.Op = strings.Repeat("e", 32) }), |
| + "trailing": append(append([]byte(nil), valid...), []byte(`{"x":1}`)...), |
| + "oversize": append(append([]byte(nil), valid...), bytes.Repeat([]byte(" "), 5000)...), |
| + } |
| + for name, body := range refused { |
| + w := doRequest(h, http.MethodPost, ManagedAdmitPath, body) |
| + if w.Code/100 != 4 { |
| + t.Errorf("%s: %d", name, w.Code) |
| + } |
| + if n := dirEntries(t, m); n != 0 { |
| + t.Fatalf("%s: wrote %d files", name, n) |
| + } |
| + } |
| + if st := admissionState(t, h); !st.Managed || st.Admitted { |
| + t.Fatalf("after refusals: %+v", st) |
| + } |
| + }) |
| + t.Run("valid, replay, and the start gate", func(t *testing.T) { |
| + m := roottest.NewManagedRoot(t) |
| + s, calls := managedServer(t, m) |
| + h := s.Handler() |
| + for _, p := range gatedStarts { |
| + w := doRequest(h, http.MethodPost, p, nil) |
| + if w.Code != http.StatusConflict || strings.TrimSpace(w.Body.String()) != managedJoiningText { |
| + t.Errorf("joining POST %s: %d %q", p, w.Code, w.Body) |
| + } |
| + } |
| + if calls.Load() != 0 { |
| + t.Fatalf("a refused start reached systemctl %d times", calls.Load()) |
| + } |
| + for _, p := range []string{"POST /stop?host=shop.example.com", "POST /sweep", "GET /ready", "GET /size?host=shop.example.com", "POST /reset?host=shop.example.com"} { |
| + method, path, _ := strings.Cut(p, " ") |
| + if w := doRequest(h, method, path, nil); w.Code == http.StatusConflict && strings.Contains(w.Body.String(), managedJoiningText) { |
| + t.Errorf("maintenance %s refused while joining", p) |
| + } |
| + } |
| + wire := m.Wire(t) |
| + if w := doRequest(h, http.MethodPost, ManagedAdmitPath, wire); w.Code != 200 { |
| + t.Fatalf("valid: %d %s", w.Code, w.Body) |
| + } |
| + for _, p := range []string{managedboot.AdmissionPath, managedboot.AdmittedMarker} { |
| + if _, err := os.Lstat(m.Path(p)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if st := admissionState(t, h); !st.Managed || !st.Admitted { |
| + t.Fatalf("after admit: %+v", st) |
| + } |
| + before, _ := os.Stat(m.Path(managedboot.AdmissionPath)) |
| + if w := doRequest(h, http.MethodPost, ManagedAdmitPath, wire); w.Code != 200 { |
| + t.Fatalf("replay: %d %s", w.Code, w.Body) |
| + } |
| + after, _ := os.Stat(m.Path(managedboot.AdmissionPath)) |
| + if !os.SameFile(before, after) || !after.ModTime().Equal(before.ModTime()) { |
| + t.Fatal("replay rewrote the record") |
| + } |
| + for _, p := range gatedStarts { |
| + if w := doRequest(h, http.MethodPost, p, nil); strings.Contains(w.Body.String(), managedJoiningText) { |
| + t.Errorf("admitted POST %s still refused", p) |
| + } |
| + } |
| + }) |
| + t.Run("crash after the record, before the marker", func(t *testing.T) { |
| + m := roottest.NewManagedRoot(t) |
| + s, _ := managedServer(t, m) |
| + h := s.Handler() |
| + if err := os.WriteFile(m.Path(managedboot.AdmissionPath), m.Wire(t), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st := admissionState(t, h); st.Admitted { |
| + t.Fatal("record without marker admitted") |
| + } |
| + if w := doRequest(h, http.MethodPost, ManagedAdmitPath, m.Wire(t)); w.Code != 200 { |
| + t.Fatalf("replay: %d %s", w.Code, w.Body) |
| + } |
| + if _, err := os.Lstat(m.Path(managedboot.AdmittedMarker)); err != nil { |
| + t.Fatal("replay did not complete the marker") |
| + } |
| + }) |
| + t.Run("identity tampered", func(t *testing.T) { |
| + for name, tamper := range map[string]func(m *roottest.ManagedRoot){ |
| + "group-writable parent": func(m *roottest.ManagedRoot) { _ = os.Chmod(m.Path("etc/carlos"), 0o775) }, |
| + "world-writable file": func(m *roottest.ManagedRoot) { _ = os.Chmod(m.Path(managedboot.IdentityPath), 0o666) }, |
| + } { |
| + m := roottest.NewManagedRoot(t) |
| + tamper(m) |
| + s, _ := managedServer(t, m) |
| + h := s.Handler() |
| + if w := doRequest(h, http.MethodPost, ManagedAdmitPath, m.Wire(t)); w.Code != http.StatusForbidden { |
| + t.Errorf("%s: %d", name, w.Code) |
| + } |
| + if dirEntries(t, m) != 0 { |
| + t.Errorf("%s: wrote files", name) |
| + } |
| + if w := doRequest(h, http.MethodPost, "/start?host=shop.example.com", nil); w.Code != http.StatusConflict { |
| + t.Errorf("%s: start not refused: %d", name, w.Code) |
| + } |
| + } |
| + }) |
| + t.Run("byo", func(t *testing.T) { |
| + root := t.TempDir() |
| + owner := managedboot.RootOwner{UID: os.Getuid(), GID: os.Getgid()} |
| + s := &Server{ManagedAdmission: func() (bool, bool, error) { return managedboot.RootAdmissionAs(root, owner) }, |
| + ManagedAdmit: func(w []byte) error { return managedboot.CommitAdmissionAs(root, w, owner) }} |
| + h := s.Handler() |
| + if st := admissionState(t, h); st.Managed || !st.Admitted { |
| + t.Fatalf("byo: %+v", st) |
| + } |
| + if w := doRequest(h, http.MethodPost, "/start?host=shop.example.com", nil); strings.Contains(w.Body.String(), managedJoiningText) { |
| + t.Fatal("byo start refused") |
| + } |
| + if w := doRequest(h, http.MethodPost, ManagedAdmitPath, []byte(`{}`)); w.Code != http.StatusForbidden { |
| + t.Fatalf("byo admit: %d", w.Code) |
| + } |
| + }) |
| + t.Run("client", func(t *testing.T) { |
| + m := roottest.NewManagedRoot(t) |
| + s, _ := managedServer(t, m) |
| + srv := httptest.NewServer(s.Handler()) |
| + defer srv.Close() |
| + c := &Client{Path: "control.sock", Dial: func(ctx context.Context, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "tcp", srv.Listener.Addr().String()) |
| + }} |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + if managed, admitted, err := c.ManagedAdmission(ctx); err != nil || !managed || admitted { |
| + t.Fatalf("joining: %v %v %v", managed, admitted, err) |
| + } |
| + if err := c.ManagedAdmit(ctx, []byte(`{}`)); err == nil { |
| + t.Fatal("client reported a refused admit as success") |
| + } |
| + if err := c.ManagedAdmit(ctx, m.Wire(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if managed, admitted, err := c.ManagedAdmission(ctx); err != nil || !managed || !admitted { |
| + t.Fatalf("admitted: %v %v %v", managed, admitted, err) |
| + } |
| + }) |
| + t.Run("nothing removes or truncates the marker", func(t *testing.T) { |
| + admissionWitness(t) |
| + }) |
| +} |
| + |
| +// admissionWitness greps the module's non-test Go: no line that names the |
| +// marker or the root admission directory removes or truncates anything, and |
| +// only managedboot itself and the roottest fixture call the owner-taking variants. |
| +func admissionWitness(t *testing.T) { |
| + t.Helper() |
| + root, err := filepath.Abs("../..") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + names := regexp.MustCompile(`AdmittedMarker|RootAdmissionDir|AdmissionPath|carlos-managed-root`) |
| + destroy := regexp.MustCompile(`Remove|Truncate|Unlink|Rename|O_TRUNC|rm -`) |
| + variants := regexp.MustCompile(`CommitAdmissionAs|RootAdmissionAs`) |
| + seen := 0 |
| + err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + if d.IsDir() && (d.Name() == ".git" || d.Name() == "node_modules" || d.Name() == "vendor") { |
| + return filepath.SkipDir |
| + } |
| + if d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { |
| + return nil |
| + } |
| + f, err := os.Open(p) |
| + if err != nil { |
| + return err |
| + } |
| + defer f.Close() |
| + rel, _ := filepath.Rel(root, p) |
| + sc := bufio.NewScanner(f) |
| + sc.Buffer(make([]byte, 1<<20), 1<<20) |
| + for n := 1; sc.Scan(); n++ { |
| + line := sc.Text() |
| + if names.MatchString(line) { |
| + seen++ |
| + if destroy.MatchString(line) { |
| + t.Errorf("%s:%d removes or truncates admission state: %s", rel, n, strings.TrimSpace(line)) |
| + } |
| + } |
| + if variants.MatchString(line) && filepath.Dir(rel) != filepath.Join("internal", "managedboot") && !strings.HasPrefix(rel, filepath.Join("internal", "managedboot", "roottest")+string(filepath.Separator)) { |
| + t.Errorf("%s:%d calls an owner-taking admission variant outside managedboot: %s", rel, n, strings.TrimSpace(line)) |
| + } |
| + } |
| + return sc.Err() |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if seen == 0 { |
| + t.Fatal("the witness found no reference to the admission paths: wrong root?") |
| + } |
| +} |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index 6714a6882..3a4c5a753 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -28,6 +28,7 @@ import ( |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/demobuild" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -54,6 +55,15 @@ type Server struct { |
| snapshots *demoSnapshotSupervisor |
| ClaimStop http.Handler |
| + // ManagedAdmit is root's verified admission commit of a relayed ready |
| + // object (managedboot.CommitAdmission) and ManagedAdmission root's |
| + // current answer (managedboot.RootAdmission). While a managed box is |
| + // not admitted the workload start routes refuse (managedGate). nil |
| + // ManagedAdmission is a service with no managed door: every start |
| + // proceeds as on main, and POST /managed-admit is 404 without |
| + // ManagedAdmit. |
| + ManagedAdmit func(wire []byte) error |
| + ManagedAdmission func() (managed, admitted bool, err error) |
| // ClaimHeldRelease is the moves held-release route's handler (moves |
| // Task 7b), registered only when set: the host sets it with both |
| // CARLOS_HOST_CLAIM and CARLOS_MOVES_PHASE1 on, so with moves off the |
| @@ -291,35 +301,40 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV |
| out, err := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput() |
| return string(out), err |
| }, |
| - PeerOK: productionPeerOK(), |
| - CgroupRoot: "/sys/fs/cgroup", |
| - ProbeOut: filepath.Join(controlsock.Dir, "probe.out"), |
| - FixtureOK: ProbeFixturesOK, |
| - ProbeEvery: 5 * time.Minute, |
| - Logf: log.Printf, |
| - ExeRoot: filepath.Join(controlsock.Dir, "exe"), |
| - OptDir: "/opt/carlos", |
| - HostApp: view.HostApp, |
| - HostRuntime: view.HostRuntime, |
| - HostDemo: view.HostDemo, |
| - DemoConfig: cfg, |
| - DemoRoutes: view.DemoRoutes, |
| - DemoPurgeGuard: view.DemoPurgeGuard, |
| - DemoRunRoot: "/run/carlos/instances", |
| - ProbeImage: BuildProbeImage, |
| - ProbeImageFile: ProbeImagePath, |
| - RootfsProbeOut: filepath.Join(controlsock.Dir, "rootfs-probe.out"), |
| - DropInDir: "/run/systemd/system", |
| - ResolvConf: "/etc/resolv.conf", |
| - ResolvedConf: ResolvedConf, |
| - LocalAddrs: func() ([]netip.Prefix, error) { return localPrefixes(fibTriePath, ifInet6Path) }, |
| - DenyEvery: 10 * time.Second, |
| - DataRoot: "/data/instances", |
| - Statfs: statfsBytes, |
| - DiskEvery: 30 * time.Second, |
| - Build: version.Build, |
| - ExeCurrent: installedBinaryCurrent, |
| - Egress: egress, |
| + PeerOK: productionPeerOK(), |
| + // Root's admission authority on a managed box (2b-2): every |
| + // production service carries it, claims on or off; on a BYO box |
| + // RootAdmission answers admitted and nothing changes. |
| + ManagedAdmit: func(wire []byte) error { return managedboot.CommitAdmission("/", wire) }, |
| + ManagedAdmission: func() (bool, bool, error) { return managedboot.RootAdmission("/") }, |
| + CgroupRoot: "/sys/fs/cgroup", |
| + ProbeOut: filepath.Join(controlsock.Dir, "probe.out"), |
| + FixtureOK: ProbeFixturesOK, |
| + ProbeEvery: 5 * time.Minute, |
| + Logf: log.Printf, |
| + ExeRoot: filepath.Join(controlsock.Dir, "exe"), |
| + OptDir: "/opt/carlos", |
| + HostApp: view.HostApp, |
| + HostRuntime: view.HostRuntime, |
| + HostDemo: view.HostDemo, |
| + DemoConfig: cfg, |
| + DemoRoutes: view.DemoRoutes, |
| + DemoPurgeGuard: view.DemoPurgeGuard, |
| + DemoRunRoot: "/run/carlos/instances", |
| + ProbeImage: BuildProbeImage, |
| + ProbeImageFile: ProbeImagePath, |
| + RootfsProbeOut: filepath.Join(controlsock.Dir, "rootfs-probe.out"), |
| + DropInDir: "/run/systemd/system", |
| + ResolvConf: "/etc/resolv.conf", |
| + ResolvedConf: ResolvedConf, |
| + LocalAddrs: func() ([]netip.Prefix, error) { return localPrefixes(fibTriePath, ifInet6Path) }, |
| + DenyEvery: 10 * time.Second, |
| + DataRoot: "/data/instances", |
| + Statfs: statfsBytes, |
| + DiskEvery: 30 * time.Second, |
| + Build: version.Build, |
| + ExeCurrent: installedBinaryCurrent, |
| + Egress: egress, |
| } |
| ln, activated, err := activatedListener() |
| if err != nil { |
| @@ -526,7 +541,9 @@ func (s *Server) Handler() http.Handler { |
| mux.HandleFunc("POST /egress", s.handleEgress) |
| mux.HandleFunc("GET /egress", s.handleEgressStatus) |
| mux.HandleFunc("GET "+RootfsReadyPath, s.handleReadyRootfs) |
| - return s.demoHandler(mux) |
| + mux.HandleFunc("POST "+ManagedAdmitPath, s.handleManagedAdmit) |
| + mux.HandleFunc("GET "+ManagedAdmissionPath, s.handleManagedAdmission) |
| + return s.managedGate(s.demoHandler(mux)) |
| } |
| // handleEgress re-asserts one host's slice now (the agent's nudge after |
diff --git a/internal/managedboot/admission.go b/internal/managedboot/admission.go| new file mode 100644 |
| index 000000000..289198a22 |
| --- /dev/null |
| +++ b/internal/managedboot/admission.go |
| @@ -0,0 +1,95 @@ |
| +package managedboot |
| + |
| +import ( |
| + "encoding/base64" |
| + "errors" |
| + "os" |
| +) |
| + |
| +// AdmissionPath is root's verified admission record. It and AdmittedMarker |
| +// live in RootAdmissionDir, root:root 0700, which the service user cannot |
| +// enter, so no file carlos can create, replace or link decides admission. |
| +const AdmissionPath = RootAdmissionDir + "/admission.json" |
| + |
| +// RootOwner is the uid and gid every file root's admission decision reads |
| +// must carry. Production is root (0, 0); only an unprivileged test passes |
| +// its own ids for a fake root it owns. |
| +type RootOwner struct{ UID, GID int } |
| + |
| +var ( |
| + errNotManaged = errors.New("managedboot: this is not a managed box") |
| + errAdmissionRoot = errors.New("managedboot: root admission is root's alone") |
| +) |
| + |
| +// 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 |
| +// operation. It writes AdmissionPath (temp file, fsync, rename without |
| +// replacing, directory fsync) and then creates AdmittedMarker (exclusive, |
| +// fsync, directory fsync), the commit point. A replay with a valid record |
| +// and no marker completes the marker; an existing valid record is kept, |
| +// never replaced. Nothing removes the marker. |
| +func CommitAdmission(root string, wire []byte) error { |
| + if os.Geteuid() != 0 { |
| + return errAdmissionRoot |
| + } |
| + return CommitAdmissionAs(root, wire, RootOwner{}) |
| +} |
| + |
| +// RootAdmission is root's answer to "may workloads run": no identity file |
| +// is a BYO box (false, true, nil). With an identity the box is admitted |
| +// only when AdmittedMarker is a root-owned regular file and AdmissionPath |
| +// is a root-owned 0600 single-link regular file in the root 0700 |
| +// directory, opened without following links, whose bytes verify again. |
| +// Anything else is (true, false, err); a box that simply has not been |
| +// admitted yet is (true, false, nil). |
| +func RootAdmission(root string) (managed, admitted bool, err error) { |
| + return RootAdmissionAs(root, RootOwner{}) |
| +} |
| + |
| +// CommitAdmissionAs is CommitAdmission with the expected owner given |
| +// instead of root and no euid check. Only CommitAdmission and tests call |
| +// it (TestManagedRootAdmitVerify's grep witness pins that). |
| +func CommitAdmissionAs(root string, wire []byte, owner RootOwner) error { |
| + id, pub, err := admissionIdentity(root, owner) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err = VerifyReady(pub, wire, id); err != nil { |
| + return err |
| + } |
| + return commitAdmission(root, wire, owner, id, pub) |
| +} |
| + |
| +// RootAdmissionAs is RootAdmission with the expected owner given instead |
| +// of root. Only RootAdmission and tests call it. |
| +func RootAdmissionAs(root string, owner RootOwner) (managed, admitted bool, err error) { |
| + id, managed, err := loadIdentity(root, owner.UID) |
| + if err != nil { |
| + return true, false, err |
| + } |
| + if !managed { |
| + return false, true, nil |
| + } |
| + pub, err := base64.StdEncoding.DecodeString(id.ReleasePubkey) |
| + if err != nil { |
| + return true, false, errIdentity |
| + } |
| + admitted, err = rootAdmitted(root, owner, id, pub) |
| + return true, admitted && err == nil, err |
| +} |
| + |
| +func admissionIdentity(root string, owner RootOwner) (Identity, []byte, error) { |
| + id, managed, err := loadIdentity(root, owner.UID) |
| + if err != nil { |
| + return Identity{}, nil, err |
| + } |
| + if !managed { |
| + return Identity{}, nil, errNotManaged |
| + } |
| + pub, err := base64.StdEncoding.DecodeString(id.ReleasePubkey) |
| + if err != nil { |
| + return Identity{}, nil, errIdentity |
| + } |
| + return id, pub, nil |
| +} |
diff --git a/internal/managedboot/admission_linux.go b/internal/managedboot/admission_linux.go| new file mode 100644 |
| index 000000000..ed4122a1e |
| --- /dev/null |
| +++ b/internal/managedboot/admission_linux.go |
| @@ -0,0 +1,212 @@ |
| +//go:build linux |
| + |
| +package managedboot |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +const ( |
| + admissionName = "admission.json" |
| + markerName = "admitted" |
| +) |
| + |
| +func admissionDoubt(what string) error { |
| + return fmt.Errorf("managedboot: root admission refused: %s", what) |
| +} |
| + |
| +// openAdmissionDir opens root+RootAdmissionDir one component at a time |
| +// without following a link. Every ancestor must be owned by owner.UID and |
| +// not writable by group or other (so nobody else can rename the directory |
| +// away); the directory itself must be owner.UID:owner.GID, mode 0700. |
| +func openAdmissionDir(root string, owner RootOwner) (int, error) { |
| + if root == "" { |
| + root = "/" |
| + } |
| + fd, err := unix.Open(root, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return -1, err |
| + } |
| + parts := strings.Split(strings.TrimPrefix(filepath.Clean(RootAdmissionDir), "/"), "/") |
| + for n, part := range parts { |
| + next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| + unix.Close(fd) |
| + if err != nil { |
| + return -1, admissionDoubt("cannot open " + part + ": " + err.Error()) |
| + } |
| + fd = next |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err != nil { |
| + unix.Close(fd) |
| + return -1, err |
| + } |
| + if int(st.Uid) != owner.UID || st.Mode&0o022 != 0 { |
| + unix.Close(fd) |
| + return -1, admissionDoubt(part + " is not owned by root or is writable by others") |
| + } |
| + if n == len(parts)-1 && (int(st.Gid) != owner.GID || st.Mode&0o7777 != 0o700) { |
| + unix.Close(fd) |
| + return -1, admissionDoubt(RootAdmissionDir + " is not root:root 0700") |
| + } |
| + } |
| + return fd, nil |
| +} |
| + |
| +// openOwnedFile opens name in dfd without following a link and checks it |
| +// is a single-link regular owner.UID:owner.GID file of mode 0600. |
| +func openOwnedFile(dfd int, name string, owner RootOwner) (*os.File, error) { |
| + fd, err := unix.Openat(dfd, name, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err != nil { |
| + unix.Close(fd) |
| + return nil, err |
| + } |
| + if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1 || int(st.Uid) != owner.UID || int(st.Gid) != owner.GID || st.Mode&0o7777 != 0o600 { |
| + unix.Close(fd) |
| + return nil, admissionDoubt(name + " is not a root-owned 0600 single-link regular file") |
| + } |
| + return os.NewFile(uintptr(fd), name), nil |
| +} |
| + |
| +// readAdmission returns the verified record's bytes, ENOENT when there is |
| +// none, or a refusal when what is there is not a verified record. |
| +func readAdmission(dfd int, owner RootOwner, pub ed25519.PublicKey, id Identity) ([]byte, error) { |
| + f, err := openOwnedFile(dfd, admissionName, owner) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer f.Close() |
| + b, err := io.ReadAll(io.LimitReader(f, MaxReadyBytes+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if _, err = VerifyReady(pub, b, id); err != nil { |
| + return nil, admissionDoubt(admissionName + " does not verify: " + err.Error()) |
| + } |
| + return b, nil |
| +} |
| + |
| +func rootAdmitted(root string, owner RootOwner, id Identity, pub ed25519.PublicKey) (bool, error) { |
| + dfd, err := openAdmissionDir(root, owner) |
| + if err != nil { |
| + return false, err |
| + } |
| + defer unix.Close(dfd) |
| + marker, err := openOwnedFile(dfd, markerName, owner) |
| + if errors.Is(err, unix.ENOENT) { |
| + // Not admitted yet. A verified record without the marker is a |
| + // commit cut short; the next relay completes it. |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + marker.Close() |
| + if _, err = readAdmission(dfd, owner, pub, id); err != nil { |
| + if errors.Is(err, unix.ENOENT) { |
| + return false, admissionDoubt("the admitted marker has no admission record") |
| + } |
| + return false, err |
| + } |
| + return true, nil |
| +} |
| + |
| +func commitAdmission(root string, wire []byte, owner RootOwner, id Identity, pub ed25519.PublicKey) error { |
| + dfd, err := openAdmissionDir(root, owner) |
| + if err != nil { |
| + return err |
| + } |
| + defer unix.Close(dfd) |
| + _, err = readAdmission(dfd, owner, pub, id) |
| + if errors.Is(err, unix.ENOENT) { |
| + err = writeAdmission(dfd, wire, owner, pub, id) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return createMarker(dfd, owner) |
| +} |
| + |
| +// writeAdmission installs wire as admissionName without ever replacing an |
| +// existing record: a concurrent commit that got there first wins, and its |
| +// record is verified like any other. |
| +func writeAdmission(dfd int, wire []byte, owner RootOwner, pub ed25519.PublicKey, id Identity) error { |
| + var suffix [8]byte |
| + if _, err := rand.Read(suffix[:]); err != nil { |
| + return err |
| + } |
| + tmp := "." + admissionName + "." + hex.EncodeToString(suffix[:]) |
| + fd, err := unix.Openat(dfd, tmp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + f := os.NewFile(uintptr(fd), tmp) |
| + defer unix.Unlinkat(dfd, tmp, 0) |
| + if err = f.Chmod(0o600); err == nil { |
| + if _, err = f.Write(wire); err == nil { |
| + err = f.Sync() |
| + } |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + err = unix.Renameat2(dfd, tmp, dfd, admissionName, unix.RENAME_NOREPLACE) |
| + if errors.Is(err, unix.EINVAL) || errors.Is(err, unix.ENOSYS) { |
| + // A filesystem without RENAME_NOREPLACE: a hard link also refuses |
| + // to replace; the deferred unlink drops the temporary name. |
| + err = unix.Linkat(dfd, tmp, dfd, admissionName, 0) |
| + } |
| + if errors.Is(err, unix.EEXIST) { |
| + _, err = readAdmission(dfd, owner, pub, id) |
| + return err |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = unix.Unlinkat(dfd, tmp, 0); err != nil && !errors.Is(err, unix.ENOENT) { |
| + return err |
| + } |
| + return unix.Fsync(dfd) |
| +} |
| + |
| +// createMarker is the commit point: AdmittedMarker, created exclusively and |
| +// durably. An existing marker must itself pass the owner checks. |
| +func createMarker(dfd int, owner RootOwner) error { |
| + fd, err := unix.Openat(dfd, markerName, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0o600) |
| + if errors.Is(err, unix.EEXIST) { |
| + f, err := openOwnedFile(dfd, markerName, owner) |
| + if err != nil { |
| + return err |
| + } |
| + return f.Close() |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = unix.Fchmod(fd, 0o600); err == nil { |
| + err = unix.Fsync(fd) |
| + } |
| + if cerr := unix.Close(fd); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return unix.Fsync(dfd) |
| +} |
diff --git a/internal/managedboot/admission_linux_test.go b/internal/managedboot/admission_linux_test.go| new file mode 100644 |
| index 000000000..71a618649 |
| --- /dev/null |
| +++ b/internal/managedboot/admission_linux_test.go |
| @@ -0,0 +1,231 @@ |
| +//go:build linux |
| + |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "os" |
| + "path/filepath" |
| + "syscall" |
| + "testing" |
| +) |
| + |
| +type admissionRoot struct { |
| + root string |
| + owner RootOwner |
| + priv ed25519.PrivateKey |
| + id Identity |
| + wire []byte |
| +} |
| + |
| +func (a admissionRoot) path(p string) string { return filepath.Join(a.root, p) } |
| + |
| +// newAdmissionRoot is a fake managed root the test's own uid owns, laid out |
| +// as the first boot's commit leaves it: identity, empty 0700 admission dir. |
| +func newAdmissionRoot(t *testing.T) admissionRoot { |
| + t.Helper() |
| + priv, id, rec := readyFixture(t) |
| + a := admissionRoot{root: t.TempDir(), owner: RootOwner{UID: os.Getuid(), GID: os.Getgid()}, priv: priv, id: id} |
| + for _, d := range []struct { |
| + p string |
| + mode os.FileMode |
| + }{{"etc", 0o755}, {"etc/carlos", 0o755}, {"var", 0o755}, {"var/lib", 0o755}, {RootAdmissionDir, 0o700}} { |
| + if err := os.Mkdir(a.path(d.p), d.mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(a.path(d.p), d.mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if st, err := os.Stat(a.path(RootAdmissionDir)); err == nil { |
| + a.owner.GID = int(st.Sys().(*syscall.Stat_t).Gid) |
| + } |
| + body, err := EncodeIdentity(id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.WriteFile(a.path(IdentityPath), body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a.wire, err = SignReady(priv, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + return a |
| +} |
| + |
| +func (a admissionRoot) state(t *testing.T) (bool, bool, error) { |
| + t.Helper() |
| + return RootAdmissionAs(a.root, a.owner) |
| +} |
| + |
| +func (a admissionRoot) mustAdmitted(t *testing.T, want bool, wantErr bool) { |
| + t.Helper() |
| + managed, admitted, err := a.state(t) |
| + if !managed || admitted != want || (err != nil) != wantErr { |
| + t.Fatalf("RootAdmission = managed %v admitted %v err %v; want admitted %v err %v", managed, admitted, err, want, wantErr) |
| + } |
| +} |
| + |
| +func TestManagedRootAdmissionChecks(t *testing.T) { |
| + t.Run("byo", func(t *testing.T) { |
| + managed, admitted, err := RootAdmissionAs(t.TempDir(), RootOwner{UID: os.Getuid(), GID: os.Getgid()}) |
| + if managed || !admitted || err != nil { |
| + t.Fatalf("no identity: %v %v %v", managed, admitted, err) |
| + } |
| + }) |
| + t.Run("commit and replay", func(t *testing.T) { |
| + a := newAdmissionRoot(t) |
| + a.mustAdmitted(t, false, false) |
| + if err := CommitAdmissionAs(a.root, a.wire, a.owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.mustAdmitted(t, true, false) |
| + for _, p := range []string{AdmissionPath, AdmittedMarker} { |
| + st, err := os.Lstat(a.path(p)) |
| + if err != nil || !st.Mode().IsRegular() || st.Mode().Perm() != 0o600 { |
| + t.Fatalf("%s: %v %v", p, st, err) |
| + } |
| + } |
| + if got, _ := os.ReadFile(a.path(AdmissionPath)); !bytes.Equal(got, a.wire) { |
| + t.Fatal("record bytes differ from the relayed object") |
| + } |
| + if err := CommitAdmissionAs(a.root, a.wire, a.owner); err != nil { |
| + t.Fatalf("replay: %v", err) |
| + } |
| + if got, _ := os.ReadFile(a.path(AdmissionPath)); !bytes.Equal(got, a.wire) { |
| + t.Fatal("replay changed the record") |
| + } |
| + entries, _ := os.ReadDir(a.path(RootAdmissionDir)) |
| + if len(entries) != 2 { |
| + t.Fatalf("admission dir holds %d entries, want 2 (no temporaries left)", len(entries)) |
| + } |
| + }) |
| + t.Run("record without marker is not admitted and replay completes it", func(t *testing.T) { |
| + a := newAdmissionRoot(t) |
| + if err := os.WriteFile(a.path(AdmissionPath), a.wire, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.mustAdmitted(t, false, false) |
| + if err := CommitAdmissionAs(a.root, a.wire, a.owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.mustAdmitted(t, true, false) |
| + }) |
| + t.Run("an existing valid record is kept", func(t *testing.T) { |
| + a := newAdmissionRoot(t) |
| + if err := CommitAdmissionAs(a.root, a.wire, a.owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _, rec := readyFixture(t) |
| + rec.ReadyAt = rec.ReadyAt.Add(1) |
| + other, _ := SignReady(a.priv, rec) |
| + if err := CommitAdmissionAs(a.root, other, a.owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _ := os.ReadFile(a.path(AdmissionPath)); !bytes.Equal(got, a.wire) { |
| + t.Fatal("a second valid object replaced the record") |
| + } |
| + }) |
| + t.Run("refused objects write nothing", func(t *testing.T) { |
| + a := newAdmissionRoot(t) |
| + _, other, _ := ed25519.GenerateKey(bytes.NewReader(bytes.Repeat([]byte{8}, 64))) |
| + _, _, rec := readyFixture(t) |
| + foreign, _ := SignReady(other, rec) |
| + for name, w := range map[string][]byte{"foreign": foreign, "empty": nil, "trailing": append(append([]byte(nil), a.wire...), '{', '}')} { |
| + if err := CommitAdmissionAs(a.root, w, a.owner); err == nil { |
| + t.Errorf("%s: committed", name) |
| + } |
| + } |
| + if entries, _ := os.ReadDir(a.path(RootAdmissionDir)); len(entries) != 0 { |
| + t.Fatalf("refused commits left %d entries", len(entries)) |
| + } |
| + }) |
| + t.Run("not root", func(t *testing.T) { |
| + if os.Geteuid() == 0 { |
| + t.Skip("the euid refusal needs an unprivileged run; the root runner covers root") |
| + } |
| + a := newAdmissionRoot(t) |
| + if err := CommitAdmission(a.root, a.wire); err == nil { |
| + t.Fatal("an unprivileged CommitAdmission committed") |
| + } |
| + if managed, admitted, err := RootAdmission(a.root); !managed || admitted || err == nil { |
| + t.Fatalf("root-expecting RootAdmission over a non-root tree: %v %v %v", managed, admitted, err) |
| + } |
| + }) |
| + refusals := map[string]func(t *testing.T, a admissionRoot){ |
| + "symlinked record": func(t *testing.T, a admissionRoot) { |
| + real := a.path(RootAdmissionDir + "/real.json") |
| + _ = os.Rename(a.path(AdmissionPath), real) |
| + _ = os.Symlink("real.json", a.path(AdmissionPath)) |
| + }, |
| + "symlinked marker": func(t *testing.T, a admissionRoot) { |
| + _ = os.Remove(a.path(AdmittedMarker)) |
| + _ = os.WriteFile(a.path("var/lib/elsewhere"), nil, 0o600) |
| + _ = os.Symlink("../elsewhere", a.path(AdmittedMarker)) |
| + }, |
| + "hard-linked record": func(t *testing.T, a admissionRoot) { |
| + _ = os.Link(a.path(AdmissionPath), a.path(RootAdmissionDir+"/copy")) |
| + }, |
| + "record mode 0644": func(t *testing.T, a admissionRoot) { _ = os.Chmod(a.path(AdmissionPath), 0o644) }, |
| + "marker mode 0666": func(t *testing.T, a admissionRoot) { _ = os.Chmod(a.path(AdmittedMarker), 0o666) }, |
| + "dir mode 0770": func(t *testing.T, a admissionRoot) { _ = os.Chmod(a.path(RootAdmissionDir), 0o770) }, |
| + "dir mode 0755": func(t *testing.T, a admissionRoot) { _ = os.Chmod(a.path(RootAdmissionDir), 0o755) }, |
| + "group-writable ancestor": func(t *testing.T, a admissionRoot) { |
| + _ = os.Chmod(a.path("var/lib"), 0o775) |
| + }, |
| + "symlinked dir": func(t *testing.T, a admissionRoot) { |
| + _ = os.Rename(a.path(RootAdmissionDir), a.path("var/lib/real")) |
| + _ = os.Symlink("real", a.path(RootAdmissionDir)) |
| + }, |
| + "marker without record": func(t *testing.T, a admissionRoot) { _ = os.Remove(a.path(AdmissionPath)) }, |
| + "tampered record": func(t *testing.T, a admissionRoot) { |
| + _ = os.WriteFile(a.path(AdmissionPath), bytes.Replace(a.wire, []byte(`"sig":"`), []byte(`"sig":"A`), 1), 0o600) |
| + }, |
| + "record is a directory": func(t *testing.T, a admissionRoot) { |
| + _ = os.Remove(a.path(AdmissionPath)) |
| + _ = os.Mkdir(a.path(AdmissionPath), 0o700) |
| + }, |
| + "dir missing": func(t *testing.T, a admissionRoot) { _ = os.RemoveAll(a.path(RootAdmissionDir)) }, |
| + "identity tampered": func(t *testing.T, a admissionRoot) { |
| + _ = os.Chmod(a.path("etc/carlos"), 0o775) |
| + }, |
| + } |
| + for name, mutate := range refusals { |
| + t.Run(name, func(t *testing.T) { |
| + a := newAdmissionRoot(t) |
| + if err := CommitAdmissionAs(a.root, a.wire, a.owner); err != nil { |
| + t.Fatal(err) |
| + } |
| + mutate(t, a) |
| + a.mustAdmitted(t, false, true) |
| + }) |
| + } |
| + t.Run("a file elsewhere claiming admission has no effect", func(t *testing.T) { |
| + a := newAdmissionRoot(t) |
| + for _, p := range []string{"var/lib/admitted", "etc/carlos/admitted", "var/lib/admission.json"} { |
| + if err := os.WriteFile(a.path(p), a.wire, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + a.mustAdmitted(t, false, false) |
| + }) |
| + t.Run("commit refuses a doubtful directory or record", func(t *testing.T) { |
| + a := newAdmissionRoot(t) |
| + _ = os.Chmod(a.path(RootAdmissionDir), 0o770) |
| + if err := CommitAdmissionAs(a.root, a.wire, a.owner); err == nil { |
| + t.Fatal("committed into a 0770 directory") |
| + } |
| + b := newAdmissionRoot(t) |
| + _ = os.WriteFile(b.path(AdmissionPath), []byte(`{}`), 0o600) |
| + if err := CommitAdmissionAs(b.root, b.wire, b.owner); err == nil { |
| + t.Fatal("committed over an unverified record") |
| + } |
| + if got, _ := os.ReadFile(b.path(AdmissionPath)); string(got) != `{}` { |
| + t.Fatal("an unverified record was replaced") |
| + } |
| + if _, err := os.Lstat(b.path(AdmittedMarker)); err == nil { |
| + t.Fatal("marker written over an unverified record") |
| + } |
| + }) |
| +} |
diff --git a/internal/managedboot/admission_other.go b/internal/managedboot/admission_other.go| new file mode 100644 |
| index 000000000..30a9b027c |
| --- /dev/null |
| +++ b/internal/managedboot/admission_other.go |
| @@ -0,0 +1,18 @@ |
| +//go:build !linux |
| + |
| +package managedboot |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "errors" |
| +) |
| + |
| +// Managed boxes are linux only; loadIdentity never reports one elsewhere, |
| +// so these are unreachable after admissionIdentity and RootAdmissionAs. |
| +func rootAdmitted(root string, owner RootOwner, id Identity, pub ed25519.PublicKey) (bool, error) { |
| + return false, errors.New("managedboot: root admission is linux only") |
| +} |
| + |
| +func commitAdmission(root string, wire []byte, owner RootOwner, id Identity, pub ed25519.PublicKey) error { |
| + return errors.New("managedboot: root admission is linux only") |
| +} |
diff --git a/internal/managedboot/ready.go b/internal/managedboot/ready.go| new file mode 100644 |
| index 000000000..4745b80b8 |
| --- /dev/null |
| +++ b/internal/managedboot/ready.go |
| @@ -0,0 +1,107 @@ |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "time" |
| +) |
| + |
| +// ReadyKind separates the ready record from every other payload the |
| +// console's release key signs (channel pointers, production flags, door |
| +// keys): strict decoding plus this kind refuses all of them. |
| +const ReadyKind = "managed-ready" |
| + |
| +// MaxReadyBytes bounds a signed ready object on every reader; the real |
| +// object is about 300 bytes. |
| +const MaxReadyBytes = 4096 |
| + |
| +// ReadyRecord is the console's signed statement that one box of one fleet, |
| +// launched by one operation, passed its readiness checks at ReadyAt. |
| +type ReadyRecord struct { |
| + Schema int `json:"schema"` |
| + Kind string `json:"kind"` |
| + Fleet string `json:"fleet"` |
| + Label string `json:"label"` |
| + Op string `json:"op"` |
| + ReadyAt time.Time `json:"ready_at"` |
| +} |
| + |
| +// readyWrapper is the release package's {payload, sig} wire convention: |
| +// the signature covers the exact base64 payload string. A scoped key's |
| +// wrapper carries a "grant" member, which the strict decode refuses. |
| +type readyWrapper struct { |
| + Payload string `json:"payload"` |
| + Sig string `json:"sig"` |
| +} |
| + |
| +var errReady = errors.New("managedboot: invalid ready record") |
| + |
| +func (r ReadyRecord) valid() bool { |
| + return r.Schema == 1 && r.Kind == ReadyKind && nameRE.MatchString(r.Fleet) && nameRE.MatchString(r.Label) && |
| + opRE.MatchString(r.Op) && !r.ReadyAt.IsZero() |
| +} |
| + |
| +// SignReady encodes r as the signed wrapper. Ed25519 and the JSON encoding |
| +// are deterministic, so one record always yields the same bytes: a |
| +// re-issued create-only PUT carries identical content. |
| +func SignReady(priv ed25519.PrivateKey, r ReadyRecord) ([]byte, error) { |
| + if len(priv) != ed25519.PrivateKeySize { |
| + return nil, errors.New("managedboot: no usable signing key for the ready record") |
| + } |
| + r.ReadyAt = r.ReadyAt.UTC() |
| + if !r.valid() { |
| + return nil, errReady |
| + } |
| + payload, err := json.Marshal(r) |
| + if err != nil { |
| + return nil, errReady |
| + } |
| + b64 := base64.StdEncoding.EncodeToString(payload) |
| + return json.Marshal(readyWrapper{Payload: b64, Sig: base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(b64)))}) |
| +} |
| + |
| +// VerifyReady checks wire against pub and the box's identity: a strict |
| +// {payload, sig} wrapper (no grant, no other member, no trailing value), a |
| +// signature by pub itself, then a strict payload of kind ReadyKind, schema |
| +// 1, naming want's fleet, label and operation, with a nonzero UTC ReadyAt. |
| +func VerifyReady(pub ed25519.PublicKey, wire []byte, want Identity) (ReadyRecord, error) { |
| + if len(pub) != ed25519.PublicKeySize || len(wire) > MaxReadyBytes { |
| + return ReadyRecord{}, errReady |
| + } |
| + var w readyWrapper |
| + if !strictDecode(wire, &w) { |
| + return ReadyRecord{}, errReady |
| + } |
| + sig, err := base64.StdEncoding.DecodeString(w.Sig) |
| + if err != nil || len(sig) != ed25519.SignatureSize || !ed25519.Verify(pub, []byte(w.Payload), sig) { |
| + return ReadyRecord{}, errors.New("managedboot: ready record signature does not verify") |
| + } |
| + payload, err := base64.StdEncoding.DecodeString(w.Payload) |
| + if err != nil { |
| + return ReadyRecord{}, errReady |
| + } |
| + var r ReadyRecord |
| + if !strictDecode(payload, &r) || !r.valid() || r.ReadyAt.Location() != time.UTC { |
| + return ReadyRecord{}, errReady |
| + } |
| + if r.Fleet != want.Fleet || r.Label != want.Label || r.Op != want.Op { |
| + return ReadyRecord{}, errors.New("managedboot: ready record names another box") |
| + } |
| + return r, nil |
| +} |
| + |
| +// strictDecode decodes exactly one JSON value with no unknown member and |
| +// nothing after it. |
| +func strictDecode(b []byte, v any) bool { |
| + dec := json.NewDecoder(bytes.NewReader(b)) |
| + dec.DisallowUnknownFields() |
| + if dec.Decode(v) != nil { |
| + return false |
| + } |
| + var extra any |
| + return dec.Decode(&extra) == io.EOF |
| +} |
diff --git a/internal/managedboot/ready_test.go b/internal/managedboot/ready_test.go| new file mode 100644 |
| index 000000000..d0ee925e7 |
| --- /dev/null |
| +++ b/internal/managedboot/ready_test.go |
| @@ -0,0 +1,90 @@ |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func readyFixture(t *testing.T) (ed25519.PrivateKey, Identity, ReadyRecord) { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(bytes.NewReader(bytes.Repeat([]byte{7}, 64))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id := Identity{Fleet: "shop", Label: "box-1", Op: "0123456789abcdef0123456789abcdef", ReleasePubkey: base64.StdEncoding.EncodeToString(pub)} |
| + rec := ReadyRecord{Schema: 1, Kind: ReadyKind, Fleet: id.Fleet, Label: id.Label, Op: id.Op, ReadyAt: time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)} |
| + return priv, id, rec |
| +} |
| + |
| +// signPayload wraps an arbitrary payload the way SignReady does, so the |
| +// refusals below are about the payload, not the signature. |
| +func signPayload(priv ed25519.PrivateKey, payload []byte, extra map[string]any) []byte { |
| + b64 := base64.StdEncoding.EncodeToString(payload) |
| + w := map[string]any{"payload": b64, "sig": base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(b64)))} |
| + for k, v := range extra { |
| + w[k] = v |
| + } |
| + out, _ := json.Marshal(w) |
| + return out |
| +} |
| + |
| +func TestManagedReadySignVerify(t *testing.T) { |
| + priv, id, rec := readyFixture(t) |
| + pub := priv.Public().(ed25519.PublicKey) |
| + wire, err := SignReady(priv, rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + again, _ := SignReady(priv, ReadyRecord{Schema: 1, Kind: ReadyKind, Fleet: id.Fleet, Label: id.Label, Op: id.Op, ReadyAt: rec.ReadyAt.In(time.FixedZone("x", 3600))}) |
| + if !bytes.Equal(wire, again) { |
| + t.Fatalf("signing is not deterministic:\n%s\n%s", wire, again) |
| + } |
| + got, err := VerifyReady(pub, wire, id) |
| + if err != nil || got != rec { |
| + t.Fatalf("valid record: %+v %v", got, err) |
| + } |
| + payload, _ := json.Marshal(rec) |
| + _, otherPriv, _ := ed25519.GenerateKey(bytes.NewReader(bytes.Repeat([]byte{9}, 64))) |
| + mutate := func(f func(*ReadyRecord)) []byte { |
| + r := rec |
| + f(&r) |
| + b, _ := json.Marshal(r) |
| + return signPayload(priv, b, nil) |
| + } |
| + refused := map[string][]byte{ |
| + "unsigned": []byte(`{"payload":"` + base64.StdEncoding.EncodeToString(payload) + `","sig":""}`), |
| + "wrong key": signPayload(otherPriv, payload, nil), |
| + "scoped grant": signPayload(priv, payload, map[string]any{"grant": map[string]string{"pub": "x", "sig": "y"}}), |
| + "trailing json": append(append([]byte(nil), wire...), []byte(` {}`)...), |
| + "plain record": payload, |
| + "other kind": mutate(func(r *ReadyRecord) { r.Kind = "channel-pointer" }), |
| + "schema 2": mutate(func(r *ReadyRecord) { r.Schema = 2 }), |
| + "other fleet": mutate(func(r *ReadyRecord) { r.Fleet = "other" }), |
| + "other label": mutate(func(r *ReadyRecord) { r.Label = "box-2" }), |
| + "other op": mutate(func(r *ReadyRecord) { r.Op = strings.Repeat("f", 32) }), |
| + "zero time": mutate(func(r *ReadyRecord) { r.ReadyAt = time.Time{} }), |
| + "non-utc time": signPayload(priv, bytes.Replace(payload, []byte(`Z"`), []byte(`+01:00"`), 1), nil), |
| + "unknown field": signPayload(priv, bytes.Replace(payload, []byte(`{`), []byte(`{"admitted":true,`), 1), nil), |
| + "pointer": signPayload(priv, []byte(`{"schema":1,"account":"a","app":"shop","channel":"stable","version":"v1"}`), nil), |
| + "oversize": signPayload(priv, append(bytes.TrimSuffix(payload, []byte("}")), []byte(`,"pad":"`+strings.Repeat("x", MaxReadyBytes)+`"}`)...), nil), |
| + } |
| + for name, w := range refused { |
| + if _, err := VerifyReady(pub, w, id); err == nil { |
| + t.Errorf("%s: verified", name) |
| + } |
| + } |
| + if _, err := VerifyReady(nil, wire, id); err == nil { |
| + t.Error("no key: verified") |
| + } |
| + if _, err := SignReady(nil, rec); err == nil { |
| + t.Error("nil key signed") |
| + } |
| + if _, err := SignReady(priv, ReadyRecord{Schema: 1, Kind: "other", Fleet: id.Fleet, Label: id.Label, Op: id.Op, ReadyAt: rec.ReadyAt}); err == nil { |
| + t.Error("other kind signed") |
| + } |
| +} |
diff --git a/internal/managedboot/roottest/roottest.go b/internal/managedboot/roottest/roottest.go| new file mode 100644 |
| index 000000000..d81ffbe8e |
| --- /dev/null |
| +++ b/internal/managedboot/roottest/roottest.go |
| @@ -0,0 +1,113 @@ |
| +//go:build linux |
| + |
| +// Package roottest lays out a fake managed box root, owned by the test's own |
| +// uid, for root admission tests. Only tests import it. |
| +package roottest |
| + |
| +import ( |
| + "bytes" |
| + "crypto/ed25519" |
| + "encoding/base64" |
| + "os" |
| + "path/filepath" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot" |
| +) |
| + |
| +// ManagedRoot is a fake managed box root owned by the test's own uid and |
| +// gid: the identity file and an empty root admission directory, laid out |
| +// with the modes the first boot's commit gives them. |
| +type ManagedRoot struct { |
| + Root string |
| + Owner managedboot.RootOwner |
| + ID managedboot.Identity |
| + Key ed25519.PrivateKey |
| + Ready managedboot.ReadyRecord |
| +} |
| + |
| +// NewManagedRoot lays out a fake root under a fresh temporary directory. |
| +func NewManagedRoot(t testing.TB) *ManagedRoot { |
| + t.Helper() |
| + return NewManagedRootIn(t, t.TempDir()) |
| +} |
| + |
| +// NewManagedRootIn lays out the fake root in dir, an existing empty |
| +// directory the caller owns and removes. |
| +func NewManagedRootIn(t testing.TB, dir string) *ManagedRoot { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(bytes.NewReader(bytes.Repeat([]byte{3}, 64))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m := &ManagedRoot{ |
| + Root: dir, |
| + Owner: managedboot.RootOwner{UID: os.Getuid(), GID: os.Getgid()}, |
| + ID: managedboot.Identity{Fleet: "shop", Label: "box-1", Op: "0123456789abcdef0123456789abcdef", ReleasePubkey: base64.StdEncoding.EncodeToString(pub)}, |
| + Key: priv, |
| + } |
| + m.Ready = managedboot.ReadyRecord{Schema: 1, Kind: managedboot.ReadyKind, Fleet: m.ID.Fleet, Label: m.ID.Label, Op: m.ID.Op, ReadyAt: time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC)} |
| + body, err := managedboot.EncodeIdentity(m.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, d := range []string{"etc", "etc/carlos", "var", "var/lib"} { |
| + m.mkdir(t, d, 0o755) |
| + } |
| + m.mkdir(t, managedboot.RootAdmissionDir, 0o700) |
| + // Files take the directory's group where it is setgid: expect that one. |
| + if st, err := os.Stat(m.Path(managedboot.RootAdmissionDir)); err == nil { |
| + if sys, ok := st.Sys().(*syscall.Stat_t); ok { |
| + m.Owner.GID = int(sys.Gid) |
| + } |
| + } |
| + m.write(t, managedboot.IdentityPath, body, 0o644) |
| + return m |
| +} |
| + |
| +// Path is p under the fake root. |
| +func (m *ManagedRoot) Path(p string) string { return filepath.Join(m.Root, p) } |
| + |
| +// Wire is the console's signed ready object for this box. |
| +func (m *ManagedRoot) Wire(t testing.TB) []byte { |
| + t.Helper() |
| + w, err := managedboot.SignReady(m.Key, m.Ready) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return w |
| +} |
| + |
| +// Commit runs root's admission against the fake root. |
| +func (m *ManagedRoot) Commit(wire []byte) error { |
| + return managedboot.CommitAdmissionAs(m.Root, wire, m.Owner) |
| +} |
| + |
| +// Admission is root's answer for the fake root. |
| +func (m *ManagedRoot) Admission() (managed, admitted bool, err error) { |
| + return managedboot.RootAdmissionAs(m.Root, m.Owner) |
| +} |
| + |
| +func (m *ManagedRoot) mkdir(t testing.TB, rel string, mode os.FileMode) { |
| + t.Helper() |
| + p := m.Path(rel) |
| + if err := os.Mkdir(p, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(p, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (m *ManagedRoot) write(t testing.TB, rel string, body []byte, mode os.FileMode) { |
| + t.Helper() |
| + p := m.Path(rel) |
| + if err := os.WriteFile(p, body, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(p, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index 45970398e..71214e022 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -60,6 +60,11 @@ type ReconcileConfig struct { |
| // its label: it admits only unlabelled records. Off a fleet it decides |
| // nothing. |
| FleetBox string |
| + // Joining is a managed box's live "root has not admitted me" (managed |
| + // fleets 2b-2). While it answers true this box owns no record of any |
| + // kind (ownsRecord) and Reconcile returns before it lists, mints or |
| + // removes anything. nil is never joining: every BYO box. |
| + Joining func() bool |
| // Pools are the pools this box serves. Empty means the shared "" pool |
| // only โ NOT "every pool" (poolServed below). |
| Pools []string |
| @@ -547,6 +552,9 @@ func (cfg ReconcileConfig) inScope(region, pool string, everywhere bool) bool { |
| // record this box no longer owns is never minted here and its row is |
| // removed, not kept on region alone (rule 9). |
| func (cfg ReconcileConfig) ownsRecord(rec Record) bool { |
| + if cfg.joining() { |
| + return false |
| + } |
| if rec.ReplicaAssignment != nil { |
| return rec.Region == cfg.Region && rec.ReplicaAssignment.Contains(cfg.FleetBox) |
| } |
| @@ -556,6 +564,9 @@ func (cfg ReconcileConfig) ownsRecord(rec Record) bool { |
| return rec.FleetBox == "" || rec.FleetBox == cfg.FleetBox |
| } |
| +// joining is cfg.Joining's answer; nil is never joining. |
| +func (cfg ReconcileConfig) joining() bool { return cfg.Joining != nil && cfg.Joining() } |
| + |
| // RouteFor is the one answer to "what route does this record describe". The |
| // mint path builds from it and the adoption match test (design ยง4.2) |
| // compares against it โ one function, so a shape the reconciler would mint |
| @@ -1421,6 +1432,9 @@ func scanInstanceRecords(ctx context.Context, st release.Store, cfg ReconcileCon |
| // never mass-retire a fleet. Minting is additive and always safe, so it |
| // proceeds regardless. |
| func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg ReconcileConfig) error { |
| + if cfg.joining() { |
| + return nil |
| + } |
| cfg.withdrawPools(ctx, s, reg, false) |
| cfg = withDemoClaimHolds(cfg) |
| if cfg.Now == nil { |
diff --git a/internal/provision/reconcile_joining_test.go b/internal/provision/reconcile_joining_test.go| new file mode 100644 |
| index 000000000..72c127cb8 |
| --- /dev/null |
| +++ b/internal/provision/reconcile_joining_test.go |
| @@ -0,0 +1,100 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +// joiningCountStore counts every read and list a pass makes. |
| +type joiningCountStore struct { |
| + release.Store |
| + gets, lists atomic.Int64 |
| +} |
| + |
| +func (s *joiningCountStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + s.gets.Add(1) |
| + return s.Store.Get(ctx, key) |
| +} |
| +func (s *joiningCountStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + s.lists.Add(1) |
| + return s.Store.List(ctx, prefix) |
| +} |
| +func (s *joiningCountStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + s.lists.Add(1) |
| + return s.Store.ListDirs(ctx, prefix) |
| +} |
| + |
| +// TestReconcileJoiningOwnsNothing: a joining managed box owns no record of |
| +// any shape, and its reconcile passes return before listing, minting or |
| +// removing; once admitted the same configuration behaves as on main. |
| +func TestReconcileJoiningOwnsNothing(t *testing.T) { |
| + joining := true |
| + cfg := ReconcileConfig{Region: "fleet/shop", FleetBox: "box-1", Pools: []string{"tito"}, DataDir: "/data", Joining: func() bool { return joining }} |
| + recs := map[string]Record{ |
| + "labelled own": {Region: "fleet/shop", FleetBox: "box-1"}, |
| + "unlabelled": {Region: "fleet/shop"}, |
| + "static": {Region: "fleet/shop", Kind: "static"}, |
| + "replica-assigned": {Region: "fleet/shop", ReplicaAssignment: &replicas.Assignment{Boxes: []string{"box-1"}}}, |
| + "service, own": {Region: "fleet/shop", FleetBox: "box-1", Kind: "service"}, |
| + } |
| + for name, rec := range recs { |
| + if cfg.ownsRecord(rec) { |
| + t.Errorf("joining: owns %s", name) |
| + } |
| + } |
| + joining = false |
| + for name, rec := range recs { |
| + if !cfg.ownsRecord(rec) { |
| + t.Errorf("admitted: does not own %s", name) |
| + } |
| + } |
| + if (ReconcileConfig{Region: "fleet/shop", FleetBox: "box-1"}).ownsRecord(Record{Region: "fleet/shop", FleetBox: "box-2"}) { |
| + t.Error("nil Joining changed the labelled-for-another-box answer") |
| + } |
| + |
| + ds, sqid := setup(t) |
| + rec := acmeRecord(sqid) |
| + rec.Region = "fleet/shop" |
| + if err := CreateRecord(ctx, ds, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A provisioned row that a normal pass would remove (no record behind it). |
| + stale := registry.Route{Host: "stale.go.tito.io", Slug: "stale", Kind: "instance", App: "tito", Account: sqid, Pool: "tito", Region: "fleet/shop", Channel: "stable", Provisioned: true, Status: "ready"} |
| + reg := regWith(t, stale) |
| + st := &joiningCountStore{Store: ds} |
| + joining = true |
| + if err := Reconcile(ctx, st, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := ReconcileSidecars(ctx, st, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st.gets.Load() != 0 || st.lists.Load() != 0 { |
| + t.Fatalf("joining passes read the store: %d gets, %d lists", st.gets.Load(), st.lists.Load()) |
| + } |
| + routes, _ := reg.List() |
| + if len(routes) != 1 || routes[0].Host != stale.Host { |
| + t.Fatalf("joining pass changed the registry: %+v", routes) |
| + } |
| + |
| + joining = false |
| + cfg.Now = func() time.Time { return time.Now() } |
| + if err := Reconcile(ctx, st, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st.lists.Load() == 0 { |
| + t.Fatal("admitted pass listed nothing") |
| + } |
| + if rt, _ := reg.Get(rec.Host); rt == nil { |
| + t.Fatal("admitted pass did not mint the record") |
| + } |
| + if rt, _ := reg.Get(stale.Host); rt != nil { |
| + t.Fatal("admitted pass kept the stale provisioned row") |
| + } |
| +} |
diff --git a/internal/provision/sidecar_reconcile.go b/internal/provision/sidecar_reconcile.go| index 30ad79b7a..a72f752f4 100644 |
| --- a/internal/provision/sidecar_reconcile.go |
| +++ b/internal/provision/sidecar_reconcile.go |
| @@ -193,6 +193,10 @@ func coSpawnStaged(dataDir, host string) bool { |
| // - the app's sidecars manifest is absent or unreadable (no argv to run, |
| // and no ceilings to stamp). |
| func ReconcileSidecars(ctx context.Context, s release.Store, reg *registry.Registry, cfg ReconcileConfig) error { |
| + // A joining managed box owns no sidecar either (ReconcileConfig.Joining). |
| + if cfg.joining() { |
| + return nil |
| + } |
| cfg.withdrawPools(ctx, s, reg, true) |
| if cfg.Now == nil { |
| cfg.Now = time.Now |