fix: bounded fleet key read, retryable door outcomes
Task 4 fix round 1 (Astra R1, Fable R1). - Root reads the fleet-writable key object only through release.Opener and io.LimitReader(4 KiB+1), closes it, and refuses excess as object_invalid (no PUT, no registration); a store with no stream is refused rather than read whole with Store.Get. - fleetIdentityCheck keeps fleetIdentityOK's predicate but returns the FleetOwners and box-listing errors; the managed door answers unavailable evidence with 503 Retry-After 5, and a real mismatch with the same 403. - fleetKeyNotRecorded is now only for failures before any write; an owner record write that failed (possibly committed) or a registry write after it is fleetKeyIncomplete, which the managed door answers 503 "did not finish". The same key converges on retry; another key is still refused. The owner door's answers are unchanged. - A failed local write of host.env or the key status file fails the first boot (bootstrap_failed); key outcomes still never do. - The agent logs a bad status file when the problem starts or changes. - Witnesses: bounded endless read, unwritable status and host.env with recovery, flaky registry lookups, owner-record and registry failures with and without a lost commit, and three first boxes racing through the real door, core and registry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+763
−50
internal/console/apiinteractivebox.go+21 −6internal/console/fleetsecretskey.go+22 −4internal/console/managedfleetkey.go+23 −3internal/console/managedfleetkey_test.go+401 −0internal/host/managedboot.go+5 −2internal/host/managedkey.go+86 −31internal/host/managedkey_test.go+201 −1internal/managedboot/fleetkey.go+4 −3
CI failed — run details
diff --git a/internal/console/apiinteractivebox.go b/internal/console/apiinteractivebox.go| index 638288669..b9d6af51a 100644 |
| --- a/internal/console/apiinteractivebox.go |
| +++ b/internal/console/apiinteractivebox.go |
| @@ -115,17 +115,32 @@ func (s *Server) handleBoxInteractive(w http.ResponseWriter, r *http.Request) { |
| // active; and the sha256 hex of token is its TokenHash (mintFleetToken's |
| // convention), compared in constant time. |
| func fleetIdentityOK(reg consoleRegistry, name, token, wantFleet, wantAccount string) bool { |
| + ok, err := fleetIdentityCheck(reg, name, token, wantFleet, wantAccount) |
| + return ok && err == nil |
| +} |
| + |
| +// fleetIdentityCheck is fleetIdentityOK's predicate with the registry's |
| +// failures kept apart: (false, nil) is a mismatch, and a non-nil error |
| +// means the evidence could not be read (FleetOwners or the box listing |
| +// failed), so nothing was decided. fleetIdentityOK folds both into false. |
| +func fleetIdentityCheck(reg consoleRegistry, name, token, wantFleet, wantAccount string) (bool, error) { |
| fleet, label, ok := strings.Cut(name, "/") |
| if !ok || fleet != wantFleet || !registry.ValidTunnelName(label) || token == "" || wantAccount == "" { |
| - return false |
| + return false, nil |
| } |
| owners, err := reg.FleetOwners() |
| - if err != nil || owners[wantFleet] != wantAccount { |
| - return false |
| + if err != nil { |
| + return false, err |
| + } |
| + if owners[wantFleet] != wantAccount { |
| + return false, nil |
| } |
| box, err := findFleetBox(reg, fleet, label) |
| - if err != nil || box == nil || box.Status != "active" { |
| - return false |
| + if err != nil { |
| + return false, err |
| + } |
| + if box == nil || box.Status != "active" { |
| + return false, nil |
| } |
| - return subtle.ConstantTimeCompare([]byte(hashToken(token)), []byte(box.TokenHash)) == 1 |
| + return subtle.ConstantTimeCompare([]byte(hashToken(token)), []byte(box.TokenHash)) == 1, nil |
| } |
diff --git a/internal/console/fleetsecretskey.go b/internal/console/fleetsecretskey.go| index 39a342981..457b24b90 100644 |
| --- a/internal/console/fleetsecretskey.go |
| +++ b/internal/console/fleetsecretskey.go |
| @@ -106,6 +106,7 @@ func (s *Server) handleAPIFleetSecretsKey(w http.ResponseWriter, r *http.Request |
| var sealed *fleetKeySealedApps |
| var placed *fleetKeyInstances |
| var notRecorded *fleetKeyNotRecorded |
| + var incomplete *fleetKeyIncomplete |
| switch { |
| case errors.Is(err, errFleetKeyPlatformKey): |
| jsonError(w, http.StatusBadRequest, "that is the platform's own secrets key, and a fleet needs its own. mint a new pair with carlos secrets genkey and register its public half") |
| @@ -119,6 +120,10 @@ func (s *Server) handleAPIFleetSecretsKey(w http.ResponseWriter, r *http.Request |
| jsonError(w, http.StatusConflict, "another fleet already uses this secrets key, and every fleet needs its own. mint a new pair with carlos secrets genkey and register its public half") |
| case errors.As(err, ¬Recorded): |
| jsonError(w, notRecorded.Status, fmt.Sprintf("the key was not recorded for %s and nothing was changed. run carlos fleets secrets-key %s %s again", fleet.Name, fleet.Name, pub)) |
| + case errors.As(err, &incomplete): |
| + // The owner door's answer is unchanged from before the core was |
| + // extracted (its sentence predates this classification). |
| + jsonError(w, incomplete.Status, fmt.Sprintf("the key was not recorded for %s and nothing was changed. run carlos fleets secrets-key %s %s again", fleet.Name, fleet.Name, pub)) |
| default: |
| jsonError(w, http.StatusInternalServerError, fmt.Sprintf("the key was not recorded for %s and nothing was changed. run carlos fleets secrets-key %s %s again", fleet.Name, fleet.Name, pub)) |
| } |
| @@ -177,14 +182,27 @@ func (e *fleetKeyInstances) Error() string { |
| return "fleet secrets key: apps on " + e.Fleet + " have instances" |
| } |
| -// fleetKeyNotRecorded is a failure that changed nothing; Status is the |
| -// owner door's answer for it (500 or 502). |
| +// fleetKeyNotRecorded is a failure before the first write, so proven to |
| +// have changed nothing; Status is the owner door's answer for it (500 or |
| +// 502). |
| type fleetKeyNotRecorded struct{ Status int } |
| func (e *fleetKeyNotRecorded) Error() string { |
| return fmt.Sprintf("fleet secrets key: not recorded (%d)", e.Status) |
| } |
| +// fleetKeyIncomplete is a failure once writing began: the owner record |
| +// write failed (it may have committed and lost its answer), or it |
| +// succeeded and the registry write then failed. Something may have |
| +// changed. The same key again converges: the record append is idempotent, |
| +// and the registry row is still the old one or already this key. Status is |
| +// the owner door's answer for it, as before (502 or 500). |
| +type fleetKeyIncomplete struct{ Status int } |
| + |
| +func (e *fleetKeyIncomplete) Error() string { |
| + return fmt.Sprintf("fleet secrets key: registration incomplete (%d)", e.Status) |
| +} |
| + |
| // COPY: the owner door's refusal on a managed fleet awaits copy review. |
| func fleetKeyManagedRefusal(fleet string) string { |
| return fleet + " is a managed fleet, and its first box registers the fleet's secrets key itself. a managed fleet's key cannot be set or replaced with carlos fleets secrets-key yet" |
| @@ -262,14 +280,14 @@ func (s *Server) registerFleetSecretsKey(ctx context.Context, acct *Account, reg |
| } |
| if err := s.recordFleetKeyFP(ctx, *row, fp); err != nil { |
| log.Printf("console: fleet secrets key %s/%s: owner record: %v", acct.Sqid, row.Name, err) |
| - return fleetKeyOutcome{}, &fleetKeyNotRecorded{Status: http.StatusBadGateway} |
| + return fleetKeyOutcome{}, &fleetKeyIncomplete{Status: http.StatusBadGateway} |
| } |
| if err := reg.SetFleetSecretsKey(row.Name, pub, fp, actor, time.Now().Unix()); err != nil { |
| if errors.Is(err, registry.ErrFleetKeyInUse) { |
| return fleetKeyOutcome{}, errFleetKeyInUse |
| } |
| log.Printf("console: fleet secrets key %s/%s: registry: %v", acct.Sqid, row.Name, err) |
| - return fleetKeyOutcome{}, &fleetKeyNotRecorded{Status: http.StatusInternalServerError} |
| + return fleetKeyOutcome{}, &fleetKeyIncomplete{Status: http.StatusInternalServerError} |
| } |
| } |
| unlock() |
diff --git a/internal/console/managedfleetkey.go b/internal/console/managedfleetkey.go| index f13de6cce..a89eb3268 100644 |
| --- a/internal/console/managedfleetkey.go |
| +++ b/internal/console/managedfleetkey.go |
| @@ -35,11 +35,16 @@ const ( |
| managedKeyReplace = "the fleet already has a different secrets key, and a box cannot replace it" |
| managedKeyInUse = "another fleet already uses this secrets key" |
| managedKeyUnavailable = "the secrets key could not be registered right now. try again shortly" |
| + managedKeyIncomplete = "the secrets key registration did not finish. try again shortly" |
| ) |
| // managedOpRE is a managed operation's ID: 16 random bytes in hex. |
| var managedOpRE = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| +// managedKeyRegistry opens the door's registry; a variable so witnesses |
| +// can make its lookups fail and recover. |
| +var managedKeyRegistry = openRegistry |
| + |
| // managedKeyTimeout bounds the door's registry and bucket work. |
| const managedKeyTimeout = 30 * time.Second |
| @@ -90,6 +95,7 @@ func (s *Server) handleManagedFleetKey(w http.ResponseWriter, r *http.Request) { |
| } |
| out, err := s.registerFleetSecretsKey(ctx, acct, reg, in.Fleet, key, "managed-box "+in.Fleet+"/"+in.Label+" op "+in.Op, true) |
| var notRecorded *fleetKeyNotRecorded |
| + var incomplete *fleetKeyIncomplete |
| switch { |
| case err == nil: |
| writeJSON(w, http.StatusOK, managedboot.FleetKeyReply{Fleet: out.Fleet, Fingerprint: out.Fingerprint, Changed: out.Changed}) |
| @@ -100,9 +106,17 @@ func (s *Server) handleManagedFleetKey(w http.ResponseWriter, r *http.Request) { |
| case errors.Is(err, errFleetKeyInUse): |
| jsonError(w, http.StatusConflict, managedKeyInUse) |
| case errors.As(err, ¬Recorded): |
| - // Nothing was changed: the box retries within its deadline. |
| + // Refused before any write: the box retries within its deadline. |
| w.Header().Set("Retry-After", "5") |
| jsonError(w, http.StatusServiceUnavailable, managedKeyUnavailable) |
| + case errors.As(err, &incomplete): |
| + // A write may have landed (the owner record, or a registry commit |
| + // whose answer was lost). Retryable: the same key converges, since |
| + // the record append is idempotent and the registry row is either |
| + // still keyless or already this key; initialOnly refuses any other. |
| + log.Printf("console: managed fleet key %s/%s: %v", in.Fleet, in.Label, err) |
| + w.Header().Set("Retry-After", "5") |
| + jsonError(w, http.StatusServiceUnavailable, managedKeyIncomplete) |
| default: |
| log.Printf("console: managed fleet key %s/%s: %v", in.Fleet, in.Label, err) |
| jsonError(w, http.StatusForbidden, managedKeyForbidden) |
| @@ -118,7 +132,7 @@ func (s *Server) managedKeyBox(ctx context.Context, in managedboot.FleetKeyReque |
| if !bearer || token == "" || !registry.ValidTunnelName(in.Fleet) || !registry.ValidTunnelName(in.Label) || !managedOpRE.MatchString(in.Op) { |
| return nil, nil, errManagedEnrolForbidden |
| } |
| - reg, err := openRegistry(s.cfg.Registry) |
| + reg, err := managedKeyRegistry(s.cfg.Registry) |
| if err != nil { |
| return nil, nil, errManagedEnrolRetryable |
| } |
| @@ -129,7 +143,13 @@ func (s *Server) managedKeyBox(ctx context.Context, in managedboot.FleetKeyReque |
| if fleet == nil || !fleet.Managed || fleet.Account == "" { |
| return nil, nil, errManagedEnrolForbidden |
| } |
| - if !fleetIdentityOK(reg, in.Fleet+"/"+in.Label, token, in.Fleet, fleet.Account) { |
| + // The same predicate as fleetIdentityOK, but evidence that could not be |
| + // read is retryable, never the box's terminal 403. |
| + ok, err := fleetIdentityCheck(reg, in.Fleet+"/"+in.Label, token, in.Fleet, fleet.Account) |
| + if err != nil { |
| + return nil, nil, errManagedEnrolRetryable |
| + } |
| + if !ok { |
| return nil, nil, errManagedEnrolForbidden |
| } |
| boxes, err := managedLoadBoxes(ctx, s.store.db, `WHERE fleet=? AND label=? AND op_id=?`, in.Fleet, in.Label, in.Op) |
diff --git a/internal/console/managedfleetkey_test.go b/internal/console/managedfleetkey_test.go| index 25aa0aa69..1e7a3276a 100644 |
| --- a/internal/console/managedfleetkey_test.go |
| +++ b/internal/console/managedfleetkey_test.go |
| @@ -3,16 +3,21 @@ package console |
| import ( |
| "bytes" |
| "context" |
| + "encoding/base64" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| + "log" |
| "net/http" |
| "net/http/httptest" |
| "path/filepath" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/managedboot" |
| + "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/status" |
| @@ -334,3 +339,399 @@ func TestManagedReadinessKeyStatus(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// flakyKeyRegistry is the door's registry with lookups and the key write |
| +// that fail a set number of times, then recover. commitSet makes the key |
| +// write commit before it fails (an answer lost after the commit). |
| +type flakyKeyRegistry struct { |
| + consoleRegistry |
| + mu sync.Mutex |
| + failFleet, failOwners, failBoxes int |
| + failSet int |
| + commitSet bool |
| + sets int |
| +} |
| + |
| +func (r *flakyKeyRegistry) fail(n *int) bool { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if *n > 0 { |
| + *n-- |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +var errFlakyRegistry = errors.New("registry: database is locked") |
| + |
| +func (r *flakyKeyRegistry) GetFleetContext(ctx context.Context, name string) (*registry.Fleet, error) { |
| + if r.fail(&r.failFleet) { |
| + return nil, errFlakyRegistry |
| + } |
| + return r.consoleRegistry.GetFleetContext(ctx, name) |
| +} |
| + |
| +func (r *flakyKeyRegistry) FleetOwners() (map[string]string, error) { |
| + if r.fail(&r.failOwners) { |
| + return nil, errFlakyRegistry |
| + } |
| + return r.consoleRegistry.FleetOwners() |
| +} |
| + |
| +func (r *flakyKeyRegistry) ListFleetBoxes(fleet string) ([]registry.FleetBox, error) { |
| + if r.fail(&r.failBoxes) { |
| + return nil, errFlakyRegistry |
| + } |
| + return r.consoleRegistry.ListFleetBoxes(fleet) |
| +} |
| + |
| +func (r *flakyKeyRegistry) SetFleetSecretsKey(name, pub, fp, by string, at int64) error { |
| + r.mu.Lock() |
| + r.sets++ |
| + r.mu.Unlock() |
| + if r.fail(&r.failSet) { |
| + if r.commitSet { |
| + if err := r.consoleRegistry.SetFleetSecretsKey(name, pub, fp, by, at); err != nil { |
| + return err |
| + } |
| + } |
| + return errFlakyRegistry |
| + } |
| + return r.consoleRegistry.SetFleetSecretsKey(name, pub, fp, by, at) |
| +} |
| + |
| +// useFlakyRegistry routes the door's registry through r for one test. |
| +func useFlakyRegistry(t *testing.T, s *Server, r *flakyKeyRegistry) { |
| + t.Helper() |
| + real, err := openRegistry(s.cfg.Registry) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.consoleRegistry = real |
| + saved := managedKeyRegistry |
| + managedKeyRegistry = func(string) (consoleRegistry, error) { return r, nil } |
| + t.Cleanup(func() { managedKeyRegistry = saved }) |
| +} |
| + |
| +// ownerPutStore shapes Puts of the fleet owner record: fail n of them, |
| +// committing first when commit is set. |
| +type ownerPutStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + fail int |
| + commit bool |
| + puts int |
| +} |
| + |
| +func (o *ownerPutStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if key != release.FleetOwnerKey("abc", "shop") { |
| + return o.Store.Put(ctx, key, body, ifMatch) |
| + } |
| + o.mu.Lock() |
| + o.puts++ |
| + failing := o.fail > 0 |
| + if failing { |
| + o.fail-- |
| + } |
| + o.mu.Unlock() |
| + if !failing { |
| + return o.Store.Put(ctx, key, body, ifMatch) |
| + } |
| + if o.commit { |
| + if _, err := o.Store.Put(ctx, key, body, ifMatch); err != nil { |
| + return "", err |
| + } |
| + } |
| + return "", errors.New("connection reset by peer") |
| +} |
| + |
| +func keyDoorReply(t *testing.T, w *httptest.ResponseRecorder) managedboot.FleetKeyReply { |
| + t.Helper() |
| + var reply managedboot.FleetKeyReply |
| + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &reply) != nil { |
| + t.Fatalf("= %d %s, want 200", w.Code, w.Body) |
| + } |
| + return reply |
| +} |
| + |
| +func assertKeyDoorRetry(t *testing.T, w *httptest.ResponseRecorder, body string) { |
| + t.Helper() |
| + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "5" || !strings.Contains(w.Body.String(), body) { |
| + t.Fatalf("= %d Retry-After %q %s, want 503, 5, %q", w.Code, w.Header().Get("Retry-After"), w.Body, body) |
| + } |
| +} |
| + |
| +func keyAuditCount(t *testing.T, s *Server) int { |
| + t.Helper() |
| + events, err := s.store.Events(77, "shop", 10) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + n := 0 |
| + for _, e := range events { |
| + if e.Action == "fleet-secrets-key" { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// TestManagedFleetKeyDoorUnavailableEvidence: evidence the door could not |
| +// read is retryable (503, Retry-After 5, nothing written), never the |
| +// identical terminal 403; once the lookup recovers the same request |
| +// succeeds. |
| +func TestManagedFleetKeyDoorUnavailableEvidence(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + set func(r *flakyKeyRegistry) |
| + }{ |
| + {"fleet row", func(r *flakyKeyRegistry) { r.failFleet = 1 }}, |
| + {"fleet owners", func(r *flakyKeyRegistry) { r.failOwners = 1 }}, |
| + {"fleet boxes", func(r *flakyKeyRegistry) { r.failBoxes = 1 }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + s, b, tunnel := keyDoorFixture(t) |
| + r := &flakyKeyRegistry{} |
| + c.set(r) |
| + useFlakyRegistry(t, s, r) |
| + pub, fp := fskKey(t) |
| + before, record := keyDoorState(t, s) |
| + assertKeyDoorRetry(t, keyDoorHTTP(s, tunnel, keyDoorBody(b, pub)), managedKeyUnavailable) |
| + if row, rec := keyDoorState(t, s); row != before || rec != record || r.sets != 0 { |
| + t.Fatal("unavailable evidence wrote") |
| + } |
| + if reply := keyDoorReply(t, keyDoorHTTP(s, tunnel, keyDoorBody(b, pub))); !reply.Changed || reply.Fingerprint != fp { |
| + t.Fatalf("after recovery %+v", reply) |
| + } |
| + // A real mismatch on the recovered registry is still the 403. |
| + if w := keyDoorHTTP(s, strings.Repeat("0", 64), keyDoorBody(b, pub)); w.Code != http.StatusForbidden { |
| + t.Fatalf("wrong token after recovery = %d", w.Code) |
| + } |
| + }) |
| + } |
| + t.Run("no registry at all", func(t *testing.T) { |
| + s, b, tunnel := keyDoorFixture(t) |
| + path := s.cfg.Registry |
| + s.cfg.Registry = filepath.Join(t.TempDir(), "missing", "registry.db") |
| + pub, fp := fskKey(t) |
| + assertKeyDoorRetry(t, keyDoorHTTP(s, tunnel, keyDoorBody(b, pub)), managedKeyUnavailable) |
| + s.cfg.Registry = path |
| + if reply := keyDoorReply(t, keyDoorHTTP(s, tunnel, keyDoorBody(b, pub))); reply.Fingerprint != fp || !reply.Changed { |
| + t.Fatalf("after recovery %+v", reply) |
| + } |
| + }) |
| +} |
| + |
| +// TestManagedFleetKeyDoorIncomplete: a failure once writing began is not a |
| +// no-change answer. The owner record write failing (with or without its |
| +// commit landing), or the registry write failing after the record (with or |
| +// without its commit), is a retryable 503 that says the registration did |
| +// not finish; the same key again completes it (one fingerprint listed, one |
| +// changed registration audited), and another key is still refused. |
| +func TestManagedFleetKeyDoorIncomplete(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + owner *ownerPutStore |
| + reg *flakyKeyRegistry |
| + retryChanged bool |
| + recordAtFirst bool |
| + }{ |
| + {"owner record write fails", &ownerPutStore{fail: 1}, &flakyKeyRegistry{}, true, false}, |
| + {"owner record commits, answer lost", &ownerPutStore{fail: 1, commit: true}, &flakyKeyRegistry{}, true, true}, |
| + {"registry write fails after the record", nil, &flakyKeyRegistry{failSet: 1}, true, true}, |
| + {"registry commits, answer lost", nil, &flakyKeyRegistry{failSet: 1, commitSet: true}, false, true}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + s, b, tunnel := keyDoorFixture(t) |
| + useFlakyRegistry(t, s, c.reg) |
| + if c.owner != nil { |
| + c.owner.Store = s.cfg.Releases |
| + s.cfg.Releases = c.owner |
| + } |
| + pub, fp := fskKey(t) |
| + assertKeyDoorRetry(t, keyDoorHTTP(s, tunnel, keyDoorBody(b, pub)), managedKeyIncomplete) |
| + rec, err := readFleetOwner(t, s.cfg.Releases, "abc", "shop") |
| + if listed := err == nil && len(rec.SecretsKeyFPs) == 1 && rec.SecretsKeyFPs[0] == fp; listed != c.recordAtFirst { |
| + t.Fatalf("owner record after the failure %+v %v, want listed=%v", rec, err, c.recordAtFirst) |
| + } |
| + if c.owner == nil && !c.recordAtFirst { |
| + t.Fatal("bad case") |
| + } |
| + // The retry converges on the same key. |
| + reply := keyDoorReply(t, keyDoorHTTP(s, tunnel, keyDoorBody(b, pub))) |
| + if reply.Fingerprint != fp || reply.Changed != c.retryChanged { |
| + t.Fatalf("retry %+v, want changed=%v", reply, c.retryChanged) |
| + } |
| + row, _ := keyDoorState(t, s) |
| + if row.SecretsKeyFP != fp || row.SecretsPub != pub { |
| + t.Fatalf("registry %+v", row) |
| + } |
| + if rec, err := readFleetOwner(t, s.cfg.Releases, "abc", "shop"); err != nil || len(rec.SecretsKeyFPs) != 1 || rec.SecretsKeyFPs[0] != fp { |
| + t.Fatalf("owner record %+v %v, want the one fingerprint", rec, err) |
| + } |
| + if want := map[bool]int{true: 1, false: 0}[c.retryChanged]; keyAuditCount(t, s) != want { |
| + t.Fatalf("%d audit lines, want %d", keyAuditCount(t, s), want) |
| + } |
| + // Never a replacement, retry or not. |
| + other, _ := fskKey(t) |
| + if w := keyDoorHTTP(s, tunnel, keyDoorBody(b, other)); w.Code != http.StatusConflict { |
| + t.Fatalf("another key after the retry = %d %s", w.Code, w.Body) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// keyDoorFleet is keyDoorFixture with three enrolled boxes of fleet shop |
| +// and each one's tunnel token. |
| +func keyDoorFleet(t *testing.T) (*Server, []managedBox, []string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + s, _ := managedPreparationFixture(t) |
| + setManagedHistory(t, s, provision.HostsState{Mode: provision.HostsModeIncomplete}) |
| + r := managedReq("shop", "abc") |
| + r.Boxes = 3 |
| + op, bs, _, err := s.reserveManagedFleet(ctx, r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = s.prepareManagedFleet(ctx, op, bs); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.store.CreateAccount(77, "abc", "abc", "owner@example.com", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cli = newCLILimits() |
| + s.cfg.TunnelHost = "tunnel.example.com" |
| + s.cfg.SecretsPub, _ = mustTestSecretsKey() |
| + key, _, err := openManagedEnrolKey(s.cfg.AlertSealKeyPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now().UTC() |
| + _, boxes, err := s.store.ManagedFleet(ctx, "abc", "shop") |
| + if err != nil || len(boxes) != 3 { |
| + t.Fatalf("boxes %v %v", boxes, err) |
| + } |
| + var tunnels []string |
| + for _, b := range boxes { |
| + if err := s.stepManagedBox(ctx, b, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + token, _ := deriveManagedEnrolToken(key, b.ClientToken) |
| + reply, err := s.enrolManagedBox(ctx, managedEnrolRequest{Token: token, DataDirEmpty: true}, now.Add(time.Second)) |
| + if err != nil { |
| + t.Fatalf("enrol %s: %v", b.Label, err) |
| + } |
| + tunnels = append(tunnels, reply.TunnelToken) |
| + } |
| + _, boxes, _ = s.store.ManagedFleet(ctx, "abc", "shop") |
| + for _, b := range boxes { |
| + if b.State != "enrolled" { |
| + t.Fatalf("%s %s", b.Label, b.State) |
| + } |
| + } |
| + return s, boxes, tunnels |
| +} |
| + |
| +// TestManagedFleetKeyFirstBoxesRace: three first boxes race through the |
| +// box protocol (read, mint, create-only PUT, adopt the stored object on a |
| +// lost race) on one fleet bucket, then register at the same moment through |
| +// the real door, core and registry. Exactly one registration changes |
| +// anything, the registry holds the winning object's fingerprint, and no |
| +// key or token reaches the console's log. |
| +func TestManagedFleetKeyFirstBoxesRace(t *testing.T) { |
| + s, boxes, tunnels := keyDoorFleet(t) |
| + bucket := release.NewDirStore(t.TempDir()) |
| + var logs bytes.Buffer |
| + saved := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(saved) |
| + |
| + ctx := context.Background() |
| + var put, register sync.WaitGroup |
| + put.Add(3) |
| + register.Add(3) |
| + keys := make([]managedboot.FleetKey, 3) |
| + replies := make([]*httptest.ResponseRecorder, 3) |
| + putErrs := make([]error, 3) |
| + var minted []string |
| + var mu sync.Mutex |
| + var wg sync.WaitGroup |
| + for i, b := range boxes { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + id := managedboot.Identity{Fleet: b.Fleet, Label: b.Label, Op: b.OpID, ReleasePubkey: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32))} |
| + k, err := managedboot.MintFleetKey(id) |
| + if err != nil { |
| + putErrs[i] = err |
| + put.Done() |
| + register.Done() |
| + return |
| + } |
| + mu.Lock() |
| + minted = append(minted, k.Private) |
| + mu.Unlock() |
| + body, _ := managedboot.EncodeFleetKey(k) |
| + put.Done() |
| + put.Wait() // every box has read "absent" and minted |
| + if _, err := bucket.Put(ctx, managedboot.FleetKeyObject, body, ""); err != nil { |
| + putErrs[i] = err |
| + raw, _, gerr := bucket.Get(ctx, managedboot.FleetKeyObject) |
| + if gerr == nil { |
| + k, gerr = managedboot.ParseFleetKey(raw, b.Fleet) |
| + } |
| + if gerr != nil { |
| + putErrs[i] = gerr |
| + } |
| + } |
| + keys[i] = k |
| + register.Done() |
| + register.Wait() |
| + replies[i] = keyDoorHTTP(s, tunnels[i], keyDoorBody(b, k.Public)) |
| + }() |
| + } |
| + wg.Wait() |
| + won := 0 |
| + for _, err := range putErrs { |
| + switch { |
| + case err == nil: |
| + won++ |
| + case !errors.Is(err, release.ErrCASConflict): |
| + t.Fatalf("box: %v", err) |
| + } |
| + } |
| + raw, _, err := bucket.Get(ctx, managedboot.FleetKeyObject) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + stored, err := managedboot.ParseFleetKey(raw, "shop") |
| + if err != nil || won != 1 { |
| + t.Fatalf("stored %v, %d winners", err, won) |
| + } |
| + changed := 0 |
| + for i, w := range replies { |
| + reply := keyDoorReply(t, w) |
| + if keys[i] != stored || reply.Fingerprint != stored.Fingerprint { |
| + t.Fatalf("box %d registered %s, the object is %s", i, reply.Fingerprint, stored.Fingerprint) |
| + } |
| + if reply.Changed { |
| + changed++ |
| + } |
| + } |
| + row, _ := keyDoorState(t, s) |
| + if changed != 1 || row.SecretsKeyFP != stored.Fingerprint || row.SecretsPub != stored.Public { |
| + t.Fatalf("changed %d, registry %+v, object %s", changed, row, stored.Fingerprint) |
| + } |
| + if rec, err := readFleetOwner(t, s.cfg.Releases, "abc", "shop"); err != nil || len(rec.SecretsKeyFPs) != 1 || rec.SecretsKeyFPs[0] != stored.Fingerprint { |
| + t.Fatalf("owner record %+v %v", rec, err) |
| + } |
| + if n := keyAuditCount(t, s); n != 1 { |
| + t.Fatalf("%d audit lines", n) |
| + } |
| + for _, secret := range append(minted, tunnels...) { |
| + if strings.Contains(logs.String(), secret) { |
| + t.Fatal("a private key or tunnel token reached the console log") |
| + } |
| + } |
| +} |
diff --git a/internal/host/managedboot.go b/internal/host/managedboot.go| index e76c94563..86032e51d 100644 |
| --- a/internal/host/managedboot.go |
| +++ b/internal/host/managedboot.go |
| @@ -105,7 +105,8 @@ type managedBoot struct { |
| // carlos's group, which may read the credentials. |
| uid, gid, serviceGID int |
| // fleetStore opens the fleet's own bucket for the secrets key step |
| - // (managedkey.go), which never fails the boot; nil skips the step. |
| + // (managedkey.go): no key outcome fails the boot, only a failed local |
| + // write does; nil skips the step. |
| fleetStore func(ctx context.Context, env map[string]string) (release.Store, error) |
| // crash and beforeExec are test seams. |
| crash func(step string) error |
| @@ -191,7 +192,9 @@ func (m *managedBoot) Run(ctx context.Context, in managedboot.LaunchInput) (err |
| return err |
| } |
| if m.fleetStore != nil { |
| - m.establishFleetKey(ctx, in, env) |
| + if err = m.establishFleetKey(ctx, in, env); err != nil { |
| + return err |
| + } |
| } |
| if err = m.step("key"); err != nil { |
| return err |
diff --git a/internal/host/managedkey.go b/internal/host/managedkey.go| index 728ad0500..c7365ded2 100644 |
| --- a/internal/host/managedkey.go |
| +++ b/internal/host/managedkey.go |
| @@ -10,6 +10,7 @@ import ( |
| "log" |
| "net/http" |
| "os" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/appconfig" |
| @@ -109,8 +110,9 @@ func ensureFleetKey(ctx context.Context, s release.Store, id managedboot.Identit |
| } |
| // getFleetKey reads and validates the stored object: found false with no |
| -// error when it is absent. A read that keeps failing is object_unreadable, |
| -// a body that does not validate for fleet object_invalid. |
| +// error when it is absent. A read that keeps failing is object_unreadable; |
| +// a body over managedboot.MaxFleetKeyObject, or one that does not validate |
| +// for fleet, is object_invalid at once, with no further read. |
| func getFleetKey(ctx context.Context, s release.Store, fleet string) (managedboot.FleetKey, bool, error) { |
| for attempt := range mbKeyGetAttempts { |
| if attempt > 0 && mbKeyPause > 0 { |
| @@ -122,13 +124,15 @@ func getFleetKey(ctx context.Context, s release.Store, fleet string) (managedboo |
| case <-t.C: |
| } |
| } |
| - getCtx, cancel := context.WithTimeout(ctx, mbRequestTimeout) |
| - raw, _, err := s.Get(getCtx, managedboot.FleetKeyObject) |
| - cancel() |
| - if errors.Is(err, os.ErrNotExist) { |
| + raw, err := readFleetKeyObject(ctx, s) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| return managedboot.FleetKey{}, false, nil |
| - } |
| - if err != nil { |
| + case errors.Is(err, errFleetKeyOversize): |
| + return managedboot.FleetKey{}, false, keyFailure(managedboot.KeyStatusObjectInvalid) |
| + case errors.Is(err, errFleetKeyNoStream): |
| + return managedboot.FleetKey{}, false, keyFailure(managedboot.KeyStatusObjectUnreadable) |
| + case err != nil: |
| continue |
| } |
| k, err := managedboot.ParseFleetKey(raw, fleet) |
| @@ -140,6 +144,37 @@ func getFleetKey(ctx context.Context, s release.Store, fleet string) (managedboo |
| return managedboot.FleetKey{}, false, keyFailure(managedboot.KeyStatusObjectUnreadable) |
| } |
| +var ( |
| + errFleetKeyOversize = errors.New("managed boot: the fleet key object is too large") |
| + errFleetKeyNoStream = errors.New("managed boot: the fleet bucket cannot stream") |
| +) |
| + |
| +// readFleetKeyObject streams the key object through a hard bound: the |
| +// object is fleet-writable, so root never reads more than |
| +// MaxFleetKeyObject+1 bytes of it (Store.Get would read the whole body into |
| +// memory first). A store that cannot stream is refused, never read whole. |
| +func readFleetKeyObject(ctx context.Context, s release.Store) ([]byte, error) { |
| + o, ok := s.(release.Opener) |
| + if !ok { |
| + return nil, errFleetKeyNoStream |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, mbRequestTimeout) |
| + defer cancel() |
| + body, _, err := o.Open(ctx, managedboot.FleetKeyObject) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer body.Close() |
| + raw, err := io.ReadAll(io.LimitReader(body, managedboot.MaxFleetKeyObject+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if len(raw) > managedboot.MaxFleetKeyObject { |
| + return nil, errFleetKeyOversize |
| + } |
| + return raw, nil |
| +} |
| + |
| // mbRegisterError is one registration exchange that did not succeed: |
| // retry says the console did not decide (503, 429, gateway failures, no |
| // answer), and wait is its Retry-After when it gave one. |
| @@ -203,21 +238,22 @@ func registerFleetKey(ctx context.Context, c *http.Client, origin, tunnelToken s |
| return &mbRegisterError{status: resp.StatusCode} |
| } |
| -// establishFleetKey is the key step. It never fails the boot: every outcome |
| -// ends in a status code at KeyStatusPath, and host.env holds the key only |
| -// for ok. A stop (SIGTERM, shutdown) writes nothing: the next boot repeats |
| -// the step, which only reads and adopts what the first attempt stored. |
| -func (m *managedBoot) establishFleetKey(ctx context.Context, in managedboot.LaunchInput, env map[string]string) { |
| +// establishFleetKey is the key step. No key outcome fails the boot: every |
| +// one ends in a status code at KeyStatusPath, and host.env holds the key |
| +// only for ok. A local write that fails (host.env or the status file) does |
| +// fail it, as every other root write of the first boot does, so no box |
| +// completes its first boot without a status file. A stop (SIGTERM, |
| +// shutdown) writes nothing: the next boot repeats the step, which only |
| +// reads and adopts what the first attempt stored. |
| +func (m *managedBoot) establishFleetKey(ctx context.Context, in managedboot.LaunchInput, env map[string]string) error { |
| deadline := m.now().Add(mbKeyDeadline) |
| - ctx, cancel := context.WithTimeout(ctx, mbKeyDeadline) |
| + stepCtx, cancel := context.WithTimeout(ctx, mbKeyDeadline) |
| defer cancel() |
| - code, key := m.fleetKeyOutcome(ctx, in, env, deadline) |
| - if errors.Is(context.Cause(ctx), context.Canceled) { |
| - return |
| - } |
| - if err := m.installFleetKey(key, code); err != nil { |
| - m.logf("managed boot: fleet secrets key: %v", err) |
| + code, key := m.fleetKeyOutcome(stepCtx, in, env, deadline) |
| + if err := ctx.Err(); err != nil { |
| + return err |
| } |
| + return m.installFleetKey(key, code) |
| } |
| // fleetKeyOutcome ensures and registers the key: the code, and the key |
| @@ -257,20 +293,21 @@ func (m *managedBoot) fleetKeyOutcome(ctx context.Context, in managedboot.Launch |
| } |
| // installFleetKey writes host.env with CARLOS_SECRETS_KEY (k) or without it |
| -// (nil), atomically and only if it changes, then the status code. A host.env |
| -// that cannot be rewritten is reported as unreadable. |
| +// (nil), atomically and only if it changes, then the status code. Either |
| +// write failing is the step's error. |
| func (m *managedBoot) installFleetKey(k *managedboot.FleetKey, code string) error { |
| - err := m.writeHostEnvKey(k) |
| - if err != nil && k != nil { |
| - code = managedboot.KeyStatusObjectUnreadable |
| - err = errors.Join(err, m.writeHostEnvKey(nil)) |
| + if err := m.writeHostEnvKey(k); err != nil { |
| + return fmt.Errorf("managed boot: fleet secrets key: %w", err) |
| + } |
| + status, err := managedboot.EncodeKeyStatus(code) |
| + if err != nil { |
| + return err |
| } |
| - status, serr := managedboot.EncodeKeyStatus(code) |
| - if serr == nil { |
| - serr = mbWriteRootFile(m.root, managedboot.KeyStatusPath, status, 0o644, m.uid, -1) |
| + if err = mbWriteRootFile(m.root, managedboot.KeyStatusPath, status, 0o644, m.uid, -1); err != nil { |
| + return fmt.Errorf("managed boot: fleet secrets key status: %w", err) |
| } |
| m.logf("managed boot: fleet secrets key: %s", code) |
| - return errors.Join(err, serr) |
| + return nil |
| } |
| func (m *managedBoot) writeHostEnvKey(k *managedboot.FleetKey) error { |
| @@ -314,16 +351,34 @@ var ( |
| managedKeyStatusOwner = 0 |
| ) |
| +// managedKeyLogged is the last status-file problem managedKeyHeartbeat |
| +// logged: it logs a problem when it starts or changes, not every tick. |
| +var managedKeyLogged struct { |
| + sync.Mutex |
| + last string |
| +} |
| + |
| // managedKeyHeartbeat is the heartbeat's managed_key: "" off a managed box |
| // (no status file), root's code when it is well formed, and |
| // status_unreadable for a file that is there but not root's record. |
| func managedKeyHeartbeat() string { |
| code, present, err := managedboot.LoadKeyStatus(managedKeyStatusRoot, managedKeyStatusOwner) |
| + problem := "" |
| + if err != nil { |
| + problem = err.Error() |
| + } |
| + managedKeyLogged.Lock() |
| + if problem != managedKeyLogged.last { |
| + if problem != "" { |
| + log.Printf("agent: managed key status: %s", problem) |
| + } |
| + managedKeyLogged.last = problem |
| + } |
| + managedKeyLogged.Unlock() |
| if !present && err == nil { |
| return "" |
| } |
| if err != nil { |
| - log.Printf("agent: managed key status: %v", err) |
| return managedboot.KeyStatusUnreadable |
| } |
| return code |
diff --git a/internal/host/managedkey_test.go b/internal/host/managedkey_test.go| index e99a6bd8d..e7705da82 100644 |
| --- a/internal/host/managedkey_test.go |
| +++ b/internal/host/managedkey_test.go |
| @@ -3,10 +3,12 @@ |
| package host |
| import ( |
| + "bytes" |
| "context" |
| "encoding/json" |
| "errors" |
| "io" |
| + "log" |
| "net/http" |
| "os" |
| "path/filepath" |
| @@ -35,8 +37,57 @@ type mbKeyBucket struct { |
| deletes int |
| // put shapes the n-th PUT (1-based); nil is the store's own answer. |
| put func(ctx context.Context, n int, body []byte) (string, error, bool) |
| - // get shapes the n-th GET; nil is the store's own answer. |
| + // get shapes the n-th read; nil is the store's own answer. |
| get func(n int) ([]byte, string, error, bool) |
| + // open replaces the n-th read's body; nil is get's or the store's. |
| + open func(n int) (io.ReadCloser, bool) |
| +} |
| + |
| +// Open is the streaming read root uses: it counts as a GET, like Get. |
| +func (b *mbKeyBucket) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + b.mu.Lock() |
| + b.gets++ |
| + n, hook, open := b.gets, b.get, b.open |
| + b.mu.Unlock() |
| + if open != nil { |
| + if body, ok := open(n); ok { |
| + return body, "", nil |
| + } |
| + } |
| + if hook != nil { |
| + if body, etag, err, ok := hook(n); ok { |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + return io.NopCloser(bytes.NewReader(body)), etag, nil |
| + } |
| + } |
| + return b.Store.(release.Opener).Open(ctx, key) |
| +} |
| + |
| +// mbEndless is a body that never ends; it counts what was read from it |
| +// and whether it was closed. |
| +type mbEndless struct { |
| + mu sync.Mutex |
| + read int |
| + closed bool |
| +} |
| + |
| +func (e *mbEndless) Read(p []byte) (int, error) { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + for i := range p { |
| + p[i] = '{' |
| + } |
| + e.read += len(p) |
| + return len(p), nil |
| +} |
| + |
| +func (e *mbEndless) Close() error { |
| + e.mu.Lock() |
| + e.closed = true |
| + e.mu.Unlock() |
| + return nil |
| } |
| func newKeyBucket(t *testing.T) *mbKeyBucket { |
| @@ -699,6 +750,7 @@ func TestManagedFleetKeyHostEnv(t *testing.T) { |
| _, raw := f.heartbeat() |
| var seen []string |
| seen = append(seen, f.logs...) |
| + seen = append(seen, f.errs...) |
| seen = append(seen, f.crumbs...) |
| seen = append(seen, door.bodies...) |
| seen = append(seen, door.headers...) |
| @@ -720,3 +772,151 @@ func TestManagedFleetKeyHostEnv(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// TestManagedFleetKeyBoundedRead: the key object is fleet-writable, so root |
| +// reads it through a hard bound. An endless object is read no further than |
| +// MaxFleetKeyObject+1 bytes, closed, and is object_invalid: no PUT, no |
| +// registration, and the boot completes. |
| +func TestManagedFleetKeyBoundedRead(t *testing.T) { |
| + noKeyPause(t) |
| + for _, c := range []struct { |
| + name string |
| + body func() io.ReadCloser |
| + }{ |
| + {"endless", func() io.ReadCloser { return &mbEndless{} }}, |
| + {"one byte over", func() io.ReadCloser { |
| + return io.NopCloser(bytes.NewReader(bytes.Repeat([]byte(" "), managedboot.MaxFleetKeyObject+1))) |
| + }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + bucket := newKeyBucket(t) |
| + var bodies []io.ReadCloser |
| + bucket.open = func(n int) (io.ReadCloser, bool) { |
| + b := c.body() |
| + bodies = append(bodies, b) |
| + return b, true |
| + } |
| + door := &mbKeyDoor{} |
| + f := keyFixture(t, "box-1", bucket, door) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.assertKeyFailed(managedboot.KeyStatusObjectInvalid) |
| + if gets, puts, deletes := bucket.counts(); gets != 1 || puts != 0 || deletes != 0 { |
| + t.Fatalf("gets %d puts %d deletes %d, want one bounded read and nothing written", gets, puts, deletes) |
| + } |
| + if _, calls, _ := door.registered(); calls != 0 { |
| + t.Fatalf("%d registrations of an oversize object", calls) |
| + } |
| + if e, ok := bodies[0].(*mbEndless); ok { |
| + e.mu.Lock() |
| + read, closed := e.read, e.closed |
| + e.mu.Unlock() |
| + if read > managedboot.MaxFleetKeyObject+1 || !closed { |
| + t.Fatalf("read %d bytes (bound %d), closed %v", read, managedboot.MaxFleetKeyObject+1, closed) |
| + } |
| + } |
| + }) |
| + } |
| + t.Run("a store that cannot stream is never read whole", func(t *testing.T) { |
| + bucket := newKeyBucket(t) |
| + f := keyFixture(t, "box-1", bucket, &mbKeyDoor{}) |
| + f.fleetStore = func(context.Context, map[string]string) (release.Store, error) { |
| + return mbGetOnly{bucket}, nil |
| + } |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.assertKeyFailed(managedboot.KeyStatusObjectUnreadable) |
| + if gets, puts, _ := bucket.counts(); gets != 0 || puts != 0 { |
| + t.Fatalf("gets %d puts %d through a store with no stream", gets, puts) |
| + } |
| + }) |
| +} |
| + |
| +// mbGetOnly hides every optional interface of its store, Open included. |
| +type mbGetOnly struct{ release.Store } |
| + |
| +// TestManagedFleetKeyStatusWriteFails: the status file and host.env are |
| +// root's local writes; failing either fails the first boot |
| +// (bootstrap_failed, nothing run, no complete marker), whatever the key |
| +// outcome, and the next boot completes once the write can succeed. |
| +func TestManagedFleetKeyStatusWriteFails(t *testing.T) { |
| + noKeyPause(t) |
| + for _, c := range []struct { |
| + name string |
| + door *mbKeyDoor |
| + breakW func(f *mbFixture) |
| + mend func(f *mbFixture) |
| + code string |
| + }{ |
| + {"status path not writable after ok", &mbKeyDoor{}, |
| + func(f *mbFixture) { f.mkdir(managedboot.KeyStatusPath, 0o755) }, |
| + func(f *mbFixture) { _ = os.Remove(f.path(managedboot.KeyStatusPath)) }, managedboot.KeyStatusOK}, |
| + {"status path not writable after a refusal", &mbKeyDoor{respond: func(w http.ResponseWriter, n int) bool { w.WriteHeader(http.StatusForbidden); return true }}, |
| + func(f *mbFixture) { f.mkdir(managedboot.KeyStatusPath, 0o755) }, |
| + func(f *mbFixture) { _ = os.Remove(f.path(managedboot.KeyStatusPath)) }, managedboot.KeyStatusRegistrationRefused}, |
| + {"host.env not writable", &mbKeyDoor{}, |
| + func(f *mbFixture) { f.mkdir("/etc/carlos", 0o775) }, |
| + func(f *mbFixture) { f.mkdir("/etc/carlos", 0o755) }, managedboot.KeyStatusOK}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + bucket := newKeyBucket(t) |
| + f := keyFixture(t, "box-1", bucket, c.door) |
| + open := f.fleetStore |
| + broken := false |
| + f.fleetStore = func(ctx context.Context, env map[string]string) (release.Store, error) { |
| + if !broken { |
| + c.breakW(f) |
| + broken = true |
| + } |
| + return open(ctx, env) |
| + } |
| + if err := f.boot(""); err == nil { |
| + t.Fatal("the boot completed without its key status") |
| + } |
| + if got := f.lastCrumb(); got != managedboot.CodeBootstrapFailed { |
| + t.Fatalf("breadcrumb %q, want bootstrap_failed", got) |
| + } |
| + if f.exists(mbCompleteMarker) || f.count("bootstrap") != 0 || f.count("systemctl start") != 0 { |
| + t.Fatal("a boot without its key status ran on") |
| + } |
| + f.assertNotAdmitted() |
| + c.mend(f) |
| + if err := f.boot(""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := f.keyStatus(); got != c.code { |
| + t.Fatalf("status after the mend %q, want %q", got, c.code) |
| + } |
| + if f.lastCrumb() == managedboot.CodeBootstrapFailed || !f.exists(mbCompleteMarker) { |
| + t.Fatalf("resumed boot did not complete: %v", f.crumbs) |
| + } |
| + if _, puts, _ := bucket.counts(); puts != 1 { |
| + t.Fatalf("%d PUTs across the two boots, want 1", puts) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestManagedFleetKeyHeartbeatLogsOnce: a broken status file is logged when |
| +// it starts, not every tick. |
| +func TestManagedFleetKeyHeartbeatLogsOnce(t *testing.T) { |
| + f := keyFixture(t, "box-1", newKeyBucket(t), &mbKeyDoor{}) |
| + f.write(managedboot.KeyStatusPath, []byte("junk\n"), 0o644) |
| + managedKeyLogged.Lock() |
| + managedKeyLogged.last = "" |
| + managedKeyLogged.Unlock() |
| + var buf bytes.Buffer |
| + saved := log.Writer() |
| + log.SetOutput(&buf) |
| + defer log.SetOutput(saved) |
| + for range 3 { |
| + if got, _ := f.heartbeat(); got != managedboot.KeyStatusUnreadable { |
| + t.Fatalf("managed_key %q", got) |
| + } |
| + } |
| + if n := strings.Count(buf.String(), "managed key status"); n != 1 { |
| + t.Fatalf("logged %d times over three ticks:\n%s", n, buf.String()) |
| + } |
| +} |
diff --git a/internal/managedboot/fleetkey.go b/internal/managedboot/fleetkey.go| index bf7161f5d..3b8d30bdb 100644 |
| --- a/internal/managedboot/fleetkey.go |
| +++ b/internal/managedboot/fleetkey.go |
| @@ -23,8 +23,9 @@ const FleetKeyPath = "/api/fleet/managed/secrets-key" |
| // FleetKeySchema is the one FleetKey schema. |
| const FleetKeySchema = 1 |
| -// maxFleetKeyObject bounds what a box reads back from the bucket. |
| -const maxFleetKeyObject = 4 << 10 |
| +// MaxFleetKeyObject bounds what a box reads back from the bucket: the |
| +// object is fleet-writable, so root reads at most this plus one byte. |
| +const MaxFleetKeyObject = 4 << 10 |
| // FleetKey is FleetKeyObject's body. It holds the private half in plaintext |
| // under the bucket's SSE-S3 (Paul, addendum P2), so it is never logged, |
| @@ -95,7 +96,7 @@ func EncodeFleetKey(k FleetKey) ([]byte, error) { |
| // ParseFleetKey reads an object strictly (no unknown fields, one value, at |
| // most 4 KiB) and validates it for fleet. |
| func ParseFleetKey(b []byte, fleet string) (FleetKey, error) { |
| - if len(b) > maxFleetKeyObject { |
| + if len(b) > MaxFleetKeyObject { |
| return FleetKey{}, errFleetKey |
| } |
| var k FleetKey |