feat: frozen managed cloud-init and token-bound seed door
Managed fleets 2b-2 Task 1. New provider-neutral internal/managedboot: Frozen boot inputs and LaunchInput with allowlists, strict canonical DecodeLaunchInput, breadcrumb codes, and RenderUserData over the embedded v1 cloud-init template (plain sh, golden-pinned, under 12,288 bytes). The console freezes Boot (verified stable linux-arm64 seed, origin, tunnel host, release key) in the reserved-to-launching commit and renders user data from it on every dispatch; AdvanceManagedBox keeps Boot immutable. POST /api/fleet/enrol/seed streams the frozen seed to an unused token without consuming it. The enrol reply adds bucket, bucket_region and op. Census: seed route in claim-routes, seed open in the authority census, NewServer re-pinned in a 2b-2 record-write layer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
28 files changed,
+2,373
−33
internal/compute/imports_test.go+1 −1internal/console/claim_authority_census_test.go+6 −0internal/console/claim_invariant_fixtures_test.go+6 −0internal/console/managed_e2e_test.go+7 −5internal/console/managedenrol.go+5 −1internal/console/managedhistory_test.go+3 −0internal/console/managedready_test.go+9 −9internal/console/managedrecovery_test.go+2 −0internal/console/managedseed.go+155 −0internal/console/managedseed_linux_test.go+183 −0internal/console/managedseed_test.go+516 −0internal/console/managedstore.go+12 −0internal/console/managedworker.go+78 −16internal/console/managedworker_test.go+1 −0internal/console/server.go+3 −0internal/console/testdata/claim-authority-sites.txt+1 −0internal/console/testdata/claim-routes.txt+1 −0internal/managedboot/boottest/boottest.go+132 −0internal/managedboot/breadcrumb.go+19 −0internal/managedboot/cloudinit_v1.sh.tmpl+179 −0internal/managedboot/frozen.go+183 −0internal/managedboot/testdata/userdata-v1.golden+179 −0internal/managedboot/userdata.go+63 −0internal/managedboot/userdata_linux_test.go+203 −0internal/managedboot/userdata_rootrunner_linux_test.go+111 −0internal/managedboot/userdata_test.go+288 −0internal/provision/managed_fleets_2b2_census_test.go+26 −0internal/provision/plan9_b8_census_test.go+1 −1
diff --git a/internal/compute/imports_test.go b/internal/compute/imports_test.go| index e10b86819..bd4220087 100644 |
| --- a/internal/compute/imports_test.go |
| +++ b/internal/compute/imports_test.go |
| @@ -11,7 +11,7 @@ import ( |
| ) |
| func TestManagedCoreImports(t *testing.T) { |
| - for _, dir := range []string{".", "../fleetstore", "../console"} { |
| + for _, dir := range []string{".", "../fleetstore", "../console", "../managedboot", "../managedboot/boottest"} { |
| entries, err := os.ReadDir(dir) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/console/claim_authority_census_test.go b/internal/console/claim_authority_census_test.go| index 6a295d3f0..c9586f073 100644 |
| --- a/internal/console/claim_authority_census_test.go |
| +++ b/internal/console/claim_authority_census_test.go |
| @@ -27,6 +27,12 @@ import ( |
| // and uploads to the durable operation's exact snapshot key. No request path |
| // selects this file. TestDemoClaimFreshSeed and the snapshot refusal tests |
| // cover this boundary; the open adds no root or bucket-constructor authority. |
| +// openManagedSeed opens, read-only, the one deployment store object a |
| +// managed box's frozen Boot names (bootstrap/router/<v>/carlos-linux-arm64, |
| +// allowlisted by managedboot.Frozen.Validate), only for an unused enrolment |
| +// token inside its launching window. It writes nothing, caps the stream at |
| +// 96 MiB and adds no root or bucket-constructor authority. TestManagedSeedDoor |
| +// and TestManagedCloudInitScriptRun cover it. |
| func claimAuthoritySites(t *testing.T) []string { |
| t.Helper() |
| selected := map[string]bool{ |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index a2761aae0..0b39b0ae8 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1404,6 +1404,12 @@ var claimFixtures = map[string]claimFixture{ |
| status: http.StatusConflict, |
| msg: errManagedHostClaim.Error(), |
| }}, |
| + "route POST /api/fleet/enrol/seed": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimRefusedAPI(http.MethodPost, "/api/fleet/enrol/seed", `{"token":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`), |
| + status: http.StatusConflict, |
| + msg: errManagedHostClaim.Error(), |
| + }}, |
| "route POST /api/ses/events": {door: &claimDoor{ |
| apps: claimRefs("bab/titogo"), |
| setup: func(t *testing.T, cx *claimCase) { |
diff --git a/internal/console/managed_e2e_test.go b/internal/console/managed_e2e_test.go| index e0a8793a9..9960dd9ce 100644 |
| --- a/internal/console/managed_e2e_test.go |
| +++ b/internal/console/managed_e2e_test.go |
| @@ -34,11 +34,13 @@ func managedE2E(t *testing.T, n int, disconnect ...bool) (*Server, *compute.Fake |
| s := managedAPIFixture(t) |
| s.cfg.TunnelHost = "tunnel.example.com" |
| setManagedHistory(t, s, provision.HostsState{Mode: provision.HostsModeIncomplete}) |
| - pub, priv, err := ed25519.GenerateKey(nil) |
| - if err != nil { |
| - t.Fatal(err) |
| + if s.cfg.Key == nil { |
| + pub, priv, err := ed25519.GenerateKey(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.Key, s.cfg.ReleasePub = priv, pub |
| } |
| - s.cfg.Key, s.cfg.ReleasePub = priv, pub |
| readyStable(t, s, "v0.34.0") |
| s.managed.snapshot.Config.Ceiling = 200 |
| s.managedExtra = readyExtras{managedCheck{State: "pass"}, managedCheck{State: "pass"}} |
| @@ -48,7 +50,7 @@ func managedE2E(t *testing.T, n int, disconnect ...bool) (*Server, *compute.Fake |
| t.Fatal(preview.Code, preview.Body) |
| } |
| var plan fleetShowPlan |
| - if err = json.Unmarshal(preview.Body.Bytes(), &plan); err != nil { |
| + if err := json.Unmarshal(preview.Body.Bytes(), &plan); err != nil { |
| t.Fatal(err) |
| } |
| var out fleetShowReply |
diff --git a/internal/console/managedenrol.go b/internal/console/managedenrol.go| index 99d306775..396be6793 100644 |
| --- a/internal/console/managedenrol.go |
| +++ b/internal/console/managedenrol.go |
| @@ -51,6 +51,10 @@ type managedEnrolReply struct { |
| TunnelToken string `json:"tunnel_token"` |
| Credentials fleetstore.Credentials `json:"credentials"` |
| Joining bool `json:"joining"` |
| + // The box's frozen fleet storage and operation, for its cross-checks. |
| + Bucket string `json:"bucket"` |
| + BucketRegion string `json:"bucket_region"` |
| + Operation string `json:"op"` |
| } |
| func (s *Server) handleManagedEnrol(w http.ResponseWriter, r *http.Request) { |
| @@ -192,5 +196,5 @@ func (s *Server) enrolManagedBox(ctx context.Context, in managedEnrolRequest, no |
| return fail() |
| } |
| s.wakeManagedFleets() |
| - return managedEnrolReply{Fleet: b.Fleet, Label: b.Label, TunnelURL: "https://" + s.cfg.TunnelHost, TunnelToken: token, Credentials: credentials, Joining: true}, nil |
| + return managedEnrolReply{Fleet: b.Fleet, Label: b.Label, TunnelURL: "https://" + s.cfg.TunnelHost, TunnelToken: token, Credentials: credentials, Joining: true, Bucket: b.Storage.Bucket, BucketRegion: b.Storage.Region, Operation: b.OpID}, nil |
| } |
diff --git a/internal/console/managedhistory_test.go b/internal/console/managedhistory_test.go| index c179fb317..0abee44e9 100644 |
| --- a/internal/console/managedhistory_test.go |
| +++ b/internal/console/managedhistory_test.go |
| @@ -36,6 +36,9 @@ func managedPreparationFixture(t *testing.T) (*Server, consoleRegistry) { |
| // the pass time. Clock-sensitive tests install a controlled one. |
| fixed := time.Now() |
| s.managedClock = func() time.Time { return fixed } |
| + // Boxes freeze their boot inputs at launch: a signed stable pointer |
| + // with a linux-arm64 seed, the release key and both origins. |
| + managedBootConfig(t, s) |
| return s, reg |
| } |
| func setManagedHistory(t *testing.T, s *Server, st provision.HostsState) { |
diff --git a/internal/console/managedready_test.go b/internal/console/managedready_test.go| index 6f5f9435e..d724ee060 100644 |
| --- a/internal/console/managedready_test.go |
| +++ b/internal/console/managedready_test.go |
| @@ -30,12 +30,14 @@ func readyFixture(t *testing.T) (*Server, managedBox, time.Time) { |
| if err := reg.AddManagedFleetBox(registry.FleetBox{Fleet: b.Fleet, Label: b.Label, TokenHash: b.EnrolHash}, 123); err != nil { |
| t.Fatal(err) |
| } |
| - pub, priv, err := ed25519.GenerateKey(nil) |
| - if err != nil { |
| - t.Fatal(err) |
| + if s.cfg.Key == nil { |
| + pub, priv, err := ed25519.GenerateKey(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.Key = priv |
| + s.cfg.ReleasePub = pub |
| } |
| - s.cfg.Key = priv |
| - s.cfg.ReleasePub = pub |
| readyStable(t, s, "v0.34.0") |
| readyBeat(t, s, b, status.Box{Label: b.Label, GeneratedAt: now, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true, Tunnel: "connected"}}) |
| s.managedExtra = readyExtras{managedCheck{State: "pass"}, managedCheck{State: "pass"}} |
| @@ -43,10 +45,8 @@ func readyFixture(t *testing.T) (*Server, managedBox, time.Time) { |
| } |
| func readyStable(t *testing.T, s *Server, v string) { |
| t.Helper() |
| - r := release.SystemRelease{Version: v, Source: "release:" + v, ReleaseTag: v, Artifacts: map[string]release.SystemArtifact{"linux-amd64": {Key: release.SystemArtifactKey(v, "linux-amd64"), SHA256: strings.Repeat("a", 64)}}} |
| - if _, err := release.PromoteSystem(context.Background(), s.cfg.Releases, release.RootSigner(s.cfg.Key), "router", "stable", r, release.SystemPromoteOptions{}); err != nil { |
| - t.Fatal(err) |
| - } |
| + // Every stable release carries the managed seed's linux-arm64 artifact. |
| + managedSeedStable(t, s, v, managedTestSeed) |
| } |
| func readyBeat(t *testing.T, s *Server, b managedBox, beat status.Box) { |
| t.Helper() |
diff --git a/internal/console/managedrecovery_test.go b/internal/console/managedrecovery_test.go| index 05a563c05..458c996ac 100644 |
| --- a/internal/console/managedrecovery_test.go |
| +++ b/internal/console/managedrecovery_test.go |
| @@ -43,6 +43,7 @@ func TestManagedRejectedAfterAmbiguity(t *testing.T) { |
| b.State = "launching" |
| b.LaunchStartedAt = now |
| b.EnrolExpires = now.Add(30 * time.Minute) |
| + b.Boot = managedExpectedBoot(s, "v0.34.0", managedTestSeed) |
| }) |
| if _, err := s.store.db.Exec(`UPDATE managed_boxes SET launch=CAST(json_remove(launch,'$.readiness_checked_at') AS BLOB)`); err != nil { |
| t.Fatal(err) |
| @@ -141,6 +142,7 @@ func TestManagedFreshRejectedLaunch(t *testing.T) { |
| b.State = "launching" |
| b.LaunchStartedAt = now |
| b.EnrolExpires = now.Add(30 * time.Minute) |
| + b.Boot = managedExpectedBoot(s, "v0.34.0", managedTestSeed) |
| }) |
| s = restartManagedWorker(t, s) |
| p.FailLaunch = compute.ErrLaunchRejected |
diff --git a/internal/console/managedseed.go b/internal/console/managedseed.go| new file mode 100644 |
| index 000000000..2d5234b89 |
| --- /dev/null |
| +++ b/internal/console/managedseed.go |
| @@ -0,0 +1,155 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "io" |
| + "log" |
| + "net/http" |
| + "os" |
| + "strconv" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// COPY: the seed door's own refusal awaits the controller's copy review; |
| +// its other refusals are enrolment's. |
| +const managedSeedInvalid = "invalid seed request" |
| + |
| +// managedSeedMaxBytes caps one seed stream; the box enforces the same cap. |
| +const managedSeedMaxBytes = 96 << 20 |
| + |
| +// managedSeedStreams bounds concurrent seed streams across the console. |
| +var managedSeedStreams = make(chan struct{}, 4) |
| + |
| +// handleManagedSeed is POST /api/fleet/enrol/seed: a box presents its |
| +// unused enrolment token and receives the frozen seed binary. The token is |
| +// not consumed. The console does not vouch for the bytes; the box checks |
| +// them against its frozen digest before running them. Unknown, used, |
| +// expired and not-yet-launched tokens get enrolment's one 403. |
| +func (s *Server) handleManagedSeed(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + now := time.Now().UTC() |
| + if !s.cli.managedEnrolIP.allow(s.clientIP(r), now) || !s.cli.managedEnrolGlobal.allow("deployment", now) { |
| + w.Header().Set("Retry-After", "60") |
| + jsonError(w, http.StatusTooManyRequests, managedEnrolRetry) |
| + return |
| + } |
| + var wire struct { |
| + Token *string `json:"token"` |
| + } |
| + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)) |
| + dec.DisallowUnknownFields() |
| + var extra any |
| + if dec.Decode(&wire) != nil || dec.Decode(&extra) != io.EOF || wire.Token == nil { |
| + jsonError(w, http.StatusBadRequest, managedSeedInvalid) |
| + return |
| + } |
| + if s.cfg.HostClaim { |
| + jsonError(w, http.StatusConflict, errManagedHostClaim.Error()) |
| + return |
| + } |
| + frozen, b, err := s.managedSeedBox(r.Context(), *wire.Token, now) |
| + if err != nil { |
| + writeManagedEnrolError(w, err) |
| + return |
| + } |
| + select { |
| + case managedSeedStreams <- struct{}{}: |
| + defer func() { <-managedSeedStreams }() |
| + default: |
| + writeManagedEnrolError(w, errManagedEnrolRetryable) |
| + return |
| + } |
| + body, size, err := s.openManagedSeed(r.Context(), frozen.SeedKey) |
| + if err != nil { |
| + log.Printf("console: managed seed: %s/%s: seed unavailable", b.Fleet, b.Label) |
| + writeManagedEnrolError(w, errManagedEnrolRetryable) |
| + return |
| + } |
| + defer body.Close() |
| + w.Header().Set("Content-Type", "application/octet-stream") |
| + w.Header().Set("Content-Length", strconv.FormatInt(size, 10)) |
| + w.WriteHeader(http.StatusOK) |
| + if _, err = io.CopyN(w, body, size); err != nil { |
| + log.Printf("console: managed seed: %s/%s: stream ended early", b.Fleet, b.Label) |
| + return |
| + } |
| + log.Printf("console: managed seed: %s/%s: served", b.Fleet, b.Label) |
| +} |
| + |
| +// openManagedSeed streams key when the store can, else reads it whole; an |
| +// object of unknown or excessive size is refused. |
| +func (s *Server) openManagedSeed(ctx context.Context, key string) (io.ReadCloser, int64, error) { |
| + if s.cfg.Releases == nil { |
| + return nil, 0, os.ErrNotExist |
| + } |
| + if o, ok := s.cfg.Releases.(release.Opener); ok { |
| + body, _, err := o.Open(ctx, key) |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + size := int64(-1) |
| + if sized, ok := body.(interface{ Size() int64 }); ok { |
| + size = sized.Size() |
| + } else if f, ok := body.(*os.File); ok { |
| + if info, err := f.Stat(); err == nil && info.Mode().IsRegular() { |
| + size = info.Size() |
| + } |
| + } |
| + if size < 0 || size > managedSeedMaxBytes { |
| + body.Close() |
| + return nil, 0, errManagedEnrolRetryable |
| + } |
| + return body, size, nil |
| + } |
| + b, _, err := s.cfg.Releases.Get(ctx, key) |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + if len(b) > managedSeedMaxBytes { |
| + return nil, 0, errManagedEnrolRetryable |
| + } |
| + return io.NopCloser(bytes.NewReader(b)), int64(len(b)), nil |
| +} |
| + |
| +// managedSeedFor returns the frozen boot inputs of the box that token |
| +// belongs to, if the token is unused and inside its launching window. It |
| +// reads only: no claim, no state change. Errors are enrolment's |
| +// (errManagedEnrolForbidden, or errManagedEnrolRetryable when SQL fails). |
| +func (s *Server) managedSeedFor(ctx context.Context, token string, now time.Time) (managedboot.Frozen, error) { |
| + f, _, err := s.managedSeedBox(ctx, token, now) |
| + return f, err |
| +} |
| + |
| +func (s *Server) managedSeedBox(ctx context.Context, token string, now time.Time) (managedboot.Frozen, managedBox, error) { |
| + refused := func() (managedboot.Frozen, managedBox, error) { |
| + return managedboot.Frozen{}, managedBox{}, errManagedEnrolForbidden |
| + } |
| + if s.cfg.HostClaim || !managedHashRE.MatchString(token) || now.UnixNano() <= 0 { |
| + return refused() |
| + } |
| + digest := sha256.Sum256([]byte(token)) |
| + hash := hex.EncodeToString(digest[:]) |
| + boxes, err := managedLoadBoxes(ctx, s.store.db, `WHERE json_extract(CAST(launch AS TEXT),'$.EnrolHash')=? AND json_extract(CAST(launch AS TEXT),'$.EnrolHash') != ''`, hash) |
| + if err != nil { |
| + return managedboot.Frozen{}, managedBox{}, errManagedEnrolRetryable |
| + } |
| + if len(boxes) != 1 { |
| + return refused() |
| + } |
| + b := boxes[0] |
| + // The same predicate as enrolment's claim, without the claim. |
| + if b.EnrolHash != hash || !b.EnrolUsedAt.IsZero() || (b.State != "launching" && b.State != "booting") || b.LaunchStartedAt.IsZero() || now.Before(b.LaunchStartedAt) || !now.Before(b.EnrolExpires) { |
| + return refused() |
| + } |
| + if b.Boot.IsZero() || b.Boot.Validate() != nil { |
| + return refused() |
| + } |
| + return b.Boot, b, nil |
| +} |
diff --git a/internal/console/managedseed_linux_test.go b/internal/console/managedseed_linux_test.go| new file mode 100644 |
| index 000000000..076f8d226 |
| --- /dev/null |
| +++ b/internal/console/managedseed_linux_test.go |
| @@ -0,0 +1,183 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/pem" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/managedboot/boottest" |
| +) |
| + |
| +// TestManagedCloudInitScriptRun runs the rendered user data as the test |
| +// user under a scratch root prefix, against the real seed door over TLS, |
| +// with real curl and python3 and logging shims for everything that changes |
| +// the machine. It needs no privileges and never skips. |
| +func TestManagedCloudInitScriptRun(t *testing.T) { |
| + for _, good := range []bool{true, false} { |
| + t.Run(map[bool]string{true: "right bytes", false: "wrong bytes"}[good], func(t *testing.T) { |
| + s, _, _, _ := managedWorkerFixture(t) |
| + now := time.Now().UTC() |
| + s.cli = newCLILimits() |
| + var mu sync.Mutex |
| + var bodies []string |
| + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/api/fleet/enrol/seed" || r.Method != http.MethodPost { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + b, _ := io.ReadAll(r.Body) |
| + mu.Lock() |
| + bodies = append(bodies, string(b)) |
| + mu.Unlock() |
| + r.Body = io.NopCloser(bytes.NewReader(b)) |
| + s.handleManagedSeed(w, r) |
| + })) |
| + defer srv.Close() |
| + s.cfg.Origin = srv.URL |
| + b := workerStep(t, s, now) |
| + if b.Boot.IsZero() { |
| + t.Fatalf("not launched: %+v", b) |
| + } |
| + spec, err := s.managedLaunchRequest(b) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + key, _, _ := openManagedEnrolKey(s.cfg.AlertSealKeyPath) |
| + token, _ := deriveManagedEnrolToken(key, b.ClientToken) |
| + if !good { |
| + _, etag, _ := s.cfg.Releases.Get(context.Background(), b.Boot.SeedKey) |
| + if _, err = s.cfg.Releases.Put(context.Background(), b.Boot.SeedKey, append([]byte("x"), managedTestSeed...), etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + ca := filepath.Join(t.TempDir(), "ca.pem") |
| + if err = os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + h := boottest.New(t, spec.UserData, fmt.Sprintf("%d:%d", os.Getuid(), os.Getgid()), ca) |
| + out, runErr := h.Run(t) |
| + calls := h.Calls(t) |
| + for _, c := range append(calls, out) { |
| + if strings.Contains(c, token) { |
| + t.Fatalf("token on a command line or output: %q", c) |
| + } |
| + } |
| + bootDir := h.Path(managedboot.BootDir) |
| + bounded := 0 |
| + for _, c := range calls { |
| + if strings.HasPrefix(c, "timeout ") { |
| + bounded++ |
| + if c != "timeout 900 /bin/sh "+h.Script { |
| + t.Fatalf("bound %q", c) |
| + } |
| + } |
| + } |
| + if bounded != 1 { |
| + t.Fatalf("re-exec %d times", bounded) |
| + } |
| + var curl string |
| + for _, c := range calls { |
| + if strings.HasPrefix(c, "curl ") { |
| + curl = c |
| + } |
| + } |
| + if want := "curl --proto =https --tlsv1.2 -fsS --retry 20 --retry-max-time 600 --max-filesize 100663296 -H Content-Type: application/json --data-binary @" + bootDir + "/seed-request.json -o " + bootDir + "/seed.part " + srv.URL + "/api/fleet/enrol/seed"; curl != want { |
| + t.Fatalf("curl call\n got %q\nwant %q", curl, want) |
| + } |
| + mu.Lock() |
| + if len(bodies) != 1 || bodies[0] != `{"token":"`+token+`"}`+"\n" { |
| + t.Fatalf("seed request bodies %q", bodies) |
| + } |
| + mu.Unlock() |
| + if _, err = os.Stat(filepath.Join(bootDir, "seed.part")); good && !os.IsNotExist(err) { |
| + t.Fatal("seed.part left behind", err) |
| + } |
| + if !good { |
| + if runErr == nil || !strings.Contains(out, managedboot.Breadcrumb(managedboot.CodeBootstrapFailed)+"\n") || strings.Contains(out, managedboot.CodeSeedVerified) { |
| + t.Fatalf("wrong bytes: %v %q", runErr, out) |
| + } |
| + for _, c := range calls { |
| + if strings.HasPrefix(c, "systemctl start") || strings.Contains(c, "daemon-reload") { |
| + t.Fatalf("unit started after a refused seed: %q", c) |
| + } |
| + } |
| + for _, p := range []string{filepath.Join(bootDir, "seed"), h.Path("/etc/systemd/system/carlos-managed-boot.service")} { |
| + if _, err = os.Lstat(p); !os.IsNotExist(err) { |
| + t.Fatalf("%s exists after a refused seed", p) |
| + } |
| + } |
| + return |
| + } |
| + if runErr != nil || out != managedboot.Breadcrumb(managedboot.CodeSeedVerified)+"\n" { |
| + t.Fatalf("run: %v %q", runErr, out) |
| + } |
| + st, err := os.Lstat(filepath.Join(bootDir, "seed")) |
| + if err != nil || st.Mode() != 0o700 { |
| + t.Fatalf("seed %v %v", st, err) |
| + } |
| + if got, _ := os.ReadFile(filepath.Join(bootDir, "seed")); !bytes.Equal(got, managedTestSeed) { |
| + t.Fatal("seed bytes") |
| + } |
| + if _, err = os.Lstat(filepath.Join(bootDir, "seed-request.json")); !os.IsNotExist(err) { |
| + t.Fatal("seed request kept", err) |
| + } |
| + raw, err := os.ReadFile(filepath.Join(bootDir, "boot-input.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + in, err := managedboot.DecodeLaunchInput(raw) |
| + if err != nil || in.Frozen != b.Boot || in.Token != token || in.Fleet != b.Fleet || in.Label != b.Label || in.Op != b.OpID || !in.Expires.Equal(b.EnrolExpires) { |
| + t.Fatalf("boot input %+v %v", in, err) |
| + } |
| + for path, want := range map[string]string{ |
| + "/etc/systemd/system/carlos-managed-boot.service": "[Unit]\nRequires=nftables.service\nAfter=nftables.service\nBefore=carlos-edge.service\n\n[Service]\nType=oneshot\nRemainAfterExit=yes\n" + |
| + "ExecStart=/usr/bin/python3 -I /var/lib/carlos-managed-boot/verify.py seed\nExecStart=/var/lib/carlos-managed-boot/seed system managed-boot --input /var/lib/carlos-managed-boot/boot-input.json\n\n[Install]\nWantedBy=multi-user.target\n", |
| + "/etc/systemd/system/carlos-managed-boot.service.d/10-enrol.conf": "[Unit]\nWants=network-online.target\nAfter=network-online.target\n", |
| + "/etc/systemd/system/carlos-edge.service.d/60-managed.conf": "[Unit]\nRequires=carlos-managed-boot.service\nAfter=carlos-managed-boot.service\n", |
| + } { |
| + got, err := os.ReadFile(h.Path(path)) |
| + if err != nil || string(got) != want { |
| + t.Fatalf("%s:\n%s (%v)", path, got, err) |
| + } |
| + } |
| + conf, _ := os.ReadFile(h.Path("/etc/nftables.conf")) |
| + if !strings.Contains(string(conf), "meta skuid != { 0, "+boottest.ServiceUID+" } ip daddr 169.254.169.254 reject") || !strings.Contains(string(conf), "chain forward") { |
| + t.Fatalf("nftables.conf:\n%s", conf) |
| + } |
| + tail := calls[len(calls)-4:] |
| + want := []string{ |
| + "systemctl daemon-reload", |
| + "systemctl enable carlos-managed-boot.service", |
| + "python3 -I " + bootDir + "/verify.py seed", |
| + "systemctl start --no-block carlos-managed-boot.service", |
| + } |
| + if strings.Join(tail, "\n") != strings.Join(want, "\n") { |
| + t.Fatalf("final calls\n%s", strings.Join(tail, "\n")) |
| + } |
| + var verified int |
| + for _, c := range calls { |
| + if strings.HasPrefix(c, "python3 -I "+bootDir+"/verify.py") { |
| + verified++ |
| + } |
| + } |
| + if verified != 2 { |
| + t.Fatalf("verify ran %d times", verified) |
| + } |
| + // The seed door left the token usable for enrolment. |
| + if got := workerBox(t, s); !got.EnrolUsedAt.IsZero() { |
| + t.Fatal("seed consumed the token") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/managedseed_test.go b/internal/console/managedseed_test.go| new file mode 100644 |
| index 000000000..b2ce5b2d8 |
| --- /dev/null |
| +++ b/internal/console/managedseed_test.go |
| @@ -0,0 +1,516 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http/httptest" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/compute" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +var managedTestSeed = []byte("#!/bin/false\nmanaged seed for tests\n") |
| + |
| +// managedBootConfig gives a fixture what freezing a box's boot needs. |
| +func managedBootConfig(t *testing.T, s *Server) { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.Key, s.cfg.ReleasePub = priv, pub |
| + s.cfg.Origin = "https://console.example.com" |
| + s.cfg.TunnelHost = "tunnel.example.com" |
| + managedSeedStable(t, s, "v0.34.0", managedTestSeed) |
| +} |
| + |
| +// managedSeedStable stores seed as version v's linux-arm64 artifact and |
| +// promotes v to stable. |
| +func managedSeedStable(t *testing.T, s *Server, v string, seed []byte) { |
| + t.Helper() |
| + ctx := context.Background() |
| + sum := sha256.Sum256(seed) |
| + key := release.SystemArtifactKey(v, managedboot.SeedArtifactPlatform) |
| + _, etag, _ := s.cfg.Releases.Get(ctx, key) |
| + if _, err := s.cfg.Releases.Put(ctx, key, seed, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := release.SystemRelease{Version: v, Source: "release:" + v, ReleaseTag: v, Artifacts: map[string]release.SystemArtifact{ |
| + managedboot.SeedArtifactPlatform: {Key: key, SHA256: hex.EncodeToString(sum[:])}, |
| + "linux-amd64": {Key: release.SystemArtifactKey(v, "linux-amd64"), SHA256: strings.Repeat("a", 64)}, |
| + }} |
| + if _, err := release.PromoteSystem(ctx, s.cfg.Releases, release.RootSigner(s.cfg.Key), "router", "stable", r, release.SystemPromoteOptions{}); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func managedExpectedBoot(s *Server, v string, seed []byte) managedboot.Frozen { |
| + sum := sha256.Sum256(seed) |
| + return managedboot.Frozen{Format: managedboot.FormatV1, ConsoleOrigin: s.cfg.Origin, TunnelHost: s.cfg.TunnelHost, ReleasePubkey: base64.StdEncoding.EncodeToString(s.cfg.ReleasePub), SeedVersion: v, SeedKey: release.SystemArtifactKey(v, managedboot.SeedArtifactPlatform), SeedSHA256: hex.EncodeToString(sum[:])} |
| +} |
| + |
| +// bootRecorder records each Launch's user data and the box's persisted |
| +// Boot at the moment of the call. |
| +type bootRecorder struct { |
| + *compute.Fake |
| + t *testing.T |
| + s *Server |
| + mu sync.Mutex |
| + userData []string |
| + atLaunch []managedboot.Frozen |
| +} |
| + |
| +func recordBoots(t *testing.T, s *Server) *bootRecorder { |
| + r := &bootRecorder{Fake: s.cfg.ManagedCompute.(*compute.Fake), t: t, s: s} |
| + s.cfg.ManagedCompute = r |
| + return r |
| +} |
| +func (r *bootRecorder) Launch(ctx context.Context, spec compute.LaunchSpec) (compute.Instance, error) { |
| + _, bs, err := r.s.store.ManagedFleet(context.Background(), "abc", "shop") |
| + r.mu.Lock() |
| + for _, b := range bs { |
| + if b.Label == spec.Identity.Label { |
| + r.atLaunch = append(r.atLaunch, b.Boot) |
| + } |
| + } |
| + r.userData = append(r.userData, spec.UserData) |
| + r.mu.Unlock() |
| + if err != nil { |
| + r.t.Error(err) |
| + } |
| + return r.Fake.Launch(ctx, spec) |
| +} |
| + |
| +func TestManagedBootFrozenAtLaunch(t *testing.T) { |
| + t.Run("frozen before launch", func(t *testing.T) { |
| + s, p, _, now := managedWorkerFixture(t) |
| + rec := recordBoots(t, s) |
| + want := managedExpectedBoot(s, "v0.34.0", managedTestSeed) |
| + b := workerStep(t, s, now) |
| + if b.State != "booting" && b.State != "launching" || b.Boot != want || p.Calls()["Launch"] != 1 { |
| + t.Fatalf("launch: %+v %v", b, p.Calls()) |
| + } |
| + if len(rec.atLaunch) != 1 || rec.atLaunch[0] != want { |
| + t.Fatalf("Boot not durable before Launch: %+v", rec.atLaunch) |
| + } |
| + key, _, _ := openManagedEnrolKey(s.cfg.AlertSealKeyPath) |
| + token, _ := deriveManagedEnrolToken(key, b.ClientToken) |
| + script, err := managedboot.RenderUserData(managedboot.LaunchInput{Frozen: want, Fleet: b.Fleet, Label: b.Label, Op: b.OpID, Token: token, Expires: b.EnrolExpires}) |
| + if err != nil || rec.userData[0] != script { |
| + t.Fatalf("user data is not the frozen render: %v", err) |
| + } |
| + var raw string |
| + if err = s.store.db.QueryRow(`SELECT launch FROM managed_boxes`).Scan(&raw); err != nil || strings.Contains(raw, token) || strings.Contains(raw, "CARLOS_BOOT") { |
| + t.Fatal("token or user data stored", err) |
| + } |
| + }) |
| + t.Run("one pointer read per pass", func(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + setManagedHistoryIncomplete(t, s) |
| + r := managedReq("shop", "abc") |
| + r.Boxes = 3 |
| + op, bs, _, err := s.reserveManagedFleet(context.Background(), r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.prepareManagedFleet(context.Background(), op, bs); err != nil { |
| + t.Fatal(err) |
| + } |
| + st := countReadiness(s) |
| + p := s.cfg.ManagedCompute.(*compute.Fake) |
| + if err = s.RunManagedFleetsPass(context.Background(), time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, boxes, _ := s.store.ManagedFleet(context.Background(), "abc", "shop") |
| + if st.gets[release.SystemPointerKey("router", "stable")] != 1 || p.Calls()["Launch"] != 3 || len(boxes) != 3 { |
| + t.Fatalf("pointer reads %v launches %v", st.gets, p.Calls()) |
| + } |
| + for _, b := range boxes { |
| + if b.Boot != boxes[0].Boot || b.Boot.IsZero() { |
| + t.Fatal("boxes of one pass froze different inputs") |
| + } |
| + } |
| + }) |
| + for _, kind := range []string{"absent", "unsigned", "no-arm64", "bad-origin"} { |
| + t.Run("stable "+kind, func(t *testing.T) { |
| + s, p, b, now := managedWorkerFixture(t) |
| + ctx := context.Background() |
| + pointer := release.SystemPointerKey("router", "stable") |
| + switch kind { |
| + case "absent": |
| + _ = s.cfg.Releases.Delete(ctx, pointer) |
| + case "unsigned": |
| + _, etag, _ := s.cfg.Releases.Get(ctx, pointer) |
| + if _, err := s.cfg.Releases.Put(ctx, pointer, []byte(`{"payload":{},"sig":""}`), etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "no-arm64": |
| + r := release.SystemRelease{Version: "v0.35.0", Source: "release:v0.35.0", ReleaseTag: "v0.35.0", Artifacts: map[string]release.SystemArtifact{"linux-amd64": {Key: release.SystemArtifactKey("v0.35.0", "linux-amd64"), SHA256: strings.Repeat("a", 64)}}} |
| + if _, err := release.PromoteSystem(ctx, s.cfg.Releases, release.RootSigner(s.cfg.Key), "router", "stable", r, release.SystemPromoteOptions{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "bad-origin": |
| + s.cfg.Origin = "http://console.example.com" |
| + } |
| + for _, at := range []time.Duration{0, time.Minute, 29 * time.Minute} { |
| + if got := workerStep(t, s, now.Add(at)); got.State != "reserved" || !got.Boot.IsZero() || !got.LaunchStartedAt.IsZero() { |
| + t.Fatalf("launched without frozen inputs: %+v", got) |
| + } |
| + } |
| + if p.Calls()["Launch"] != 0 { |
| + t.Fatal(p.Calls()) |
| + } |
| + if got := workerStep(t, s, b.CreatedAt.Add(30*time.Minute)); got.State != "terminated" || got.LastError != "managed_preparation_timeout" || p.Calls()["Launch"] != 0 { |
| + t.Fatalf("deadline changed: %+v", got) |
| + } |
| + }) |
| + } |
| + t.Run("recovery re-renders identically", func(t *testing.T) { |
| + s, p, _, now := managedWorkerFixture(t) |
| + rec := recordBoots(t, s) |
| + p.FailLaunch = errors.New("network") |
| + b := workerStep(t, s, now) |
| + if b.State != "launching" || len(rec.userData) != 1 { |
| + t.Fatalf("%+v", b) |
| + } |
| + managedSeedStable(t, s, "v0.35.0", []byte("newer seed")) |
| + s.cfg.Origin = "https://other.example.com" |
| + s.cfg.TunnelHost = "other-tunnel.example.com" |
| + s = restartManagedWorker(t, s) |
| + rec.s = s |
| + p.FailLaunch = nil |
| + b = workerStep(t, s, now.Add(time.Second)) |
| + if p.Calls()["Launch"] != 2 || len(rec.userData) != 2 || rec.userData[1] != rec.userData[0] || b.CloudID == "" { |
| + t.Fatalf("recovery: %v %d", p.Calls(), len(rec.userData)) |
| + } |
| + }) |
| + t.Run("boot is immutable", func(t *testing.T) { |
| + s, _, _, now := managedWorkerFixture(t) |
| + b := workerStep(t, s, now) |
| + next := b |
| + next.Boot.SeedVersion = "v0.35.0" |
| + next.Boot.SeedKey = release.SystemArtifactKey("v0.35.0", managedboot.SeedArtifactPlatform) |
| + if ok, err := s.store.AdvanceManagedBox(context.Background(), b, next); err == nil || ok { |
| + t.Fatal("boot change accepted") |
| + } |
| + next = b |
| + next.Boot = managedboot.Frozen{} |
| + if ok, err := s.store.AdvanceManagedBox(context.Background(), b, next); err == nil || ok { |
| + t.Fatal("boot cleared") |
| + } |
| + // A box already launched without Boot cannot gain one later. |
| + s2, _, b2, now2 := managedWorkerFixture(t) |
| + b2 = workerAdvance(t, s2, b2, func(b *managedBox) { |
| + b.State = "launching" |
| + b.LaunchStartedAt = now2 |
| + b.EnrolExpires = now2.Add(30 * time.Minute) |
| + }) |
| + next = b2 |
| + next.Boot = managedExpectedBoot(s2, "v0.34.0", managedTestSeed) |
| + if ok, err := s2.store.AdvanceManagedBox(context.Background(), b2, next); err == nil || ok { |
| + t.Fatal("late boot accepted") |
| + } |
| + }) |
| + t.Run("launching without boot", func(t *testing.T) { |
| + s, p, b, now := managedWorkerFixture(t) |
| + workerAdvance(t, s, b, func(b *managedBox) { |
| + b.State = "launching" |
| + b.LaunchStartedAt = now |
| + b.EnrolExpires = now.Add(30 * time.Minute) |
| + }) |
| + if _, err := s.managedLaunchRequest(workerBox(t, s)); err == nil { |
| + t.Fatal("zero Boot rendered") |
| + } |
| + got := workerStep(t, s, now.Add(time.Second)) |
| + if p.Calls()["Launch"] != 0 || got.State != "failed" || got.LastError != "managed_boot_missing" { |
| + t.Fatalf("zero Boot launched: %+v %v", got, p.Calls()) |
| + } |
| + }) |
| +} |
| + |
| +func setManagedHistoryIncomplete(t *testing.T, s *Server) { |
| + t.Helper() |
| + setManagedHistory(t, s, provision.HostsState{Mode: provision.HostsModeIncomplete}) |
| +} |
| + |
| +func seedHTTP(s *Server, body, ip string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("POST", "/api/fleet/enrol/seed", strings.NewReader(body)) |
| + r.RemoteAddr = ip + ":1234" |
| + w := httptest.NewRecorder() |
| + s.handleManagedSeed(w, r) |
| + return w |
| +} |
| +func seedBody(token string) string { return fmt.Sprintf(`{"token":%q}`, token) } |
| + |
| +// managedSeedTestStore fails or holds seed reads. |
| +type managedSeedTestStore struct { |
| + release.Store |
| + fail bool |
| + hold chan struct{} |
| + started chan struct{} |
| +} |
| + |
| +func (st *managedSeedTestStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + if st.fail && strings.HasPrefix(key, "bootstrap/") { |
| + return nil, "", errors.New("store unavailable") |
| + } |
| + b, etag, err := st.Store.Get(ctx, key) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + if st.hold != nil && strings.HasPrefix(key, "bootstrap/") { |
| + st.started <- struct{}{} |
| + return &heldBody{Reader: bytes.NewReader(b), hold: st.hold, size: int64(len(b))}, etag, nil |
| + } |
| + return &heldBody{Reader: bytes.NewReader(b), size: int64(len(b))}, etag, nil |
| +} |
| + |
| +type heldBody struct { |
| + *bytes.Reader |
| + hold chan struct{} |
| + size int64 |
| + once sync.Once |
| +} |
| + |
| +func (h *heldBody) Read(p []byte) (int, error) { |
| + if h.hold != nil { |
| + h.once.Do(func() { <-h.hold }) |
| + } |
| + return h.Reader.Read(p) |
| +} |
| +func (h *heldBody) Close() error { return nil } |
| +func (h *heldBody) Size() int64 { return h.size } |
| + |
| +func TestManagedSeedDoor(t *testing.T) { |
| + ctx := context.Background() |
| + t.Run("serves frozen seed without consuming", func(t *testing.T) { |
| + s, b, token, _ := enrolFixture(t) |
| + for _, state := range []string{"launching", "booting"} { |
| + if b.State != state { |
| + b = workerAdvance(t, s, b, func(b *managedBox) { b.State = state }) |
| + } |
| + w := seedHTTP(s, seedBody(token), "192.0.2.10") |
| + if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), managedTestSeed) || w.Header().Get("Content-Length") != fmt.Sprint(len(managedTestSeed)) || |
| + w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Content-Type") != "application/octet-stream" { |
| + t.Fatalf("%s: %d %v %q", state, w.Code, w.Header(), w.Body.String()) |
| + } |
| + managedNoToken(t, w, token) |
| + } |
| + if got := workerBox(t, s); !got.EnrolUsedAt.IsZero() || got.State != "booting" { |
| + t.Fatalf("seed consumed the token: %+v", got) |
| + } |
| + if w := enrolHTTP(s, enrolBody(token)); w.Code != 200 { |
| + t.Fatalf("enrol after seed: %d %s", w.Code, w.Body.String()) |
| + } |
| + // The seed door follows the enrolment claim: a used token is refused. |
| + if w := seedHTTP(s, seedBody(token), "192.0.2.11"); w.Code != 403 { |
| + t.Fatalf("used token: %d", w.Code) |
| + } |
| + }) |
| + t.Run("identical refusals", func(t *testing.T) { |
| + s, b, token, now := enrolFixture(t) |
| + ref := enrolHTTP(s, enrolBody(strings.Repeat("0", 64))) |
| + if ref.Code != 403 { |
| + t.Fatal(ref.Code) |
| + } |
| + for _, tok := range []string{strings.Repeat("0", 64), "unknown", ""} { |
| + w := seedHTTP(s, seedBody(tok), "192.0.2.12") |
| + if w.Code != 403 || w.Body.String() != ref.Body.String() || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("%q: %d %q", tok, w.Code, w.Body.String()) |
| + } |
| + } |
| + for name, at := range map[string]time.Time{"expired": b.EnrolExpires, "before launch": b.LaunchStartedAt.Add(-time.Second)} { |
| + if _, err := s.managedSeedFor(ctx, token, at); err != errManagedEnrolForbidden { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + if f, err := s.managedSeedFor(ctx, token, now); err != nil || f != b.Boot { |
| + t.Fatalf("valid: %v", err) |
| + } |
| + used := workerAdvance(t, s, b, func(b *managedBox) { b.EnrolUsedAt = now }) |
| + if _, err := s.managedSeedFor(ctx, token, now); err != errManagedEnrolForbidden || used.EnrolUsedAt.IsZero() { |
| + t.Fatal("used token served", err) |
| + } |
| + // A reservation that never launched has no seed. |
| + s2, _, b2, now2 := managedWorkerFixture(t) |
| + key, _, _ := openManagedEnrolKey(s2.cfg.AlertSealKeyPath) |
| + tok2, _ := deriveManagedEnrolToken(key, b2.ClientToken) |
| + s2.cli = newCLILimits() |
| + if _, err := s2.managedSeedFor(ctx, tok2, now2); err != errManagedEnrolForbidden { |
| + t.Fatal("reserved box served", err) |
| + } |
| + if w := seedHTTP(s2, seedBody(tok2), "192.0.2.13"); w.Code != 403 || w.Body.String() != ref.Body.String() { |
| + t.Fatal(w.Code) |
| + } |
| + }) |
| + t.Run("store and SQL failures retry", func(t *testing.T) { |
| + s, _, token, _ := enrolFixture(t) |
| + s.cfg.Releases = &managedSeedTestStore{Store: s.cfg.Releases, fail: true} |
| + w := seedHTTP(s, seedBody(token), "192.0.2.14") |
| + if w.Code != 503 || w.Header().Get("Retry-After") != "5" || w.Header().Get("Cache-Control") != "no-store" { |
| + t.Fatalf("store failure: %d %v", w.Code, w.Header()) |
| + } |
| + managedNoToken(t, w, token) |
| + s.store.Close() |
| + if w = seedHTTP(s, seedBody(token), "192.0.2.15"); w.Code != 503 || w.Header().Get("Retry-After") != "5" { |
| + t.Fatalf("SQL failure: %d", w.Code) |
| + } |
| + }) |
| + t.Run("limiters", func(t *testing.T) { |
| + s, _, token, _ := enrolFixture(t) |
| + s.cli.managedEnrolIP = newRateLimiter(1, time.Minute) |
| + s.cli.managedEnrolGlobal = newRateLimiter(2, time.Minute) |
| + if w := seedHTTP(s, seedBody(token), "192.0.2.20"); w.Code != 200 { |
| + t.Fatal(w.Code) |
| + } |
| + // The per-IP refusal does not spend the deployment budget. |
| + if w := seedHTTP(s, seedBody(token), "192.0.2.20"); w.Code != 429 || w.Header().Get("Retry-After") != "60" { |
| + t.Fatalf("ip limit: %d", w.Code) |
| + } |
| + if w := seedHTTP(s, seedBody(token), "192.0.2.21"); w.Code != 200 { |
| + t.Fatalf("global spent by an IP refusal: %d", w.Code) |
| + } |
| + if w := seedHTTP(s, seedBody(token), "192.0.2.22"); w.Code != 429 { |
| + t.Fatalf("global limit: %d", w.Code) |
| + } |
| + // Enrolment shares the same budgets. |
| + s.cli.managedEnrolGlobal = newRateLimiter(100, time.Minute) |
| + r := httptest.NewRequest("POST", "/api/fleet/enrol", strings.NewReader(enrolBody(token))) |
| + r.RemoteAddr = "192.0.2.20:1234" |
| + w := httptest.NewRecorder() |
| + s.handleManagedEnrol(w, r) |
| + if w.Code != 429 { |
| + t.Fatalf("enrol after seed from the same IP: %d", w.Code) |
| + } |
| + }) |
| + t.Run("host claim", func(t *testing.T) { |
| + s, _, token, _ := enrolFixture(t) |
| + s.cfg.HostClaim = true |
| + w := seedHTTP(s, seedBody(token), "192.0.2.30") |
| + if w.Code != 409 || !strings.Contains(w.Body.String(), errManagedHostClaim.Error()) { |
| + t.Fatalf("%d %s", w.Code, w.Body.String()) |
| + } |
| + }) |
| + t.Run("strict body", func(t *testing.T) { |
| + s, b, token, _ := enrolFixture(t) |
| + full, _ := json.Marshal(managedboot.LaunchInput{Frozen: b.Boot, Fleet: b.Fleet, Label: b.Label, Op: b.OpID, Token: token, Expires: b.EnrolExpires}) |
| + for _, body := range []string{ |
| + `{"token":"` + token + `","pad":"` + strings.Repeat("x", 4096) + `"}`, |
| + `{"token":"` + token + `","fleet":"shop"}`, |
| + string(full), |
| + `{}`, |
| + `{"token":null}`, |
| + seedBody(token) + `{}`, |
| + `not json`, |
| + } { |
| + w := seedHTTP(s, body, "192.0.2.31") |
| + if w.Code != 400 { |
| + t.Fatalf("%.60s: %d", body, w.Code) |
| + } |
| + managedNoToken(t, w, token) |
| + } |
| + }) |
| + t.Run("four streams", func(t *testing.T) { |
| + s, _, token, _ := enrolFixture(t) |
| + st := &managedSeedTestStore{Store: s.cfg.Releases, hold: make(chan struct{}), started: make(chan struct{}, 8)} |
| + s.cfg.Releases = st |
| + var wg sync.WaitGroup |
| + codes := make(chan int, 4) |
| + for i := 0; i < 4; i++ { |
| + wg.Add(1) |
| + go func(i int) { |
| + defer wg.Done() |
| + codes <- seedHTTP(s, seedBody(token), fmt.Sprintf("192.0.2.%d", 40+i)).Code |
| + }(i) |
| + } |
| + for i := 0; i < 4; i++ { |
| + select { |
| + case <-st.started: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("streams did not start") |
| + } |
| + } |
| + w := seedHTTP(s, seedBody(token), "192.0.2.50") |
| + if w.Code != 503 || w.Header().Get("Retry-After") != "5" { |
| + t.Fatalf("fifth stream: %d", w.Code) |
| + } |
| + close(st.hold) |
| + wg.Wait() |
| + close(codes) |
| + for c := range codes { |
| + if c != 200 { |
| + t.Fatalf("held stream: %d", c) |
| + } |
| + } |
| + st.hold = nil |
| + if w = seedHTTP(s, seedBody(token), "192.0.2.51"); w.Code != 200 { |
| + t.Fatalf("slots not released: %d", w.Code) |
| + } |
| + }) |
| +} |
| + |
| +func managedNoToken(t *testing.T, w *httptest.ResponseRecorder, token string) { |
| + t.Helper() |
| + if token == "" { |
| + return |
| + } |
| + if strings.Contains(w.Body.String(), token) || strings.Contains(fmt.Sprint(w.Header()), token) { |
| + t.Fatal("response carries the token") |
| + } |
| +} |
| + |
| +func TestManagedEnrolReplyFields(t *testing.T) { |
| + s, b, token, _ := enrolFixture(t) |
| + w := enrolHTTP(s, enrolBody(token)) |
| + if w.Code != 200 { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| + var got map[string]json.RawMessage |
| + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + var keys []string |
| + for k := range got { |
| + keys = append(keys, k) |
| + } |
| + want := []string{"bucket", "bucket_region", "credentials", "fleet", "joining", "label", "op", "tunnel_token", "tunnel_url"} |
| + slices.Sort(keys) |
| + if !reflect.DeepEqual(keys, want) { |
| + t.Fatalf("reply fields %v", keys) |
| + } |
| + var reply managedEnrolReply |
| + _ = json.Unmarshal(w.Body.Bytes(), &reply) |
| + if reply.Bucket != b.Storage.Bucket || reply.BucketRegion != b.Storage.Region || reply.Operation != b.OpID || b.Storage.Bucket == "" || b.Storage.Region == "" || |
| + reply.Fleet != b.Fleet || reply.Label != b.Label || reply.TunnelURL != "https://tunnel.example.com" || !reply.Joining { |
| + t.Fatalf("%+v", reply) |
| + } |
| + forbidden := httptest.NewRecorder() |
| + writeManagedEnrolError(forbidden, errManagedEnrolForbidden) |
| + if forbidden.Body.String() != `{"error":"enrolment token is invalid or unavailable"}`+"\n" { |
| + t.Fatalf("403 body %q", forbidden.Body.String()) |
| + } |
| + retry := httptest.NewRecorder() |
| + writeManagedEnrolError(retry, errManagedEnrolRetryable) |
| + if retry.Code != 503 || retry.Body.String() != `{"error":"enrolment is temporarily unavailable. try again shortly"}`+"\n" { |
| + t.Fatalf("503 body %q", retry.Body.String()) |
| + } |
| + if w = enrolHTTP(s, enrolBody(token)); w.Code != 403 || w.Body.String() != forbidden.Body.String() { |
| + t.Fatal(w.Code, w.Body.String()) |
| + } |
| +} |
diff --git a/internal/console/managedstore.go b/internal/console/managedstore.go| index 77b9abfc1..d49b65427 100644 |
| --- a/internal/console/managedstore.go |
| +++ b/internal/console/managedstore.go |
| @@ -18,6 +18,7 @@ import ( |
| "github.com/carlosframework/platform/internal/compute" |
| "github.com/carlosframework/platform/internal/fleetstore" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -51,6 +52,9 @@ type managedBox struct { |
| EnrolDrainStart int64 `json:"enrol_drain_start"` |
| ConfigGeneration uint64 `json:"config_generation"` |
| Storage fleetstore.FleetStorage |
| + // Boot is frozen in the reserved-to-launching commit and never changes: |
| + // every launch retry renders the same user data from it. |
| + Boot managedboot.Frozen `json:"boot"` |
| } |
| type managedRequest struct { |
| @@ -410,6 +414,14 @@ func (s *Store) AdvanceManagedBox(ctx context.Context, before, after managedBox) |
| if before.EnrolDrainStart != 0 && before.EnrolDrainStart != after.EnrolDrainStart { |
| return false, errors.New("managed enrolment drain is immutable") |
| } |
| + // Boot is set once, together with the first launch time, and is then |
| + // immutable; a box that launched without it never gains one. |
| + if !before.Boot.IsZero() && before.Boot != after.Boot { |
| + return false, errors.New("managed boot inputs are immutable") |
| + } |
| + if before.Boot.IsZero() && !after.Boot.IsZero() && (!before.LaunchStartedAt.IsZero() || after.LaunchStartedAt.IsZero() || after.Boot.Validate() != nil) { |
| + return false, errors.New("managed boot inputs are frozen only at launch") |
| + } |
| if before.CloudID != "" && before.CloudID != after.CloudID { |
| return false, errors.New("managed cloud identity is immutable") |
| } |
diff --git a/internal/console/managedworker.go b/internal/console/managedworker.go| index 6f4059ac3..0465d8ee1 100644 |
| --- a/internal/console/managedworker.go |
| +++ b/internal/console/managedworker.go |
| @@ -3,9 +3,11 @@ package console |
| import ( |
| "bytes" |
| "context" |
| + "crypto/ed25519" |
| "crypto/rand" |
| "crypto/sha256" |
| "database/sql" |
| + "encoding/base64" |
| "encoding/hex" |
| "encoding/json" |
| "errors" |
| @@ -16,6 +18,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/compute" |
| + "github.com/carlosframework/platform/internal/managedboot" |
| ) |
| const managedCallTimeout = 30 * time.Second |
| @@ -284,30 +287,75 @@ func (s *Server) saveManagedBox(ctx context.Context, b, next managedBox, now tim |
| } |
| return nil |
| } |
| + |
| +// errManagedBootMissing: the box has no frozen boot inputs, so no user |
| +// data can be rendered for it. errManagedEnrolKeyChanged: the enrolment key |
| +// no longer derives the box's stored token hash. |
| +var ( |
| + errManagedBootMissing = errors.New("managed_boot_missing") |
| + errManagedEnrolKeyChanged = errors.New("enrolment key changed") |
| +) |
| + |
| +// managedLaunchRequest is the box's frozen launch: its spec plus user data |
| +// rendered from the frozen Boot and the derived one-time token. Retries and |
| +// recoveries render identical bytes whatever the configuration is now. |
| func (s *Server) managedLaunchRequest(b managedBox) (compute.LaunchSpec, error) { |
| + if b.Boot.IsZero() { |
| + return compute.LaunchSpec{}, errManagedBootMissing |
| + } |
| key, _, err := openManagedEnrolKey(s.cfg.AlertSealKeyPath) |
| if err != nil { |
| - return compute.LaunchSpec{}, errors.New("enrolment key changed") |
| + return compute.LaunchSpec{}, errManagedEnrolKeyChanged |
| } |
| token, hash := deriveManagedEnrolToken(key, b.ClientToken) |
| if hash != b.EnrolHash { |
| - return compute.LaunchSpec{}, errors.New("enrolment key changed") |
| - } |
| - // This is the provider-neutral bootstrap payload. Task 2b supplies the |
| - // platform script; no long-lived credential is included here. |
| - data, err := json.Marshal(struct { |
| - Fleet, Label, Operation, Token string |
| - Expires time.Time |
| - }{b.Fleet, b.Label, b.OpID, token, b.EnrolExpires}) |
| + return compute.LaunchSpec{}, errManagedEnrolKeyChanged |
| + } |
| + data, err := managedboot.RenderUserData(managedboot.LaunchInput{Frozen: b.Boot, Fleet: b.Fleet, Label: b.Label, Op: b.OpID, Token: token, Expires: b.EnrolExpires.UTC()}) |
| if err != nil { |
| - return compute.LaunchSpec{}, errManagedWorker |
| + return compute.LaunchSpec{}, err |
| } |
| spec := b.Launch |
| spec.SecurityGroups = append([]string(nil), b.Launch.SecurityGroups...) |
| - spec.UserData = string(data) |
| + spec.UserData = data |
| return spec, nil |
| } |
| +// managedLaunchRefusal is the failure reason for a request that cannot be |
| +// rendered. |
| +func managedLaunchRefusal(err error) string { |
| + switch { |
| + case errors.Is(err, errManagedEnrolKeyChanged): |
| + return errManagedEnrolKeyChanged.Error() |
| + case errors.Is(err, errManagedBootMissing): |
| + return errManagedBootMissing.Error() |
| + } |
| + return "managed_boot_invalid" |
| +} |
| + |
| +// managedBootFrozen is what a box launching in this pass freezes: the |
| +// verified stable pointer's linux-arm64 artifact (one pointer read per |
| +// pass, shared with readiness), this console's origins and its release |
| +// public key. Any missing or invalid part is an error and nothing launches. |
| +func (s *Server) managedBootFrozen(ctx context.Context) (managedboot.Frozen, error) { |
| + p, err := s.managedStable(ctx) |
| + if err != nil { |
| + return managedboot.Frozen{}, err |
| + } |
| + if p == nil { |
| + return managedboot.Frozen{}, errManagedWorker |
| + } |
| + a, ok := p.Current.Artifacts[managedboot.SeedArtifactPlatform] |
| + if !ok || len(s.cfg.ReleasePub) != ed25519.PublicKeySize { |
| + return managedboot.Frozen{}, errManagedWorker |
| + } |
| + f := managedboot.Frozen{Format: managedboot.FormatV1, ConsoleOrigin: s.cfg.Origin, TunnelHost: s.cfg.TunnelHost, ReleasePubkey: base64.StdEncoding.EncodeToString(s.cfg.ReleasePub), SeedVersion: p.Current.Version, SeedKey: a.Key, SeedSHA256: a.SHA256} |
| + if err = f.Validate(); err != nil { |
| + return managedboot.Frozen{}, err |
| + } |
| + return f, nil |
| +} |
| + |
| // managedHeldLock is the fleet lock a worker step holds. Slow provider and |
| // observation calls give it up through managedOutsideLock. |
| type managedHeldLockKey struct{} |
| @@ -409,15 +457,29 @@ func (s *Server) stepManagedBoxHeld(ctx context.Context, b managedBox, now time. |
| if waiting, err := s.managedFleetNeedsOperator(ctx, b); err != nil || waiting { |
| return err |
| } |
| - // Validate before recording an attempt: a changed key on a never-launched |
| - // reservation is positive evidence that no cloud instance exists. |
| - if _, err = s.managedLaunchRequest(b); err != nil { |
| - return s.failManagedBoxHeld(ctx, b, "enrolment key changed", now) |
| + // The boot inputs are read outside the lock. Until they are |
| + // available and valid the box stays reserved under its preparation |
| + // deadline, and nothing is dispatched. |
| + var frozen managedboot.Frozen |
| + var frozenErr error |
| + if err = s.managedOutsideLock(ctx, b, func(c context.Context) { frozen, frozenErr = s.managedBootFrozen(c) }); err != nil { |
| + return err |
| + } |
| + if frozenErr != nil { |
| + return nil |
| } |
| next := b |
| next.State = "launching" |
| next.LaunchStartedAt = now |
| next.EnrolExpires = now.Add(30 * time.Minute) |
| + next.Boot = frozen |
| + // Validate before recording an attempt: a changed key on a never-launched |
| + // reservation is positive evidence that no cloud instance exists. |
| + if _, err = s.managedLaunchRequest(next); err != nil { |
| + return s.failManagedBoxHeld(ctx, b, managedLaunchRefusal(err), now) |
| + } |
| + // Boot is persisted in the same commit as the launch time; the |
| + // first dispatch follows only that commit. |
| if err = s.saveManagedBox(ctx, b, next, now); err != nil { |
| return err |
| } |
| @@ -500,7 +562,7 @@ func (s *Server) findManagedBox(ctx context.Context, b managedBox) ([]compute.In |
| func (s *Server) launchManagedBox(ctx context.Context, b managedBox, now time.Time, firstDispatch bool) error { |
| spec, err := s.managedLaunchRequest(b) |
| if err != nil { |
| - return s.failManagedBoxHeld(ctx, b, "enrolment key changed", now) |
| + return s.failManagedBoxHeld(ctx, b, managedLaunchRefusal(err), now) |
| } |
| if s.cfg.ManagedCompute == nil { |
| return nil |
diff --git a/internal/console/managedworker_test.go b/internal/console/managedworker_test.go| index 5fbd93fe0..777a6f8a4 100644 |
| --- a/internal/console/managedworker_test.go |
| +++ b/internal/console/managedworker_test.go |
| @@ -75,6 +75,7 @@ func TestManagedRestartBeforeDispatch(t *testing.T) { |
| b.State = "launching" |
| b.LaunchStartedAt = now |
| b.EnrolExpires = now.Add(30 * time.Minute) |
| + b.Boot = managedExpectedBoot(s, "v0.34.0", managedTestSeed) |
| }) |
| want, err := s.managedLaunchRequest(b) |
| if err != nil { |
diff --git a/internal/console/server.go b/internal/console/server.go| index 82b62867a..1b493b415 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -2235,6 +2235,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // all run before any field of the message is trusted. |
| s.registerRoute("POST /api/ses/events", s.handleSESEvents) |
| s.registerRoute("POST /api/fleet/enrol", s.handleManagedEnrol) |
| + // The seed door (managedseed.go): the same public, token-bound shape as |
| + // enrolment, read-only, and it never consumes the token. |
| + s.registerRoute("POST /api/fleet/enrol/seed", s.handleManagedSeed) |
| // The box door of interactive sessions (apiinteractivebox.go, rootfs |
| // apps spec §5.10): no console principal either. The box that owns a |
| // session's instance proves itself with the session's own token from |
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt| index f54897ec6..6f9910c18 100644 |
| --- a/internal/console/testdata/claim-authority-sites.txt |
| +++ b/internal/console/testdata/claim-authority-sites.txt |
| @@ -159,3 +159,4 @@ managedhistory.go|openManagedEnrolCredentials|seal.Open(sealed) |
| hacapacity_observe.go|Get|os.Open(filepath.Join(s.directory, filepath.FromSlash(key))) |
| hacapacity_observe.go|dirPage|os.Open(filepath.Join(s.directory, filepath.FromSlash(prefix))) |
| demo_claim_seed.go|publishDemoClaimSeed|os.Open(path) |
| +managedseed.go|openManagedSeed|o.Open(ctx, key) |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 0875511de..7f569545d 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -348,6 +348,7 @@ route POST /api/cli/system/rollback |
| route POST /api/cli/system/seeds-floor |
| route POST /api/cli/system/update |
| route POST /api/fleet/enrol |
| +route POST /api/fleet/enrol/seed |
| route POST /api/fleet/replicas/{account}/{app}/{host}/coordinator |
| route POST /api/fleet/replicas/{account}/{app}/{host}/release |
| route POST /api/ses/events |
diff --git a/internal/managedboot/boottest/boottest.go b/internal/managedboot/boottest/boottest.go| new file mode 100644 |
| index 000000000..35ed39047 |
| --- /dev/null |
| +++ b/internal/managedboot/boottest/boottest.go |
| @@ -0,0 +1,132 @@ |
| +//go:build linux |
| + |
| +// Package boottest runs a rendered managed cloud-init script for tests: in |
| +// a scratch root prefix, with logging shims for the commands that change |
| +// the machine and the real curl and python3 behind logging pass-throughs. |
| +// Only tests import it. |
| +package boottest |
| + |
| +import ( |
| + "bytes" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// Harness is one prepared run. |
| +type Harness struct { |
| + Root string // CARLOS_MANAGED_BOOT_ROOT |
| + Bin string // shim directory, first on PATH |
| + Log string // one line per shimmed call |
| + Script string |
| + Env []string |
| +} |
| + |
| +// ServiceUID is what the id shim reports for the carlos user. |
| +const ServiceUID = "64000" |
| + |
| +// New writes script and the shims. owner, when nonempty, is passed as |
| +// CARLOS_MANAGED_BOOT_OWNER; caBundle, when nonempty, as CURL_CA_BUNDLE. |
| +func New(t testing.TB, script, owner, caBundle string) *Harness { |
| + t.Helper() |
| + dir := t.TempDir() |
| + h := &Harness{Root: filepath.Join(dir, "root"), Bin: filepath.Join(dir, "bin"), Log: filepath.Join(dir, "calls.log"), Script: filepath.Join(dir, "user-data")} |
| + for _, d := range []string{h.Root, h.Bin, filepath.Join(dir, "home"), filepath.Join(h.Root, "etc")} { |
| + if err := os.MkdirAll(d, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := os.WriteFile(filepath.Join(h.Root, "etc/os-release"), []byte("PRETTY_NAME=\"Debian GNU/Linux 13 (trixie)\"\nVERSION_CODENAME=trixie\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(h.Script, []byte(script), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + logLine := `printf '%s\n' "$(basename "$0") $*" | tr '\n' ' ' >>` + shQuote(h.Log) + `; echo >>` + shQuote(h.Log) + "\n" |
| + shims := map[string]string{ |
| + "apt-get": "exit 0\n", |
| + "nft": "exit 0\n", |
| + "systemctl": "exit 0\n", |
| + "useradd": "exit 0\n", |
| + "chown": "exit 0\n", |
| + "id": "[ \"$1\" = -u ] && echo " + ServiceUID + "\nexit 0\n", |
| + "timeout": "shift\nexec \"$@\"\n", |
| + } |
| + for _, real := range []string{"curl", "python3"} { |
| + path, err := exec.LookPath(real) |
| + if err != nil { |
| + t.Fatalf("%s is required: %v", real, err) |
| + } |
| + shims[real] = "exec " + shQuote(path) + " \"$@\"\n" |
| + } |
| + for name, body := range shims { |
| + if err := os.WriteFile(filepath.Join(h.Bin, name), []byte("#!/bin/sh\n"+logLine+body), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + h.Env = []string{"PATH=" + h.Bin + ":/usr/bin:/bin", "HOME=" + filepath.Join(dir, "home"), "LANG=C", "CARLOS_MANAGED_BOOT_ROOT=" + h.Root} |
| + if owner != "" { |
| + h.Env = append(h.Env, "CARLOS_MANAGED_BOOT_OWNER="+owner) |
| + } |
| + if caBundle != "" { |
| + h.Env = append(h.Env, "CURL_CA_BUNDLE="+caBundle) |
| + } |
| + return h |
| +} |
| + |
| +func shQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } |
| + |
| +// Run executes the script as cloud-init would, with /bin/sh, and returns |
| +// its standard output and exit error. |
| +func (h *Harness) Run(t testing.TB) (string, error) { |
| + t.Helper() |
| + cmd := exec.Command("/bin/sh", h.Script) |
| + cmd.Env = h.Env |
| + cmd.Dir = filepath.Dir(h.Script) |
| + var out, errOut bytes.Buffer |
| + cmd.Stdout, cmd.Stderr = &out, &errOut |
| + err := cmd.Run() |
| + if err != nil { |
| + t.Logf("script stderr: %s", errOut.String()) |
| + } |
| + return out.String(), err |
| +} |
| + |
| +// Calls is the shim log, one entry per call. |
| +func (h *Harness) Calls(t testing.TB) []string { |
| + t.Helper() |
| + b, err := os.ReadFile(h.Log) |
| + if err != nil && !os.IsNotExist(err) { |
| + t.Fatal(err) |
| + } |
| + var out []string |
| + for _, line := range strings.Split(string(b), "\n") { |
| + if line = strings.TrimSpace(line); line != "" { |
| + out = append(out, line) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// Path is p (absolute, as on the box) under the root prefix. |
| +func (h *Harness) Path(p string) string { return filepath.Join(h.Root, p) } |
| + |
| +// Heredoc returns the body of the heredoc opened by a line ending in |
| +// "<<'"+name+"'" (or "<<"+name), without its delimiter lines. |
| +func Heredoc(script, name string) string { |
| + lines := strings.Split(script, "\n") |
| + for i, line := range lines { |
| + if strings.HasSuffix(line, "<<'"+name+"'") || strings.HasSuffix(line, "<<"+name) { |
| + var body []string |
| + for _, l := range lines[i+1:] { |
| + if l == name { |
| + return strings.Join(body, "\n") + "\n" |
| + } |
| + body = append(body, l) |
| + } |
| + } |
| + } |
| + return "" |
| +} |
diff --git a/internal/managedboot/breadcrumb.go b/internal/managedboot/breadcrumb.go| new file mode 100644 |
| index 000000000..c899de18a |
| --- /dev/null |
| +++ b/internal/managedboot/breadcrumb.go |
| @@ -0,0 +1,19 @@ |
| +package managedboot |
| + |
| +// Breadcrumb codes are the only words a managed box's console output can |
| +// contribute to diagnostics. They match the provider adapter's sanitizer |
| +// list exactly and never carry values. |
| +const ( |
| + CodeSeedVerified = "seed_verified" |
| + CodeEnrolPending = "enrol_pending" |
| + CodeEnrolFailed = "enrol_failed" |
| + CodeStableVerified = "stable_verified" |
| + CodeJoining = "joining" |
| + CodeBootstrapFailed = "bootstrap_failed" |
| +) |
| + |
| +// BreadcrumbPrefix starts every breadcrumb line. |
| +const BreadcrumbPrefix = "CARLOS_BOOT:" |
| + |
| +// Breadcrumb is the console line for code. |
| +func Breadcrumb(code string) string { return BreadcrumbPrefix + code } |
diff --git a/internal/managedboot/cloudinit_v1.sh.tmpl b/internal/managedboot/cloudinit_v1.sh.tmpl| new file mode 100644 |
| index 000000000..994bf7631 |
| --- /dev/null |
| +++ b/internal/managedboot/cloudinit_v1.sh.tmpl |
| @@ -0,0 +1,179 @@ |
| +#!/bin/sh |
| +# CARLOS managed box first boot, format 1. Every value was allowlisted. |
| +set -eu |
| +umask 077 |
| +if [ "${CARLOS_MANAGED_BOOT_BOUNDED:-}" != 1 ]; then |
| + export CARLOS_MANAGED_BOOT_BOUNDED=1 |
| + exec timeout 900 /bin/sh "$0" |
| +fi |
| +crumb() { printf 'CARLOS_BOOT:%s\n' "$1"; } |
| +trap 'rc=$?; [ "$rc" = 0 ] || crumb bootstrap_failed' EXIT |
| +trap 'exit 1' HUP INT TERM |
| +R=${CARLOS_MANAGED_BOOT_ROOT:-} |
| +B=$R/var/lib/carlos-managed-boot |
| +ORIGIN={{sq .Origin}} |
| +export DEBIAN_FRONTEND=noninteractive |
| + |
| +# Root-owned real directories only; staging is on the root disk. |
| +python3 -I - <<'PYDIR' |
| +import os, stat |
| +E = os.environ |
| +R = E.get('CARLOS_MANAGED_BOOT_ROOT', '') |
| +O = tuple(int(x) for x in E.get('CARLOS_MANAGED_BOOT_OWNER', '0:0').split(':')) if R else (0, 0) |
| +W = 'var/lib/carlos-managed-boot' |
| +for path in ('etc/systemd/system/carlos-managed-boot.service.d', 'etc/systemd/system/carlos-edge.service.d', W): |
| + fd = os.open(R or '/', os.O_RDONLY | os.O_DIRECTORY) |
| + parts = path.split('/') |
| + for n, part in enumerate(parts): |
| + final = path == W and n == len(parts) - 1 |
| + mode = 0o700 if final else 0o755 |
| + made = False |
| + try: |
| + os.mkdir(part, 0o700, dir_fd=fd) |
| + made = True |
| + except FileExistsError: |
| + pass |
| + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) |
| + os.close(fd) |
| + fd = child |
| + if made: |
| + os.fchmod(fd, mode) |
| + st = os.fstat(fd) |
| + if final: |
| + if (st.st_uid, st.st_gid) != O or stat.S_IMODE(st.st_mode) != 0o700: |
| + raise SystemExit('managed_boot_directory') |
| + elif st.st_uid != O[0] or st.st_mode & 0o022: |
| + raise SystemExit('managed_boot_directory') |
| + os.close(fd) |
| +PYDIR |
| + |
| +# put PATH MODE: stdin to PATH (under the root prefix), fsynced, renamed. |
| +P='import os, sys |
| +p, m = sys.argv[1], int(sys.argv[2], 8) |
| +d, t = os.path.dirname(p), p + ".tmp" |
| +try: |
| + os.unlink(t) |
| +except FileNotFoundError: |
| + pass |
| +f = os.open(t, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, m) |
| +os.fchmod(f, m) |
| +with os.fdopen(f, "wb") as w: |
| + w.write(sys.stdin.buffer.read()) |
| + w.flush() |
| + os.fsync(w.fileno()) |
| +os.replace(t, p) |
| +f = os.open(d, os.O_RDONLY | os.O_DIRECTORY) |
| +os.fsync(f) |
| +os.close(f)' |
| +put() { python3 -I -c "$P" "$R$1" "$2"; } |
| + |
| +# Packages come from the HTTPS Debian mirror only. |
| +C=$(sed -n 's/^VERSION_CODENAME=//p' "$R/etc/os-release") |
| +case $C in ''|*[!a-z]*) exit 1 ;; esac |
| +K='[signed-by=/usr/share/keyrings/debian-archive-keyring.gpg]' |
| +printf 'deb %s https://deb.debian.org/debian %s %s-updates main\ndeb %s https://deb.debian.org/debian-security %s-security main\n' "$K" "$C" "$C" "$K" "$C" | put /var/lib/carlos-managed-boot/sources.list 600 |
| +apt-get -q -o Dir::Etc::SourceList="$B/sources.list" -o Dir::Etc::SourceParts=/dev/null update |
| +apt-get -y -q -o Dir::Etc::SourceList="$B/sources.list" -o Dir::Etc::SourceParts=/dev/null install nftables curl ca-certificates python3 |
| +id -u carlos >/dev/null 2>&1 || useradd --system --user-group --no-create-home --shell /usr/sbin/nologin carlos |
| +U=$(id -u carlos) |
| +case $U in ''|*[!0-9]*) exit 1 ;; esac |
| + |
| +# Instance metadata: uid 0 and carlos only; forwarded traffic never. |
| +put /etc/nftables.conf 644 <<NFT |
| +#!/usr/sbin/nft -f |
| +table inet carlos_managed_imds |
| +delete table inet carlos_managed_imds |
| +table inet carlos_managed_imds { |
| + chain output { type filter hook output priority -310; policy accept; |
| + meta skuid != { 0, $U } ip daddr 169.254.169.254 reject |
| + meta skuid != { 0, $U } ip6 daddr fd00:ec2::254 reject |
| + } |
| + chain forward { type filter hook forward priority -310; policy accept; |
| + ip daddr 169.254.169.254 reject |
| + ip6 daddr fd00:ec2::254 reject |
| + } |
| +} |
| +NFT |
| +nft -f "$R/etc/nftables.conf" |
| +systemctl enable nftables.service |
| +nft list table inet carlos_managed_imds >/dev/null |
| + |
| +# The seed check precedes every execution of the seed. |
| +put /var/lib/carlos-managed-boot/verify.py 600 <<'PYVERIFY' |
| +import hashlib, os, re, stat, sys |
| +E = os.environ |
| +R = E.get('CARLOS_MANAGED_BOOT_ROOT', '') |
| +O = tuple(int(x) for x in E.get('CARLOS_MANAGED_BOOT_OWNER', '0:0').split(':')) if R else (0, 0) |
| +W = R + '/var/lib/carlos-managed-boot' |
| +def regular(path, mode): |
| + try: |
| + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) |
| + except OSError: |
| + raise SystemExit('managed_boot_file') |
| + st = os.fstat(fd) |
| + if not stat.S_ISREG(st.st_mode) or (st.st_uid, st.st_gid) != O or stat.S_IMODE(st.st_mode) != mode or st.st_nlink != 1: |
| + os.close(fd) |
| + raise SystemExit('managed_boot_file') |
| + return os.fdopen(fd, 'rb') |
| +if len(sys.argv) != 2 or sys.argv[1] not in ('seed', 'seed.part'): |
| + raise SystemExit('managed_boot_usage') |
| +st = os.lstat(W) |
| +if not stat.S_ISDIR(st.st_mode) or (st.st_uid, st.st_gid) != O or stat.S_IMODE(st.st_mode) != 0o700: |
| + raise SystemExit('managed_boot_directory') |
| +if os.statvfs(W).f_flag & os.ST_NOEXEC: |
| + raise SystemExit('managed_boot_noexec') |
| +with regular(W + '/seed.sha256', 0o600) as f: |
| + want = f.read(65).decode('ascii', 'replace') |
| +if not re.fullmatch('[0-9a-f]{64}', want): |
| + raise SystemExit('managed_boot_digest') |
| +h = hashlib.sha256() |
| +with regular(W + '/' + sys.argv[1], 0o700) as f: |
| + for chunk in iter(lambda: f.read(1 << 20), b''): |
| + h.update(chunk) |
| +if h.hexdigest() != want: |
| + raise SystemExit('managed_boot_digest') |
| +PYVERIFY |
| +put /var/lib/carlos-managed-boot/boot-input.json 600 <<'BOOTINPUT' |
| +{{.BootInput}} |
| +BOOTINPUT |
| +put /var/lib/carlos-managed-boot/seed-request.json 600 <<'SEEDREQUEST' |
| +{{.SeedRequest}} |
| +SEEDREQUEST |
| +printf '%s' {{sq .SeedSHA256}} | put /var/lib/carlos-managed-boot/seed.sha256 600 |
| + |
| +curl --proto =https --tlsv1.2 -fsS --retry 20 --retry-max-time 600 --max-filesize 100663296 -H 'Content-Type: application/json' --data-binary @"$B/seed-request.json" -o "$B/seed.part" "$ORIGIN/api/fleet/enrol/seed" |
| +chmod 0700 "$B/seed.part" |
| +python3 -I "$B/verify.py" seed.part |
| +mv -fT "$B/seed.part" "$B/seed" |
| +rm -f "$B/seed-request.json" |
| +crumb seed_verified |
| + |
| +put /etc/systemd/system/carlos-managed-boot.service 644 <<'UNIT' |
| +[Unit] |
| +Requires=nftables.service |
| +After=nftables.service |
| +Before=carlos-edge.service |
| + |
| +[Service] |
| +Type=oneshot |
| +RemainAfterExit=yes |
| +ExecStart=/usr/bin/python3 -I /var/lib/carlos-managed-boot/verify.py seed |
| +ExecStart=/var/lib/carlos-managed-boot/seed system managed-boot --input /var/lib/carlos-managed-boot/boot-input.json |
| + |
| +[Install] |
| +WantedBy=multi-user.target |
| +UNIT |
| +put /etc/systemd/system/carlos-managed-boot.service.d/10-enrol.conf 644 <<'UNIT' |
| +[Unit] |
| +Wants=network-online.target |
| +After=network-online.target |
| +UNIT |
| +put /etc/systemd/system/carlos-edge.service.d/60-managed.conf 644 <<'UNIT' |
| +[Unit] |
| +Requires=carlos-managed-boot.service |
| +After=carlos-managed-boot.service |
| +UNIT |
| +systemctl daemon-reload |
| +systemctl enable carlos-managed-boot.service |
| +python3 -I "$B/verify.py" seed |
| +systemctl start --no-block carlos-managed-boot.service |
diff --git a/internal/managedboot/frozen.go b/internal/managedboot/frozen.go| new file mode 100644 |
| index 000000000..eed7d7c56 |
| --- /dev/null |
| +++ b/internal/managedboot/frozen.go |
| @@ -0,0 +1,183 @@ |
| +// Package managedboot holds what a console-launched managed box boots from: |
| +// the inputs frozen at launch, the cloud-init renderer and the boot |
| +// breadcrumbs. It is provider-neutral and imports nothing from the console, |
| +// so the root binary can read the same types the console writes. |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "regexp" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// FormatV1 selects cloudinit_v1.sh.tmpl. A later template is a new format; |
| +// a box frozen at v1 keeps rendering v1 for every retry of its launch. |
| +const FormatV1 = 1 |
| + |
| +// MaxUserDataBytes bounds the rendered script, well under the provider's |
| +// 16,384-byte limit. |
| +const MaxUserDataBytes = 12288 |
| + |
| +// SeedArtifactPlatform is the only platform a managed box runs. |
| +const SeedArtifactPlatform = "linux-arm64" |
| + |
| +const ( |
| + // BootDir is root-owned 0700 on the box's root disk. |
| + BootDir = "/var/lib/carlos-managed-boot" |
| + // BootInputPath is the full LaunchInput, root 0600. |
| + BootInputPath = BootDir + "/boot-input.json" |
| + // SeedRequestPath is the seed door request body (the token only), |
| + // root 0600, deleted once the seed is verified. |
| + SeedRequestPath = BootDir + "/seed-request.json" |
| +) |
| + |
| +// Frozen is everything about a box's boot that the console fixes at the |
| +// reserved-to-launching commit and never changes afterwards. |
| +type Frozen struct { |
| + Format int `json:"format"` |
| + ConsoleOrigin string `json:"console_origin"` |
| + TunnelHost string `json:"tunnel_host"` |
| + ReleasePubkey string `json:"release_pubkey"` |
| + SeedVersion string `json:"seed_version"` |
| + SeedKey string `json:"seed_key"` |
| + SeedSHA256 string `json:"seed_sha256"` |
| +} |
| + |
| +// LaunchInput is Frozen plus the per-box values. Token is the one-time |
| +// enrolment token and is never stored by the console. |
| +type LaunchInput struct { |
| + Frozen Frozen `json:"frozen"` |
| + Fleet string `json:"fleet"` |
| + Label string `json:"label"` |
| + Op string `json:"op"` |
| + Token string `json:"token"` |
| + Expires time.Time `json:"expires"` |
| +} |
| + |
| +var ( |
| + nameRE = regexp.MustCompile(`^[a-z0-9-]{1,32}$`) |
| + opRE = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| + hex64RE = regexp.MustCompile(`^[0-9a-f]{64}$`) |
| + labelRE = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`) |
| + versionRE = regexp.MustCompile(`^[0-9A-Za-z._-]{1,64}$`) |
| + seedKeyRE = regexp.MustCompile(`^bootstrap/router/[0-9A-Za-z._-]+/carlos-linux-arm64$`) |
| + errInvalid = errors.New("managedboot: invalid boot input") |
| +) |
| + |
| +func invalid(field string) error { return errors.New("managedboot: invalid " + field) } |
| + |
| +// validHostname is lowercase DNS labels joined by dots, at most 253 bytes. |
| +func validHostname(h string) bool { |
| + if h == "" || len(h) > 253 { |
| + return false |
| + } |
| + for _, label := range strings.Split(h, ".") { |
| + if !labelRE.MatchString(label) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// validOrigin is https://<hostname>[:port] with nothing else: no path, |
| +// query, fragment, userinfo or trailing slash. |
| +func validOrigin(o string) bool { |
| + rest, ok := strings.CutPrefix(o, "https://") |
| + if !ok { |
| + return false |
| + } |
| + host, port, hasPort := strings.Cut(rest, ":") |
| + if hasPort { |
| + n, err := strconv.Atoi(port) |
| + if err != nil || n < 1 || n > 65535 || strconv.Itoa(n) != port { |
| + return false |
| + } |
| + } |
| + return validHostname(host) |
| +} |
| + |
| +// IsZero reports whether f was never frozen. |
| +func (f Frozen) IsZero() bool { return f == Frozen{} } |
| + |
| +// Validate checks every field against its allowlist. |
| +func (f Frozen) Validate() error { |
| + switch { |
| + case f.Format != FormatV1: |
| + return invalid("format") |
| + case !validOrigin(f.ConsoleOrigin): |
| + return invalid("console origin") |
| + case !validHostname(f.TunnelHost): |
| + return invalid("tunnel host") |
| + case !validPubkey(f.ReleasePubkey): |
| + return invalid("release public key") |
| + case !versionRE.MatchString(f.SeedVersion) || f.SeedVersion == "." || f.SeedVersion == "..": |
| + return invalid("seed version") |
| + case !seedKeyRE.MatchString(f.SeedKey) || f.SeedKey != "bootstrap/router/"+f.SeedVersion+"/carlos-"+SeedArtifactPlatform: |
| + return invalid("seed key") |
| + case !hex64RE.MatchString(f.SeedSHA256): |
| + return invalid("seed digest") |
| + } |
| + return nil |
| +} |
| + |
| +func validPubkey(s string) bool { |
| + b, err := base64.StdEncoding.DecodeString(s) |
| + return err == nil && len(b) == 32 && base64.StdEncoding.EncodeToString(b) == s |
| +} |
| + |
| +// Validate checks the frozen inputs and every per-box field. |
| +func (in LaunchInput) Validate() error { |
| + if err := in.Frozen.Validate(); err != nil { |
| + return err |
| + } |
| + switch { |
| + case !nameRE.MatchString(in.Fleet): |
| + return invalid("fleet") |
| + case !nameRE.MatchString(in.Label): |
| + return invalid("label") |
| + case !opRE.MatchString(in.Op): |
| + return invalid("operation") |
| + case !hex64RE.MatchString(in.Token): |
| + return invalid("token") |
| + case in.Expires.IsZero() || in.Expires.Location() != time.UTC: |
| + return invalid("expiry") |
| + } |
| + return nil |
| +} |
| + |
| +// encodeLaunchInput is the one encoding of a LaunchInput: the bytes the |
| +// rendered script writes to BootInputPath, without the heredoc's newline. |
| +func encodeLaunchInput(in LaunchInput) ([]byte, error) { |
| + return json.Marshal(in) |
| +} |
| + |
| +// DecodeLaunchInput reads BootInputPath. It is strict: unknown fields, |
| +// trailing values and invalid fields are refused, and the bytes must be the |
| +// canonical encoding the console rendered (one trailing newline allowed), |
| +// so a case-folded or duplicated key cannot change what root reads. |
| +func DecodeLaunchInput(b []byte) (LaunchInput, error) { |
| + var in LaunchInput |
| + dec := json.NewDecoder(bytes.NewReader(b)) |
| + dec.DisallowUnknownFields() |
| + if err := dec.Decode(&in); err != nil { |
| + return LaunchInput{}, errInvalid |
| + } |
| + var extra any |
| + if dec.Decode(&extra) != io.EOF { |
| + return LaunchInput{}, errInvalid |
| + } |
| + if err := in.Validate(); err != nil { |
| + return LaunchInput{}, err |
| + } |
| + canonical, err := encodeLaunchInput(in) |
| + if err != nil || !bytes.Equal(canonical, bytes.TrimSuffix(b, []byte("\n"))) { |
| + return LaunchInput{}, errInvalid |
| + } |
| + return in, nil |
| +} |
diff --git a/internal/managedboot/testdata/userdata-v1.golden b/internal/managedboot/testdata/userdata-v1.golden| new file mode 100644 |
| index 000000000..ef4546897 |
| --- /dev/null |
| +++ b/internal/managedboot/testdata/userdata-v1.golden |
| @@ -0,0 +1,179 @@ |
| +#!/bin/sh |
| +# CARLOS managed box first boot, format 1. Every value was allowlisted. |
| +set -eu |
| +umask 077 |
| +if [ "${CARLOS_MANAGED_BOOT_BOUNDED:-}" != 1 ]; then |
| + export CARLOS_MANAGED_BOOT_BOUNDED=1 |
| + exec timeout 900 /bin/sh "$0" |
| +fi |
| +crumb() { printf 'CARLOS_BOOT:%s\n' "$1"; } |
| +trap 'rc=$?; [ "$rc" = 0 ] || crumb bootstrap_failed' EXIT |
| +trap 'exit 1' HUP INT TERM |
| +R=${CARLOS_MANAGED_BOOT_ROOT:-} |
| +B=$R/var/lib/carlos-managed-boot |
| +ORIGIN='https://console.example.com' |
| +export DEBIAN_FRONTEND=noninteractive |
| + |
| +# Root-owned real directories only; staging is on the root disk. |
| +python3 -I - <<'PYDIR' |
| +import os, stat |
| +E = os.environ |
| +R = E.get('CARLOS_MANAGED_BOOT_ROOT', '') |
| +O = tuple(int(x) for x in E.get('CARLOS_MANAGED_BOOT_OWNER', '0:0').split(':')) if R else (0, 0) |
| +W = 'var/lib/carlos-managed-boot' |
| +for path in ('etc/systemd/system/carlos-managed-boot.service.d', 'etc/systemd/system/carlos-edge.service.d', W): |
| + fd = os.open(R or '/', os.O_RDONLY | os.O_DIRECTORY) |
| + parts = path.split('/') |
| + for n, part in enumerate(parts): |
| + final = path == W and n == len(parts) - 1 |
| + mode = 0o700 if final else 0o755 |
| + made = False |
| + try: |
| + os.mkdir(part, 0o700, dir_fd=fd) |
| + made = True |
| + except FileExistsError: |
| + pass |
| + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) |
| + os.close(fd) |
| + fd = child |
| + if made: |
| + os.fchmod(fd, mode) |
| + st = os.fstat(fd) |
| + if final: |
| + if (st.st_uid, st.st_gid) != O or stat.S_IMODE(st.st_mode) != 0o700: |
| + raise SystemExit('managed_boot_directory') |
| + elif st.st_uid != O[0] or st.st_mode & 0o022: |
| + raise SystemExit('managed_boot_directory') |
| + os.close(fd) |
| +PYDIR |
| + |
| +# put PATH MODE: stdin to PATH (under the root prefix), fsynced, renamed. |
| +P='import os, sys |
| +p, m = sys.argv[1], int(sys.argv[2], 8) |
| +d, t = os.path.dirname(p), p + ".tmp" |
| +try: |
| + os.unlink(t) |
| +except FileNotFoundError: |
| + pass |
| +f = os.open(t, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, m) |
| +os.fchmod(f, m) |
| +with os.fdopen(f, "wb") as w: |
| + w.write(sys.stdin.buffer.read()) |
| + w.flush() |
| + os.fsync(w.fileno()) |
| +os.replace(t, p) |
| +f = os.open(d, os.O_RDONLY | os.O_DIRECTORY) |
| +os.fsync(f) |
| +os.close(f)' |
| +put() { python3 -I -c "$P" "$R$1" "$2"; } |
| + |
| +# Packages come from the HTTPS Debian mirror only. |
| +C=$(sed -n 's/^VERSION_CODENAME=//p' "$R/etc/os-release") |
| +case $C in ''|*[!a-z]*) exit 1 ;; esac |
| +K='[signed-by=/usr/share/keyrings/debian-archive-keyring.gpg]' |
| +printf 'deb %s https://deb.debian.org/debian %s %s-updates main\ndeb %s https://deb.debian.org/debian-security %s-security main\n' "$K" "$C" "$C" "$K" "$C" | put /var/lib/carlos-managed-boot/sources.list 600 |
| +apt-get -q -o Dir::Etc::SourceList="$B/sources.list" -o Dir::Etc::SourceParts=/dev/null update |
| +apt-get -y -q -o Dir::Etc::SourceList="$B/sources.list" -o Dir::Etc::SourceParts=/dev/null install nftables curl ca-certificates python3 |
| +id -u carlos >/dev/null 2>&1 || useradd --system --user-group --no-create-home --shell /usr/sbin/nologin carlos |
| +U=$(id -u carlos) |
| +case $U in ''|*[!0-9]*) exit 1 ;; esac |
| + |
| +# Instance metadata: uid 0 and carlos only; forwarded traffic never. |
| +put /etc/nftables.conf 644 <<NFT |
| +#!/usr/sbin/nft -f |
| +table inet carlos_managed_imds |
| +delete table inet carlos_managed_imds |
| +table inet carlos_managed_imds { |
| + chain output { type filter hook output priority -310; policy accept; |
| + meta skuid != { 0, $U } ip daddr 169.254.169.254 reject |
| + meta skuid != { 0, $U } ip6 daddr fd00:ec2::254 reject |
| + } |
| + chain forward { type filter hook forward priority -310; policy accept; |
| + ip daddr 169.254.169.254 reject |
| + ip6 daddr fd00:ec2::254 reject |
| + } |
| +} |
| +NFT |
| +nft -f "$R/etc/nftables.conf" |
| +systemctl enable nftables.service |
| +nft list table inet carlos_managed_imds >/dev/null |
| + |
| +# The seed check precedes every execution of the seed. |
| +put /var/lib/carlos-managed-boot/verify.py 600 <<'PYVERIFY' |
| +import hashlib, os, re, stat, sys |
| +E = os.environ |
| +R = E.get('CARLOS_MANAGED_BOOT_ROOT', '') |
| +O = tuple(int(x) for x in E.get('CARLOS_MANAGED_BOOT_OWNER', '0:0').split(':')) if R else (0, 0) |
| +W = R + '/var/lib/carlos-managed-boot' |
| +def regular(path, mode): |
| + try: |
| + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) |
| + except OSError: |
| + raise SystemExit('managed_boot_file') |
| + st = os.fstat(fd) |
| + if not stat.S_ISREG(st.st_mode) or (st.st_uid, st.st_gid) != O or stat.S_IMODE(st.st_mode) != mode or st.st_nlink != 1: |
| + os.close(fd) |
| + raise SystemExit('managed_boot_file') |
| + return os.fdopen(fd, 'rb') |
| +if len(sys.argv) != 2 or sys.argv[1] not in ('seed', 'seed.part'): |
| + raise SystemExit('managed_boot_usage') |
| +st = os.lstat(W) |
| +if not stat.S_ISDIR(st.st_mode) or (st.st_uid, st.st_gid) != O or stat.S_IMODE(st.st_mode) != 0o700: |
| + raise SystemExit('managed_boot_directory') |
| +if os.statvfs(W).f_flag & os.ST_NOEXEC: |
| + raise SystemExit('managed_boot_noexec') |
| +with regular(W + '/seed.sha256', 0o600) as f: |
| + want = f.read(65).decode('ascii', 'replace') |
| +if not re.fullmatch('[0-9a-f]{64}', want): |
| + raise SystemExit('managed_boot_digest') |
| +h = hashlib.sha256() |
| +with regular(W + '/' + sys.argv[1], 0o700) as f: |
| + for chunk in iter(lambda: f.read(1 << 20), b''): |
| + h.update(chunk) |
| +if h.hexdigest() != want: |
| + raise SystemExit('managed_boot_digest') |
| +PYVERIFY |
| +put /var/lib/carlos-managed-boot/boot-input.json 600 <<'BOOTINPUT' |
| +{"frozen":{"format":1,"console_origin":"https://console.example.com","tunnel_host":"tunnel.example.com","release_pubkey":"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=","seed_version":"v0.35.0","seed_key":"bootstrap/router/v0.35.0/carlos-linux-arm64","seed_sha256":"abababababababababababababababababababababababababababababababab"},"fleet":"shop","label":"box-1","op":"0123456789abcdef0123456789abcdef","token":"5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e","expires":"2026-11-09T12:30:00Z"} |
| +BOOTINPUT |
| +put /var/lib/carlos-managed-boot/seed-request.json 600 <<'SEEDREQUEST' |
| +{"token":"5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e"} |
| +SEEDREQUEST |
| +printf '%s' 'abababababababababababababababababababababababababababababababab' | put /var/lib/carlos-managed-boot/seed.sha256 600 |
| + |
| +curl --proto =https --tlsv1.2 -fsS --retry 20 --retry-max-time 600 --max-filesize 100663296 -H 'Content-Type: application/json' --data-binary @"$B/seed-request.json" -o "$B/seed.part" "$ORIGIN/api/fleet/enrol/seed" |
| +chmod 0700 "$B/seed.part" |
| +python3 -I "$B/verify.py" seed.part |
| +mv -fT "$B/seed.part" "$B/seed" |
| +rm -f "$B/seed-request.json" |
| +crumb seed_verified |
| + |
| +put /etc/systemd/system/carlos-managed-boot.service 644 <<'UNIT' |
| +[Unit] |
| +Requires=nftables.service |
| +After=nftables.service |
| +Before=carlos-edge.service |
| + |
| +[Service] |
| +Type=oneshot |
| +RemainAfterExit=yes |
| +ExecStart=/usr/bin/python3 -I /var/lib/carlos-managed-boot/verify.py seed |
| +ExecStart=/var/lib/carlos-managed-boot/seed system managed-boot --input /var/lib/carlos-managed-boot/boot-input.json |
| + |
| +[Install] |
| +WantedBy=multi-user.target |
| +UNIT |
| +put /etc/systemd/system/carlos-managed-boot.service.d/10-enrol.conf 644 <<'UNIT' |
| +[Unit] |
| +Wants=network-online.target |
| +After=network-online.target |
| +UNIT |
| +put /etc/systemd/system/carlos-edge.service.d/60-managed.conf 644 <<'UNIT' |
| +[Unit] |
| +Requires=carlos-managed-boot.service |
| +After=carlos-managed-boot.service |
| +UNIT |
| +systemctl daemon-reload |
| +systemctl enable carlos-managed-boot.service |
| +python3 -I "$B/verify.py" seed |
| +systemctl start --no-block carlos-managed-boot.service |
diff --git a/internal/managedboot/userdata.go b/internal/managedboot/userdata.go| new file mode 100644 |
| index 000000000..54c912c91 |
| --- /dev/null |
| +++ b/internal/managedboot/userdata.go |
| @@ -0,0 +1,63 @@ |
| +package managedboot |
| + |
| +import ( |
| + _ "embed" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "text/template" |
| +) |
| + |
| +//go:embed cloudinit_v1.sh.tmpl |
| +var cloudInitV1 string |
| + |
| +// templates maps each Format to its script. A format, once shipped, never |
| +// changes: boxes frozen at it must re-render the same bytes on retry. |
| +var templates = map[int]*template.Template{ |
| + FormatV1: template.Must(template.New("v1").Funcs(template.FuncMap{"sq": shellQuote}).Option("missingkey=error").Parse(cloudInitV1)), |
| +} |
| + |
| +// shellQuote single-quotes an already allowlisted value. A quote in it is |
| +// a renderer bug, never something to escape. |
| +func shellQuote(v string) (string, error) { |
| + if strings.ContainsAny(v, "'\x00\n\r") { |
| + return "", errors.New("managedboot: unquotable value") |
| + } |
| + return "'" + v + "'", nil |
| +} |
| + |
| +type renderData struct { |
| + Origin, SeedSHA256, BootInput, SeedRequest string |
| +} |
| + |
| +// RenderUserData renders in's cloud-init script. It is pure: the same |
| +// input always yields the same bytes, plain text with no compression, and |
| +// any field outside its allowlist or a script over MaxUserDataBytes is |
| +// refused with nothing rendered. |
| +func RenderUserData(in LaunchInput) (string, error) { |
| + if err := in.Validate(); err != nil { |
| + return "", err |
| + } |
| + t := templates[in.Frozen.Format] |
| + if t == nil { |
| + return "", invalid("format") |
| + } |
| + input, err := encodeLaunchInput(in) |
| + if err != nil { |
| + return "", errInvalid |
| + } |
| + request, err := json.Marshal(struct { |
| + Token string `json:"token"` |
| + }{in.Token}) |
| + if err != nil { |
| + return "", errInvalid |
| + } |
| + var out strings.Builder |
| + if err = t.Execute(&out, renderData{Origin: in.Frozen.ConsoleOrigin, SeedSHA256: in.Frozen.SeedSHA256, BootInput: string(input), SeedRequest: string(request)}); err != nil { |
| + return "", errInvalid |
| + } |
| + if out.Len() > MaxUserDataBytes { |
| + return "", errors.New("managedboot: user data is too large") |
| + } |
| + return out.String(), nil |
| +} |
diff --git a/internal/managedboot/userdata_linux_test.go b/internal/managedboot/userdata_linux_test.go| new file mode 100644 |
| index 000000000..b69fd4972 |
| --- /dev/null |
| +++ b/internal/managedboot/userdata_linux_test.go |
| @@ -0,0 +1,203 @@ |
| +package managedboot |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot/boottest" |
| +) |
| + |
| +// helperWrapper runs an extracted script snippet under python3 -I with |
| +// optional patches: "noexec" makes statvfs report a noexec mount, "owner" |
| +// stops at the first filesystem call and prints the expected owner and |
| +// work path the snippet computed. |
| +const helperWrapper = `import os, sys, types |
| +src, mode, args = open(sys.argv[1]).read(), sys.argv[2], sys.argv[3:] |
| +if mode == 'noexec': |
| + real = os.statvfs |
| + os.statvfs = lambda p: types.SimpleNamespace(f_flag=real(p).f_flag | os.ST_NOEXEC) |
| +if mode == 'owner': |
| + def stop(*a, **k): |
| + raise RuntimeError('stop') |
| + os.open = os.lstat = os.mkdir = os.statvfs = stop |
| +sys.argv = ['snippet'] + args |
| +g = {'__name__': '__main__'} |
| +try: |
| + exec(compile(src, 'snippet', 'exec'), g) |
| +except RuntimeError: |
| + if mode != 'owner': |
| + raise |
| +if mode == 'owner': |
| + print(g['O'], g['W']) |
| +` |
| + |
| +type helperRun struct { |
| + t *testing.T |
| + dir string |
| + helper string |
| + wrapper string |
| +} |
| + |
| +func newHelperRun(t *testing.T, script, name string) *helperRun { |
| + t.Helper() |
| + dir := t.TempDir() |
| + h := &helperRun{t: t, dir: dir, helper: filepath.Join(dir, "snippet.py"), wrapper: filepath.Join(dir, "wrap.py")} |
| + body := boottest.Heredoc(script, name) |
| + if body == "" { |
| + t.Fatalf("no %s heredoc", name) |
| + } |
| + if err := os.WriteFile(h.helper, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(h.wrapper, []byte(helperWrapper), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return h |
| +} |
| + |
| +func (h *helperRun) run(mode string, env []string, args ...string) (string, error) { |
| + cmd := exec.Command("python3", append([]string{"-I", h.wrapper, h.helper, mode}, args...)...) |
| + cmd.Env = append([]string{"PATH=/usr/bin:/bin", "LANG=C"}, env...) |
| + out, err := cmd.CombinedOutput() |
| + return string(out), err |
| +} |
| + |
| +func TestManagedCloudInitVerifyHelper(t *testing.T) { |
| + script, err := RenderUserData(goldenInput()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h := newHelperRun(t, script, "PYVERIFY") |
| + owner := fmt.Sprintf("%d:%d", os.Getuid(), os.Getgid()) |
| + seed := []byte("#!/bin/false\nseed bytes\n") |
| + digest := sha256.Sum256(seed) |
| + |
| + // setup builds a fresh root with an exact seed and returns its paths. |
| + setup := func(t *testing.T) (root, work string) { |
| + root = filepath.Join(t.TempDir(), "root") |
| + work = filepath.Join(root, "var/lib/carlos-managed-boot") |
| + if err := os.MkdirAll(work, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(work, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(work, "seed.sha256"), []byte(hex.EncodeToString(digest[:])), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(work, "seed"), seed, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chmod(filepath.Join(work, "seed"), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + return root, work |
| + } |
| + env := func(root, owner string) []string { |
| + return []string{"CARLOS_MANAGED_BOOT_ROOT=" + root, "CARLOS_MANAGED_BOOT_OWNER=" + owner} |
| + } |
| + |
| + root, _ := setup(t) |
| + if out, err := h.run("plain", env(root, owner), "seed"); err != nil { |
| + t.Fatalf("exact bytes refused: %v %s", err, out) |
| + } |
| + |
| + cases := []struct { |
| + name, want string |
| + owner string |
| + mode string |
| + arg string |
| + edit func(t *testing.T, work string) |
| + }{ |
| + {name: "wrong owner", want: "managed_boot_directory", owner: fmt.Sprintf("%d:%d", os.Getuid()+1, os.Getgid())}, |
| + {name: "wrong group", want: "managed_boot_directory", owner: fmt.Sprintf("%d:%d", os.Getuid(), os.Getgid()+1)}, |
| + {name: "directory mode", want: "managed_boot_directory", edit: func(t *testing.T, w string) { must(t, os.Chmod(w, 0o750)) }}, |
| + {name: "noexec", want: "managed_boot_noexec", mode: "noexec"}, |
| + {name: "symlink", want: "managed_boot_file", edit: func(t *testing.T, w string) { |
| + must(t, os.Rename(filepath.Join(w, "seed"), filepath.Join(w, "real"))) |
| + must(t, os.Symlink("real", filepath.Join(w, "seed"))) |
| + }}, |
| + {name: "hardlink", want: "managed_boot_file", edit: func(t *testing.T, w string) { |
| + must(t, os.Link(filepath.Join(w, "seed"), filepath.Join(w, "seed.copy"))) |
| + }}, |
| + {name: "fifo", want: "managed_boot_file", edit: func(t *testing.T, w string) { |
| + must(t, os.Remove(filepath.Join(w, "seed"))) |
| + must(t, syscall.Mkfifo(filepath.Join(w, "seed"), 0o700)) |
| + }}, |
| + {name: "directory seed", want: "managed_boot_file", edit: func(t *testing.T, w string) { |
| + must(t, os.Remove(filepath.Join(w, "seed"))) |
| + must(t, os.Mkdir(filepath.Join(w, "seed"), 0o700)) |
| + }}, |
| + {name: "seed mode", want: "managed_boot_file", edit: func(t *testing.T, w string) { must(t, os.Chmod(filepath.Join(w, "seed"), 0o755)) }}, |
| + {name: "digest mode", want: "managed_boot_file", edit: func(t *testing.T, w string) { must(t, os.Chmod(filepath.Join(w, "seed.sha256"), 0o644)) }}, |
| + {name: "digest symlink", want: "managed_boot_file", edit: func(t *testing.T, w string) { |
| + must(t, os.Rename(filepath.Join(w, "seed.sha256"), filepath.Join(w, "d"))) |
| + must(t, os.Symlink("d", filepath.Join(w, "seed.sha256"))) |
| + }}, |
| + {name: "malformed digest", want: "managed_boot_digest", edit: func(t *testing.T, w string) { writeDigest(t, w, "xyz") }}, |
| + {name: "uppercase digest", want: "managed_boot_digest", edit: func(t *testing.T, w string) { writeDigest(t, w, strings.ToUpper(hex.EncodeToString(digest[:]))) }}, |
| + {name: "digest newline", want: "managed_boot_digest", edit: func(t *testing.T, w string) { writeDigest(t, w, hex.EncodeToString(digest[:])+"\n") }}, |
| + {name: "one byte", want: "managed_boot_digest", edit: func(t *testing.T, w string) { |
| + b := append([]byte(nil), seed...) |
| + b[3] ^= 1 |
| + must(t, os.WriteFile(filepath.Join(w, "seed"), b, 0o700)) |
| + }}, |
| + {name: "missing seed", want: "managed_boot_file", edit: func(t *testing.T, w string) { must(t, os.Remove(filepath.Join(w, "seed"))) }}, |
| + {name: "usage", want: "managed_boot_usage", arg: "../seed"}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + root, work := setup(t) |
| + if c.edit != nil { |
| + c.edit(t, work) |
| + } |
| + o, mode, arg := owner, "plain", "seed" |
| + if c.owner != "" { |
| + o = c.owner |
| + } |
| + if c.mode != "" { |
| + mode = c.mode |
| + } |
| + if c.arg != "" { |
| + arg = c.arg |
| + } |
| + out, err := h.run(mode, env(root, o), arg) |
| + if err == nil || !strings.Contains(out, c.want) { |
| + t.Fatalf("want refusal %s, got %v %q", c.want, err, out) |
| + } |
| + }) |
| + } |
| + |
| + // Hook safety: with no root prefix the owner variable is ignored, for |
| + // the helper and for the directory walk alike. |
| + for name, want := range map[string]string{"PYVERIFY": "(0, 0) /var/lib/carlos-managed-boot", "PYDIR": "(0, 0) var/lib/carlos-managed-boot"} { |
| + s := newHelperRun(t, script, name) |
| + out, err := s.run("owner", []string{"CARLOS_MANAGED_BOOT_OWNER=" + owner}, "seed") |
| + if err != nil || strings.TrimSpace(out) != want { |
| + t.Fatalf("%s without a root prefix: %v %q", name, err, out) |
| + } |
| + out, err = s.run("owner", []string{"CARLOS_MANAGED_BOOT_ROOT=/x", "CARLOS_MANAGED_BOOT_OWNER=" + owner}, "seed") |
| + if err != nil || !strings.HasPrefix(strings.TrimSpace(out), fmt.Sprintf("(%d, %d) ", os.Getuid(), os.Getgid())) { |
| + t.Fatalf("%s with a root prefix: %v %q", name, err, out) |
| + } |
| + } |
| +} |
| + |
| +func writeDigest(t *testing.T, work, s string) { |
| + t.Helper() |
| + must(t, os.WriteFile(filepath.Join(work, "seed.sha256"), []byte(s), 0o600)) |
| +} |
| + |
| +func must(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/managedboot/userdata_rootrunner_linux_test.go b/internal/managedboot/userdata_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..0585b0e8a |
| --- /dev/null |
| +++ b/internal/managedboot/userdata_rootrunner_linux_test.go |
| @@ -0,0 +1,111 @@ |
| +//go:build linux && rootrunner |
| + |
| +package managedboot |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/pem" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/managedboot/boottest" |
| +) |
| + |
| +// TestManagedCloudInitRootOwnership runs the rendered script and its |
| +// helpers as real uid 0, where the expected owner is root:root (no owner |
| +// variable), and checks that files owned by the service uid are refused. |
| +// Root runner only: it fails, never skips, without its capability. |
| +func TestManagedCloudInitRootOwnership(t *testing.T) { |
| + if os.Getenv("CARLOS_MANAGED_ROOT_TEST") != "1" { |
| + t.Fatal("CARLOS_MANAGED_ROOT_TEST=1 is required: this witness runs only on the root runner") |
| + } |
| + if os.Geteuid() != 0 { |
| + t.Fatal("this witness must run as uid 0") |
| + } |
| + seed := []byte("#!/bin/false\nroot runner seed\n") |
| + digest := sha256.Sum256(seed) |
| + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Method != http.MethodPost || r.URL.Path != "/api/fleet/enrol/seed" { |
| + http.Error(w, "no", http.StatusNotFound) |
| + return |
| + } |
| + _, _ = io.Copy(io.Discard, r.Body) |
| + w.Header().Set("Content-Type", "application/octet-stream") |
| + _, _ = w.Write(seed) |
| + })) |
| + defer srv.Close() |
| + ca := filepath.Join(t.TempDir(), "ca.pem") |
| + if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + in := goldenInput() |
| + in.Frozen.ConsoleOrigin = srv.URL |
| + in.Frozen.SeedSHA256 = hex.EncodeToString(digest[:]) |
| + script, err := RenderUserData(in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // A root prefix and no owner variable: root:root is the expected owner. |
| + h := boottest.New(t, script, "", ca) |
| + if out, err := h.Run(t); err != nil { |
| + t.Fatalf("root run failed: %v\n%s", err, out) |
| + } |
| + work := h.Path(BootDir) |
| + for name, mode := range map[string]os.FileMode{"seed": 0o700, "seed.sha256": 0o600, "boot-input.json": 0o600, "verify.py": 0o600} { |
| + st, err := os.Lstat(filepath.Join(work, name)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sys := st.Sys().(*syscall.Stat_t) |
| + if sys.Uid != 0 || sys.Gid != 0 || st.Mode().Perm() != mode || !st.Mode().IsRegular() { |
| + t.Fatalf("%s: %v %d:%d", name, st.Mode(), sys.Uid, sys.Gid) |
| + } |
| + } |
| + verify := func() (string, error) { |
| + cmd := exec.Command("python3", "-I", filepath.Join(work, "verify.py"), "seed") |
| + cmd.Env = []string{"PATH=/usr/bin:/bin", "CARLOS_MANAGED_BOOT_ROOT=" + h.Root} |
| + out, err := cmd.CombinedOutput() |
| + return string(out), err |
| + } |
| + if out, err := verify(); err != nil { |
| + t.Fatalf("root:root seed refused: %v %s", err, out) |
| + } |
| + service, _ := strconv.Atoi(boottest.ServiceUID) |
| + for _, path := range []string{filepath.Join(work, "seed"), filepath.Join(work, "seed.sha256"), work} { |
| + if err := os.Lchown(path, service, service); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out, err := verify(); err == nil { |
| + t.Fatalf("%s owned by the service uid accepted: %s", path, out) |
| + } |
| + if err := os.Lchown(path, 0, 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out, err := verify(); err != nil { |
| + t.Fatalf("restored %s refused: %v %s", path, err, out) |
| + } |
| + } |
| + // The directory walk refuses a service-owned ancestor of the boot dir. |
| + walk := filepath.Join(t.TempDir(), "walk.py") |
| + if err := os.WriteFile(walk, []byte(boottest.Heredoc(script, "PYDIR")), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + lib := h.Path("/var/lib") |
| + if err := os.Lchown(lib, service, service); err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command("python3", "-I", walk) |
| + cmd.Env = []string{"PATH=/usr/bin:/bin", "CARLOS_MANAGED_BOOT_ROOT=" + h.Root} |
| + if out, err := cmd.CombinedOutput(); err == nil || !strings.Contains(string(out), "managed_boot_directory") { |
| + t.Fatalf("service-owned ancestor accepted: %v %s", err, out) |
| + } |
| +} |
diff --git a/internal/managedboot/userdata_test.go b/internal/managedboot/userdata_test.go| new file mode 100644 |
| index 000000000..b18f7f659 |
| --- /dev/null |
| +++ b/internal/managedboot/userdata_test.go |
| @@ -0,0 +1,288 @@ |
| +package managedboot |
| + |
| +import ( |
| + "bytes" |
| + "encoding/base64" |
| + "encoding/json" |
| + "flag" |
| + "os" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +var updateGolden = flag.Bool("update", false, "rewrite testdata/userdata-v1.golden") |
| + |
| +func goldenInput() LaunchInput { |
| + return LaunchInput{ |
| + Frozen: Frozen{ |
| + Format: FormatV1, |
| + ConsoleOrigin: "https://console.example.com", |
| + TunnelHost: "tunnel.example.com", |
| + ReleasePubkey: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)), |
| + SeedVersion: "v0.35.0", |
| + SeedKey: "bootstrap/router/v0.35.0/carlos-linux-arm64", |
| + SeedSHA256: strings.Repeat("ab", 32), |
| + }, |
| + Fleet: "shop", |
| + Label: "box-1", |
| + Op: "0123456789abcdef0123456789abcdef", |
| + Token: strings.Repeat("5e", 32), |
| + Expires: time.Date(2026, 11, 9, 12, 30, 0, 0, time.UTC), |
| + } |
| +} |
| + |
| +func TestManagedUserDataGolden(t *testing.T) { |
| + in := goldenInput() |
| + got, err := RenderUserData(in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + again, err := RenderUserData(in) |
| + if err != nil || again != got { |
| + t.Fatal("two renders differ", err) |
| + } |
| + if *updateGolden { |
| + if err = os.WriteFile("testdata/userdata-v1.golden", []byte(got), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + want, err := os.ReadFile("testdata/userdata-v1.golden") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got != string(want) { |
| + t.Fatalf("render differs from the golden file; a template change is a new Format") |
| + } |
| + if len(got) > MaxUserDataBytes { |
| + t.Fatalf("%d bytes", len(got)) |
| + } |
| + if !strings.HasPrefix(got, "#!/bin/sh\n") || bytes.HasPrefix([]byte(got), []byte{0x1f, 0x8b}) { |
| + t.Fatal("not a plain shell script") |
| + } |
| + // Nothing nondeterministic reaches the output: a different clock or |
| + // map iteration cannot change it, and only in's fields vary it. |
| + other := in |
| + other.Label = "box-2" |
| + o, err := RenderUserData(other) |
| + if err != nil || o == got || strings.Replace(got, `"label":"box-1"`, `"label":"box-2"`, 1) != o { |
| + t.Fatal("render is not a function of its input alone") |
| + } |
| +} |
| + |
| +func TestManagedUserDataAllowlist(t *testing.T) { |
| + type edit struct { |
| + name string |
| + fn func(*LaunchInput) |
| + } |
| + str := func(field string, set func(*LaunchInput, string), bad ...string) []edit { |
| + var out []edit |
| + probes := []string{"'", `"`, "$(id)", "`id`", "\n", "\x00", " ", " "} |
| + for _, v := range append(bad, probes...) { |
| + v := v |
| + out = append(out, edit{field + "=" + v, func(in *LaunchInput) { set(in, v) }}) |
| + } |
| + // Injection probes inside an otherwise valid value, too. |
| + for _, p := range probes { |
| + p := p |
| + out = append(out, edit{field + "+" + p, func(in *LaunchInput) { set(in, injectInto(in, field)+p) }}) |
| + } |
| + return out |
| + } |
| + var edits []edit |
| + edits = append(edits, str("fleet", func(in *LaunchInput, v string) { in.Fleet = v }, "", "Shop", "shop_1", strings.Repeat("a", 33), "shop.x")...) |
| + edits = append(edits, str("label", func(in *LaunchInput, v string) { in.Label = v }, "", "Box-1", strings.Repeat("a", 33), "box/1")...) |
| + edits = append(edits, str("op", func(in *LaunchInput, v string) { in.Op = v }, "", strings.Repeat("a", 31), strings.Repeat("a", 33), strings.Repeat("A", 32), strings.Repeat("g", 32))...) |
| + edits = append(edits, str("token", func(in *LaunchInput, v string) { in.Token = v }, "", strings.Repeat("a", 63), strings.Repeat("a", 65), strings.Repeat("A", 64))...) |
| + edits = append(edits, str("origin", func(in *LaunchInput, v string) { in.Frozen.ConsoleOrigin = v }, "", "http://console.example.com", "https://console.example.com/", "https://console.example.com/x", "https://console.example.com?x=1", "https://u@console.example.com", "https://Console.example.com", "https://console.example.com:0", "https://console.example.com:65536", "https://console.example.com:080", "https://console.example.com#x", "https://", "https://-x.example.com")...) |
| + edits = append(edits, str("tunnel", func(in *LaunchInput, v string) { in.Frozen.TunnelHost = v }, "", "https://tunnel.example.com", "tunnel.example.com:443", "tunnel.example.com/", "Tunnel.example.com", "tunnel..example.com")...) |
| + edits = append(edits, str("pubkey", func(in *LaunchInput, v string) { in.Frozen.ReleasePubkey = v }, "", base64.StdEncoding.EncodeToString(make([]byte, 31)), base64.StdEncoding.EncodeToString(make([]byte, 33)), base64.RawStdEncoding.EncodeToString(make([]byte, 32)), base64.URLEncoding.EncodeToString(bytes.Repeat([]byte{0xfb}, 32)))...) |
| + edits = append(edits, str("seed_version", func(in *LaunchInput, v string) { in.Frozen.SeedVersion = v }, "", "v0.36.0", "..", strings.Repeat("v", 65))...) |
| + edits = append(edits, str("seed_key", func(in *LaunchInput, v string) { in.Frozen.SeedKey = v }, "", "bootstrap/router/v0.35.0/carlos-linux-amd64", "bootstrap/console/v0.35.0/carlos-linux-arm64", "/bootstrap/router/v0.35.0/carlos-linux-arm64", "bootstrap/router/v0.35.0/carlos-linux-arm64/", "bootstrap/router//carlos-linux-arm64", "bootstrap/router/v0.35.0/x/carlos-linux-arm64")...) |
| + edits = append(edits, str("sha", func(in *LaunchInput, v string) { in.Frozen.SeedSHA256 = v }, "", strings.Repeat("a", 63), strings.Repeat("A", 64), strings.Repeat("a", 65))...) |
| + edits = append(edits, |
| + edit{"expires zero", func(in *LaunchInput) { in.Expires = time.Time{} }}, |
| + edit{"expires local", func(in *LaunchInput) { in.Expires = in.Expires.In(time.FixedZone("x", 3600)) }}, |
| + edit{"format 0", func(in *LaunchInput) { in.Frozen.Format = 0 }}, |
| + edit{"format 2", func(in *LaunchInput) { in.Frozen.Format = 2 }}, |
| + ) |
| + for _, e := range edits { |
| + in := goldenInput() |
| + e.fn(&in) |
| + if out, err := RenderUserData(in); err == nil || out != "" { |
| + t.Errorf("%q: rendered (err=%v)", e.name, err) |
| + } |
| + if raw, err := json.Marshal(in); err == nil { |
| + if _, err = DecodeLaunchInput(raw); err == nil { |
| + t.Errorf("%q: decoded", e.name) |
| + } |
| + } |
| + } |
| + // Frozen alone validates the same way. |
| + f := goldenInput().Frozen |
| + if f.Validate() != nil || f.IsZero() || !(Frozen{}).IsZero() || (Frozen{}).Validate() == nil { |
| + t.Fatal("frozen validation") |
| + } |
| + // A valid port is fine. |
| + in := goldenInput() |
| + in.Frozen.ConsoleOrigin = "https://127.0.0.1:8443" |
| + if _, err := RenderUserData(in); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Oversized output is refused even with valid fields. |
| + saved := templates[FormatV1] |
| + defer func() { templates[FormatV1] = saved }() |
| + templates[FormatV1] = saved.New("big") |
| + if _, err := templates[FormatV1].Parse(strings.Repeat("#", MaxUserDataBytes+1)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if out, err := RenderUserData(goldenInput()); err == nil || out != "" { |
| + t.Fatal("oversized render accepted") |
| + } |
| +} |
| + |
| +// injectInto returns the field's current valid value, so a probe can be |
| +// appended to it. |
| +func injectInto(in *LaunchInput, field string) string { |
| + switch field { |
| + case "fleet": |
| + return in.Fleet |
| + case "label": |
| + return in.Label |
| + case "op": |
| + return in.Op |
| + case "token": |
| + return in.Token |
| + case "origin": |
| + return in.Frozen.ConsoleOrigin |
| + case "tunnel": |
| + return in.Frozen.TunnelHost |
| + case "pubkey": |
| + return in.Frozen.ReleasePubkey |
| + case "seed_version": |
| + return in.Frozen.SeedVersion |
| + case "seed_key": |
| + return in.Frozen.SeedKey |
| + case "sha": |
| + return in.Frozen.SeedSHA256 |
| + } |
| + panic(field) |
| +} |
| + |
| +// heredocs returns each heredoc's delimiter and body lines, and the lines |
| +// outside any heredoc. |
| +func heredocs(script string) (bodies map[string][]string, outside []string) { |
| + bodies = map[string][]string{} |
| + start := regexp.MustCompile(`<<'?([A-Z]+)'?\s*$`) |
| + lines := strings.Split(script, "\n") |
| + for i := 0; i < len(lines); i++ { |
| + outside = append(outside, lines[i]) |
| + m := start.FindStringSubmatch(lines[i]) |
| + if m == nil { |
| + continue |
| + } |
| + name := m[1] |
| + key := name + ":" + lines[i] |
| + for i++; i < len(lines) && lines[i] != name; i++ { |
| + bodies[key] = append(bodies[key], lines[i]) |
| + } |
| + } |
| + return bodies, outside |
| +} |
| + |
| +func TestManagedUserDataSecrets(t *testing.T) { |
| + in := goldenInput() |
| + script, err := RenderUserData(in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := strings.Count(script, in.Token); n != 2 { |
| + t.Fatalf("token appears %d times", n) |
| + } |
| + if strings.Contains(script, "set -x") || strings.Contains(script, "set -o xtrace") { |
| + t.Fatal("tracing enabled") |
| + } |
| + bodies, outside := heredocs(script) |
| + for _, line := range outside { |
| + if strings.Contains(line, in.Token) { |
| + t.Fatalf("token outside a heredoc: %q", line) |
| + } |
| + } |
| + var input, request []string |
| + for key, body := range bodies { |
| + joined := strings.Join(body, "\n") |
| + switch key { |
| + case "BOOTINPUT:put /var/lib/carlos-managed-boot/boot-input.json 600 <<'BOOTINPUT'": |
| + input = body |
| + case "SEEDREQUEST:put /var/lib/carlos-managed-boot/seed-request.json 600 <<'SEEDREQUEST'": |
| + request = body |
| + default: |
| + if strings.Contains(joined, in.Token) { |
| + t.Fatalf("token inside heredoc %s", key) |
| + } |
| + } |
| + } |
| + if len(request) != 1 || request[0] != `{"token":"`+in.Token+`"}` { |
| + t.Fatalf("seed request %q", request) |
| + } |
| + if len(input) != 1 { |
| + t.Fatalf("boot input %q", input) |
| + } |
| + got, err := DecodeLaunchInput([]byte(input[0] + "\n")) |
| + if err != nil || !reflect.DeepEqual(got, in) { |
| + t.Fatalf("boot input decodes to %+v (%v)", got, err) |
| + } |
| + // Breadcrumbs never carry values. |
| + use := regexp.MustCompile(`\bcrumb (\S+)`) |
| + for _, line := range outside { |
| + for _, m := range use.FindAllStringSubmatch(line, -1) { |
| + code := strings.TrimSuffix(m[1], "'") |
| + if code != CodeSeedVerified && code != CodeBootstrapFailed { |
| + t.Fatalf("breadcrumb line %q", line) |
| + } |
| + } |
| + } |
| + if !strings.Contains(script, "crumb() { printf 'CARLOS_BOOT:%s\\n' \"$1\"; }\n") { |
| + t.Fatal("breadcrumb function changed") |
| + } |
| + // The only environment hooks are the bound marker and the two |
| + // test-only prefix variables. |
| + names := map[string]bool{} |
| + for _, m := range regexp.MustCompile(`CARLOS_[A-Z_]+`).FindAllString(script, -1) { |
| + names[m] = true |
| + } |
| + want := map[string]bool{"CARLOS_MANAGED_BOOT_BOUNDED": true, "CARLOS_MANAGED_BOOT_ROOT": true, "CARLOS_MANAGED_BOOT_OWNER": true, "CARLOS_BOOT": true} |
| + if !reflect.DeepEqual(names, want) { |
| + t.Fatalf("environment names %v", names) |
| + } |
| + if n := strings.Count(script, "CARLOS_MANAGED_BOOT_OWNER"); n != 2 { |
| + t.Fatalf("owner hook appears %d times", n) |
| + } |
| + for _, line := range strings.Split(script, "\n") { |
| + if strings.Contains(line, "CARLOS_MANAGED_BOOT_OWNER") && line != "O = tuple(int(x) for x in E.get('CARLOS_MANAGED_BOOT_OWNER', '0:0').split(':')) if R else (0, 0)" { |
| + t.Fatalf("owner hook outside the guarded line: %q", line) |
| + } |
| + } |
| +} |
| + |
| +func TestManagedDecodeLaunchInputStrict(t *testing.T) { |
| + in := goldenInput() |
| + raw, _ := json.Marshal(in) |
| + if _, err := DecodeLaunchInput(raw); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, bad := range []string{ |
| + strings.Replace(string(raw), `"fleet"`, `"Fleet"`, 1), |
| + strings.Replace(string(raw), `{"frozen"`, `{"fleet":"other","frozen"`, 1), |
| + strings.Replace(string(raw), `"op"`, `"extra":1,"op"`, 1), |
| + string(raw) + `{}`, |
| + string(raw) + "\n\n", |
| + " " + string(raw), |
| + } { |
| + if _, err := DecodeLaunchInput([]byte(bad)); err == nil { |
| + t.Errorf("accepted %s", bad) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/managed_fleets_2b2_census_test.go b/internal/provision/managed_fleets_2b2_census_test.go| new file mode 100644 |
| index 000000000..c1372a149 |
| --- /dev/null |
| +++ b/internal/provision/managed_fleets_2b2_census_test.go |
| @@ -0,0 +1,26 @@ |
| +package provision |
| + |
| +// Record-write census entries for managed fleets 2b-2, layered on |
| +// managedFleets2b1WriteCensusInventory. Reviewed by the branch author; |
| +// independent approval is the controller's, with the 2b-2 census card. |
| +// Task 1 adds no record write: |
| +// - NewServer registers POST /api/fleet/enrol/seed beside enrolment. The |
| +// handler (managedseed.go) reads the managed box row by token hash and |
| +// streams the frozen seed object (bootstrap/router/<v>/carlos-linux-arm64) |
| +// 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. |
| +func managedFleets2b2WriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), managedFleets2b1WriteCensusInventory()...) |
| + 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 { |
| + if e.Class != r.Class || e.Kinds != r.Kinds { |
| + panic("managed-fleets-2b2 re-pin changes the class or kinds of " + r.File + ":" + r.Unit) |
| + } |
| + entries[i] = r |
| + return entries |
| + } |
| + } |
| + panic("managed-fleets-2b2 re-pin of an unlisted unit " + r.File + ":" + r.Unit) |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index bac3cb89c..4626fd1f3 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := managedFleets2b1WriteCensusInventory() |
| + inventory := managedFleets2b2WriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |