feat: managed box first contact with verified install
carlos system managed-boot, run as root by carlos-managed-boot.service on every boot of a managed box. The first boot waits for the metadata firewall, attests /data, trades its one-time token once (503/429 and transport errors retried until expiry, 403 terminal, a refused 200 never re-traded), stages host.env, credentials and the identity in a root-only directory committed by one rename, scrubs every copy of the token, installs the admission and control drop-ins before any workload unit exists, installs the signed stable release through the store door, re-hashes it before its first exec, runs bootstrap, writes the complete marker and queues `start --no-block carlos-edge.service`. Later boots take the complete path: no network, no digest check, drop-ins re-asserted. A boot cut off part way resumes without repeating a completed network step. managedboot gains the enrol wire types, the root-owned identity, the managed host.env, the workload/maintenance unit classification and the admission drop-ins, and a scrubbed form of the boot input. Census: root-read overlay managed-fleets-2b2 and a record-write entry for ManagedHostEnv's hibernate prefix literal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
20 files changed,
+3,236
−1
docs/superpowers/notes/census-proposal-managed-fleets-2b2.md+46 −0internal/console/managedenrolwire_test.go+72 −0internal/host/managedboot.go+624 −0internal/host/managedboot_linux.go+444 −0internal/host/managedboot_linux_test.go+1,192 −0internal/host/managedboot_other.go+30 −0internal/host/managedstable.go+72 −0internal/managedboot/bootinput.go+60 −0internal/managedboot/enrolwire.go+70 −0internal/managedboot/hostenv.go+66 −0internal/managedboot/identity.go+89 −0internal/managedboot/identity_linux.go+68 −0internal/managedboot/identity_linux_test.go+154 −0internal/managedboot/identity_other.go+8 −0internal/managedboot/units.go+175 −0internal/provision/managed_fleets_2b2_census_test.go+7 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv+52 −0system.go+5 −1system_test.go+1 −0
diff --git a/docs/superpowers/notes/census-proposal-managed-fleets-2b2.md b/docs/superpowers/notes/census-proposal-managed-fleets-2b2.md| new file mode 100644 |
| index 000000000..8587f63b9 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-managed-fleets-2b2.md |
| @@ -0,0 +1,46 @@ |
| +# Census approval: managed-fleets-2b2 |
| + |
| +Ruling `census-ruling-managed-fleets-2b2`. The independent reviewer approves or rejects every change below, 22 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `system.go` `runSystem` | body | unchanged (0) | adds the managed-boot case, routed to host.RunSystemManagedBoot (root oneshot behind carlos-managed-boot.service on a managed box); no read of its own; every other branch unchanged | |
| +| `system.go` `systemVerb` | body | unchanged (0) | recognizes managed-boot as a system verb; parsing only, no read added | |
| + |
| +Envelopes re-pinned: `.`, `internal/host`, `internal/managedboot`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `system.go` `runSystem`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added;rev3=census-ruling-nearest-region-a;basis=adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops the "join" case (host.RunSystemJoin, deleted with internal/host/joinroot.go, its only caller) and its line in the usage text; every other branch unchanged; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the system verb dispatch gains named-units, routed to host.RunSystemNamedUnits; no read of its own;rev3=census-ruling-design-pdf-service;basis=add dispatch for carlos system pdf; no new reads;rev3=census-ruling-managed-fleets-2a;basis=Adds managed-fleets operator CLI dispatch; no direct read added; existing root command branches unchanged.;rev3=census-ruling-agent-start-demo-2;basis=system.go:62-66 adds the demos family dispatch to the console-only operator client (system_demos.go:19, system_demos_api.go:23); no direct read added and other root commands are unchanged.;rev3=census-ruling-region-ha-p3b2;basis=Dispatches carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback} to internal/host; no read of its own. |
| +- `system.go` `systemVerb`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added;rev3=census-ruling-nearest-region-a;basis=adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops "join" from the verb list, so `carlos system join` now falls to the unknown-verb message; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the known-verb list gains named-units; no read of its own;rev3=census-ruling-design-pdf-service;basis=add recognition for carlos system pdf; no new reads;rev3=census-ruling-managed-fleets-2a;basis=Recognizes managed-fleets as a CLI family; no read added.;rev3=census-ruling-agent-start-demo-2;basis=system.go:43-57 recognizes demos; parsing only, no direct read added.;rev3=census-ruling-region-ha-p3b2;basis=Recognizes group-maintenance as a system verb; parsing only. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/host/managedboot.go:const#1`: reads +data-literal; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot.go:managedBoot.attest`: reads +file:Lstat, +file:ReadDir; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot.go:managedBoot.clearStaging`: reads +file:ReadDir; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot.go:managedBoot.post`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot.go:managedBoot.present`: reads +file:Lstat; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot.go:managedBoot.scrub`: reads +file:WalkDir; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot.go:managedBoot.stage`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot.go:mbHolds`: reads +file:Lstat, +file:ReadFile; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:managedBoot.readInput`: reads +file:Lstat; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbBreadcrumb`: reads +file:OpenFile; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbCopyDurable`: reads +file:Fstat, +file:OpenFile ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbHashExec`: reads +file:Fstat, +file:Open; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbReadRootFile`: reads +file:Fstat, +file:Openat, +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbRemoveTree`: reads +file:ReadDir; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbRun`: reads +file:CommandContext; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbShred`: reads +file:Fstat, +file:Open; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbSyncDir`: reads +file:Open; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbWalk`: reads +file:Fstat, +file:Open, +file:Openat ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/host/managedboot_linux.go:mbWriteRootFile`: reads +file:Openat, +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/managedboot/cloudinit_v1.sh.tmpl:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| +- new `internal/managedboot/identity_linux.go:loadIdentity`: reads +file:Fstat, +file:Open, +file:Openat, +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/managedboot/units.go:ensureDropIn`: reads +file:Lstat ×2, +file:Open, +file:OpenFile, +file:Read, +file:ReadFile; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `d467adec3d86ae220afe98269aa226e87adba1b83e31eda214ceea0f02720a98` → `7bbffc3b2a59f79f6aefdd6a0a344976f51f36eda4b6a7499c5027f6a712dbe2`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/console/managedenrolwire_test.go b/internal/console/managedenrolwire_test.go| new file mode 100644 |
| index 000000000..aaada291e |
| --- /dev/null |
| +++ b/internal/console/managedenrolwire_test.go |
| @@ -0,0 +1,72 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/fleetstore" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| +) |
| + |
| +// TestManagedEnrolWireMatchesConsole pins the box's wire types to the |
| +// console's: every field of each side survives a round trip through the |
| +// other, byte for byte, with unknown fields refused. |
| +func TestManagedEnrolWireMatchesConsole(t *testing.T) { |
| + strict := func(raw []byte, v any) { |
| + t.Helper() |
| + dec := json.NewDecoder(bytes.NewReader(raw)) |
| + dec.DisallowUnknownFields() |
| + if err := dec.Decode(v); err != nil { |
| + t.Fatalf("%s: %v", raw, err) |
| + } |
| + } |
| + reply := managedEnrolReply{Fleet: "shop", Label: "box-1", TunnelURL: "https://tunnel.example.com", TunnelToken: "token", |
| + Credentials: fleetstore.Credentials{ID: "AKIAEXAMPLE", Secret: []byte("secret")}, Joining: true, |
| + Bucket: "bucket", BucketRegion: "eu-west-1", Operation: "op"} |
| + consoleRaw, err := json.Marshal(reply) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var box managedboot.EnrolReply |
| + strict(consoleRaw, &box) |
| + boxRaw, err := json.Marshal(box) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.Equal(consoleRaw, boxRaw) { |
| + t.Errorf("reply:\nconsole %s\nbox %s", consoleRaw, boxRaw) |
| + } |
| + var back managedEnrolReply |
| + strict(boxRaw, &back) |
| + if back.Fleet != reply.Fleet || back.Label != reply.Label || back.TunnelURL != reply.TunnelURL || back.TunnelToken != reply.TunnelToken || |
| + back.Credentials.ID != reply.Credentials.ID || !bytes.Equal(back.Credentials.Secret, reply.Credentials.Secret) || back.Joining != reply.Joining || |
| + back.Bucket != reply.Bucket || back.BucketRegion != reply.BucketRegion || back.Operation != reply.Operation { |
| + t.Errorf("reply round trip: %+v", back) |
| + } |
| + |
| + req := managedboot.EnrolRequest{Token: "t", DataDirEmpty: true, DataDirEntries: 3} |
| + boxReq, err := json.Marshal(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var consoleReq managedEnrolRequest |
| + strict(boxReq, &consoleReq) |
| + again, err := json.Marshal(consoleReq) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.Equal(boxReq, again) || consoleReq.Token != "t" || !consoleReq.DataDirEmpty || consoleReq.DataDirEntries != 3 { |
| + t.Errorf("request:\nbox %s\nconsole %s", boxReq, again) |
| + } |
| + // The handler's own wire reads both fields as present. |
| + var wire struct { |
| + Token string `json:"token"` |
| + Empty *bool `json:"data_dir_empty"` |
| + Entries *int `json:"data_dir_entries"` |
| + } |
| + strict(boxReq, &wire) |
| + if wire.Empty == nil || wire.Entries == nil { |
| + t.Error("the box's request omits a field the enrol handler requires") |
| + } |
| +} |
diff --git a/internal/host/managedboot.go b/internal/host/managedboot.go| new file mode 100644 |
| index 000000000..957241d53 |
| --- /dev/null |
| +++ b/internal/host/managedboot.go |
| @@ -0,0 +1,624 @@ |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "io/fs" |
| + "math/big" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +// carlos system managed-boot: a console-launched managed box's first |
| +// contact, run as root by carlos-managed-boot.service on every boot. |
| +// |
| +// The first boot gates on the metadata firewall, attests /data, trades its |
| +// one-time token once, stages host.env, credentials and the identity in a |
| +// root-only directory and commits them with one rename, scrubs the token, |
| +// installs the admission drop-ins, installs the signed stable release, |
| +// runs its bootstrap, marks the boot complete and queues the first |
| +// carlos-edge start. Each later boot finds the complete marker and only |
| +// re-asserts the drop-ins and queues the edge: no network, and no check of |
| +// /opt/carlos/carlos, whose integrity belongs to the update path from then |
| +// on. A boot cut off part way resumes after its last durable step and never |
| +// repeats a completed network step; one cut off before the commit has no |
| +// token left to trade and ends at enrol_failed. |
| + |
| +const ( |
| + mbStagingPrefix = "staging." |
| + mbCommittedDir = managedboot.BootDir + "/committed" |
| + mbCompleteMarker = managedboot.BootDir + "/complete" |
| + mbStableRecord = managedboot.BootDir + "/stable.json" |
| + mbStablePart = managedboot.BootDir + "/stable.part" |
| + mbSystemdDir = "/etc/systemd/system" |
| + mbEnrolDropIn = mbSystemdDir + "/carlos-managed-boot.service.d/10-enrol.conf" |
| + mbEdgeUnit = "carlos-edge.service" |
| + mbStableBinary = "/opt/carlos/carlos" |
| + mbEtcCarlos = "/etc/carlos" |
| + mbDataDir = "/data" |
| + mbNft = "/usr/sbin/nft" |
| + mbIMDSTable = "carlos_managed_imds" |
| + mbIMDSWait = 60 * time.Second |
| + mbReplyLimit = 64 << 10 |
| + mbScanLimit = 16 << 20 |
| + mbFileLimit = 64 << 10 |
| + mbRequestTimeout = 60 * time.Second |
| +) |
| + |
| +// mbCleanEnv is the whole environment of every child managed-boot runs. |
| +var mbCleanEnv = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/root"} |
| + |
| +// mbCommitted is what the commit holds and where each file is installed. |
| +var mbCommitted = []struct { |
| + name, final string |
| + mode os.FileMode |
| + service bool // group carlos |
| +}{ |
| + {"host.env", managedboot.HostEnvPath, 0o600, false}, |
| + {"credentials", managedboot.CredentialsPath, 0o640, true}, |
| + {"managed-box.json", managedboot.IdentityPath, 0o644, false}, |
| +} |
| + |
| +// mbScrubTrees are where cloud-init keeps copies of the user data, and so |
| +// of the token: each regular file in them that holds it is shredded. |
| +var mbScrubTrees = []string{"/var/lib/cloud", "/run/cloud-init", "/var/log/cloud-init.log", "/var/log/cloud-init-output.log", managedboot.BootDir} |
| + |
| +// errManagedBootHalted is what a test's crash hook returns: the boot stops |
| +// there with no breadcrumb, as a power loss would. |
| +var errManagedBootHalted = errors.New("managed boot: halted") |
| + |
| +type managedBoot struct { |
| + root string |
| + http *http.Client |
| + now func() time.Time |
| + sleep func(ctx context.Context, d time.Duration) error |
| + jitter func() time.Duration |
| + run func(ctx context.Context, argv []string, env []string) error |
| + systemctl func(ctx context.Context, args ...string) error |
| + breadcrumb func(code string) |
| + logf func(format string, args ...any) |
| + // openStore opens the store door from the committed host.env. |
| + openStore func(env map[string]string) (release.Store, error) |
| + // uid and gid own every root file (0:0 on a box); serviceGID is |
| + // carlos's group, which may read the credentials. |
| + uid, gid, serviceGID int |
| + // fleetKey establishes the fleet secrets key (Task 4); nil skips it. |
| + // It never fails the boot. |
| + fleetKey func(ctx context.Context, env map[string]string) |
| + // crash and beforeExec are test seams. |
| + crash func(step string) error |
| + beforeExec func() |
| +} |
| + |
| +// p is abs under the boot's root. |
| +func (m *managedBoot) p(abs string) string { return filepath.Join(m.root, abs) } |
| + |
| +func (m *managedBoot) step(name string) error { |
| + if m.crash != nil { |
| + return m.crash(name) |
| + } |
| + return nil |
| +} |
| + |
| +// Run is one boot of the state machine. A failure emits one breadcrumb, |
| +// enrol_failed for the trade and bootstrap_failed for everything else. |
| +func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) (err error) { |
| + code := managedboot.CodeBootstrapFailed |
| + defer func() { |
| + if err != nil && !errors.Is(err, errManagedBootHalted) { |
| + m.breadcrumb(code) |
| + } |
| + }() |
| + if err = m.waitFirewall(ctx); err != nil { |
| + return err |
| + } |
| + complete, err := m.present(mbCompleteMarker) |
| + if err != nil { |
| + return err |
| + } |
| + if complete { |
| + return m.completePath(ctx) |
| + } |
| + if err = m.clearStaging(); err != nil { |
| + return err |
| + } |
| + committed, err := m.present(mbCommittedDir) |
| + if err != nil { |
| + return err |
| + } |
| + if !committed { |
| + if in.Token == "" { |
| + code = managedboot.CodeEnrolFailed |
| + return errors.New("managed boot: no committed enrolment and no token to trade") |
| + } |
| + if err = m.step("trade"); err != nil { |
| + return err |
| + } |
| + reply, err := m.trade(ctx, in) |
| + if err != nil { |
| + code = managedboot.CodeEnrolFailed |
| + return err |
| + } |
| + if err = m.stage(in, reply); err != nil { |
| + if errors.Is(err, errManagedBootHalted) { |
| + return err |
| + } |
| + code = managedboot.CodeEnrolFailed |
| + return err |
| + } |
| + if err = m.step("committed"); err != nil { |
| + return err |
| + } |
| + } |
| + env, err := m.installCommitted(in) |
| + if err != nil { |
| + return err |
| + } |
| + if err = m.scrub(in); err != nil { |
| + return err |
| + } |
| + if err = m.step("scrubbed"); err != nil { |
| + return err |
| + } |
| + if m.fleetKey != nil { |
| + m.fleetKey(ctx, env) |
| + } |
| + if err = m.step("key"); err != nil { |
| + return err |
| + } |
| + // Before any workload unit file exists: bootstrap writes them. |
| + if _, err = managedboot.InstallAdmissionDropIns(m.p(mbSystemdDir), nil); err != nil { |
| + return err |
| + } |
| + if _, err = managedboot.InstallControlDropIn(m.p(mbSystemdDir)); err != nil { |
| + return err |
| + } |
| + if err = m.systemctl(ctx, "daemon-reload"); err != nil { |
| + return err |
| + } |
| + sha, err := m.stable(ctx, in, env) |
| + if err != nil { |
| + return err |
| + } |
| + m.breadcrumb(managedboot.CodeStableVerified) |
| + if err = m.step("stable"); err != nil { |
| + return err |
| + } |
| + if m.beforeExec != nil { |
| + m.beforeExec() |
| + } |
| + // Re-hashed immediately before its first execution. |
| + if got, err := mbHashExec(m.p(mbStableBinary), m.uid, m.gid); err != nil || got != sha { |
| + return errors.Join(errors.New("managed boot: the installed release does not match its signed digest"), err) |
| + } |
| + if err = m.run(ctx, []string{m.p(mbStableBinary), "bootstrap"}, mbCleanEnv); err != nil { |
| + return fmt.Errorf("managed boot: bootstrap: %w", err) |
| + } |
| + if err = m.step("bootstrapped"); err != nil { |
| + return err |
| + } |
| + if err = mbWriteRootFile(m.root, mbCompleteMarker, []byte("complete\n"), 0o600, m.uid, -1); err != nil { |
| + return err |
| + } |
| + if err = m.step("complete"); err != nil { |
| + return err |
| + } |
| + if _, err = m.finish(ctx, false); err != nil { |
| + return err |
| + } |
| + m.breadcrumb(managedboot.CodeJoining) |
| + return nil |
| +} |
| + |
| +// completePath is every boot after the first: no network, no digest. |
| +func (m *managedBoot) completePath(ctx context.Context) error { |
| + a, err := managedboot.InstallAdmissionDropIns(m.p(mbSystemdDir), nil) |
| + if err != nil { |
| + return err |
| + } |
| + c, err := managedboot.InstallControlDropIn(m.p(mbSystemdDir)) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = m.finish(ctx, a || c) |
| + return err |
| +} |
| + |
| +// finish removes the enrolment drop-in (the box no longer waits for the |
| +// network to trade), reloads systemd if anything changed, and queues the |
| +// edge. A blocking start would wait on this very unit. |
| +func (m *managedBoot) finish(ctx context.Context, changed bool) (bool, error) { |
| + removed, err := m.removeEnrolDropIn() |
| + if err != nil { |
| + return false, err |
| + } |
| + if changed || removed { |
| + if err = m.systemctl(ctx, "daemon-reload"); err != nil { |
| + return false, err |
| + } |
| + } |
| + return removed, m.systemctl(ctx, "start", "--no-block", mbEdgeUnit) |
| +} |
| + |
| +func (m *managedBoot) removeEnrolDropIn() (bool, error) { |
| + err := os.Remove(m.p(mbEnrolDropIn)) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + return true, mbSyncDir(filepath.Dir(m.p(mbEnrolDropIn))) |
| +} |
| + |
| +// waitFirewall waits up to a minute for the metadata table; systemd's |
| +// ordering normally means it is already there. Without it nothing reaches |
| +// the network. |
| +func (m *managedBoot) waitFirewall(ctx context.Context) error { |
| + deadline := m.now().Add(mbIMDSWait) |
| + for { |
| + if m.run(ctx, []string{mbNft, "list", "table", "inet", mbIMDSTable}, mbCleanEnv) == nil { |
| + return nil |
| + } |
| + if !m.now().Before(deadline) { |
| + return errors.New("managed boot: the metadata firewall is not in place") |
| + } |
| + if err := m.sleep(ctx, time.Second); err != nil { |
| + return err |
| + } |
| + } |
| +} |
| + |
| +func (m *managedBoot) present(abs string) (bool, error) { |
| + _, err := os.Lstat(m.p(abs)) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return false, nil |
| + } |
| + return err == nil, err |
| +} |
| + |
| +// clearStaging shreds what a boot cut off mid-staging left behind. |
| +func (m *managedBoot) clearStaging() error { |
| + entries, err := os.ReadDir(m.p(managedboot.BootDir)) |
| + if err != nil { |
| + return err |
| + } |
| + for _, e := range entries { |
| + if strings.HasPrefix(e.Name(), mbStagingPrefix) { |
| + if err := mbRemoveTree(m.root, managedboot.BootDir+"/"+e.Name(), m.uid); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// attest reports what /data holds before anything writes under it: absent |
| +// or an empty real directory is empty; a symlink or any other file type is |
| +// not. |
| +func (m *managedBoot) attest() (bool, int) { |
| + st, err := os.Lstat(m.p(mbDataDir)) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return true, 0 |
| + } |
| + if err != nil || !st.IsDir() { |
| + return false, 1 |
| + } |
| + entries, err := os.ReadDir(m.p(mbDataDir)) |
| + if err != nil { |
| + return false, 1 |
| + } |
| + return len(entries) == 0, len(entries) |
| +} |
| + |
| +// trade sends the one enrolment request, retrying only what the console |
| +// says left the token unused (503, 429) and what never reached it |
| +// (transport errors, gateway failures), never past the token's expiry. A |
| +// 200 is consumed once: a reply that fails its checks is terminal. |
| +func (m *managedBoot) trade(ctx context.Context, in managedboot.LaunchInput) (managedboot.EnrolReply, error) { |
| + empty, entries := m.attest() |
| + body, err := json.Marshal(managedboot.EnrolRequest{Token: in.Token, DataDirEmpty: empty, DataDirEntries: entries}) |
| + if err != nil { |
| + return managedboot.EnrolReply{}, err |
| + } |
| + url := in.Frozen.ConsoleOrigin + managedboot.EnrolPath |
| + pending := false |
| + for { |
| + now := m.now() |
| + if !now.Before(in.Expires) { |
| + return managedboot.EnrolReply{}, errors.New("managed boot: the enrolment token expired before the trade") |
| + } |
| + status, header, raw, err := m.post(ctx, url, body) |
| + var wait time.Duration |
| + switch { |
| + case err != nil: |
| + wait = m.jitter() |
| + case status == http.StatusOK: |
| + var reply managedboot.EnrolReply |
| + if json.Unmarshal(raw, &reply) != nil { |
| + return managedboot.EnrolReply{}, errors.New("managed boot: the enrolment reply is not readable") |
| + } |
| + if err := managedboot.CheckReply(in, reply); err != nil { |
| + return managedboot.EnrolReply{}, err |
| + } |
| + return reply, nil |
| + case status == http.StatusServiceUnavailable: |
| + wait = retryAfter(header, 5*time.Second) |
| + case status == http.StatusTooManyRequests: |
| + wait = retryAfter(header, 60*time.Second) |
| + case status == http.StatusInternalServerError || status == http.StatusBadGateway || status == http.StatusGatewayTimeout: |
| + wait = m.jitter() |
| + default: |
| + return managedboot.EnrolReply{}, fmt.Errorf("managed boot: the console refused the enrolment (%d)", status) |
| + } |
| + if !pending { |
| + m.breadcrumb(managedboot.CodeEnrolPending) |
| + pending = true |
| + } |
| + if left := in.Expires.Sub(m.now()); wait > left { |
| + wait = left |
| + } |
| + if err := m.sleep(ctx, wait); err != nil { |
| + return managedboot.EnrolReply{}, err |
| + } |
| + } |
| +} |
| + |
| +func (m *managedBoot) post(ctx context.Context, url string, body []byte) (int, http.Header, []byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, mbRequestTimeout) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) |
| + if err != nil { |
| + return 0, nil, nil, err |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := m.http.Do(req) |
| + if err != nil { |
| + // The URL is the frozen origin; the token is only in the body. |
| + return 0, nil, nil, errors.New("managed boot: enrolment request failed") |
| + } |
| + defer resp.Body.Close() |
| + raw, err := io.ReadAll(io.LimitReader(resp.Body, mbReplyLimit+1)) |
| + if err != nil || len(raw) > mbReplyLimit { |
| + return 0, nil, nil, errors.New("managed boot: enrolment reply failed") |
| + } |
| + return resp.StatusCode, resp.Header, raw, nil |
| +} |
| + |
| +// retryAfter is the header's whole seconds, else def, bounded to 1-300 s. |
| +func retryAfter(h http.Header, def time.Duration) time.Duration { |
| + n, err := strconv.Atoi(strings.TrimSpace(h.Get("Retry-After"))) |
| + if err != nil || n < 1 { |
| + return def |
| + } |
| + return time.Duration(min(n, 300)) * time.Second |
| +} |
| + |
| +// mbJitter is 1-30 s. |
| +func mbJitter() time.Duration { |
| + n, err := rand.Int(rand.Reader, big.NewInt(30)) |
| + if err != nil { |
| + return 15 * time.Second |
| + } |
| + return time.Duration(n.Int64()+1) * time.Second |
| +} |
| + |
| +// stage writes the trade's files into a fresh root-only directory, syncs |
| +// each and the directory, then commits them with one rename. |
| +func (m *managedBoot) stage(in managedboot.LaunchInput, reply managedboot.EnrolReply) error { |
| + id := managedboot.IdentityOf(in) |
| + env, err := managedboot.ManagedHostEnv(id, reply, in.Frozen, "") |
| + if err != nil { |
| + return err |
| + } |
| + hostEnv, err := hostenv.Render(env) |
| + if err != nil { |
| + return errors.New("managed boot: host.env does not render") |
| + } |
| + creds, err := managedboot.RenderCredentials(reply.Credentials) |
| + if err != nil { |
| + return err |
| + } |
| + if parsed, err := rootaws.ParseStaticCredentials(creds); err != nil || parsed.AccessKeyID != reply.Credentials.ID || parsed.SecretAccessKey != string(reply.Credentials.Secret) { |
| + return errors.New("managed boot: the credentials do not render") |
| + } |
| + identity, err := managedboot.EncodeIdentity(id) |
| + if err != nil { |
| + return err |
| + } |
| + if err = mbEnsureDir(m.root, mbEtcCarlos, 0o755, m.uid); err != nil { |
| + return err |
| + } |
| + var suffix [8]byte |
| + if _, err = rand.Read(suffix[:]); err != nil { |
| + return err |
| + } |
| + staging := managedboot.BootDir + "/" + mbStagingPrefix + hex.EncodeToString(suffix[:]) |
| + if err = mbEnsureDir(m.root, staging, 0o700, m.uid); err != nil { |
| + return err |
| + } |
| + bodies := map[string][]byte{"host.env": hostEnv, "credentials": creds, "managed-box.json": identity} |
| + for n, f := range mbCommitted { |
| + group := -1 |
| + if f.service { |
| + group = m.serviceGID |
| + } |
| + if err = mbWriteRootFile(m.root, staging+"/"+f.name, bodies[f.name], f.mode, m.uid, group); err != nil { |
| + return err |
| + } |
| + if n == 0 { |
| + if err = m.step("staging-partial"); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + if err = mbSyncDir(m.p(staging)); err != nil { |
| + return err |
| + } |
| + if err = os.Rename(m.p(staging), m.p(mbCommittedDir)); err != nil { |
| + return err |
| + } |
| + return mbSyncDir(m.p(managedboot.BootDir)) |
| +} |
| + |
| +// installCommitted moves each committed file to its final path (a later |
| +// boot finds the ones already moved there), checks all three, and creates |
| +// root's admission directory. It returns the host.env values. |
| +func (m *managedBoot) installCommitted(in managedboot.LaunchInput) (map[string]string, error) { |
| + if err := mbEnsureDir(m.root, mbEtcCarlos, 0o755, m.uid); err != nil { |
| + return nil, err |
| + } |
| + bodies := map[string][]byte{} |
| + for _, f := range mbCommitted { |
| + src := mbCommittedDir + "/" + f.name |
| + if ok, err := m.present(src); err != nil { |
| + return nil, err |
| + } else if ok { |
| + if err = mbMove(m.root, src, f.final); err != nil { |
| + return nil, err |
| + } |
| + } |
| + body, err := mbReadRootFile(m.root, f.final, m.uid, mbFileLimit, f.mode) |
| + if err != nil { |
| + return nil, err |
| + } |
| + bodies[f.name] = body |
| + } |
| + id, err := managedboot.ParseIdentity(bodies["managed-box.json"]) |
| + if err != nil || id != managedboot.IdentityOf(in) { |
| + return nil, errors.New("managed boot: the installed identity is not this box's") |
| + } |
| + if _, err = rootaws.ParseStaticCredentials(bodies["credentials"]); err != nil { |
| + return nil, errors.New("managed boot: the installed credentials are not readable") |
| + } |
| + env, err := hostenv.Parse(bodies["host.env"]) |
| + if err != nil { |
| + return nil, errors.New("managed boot: the installed host.env is not readable") |
| + } |
| + if env["CARLOS_FLEET"] != in.Fleet || env["CARLOS_FLEET_BOX"] != in.Label || env["CARLOS_RELEASE_PUBKEY"] != in.Frozen.ReleasePubkey { |
| + return nil, errors.New("managed boot: the installed host.env is not this box's") |
| + } |
| + if err = mbEnsureDir(m.root, managedboot.RootAdmissionDir, 0o700, m.uid); err != nil { |
| + return nil, err |
| + } |
| + return env, nil |
| +} |
| + |
| +// scrub shreds every copy of the token cloud-init and the seed left on |
| +// disk, removes the seed request and rewrites the boot input without the |
| +// token, last: a scrubbed boot input means the scrub is done. |
| +func (m *managedBoot) scrub(in managedboot.LaunchInput) error { |
| + if in.Token == "" { |
| + return nil |
| + } |
| + token := []byte(in.Token) |
| + for _, tree := range mbScrubTrees { |
| + err := filepath.WalkDir(m.p(tree), func(path string, d fs.DirEntry, err error) error { |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if !d.Type().IsRegular() || path == m.p(managedboot.BootInputPath) { |
| + return nil |
| + } |
| + holds, err := mbHolds(path, token) |
| + if err != nil || !holds { |
| + return err |
| + } |
| + return mbShred(path) |
| + }) |
| + if err != nil { |
| + return fmt.Errorf("managed boot: scrub %s: %w", tree, err) |
| + } |
| + } |
| + if ok, err := m.present(managedboot.SeedRequestPath); err != nil { |
| + return err |
| + } else if ok { |
| + if err = mbShred(m.p(managedboot.SeedRequestPath)); err != nil { |
| + return err |
| + } |
| + } |
| + scrubbed, err := managedboot.EncodeScrubbedBootInput(in) |
| + if err != nil { |
| + return err |
| + } |
| + return mbWriteRootFile(m.root, managedboot.BootInputPath, scrubbed, 0o600, m.uid, -1) |
| +} |
| + |
| +// mbHolds reports whether a regular file of at most mbScanLimit bytes |
| +// holds needle. Larger files (the seed) cannot be a copy of the user data. |
| +func mbHolds(path string, needle []byte) (bool, error) { |
| + st, err := os.Lstat(path) |
| + if err != nil || !st.Mode().IsRegular() || st.Size() > mbScanLimit { |
| + return false, err |
| + } |
| + body, err := os.ReadFile(path) |
| + if err != nil { |
| + return false, err |
| + } |
| + return bytes.Contains(body, needle), nil |
| +} |
| + |
| +// mbStable is the record of the release this boot installed. |
| +type mbStable struct { |
| + Version string `json:"version"` |
| + SHA256 string `json:"sha256"` |
| +} |
| + |
| +// stable installs the signed stable release once; a resumed boot whose |
| +// record still matches the installed binary makes no store call. |
| +func (m *managedBoot) stable(ctx context.Context, in managedboot.LaunchInput, env map[string]string) (string, error) { |
| + if raw, err := mbReadRootFile(m.root, mbStableRecord, m.uid, mbFileLimit, 0o600); err == nil { |
| + var rec mbStable |
| + if json.Unmarshal(raw, &rec) == nil && rec.SHA256 != "" { |
| + if got, err := mbHashExec(m.p(mbStableBinary), m.uid, m.gid); err == nil && got == rec.SHA256 { |
| + return rec.SHA256, nil |
| + } |
| + } |
| + } |
| + pub, err := base64.StdEncoding.DecodeString(in.Frozen.ReleasePubkey) |
| + if err != nil || len(pub) != ed25519.PublicKeySize { |
| + return "", errors.New("managed boot: the frozen release key is not a key") |
| + } |
| + s, err := m.openStore(env) |
| + if err != nil { |
| + return "", err |
| + } |
| + version, sha, err := installManagedStableAs(ctx, s, ed25519.PublicKey(pub), m.root, m.uid, m.gid) |
| + if err != nil { |
| + return "", err |
| + } |
| + rec, err := json.Marshal(mbStable{Version: version, SHA256: sha}) |
| + if err != nil { |
| + return "", err |
| + } |
| + if err = mbWriteRootFile(m.root, mbStableRecord, rec, 0o600, m.uid, -1); err != nil { |
| + return "", err |
| + } |
| + return sha, nil |
| +} |
| + |
| +// mbDoorStore opens the store door with the committed host.env's tunnel. |
| +func mbDoorStore(env map[string]string) (release.Store, error) { |
| + getenv := func(k string) string { return env[k] } |
| + return openFleetDoorStore(getenv, FleetIdentity{Fleet: env["CARLOS_FLEET"], Label: env["CARLOS_FLEET_BOX"]}) |
| +} |
diff --git a/internal/host/managedboot_linux.go b/internal/host/managedboot_linux.go| new file mode 100644 |
| index 000000000..3c2ca7c3f |
| --- /dev/null |
| +++ b/internal/host/managedboot_linux.go |
| @@ -0,0 +1,444 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "encoding/hex" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "os/user" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// RunSystemManagedBoot is `carlos system managed-boot --input <path>`, |
| +// carlos-managed-boot.service's second ExecStart, after the seed check. |
| +// Root only; the input must be the root-owned 0600 boot input in BootDir. |
| +func RunSystemManagedBoot(args []string) { |
| + fs := flag.NewFlagSet("system managed-boot", flag.ExitOnError) |
| + input := fs.String("input", "", "the boot input ("+managedboot.BootInputPath+")") |
| + _ = fs.Parse(args) |
| + if fs.NArg() != 0 || filepath.Clean(*input) != managedboot.BootInputPath { |
| + log.Fatalf("system managed-boot: --input must be %s", managedboot.BootInputPath) |
| + } |
| + if os.Geteuid() != 0 { |
| + log.Fatal("system managed-boot: run as root") |
| + } |
| + g, err := user.LookupGroup(serviceUser) |
| + if err != nil { |
| + log.Fatalf("system managed-boot: group %s: %v", serviceUser, err) |
| + } |
| + serviceGID, err := strconv.Atoi(g.Gid) |
| + if err != nil { |
| + log.Fatalf("system managed-boot: group %s: %v", serviceUser, err) |
| + } |
| + m := newManagedBoot("/", 0, 0, serviceGID) |
| + in, err := m.readInput() |
| + if err != nil { |
| + m.breadcrumb(managedboot.CodeBootstrapFailed) |
| + log.Fatalf("system managed-boot: %v", err) |
| + } |
| + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) |
| + defer stop() |
| + if err = m.Run(ctx, in); err != nil { |
| + log.Fatalf("system managed-boot: %v", err) |
| + } |
| +} |
| + |
| +// newManagedBoot is the production wiring. |
| +func newManagedBoot(root string, uid, gid, serviceGID int) *managedBoot { |
| + m := &managedBoot{ |
| + root: root, uid: uid, gid: gid, serviceGID: serviceGID, |
| + http: mbHTTPClient(), |
| + now: time.Now, |
| + sleep: mbSleep, |
| + jitter: mbJitter, |
| + run: mbRun, |
| + breadcrumb: mbBreadcrumb, |
| + logf: log.Printf, |
| + openStore: mbDoorStore, |
| + } |
| + m.systemctl = func(ctx context.Context, args ...string) error { |
| + return m.run(ctx, append([]string{"/usr/bin/systemctl"}, args...), mbCleanEnv) |
| + } |
| + return m |
| +} |
| + |
| +// readInput reads and decodes the boot input: a root-owned 0600 regular |
| +// file in the root-owned 0700 BootDir, rendered or scrubbed. |
| +func (m *managedBoot) readInput() (managedboot.LaunchInput, error) { |
| + st, err := os.Lstat(m.p(managedboot.BootDir)) |
| + if err != nil { |
| + return managedboot.LaunchInput{}, err |
| + } |
| + if !st.IsDir() || st.Mode().Perm() != 0o700 { |
| + return managedboot.LaunchInput{}, errors.New("managed boot: the boot directory is not root's alone") |
| + } |
| + raw, err := mbReadRootFile(m.root, managedboot.BootInputPath, m.uid, mbFileLimit, 0o600) |
| + if err != nil { |
| + return managedboot.LaunchInput{}, err |
| + } |
| + in, _, err := managedboot.DecodeBootInput(raw) |
| + return in, err |
| +} |
| + |
| +// mbHTTPClient talks to the frozen console origin only: TLS 1.2 or later, |
| +// no proxy from the environment, no redirects. |
| +func mbHTTPClient() *http.Client { |
| + return &http.Client{ |
| + Transport: &http.Transport{ |
| + Proxy: nil, |
| + DialContext: (&net.Dialer{Timeout: 30 * time.Second}).DialContext, |
| + TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, |
| + TLSHandshakeTimeout: 30 * time.Second, |
| + ResponseHeaderTimeout: mbRequestTimeout, |
| + }, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + } |
| +} |
| + |
| +func mbSleep(ctx context.Context, d time.Duration) error { |
| + t := time.NewTimer(d) |
| + defer t.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-t.C: |
| + return nil |
| + } |
| +} |
| + |
| +// mbRun runs argv with exactly env, from /, output to the journal. |
| +func mbRun(ctx context.Context, argv []string, env []string) error { |
| + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) |
| + cmd.Env = env |
| + cmd.Dir = "/" |
| + cmd.Stdout = os.Stdout |
| + cmd.Stderr = os.Stderr |
| + return cmd.Run() |
| +} |
| + |
| +// mbBreadcrumb writes one value-free line to the serial console (what the |
| +// provider's console output returns) and the journal. |
| +func mbBreadcrumb(code string) { |
| + line := managedboot.Breadcrumb(code) + "\n" |
| + if f, err := os.OpenFile("/dev/console", os.O_WRONLY|syscall.O_NOCTTY, 0); err == nil { |
| + _, _ = f.WriteString(line) |
| + _ = f.Close() |
| + } |
| + _, _ = os.Stderr.WriteString(line) |
| +} |
| + |
| +// mbWalk opens abs's directory components beneath root without following a |
| +// symlink, each owned by uid and not writable by group or other; root |
| +// itself is the trust anchor. With create, a missing component is made: |
| +// mode for the last, 0755 before it. The last component, existing, may be |
| +// no more permissive than mode. |
| +func mbWalk(root, abs string, uid int, create bool, mode os.FileMode) (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.Trim(filepath.Clean(abs), "/"), "/") |
| + for n, part := range parts { |
| + if part == "" { |
| + continue |
| + } |
| + last := n == len(parts)-1 |
| + want := os.FileMode(0o755) |
| + if last { |
| + want = mode |
| + } |
| + made := false |
| + next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0) |
| + if errors.Is(err, unix.ENOENT) && create { |
| + if err = unix.Mkdirat(fd, part, 0o700); err != nil && !errors.Is(err, unix.EEXIST) { |
| + unix.Close(fd) |
| + return -1, err |
| + } |
| + made = err == nil |
| + next, err = unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0) |
| + } |
| + if err != nil { |
| + unix.Close(fd) |
| + return -1, fmt.Errorf("%s: %w", filepath.Join(parts[:n+1]...), err) |
| + } |
| + if made { |
| + if err = unix.Fchmod(next, uint32(want.Perm())); err == nil { |
| + err = unix.Fsync(fd) |
| + } |
| + if err != nil { |
| + unix.Close(next) |
| + unix.Close(fd) |
| + return -1, err |
| + } |
| + } |
| + unix.Close(fd) |
| + fd = next |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err != nil { |
| + unix.Close(fd) |
| + return -1, err |
| + } |
| + perm := os.FileMode(st.Mode & 0o7777) |
| + if int(st.Uid) != uid || perm&0o022 != 0 || (last && create && perm&^want.Perm() != 0) { |
| + unix.Close(fd) |
| + return -1, fmt.Errorf("managed boot: /%s is not root's alone", filepath.Join(parts[:n+1]...)) |
| + } |
| + } |
| + return fd, nil |
| +} |
| + |
| +// mbEnsureDir makes abs (and its missing parents) beneath root, root-owned. |
| +func mbEnsureDir(root, abs string, mode os.FileMode, uid int) error { |
| + fd, err := mbWalk(root, abs, uid, true, mode) |
| + if err != nil { |
| + return err |
| + } |
| + return unix.Close(fd) |
| +} |
| + |
| +// mbReadRootFile reads a regular, singly linked file owned by uid, not |
| +// writable by group or other (exactly mode when mode is nonzero), of at most |
| +// limit bytes, from a root-owned directory chain. |
| +func mbReadRootFile(root, abs string, uid int, limit int64, mode os.FileMode) ([]byte, error) { |
| + dir, err := mbWalk(root, filepath.Dir(abs), uid, false, 0o755) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer unix.Close(dir) |
| + fd, err := unix.Openat(dir, filepath.Base(abs), unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) |
| + if err != nil { |
| + return nil, fmt.Errorf("%s: %w", abs, err) |
| + } |
| + f := os.NewFile(uintptr(fd), abs) |
| + defer f.Close() |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err != nil { |
| + return nil, err |
| + } |
| + perm := os.FileMode(st.Mode & 0o7777) |
| + if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1 || int(st.Uid) != uid || perm&0o022 != 0 || (mode != 0 && perm != mode) || st.Size > limit { |
| + return nil, fmt.Errorf("managed boot: %s is not root's alone", abs) |
| + } |
| + body, err := io.ReadAll(io.LimitReader(f, limit+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if int64(len(body)) > limit { |
| + return nil, fmt.Errorf("managed boot: %s is too large", abs) |
| + } |
| + return body, nil |
| +} |
| + |
| +// mbWriteRootFile replaces abs with body: an exclusive temp file beside it |
| +// (mode, group when group >= 0), fsync, rename, directory fsync. |
| +func mbWriteRootFile(root, abs string, body []byte, mode os.FileMode, uid, group int) error { |
| + dir, err := mbWalk(root, filepath.Dir(abs), uid, false, 0o755) |
| + if err != nil { |
| + return err |
| + } |
| + defer unix.Close(dir) |
| + var suffix [8]byte |
| + if _, err = rand.Read(suffix[:]); err != nil { |
| + return err |
| + } |
| + tmp := "." + filepath.Base(abs) + "." + hex.EncodeToString(suffix[:]) |
| + fd, err := unix.Openat(dir, tmp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + f := os.NewFile(uintptr(fd), tmp) |
| + err = unix.Fchmod(fd, uint32(mode.Perm())) |
| + if err == nil && group >= 0 { |
| + err = unix.Fchown(fd, -1, group) |
| + } |
| + if err == nil { |
| + _, err = f.Write(body) |
| + } |
| + if err == nil { |
| + err = f.Sync() |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err == nil { |
| + err = unix.Renameat(dir, tmp, dir, filepath.Base(abs)) |
| + } |
| + if err != nil { |
| + _ = unix.Unlinkat(dir, tmp, 0) |
| + return err |
| + } |
| + return unix.Fsync(dir) |
| +} |
| + |
| +// mbMove renames src to dst beneath root and syncs both directories. Across |
| +// filesystems it copies durably, keeping mode and group, then shreds src. |
| +func mbMove(root, src, dst string) error { |
| + from, to := filepath.Join(root, src), filepath.Join(root, dst) |
| + err := os.Rename(from, to) |
| + if errors.Is(err, unix.EXDEV) { |
| + err = mbCopyDurable(from, to) |
| + if err == nil { |
| + err = mbShred(from) |
| + } |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = mbSyncDir(filepath.Dir(to)); err != nil { |
| + return err |
| + } |
| + return mbSyncDir(filepath.Dir(from)) |
| +} |
| + |
| +func mbCopyDurable(from, to string) error { |
| + in, err := os.OpenFile(from, os.O_RDONLY|syscall.O_NOFOLLOW, 0) |
| + if err != nil { |
| + return err |
| + } |
| + defer in.Close() |
| + var st unix.Stat_t |
| + if err = unix.Fstat(int(in.Fd()), &st); err != nil { |
| + return err |
| + } |
| + tmp := to + ".move" |
| + _ = os.Remove(tmp) |
| + out, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + if err = out.Chown(-1, int(st.Gid)); err == nil { |
| + if err = out.Chmod(os.FileMode(st.Mode & 0o777)); err == nil { |
| + if _, err = io.Copy(out, in); err == nil { |
| + err = out.Sync() |
| + } |
| + } |
| + } |
| + if cerr := out.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err == nil { |
| + err = os.Rename(tmp, to) |
| + } |
| + if err != nil { |
| + _ = os.Remove(tmp) |
| + } |
| + return err |
| +} |
| + |
| +func mbSyncDir(path string) error { |
| + d, err := os.Open(path) |
| + if err != nil { |
| + return err |
| + } |
| + defer d.Close() |
| + return d.Sync() |
| +} |
| + |
| +// mbShred overwrites a regular file with zeros, syncs it and unlinks it. |
| +func mbShred(path string) error { |
| + fd, err := unix.Open(path, unix.O_WRONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) |
| + if err != nil { |
| + return err |
| + } |
| + f := os.NewFile(uintptr(fd), path) |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err == nil && st.Mode&unix.S_IFMT != unix.S_IFREG { |
| + err = fmt.Errorf("%s is not a regular file", path) |
| + } |
| + zero := make([]byte, 64<<10) |
| + for left := st.Size; err == nil && left > 0; { |
| + n := min(left, int64(len(zero))) |
| + _, err = f.Write(zero[:n]) |
| + left -= n |
| + } |
| + if err == nil { |
| + err = f.Sync() |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = os.Remove(path); err != nil { |
| + return err |
| + } |
| + return mbSyncDir(filepath.Dir(path)) |
| +} |
| + |
| +// mbRemoveTree shreds every file in a root-owned directory beneath root and |
| +// removes it. It holds only regular files (a staging directory). |
| +func mbRemoveTree(root, abs string, uid int) error { |
| + fd, err := mbWalk(root, abs, uid, false, 0o700) |
| + if err != nil { |
| + return err |
| + } |
| + unix.Close(fd) |
| + dir := filepath.Join(root, abs) |
| + entries, err := os.ReadDir(dir) |
| + if err != nil { |
| + return err |
| + } |
| + for _, e := range entries { |
| + if !e.Type().IsRegular() { |
| + return fmt.Errorf("managed boot: %s holds something other than a file", abs) |
| + } |
| + if err = mbShred(filepath.Join(dir, e.Name())); err != nil { |
| + return err |
| + } |
| + } |
| + if err = os.Remove(dir); err != nil { |
| + return err |
| + } |
| + return mbSyncDir(filepath.Dir(dir)) |
| +} |
| + |
| +// mbHashExec hashes the release about to run: a regular, singly linked |
| +// uid:gid 0755 file, opened without following a symlink. |
| +func mbHashExec(path string, uid, gid int) (string, error) { |
| + fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) |
| + if err != nil { |
| + return "", err |
| + } |
| + f := os.NewFile(uintptr(fd), path) |
| + defer f.Close() |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err != nil { |
| + return "", err |
| + } |
| + if st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1 || int(st.Uid) != uid || int(st.Gid) != gid || st.Mode&0o7777 != 0o755 { |
| + return "", fmt.Errorf("managed boot: %s is not root's 0755 release", path) |
| + } |
| + h := sha256.New() |
| + n, err := io.Copy(h, io.LimitReader(f, mbArtifactLimit+1)) |
| + if err != nil { |
| + return "", err |
| + } |
| + if n > mbArtifactLimit { |
| + return "", fmt.Errorf("managed boot: %s is too large", path) |
| + } |
| + return hex.EncodeToString(h.Sum(nil)), nil |
| +} |
diff --git a/internal/host/managedboot_linux_test.go b/internal/host/managedboot_linux_test.go| new file mode 100644 |
| index 000000000..b0018f46c |
| --- /dev/null |
| +++ b/internal/host/managedboot_linux_test.go |
| @@ -0,0 +1,1192 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io/fs" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +const ( |
| + mbtToken = "5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e" |
| + mbtTunnelToken = "7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a" |
| + mbtSecret = "SECRETsentinelSECRETsentinel0123456789ab" |
| + mbtKeyID = "AKIAEXAMPLEKEY000001" |
| + mbtOp = "0123456789abcdef0123456789abcdef" |
| + mbtTunnelHost = "tunnel.example.com" |
| +) |
| + |
| +// mbCountingStore counts every read the box makes of the store door. |
| +type mbCountingStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + gets int |
| +} |
| + |
| +func (c *mbCountingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.mu.Lock() |
| + c.gets++ |
| + c.mu.Unlock() |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *mbCountingStore) count() int { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.gets |
| +} |
| + |
| +// mbFixture is a fake root, a fake console and a fake store door for one |
| +// managed box across any number of boots. |
| +type mbFixture struct { |
| + t *testing.T |
| + root string |
| + in managedboot.LaunchInput |
| + priv ed25519.PrivateKey |
| + dir *release.DirStore |
| + store *mbCountingStore |
| + srv *httptest.Server |
| + binary []byte |
| + start time.Time |
| + clock time.Time |
| + nftAt time.Time // the firewall table exists from this time on |
| + nftNone bool // it never does |
| + |
| + mu sync.Mutex |
| + used bool |
| + enrolN int |
| + requests []managedboot.EnrolRequest |
| + enrol func(w http.ResponseWriter, n int) bool // overrides one call when it returns true |
| + reply managedboot.EnrolReply |
| + calls []string |
| + crumbs []string |
| + bootEnv [][]string |
| + atExec func() |
| + errs []string |
| + sleptFor time.Duration |
| + failCheck func() string |
| +} |
| + |
| +func newMBFixture(t *testing.T) *mbFixture { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f := &mbFixture{t: t, root: t.TempDir(), priv: priv, dir: release.NewDirStore(t.TempDir()), binary: []byte("#!/bin/true stable release v0.35.1\n")} |
| + f.store = &mbCountingStore{Store: f.dir} |
| + f.start = time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) |
| + f.clock = f.start |
| + f.nftAt = f.start |
| + f.srv = httptest.NewTLSServer(http.HandlerFunc(f.serve)) |
| + t.Cleanup(f.srv.Close) |
| + f.in = managedboot.LaunchInput{ |
| + Frozen: managedboot.Frozen{ |
| + Format: managedboot.FormatV1, |
| + ConsoleOrigin: f.srv.URL, |
| + TunnelHost: mbtTunnelHost, |
| + ReleasePubkey: base64.StdEncoding.EncodeToString(pub), |
| + SeedVersion: "v0.35.0", |
| + SeedKey: "bootstrap/router/v0.35.0/carlos-linux-arm64", |
| + SeedSHA256: strings.Repeat("ab", 32), |
| + }, |
| + Fleet: "shop", Label: "box-1", Op: mbtOp, Token: mbtToken, |
| + Expires: f.start.Add(30 * time.Minute), |
| + } |
| + if err := f.in.Validate(); err != nil { |
| + t.Fatalf("fixture input: %v", err) |
| + } |
| + f.reply = managedboot.EnrolReply{Fleet: "shop", Label: "box-1", TunnelURL: "https://" + mbtTunnelHost, TunnelToken: mbtTunnelToken, |
| + Credentials: managedboot.EnrolCredentials{ID: mbtKeyID, Secret: []byte(mbtSecret)}, Joining: true, |
| + Bucket: "carlos-fleet-shop", BucketRegion: "eu-west-1", Operation: mbtOp} |
| + // What cloud-init and the seed script leave behind. |
| + input, err := json.Marshal(f.in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.mkdir("/var/lib/carlos-managed-boot", 0o700) |
| + f.write(managedboot.BootInputPath, append(input, '\n'), 0o600) |
| + f.write(managedboot.SeedRequestPath, []byte(`{"token":"`+mbtToken+`"}`+"\n"), 0o600) |
| + f.write("/var/lib/carlos-managed-boot/seed", []byte("seed binary"), 0o700) |
| + f.write("/etc/systemd/system/carlos-managed-boot.service.d/10-enrol.conf", []byte("[Unit]\nWants=network-online.target\nAfter=network-online.target\n"), 0o644) |
| + userData := "#!/bin/sh\nput boot-input <<'X'\n" + string(input) + "\nX\n" |
| + for _, p := range []string{"user-data.txt", "user-data.txt.i", "scripts/part-001", "obj.pkl"} { |
| + f.write("/var/lib/cloud/instances/i-0abc/"+p, []byte(userData), 0o600) |
| + } |
| + if err := os.Symlink("instances/i-0abc", filepath.Join(f.root, "var/lib/cloud/instance")); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.write("/var/lib/cloud/instances/i-0abc/sem/config_scripts_user", []byte("ran\n"), 0o644) |
| + f.write("/run/cloud-init/instance-data.json", []byte(`{"v1":{"instance_id":"i-0abc"}}`), 0o644) |
| + f.write("/var/log/cloud-init-output.log", []byte("CARLOS_BOOT:seed_verified\n"), 0o644) |
| + f.publish(f.binary, "router", "stable", "linux-arm64", f.priv) |
| + return f |
| +} |
| + |
| +func (f *mbFixture) path(abs string) string { return filepath.Join(f.root, abs) } |
| + |
| +func (f *mbFixture) mkdir(abs string, mode os.FileMode) { |
| + f.t.Helper() |
| + if err := os.MkdirAll(f.path(abs), 0o755); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if err := os.Chmod(f.path(abs), mode); err != nil { |
| + f.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (f *mbFixture) write(abs string, body []byte, mode os.FileMode) { |
| + f.t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(f.path(abs)), 0o755); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if err := os.WriteFile(f.path(abs), body, mode); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if err := os.Chmod(f.path(abs), mode); err != nil { |
| + f.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (f *mbFixture) exists(abs string) bool { |
| + _, err := os.Lstat(f.path(abs)) |
| + return err == nil |
| +} |
| + |
| +// publish promotes v0.35.1 on channel with body as its platform artifact. |
| +func (f *mbFixture) publish(body []byte, component, channel, platform string, key ed25519.PrivateKey) { |
| + f.publishSigned(body, body, component, channel, platform, key) |
| +} |
| + |
| +// fresh replaces the store door's contents with an empty store. |
| +func (f *mbFixture) fresh() { |
| + f.dir = release.NewDirStore(f.t.TempDir()) |
| + f.store.Store = f.dir |
| +} |
| + |
| +// publishSigned stores body but signs the digest of signed. |
| +func (f *mbFixture) publishSigned(body, signed []byte, component, channel, platform string, key ed25519.PrivateKey) { |
| + f.t.Helper() |
| + ctx := context.Background() |
| + version := "v0.35.1" |
| + sum := sha256.Sum256(signed) |
| + art := release.SystemArtifact{Key: release.SystemArtifactKey(version, platform), SHA256: hex.EncodeToString(sum[:])} |
| + rel := release.SystemRelease{Version: version, ReleaseTag: version, Artifacts: map[string]release.SystemArtifact{platform: art}} |
| + if _, err := f.dir.Put(ctx, art.Key, body, ""); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if _, err := release.PromoteSystem(ctx, f.dir, release.RootSigner(key), component, channel, rel, release.SystemPromoteOptions{}); err != nil { |
| + f.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (f *mbFixture) serve(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != managedboot.EnrolPath || r.Method != http.MethodPost { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + var req managedboot.EnrolRequest |
| + dec := json.NewDecoder(r.Body) |
| + dec.DisallowUnknownFields() |
| + if err := dec.Decode(&req); err != nil { |
| + w.WriteHeader(400) |
| + return |
| + } |
| + f.mu.Lock() |
| + f.enrolN++ |
| + n := f.enrolN |
| + f.requests = append(f.requests, req) |
| + override := f.enrol |
| + f.mu.Unlock() |
| + if override != nil && override(w, n) { |
| + return |
| + } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.used || req.Token != mbtToken || !req.DataDirEmpty || req.DataDirEntries != 0 { |
| + f.used = true |
| + w.WriteHeader(http.StatusForbidden) |
| + _, _ = w.Write([]byte(`{"error":"enrolment token is invalid or unavailable"}`)) |
| + return |
| + } |
| + f.used = true |
| + w.Header().Set("Content-Type", "application/json") |
| + _ = json.NewEncoder(w).Encode(f.reply) |
| +} |
| + |
| +// consume marks the token used without answering: the reply is lost. |
| +func (f *mbFixture) consume() { |
| + f.mu.Lock() |
| + f.used = true |
| + f.mu.Unlock() |
| +} |
| + |
| +func (f *mbFixture) log(s string) { |
| + f.mu.Lock() |
| + f.calls = append(f.calls, s) |
| + f.mu.Unlock() |
| +} |
| + |
| +// boot is one boot: a fresh process over the same disk. |
| +func (f *mbFixture) boot(crashAt string) error { |
| + f.t.Helper() |
| + in := f.in |
| + raw, err := os.ReadFile(f.path(managedboot.BootInputPath)) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + if in, _, err = managedboot.DecodeBootInput(raw); err != nil { |
| + f.t.Fatalf("boot input: %v", err) |
| + } |
| + m := &managedBoot{ |
| + root: f.root, uid: os.Getuid(), gid: os.Getgid(), serviceGID: os.Getgid(), |
| + http: f.srv.Client(), |
| + now: func() time.Time { f.mu.Lock(); defer f.mu.Unlock(); return f.clock }, |
| + sleep: func(ctx context.Context, d time.Duration) error { |
| + f.mu.Lock() |
| + f.clock = f.clock.Add(d) |
| + f.sleptFor += d |
| + f.mu.Unlock() |
| + return nil |
| + }, |
| + jitter: func() time.Duration { return 7 * time.Second }, |
| + run: func(ctx context.Context, argv []string, env []string) error { |
| + switch { |
| + case argv[0] == mbNft: |
| + f.mu.Lock() |
| + ready := !f.nftNone && !f.clock.Before(f.nftAt) |
| + f.mu.Unlock() |
| + if !ready { |
| + return errors.New("no such table") |
| + } |
| + return nil |
| + case argv[0] == "/usr/bin/systemctl": |
| + f.log("systemctl " + strings.Join(argv[1:], " ")) |
| + return nil |
| + case len(argv) == 2 && argv[0] == f.path(mbStableBinary) && argv[1] == "bootstrap": |
| + f.mu.Lock() |
| + f.bootEnv = append(f.bootEnv, append([]string(nil), env...)) |
| + check := f.failCheck |
| + f.mu.Unlock() |
| + if check != nil { |
| + if msg := check(); msg != "" { |
| + f.mu.Lock() |
| + f.errs = append(f.errs, msg) |
| + f.mu.Unlock() |
| + } |
| + } |
| + f.log("bootstrap") |
| + // Bootstrap writes the units and creates /data. |
| + f.write("/etc/systemd/system/carlos-app@.service", []byte("[Service]\n"), 0o644) |
| + f.mkdir("/data", 0o750) |
| + return nil |
| + } |
| + f.t.Errorf("unexpected exec %v", argv) |
| + return errors.New("unexpected exec") |
| + }, |
| + breadcrumb: func(code string) { |
| + f.mu.Lock() |
| + f.crumbs = append(f.crumbs, code) |
| + f.mu.Unlock() |
| + }, |
| + logf: f.t.Logf, |
| + openStore: func(env map[string]string) (release.Store, error) { |
| + if env["CARLOS_TUNNEL_URL"] != "https://"+mbtTunnelHost || env["CARLOS_TUNNEL_TOKEN"] != mbtTunnelToken { |
| + return nil, errors.New("store door opened without the committed tunnel") |
| + } |
| + return f.store, nil |
| + }, |
| + beforeExec: f.atExec, |
| + } |
| + m.systemctl = func(ctx context.Context, args ...string) error { |
| + if !f.exists(mbEnrolDropIn) && !f.exists(mbCompleteMarker) { |
| + f.mu.Lock() |
| + f.errs = append(f.errs, "enrol drop-in removed before the complete marker") |
| + f.mu.Unlock() |
| + } |
| + return m.run(ctx, append([]string{"/usr/bin/systemctl"}, args...), mbCleanEnv) |
| + } |
| + if crashAt != "" { |
| + m.crash = func(step string) error { |
| + if step == crashAt { |
| + return errManagedBootHalted |
| + } |
| + return nil |
| + } |
| + } |
| + err = m.Run(context.Background(), in) |
| + f.mu.Lock() |
| + errs := f.errs |
| + f.errs = nil |
| + f.mu.Unlock() |
| + for _, e := range errs { |
| + f.t.Error(e) |
| + } |
| + return err |
| +} |
| + |
| +func (f *mbFixture) count(prefix string) int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + n := 0 |
| + for _, c := range f.calls { |
| + if strings.HasPrefix(c, prefix) { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +func (f *mbFixture) lastCrumb() string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if len(f.crumbs) == 0 { |
| + return "" |
| + } |
| + return f.crumbs[len(f.crumbs)-1] |
| +} |
| + |
| +func (f *mbFixture) enrols() int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.enrolN |
| +} |
| + |
| +// assertNothingStaged: no credential, host.env or commit survives, nothing |
| +// ran and the edge was never queued. |
| +func (f *mbFixture) assertNothingStaged() { |
| + f.t.Helper() |
| + for _, p := range []string{mbCommittedDir, managedboot.HostEnvPath, managedboot.CredentialsPath, managedboot.IdentityPath, mbCompleteMarker} { |
| + if f.exists(p) { |
| + f.t.Errorf("%s exists", p) |
| + } |
| + } |
| + entries, _ := os.ReadDir(f.path(managedboot.BootDir)) |
| + for _, e := range entries { |
| + if strings.HasPrefix(e.Name(), mbStagingPrefix) { |
| + f.t.Errorf("staging %s survives", e.Name()) |
| + } |
| + } |
| + if n := f.count("bootstrap"); n != 0 { |
| + f.t.Errorf("bootstrap ran %d times", n) |
| + } |
| + if n := f.count("systemctl start"); n != 0 { |
| + f.t.Errorf("edge start queued %d times", n) |
| + } |
| + f.assertNotAdmitted() |
| +} |
| + |
| +func (f *mbFixture) assertNotAdmitted() { |
| + f.t.Helper() |
| + if f.exists(managedboot.AdmittedMarker) { |
| + f.t.Error("an admission marker exists") |
| + } |
| +} |
| + |
| +func (f *mbFixture) assertSucceeded() { |
| + f.t.Helper() |
| + // The complete path emits no breadcrumb, so the last may be the |
| + // first boot's; it is never a failure. |
| + last := f.lastCrumb() |
| + if !f.exists(mbCompleteMarker) || f.exists(mbEnrolDropIn) || last == managedboot.CodeBootstrapFailed || last == managedboot.CodeEnrolFailed { |
| + f.t.Errorf("boot did not complete: crumbs %v", f.crumbs) |
| + } |
| + if n := f.count("systemctl start --no-block carlos-edge.service"); n != 1 { |
| + f.t.Errorf("edge queued %d times, want 1", n) |
| + } |
| + f.assertNotAdmitted() |
| +} |
| + |
| +func TestManagedBootFirewallOrdering(t *testing.T) { |
| + script, err := managedboot.RenderUserData(newMBFixture(t).in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, want := range []string{"[Unit]\nRequires=nftables.service\nAfter=nftables.service\n", "[Unit]\nWants=network-online.target\nAfter=network-online.target\n"} { |
| + if !strings.Contains(script, want) { |
| + t.Errorf("unit text lacks %q", want) |
| + } |
| + } |
| + t.Run("table appears after 5 s", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + f.nftAt = f.start.Add(5 * time.Second) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.assertSucceeded() |
| + if f.sleptFor < 5*time.Second || f.sleptFor > 6*time.Second { |
| + t.Errorf("waited %v", f.sleptFor) |
| + } |
| + }) |
| + t.Run("table never appears", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + f.nftNone = true |
| + if err := f.boot(""); err == nil { |
| + t.Fatal("boot passed with no firewall") |
| + } |
| + if f.enrols() != 0 || f.store.count() != 0 { |
| + t.Errorf("network calls with no firewall: enrol %d store %d", f.enrols(), f.store.count()) |
| + } |
| + if f.sleptFor < mbIMDSWait || f.sleptFor > mbIMDSWait+2*time.Second { |
| + t.Errorf("waited %v, want about %v", f.sleptFor, mbIMDSWait) |
| + } |
| + if f.lastCrumb() != managedboot.CodeBootstrapFailed { |
| + t.Errorf("crumbs %v", f.crumbs) |
| + } |
| + if !f.exists(mbEnrolDropIn) { |
| + t.Error("enrol drop-in removed on a failed boot") |
| + } |
| + f.assertNothingStaged() |
| + }) |
| +} |
| + |
| +func TestManagedBootAttestation(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + prep func(f *mbFixture) |
| + empty bool |
| + entries int |
| + }{ |
| + {"absent", func(f *mbFixture) {}, true, 0}, |
| + {"empty dir", func(f *mbFixture) { f.mkdir("/data", 0o755) }, true, 0}, |
| + {"dotfile", func(f *mbFixture) { f.write("/data/.keep", nil, 0o644) }, false, 1}, |
| + {"lost+found", func(f *mbFixture) { f.mkdir("/data/lost+found", 0o700) }, false, 1}, |
| + {"two entries", func(f *mbFixture) { f.write("/data/a", nil, 0o644); f.write("/data/b", nil, 0o644) }, false, 2}, |
| + {"symlink", func(f *mbFixture) { |
| + f.mkdir("/elsewhere", 0o755) |
| + if err := os.Symlink("elsewhere", f.path("/data")); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, false, 1}, |
| + {"regular file", func(f *mbFixture) { f.write("/data", []byte("x"), 0o644) }, false, 1}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + f := newMBFixture(t) |
| + c.prep(f) |
| + err := f.boot("") |
| + if len(f.requests) != 1 { |
| + t.Fatalf("%d trades", len(f.requests)) |
| + } |
| + if got := f.requests[0]; got.DataDirEmpty != c.empty || got.DataDirEntries != c.entries || got.Token != mbtToken { |
| + t.Errorf("attested empty=%v entries=%d, want %v %d", got.DataDirEmpty, got.DataDirEntries, c.empty, c.entries) |
| + } |
| + if c.empty { |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.assertSucceeded() |
| + return |
| + } |
| + if err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed { |
| + t.Errorf("non-empty /data: err %v crumbs %v", err, f.crumbs) |
| + } |
| + f.assertNothingStaged() |
| + }) |
| + } |
| +} |
| + |
| +func TestManagedBootTradeRetry(t *testing.T) { |
| + t.Run("503 429 transport then 200", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + f.enrol = func(w http.ResponseWriter, n int) bool { |
| + switch n { |
| + case 1: |
| + w.Header().Set("Retry-After", "5") |
| + w.WriteHeader(503) |
| + case 2: |
| + w.Header().Set("Retry-After", "60") |
| + w.WriteHeader(429) |
| + case 3: |
| + panic(http.ErrAbortHandler) |
| + default: |
| + return false |
| + } |
| + return true |
| + } |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.assertSucceeded() |
| + if f.enrols() != 4 || f.sleptFor != 5*time.Second+60*time.Second+7*time.Second { |
| + t.Errorf("enrols %d slept %v", f.enrols(), f.sleptFor) |
| + } |
| + pending := 0 |
| + for _, c := range f.crumbs { |
| + if c == managedboot.CodeEnrolPending { |
| + pending++ |
| + } |
| + } |
| + if pending != 1 { |
| + t.Errorf("enrol_pending %d times", pending) |
| + } |
| + }) |
| + t.Run("503 until expiry", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + f.enrol = func(w http.ResponseWriter, n int) bool { |
| + w.Header().Set("Retry-After", "5") |
| + w.WriteHeader(503) |
| + return true |
| + } |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed { |
| + t.Fatalf("err %v crumbs %v", err, f.crumbs) |
| + } |
| + if f.clock.Before(f.in.Expires) || f.clock.After(f.in.Expires) { |
| + t.Errorf("stopped at %v, expiry %v", f.clock, f.in.Expires) |
| + } |
| + if n := f.enrols(); n != 30*60/5 { |
| + t.Errorf("%d attempts", n) |
| + } |
| + f.assertNothingStaged() |
| + }) |
| + t.Run("403 is terminal", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + f.consume() |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed { |
| + t.Fatalf("err %v crumbs %v", err, f.crumbs) |
| + } |
| + if f.enrols() != 1 || f.sleptFor != 0 { |
| + t.Errorf("enrols %d slept %v", f.enrols(), f.sleptFor) |
| + } |
| + f.assertNothingStaged() |
| + }) |
| + bad := map[string]func(r *managedboot.EnrolReply){ |
| + "wrong fleet": func(r *managedboot.EnrolReply) { r.Fleet = "other" }, |
| + "wrong label": func(r *managedboot.EnrolReply) { r.Label = "box-2" }, |
| + "wrong op": func(r *managedboot.EnrolReply) { r.Operation = strings.Repeat("f", 32) }, |
| + "wrong tunnel": func(r *managedboot.EnrolReply) { r.TunnelURL = "https://evil.example.com" }, |
| + "http tunnel": func(r *managedboot.EnrolReply) { r.TunnelURL = "http://" + mbtTunnelHost }, |
| + "not joining": func(r *managedboot.EnrolReply) { r.Joining = false }, |
| + "no tunnel token": func(r *managedboot.EnrolReply) { r.TunnelToken = "" }, |
| + "no key id": func(r *managedboot.EnrolReply) { r.Credentials.ID = "" }, |
| + "no secret": func(r *managedboot.EnrolReply) { r.Credentials.Secret = nil }, |
| + "secret newline": func(r *managedboot.EnrolReply) { r.Credentials.Secret = []byte(mbtSecret + "\n[x]") }, |
| + "empty bucket": func(r *managedboot.EnrolReply) { r.Bucket = "" }, |
| + "empty region": func(r *managedboot.EnrolReply) { r.BucketRegion = "" }, |
| + "bucket injection": func(r *managedboot.EnrolReply) { r.Bucket = "a b\nCARLOS_HOST_CLAIM=1" }, |
| + "tunnel token form": func(r *managedboot.EnrolReply) { r.TunnelToken = mbtTunnelToken + "\nX=1" }, |
| + } |
| + for name, mutate := range bad { |
| + t.Run(name, func(t *testing.T) { |
| + f := newMBFixture(t) |
| + mutate(&f.reply) |
| + err := f.boot("") |
| + if err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed { |
| + t.Fatalf("err %v crumbs %v", err, f.crumbs) |
| + } |
| + if f.enrols() != 1 { |
| + t.Errorf("a refused 200 was traded again: %d", f.enrols()) |
| + } |
| + if strings.Contains(err.Error(), mbtSecret) || strings.Contains(err.Error(), mbtTunnelToken) || strings.Contains(strings.Join(f.crumbs, " "), mbtSecret) { |
| + t.Errorf("a secret reached the error or breadcrumbs: %v", err) |
| + } |
| + f.assertNothingStaged() |
| + }) |
| + } |
| +} |
| + |
| +func TestManagedBootRebootBoundaries(t *testing.T) { |
| + t.Run("a before trade", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot("trade"); !errors.Is(err, errManagedBootHalted) { |
| + t.Fatal(err) |
| + } |
| + if f.enrols() != 0 { |
| + t.Fatal("traded before the crash point") |
| + } |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.enrols() != 1 { |
| + t.Errorf("%d trades", f.enrols()) |
| + } |
| + f.assertSucceeded() |
| + }) |
| + t.Run("b request sent reply lost", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + f.enrol = func(w http.ResponseWriter, n int) bool { |
| + if n == 1 { |
| + f.consume() |
| + panic(http.ErrAbortHandler) |
| + } |
| + return false |
| + } |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed { |
| + t.Fatalf("err %v crumbs %v", err, f.crumbs) |
| + } |
| + f.assertNothingStaged() |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed { |
| + t.Fatalf("next boot: err %v crumbs %v", err, f.crumbs) |
| + } |
| + f.assertNothingStaged() |
| + }) |
| + t.Run("c staging partially written", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot("staging-partial"); !errors.Is(err, errManagedBootHalted) { |
| + t.Fatal(err) |
| + } |
| + var partial string |
| + entries, _ := os.ReadDir(f.path(managedboot.BootDir)) |
| + for _, e := range entries { |
| + if strings.HasPrefix(e.Name(), mbStagingPrefix) { |
| + partial = e.Name() |
| + } |
| + } |
| + if partial == "" { |
| + t.Fatal("no partial staging to recover from") |
| + } |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeEnrolFailed { |
| + t.Fatalf("err %v crumbs %v", err, f.crumbs) |
| + } |
| + if f.enrols() != 2 { |
| + t.Errorf("%d trades", f.enrols()) |
| + } |
| + f.assertNothingStaged() |
| + }) |
| + t.Run("d after commit", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot("committed"); !errors.Is(err, errManagedBootHalted) { |
| + t.Fatal(err) |
| + } |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.enrols() != 1 { |
| + t.Errorf("%d trades after a commit", f.enrols()) |
| + } |
| + f.assertSucceeded() |
| + }) |
| + for _, step := range []string{"scrubbed", "key", "stable", "bootstrapped", "complete"} { |
| + t.Run("e after "+step, func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot(step); !errors.Is(err, errManagedBootHalted) { |
| + t.Fatal(err) |
| + } |
| + f.assertNotAdmitted() |
| + before := f.store.count() |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.enrols() != 1 { |
| + t.Errorf("%d trades", f.enrols()) |
| + } |
| + if f.store.count() != 2 { |
| + t.Errorf("store reads %d (before the crash %d), want 2 in all", f.store.count(), before) |
| + } |
| + f.assertSucceeded() |
| + }) |
| + } |
| +} |
| + |
| +func TestManagedBootStartPlan(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{"systemctl daemon-reload", "bootstrap", "systemctl daemon-reload", "systemctl start --no-block carlos-edge.service"} |
| + if !slices.Equal(f.calls, want) { |
| + t.Errorf("calls %q\nwant %q", f.calls, want) |
| + } |
| + if want := []string{managedboot.CodeStableVerified, managedboot.CodeJoining}; !slices.Equal(f.crumbs, want) { |
| + t.Errorf("crumbs %q, want %q", f.crumbs, want) |
| + } |
| + f.calls = nil |
| + // Every later boot: nothing changed, so no reload; the edge is queued. |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := []string{"systemctl start --no-block carlos-edge.service"}; !slices.Equal(f.calls, want) { |
| + t.Errorf("complete path calls %q", f.calls) |
| + } |
| + t.Run("crash between complete and queueing", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot("complete"); !errors.Is(err, errManagedBootHalted) { |
| + t.Fatal(err) |
| + } |
| + if f.count("systemctl start") != 0 { |
| + t.Fatal("queued before the crash point") |
| + } |
| + f.calls = nil |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := []string{"systemctl daemon-reload", "systemctl start --no-block carlos-edge.service"}; !slices.Equal(f.calls, want) { |
| + t.Errorf("calls %q", f.calls) |
| + } |
| + }) |
| +} |
| + |
| +func TestManagedBootUpdateReboot(t *testing.T) { |
| + for _, name := range []string{"updated", "rolled back"} { |
| + t.Run(name, func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Task 3 owns this record; the boot must leave it alone. |
| + f.write(managedboot.AdmittedMarker, []byte("admitted\n"), 0o600) |
| + bin := f.path(mbStableBinary) |
| + if name == "updated" { |
| + f.write(mbStableBinary, []byte("a later signed release"), 0o755) |
| + } else { |
| + if err := os.Remove(bin); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.write(mbStableBinary, []byte("carlos.prev restored by recovery"), 0o755) |
| + } |
| + // Unreadable: a boot that read it would fail. |
| + if err := os.Chmod(bin, 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = os.Chmod(bin, 0o755) }) |
| + f.calls, f.crumbs = nil, nil |
| + enrols, gets := f.enrols(), f.store.count() |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.enrols() != enrols || f.store.count() != gets { |
| + t.Errorf("network on the complete path: enrol %d store %d", f.enrols()-enrols, f.store.count()-gets) |
| + } |
| + if want := []string{"systemctl start --no-block carlos-edge.service"}; !slices.Equal(f.calls, want) { |
| + t.Errorf("calls %q", f.calls) |
| + } |
| + if b, err := os.ReadFile(f.path(managedboot.AdmittedMarker)); err != nil || string(b) != "admitted\n" { |
| + t.Errorf("admission record changed: %q %v", b, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func mbOwner(t *testing.T, path string) (uid, gid int, mode os.FileMode) { |
| + t.Helper() |
| + st, err := os.Lstat(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sys := st.Sys().(*syscall.Stat_t) |
| + return int(sys.Uid), int(sys.Gid), st.Mode() |
| +} |
| + |
| +func TestManagedBootStagingModes(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + uid, gid := os.Getuid(), os.Getgid() |
| + for _, c := range []struct { |
| + path string |
| + mode os.FileMode |
| + }{ |
| + {managedboot.HostEnvPath, 0o600}, |
| + {managedboot.CredentialsPath, 0o640}, |
| + {managedboot.IdentityPath, 0o644}, |
| + {managedboot.RootAdmissionDir, os.ModeDir | 0o700}, |
| + {"/etc/carlos", os.ModeDir | 0o755}, |
| + {mbStableBinary, 0o755}, |
| + } { |
| + u, g, mode := mbOwner(t, f.path(c.path)) |
| + if u != uid || g != gid || mode != c.mode { |
| + t.Errorf("%s: %d:%d %v, want %d:%d %v", c.path, u, g, mode, uid, gid, c.mode) |
| + } |
| + } |
| + creds, _ := os.ReadFile(f.path(managedboot.CredentialsPath)) |
| + parsed, err := rootaws.ParseStaticCredentials(creds) |
| + if err != nil || parsed.AccessKeyID != mbtKeyID || parsed.SecretAccessKey != mbtSecret { |
| + t.Errorf("credentials do not parse back: %v", err) |
| + } |
| + raw, _ := os.ReadFile(f.path(managedboot.IdentityPath)) |
| + id, err := managedboot.ParseIdentity(raw) |
| + if err != nil || id.ReleasePubkey != f.in.Frozen.ReleasePubkey || id.Fleet != "shop" || id.Label != "box-1" || id.Op != mbtOp { |
| + t.Errorf("identity %+v %v", id, err) |
| + } |
| + if entries, err := os.ReadDir(f.path(managedboot.RootAdmissionDir)); err != nil || len(entries) != 0 { |
| + t.Errorf("admission dir holds %v (%v)", entries, err) |
| + } |
| + if f.exists(mbCommittedDir + "/credentials") { |
| + t.Error("a second copy of the credentials survives in the commit") |
| + } |
| + t.Run("carlos-writable path refused", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot("committed"); !errors.Is(err, errManagedBootHalted) { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(f.path("/etc/carlos"), 0o775); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeBootstrapFailed { |
| + t.Fatalf("a group-writable /etc/carlos was trusted: %v", err) |
| + } |
| + if f.count("bootstrap") != 0 { |
| + t.Error("bootstrap ran") |
| + } |
| + }) |
| +} |
| + |
| +func TestManagedBootUnitDropIns(t *testing.T) { |
| + f := newMBFixture(t) |
| + etc := f.path(mbSystemdDir) |
| + f.failCheck = func() string { |
| + for _, u := range managedboot.WorkloadUnits { |
| + b, err := os.ReadFile(filepath.Join(etc, u+".d", managedboot.AdmissionDropInName)) |
| + if err != nil || string(b) != managedboot.AdmissionDropIn { |
| + return "no admission drop-in for " + u + " before bootstrap" |
| + } |
| + } |
| + if b, err := os.ReadFile(filepath.Join(etc, managedboot.ControlUnit+".d", managedboot.ControlDropInName)); err != nil || string(b) != managedboot.ControlDropIn { |
| + return "no control drop-in before bootstrap" |
| + } |
| + entries, _ := os.ReadDir(etc) |
| + for _, e := range entries { |
| + if !e.IsDir() && slices.Contains(managedboot.WorkloadUnits, e.Name()) { |
| + return "a workload unit file exists before bootstrap" |
| + } |
| + } |
| + return "" |
| + } |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.count("bootstrap") != 1 { |
| + t.Fatal("bootstrap did not run") |
| + } |
| + for _, u := range managedboot.MaintenanceUnits { |
| + if _, err := os.Lstat(filepath.Join(etc, u+".d", managedboot.AdmissionDropInName)); err == nil { |
| + t.Errorf("maintenance unit %s carries the admission condition", u) |
| + } |
| + } |
| + if managedboot.AdmissionDropIn != "[Unit]\nConditionPathExists=/var/lib/carlos-managed-root/admitted\n" { |
| + t.Errorf("drop-in body %q", managedboot.AdmissionDropIn) |
| + } |
| + // The complete path rewrites a deleted and an altered drop-in. |
| + gone := filepath.Join(etc, "carlos-instance@.service.d", managedboot.AdmissionDropInName) |
| + altered := filepath.Join(etc, "carlos-app@.socket.d", managedboot.AdmissionDropInName) |
| + control := filepath.Join(etc, managedboot.ControlUnit+".d", managedboot.ControlDropInName) |
| + if err := os.Remove(gone); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(altered, []byte("[Unit]\nConditionPathExists=\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Remove(control); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.calls = nil |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range []string{gone, altered} { |
| + if b, err := os.ReadFile(p); err != nil || string(b) != managedboot.AdmissionDropIn { |
| + t.Errorf("%s not restored: %q %v", p, b, err) |
| + } |
| + } |
| + if b, err := os.ReadFile(control); err != nil || string(b) != managedboot.ControlDropIn { |
| + t.Errorf("control drop-in not restored: %v", err) |
| + } |
| + if want := []string{"systemctl daemon-reload", "systemctl start --no-block carlos-edge.service"}; !slices.Equal(f.calls, want) { |
| + t.Errorf("calls %q", f.calls) |
| + } |
| + // Present and exact: zero writes. |
| + st, _ := os.Stat(altered) |
| + f.calls = nil |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st2, _ := os.Stat(altered); !st2.ModTime().Equal(st.ModTime()) || !os.SameFile(st, st2) { |
| + t.Error("an exact drop-in was rewritten") |
| + } |
| + if want := []string{"systemctl start --no-block carlos-edge.service"}; !slices.Equal(f.calls, want) { |
| + t.Errorf("calls %q", f.calls) |
| + } |
| +} |
| + |
| +func TestManagedUnitClassification(t *testing.T) { |
| + entries, err := fs.ReadDir(unitsFS, "units") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + embedded := map[string]bool{} |
| + for _, e := range entries { |
| + embedded[e.Name()] = true |
| + n := 0 |
| + if slices.Contains(managedboot.WorkloadUnits, e.Name()) { |
| + n++ |
| + } |
| + if slices.Contains(managedboot.MaintenanceUnits, e.Name()) { |
| + n++ |
| + } |
| + if n != 1 { |
| + t.Errorf("unit %s is classified %d times, want exactly once (WorkloadUnits or MaintenanceUnits)", e.Name(), n) |
| + } |
| + } |
| + for _, u := range managedboot.WorkloadUnits { |
| + if !strings.HasSuffix(u, "@.service") && !strings.HasSuffix(u, "@.socket") { |
| + t.Errorf("workload unit %s is not a template", u) |
| + } |
| + if !embedded[u] { |
| + t.Errorf("workload unit %s is not embedded", u) |
| + } |
| + } |
| + for _, u := range managedboot.MaintenanceUnits { |
| + if !embedded[u] && u != "carlos-managed-boot.service" { |
| + t.Errorf("maintenance unit %s is not embedded", u) |
| + } |
| + } |
| + dir := t.TempDir() |
| + for _, u := range []string{"carlos-edge.service", "carlos-instance-control.socket", "../x.service", "a b.service"} { |
| + if _, err := managedboot.InstallAdmissionDropIns(dir, []string{u}); err == nil { |
| + t.Errorf("named unit %q accepted", u) |
| + } |
| + } |
| + if entries, _ := os.ReadDir(dir); len(entries) != 0 { |
| + t.Errorf("a refused named unit wrote %d entries", len(entries)) |
| + } |
| + if _, err := managedboot.InstallAdmissionDropIns(dir, []string{"shop-worker.service"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if b, err := os.ReadFile(filepath.Join(dir, "shop-worker.service.d", managedboot.AdmissionDropInName)); err != nil || string(b) != managedboot.AdmissionDropIn { |
| + t.Errorf("named unit drop-in: %q %v", b, err) |
| + } |
| +} |
| + |
| +// filesHolding lists every regular file under root that holds needle. |
| +func filesHolding(t *testing.T, root string, needle string) []string { |
| + t.Helper() |
| + var hits []string |
| + _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { |
| + if err != nil || !d.Type().IsRegular() { |
| + return nil |
| + } |
| + if b, err := os.ReadFile(path); err == nil && bytes.Contains(b, []byte(needle)) { |
| + rel, _ := filepath.Rel(root, path) |
| + hits = append(hits, "/"+rel) |
| + } |
| + return nil |
| + }) |
| + return hits |
| +} |
| + |
| +func TestManagedBootScrub(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if hits := filesHolding(t, f.root, mbtToken); len(hits) != 0 { |
| + t.Errorf("the enrolment token survives in %v", hits) |
| + } |
| + if hits := filesHolding(t, f.root, mbtSecret); !slices.Equal(hits, []string{managedboot.CredentialsPath}) { |
| + t.Errorf("the secret is in %v, want only the credentials", hits) |
| + } |
| + if hits := filesHolding(t, f.root, mbtTunnelToken); !slices.Equal(hits, []string{managedboot.HostEnvPath}) { |
| + t.Errorf("the tunnel token is in %v, want only host.env", hits) |
| + } |
| + raw, _ := os.ReadFile(f.path(managedboot.BootInputPath)) |
| + in, scrubbed, err := managedboot.DecodeBootInput(raw) |
| + want := f.in |
| + want.Token = "" |
| + if err != nil || !scrubbed || in != want { |
| + t.Errorf("boot input after the scrub: %+v scrubbed=%v %v", in, scrubbed, err) |
| + } |
| + for _, p := range []string{managedboot.SeedRequestPath, "/var/lib/cloud/instances/i-0abc/user-data.txt", "/var/lib/cloud/instances/i-0abc/user-data.txt.i", "/var/lib/cloud/instances/i-0abc/scripts/part-001", "/var/lib/cloud/instances/i-0abc/obj.pkl"} { |
| + if f.exists(p) { |
| + t.Errorf("%s survives", p) |
| + } |
| + } |
| + for _, p := range []string{"/var/lib/cloud/instances/i-0abc/sem/config_scripts_user", "/run/cloud-init/instance-data.json", "/var/log/cloud-init-output.log", "/var/lib/carlos-managed-boot/seed"} { |
| + if !f.exists(p) { |
| + t.Errorf("%s was removed though it holds no token", p) |
| + } |
| + } |
| + t.Run("scrub failure stops before bootstrap", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + scripts := f.path("/var/lib/cloud/instances/i-0abc/scripts") |
| + if err := os.Chmod(scripts, 0o500); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = os.Chmod(scripts, 0o755) }) |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeBootstrapFailed { |
| + t.Fatalf("err %v crumbs %v", err, f.crumbs) |
| + } |
| + if f.count("bootstrap") != 0 || f.store.count() != 0 { |
| + t.Error("bootstrap or the stable fetch ran after a failed scrub") |
| + } |
| + }) |
| +} |
| + |
| +func TestManagedBootStableTrust(t *testing.T) { |
| + _, other, _ := ed25519.GenerateKey(rand.Reader) |
| + stableKey := release.SystemPointerKey("router", "stable") |
| + cases := map[string]func(f *mbFixture){ |
| + "other key": func(f *mbFixture) { f.fresh(); f.publish(f.binary, "router", "stable", "linux-arm64", other) }, |
| + "scoped grant": func(f *mbFixture) { |
| + raw, _, err := f.dir.Get(context.Background(), stableKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var w map[string]any |
| + _ = json.Unmarshal(raw, &w) |
| + w["grant"] = map[string]string{"payload": "e30=", "sig": "AA=="} |
| + raw, _ = json.Marshal(w) |
| + _, etag, _ := f.dir.Get(context.Background(), stableKey) |
| + if _, err = f.dir.Put(context.Background(), stableKey, raw, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "wrong channel": func(f *mbFixture) { |
| + beta := release.NewDirStore(t.TempDir()) |
| + if _, err := release.PromoteSystem(context.Background(), beta, release.RootSigner(f.priv), "router", "beta", release.SystemRelease{Version: "v0.35.1", Artifacts: map[string]release.SystemArtifact{"linux-arm64": {Key: release.SystemArtifactKey("v0.35.1", "linux-arm64"), SHA256: strings.Repeat("0", 64)}}}, release.SystemPromoteOptions{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _, _ := beta.Get(context.Background(), release.SystemPointerKey("router", "beta")) |
| + _, etag, _ := f.dir.Get(context.Background(), stableKey) |
| + if _, err := f.dir.Put(context.Background(), stableKey, raw, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + "no linux-arm64": func(f *mbFixture) { |
| + f.fresh() |
| + f.publish(f.binary, "router", "stable", "linux-amd64", f.priv) |
| + }, |
| + "sha mismatch": func(f *mbFixture) { |
| + f.fresh() |
| + f.publishSigned([]byte("tampered"), f.binary, "router", "stable", "linux-arm64", f.priv) |
| + }, |
| + "oversize": func(f *mbFixture) { |
| + old := mbArtifactLimit |
| + mbArtifactLimit = 8 |
| + f.t.Cleanup(func() { mbArtifactLimit = old }) |
| + }, |
| + "swapped before exec": func(f *mbFixture) { |
| + f.atExec = func() { |
| + if err := os.WriteFile(f.path(mbStableBinary), []byte("swapped"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }, |
| + "relinked before exec": func(f *mbFixture) { |
| + f.atExec = func() { |
| + if err := os.Link(f.path(mbStableBinary), f.path("/opt/carlos/carlos.link")); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }, |
| + "symlinked before exec": func(f *mbFixture) { |
| + f.atExec = func() { |
| + bin := f.path(mbStableBinary) |
| + _ = os.Rename(bin, bin+".real") |
| + if err := os.Symlink("carlos.real", bin); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }, |
| + } |
| + for name, prep := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + f := newMBFixture(t) |
| + prep(f) |
| + if err := f.boot(""); err == nil || f.lastCrumb() != managedboot.CodeBootstrapFailed { |
| + t.Fatalf("err %v crumbs %v", err, f.crumbs) |
| + } |
| + if f.count("bootstrap") != 0 || f.exists(mbCompleteMarker) || f.count("systemctl start") != 0 { |
| + t.Error("something ran from an untrusted release") |
| + } |
| + f.assertNotAdmitted() |
| + }) |
| + } |
| + t.Run("valid", func(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + sum := sha256.Sum256(f.binary) |
| + if got, err := mbHashExec(f.path(mbStableBinary), os.Getuid(), os.Getgid()); err != nil || got != hex.EncodeToString(sum[:]) { |
| + t.Errorf("installed release %s %v", got, err) |
| + } |
| + if !slices.Contains(f.crumbs, managedboot.CodeStableVerified) { |
| + t.Errorf("crumbs %v", f.crumbs) |
| + } |
| + if len(f.bootEnv) != 1 || !slices.Equal(f.bootEnv[0], mbCleanEnv) { |
| + t.Errorf("bootstrap env %v", f.bootEnv) |
| + } |
| + }) |
| + t.Run("children run from /", func(t *testing.T) { |
| + out := filepath.Join(t.TempDir(), "pwd") |
| + if err := mbRun(context.Background(), []string{"/bin/sh", "-c", `pwd >"$0"`, out}, mbCleanEnv); err != nil { |
| + t.Fatal(err) |
| + } |
| + if b, _ := os.ReadFile(out); string(b) != "/\n" { |
| + t.Errorf("cwd %q", b) |
| + } |
| + }) |
| +} |
| + |
| +func TestManagedBootNoDeploymentAuthority(t *testing.T) { |
| + f := newMBFixture(t) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := os.ReadFile(f.path(managedboot.HostEnvPath)) |
| + env, err := hostenv.Parse(raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := map[string]string{ |
| + "CARLOS_REGION": "fleet/shop", "CARLOS_FLEET": "shop", "CARLOS_FLEET_BOX": "box-1", "CARLOS_TUNNEL_NAME": "shop/box-1", |
| + "CARLOS_TUNNEL_URL": "https://" + mbtTunnelHost, "CARLOS_TUNNEL_TOKEN": mbtTunnelToken, "CARLOS_RELEASE_PUBKEY": f.in.Frozen.ReleasePubkey, |
| + "CARLOS_HIBERNATE_BUCKET": "carlos-fleet-shop", "CARLOS_HIBERNATE_REGION": "eu-west-1", "CARLOS_HIBERNATE_PREFIX": "instances", |
| + "AWS_SHARED_CREDENTIALS_FILE": "/etc/carlos/credentials", |
| + } |
| + if len(env) != len(want) { |
| + t.Errorf("host.env has %d keys, want %d: %v", len(env), len(want), env) |
| + } |
| + for k, v := range want { |
| + if env[k] != v { |
| + t.Errorf("%s=%q, want %q", k, env[k], v) |
| + } |
| + } |
| + forbidden := []string{"CARLOS_DEPLOYMENT_BUCKET", "CARLOS_DEPLOYMENT_DIR", "CARLOS_HOST_CLAIM", "CARLOS_GROUP_ADMISSION", "AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_CONFIG_FILE", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"} |
| + for _, envs := range append([][]string{}, f.bootEnv...) { |
| + for _, kv := range envs { |
| + for _, k := range forbidden { |
| + if strings.HasPrefix(kv, k+"=") { |
| + t.Errorf("bootstrap env carries %s", k) |
| + } |
| + } |
| + if strings.Contains(kv, mbtToken) { |
| + t.Error("bootstrap env carries the token") |
| + } |
| + } |
| + } |
| + for _, k := range forbidden { |
| + if _, ok := env[k]; ok { |
| + t.Errorf("host.env carries %s", k) |
| + } |
| + } |
| + id := managedboot.IdentityOf(f.in) |
| + withKey, err := managedboot.ManagedHostEnv(id, f.reply, f.in.Frozen, "key-material") |
| + if err != nil || withKey["CARLOS_SECRETS_KEY"] != "key-material" || len(withKey) != len(want)+1 { |
| + t.Errorf("with a secrets key: %v %v", withKey, err) |
| + } |
| +} |
diff --git a/internal/host/managedboot_other.go b/internal/host/managedboot_other.go| new file mode 100644 |
| index 000000000..d88239d4d |
| --- /dev/null |
| +++ b/internal/host/managedboot_other.go |
| @@ -0,0 +1,30 @@ |
| +//go:build !linux |
| + |
| +package host |
| + |
| +import ( |
| + "errors" |
| + "log" |
| + "os" |
| +) |
| + |
| +// errManagedBootLinux: managed boxes are linux only. |
| +var errManagedBootLinux = errors.New("managed boot: managed boxes run linux only") |
| + |
| +// RunSystemManagedBoot refuses: a managed box is a linux box. |
| +func RunSystemManagedBoot(args []string) { |
| + log.Fatalf("system managed-boot: %v", errManagedBootLinux) |
| +} |
| + |
| +func mbEnsureDir(root, abs string, mode os.FileMode, uid int) error { return errManagedBootLinux } |
| +func mbReadRootFile(root, abs string, uid int, limit int64, mode os.FileMode) ([]byte, error) { |
| + return nil, errManagedBootLinux |
| +} |
| +func mbWriteRootFile(root, abs string, body []byte, mode os.FileMode, uid, group int) error { |
| + return errManagedBootLinux |
| +} |
| +func mbMove(root, src, dst string) error { return errManagedBootLinux } |
| +func mbSyncDir(path string) error { return errManagedBootLinux } |
| +func mbShred(path string) error { return errManagedBootLinux } |
| +func mbRemoveTree(root, abs string, uid int) error { return errManagedBootLinux } |
| +func mbHashExec(path string, uid, gid int) (string, error) { return "", errManagedBootLinux } |
diff --git a/internal/host/managedstable.go b/internal/host/managedstable.go| new file mode 100644 |
| index 000000000..d4984eb36 |
| --- /dev/null |
| +++ b/internal/host/managedstable.go |
| @@ -0,0 +1,72 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +var mbSHA256RE = regexp.MustCompile(`^[0-9a-f]{64}$`) |
| + |
| +// mbArtifactLimit is the update path's artifact bound; a test lowers it. |
| +var mbArtifactLimit = systemArtifactLimit |
| + |
| +// installManagedStable installs the stable channel's linux-arm64 router |
| +// release at root+/opt/carlos/carlos, root 0755. The pointer must verify |
| +// under pub, the deployment's root key (GetSystemPointer refuses a scoped |
| +// grant), and the artifact is fetched through s into the root-only boot |
| +// directory against the signed digest, then renamed into place and hashed |
| +// again there. It reuses the verification primitives only: install-channel's |
| +// group and floor checks assume a deployment-bucket identity a managed box |
| +// does not have. |
| +func installManagedStable(ctx context.Context, s release.Store, pub ed25519.PublicKey, root string) (version string, err error) { |
| + version, _, err = installManagedStableAs(ctx, s, pub, root, 0, 0) |
| + return version, err |
| +} |
| + |
| +// installManagedStableAs is installManagedStable with root's uid and gid |
| +// given, and the signed digest returned for the check before first exec. |
| +func installManagedStableAs(ctx context.Context, s release.Store, pub ed25519.PublicKey, root string, uid, gid int) (string, string, error) { |
| + p, _, err := release.GetSystemPointer(ctx, s, pub, release.SystemComponentRouter, "stable") |
| + if err != nil { |
| + return "", "", fmt.Errorf("managed boot: the stable channel does not verify: %w", err) |
| + } |
| + platform := managedboot.SeedArtifactPlatform |
| + art, ok := p.Current.Artifacts[platform] |
| + if !ok { |
| + return "", "", fmt.Errorf("managed boot: stable %s has no %s artifact", p.Current.Version, platform) |
| + } |
| + if art.Key != release.SystemArtifactKey(p.Current.Version, platform) || !mbSHA256RE.MatchString(art.SHA256) { |
| + return "", "", fmt.Errorf("managed boot: stable %s names an artifact outside its own release", p.Current.Version) |
| + } |
| + part := filepath.Join(root, mbStablePart) |
| + _ = os.Remove(part) |
| + if err = release.FetchToFile(ctx, s, art.Key, part, mbArtifactLimit, art.SHA256); err != nil { |
| + return "", "", fmt.Errorf("managed boot: stable %s: %w", p.Current.Version, err) |
| + } |
| + if err = os.Chmod(part, 0o755); err != nil { |
| + _ = os.Remove(part) |
| + return "", "", err |
| + } |
| + if err = mbEnsureDir(root, "/opt/carlos", 0o755, uid); err != nil { |
| + _ = os.Remove(part) |
| + return "", "", err |
| + } |
| + if err = mbMove(root, mbStablePart, mbStableBinary); err != nil { |
| + _ = os.Remove(part) |
| + return "", "", err |
| + } |
| + got, err := mbHashExec(filepath.Join(root, mbStableBinary), uid, gid) |
| + if err != nil || got != art.SHA256 { |
| + _ = os.Remove(filepath.Join(root, mbStableBinary)) |
| + return "", "", errors.Join(fmt.Errorf("managed boot: stable %s changed after its fetch", p.Current.Version), err) |
| + } |
| + return p.Current.Version, art.SHA256, nil |
| +} |
diff --git a/internal/managedboot/bootinput.go b/internal/managedboot/bootinput.go| new file mode 100644 |
| index 000000000..e072cebcd |
| --- /dev/null |
| +++ b/internal/managedboot/bootinput.go |
| @@ -0,0 +1,60 @@ |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "io" |
| +) |
| + |
| +// EncodeScrubbedBootInput is BootInputPath's bytes once the trade has |
| +// committed: the same canonical LaunchInput with the token removed. Every |
| +// later boot reads this form; nothing after the commit needs the token. |
| +func EncodeScrubbedBootInput(in LaunchInput) ([]byte, error) { |
| + in.Token = "" |
| + if err := validScrubbed(in); err != nil { |
| + return nil, err |
| + } |
| + b, err := encodeLaunchInput(in) |
| + if err != nil { |
| + return nil, errInvalid |
| + } |
| + return append(b, '\n'), nil |
| +} |
| + |
| +// DecodeBootInput reads BootInputPath on any boot: the rendered input |
| +// (DecodeLaunchInput's rules) or its scrubbed form, which is the same |
| +// canonical encoding with an empty token. scrubbed reports the latter. |
| +func DecodeBootInput(b []byte) (in LaunchInput, scrubbed bool, err error) { |
| + if in, err = DecodeLaunchInput(b); err == nil { |
| + return in, false, nil |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(b)) |
| + dec.DisallowUnknownFields() |
| + if dec.Decode(&in) != nil { |
| + return LaunchInput{}, false, errInvalid |
| + } |
| + var extra any |
| + if dec.Decode(&extra) != io.EOF { |
| + return LaunchInput{}, false, errInvalid |
| + } |
| + if in.Token != "" { |
| + return LaunchInput{}, false, errInvalid |
| + } |
| + if err = validScrubbed(in); err != nil { |
| + return LaunchInput{}, false, err |
| + } |
| + canonical, err := encodeLaunchInput(in) |
| + if err != nil || !bytes.Equal(canonical, bytes.TrimSuffix(b, []byte("\n"))) { |
| + return LaunchInput{}, false, errInvalid |
| + } |
| + return in, true, nil |
| +} |
| + |
| +// validScrubbed is LaunchInput.Validate for an input whose token is gone. |
| +func validScrubbed(in LaunchInput) error { |
| + if in.Token != "" { |
| + return errInvalid |
| + } |
| + in.Token = "0000000000000000000000000000000000000000000000000000000000000000" |
| + return in.Validate() |
| +} |
diff --git a/internal/managedboot/enrolwire.go b/internal/managedboot/enrolwire.go| new file mode 100644 |
| index 000000000..bc5960006 |
| --- /dev/null |
| +++ b/internal/managedboot/enrolwire.go |
| @@ -0,0 +1,70 @@ |
| +package managedboot |
| + |
| +import ( |
| + "errors" |
| + "regexp" |
| + "strings" |
| +) |
| + |
| +// EnrolPath is the console's enrolment door, under the frozen origin. |
| +const EnrolPath = "/api/fleet/enrol" |
| + |
| +// EnrolRequest is the box's one trade: its token and what it found in /data. |
| +// The console's managedEnrolRequest reads the same JSON. |
| +type EnrolRequest struct { |
| + Token string `json:"token"` |
| + DataDirEmpty bool `json:"data_dir_empty"` |
| + DataDirEntries int `json:"data_dir_entries"` |
| +} |
| + |
| +// EnrolCredentials is the fleet user's access key: ID is the access-key ID |
| +// and Secret the secret access key's UTF-8 bytes (base64 on the wire). |
| +type EnrolCredentials struct { |
| + ID string `json:"id"` |
| + Secret []byte `json:"secret"` |
| +} |
| + |
| +// EnrolReply is the console's managedEnrolReply as the box reads it. |
| +type EnrolReply struct { |
| + Fleet string `json:"fleet"` |
| + Label string `json:"label"` |
| + TunnelURL string `json:"tunnel_url"` |
| + TunnelToken string `json:"tunnel_token"` |
| + Credentials EnrolCredentials `json:"credentials"` |
| + Joining bool `json:"joining"` |
| + Bucket string `json:"bucket"` |
| + BucketRegion string `json:"bucket_region"` |
| + Operation string `json:"op"` |
| +} |
| + |
| +var ( |
| + bucketRE = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$`) |
| + regionRE = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]{1,2}$`) |
| + tunnelTokenRE = regexp.MustCompile(`^[0-9a-f]{64}$`) |
| + accessKeyRE = regexp.MustCompile(`^[A-Za-z0-9]{16,128}$`) |
| + secretKeyRE = regexp.MustCompile(`^[A-Za-z0-9/+=]{16,128}$`) |
| + errReply = errors.New("managedboot: the enrolment reply does not match this box") |
| +) |
| + |
| +// CheckReply holds a 200 reply to the box's frozen identity: the same fleet, |
| +// label and operation, the frozen tunnel host, a joining box, and complete |
| +// credentials and storage. The error never carries a reply value. |
| +func CheckReply(in LaunchInput, r EnrolReply) error { |
| + switch { |
| + case r.Fleet != in.Fleet || r.Label != in.Label || r.Operation != in.Op: |
| + return errReply |
| + case r.TunnelURL != "https://"+in.Frozen.TunnelHost: |
| + return errReply |
| + case !r.Joining: |
| + return errReply |
| + case !tunnelTokenRE.MatchString(r.TunnelToken): |
| + return errReply |
| + case !accessKeyRE.MatchString(r.Credentials.ID) || !secretKeyRE.MatchString(string(r.Credentials.Secret)): |
| + return errReply |
| + case !bucketRE.MatchString(r.Bucket) || strings.Contains(r.Bucket, ".."): |
| + return errReply |
| + case !regionRE.MatchString(r.BucketRegion): |
| + return errReply |
| + } |
| + return nil |
| +} |
diff --git a/internal/managedboot/hostenv.go b/internal/managedboot/hostenv.go| new file mode 100644 |
| index 000000000..f82772478 |
| --- /dev/null |
| +++ b/internal/managedboot/hostenv.go |
| @@ -0,0 +1,66 @@ |
| +package managedboot |
| + |
| +import ( |
| + "errors" |
| + "regexp" |
| +) |
| + |
| +// CredentialsPath is the fleet user's static credentials, root:carlos 0640. |
| +const CredentialsPath = "/etc/carlos/credentials" |
| + |
| +// HostEnvPath is the box's host.env, root:root 0600. |
| +const HostEnvPath = "/etc/carlos/host.env" |
| + |
| +var secretsKeyRE = regexp.MustCompile(`^[A-Za-z0-9+/=_:.-]{1,512}$`) |
| + |
| +// ManagedHostEnv is a managed box's whole host.env: its fleet identity, |
| +// tunnel, release key and fleet storage, and the fleet secrets key when it |
| +// has one. It never names a deployment bucket or directory, a host claim, a |
| +// group admission or an AWS profile: a managed box holds no deployment |
| +// authority. id must be the identity the box enrolled from, and r a reply |
| +// CheckReply accepted for it. |
| +func ManagedHostEnv(id Identity, r EnrolReply, f Frozen, secretsKey string) (map[string]string, error) { |
| + if err := id.Validate(); err != nil { |
| + return nil, err |
| + } |
| + if err := f.Validate(); err != nil { |
| + return nil, err |
| + } |
| + in := LaunchInput{Frozen: f, Fleet: id.Fleet, Label: id.Label, Op: id.Op} |
| + if id.ReleasePubkey != f.ReleasePubkey { |
| + return nil, errIdentity |
| + } |
| + if err := CheckReply(in, r); err != nil { |
| + return nil, err |
| + } |
| + if secretsKey != "" && !secretsKeyRE.MatchString(secretsKey) { |
| + return nil, errors.New("managedboot: invalid fleet secrets key") |
| + } |
| + env := map[string]string{ |
| + "CARLOS_REGION": "fleet/" + id.Fleet, |
| + "CARLOS_FLEET": id.Fleet, |
| + "CARLOS_FLEET_BOX": id.Label, |
| + "CARLOS_TUNNEL_NAME": id.Fleet + "/" + id.Label, |
| + "CARLOS_TUNNEL_URL": r.TunnelURL, |
| + "CARLOS_TUNNEL_TOKEN": r.TunnelToken, |
| + "CARLOS_RELEASE_PUBKEY": f.ReleasePubkey, |
| + "CARLOS_HIBERNATE_BUCKET": r.Bucket, |
| + "CARLOS_HIBERNATE_REGION": r.BucketRegion, |
| + "CARLOS_HIBERNATE_PREFIX": "instances", |
| + "AWS_SHARED_CREDENTIALS_FILE": CredentialsPath, |
| + } |
| + if secretsKey != "" { |
| + env["CARLOS_SECRETS_KEY"] = secretsKey |
| + } |
| + return env, nil |
| +} |
| + |
| +// RenderCredentials is CredentialsPath's bytes: one default profile with the |
| +// reply's literal keys. CheckReply has already held both to a character set |
| +// with no whitespace, comment or quote characters. |
| +func RenderCredentials(c EnrolCredentials) ([]byte, error) { |
| + if !accessKeyRE.MatchString(c.ID) || !secretKeyRE.MatchString(string(c.Secret)) { |
| + return nil, errors.New("managedboot: invalid credentials") |
| + } |
| + return []byte("[default]\naws_access_key_id = " + c.ID + "\naws_secret_access_key = " + string(c.Secret) + "\n"), nil |
| +} |
diff --git a/internal/managedboot/identity.go b/internal/managedboot/identity.go| new file mode 100644 |
| index 000000000..458b2fc3a |
| --- /dev/null |
| +++ b/internal/managedboot/identity.go |
| @@ -0,0 +1,89 @@ |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| +) |
| + |
| +const ( |
| + // IdentityPath says "this is a managed box": root:root 0644 in the |
| + // root-owned /etc/carlos, written once at the first boot's commit. |
| + IdentityPath = "/etc/carlos/managed-box.json" |
| + // RootAdmissionDir is root:root 0700, created at the commit; Task 3's |
| + // verified admission owns what is inside it. |
| + RootAdmissionDir = "/var/lib/carlos-managed-root" |
| + // AdmittedMarker is written once by root's verified admission and never |
| + // removed. Every workload unit is conditioned on it. |
| + AdmittedMarker = RootAdmissionDir + "/admitted" |
| + // KeyStatusPath is the fleet secrets key's status, root 0644 (Task 4). |
| + KeyStatusPath = "/etc/carlos/managed-key-status.json" |
| +) |
| + |
| +// Identity is the managed box's root-owned record of who it is and which |
| +// key its console signs with. |
| +type Identity struct { |
| + Fleet string `json:"fleet"` |
| + Label string `json:"label"` |
| + Op string `json:"op"` |
| + ReleasePubkey string `json:"release_pubkey"` |
| +} |
| + |
| +var errIdentity = errors.New("managedboot: invalid managed box identity") |
| + |
| +// Validate checks every field against the same allowlists as LaunchInput. |
| +func (id Identity) Validate() error { |
| + if !nameRE.MatchString(id.Fleet) || !nameRE.MatchString(id.Label) || !opRE.MatchString(id.Op) || !validPubkey(id.ReleasePubkey) { |
| + return errIdentity |
| + } |
| + return nil |
| +} |
| + |
| +// IdentityOf is the identity a box enrolled from in records. |
| +func IdentityOf(in LaunchInput) Identity { |
| + return Identity{Fleet: in.Fleet, Label: in.Label, Op: in.Op, ReleasePubkey: in.Frozen.ReleasePubkey} |
| +} |
| + |
| +// EncodeIdentity is the one encoding of IdentityPath's bytes. |
| +func EncodeIdentity(id Identity) ([]byte, error) { |
| + if err := id.Validate(); err != nil { |
| + return nil, err |
| + } |
| + b, err := json.Marshal(id) |
| + if err != nil { |
| + return nil, errIdentity |
| + } |
| + return append(b, '\n'), nil |
| +} |
| + |
| +// ParseIdentity reads IdentityPath's bytes strictly: unknown fields, |
| +// trailing values, invalid fields and any encoding other than |
| +// EncodeIdentity's are refused. |
| +func ParseIdentity(b []byte) (Identity, error) { |
| + var id Identity |
| + dec := json.NewDecoder(bytes.NewReader(b)) |
| + dec.DisallowUnknownFields() |
| + if dec.Decode(&id) != nil { |
| + return Identity{}, errIdentity |
| + } |
| + var extra any |
| + if dec.Decode(&extra) != io.EOF { |
| + return Identity{}, errIdentity |
| + } |
| + canonical, err := EncodeIdentity(id) |
| + if err != nil || !bytes.Equal(canonical, b) { |
| + return Identity{}, errIdentity |
| + } |
| + return id, nil |
| +} |
| + |
| +// LoadIdentity reads root+IdentityPath. The bool is "this is a managed |
| +// box": false with no error only when the file (or /etc/carlos) is absent. |
| +// Every component from root down is opened without following a symlink and |
| +// must be owned by root and not writable by group or other; a file that is |
| +// there but fails any check is a managed box with an error, never "not |
| +// managed". |
| +func LoadIdentity(root string) (Identity, bool, error) { |
| + return loadIdentity(root, 0) |
| +} |
diff --git a/internal/managedboot/identity_linux.go b/internal/managedboot/identity_linux.go| new file mode 100644 |
| index 000000000..51aa48147 |
| --- /dev/null |
| +++ b/internal/managedboot/identity_linux.go |
| @@ -0,0 +1,68 @@ |
| +//go:build linux |
| + |
| +package managedboot |
| + |
| +import ( |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// maxIdentityBytes bounds IdentityPath; the real file is under 200 bytes. |
| +const maxIdentityBytes = 4096 |
| + |
| +// loadIdentity is LoadIdentity with the expected owner uid as a parameter, |
| +// so an unprivileged test can own its fake root. |
| +func loadIdentity(root string, owner int) (Identity, bool, error) { |
| + if root == "" { |
| + root = "/" |
| + } |
| + fd, err := unix.Open(root, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return Identity{}, true, err |
| + } |
| + parts := strings.Split(strings.TrimPrefix(filepath.Clean(IdentityPath), "/"), "/") |
| + for n, part := range parts { |
| + last := n == len(parts)-1 |
| + flags := unix.O_RDONLY | unix.O_CLOEXEC | unix.O_NOFOLLOW |
| + if last { |
| + flags |= unix.O_NONBLOCK |
| + } else { |
| + flags |= unix.O_DIRECTORY |
| + } |
| + next, err := unix.Openat(fd, part, flags, 0) |
| + unix.Close(fd) |
| + if errors.Is(err, unix.ENOENT) { |
| + // No /etc/carlos or no identity file: not a managed box. |
| + return Identity{}, false, nil |
| + } |
| + if err != nil { |
| + return Identity{}, true, err |
| + } |
| + fd = next |
| + var st unix.Stat_t |
| + if err = unix.Fstat(fd, &st); err != nil { |
| + unix.Close(fd) |
| + return Identity{}, true, err |
| + } |
| + if int(st.Uid) != owner || st.Mode&0o022 != 0 || (last && (st.Mode&unix.S_IFMT != unix.S_IFREG || st.Nlink != 1)) { |
| + unix.Close(fd) |
| + return Identity{}, true, errIdentity |
| + } |
| + } |
| + f := os.NewFile(uintptr(fd), IdentityPath) |
| + defer f.Close() |
| + b, err := io.ReadAll(io.LimitReader(f, maxIdentityBytes+1)) |
| + if err != nil { |
| + return Identity{}, true, err |
| + } |
| + if len(b) > maxIdentityBytes { |
| + return Identity{}, true, errIdentity |
| + } |
| + id, err := ParseIdentity(b) |
| + return id, true, err |
| +} |
diff --git a/internal/managedboot/identity_linux_test.go b/internal/managedboot/identity_linux_test.go| new file mode 100644 |
| index 000000000..b1fe086a9 |
| --- /dev/null |
| +++ b/internal/managedboot/identity_linux_test.go |
| @@ -0,0 +1,154 @@ |
| +//go:build linux |
| + |
| +package managedboot |
| + |
| +import ( |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestManagedBootLoadIdentity(t *testing.T) { |
| + in := goldenInput() |
| + id := IdentityOf(in) |
| + body, err := EncodeIdentity(id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + setup := func(t *testing.T) string { |
| + root := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(root, "etc/carlos"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(root, IdentityPath), body, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + return root |
| + } |
| + uid := os.Getuid() |
| + t.Run("valid", func(t *testing.T) { |
| + got, managed, err := loadIdentity(setup(t), uid) |
| + if err != nil || !managed || got != id { |
| + t.Fatalf("%+v %v %v", got, managed, err) |
| + } |
| + }) |
| + t.Run("absent is not managed", func(t *testing.T) { |
| + root := t.TempDir() |
| + if _, managed, err := loadIdentity(root, uid); managed || err != nil { |
| + t.Fatalf("no /etc/carlos: managed=%v %v", managed, err) |
| + } |
| + if err := os.MkdirAll(filepath.Join(root, "etc/carlos"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, managed, err := loadIdentity(root, uid); managed || err != nil { |
| + t.Fatalf("no identity file: managed=%v %v", managed, err) |
| + } |
| + }) |
| + refusals := map[string]func(t *testing.T, root string){ |
| + "wrong owner": func(t *testing.T, root string) {}, |
| + "group-writable dir": func(t *testing.T, root string) { |
| + _ = os.Chmod(filepath.Join(root, "etc/carlos"), 0o775) |
| + }, |
| + "world-writable file": func(t *testing.T, root string) { |
| + _ = os.Chmod(filepath.Join(root, IdentityPath), 0o646) |
| + }, |
| + "symlinked file": func(t *testing.T, root string) { |
| + p := filepath.Join(root, IdentityPath) |
| + _ = os.Rename(p, p+".real") |
| + _ = os.Symlink("managed-box.json.real", p) |
| + }, |
| + "symlinked dir": func(t *testing.T, root string) { |
| + d := filepath.Join(root, "etc/carlos") |
| + _ = os.Rename(d, d+".real") |
| + _ = os.Symlink("carlos.real", d) |
| + }, |
| + "hard link": func(t *testing.T, root string) { |
| + _ = os.Link(filepath.Join(root, IdentityPath), filepath.Join(root, "etc/carlos/other")) |
| + }, |
| + "tampered": func(t *testing.T, root string) { |
| + _ = os.WriteFile(filepath.Join(root, IdentityPath), []byte(strings.Replace(string(body), "box-1", "box-2", 1)+" "), 0o644) |
| + }, |
| + "unknown field": func(t *testing.T, root string) { |
| + _ = os.WriteFile(filepath.Join(root, IdentityPath), []byte(strings.Replace(string(body), "{", `{"admitted":true,`, 1)), 0o644) |
| + }, |
| + } |
| + for name, mutate := range refusals { |
| + t.Run(name, func(t *testing.T) { |
| + root := setup(t) |
| + mutate(t, root) |
| + owner := uid |
| + if name == "wrong owner" { |
| + owner = uid + 1 |
| + } |
| + if _, managed, err := loadIdentity(root, owner); err == nil || !managed { |
| + t.Fatalf("accepted: managed=%v %v", managed, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestManagedBootInputScrub(t *testing.T) { |
| + in := goldenInput() |
| + raw, err := encodeLaunchInput(in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got, scrubbed, err := DecodeBootInput(append(raw, '\n')) |
| + if err != nil || scrubbed || got != in { |
| + t.Fatalf("rendered input: %v %v", scrubbed, err) |
| + } |
| + clean, err := EncodeScrubbedBootInput(in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(clean), in.Token) { |
| + t.Fatal("the scrubbed input holds the token") |
| + } |
| + got, scrubbed, err = DecodeBootInput(clean) |
| + want := in |
| + want.Token = "" |
| + if err != nil || !scrubbed || got != want { |
| + t.Fatalf("scrubbed input: %+v %v %v", got, scrubbed, err) |
| + } |
| + if _, err := DecodeLaunchInput(clean); err == nil { |
| + t.Error("DecodeLaunchInput took a scrubbed input") |
| + } |
| + for _, bad := range []string{ |
| + strings.Replace(string(clean), `"fleet":"shop"`, `"fleet":"Shop"`, 1), |
| + strings.Replace(string(clean), `"token":""`, `"Token":""`, 1), |
| + strings.Replace(string(clean), `"token":""`, `"token":"","extra":1`, 1), |
| + string(clean) + "{}", |
| + strings.Replace(string(clean), ",", ", ", 1), |
| + } { |
| + if _, _, err := DecodeBootInput([]byte(bad)); err == nil { |
| + t.Errorf("accepted %q", bad) |
| + } |
| + } |
| +} |
| + |
| +func TestManagedBootHostEnvRefusals(t *testing.T) { |
| + in := goldenInput() |
| + id := IdentityOf(in) |
| + r := EnrolReply{Fleet: "shop", Label: "box-1", TunnelURL: "https://" + in.Frozen.TunnelHost, TunnelToken: strings.Repeat("7a", 32), |
| + Credentials: EnrolCredentials{ID: "AKIAEXAMPLEKEY000001", Secret: []byte("SECRETsentinelSECRETsentinel0123456789ab")}, Joining: true, |
| + Bucket: "carlos-fleet-shop", BucketRegion: "eu-west-1", Operation: in.Op} |
| + if _, err := ManagedHostEnv(id, r, in.Frozen, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + other := id |
| + other.ReleasePubkey = strings.Repeat("A", 43) + "=" |
| + if _, err := ManagedHostEnv(other, r, in.Frozen, ""); err == nil { |
| + t.Error("an identity with another release key was accepted") |
| + } |
| + if _, err := ManagedHostEnv(id, r, in.Frozen, "a b"); err == nil { |
| + t.Error("an unsafe secrets key was accepted") |
| + } |
| + creds, err := RenderCredentials(r.Credentials) |
| + if err != nil || string(creds) != "[default]\naws_access_key_id = AKIAEXAMPLEKEY000001\naws_secret_access_key = SECRETsentinelSECRETsentinel0123456789ab\n" { |
| + t.Errorf("credentials %q %v", creds, err) |
| + } |
| + if _, err := RenderCredentials(EnrolCredentials{ID: "AKIAEXAMPLEKEY000001", Secret: []byte("x #comment")}); err == nil { |
| + t.Error("an unsafe secret was rendered") |
| + } |
| +} |
diff --git a/internal/managedboot/identity_other.go b/internal/managedboot/identity_other.go| new file mode 100644 |
| index 000000000..0156a29f8 |
| --- /dev/null |
| +++ b/internal/managedboot/identity_other.go |
| @@ -0,0 +1,8 @@ |
| +//go:build !linux |
| + |
| +package managedboot |
| + |
| +// Managed boxes are linux only; nothing else is one. |
| +func loadIdentity(root string, owner int) (Identity, bool, error) { |
| + return Identity{}, false, nil |
| +} |
diff --git a/internal/managedboot/units.go b/internal/managedboot/units.go| new file mode 100644 |
| index 000000000..24f4c4b43 |
| --- /dev/null |
| +++ b/internal/managedboot/units.go |
| @@ -0,0 +1,175 @@ |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| +) |
| + |
| +// AdmissionDropInName sorts after every platform drop-in (50-carlos-*, |
| +// config-sync's env drop-ins), so an earlier empty ConditionPathExists= |
| +// reset is always followed by this assignment. |
| +const AdmissionDropInName = "zz-carlos-managed-admission.conf" |
| + |
| +// AdmissionDropIn is the body of every workload unit's admission drop-in. |
| +const AdmissionDropIn = "[Unit]\nConditionPathExists=" + AdmittedMarker + "\n" |
| + |
| +// ControlDropInName lets the root control service write the admission |
| +// directory under its ProtectSystem=strict sandbox. |
| +const ControlDropInName = "60-carlos-managed-root.conf" |
| + |
| +// ControlDropIn is ControlDropInName's body. |
| +const ControlDropIn = "[Service]\nReadWritePaths=" + RootAdmissionDir + "\n" |
| + |
| +// ControlUnit is the unit ControlDropInName belongs to. |
| +const ControlUnit = "carlos-instance-control.service" |
| + |
| +// WorkloadUnits are the embedded units that run tenant code or tenant data |
| +// work. On a managed box each carries the admission drop-in, so systemd |
| +// itself refuses to start one before root admits the box. |
| +var WorkloadUnits = []string{ |
| + "carlos-app@.service", |
| + "carlos-app@.socket", |
| + "carlos-instance@.service", |
| + "carlos-instance-gen@.service", |
| + "carlos-instance-sidecar@.service", |
| + "carlos-instance-cmd@.service", |
| + "carlos-instance-tty@.service", |
| + "carlos-instance-seed@.service", |
| + "carlos-instance-rootfs@.service", |
| + "carlos-instance-rootfs-gen@.service", |
| + "carlos-instance-rootfs-cmd@.service", |
| + "carlos-instance-rootfs-tty@.service", |
| + "carlos-instance-rootfs-worker@.service", |
| + "carlos-demo-build@.service", |
| + "carlos-demo-snapshot@.service", |
| + "carlos-dbread@.service", |
| +} |
| + |
| +// MaintenanceUnits are the platform's own units. They carry no admission |
| +// condition: a joining box must still bootstrap, report status, take |
| +// updates and answer probes. |
| +var MaintenanceUnits = []string{ |
| + "carlos-edge.service", |
| + "carlos-relay.service", |
| + "carlos-adopt.service", |
| + "carlos-adopt.path", |
| + "carlos-adopt.timer", |
| + "carlos-config-sync.service", |
| + "carlos-system-update.service", |
| + "carlos-system-update.path", |
| + "carlos-system-recover.service", |
| + "carlos-restart.service", |
| + "carlos-restart.path", |
| + "carlos-stage.service", |
| + "carlos-stage.path", |
| + "carlos-instance-control.service", |
| + "carlos-instance-control.socket", |
| + "carlos-instance-probe.service", |
| + "carlos-instance-rootfs-probe.service", |
| + "carlos-litestream.service", |
| + "carlos-hibernate-verify.service", |
| + "carlos-hibernate-verify.timer", |
| + "carlos-restore-verify.service", |
| + "carlos-restore-verify.timer", |
| + "carlos-dbread.socket", |
| + "carlos.slice", |
| + "carlos-instances.slice", |
| + "carlos-demo-builds.slice", |
| + "data-instances.mount", |
| + "run-carlos-instances.mount", |
| + "run-carlos-logs.mount", |
| + "carlos-managed-boot.service", |
| +} |
| + |
| +var unitNameRE = regexp.MustCompile(`^[A-Za-z0-9:_.\\@-]{1,200}\.(service|socket)$`) |
| + |
| +// InstallAdmissionDropIns writes <etcDir>/<unit>.d/AdmissionDropInName for |
| +// every WorkloadUnits template and every declared named unit. A named unit |
| +// that is a maintenance unit, or not a service or socket name, is refused |
| +// before anything is written. Present, exact drop-ins are left alone, so a |
| +// second call changes nothing; a missing or altered one is rewritten. |
| +func InstallAdmissionDropIns(etcDir string, namedUnits []string) (changed bool, err error) { |
| + units := append([]string(nil), WorkloadUnits...) |
| + for _, u := range namedUnits { |
| + if slices.Contains(MaintenanceUnits, u) || !unitNameRE.MatchString(u) { |
| + return false, errors.New("managedboot: a named unit cannot carry the admission condition: " + u) |
| + } |
| + if !slices.Contains(units, u) { |
| + units = append(units, u) |
| + } |
| + } |
| + for _, u := range units { |
| + c, err := ensureDropIn(etcDir, u, AdmissionDropInName, AdmissionDropIn) |
| + if err != nil { |
| + return changed, err |
| + } |
| + changed = changed || c |
| + } |
| + return changed, nil |
| +} |
| + |
| +// InstallControlDropIn writes the control service's ReadWritePaths drop-in. |
| +func InstallControlDropIn(etcDir string) (bool, error) { |
| + return ensureDropIn(etcDir, ControlUnit, ControlDropInName, ControlDropIn) |
| +} |
| + |
| +// ensureDropIn makes <etcDir>/<unit>.d/<name> a 0644 regular file holding |
| +// body: temp file, fsync, rename, directory fsync. Neither the directory |
| +// nor the file may be a symlink. |
| +func ensureDropIn(etcDir, unit, name, body string) (bool, error) { |
| + dir := filepath.Join(etcDir, unit+".d") |
| + if st, err := os.Lstat(dir); errors.Is(err, os.ErrNotExist) { |
| + if err = os.Mkdir(dir, 0o755); err != nil { |
| + return false, err |
| + } |
| + if err = os.Chmod(dir, 0o755); err != nil { |
| + return false, err |
| + } |
| + } else if err != nil { |
| + return false, err |
| + } else if !st.IsDir() { |
| + return false, errors.New("managedboot: " + dir + " is not a directory") |
| + } |
| + path := filepath.Join(dir, name) |
| + if st, err := os.Lstat(path); err == nil && st.Mode().IsRegular() && st.Mode().Perm() == 0o644 { |
| + if got, err := os.ReadFile(path); err == nil && bytes.Equal(got, []byte(body)) { |
| + return false, nil |
| + } |
| + } |
| + var suffix [8]byte |
| + if _, err := rand.Read(suffix[:]); err != nil { |
| + return false, err |
| + } |
| + tmp := filepath.Join(dir, "."+name+"."+hex.EncodeToString(suffix[:])) |
| + f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) |
| + if err != nil { |
| + return false, err |
| + } |
| + defer os.Remove(tmp) |
| + if err = f.Chmod(0o644); err == nil { |
| + if _, err = f.WriteString(body); err == nil { |
| + err = f.Sync() |
| + } |
| + } |
| + if cerr := f.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + if err = os.Rename(tmp, path); err != nil { |
| + return false, err |
| + } |
| + d, err := os.Open(dir) |
| + if err != nil { |
| + return true, err |
| + } |
| + defer d.Close() |
| + return true, d.Sync() |
| +} |
diff --git a/internal/provision/managed_fleets_2b2_census_test.go b/internal/provision/managed_fleets_2b2_census_test.go| index c1372a149..dfa04683e 100644 |
| --- a/internal/provision/managed_fleets_2b2_census_test.go |
| +++ b/internal/provision/managed_fleets_2b2_census_test.go |
| @@ -10,8 +10,15 @@ package provision |
| // from s.cfg.Releases. It writes no SQL row and no store object and never |
| // consumes the token. The existing instances literal stays key-site. |
| // Witnessed by TestManagedSeedDoor and TestManagedCloudInitScriptRun. |
| +// |
| +// Task 2 adds no record write: |
| +// - managedboot.ManagedHostEnv builds a managed box's host.env map. Its |
| +// "instances" literal is the CARLOS_HIBERNATE_PREFIX value (the fleet |
| +// bucket's instance prefix the agent already uses), not a record key; it |
| +// writes nothing. Witnessed by TestManagedBootNoDeploymentAuthority. |
| func managedFleets2b2WriteCensusInventory() []censusEntry { |
| entries := append([]censusEntry(nil), managedFleets2b1WriteCensusInventory()...) |
| + entries = append(entries, censusEntry{"internal/managedboot/hostenv.go", "ManagedHostEnv", "key-site", "lit:instances", "475c33aef5f55a5ffcaa97f8caa8eb30b0027a0d19486e88f1980909e468b5f5"}) |
| r := censusEntry{"internal/console/server.go", "NewServer", "key-site", "lit:instances", "1f8e69330bc04863e3a1d26da565d0996d3d44f66664404477dd6e94f42049bc"} |
| for i, e := range entries { |
| if e.File == r.File && e.Unit == r.Unit { |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index d3c1d01da..5142427af 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -131,3 +131,4 @@ plan14-root-reads-instance-restore-658-cli.tsv b970bb28c5a633d2572a1da549030e925 |
| plan14-root-reads-instance-stop-execstop-528.tsv 75fb3eb24d0bf3a8405b929675d919ec88f15386d43e9ff687ce138a7ed968a4 |
| plan14-root-reads-region-ha-shutting-down-retry.tsv 75fb3eb24d0bf3a8405b929675d919ec88f15386d43e9ff687ce138a7ed968a4 |
| plan14-root-reads-managed-fleets-2b1.tsv d467adec3d86ae220afe98269aa226e87adba1b83e31eda214ceea0f02720a98 |
| +plan14-root-reads-managed-fleets-2b2.tsv 7bbffc3b2a59f79f6aefdd6a0a344976f51f36eda4b6a7499c5027f6a712dbe2 |
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv| new file mode 100644 |
| index 000000000..ab13deb72 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv |
| @@ -0,0 +1,52 @@ |
| +# Census overlay managed-fleets-2b2, written by census-propose (#369). census-ruling-managed-fleets-2b2, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-managed-fleets-2b2.md. |
| +# 2 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 22 new dispositions: 0 reads re-frozen at their disposition with the claim, 22 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 4ad7aad0079e2020df642fc2cc6ca1e33b0e6caacdbb4e6acb81279252eadb29 internal/host/managedboot.go const#1 legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=managed-boot path and limit constants; data only data-literal@523 765b471b3a8004d57f6f1d4d73582e35ee10a1041def47f7209e7ade19023a47 |
| +@legacy f4bdcc19db302182fd9c793def03df390df710596c8bd0661c0cffa6d0974864 internal/host/managedboot.go managedBoot.attest legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat and list /data (names only) before anything writes under it, to report absent/empty/count in the enrol request; no file content read file:Lstat@57,file:ReadDir@209 7a32d2fcf1179f2afa5127839bbde21d755de536c8f329b71486c5c8248c174a |
| +@legacy e0ce88af5d49d23ad1fdb4779d535f9e9a4e8cef275ae528ac9c964d612ea1ae internal/host/managedboot.go managedBoot.clearStaging legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lists root-owned 0700 BootDir for staging.* left by a cut-off boot and shreds them via mbRemoveTree file:ReadDir@62 a7c11f7fdb4b17d34ca99b11cd392ffa787c2d6a30ef0ecdc77ea4f7ac61dcf1 |
| +@legacy 8955cc057d9b2fae30d02379ac6a460434fb62d3815d3ba6a5e20c00da41c647 internal/host/managedboot.go managedBoot.post legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=reads the enrol HTTPS reply body (64 KiB cap) from the frozen console origin; no file read file:ReadAll@600 88bbfb6acf5e7acc4cbcbe05edfa3d379e5d333dc61699d32856d17cf323caec |
| +@legacy 7ffd16d9d597e628929eddcfbebaa25697cfb3568c292822263b482c07f46492 internal/host/managedboot.go managedBoot.present legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat of fixed root-owned paths (BootDir markers, committed dir, seed request); existence only file:Lstat@69 289bacf43547b6913d9aa268c800f975263c9c1fc96f920486c1aca5c6b01940 |
| +@legacy 359d509f0534a61fb13d3a961b574e6540cbd4164a1fab1c1622350fc76c0f6a internal/host/managedboot.go managedBoot.scrub legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=walks cloud-init trees (/var/lib/cloud, /run/cloud-init, cloud-init logs) and BootDir without following symlinks and shreds regular files holding the used token; nothing read is executed or trusted file:WalkDir@174 605ad097ff1799d6419f167aa2e8bbf98cc97d4b1f25ac81ce20d3210c69aed1 |
| +@legacy 193bcb60c81a5e53008a786d4335d842d0492a2ab4419f227a9ae5af9c5a8b6e internal/host/managedboot.go managedBoot.stage legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=renders host.env/credentials/identity from the checked enrol reply into a fresh root-only staging dir; the read is crypto/rand for the dir suffix file:Read@894 67520ac85f00b62f94ce4fa6ae581d9a12c33c779dea95da59170d18303d3fb7 |
| +@legacy 10f3f1ffd13fdf4cabe37ae2611ad320831c0583e6e8986890a4ff55bd8bb505 internal/host/managedboot.go mbHolds legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat + read (16 MiB cap) of a regular file found by scrub's walk, only to test for the token bytes file:Lstat@69,file:ReadFile@191 88c094012701111d6584143b33807d43ecbe2ea54d730a9571987f0712e8e360 |
| +@legacy b4fefb56bd198375191458ef6135cd32622679299e70c8533769cfc3490e3b4e internal/host/managedboot_linux.go managedBoot.readInput legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat of BootDir (0700 dir check) then mbReadRootFile of boot-input.json (root-owned 0600, no symlink, nlink 1) file:Lstat@81 eff8288c342b21f58c6b2f62c2db67c19cd898111002c1d1c61f6070b04df0d3 |
| +@legacy da5f54377c5568707dd9fefd020055c08d4e44051ad29d7b42ece13c8f3b0bb6 internal/host/managedboot_linux.go mbBreadcrumb legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=opens /dev/console write-only to emit a value-free breadcrumb line file:OpenFile@92 1772f051eec5a1717430d88bbd86dc31e18ddedd0ac04bcd28680c39c1f2ab3c |
| +@legacy 43221a5a52c7aa602147b5e45935f958497c2083fe53db17c5e91967ea9f4103 internal/host/managedboot_linux.go mbCopyDurable legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=EXDEV fallback of mbMove: opens a root-owned committed file O_NOFOLLOW and copies it durably to its final root path file:Fstat@190,file:OpenFile@304,file:OpenFile@56 02ad0641b21a3de9c7c392f513e799209927638a778db73a186cc4870cd536b9 |
| +@legacy 1ce875ac09b27474d64e46c3c1a8f4ec429c852ec4af77410a2c19661454b5a4 internal/host/managedboot_linux.go mbHashExec legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_NOFOLLOW open + fstat of /opt/carlos/carlos: regular, nlink 1, root:root 0755, sha256 against the signed digest before first exec file:Fstat@274,file:Open@73 f4236bb074271b622159f0348a465458619cb7ec6051ff8cfdd1664133084729 |
| +@legacy 4a80fd0ab95b7a22bdc17fc4b6048e07f2df168a33b3f736d40184097630b8fd internal/host/managedboot_linux.go mbReadRootFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=openat beneath an mbWalk-verified root-owned chain, O_NOFOLLOW|O_NONBLOCK, regular, nlink 1, owner root, no g/o write, exact mode, size cap file:Fstat@482,file:Openat@233,file:ReadAll@813 4049413ad34b5e910972b1e05a473d15b380046f16a0ecc8b57f0fec76f6c0d6 |
| +@legacy 5948016d50dd2add8ae3232a03195bd5d1422bc66a8eab98d841b18b844fb034 internal/host/managedboot_linux.go mbRemoveTree legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lists a root-owned staging dir and shreds its regular files file:ReadDir@201 9fb3f04a9518441c82c251d4960bce3a4494bf5297746b2b9f01e3292b32553a |
| +@legacy cdd270639163586bd02ce42212d241456883660ab1f3f1b9be9a436c56a56d62 internal/host/managedboot_linux.go mbRun legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=runs argv with exactly the given env from /: nft list table, systemctl, and /opt/carlos/carlos bootstrap after its digest check file:CommandContext@77 c4bb8739c9eab44b2a548cd0a8684cbee4f15a5408322a8df89af1fbe634889e |
| +@legacy 452880c7a32d3d65d3cb1c4a8d93824415c6ae4da28e8bc8708349dd5238b4ec internal/host/managedboot_linux.go mbShred legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_WRONLY|O_NOFOLLOW open of a regular file to zero, fsync and unlink it file:Fstat@226,file:Open@46 a29122b0f292a0c766d5aefd626515e21839e87c68709412c2412f81965c3696 |
| +@legacy a44ac7b802a1c9bcdc037b85fe8daf87f79c0ffe9e25cbeac12d7867854b8fc4 internal/host/managedboot_linux.go mbSyncDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=opens a root-owned directory to fsync it file:Open@47 fc9bc492fa32b963b98ad1dea24c07a65b2b35d00a25ac2adbafeb16af745c09 |
| +@legacy 18b5c362804794bc0a0cd961c8fe3e8cc956d9f1226860396bf699db780a978b internal/host/managedboot_linux.go mbWalk legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=openat walk from the root anchor with O_NOFOLLOW|O_DIRECTORY; each component must be owned by root and not group/other writable file:Fstat@1243,file:Open@130,file:Openat@485,file:Openat@785 b43bc7a16c1f5e8c0e7cc2bb72ece46aef4b5185f2c2775c4fd6c8b865b878d4 |
| +@legacy 2a8f31244c853b7c1a63b960e002329b81b78146a5c4a5c85e8ae941896cf2c4 internal/host/managedboot_linux.go mbWriteRootFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_EXCL|O_NOFOLLOW temp beside the target in a verified root-owned dir, fsync, renameat, dir fsync; read is crypto/rand for the temp suffix file:Openat@381,file:Read@247 edbd584d636a3c49fe2c388052d1e42dca7864a2d25e521d2424207cbe3a77a7 |
| +@legacy eeedaf8a4350e05bf9cef635133e1d3f389ce5d50e2a6c8a321fa4adc1cf8856 internal/managedboot/cloudinit_v1.sh.tmpl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=Task 1's frozen v1 cloud-init script, now in the root binary because host imports managedboot; embedded and rendered by the console only, never executed by the root binary file:external@0 6877e48b72303dee895c728dec553be27733f9f954ddd62973ca545a2fc3508f |
| +@legacy ed4c367f8dec4ef61337a3038660df6fc76d193ca5a52845eb52293a0019cbf0 internal/managedboot/identity_linux.go loadIdentity legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_NOFOLLOW openat walk to /etc/carlos/managed-box.json; every component root-owned and not g/o writable, regular nlink 1, 4 KiB cap, strict canonical parse file:Fstat@811,file:Open@113,file:Openat@531,file:ReadAll@1154 842deb9a3240dc261a6ef4902f57259f4bd86c00ac6d7403e74f8eb7fe5abd13 |
| +@legacy 157b519285db956490e07b1212d058405fdf98a4b86425339c25186b80549512 internal/managedboot/units.go ensureDropIn legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat/read of root-owned systemd drop-ins under /etc/systemd/system to keep them exact; rewrite via temp+fsync+rename file:Lstat@123,file:Lstat@508,file:Open@1280,file:OpenFile@876,file:Read@736,file:ReadFile@608 2b5ae8af638d357059e3984138599565fa7b4baf3fe7c1082f12a690b6e94867 |
| +system.go runSystem authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added;rev3=census-ruling-nearest-region-a;basis=adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops the "join" case (host.RunSystemJoin, deleted with internal/host/joinroot.go, its only caller) and its line in the usage text; every other branch unchanged; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the system verb dispatch gains named-units, routed to host.RunSystemNamedUnits; no read of its own;rev3=census-ruling-design-pdf-service;basis=add dispatch for carlos system pdf; no new reads;rev3=census-ruling-managed-fleets-2a;basis=Adds managed-fleets operator CLI dispatch; no direct read added; existing root command branches unchanged.;rev3=census-ruling-agent-start-demo-2;basis=system.go:62-66 adds the demos family dispatch to the console-only operator client (system_demos.go:19, system_demos_api.go:23); no direct read added and other root commands are unchanged.;rev3=census-ruling-region-ha-p3b2;basis=Dispatches carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback} to internal/host; no read of its own.;rev3=census-ruling-managed-fleets-2b2;basis=adds the managed-boot case, routed to host.RunSystemManagedBoot (root oneshot behind carlos-managed-boot.service on a managed box); no read of its own; every other branch unchanged 81bf5ae3a89ac149f10d064d4e059bf50b5febfc8a1a38a9ce8b6905a89ac13d |
| +system.go systemVerb authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added;rev3=census-ruling-nearest-region-a;basis=adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops "join" from the verb list, so `carlos system join` now falls to the unknown-verb message; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the known-verb list gains named-units; no read of its own;rev3=census-ruling-design-pdf-service;basis=add recognition for carlos system pdf; no new reads;rev3=census-ruling-managed-fleets-2a;basis=Recognizes managed-fleets as a CLI family; no read added.;rev3=census-ruling-agent-start-demo-2;basis=system.go:43-57 recognizes demos; parsing only, no direct read added.;rev3=census-ruling-region-ha-p3b2;basis=Recognizes group-maintenance as a system verb; parsing only.;rev3=census-ruling-managed-fleets-2b2;basis=recognizes managed-boot as a system verb; parsing only, no read added 47e70ad5413a92fb584a48b0c3f20f684cb7b965e9238f4dc553ef09abdea9f0 |
| +internal/host/managedboot.go const#1 legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=managed-boot path and limit constants; data only data-literal@523 765b471b3a8004d57f6f1d4d73582e35ee10a1041def47f7209e7ade19023a47 |
| +internal/host/managedboot.go managedBoot.attest legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat and list /data (names only) before anything writes under it, to report absent/empty/count in the enrol request; no file content read file:Lstat@57,file:ReadDir@209 7a32d2fcf1179f2afa5127839bbde21d755de536c8f329b71486c5c8248c174a |
| +internal/host/managedboot.go managedBoot.clearStaging legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lists root-owned 0700 BootDir for staging.* left by a cut-off boot and shreds them via mbRemoveTree file:ReadDir@62 a7c11f7fdb4b17d34ca99b11cd392ffa787c2d6a30ef0ecdc77ea4f7ac61dcf1 |
| +internal/host/managedboot.go managedBoot.post legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=reads the enrol HTTPS reply body (64 KiB cap) from the frozen console origin; no file read file:ReadAll@600 88bbfb6acf5e7acc4cbcbe05edfa3d379e5d333dc61699d32856d17cf323caec |
| +internal/host/managedboot.go managedBoot.present legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat of fixed root-owned paths (BootDir markers, committed dir, seed request); existence only file:Lstat@69 289bacf43547b6913d9aa268c800f975263c9c1fc96f920486c1aca5c6b01940 |
| +internal/host/managedboot.go managedBoot.scrub legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=walks cloud-init trees (/var/lib/cloud, /run/cloud-init, cloud-init logs) and BootDir without following symlinks and shreds regular files holding the used token; nothing read is executed or trusted file:WalkDir@174 605ad097ff1799d6419f167aa2e8bbf98cc97d4b1f25ac81ce20d3210c69aed1 |
| +internal/host/managedboot.go managedBoot.stage legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=renders host.env/credentials/identity from the checked enrol reply into a fresh root-only staging dir; the read is crypto/rand for the dir suffix file:Read@894 67520ac85f00b62f94ce4fa6ae581d9a12c33c779dea95da59170d18303d3fb7 |
| +internal/host/managedboot.go mbHolds legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat + read (16 MiB cap) of a regular file found by scrub's walk, only to test for the token bytes file:Lstat@69,file:ReadFile@191 88c094012701111d6584143b33807d43ecbe2ea54d730a9571987f0712e8e360 |
| +internal/host/managedboot_linux.go managedBoot.readInput legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat of BootDir (0700 dir check) then mbReadRootFile of boot-input.json (root-owned 0600, no symlink, nlink 1) file:Lstat@81 eff8288c342b21f58c6b2f62c2db67c19cd898111002c1d1c61f6070b04df0d3 |
| +internal/host/managedboot_linux.go mbBreadcrumb legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=opens /dev/console write-only to emit a value-free breadcrumb line file:OpenFile@92 1772f051eec5a1717430d88bbd86dc31e18ddedd0ac04bcd28680c39c1f2ab3c |
| +internal/host/managedboot_linux.go mbCopyDurable legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=EXDEV fallback of mbMove: opens a root-owned committed file O_NOFOLLOW and copies it durably to its final root path file:Fstat@190,file:OpenFile@304,file:OpenFile@56 02ad0641b21a3de9c7c392f513e799209927638a778db73a186cc4870cd536b9 |
| +internal/host/managedboot_linux.go mbHashExec legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_NOFOLLOW open + fstat of /opt/carlos/carlos: regular, nlink 1, root:root 0755, sha256 against the signed digest before first exec file:Fstat@274,file:Open@73 f4236bb074271b622159f0348a465458619cb7ec6051ff8cfdd1664133084729 |
| +internal/host/managedboot_linux.go mbReadRootFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=openat beneath an mbWalk-verified root-owned chain, O_NOFOLLOW|O_NONBLOCK, regular, nlink 1, owner root, no g/o write, exact mode, size cap file:Fstat@482,file:Openat@233,file:ReadAll@813 4049413ad34b5e910972b1e05a473d15b380046f16a0ecc8b57f0fec76f6c0d6 |
| +internal/host/managedboot_linux.go mbRemoveTree legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lists a root-owned staging dir and shreds its regular files file:ReadDir@201 9fb3f04a9518441c82c251d4960bce3a4494bf5297746b2b9f01e3292b32553a |
| +internal/host/managedboot_linux.go mbRun legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=runs argv with exactly the given env from /: nft list table, systemctl, and /opt/carlos/carlos bootstrap after its digest check file:CommandContext@77 c4bb8739c9eab44b2a548cd0a8684cbee4f15a5408322a8df89af1fbe634889e |
| +internal/host/managedboot_linux.go mbShred legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_WRONLY|O_NOFOLLOW open of a regular file to zero, fsync and unlink it file:Fstat@226,file:Open@46 a29122b0f292a0c766d5aefd626515e21839e87c68709412c2412f81965c3696 |
| +internal/host/managedboot_linux.go mbSyncDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=opens a root-owned directory to fsync it file:Open@47 fc9bc492fa32b963b98ad1dea24c07a65b2b35d00a25ac2adbafeb16af745c09 |
| +internal/host/managedboot_linux.go mbWalk legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=openat walk from the root anchor with O_NOFOLLOW|O_DIRECTORY; each component must be owned by root and not group/other writable file:Fstat@1243,file:Open@130,file:Openat@485,file:Openat@785 b43bc7a16c1f5e8c0e7cc2bb72ece46aef4b5185f2c2775c4fd6c8b865b878d4 |
| +internal/host/managedboot_linux.go mbWriteRootFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_EXCL|O_NOFOLLOW temp beside the target in a verified root-owned dir, fsync, renameat, dir fsync; read is crypto/rand for the temp suffix file:Openat@381,file:Read@247 edbd584d636a3c49fe2c388052d1e42dca7864a2d25e521d2424207cbe3a77a7 |
| +internal/managedboot/cloudinit_v1.sh.tmpl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=Task 1's frozen v1 cloud-init script, now in the root binary because host imports managedboot; embedded and rendered by the console only, never executed by the root binary file:external@0 6877e48b72303dee895c728dec553be27733f9f954ddd62973ca545a2fc3508f |
| +internal/managedboot/identity_linux.go loadIdentity legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=O_NOFOLLOW openat walk to /etc/carlos/managed-box.json; every component root-owned and not g/o writable, regular nlink 1, 4 KiB cap, strict canonical parse file:Fstat@811,file:Open@113,file:Openat@531,file:ReadAll@1154 842deb9a3240dc261a6ef4902f57259f4bd86c00ac6d7403e74f8eb7fe5abd13 |
| +internal/managedboot/units.go ensureDropIn legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=lstat/read of root-owned systemd drop-ins under /etc/systemd/system to keep them exact; rewrite via temp+fsync+rename file:Lstat@123,file:Lstat@508,file:Open@1280,file:OpenFile@876,file:Read@736,file:ReadFile@608 2b5ae8af638d357059e3984138599565fa7b4baf3fe7c1082f12a690b6e94867 |
| +@coverage . 1dcaf53ecd6db0cc4870833eda8d18c2a1604e48c316e16eb153f80f612daefb |
| +@coverage internal/host b4abfbc13f1717118482426e8c0dd4d2a873b3eae02467541e72ba7c5d544585 |
| +@coverage internal/managedboot 89ff44b6b07b39d7450482d099e3b878f166d5951ef83f4334e3ea8a45d12426 |
diff --git a/system.go b/system.go| index 6b10ac631..5f39e9c58 100644 |
| --- a/system.go |
| +++ b/system.go |
| @@ -53,7 +53,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) { |
| // untouched in rest for runSystemAntivirusVerb to read. |
| // layout is a family too: migrate|revert|status stay in rest for |
| // runSystemLayout. |
| - case "group-maintenance", "demos", "managed-fleets", "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "pdf", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help": |
| + case "group-maintenance", "demos", "managed-fleets", "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "pdf", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "managed-boot", "help", "-h", "--help": |
| return args[0], args[1:], component |
| } |
| return "", args, component |
| @@ -118,6 +118,10 @@ func runSystem(args []string) { |
| hostenv.RunSystemHostEnv(rest) |
| case "named-units": |
| host.RunSystemNamedUnits(rest) |
| + case "managed-boot": |
| + // A managed box's first contact: root, run by |
| + // carlos-managed-boot.service on every boot. Not for operators. |
| + host.RunSystemManagedBoot(rest) |
| case "db-worker": |
| // The db-read worker (db region forward spec §8.3): systemd starts |
| // it per connection to carlos-dbread.socket. Never run by hand. |
diff --git a/system_test.go b/system_test.go| index bafb4f22e..af7a840c1 100644 |
| --- a/system_test.go |
| +++ b/system_test.go |
| @@ -41,6 +41,7 @@ func TestSystemVerbAcceptsTheComponentForm(t *testing.T) { |
| // takes no arguments. |
| {[]string{"host-env", "write", "--deployment", "flagship", "--region", "ie"}, "host-env", "router", 5}, |
| {[]string{"install-channel"}, "install-channel", "router", 0}, |
| + {[]string{"managed-boot", "--input", "/var/lib/carlos-managed-boot/boot-input.json"}, "managed-boot", "router", 2}, |
| // lifetimes is a family: cutover and its flag stay in rest. |
| {[]string{"lifetimes", "cutover", "--no-wait"}, "lifetimes", "router", 2}, |
| {[]string{}, "", "router", 0}, |