feat: admit fresh managed fleets into hostname history
Claim managed fleet names atomically, prepare owned storage before history and registry publication, and seal shared fleet credentials. Persist preparation failures and deadlines, and guard BYO actions on managed fleets. Include local/remote registry witnesses and the task-5 census proposal. Independent census approval and copy review remain with the controller.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+1,121
−3
docs/superpowers/notes/census-proposal-managed-fleets-2a-task-5.md+33 −0internal/console/fleetrelabel.go+20 −0internal/console/fleets.go+28 −0internal/console/managedhistory.go+341 −0internal/console/managedhistory_test.go+491 −0internal/console/managedstore.go+62 −0internal/console/server.go+7 −1internal/console/view.go+2 −0internal/provision/hostsused.go+2 −1internal/provision/managed_fleets_2a_task5_census_test.go+34 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-5.tsv+10 −0internal/registry/fleets.go+29 −0internal/registry/fleets_test.go+56 −0internal/registry/remote_dispatch.go+4 −0
diff --git a/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-5.md b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-5.md| new file mode 100644 |
| index 000000000..9e2087544 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-5.md |
| @@ -0,0 +1,33 @@ |
| +# Census approval: managed-fleets-2a-task-5 |
| + |
| +Ruling `census-ruling-managed-fleets-2a-task-5`. The independent reviewer approves or rejects every change below, 3 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/provision`, `internal/registry`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/registry/fleets.go:Registry.DeleteEmptyManagedFleet`: reads +file:Exec, +registry:Changed, +registry:remote ×2, +registry:sql, +whole:Fleet, +whole:remoteClient ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/registry/fleets.go:Registry.SetManagedFleetBucket`: reads +file:Exec, +registry:Changed, +registry:remote ×2, +registry:sql, +whole:Fleet, +whole:remoteClient ×2; written legacy, accepted-legacy, frozen |
| +- reads `internal/registry/remote_dispatch.go:Registry.dispatchRemote`: +registry:Account ×2, +registry:Bucket, +registry:Changed ×2, +registry:F ×5, +registry:Name ×2, +whole:Fleet ×5; keeps hint, task E2 |
| + |
| +Seal: `63ec311c20f67c064f2c2066f5aed2f7ddd9ecc545b385511485c480fceafb6f` → `19ad67bdbe2f4269fbfadd44bd36ca166118908e4e9d9da8f9b7a95916d013ee`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-5.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
| + |
| +## Controller review context |
| + |
| +This is an implementation proposal, not independent approval. Plan review rounds 1–3 remain closed; this task does not restart that budget. The controller owns the independent review and the #280 record. |
| + |
| +Also inspect the console authority paths excluded from the root-source scanner: |
| + |
| +- `Server.reserveManagedFleet` claims the name through `createFleetAboveTheFloor` and atomic `CreateFleet`. Request aliases precede current admission gates. Cleanup holds the fleet lock, checks console operations and reservations, then uses conditional registry deletion. Witnesses: `TestManagedPrepareNameRace`, `TestManagedPrepareNameCleanup`. |
| +- `Server.prepareManagedFleet` persists provider storage, calls `Server.admitManagedHistory`, updates only the owned registry bucket, and calls the existing inventoried `Server.writeFleetOwner`. Preparation never launches. Witnesses: `TestManagedBornExamined`, `TestManagedHistoryBeforeRegistry`, `TestManagedPreparationStorageDrift`, `TestManagedPreparationDeadline`. |
| +- `Server.admitManagedHistory` calls the existing inventoried `provision.WriteHostsState`, preserving concurrent targets and closed fleets while holding the history mutex after the fleet lock. It does not set startup verification. Witnesses: `TestManagedHistoryCASRace`, `TestManagedHistoryModes`, `TestManagedHistoryOffAndUnreadable`. |
| +- `Server.managedCredentialsHeld` seals fleet secrets and keeps the delivered key ID independent. Preparation does not advance the delivered ID; the enrolment-facing helper records it before returning credentials. Witnesses: `TestManagedFleetCredentials`, `TestManagedSealKeyLost`, `TestManagedFleetCredentialsLostSealWrite`. Task 7 supplies the enrolment call site. |
| +- BYO add, rotate and detach doors refuse managed fleets; the common drain core refuses joining boxes under the fleet lock. Existing HTML doors are rotate and detach; there is no HTML add or drain action. Witness: `TestManagedBYOBoundary`. |
| + |
| +The provision envelope now accepts the explicit `off` history mode required by Task 5. Existing absent history still means incomplete and refuses managed admission. No operator command was added to select `off`. |
| + |
| +The record-write inventory also includes the earlier tasks' CLI route changes and managed system-config writer, which the task-5 census run found unpinned. Their source is unchanged by this task. The new server initializer installs a lazy registry reader without opening the registry during startup. These entries are in `internal/provision/managed_fleets_2a_task5_census_test.go`. |
diff --git a/internal/console/fleetrelabel.go b/internal/console/fleetrelabel.go| index d258396b1..c9d8aa4d5 100644 |
| --- a/internal/console/fleetrelabel.go |
| +++ b/internal/console/fleetrelabel.go |
| @@ -415,6 +415,26 @@ func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []str |
| if err != nil { |
| return nil, err |
| } |
| + f, e := reg.GetFleet(fleet) |
| + if e != nil { |
| + return nil, e |
| + } |
| + if f != nil && f.Managed { |
| + _, boxes, e := s.store.ManagedFleet(ctx, f.Account, fleet) |
| + if e != nil { |
| + return nil, e |
| + } |
| + ready := false |
| + for _, b := range boxes { |
| + if b.Label == label && b.State == "ready" { |
| + ready = true |
| + } |
| + } |
| + if !ready { |
| + return nil, errManagedJoiningDrain |
| + } |
| + } |
| + |
| box, err := findFleetBox(reg, fleet, label) |
| if err != nil { |
| return nil, err |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index 39f01aa6d..39509d4b4 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -392,6 +392,11 @@ func (s *Server) handleAPIFleetAddBox(w http.ResponseWriter, r *http.Request) { |
| if !ok { |
| return |
| } |
| + if fleet.Managed { |
| + jsonError(w, http.StatusConflict, msgManagedBYO) |
| + return |
| + } |
| + |
| p, _ := principalFrom(r.Context()) |
| if !s.allowWrite(p, time.Now()) { |
| jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again") |
| @@ -461,6 +466,11 @@ func (s *Server) handleAPIFleetRotateBox(w http.ResponseWriter, r *http.Request) |
| if !ok { |
| return |
| } |
| + if fleet.Managed { |
| + jsonError(w, http.StatusConflict, msgManagedBYO) |
| + return |
| + } |
| + |
| p, _ := principalFrom(r.Context()) |
| if !s.allowWrite(p, time.Now()) { |
| jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again") |
| @@ -563,6 +573,11 @@ func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request) |
| if !ok { |
| return |
| } |
| + if fleet.Managed { |
| + jsonError(w, http.StatusConflict, msgManagedBYO) |
| + return |
| + } |
| + |
| p, _ := principalFrom(r.Context()) |
| if !s.allowWrite(p, time.Now()) { |
| jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again") |
| @@ -645,6 +660,9 @@ func (s *Server) handleAPIFleetDrainBox(w http.ResponseWriter, r *http.Request) |
| stuck, err := s.drainBox(r.Context(), fleet.Name, label) |
| var paused *fleetPausedError |
| switch { |
| + case errors.Is(err, errManagedJoiningDrain): |
| + jsonError(w, http.StatusConflict, errManagedJoiningDrain.Error()) |
| + return |
| case errors.Is(err, errFleetDrainHostClaim): |
| jsonError(w, http.StatusConflict, claimFleetDrainUnsupportedMsg) |
| return |
| @@ -1497,6 +1515,11 @@ func (s *Server) handleFleetRotateBoxPage(w http.ResponseWriter, r *http.Request |
| s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| return |
| } |
| + if fleet.Managed { |
| + s.renderMessage(w, r, http.StatusConflict, "Refused", msgManagedBYO) |
| + return |
| + } |
| + |
| back := func(kind, msg string) { |
| s.setFlash(w, kind, msg) |
| http.Redirect(w, r, fleetPageURL(acct.Sqid, fleet.Name), http.StatusSeeOther) |
| @@ -1557,6 +1580,11 @@ func (s *Server) handleFleetDetachBoxPage(w http.ResponseWriter, r *http.Request |
| s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| return |
| } |
| + if fleet.Managed { |
| + s.renderMessage(w, r, http.StatusConflict, "Refused", msgManagedBYO) |
| + return |
| + } |
| + |
| back := func(kind, msg string) { |
| s.setFlash(w, kind, msg) |
| http.Redirect(w, r, fleetPageURL(acct.Sqid, fleet.Name), http.StatusSeeOther) |
diff --git a/internal/console/managedhistory.go b/internal/console/managedhistory.go| new file mode 100644 |
| index 000000000..005a6cf10 |
| --- /dev/null |
| +++ b/internal/console/managedhistory.go |
| @@ -0,0 +1,341 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "os" |
| + "slices" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/fleetstore" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// COPY: safe preparation codes and refusal messages await controller review. |
| +var errManagedPreparation = errors.New("managed_preparation_failed") |
| +var errManagedJoiningDrain = errors.New("This managed box is still joining. Wait until it is ready before draining it.") |
| + |
| +const msgManagedBYO = "This action is unavailable for managed fleets." |
| + |
| +// Caller holds the fleet lock. Holding the history mutex through the CAS |
| +// makes a local invalidation win regardless of which writer arrives first. |
| +func (s *Server) admitManagedHistory(ctx context.Context, f registry.Fleet, label string) error { |
| + if !f.Managed || !registry.ValidTunnelName(f.Name) || f.Bucket == "" || (label != "" && !registry.ValidTunnelName(label)) { |
| + return errManagedPreparation |
| + } |
| + s.hosts.mu.Lock() |
| + defer s.hosts.mu.Unlock() |
| + if s.hosts.latched != "" || s.hosts.state.Mode == provision.HostsModeInvalidated || s.cfg.Releases == nil { |
| + return errManagedPreparation |
| + } |
| + for attempts := 0; attempts < 8; attempts++ { |
| + st, tag, e := provision.ReadHostsState(ctx, s.cfg.Releases) |
| + if e != nil { |
| + return errManagedPreparation |
| + } |
| + if st.Mode == "off" { |
| + return nil |
| + } |
| + key := "fleet:" + f.Name |
| + if st.Mode != provision.HostsModeActive || slices.Contains(st.Closed, key) { |
| + return errManagedPreparation |
| + } |
| + union := func(xs []string, x string) []string { |
| + if !slices.Contains(xs, x) { |
| + return append(xs, x) |
| + } |
| + return xs |
| + } |
| + st.Examined = union(st.Examined, key) |
| + if st.FleetTargets == nil { |
| + st.FleetTargets = map[string][]string{} |
| + } |
| + st.FleetTargets[key] = union(st.FleetTargets[key], "bucket:"+f.Bucket) |
| + if label != "" { |
| + st.FleetTargets[key] = union(st.FleetTargets[key], "box:fleet/"+f.Name+"/"+label) |
| + } |
| + st.At = time.Now().UTC() |
| + next, e := provision.WriteHostsState(ctx, s.cfg.Releases, st, tag) |
| + if errors.Is(e, release.ErrCASConflict) { |
| + continue |
| + } |
| + if e != nil { |
| + return errManagedPreparation |
| + } |
| + s.hosts.state, s.hosts.etag = st, next |
| + return nil |
| + } |
| + return errManagedPreparation |
| +} |
| + |
| +// reserveManagedFleet is the authenticated door's admission core. Request |
| +// aliases are resolved before provider/config gates or claiming a new name. |
| +func (s *Server) reserveManagedFleet(ctx context.Context, r managedRequest) (managedOp, []managedBox, bool, error) { |
| + if !managedRequestID.MatchString(r.RequestID) || r.Boxes <= 0 || !release.ValidAccount(r.Account) || !registry.ValidTunnelName(r.Fleet) || (r.Kind != "create" && r.Kind != "add") || r.Region == "" || r.Size == "" { |
| + return managedOp{}, nil, false, managedRefusal(400, "invalid managed fleet request", "") |
| + } |
| + defer s.lockFleet(r.Fleet)() |
| + if op, bs, found, e := s.store.lookupManagedRequest(ctx, r); found || e != nil { |
| + return op, bs, found, e |
| + } |
| + reg, e := openRegistry(s.cfg.Registry) |
| + if e != nil { |
| + return managedOp{}, nil, false, e |
| + } |
| + created := false |
| + if r.Kind == "create" { |
| + var ref *doorRefusal |
| + created, ref, e = s.createFleetAboveTheFloor(ctx, func() (bool, error) { |
| + return reg.CreateFleet(registry.Fleet{Name: r.Fleet, Account: r.Account, Managed: true}) |
| + }) |
| + if ref != nil { |
| + return managedOp{}, nil, false, managedRefusal(ref.Status, ref.Msg, "") |
| + } |
| + if e != nil { |
| + return managedOp{}, nil, false, e |
| + } |
| + } |
| + cleanup := func() { |
| + if created { |
| + var n int |
| + if e := s.store.db.QueryRowContext(ctx, `SELECT (SELECT count(*) FROM managed_ops WHERE fleet=?) + (SELECT count(*) FROM managed_boxes WHERE fleet=?)`, r.Fleet, r.Fleet).Scan(&n); e == nil && n == 0 { |
| + _, _ = reg.DeleteEmptyManagedFleet(r.Fleet, r.Account) |
| + } |
| + } |
| + } |
| + f, e := reg.GetFleet(r.Fleet) |
| + if e != nil { |
| + cleanup() |
| + return managedOp{}, nil, false, e |
| + } |
| + if f == nil || !f.Managed || f.Account != r.Account { |
| + cleanup() |
| + return managedOp{}, nil, false, managedRefusal(409, "fleet name is unavailable", "") |
| + } |
| + if r.Kind == "create" && !created { |
| + var n int |
| + e = s.store.db.QueryRowContext(ctx, `SELECT (SELECT count(*) FROM managed_ops WHERE fleet=?) + (SELECT count(*) FROM managed_boxes WHERE fleet=?)`, r.Fleet, r.Fleet).Scan(&n) |
| + bs, be := reg.ListFleetBoxes(r.Fleet) |
| + if e != nil || be != nil || n != 0 || len(bs) != 0 || f.Bucket != "" { |
| + return managedOp{}, nil, false, managedRefusal(409, "fleet name is unavailable", "") |
| + } |
| + } |
| + if s.cfg.ManagedCompute == nil || s.cfg.ManagedStorage == nil { |
| + cleanup() |
| + return managedOp{}, nil, false, managedRefusal(503, "managed providers are unavailable", "") |
| + } |
| + snap, e := s.managedSnapshot(ctx) |
| + if e != nil { |
| + cleanup() |
| + return managedOp{}, nil, false, managedRefusal(503, "managed configuration is unavailable", "") |
| + } |
| + key, _, e := openManagedEnrolKey(s.cfg.AlertSealKeyPath) |
| + if e != nil { |
| + cleanup() |
| + return managedOp{}, nil, false, errManagedPreparation |
| + } |
| + op, bs, existing, e := s.store.ReserveManaged(ctx, r, snap, s.cfg.ManagedDeployment, time.Now().UTC(), func(token string) (string, error) { _, hash := deriveManagedEnrolToken(key, token); return hash, nil }) |
| + if e != nil { |
| + cleanup() |
| + } |
| + return op, bs, existing, e |
| +} |
| + |
| +func (s *Server) prepareManagedFleet(ctx context.Context, op managedOp, boxes []managedBox) (result error) { |
| + defer func() { |
| + if result != nil { |
| + _, _ = s.store.db.ExecContext(context.WithoutCancel(ctx), `UPDATE managed_ops SET error=CASE WHEN error='' THEN 'managed_preparation_failed' ELSE error END WHERE id=? AND account=? AND fleet=? AND state='open'`, op.ID, op.Account, op.Fleet) |
| + } |
| + }() |
| + defer s.lockFleet(op.Fleet)() |
| + // Never trust a caller's stale deadline or operation state. |
| + stored, e := scanManagedOp(s.store.db.QueryRowContext(ctx, `SELECT `+managedOpCols+` FROM managed_ops WHERE id=? AND account=? AND fleet=?`, op.ID, op.Account, op.Fleet)) |
| + if e != nil { |
| + return e |
| + } |
| + op = stored |
| + if op.State != "open" { |
| + return errManagedPreparation |
| + } |
| + deadline := op.PreparationStartedAt.Add(30 * time.Minute) |
| + expired := func() error { |
| + if !time.Now().Before(deadline) { |
| + if e := s.store.failManagedPreparation(context.WithoutCancel(ctx), op); e != nil { |
| + return e |
| + } |
| + return errManagedPreparation |
| + } |
| + return nil |
| + } |
| + if e = expired(); e != nil { |
| + return e |
| + } |
| + if s.cfg.ManagedStorage == nil { |
| + return errManagedPreparation |
| + } |
| + ctx, cancel := context.WithDeadline(ctx, deadline) |
| + defer cancel() |
| + reg, e := openRegistry(s.cfg.Registry) |
| + if e != nil { |
| + return e |
| + } |
| + f, e := reg.GetFleet(op.Fleet) |
| + if e != nil { |
| + return e |
| + } |
| + if f == nil || !f.Managed || f.Account != op.Account { |
| + return errManagedPreparation |
| + } |
| + var saved fleetstore.FleetStorage |
| + var owner string |
| + e = s.store.db.QueryRowContext(ctx, `SELECT account,bucket,region FROM managed_fleet_storage WHERE fleet=?`, op.Fleet).Scan(&owner, &saved.Bucket, &saved.Region) |
| + if e != nil && e != sql.ErrNoRows { |
| + return e |
| + } |
| + if e == nil && owner != op.Account { |
| + return errManagedPreparation |
| + } |
| + region := op.Region |
| + if saved.Region != "" { |
| + region = saved.Region |
| + } |
| + got, e := s.cfg.ManagedStorage.EnsureFleetStorage(ctx, op.Fleet, region) |
| + if timeout := expired(); timeout != nil { |
| + return timeout |
| + } |
| + if e != nil { |
| + return errManagedPreparation |
| + } |
| + if got.Bucket == "" || got.Region != region || (saved.Bucket != "" && got != saved) || (f.Bucket != "" && f.Bucket != got.Bucket) { |
| + return errManagedPreparation |
| + } |
| + _, e = s.store.db.ExecContext(ctx, `INSERT INTO managed_fleet_storage(fleet,account,bucket,region) VALUES(?,?,?,?) ON CONFLICT(fleet) DO NOTHING`, op.Fleet, op.Account, got.Bucket, got.Region) |
| + if e != nil { |
| + return e |
| + } |
| + // Check even a conflict: another owner or different persisted storage is |
| + // never overwritten, including after an ambiguous provider result. |
| + e = s.store.db.QueryRowContext(ctx, `SELECT account,bucket,region FROM managed_fleet_storage WHERE fleet=?`, op.Fleet).Scan(&owner, &saved.Bucket, &saved.Region) |
| + if e != nil { |
| + return e |
| + } |
| + if owner != op.Account || saved != got { |
| + return errManagedPreparation |
| + } |
| + f.Bucket = got.Bucket |
| + if e = s.admitManagedHistory(ctx, *f, ""); e != nil { |
| + return e |
| + } |
| + ok, e := reg.SetManagedFleetBucket(f.Name, f.Account, f.Bucket) |
| + if e != nil { |
| + return e |
| + } |
| + if !ok { |
| + return errManagedPreparation |
| + } |
| + if e = s.writeFleetOwner(ctx, *f); e != nil { |
| + return errManagedPreparation |
| + } |
| + if _, e = s.managedCredentialsHeld(ctx, op.Fleet, op.Account, false); e != nil { |
| + return e |
| + } |
| + if e = expired(); e != nil { |
| + return e |
| + } |
| + // Storage on already reserved create boxes is filled only after all |
| + // preparation checks. Zero-box adds are allocated by the worker next. |
| + _, bs, e := s.store.ManagedFleet(ctx, op.Account, op.Fleet) |
| + if e != nil { |
| + return e |
| + } |
| + for _, b := range bs { |
| + if b.OpID == op.ID && b.State == "reserved" { |
| + next := b |
| + next.Storage = got |
| + ok, e := s.store.AdvanceManagedBox(ctx, b, next) |
| + if e != nil { |
| + return e |
| + } |
| + if !ok { |
| + return errManagedPreparation |
| + } |
| + } |
| + } |
| + if e = expired(); e != nil { |
| + return e |
| + } |
| + _, e = s.store.db.ExecContext(ctx, `UPDATE managed_fleet_storage SET prepared=1 WHERE fleet=? AND account=?`, op.Fleet, op.Account) |
| + return e |
| +} |
| + |
| +// The enrolment caller holds the fleet lock and persists the delivered ID |
| +// before sending the response. Preparation seals without advancing that ID. |
| +func (s *Server) managedFleetCredentials(ctx context.Context, fleet, account string) (fleetstore.Credentials, error) { |
| + return s.managedCredentialsHeld(ctx, fleet, account, true) |
| +} |
| +func (s *Server) managedCredentialsHeld(ctx context.Context, fleet, account string, deliver bool) (fleetstore.Credentials, error) { |
| + var id, keep string |
| + var sealed []byte |
| + e := s.store.db.QueryRowContext(ctx, `SELECT credential_id,credential_sealed,delivered_key_id FROM managed_fleet_storage WHERE fleet=? AND account=?`, fleet, account).Scan(&id, &sealed, &keep) |
| + if e != nil { |
| + return fleetstore.Credentials{}, e |
| + } |
| + seal, created, e := openConnectorSeal(s.cfg.AlertSealKeyPath) |
| + if e != nil { |
| + return fleetstore.Credentials{}, errManagedPreparation |
| + } |
| + info, statErr := os.Stat(s.cfg.AlertSealKeyPath) |
| + if statErr != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 { |
| + return fleetstore.Credentials{}, errManagedPreparation |
| + } |
| + var secret []byte |
| + if !created && len(sealed) > 0 { |
| + secret, e = seal.Open(sealed) |
| + } |
| + if created || e != nil || len(secret) == 0 || id == "" { |
| + if s.cfg.ManagedStorage == nil { |
| + return fleetstore.Credentials{}, errManagedPreparation |
| + } |
| + cred, e := s.cfg.ManagedStorage.RotateFleetCredentials(ctx, fleet, keep) |
| + if e != nil || cred.ID == "" || len(cred.Secret) == 0 { |
| + return fleetstore.Credentials{}, errManagedPreparation |
| + } |
| + sealed, e = seal.Seal(cred.Secret) |
| + if e != nil { |
| + return fleetstore.Credentials{}, errManagedPreparation |
| + } |
| + _, e = s.store.db.ExecContext(ctx, `UPDATE managed_fleet_storage SET credential_id=?,credential_sealed=? WHERE fleet=? AND account=?`, cred.ID, sealed, fleet, account) |
| + if e != nil { |
| + return fleetstore.Credentials{}, e |
| + } |
| + id, secret = cred.ID, cred.Secret |
| + } |
| + if deliver { |
| + _, e = s.store.db.ExecContext(ctx, `UPDATE managed_fleet_storage SET delivered_key_id=? WHERE fleet=? AND account=?`, id, fleet, account) |
| + if e != nil { |
| + return fleetstore.Credentials{}, e |
| + } |
| + } |
| + return fleetstore.Credentials{ID: id, Secret: secret}, nil |
| +} |
| + |
| +// Resolve lazily so an unavailable registry does not prevent console startup. |
| +type managedRegistryPath string |
| + |
| +func (p managedRegistryPath) GetFleet(name string) (*registry.Fleet, error) { |
| + r, e := openRegistry(string(p)) |
| + if e != nil { |
| + return nil, e |
| + } |
| + return r.GetFleet(name) |
| +} |
| +func (p managedRegistryPath) ListFleetBoxes(name string) ([]registry.FleetBox, error) { |
| + r, e := openRegistry(string(p)) |
| + if e != nil { |
| + return nil, e |
| + } |
| + return r.ListFleetBoxes(name) |
| +} |
diff --git a/internal/console/managedhistory_test.go b/internal/console/managedhistory_test.go| new file mode 100644 |
| index 000000000..241bf7234 |
| --- /dev/null |
| +++ b/internal/console/managedhistory_test.go |
| @@ -0,0 +1,491 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "github.com/carlosframework/platform/internal/compute" |
| + "github.com/carlosframework/platform/internal/fleetstore" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func managedPreparationFixture(t *testing.T) (*Server, consoleRegistry) { |
| + t.Helper() |
| + db, _ := managedDB(t) |
| + path := filepath.Join(t.TempDir(), "registry.db") |
| + reg, e := openRegistry(path) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + db.managedRegistry = reg |
| + s := &Server{store: db, cfg: Config{Registry: path, Releases: release.NewDirStore(t.TempDir()), AlertSealKeyPath: filepath.Join(t.TempDir(), "seal"), ManagedStorage: fleetstore.NewFake(), ManagedCompute: compute.NewFake(), ManagedDeployment: "test"}} |
| + s.managed.watch = &managedTestWatch{ok: true} |
| + s.managed.snapshot = managedConfigSnapshot{Config: validManagedConfig()} |
| + s.managed.read = true |
| + return s, reg |
| +} |
| +func setManagedHistory(t *testing.T, s *Server, st provision.HostsState) { |
| + t.Helper() |
| + _, tag, _ := provision.ReadHostsState(context.Background(), s.cfg.Releases) |
| + if _, e := provision.WriteHostsState(context.Background(), s.cfg.Releases, st, tag); e != nil { |
| + t.Fatal(e) |
| + } |
| +} |
| +func TestManagedBornExamined(t *testing.T) { |
| + s, reg := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + setManagedHistory(t, s, provision.HostsState{Mode: provision.HostsModeActive}) |
| + op, boxes, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if ref := s.hostsTargetRefusal(ctx, "fleet/production"); ref == nil { |
| + t.Fatal("unprepared fleet admitted") |
| + } |
| + if e = s.prepareManagedFleet(ctx, op, boxes); e != nil { |
| + t.Fatal(e) |
| + } |
| + f, _ := reg.GetFleet(op.Fleet) |
| + st, _, e := provision.ReadHostsState(ctx, s.cfg.Releases) |
| + if e != nil || !slices.Contains(st.Examined, "fleet:production") || !slices.Contains(st.FleetTargets["fleet:production"], "bucket:"+f.Bucket) { |
| + t.Fatalf("%+v %v", st, e) |
| + } |
| + if s.hosts.verified { |
| + t.Fatal("admission bypassed startup verification") |
| + } |
| + if e = s.admitManagedHistory(ctx, *f, "box-1"); e != nil { |
| + t.Fatal(e) |
| + } |
| + if ref := s.hostsCoverageRefusal(ctx, "fleet/production"); ref != nil { |
| + t.Fatal(ref) |
| + } |
| +} |
| +func TestManagedHistoryModes(t *testing.T) { |
| + for _, mode := range []string{"incomplete", "invalidated", "active"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + st := provision.HostsState{Mode: mode} |
| + if mode == "active" { |
| + st.Closed = []string{"fleet:production"} |
| + } |
| + setManagedHistory(t, s, st) |
| + if e := s.admitManagedHistory(context.Background(), registry.Fleet{Name: "production", Managed: true, Account: "abc", Bucket: "bucket"}, ""); e == nil { |
| + t.Fatal("refused mode admitted") |
| + } |
| + }) |
| + } |
| + s, _ := managedPreparationFixture(t) |
| + setManagedHistory(t, s, provision.HostsState{Mode: "active"}) |
| + s.hosts.latched = "breach" |
| + if e := s.admitManagedHistory(context.Background(), registry.Fleet{Name: "production", Managed: true, Bucket: "bucket"}, ""); e == nil { |
| + t.Fatal("latch cleared") |
| + } |
| +} |
| +func TestManagedPrepareNameRace(t *testing.T) { |
| + s, reg := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + reg.CreateFleet(registry.Fleet{Name: "production", Account: "other"}) |
| + if _, _, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")); e == nil { |
| + t.Fatal("foreign name accepted") |
| + } |
| + reg.CreateFleet(registry.Fleet{Name: "resume", Account: "abc", Managed: true}) |
| + if _, _, _, e := s.reserveManagedFleet(ctx, managedReq("resume", "abc")); e != nil { |
| + t.Fatal(e) |
| + } |
| +} |
| +func TestManagedPreparationDeadline(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + op, bs, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + _, e = s.store.db.Exec(`UPDATE managed_ops SET preparation_started_at=? WHERE id=?`, managedStamp(time.Now().Add(-31*time.Minute)), op.ID) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = s.prepareManagedFleet(ctx, op, bs); e == nil { |
| + t.Fatal("expired preparation accepted") |
| + } |
| + ops, boxes, e := s.store.ManagedFleet(ctx, "abc", "production") |
| + if e != nil || ops[0].State != "failed" { |
| + t.Fatalf("%+v %v", ops, e) |
| + } |
| + for _, b := range boxes { |
| + if b.State != "terminated" { |
| + t.Fatal(b.State) |
| + } |
| + } |
| +} |
| +func TestManagedFleetCredentials(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + setManagedHistory(t, s, provision.HostsState{Mode: "off"}) |
| + op, bs, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = s.prepareManagedFleet(ctx, op, bs); e != nil { |
| + t.Fatal(e) |
| + } |
| + a, e := s.managedFleetCredentials(ctx, op.Fleet, op.Account) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + b, e := s.managedFleetCredentials(ctx, op.Fleet, op.Account) |
| + if e != nil || a.ID != b.ID || string(a.Secret) != string(b.Secret) { |
| + t.Fatal("credentials changed", e) |
| + } |
| + var sealed []byte |
| + var delivered string |
| + if e = s.store.db.QueryRow(`SELECT credential_sealed,delivered_key_id FROM managed_fleet_storage WHERE fleet=?`, op.Fleet).Scan(&sealed, &delivered); e != nil { |
| + t.Fatal(e) |
| + } |
| + if string(sealed) == string(a.Secret) || delivered != a.ID { |
| + t.Fatal("credential persistence") |
| + } |
| +} |
| + |
| +type managedHistoryRaceStore struct { |
| + release.Store |
| + once bool |
| +} |
| + |
| +func (m *managedHistoryRaceStore) Put(ctx context.Context, key string, b []byte, tag string) (string, error) { |
| + if key == provision.HostsModeKey && !m.once { |
| + m.once = true |
| + st, current, e := provision.ReadHostsState(ctx, m.Store) |
| + if e != nil { |
| + return "", e |
| + } |
| + st.Examined = append(st.Examined, "fleet:other", "region:eu") |
| + st.FleetTargets = map[string][]string{"fleet:other": {"bucket:other"}} |
| + st.RegionTargets = []string{"box:region-box"} |
| + st.Closed = []string{"fleet:closed"} |
| + st.Reason = "retained" |
| + if _, e = provision.WriteHostsState(ctx, m.Store, st, current); e != nil { |
| + return "", e |
| + } |
| + } |
| + return m.Store.Put(ctx, key, b, tag) |
| +} |
| +func TestManagedHistoryCASRace(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + setManagedHistory(t, s, provision.HostsState{Mode: "active"}) |
| + s.cfg.Releases = &managedHistoryRaceStore{Store: s.cfg.Releases} |
| + if e := s.admitManagedHistory(context.Background(), registry.Fleet{Name: "production", Account: "abc", Managed: true, Bucket: "bucket"}, "box-1"); e != nil { |
| + t.Fatal(e) |
| + } |
| + st, _, _ := provision.ReadHostsState(context.Background(), s.cfg.Releases) |
| + if !slices.Contains(st.Examined, "fleet:other") || !slices.Contains(st.Examined, "fleet:production") || !slices.Contains(st.FleetTargets["fleet:production"], "box:fleet/production/box-1") || len(st.RegionTargets) != 1 || len(st.Closed) != 1 || st.Reason != "retained" { |
| + t.Fatalf("lost concurrent state: %+v", st) |
| + } |
| +} |
| +func TestManagedHistoryBeforeRegistry(t *testing.T) { |
| + s, reg := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + op, bs, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + // Absent history is incomplete and cannot publish storage. |
| + if e = s.prepareManagedFleet(ctx, op, bs); e == nil { |
| + t.Fatal("incomplete history accepted") |
| + } |
| + f, _ := reg.GetFleet(op.Fleet) |
| + if f.Bucket != "" { |
| + t.Fatal("bucket published before admission") |
| + } |
| + setManagedHistory(t, s, provision.HostsState{Mode: "active"}) |
| + if e = s.prepareManagedFleet(ctx, op, bs); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = s.prepareManagedFleet(ctx, op, bs); e != nil { |
| + t.Fatal("retry", e) |
| + } |
| + if s.cfg.ManagedCompute.(*compute.Fake).Calls()["Launch"] != 0 { |
| + t.Fatal("preparation launched") |
| + } |
| +} |
| +func TestManagedSealKeyLost(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + setManagedHistory(t, s, provision.HostsState{Mode: "off"}) |
| + op, bs, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = s.prepareManagedFleet(ctx, op, bs); e != nil { |
| + t.Fatal(e) |
| + } |
| + first, e := s.managedFleetCredentials(ctx, op.Fleet, op.Account) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + for _, lost := range []bool{true, false} { |
| + if lost { |
| + if e = os.Remove(s.cfg.AlertSealKeyPath); e != nil { |
| + t.Fatal(e) |
| + } |
| + } else { |
| + _, e = s.store.db.Exec(`UPDATE managed_fleet_storage SET credential_sealed=? WHERE fleet=?`, []byte("corrupt"), op.Fleet) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + next, e := s.managedFleetCredentials(ctx, op.Fleet, op.Account) |
| + if e != nil || next.ID == first.ID { |
| + t.Fatal("rotation", next.ID, e) |
| + } |
| + first = next |
| + } |
| + key, _, e := openManagedEnrolKey(s.cfg.AlertSealKeyPath) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + _, hash := deriveManagedEnrolToken(key, bs[0].ClientToken) |
| + if hash == bs[0].EnrolHash { |
| + t.Fatal("key loss retained launch hash") |
| + } |
| + if s.cfg.ManagedCompute.(*compute.Fake).Calls()["Launch"] != 0 { |
| + t.Fatal("launched") |
| + } |
| +} |
| +func TestManagedAddAfterPreparationFailure(t *testing.T) { |
| + s, reg := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + reg.CreateFleet(registry.Fleet{Name: "production", Account: "abc", Managed: true}) |
| + r := managedReq("production", "abc") |
| + r.Kind = "add" |
| + op, bs, _, e := s.reserveManagedFleet(ctx, r) |
| + if e != nil || len(bs) != 0 { |
| + t.Fatal(op, bs, e) |
| + } |
| + s.store.FinishManagedOp(ctx, op.ID, time.Now()) |
| + work, _, e := s.store.ManagedWork(ctx) |
| + if e != nil || len(work) != 1 || !work[0].PreparationStartedAt.Equal(op.PreparationStartedAt) { |
| + t.Fatal("lost preparing work", work, e) |
| + } |
| + if e = s.prepareManagedFleet(ctx, op, nil); e == nil { |
| + t.Fatal("expected incomplete history failure") |
| + } |
| + setManagedHistory(t, s, provision.HostsState{Mode: "off"}) |
| + if e = s.prepareManagedFleet(ctx, work[0], nil); e != nil { |
| + t.Fatal(e) |
| + } |
| + bs, e = s.store.AllocatePreparedManaged(ctx, op.ID, managedConfigSnapshot{Config: validManagedConfig()}, "test", time.Now(), managedHash) |
| + if e != nil || len(bs) != r.Boxes || bs[0].Storage.Bucket == "" { |
| + t.Fatal("allocation", bs, e) |
| + } |
| +} |
| +func TestManagedBYOBoundary(t *testing.T) { |
| + fx, token := fleetFixture(t, "managed-boundary") |
| + reg := openTestReg(t, fx) |
| + defer reg.Close() |
| + reg.CreateFleet(registry.Fleet{Name: "production", Account: fx.sqid, Managed: true}) |
| + reg.AddFleetBox(registry.FleetBox{Fleet: "production", Label: "box-1", TokenHash: strings.Repeat("a", 64)}) |
| + base := fleetsURL(fx, fx.sqid) + "/production/boxes" |
| + for _, suffix := range []string{"", "/box-1/rotate", "/box-1/detach", "/box-1/drain"} { |
| + st, body := postJSON(t, base+suffix, map[string]any{"label": "box-1"}, token) |
| + if st != 409 { |
| + t.Fatalf("%s: %d %v", suffix, st, body) |
| + } |
| + } |
| + browser := newBrowser(t) |
| + signUp(t, fx, browser, "managed-boundary-browser") |
| + csrf := sessionToken(t, fx, browser) |
| + for _, action := range []string{"rotate", "detach"} { |
| + st, _, body := postFormHeaders(t, browser, fx.u("/fleets/production/"+action), url.Values{"csrf": {csrf}, "label": {"box-1"}}) |
| + if st != 409 { |
| + t.Fatalf("page %s: %d %s", action, st, body) |
| + } |
| + } |
| + st, body := postJSON(t, base+"/box-1/tags", map[string]string{"tags": "ssd"}, token) |
| + if st != 200 { |
| + t.Fatal("managed tag", st, body) |
| + } |
| + before, _ := reg.ListFleetBoxes("production") |
| + if len(before) != 1 || before[0].DrainingSince != 0 || before[0].TokenHash != strings.Repeat("a", 64) || before[0].Status != "active" { |
| + t.Fatal(before) |
| + } |
| + // The common drain core distinguishes ready rows before its existing |
| + // inventory checks, without giving a joining box mutation authority. |
| + b := managedBox{Fleet: "production", Label: "box-1", Account: fx.sqid, State: "ready"} |
| + raw, _ := json.Marshal(b) |
| + _, e := fx.st.db.Exec(`INSERT INTO managed_boxes(fleet,label,op_id,account,state,client_token,cloud_id,launch) VALUES(?,?,?,?,?,?,?,?)`, b.Fleet, b.Label, "op", b.Account, b.State, "token", "", raw) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = fx.srv.drainBox(context.Background(), b.Fleet, b.Label); errors.Is(e, errManagedJoiningDrain) { |
| + t.Fatal("ready box refused as joining") |
| + } |
| +} |
| + |
| +type managedStorageSpy struct { |
| + *fleetstore.Fake |
| + ensures, rotations int |
| + fail bool |
| + drift bool |
| + keeps []string |
| +} |
| + |
| +func (p *managedStorageSpy) EnsureFleetStorage(ctx context.Context, fleet, region string) (fleetstore.FleetStorage, error) { |
| + p.ensures++ |
| + if p.fail { |
| + return fleetstore.FleetStorage{}, errors.New("private provider error") |
| + } |
| + v, e := p.Fake.EnsureFleetStorage(ctx, fleet, region) |
| + if p.drift { |
| + v.Bucket = "foreign" |
| + } |
| + return v, e |
| +} |
| +func (p *managedStorageSpy) RotateFleetCredentials(ctx context.Context, fleet, keep string) (fleetstore.Credentials, error) { |
| + p.rotations++ |
| + p.keeps = append(p.keeps, keep) |
| + return p.Fake.RotateFleetCredentials(ctx, fleet, keep) |
| +} |
| +func TestManagedFleetCredentialsLostSealWrite(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + spy := &managedStorageSpy{Fake: fleetstore.NewFake()} |
| + s.cfg.ManagedStorage = spy |
| + setManagedHistory(t, s, provision.HostsState{Mode: "off"}) |
| + op, bs, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = s.prepareManagedFleet(ctx, op, bs); e != nil { |
| + t.Fatal(e) |
| + } |
| + first, e := s.managedFleetCredentials(ctx, op.Fleet, op.Account) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = s.managedFleetCredentials(ctx, op.Fleet, op.Account); e != nil || spy.rotations != 1 { |
| + t.Fatal("mint on retry", spy.rotations, e) |
| + } |
| + s.store.db.Exec(`UPDATE managed_fleet_storage SET credential_sealed=NULL WHERE fleet=?`, op.Fleet) |
| + _, e = s.store.db.Exec(`CREATE TRIGGER refuse_managed_seal BEFORE UPDATE OF credential_sealed ON managed_fleet_storage BEGIN SELECT RAISE(ABORT,'test crash before sealing'); END`) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + for range 2 { |
| + if _, e = s.managedFleetCredentials(ctx, op.Fleet, op.Account); e == nil { |
| + t.Fatal("failed seal accepted") |
| + } |
| + } |
| + var delivered string |
| + s.store.db.QueryRow(`SELECT delivered_key_id FROM managed_fleet_storage WHERE fleet=?`, op.Fleet).Scan(&delivered) |
| + if delivered != first.ID { |
| + t.Fatal("unsealed rotation advanced delivered ID") |
| + } |
| + s.store.db.Exec(`DROP TRIGGER refuse_managed_seal`) |
| + if _, e = s.managedFleetCredentials(ctx, op.Fleet, op.Account); e != nil { |
| + t.Fatal(e) |
| + } |
| + for _, keep := range spy.keeps[1:] { |
| + if keep != first.ID { |
| + t.Fatal("did not preserve delivered key", spy.keeps) |
| + } |
| + } |
| +} |
| +func TestManagedPreparationStorageDrift(t *testing.T) { |
| + s, reg := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + spy := &managedStorageSpy{Fake: fleetstore.NewFake()} |
| + s.cfg.ManagedStorage = spy |
| + op, bs, _, e := s.reserveManagedFleet(ctx, managedReq("production", "abc")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + // Storage persists before failed history admission, and survives retries. |
| + if e = s.prepareManagedFleet(ctx, op, bs); e == nil { |
| + t.Fatal("incomplete history") |
| + } |
| + spy.drift = true |
| + setManagedHistory(t, s, provision.HostsState{Mode: "active"}) |
| + if e = s.prepareManagedFleet(ctx, op, bs); e == nil { |
| + t.Fatal("drift accepted") |
| + } |
| + f, _ := reg.GetFleet(op.Fleet) |
| + if f.Bucket != "" { |
| + t.Fatal("drift published") |
| + } |
| + spy.drift = false |
| + owner := release.FleetOwnerKey(op.Account, op.Fleet) |
| + raw, _ := json.Marshal(release.FleetOwner{Fleet: op.Fleet, Account: "foreign", CreatedAt: 1}) |
| + s.cfg.Releases.Put(ctx, owner, raw, "") |
| + if e = s.prepareManagedFleet(ctx, op, bs); e == nil { |
| + t.Fatal("foreign owner accepted") |
| + } |
| + after, _, _ := s.cfg.Releases.Get(ctx, owner) |
| + if string(after) != string(raw) { |
| + t.Fatal("foreign owner overwritten") |
| + } |
| +} |
| +func TestManagedPrepareNameCleanup(t *testing.T) { |
| + s, reg := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + s.managed.snapshot.Config.Enabled = false |
| + if _, _, _, e := s.reserveManagedFleet(ctx, managedReq("new", "abc")); e == nil { |
| + t.Fatal("disabled accepted") |
| + } |
| + if f, _ := reg.GetFleet("new"); f != nil { |
| + t.Fatal("new empty claim leaked") |
| + } |
| + reg.CreateFleet(registry.Fleet{Name: "existing", Account: "abc", Managed: true}) |
| + if _, _, _, e := s.reserveManagedFleet(ctx, managedReq("existing", "abc")); e == nil { |
| + t.Fatal("disabled resume accepted") |
| + } |
| + if f, _ := reg.GetFleet("existing"); f == nil { |
| + t.Fatal("deleted someone else's empty claim") |
| + } |
| + s.managed.snapshot.Config.Enabled = true |
| + // Two atomic claimers, only the winner can own the name. |
| + ready := make(chan struct{}) |
| + done := make(chan bool) |
| + go func() { |
| + <-ready |
| + ok, _ := reg.CreateFleet(registry.Fleet{Name: "race", Account: "foreign"}) |
| + done <- ok |
| + }() |
| + close(ready) |
| + op, _, _, e := s.reserveManagedFleet(ctx, managedReq("race", "abc")) |
| + byo := <-done |
| + if (e == nil) == byo { |
| + t.Fatal("claim winners", byo, e) |
| + } |
| + f, _ := reg.GetFleet("race") |
| + if e == nil && (f.Account != op.Account || !f.Managed) { |
| + t.Fatal(f) |
| + } |
| +} |
| + |
| +func TestManagedHistoryOffAndUnreadable(t *testing.T) { |
| + s, _ := managedPreparationFixture(t) |
| + ctx := context.Background() |
| + f := registry.Fleet{Name: "production", Account: "abc", Managed: true, Bucket: "bucket"} |
| + setManagedHistory(t, s, provision.HostsState{Mode: "off"}) |
| + _, before, _ := provision.ReadHostsState(ctx, s.cfg.Releases) |
| + if e := s.admitManagedHistory(ctx, f, ""); e != nil { |
| + t.Fatal(e) |
| + } |
| + _, after, _ := provision.ReadHostsState(ctx, s.cfg.Releases) |
| + if before != after { |
| + t.Fatal("off history written") |
| + } |
| + s.cfg.Releases.Put(ctx, provision.HostsModeKey, []byte("invalid"), after) |
| + if e := s.admitManagedHistory(ctx, f, ""); e == nil { |
| + t.Fatal("unreadable history accepted") |
| + } |
| +} |
diff --git a/internal/console/managedstore.go b/internal/console/managedstore.go| index 06936ec4f..848e165a3 100644 |
| --- a/internal/console/managedstore.go |
| +++ b/internal/console/managedstore.go |
| @@ -492,3 +492,65 @@ func (s *Store) AllocatePreparedManaged(ctx context.Context, id string, snap man |
| } |
| return |
| } |
| + |
| +func (s *Store) lookupManagedRequest(ctx context.Context, r managedRequest) (op managedOp, boxes []managedBox, found bool, err error) { |
| + err = s.managedTransaction(ctx, func(c *sql.Conn) error { |
| + var id string |
| + var payload []byte |
| + e := c.QueryRowContext(ctx, `SELECT op_id,payload FROM managed_request_aliases WHERE account=? AND request_id=?`, r.Account, r.RequestID).Scan(&id, &payload) |
| + if e == nil { |
| + if string(payload) != string(managedPayload(r)) { |
| + return managedRefusal(409, "request ID has different parameters", "") |
| + } |
| + op, e = scanManagedOp(c.QueryRowContext(ctx, `SELECT `+managedOpCols+` FROM managed_ops WHERE id=? AND account=?`, id, r.Account)) |
| + } else if e == sql.ErrNoRows { |
| + op, e = scanManagedOp(c.QueryRowContext(ctx, `SELECT `+managedOpCols+` FROM managed_ops WHERE fleet=? AND state='open'`, r.Fleet)) |
| + if e == sql.ErrNoRows { |
| + return nil |
| + } |
| + if e == nil { |
| + if op.Account != r.Account { |
| + return managedRefusal(409, "fleet name is unavailable", "") |
| + } |
| + if !managedMatches(op, r) { |
| + return managedRefusal(409, "fleet has a different open operation", op.ID) |
| + } |
| + e = managedAlias(ctx, c, r, op.ID) |
| + } |
| + } |
| + if e != nil { |
| + return e |
| + } |
| + found = true |
| + boxes, e = managedLoadBoxes(ctx, c, `WHERE op_id=?`, op.ID) |
| + return e |
| + }) |
| + return |
| +} |
| + |
| +func (s *Store) failManagedPreparation(ctx context.Context, op managedOp) error { |
| + return s.managedTransaction(ctx, func(c *sql.Conn) error { |
| + bs, e := managedLoadBoxes(ctx, c, `WHERE op_id=?`, op.ID) |
| + if e != nil { |
| + return e |
| + } |
| + for _, b := range bs { |
| + // Only positive proof of never dispatching releases a reservation. |
| + if b.State != "reserved" || !b.LaunchStartedAt.IsZero() || b.CloudID != "" { |
| + continue |
| + } |
| + b.State = "terminated" |
| + b.LastError = "managed_preparation_timeout" |
| + b.UpdatedAt = time.Now().UTC() |
| + data, e := json.Marshal(b) |
| + if e != nil { |
| + return e |
| + } |
| + if _, e = c.ExecContext(ctx, `UPDATE managed_boxes SET state='terminated',launch=? WHERE fleet=? AND label=?`, data, b.Fleet, b.Label); e != nil { |
| + return e |
| + } |
| + } |
| + _, e = c.ExecContext(ctx, `UPDATE managed_ops SET state='failed',error=CASE WHEN error='' THEN 'managed_preparation_timeout' ELSE error END,updated_at=? WHERE id=? AND state='open'`, managedStamp(time.Now()), op.ID) |
| + return e |
| + }) |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 390294852..9104c25fe 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -39,11 +39,13 @@ import ( |
| "github.com/carlosframework/platform/internal/applog" |
| "github.com/carlosframework/platform/internal/apppolicy" |
| "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/compute" |
| "github.com/carlosframework/platform/internal/dbreads" |
| "github.com/carlosframework/platform/internal/dnsrec" |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/economics" |
| "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/fleetstore" |
| "github.com/carlosframework/platform/internal/geo" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/hostops" |
| @@ -614,7 +616,10 @@ type Config struct { |
| // AlertSealKeyPath is the connector seal's key file (alertseal.go, |
| // fleet alerts spec §5.1): beside console.db, never inside it, so a |
| // replica or backup of the database alone cannot open a Slack URL. |
| - AlertSealKeyPath string |
| + AlertSealKeyPath string |
| + ManagedCompute compute.Provisioner |
| + ManagedStorage fleetstore.Provisioner |
| + ManagedDeployment string |
| // AlertEngineBeatPath is the beat file the alert engine replaces after |
| // each pass (alertwatch.go), which the console box's agent watches as |
| // CARLOS_ALERT_ENGINE_BEAT (fleet alerts spec §8). "" writes none |
| @@ -1686,6 +1691,7 @@ func normalizeDelegationZone(raw string) string { |
| // NewServer wires a server over an opened Store, loading (or minting) the |
| // console's Keymail signing key. |
| func NewServer(cfg Config, st *Store) (*Server, error) { |
| + st.managedRegistry = managedRegistryPath(cfg.Registry) |
| if cfg.Billing != nil && cfg.PlanCatalog == nil { |
| return nil, errors.New("billing needs a plan catalog (CARLOS_PLAN_CATALOG)") |
| } |
diff --git a/internal/console/view.go b/internal/console/view.go| index a53c7ef02..10f09f46f 100644 |
| --- a/internal/console/view.go |
| +++ b/internal/console/view.go |
| @@ -530,6 +530,8 @@ type consoleRegistry interface { |
| ListPaths() ([]registry.RoutePath, error) |
| SetPlacement(string, string) error |
| CreateFleet(registry.Fleet) (bool, error) |
| + DeleteEmptyManagedFleet(string, string) (bool, error) |
| + SetManagedFleetBucket(string, string, string) (bool, error) |
| GetFleet(string) (*registry.Fleet, error) |
| ListFleets() ([]registry.Fleet, error) |
| FleetOwners() (map[string]string, error) |
diff --git a/internal/provision/hostsused.go b/internal/provision/hostsused.go| index ad59fce97..7a9e0f189 100644 |
| --- a/internal/provision/hostsused.go |
| +++ b/internal/provision/hostsused.go |
| @@ -35,6 +35,7 @@ const ( |
| // with the console stopped (console hosts-used); a serving console can only |
| // move active to invalidated. |
| const ( |
| + HostsModeOff = "off" |
| HostsModeIncomplete = "incomplete" |
| HostsModeActive = "active" |
| HostsModeInvalidated = "invalidated" |
| @@ -119,7 +120,7 @@ func (r Record) DataKind() bool { |
| func validHostsMode(m string) bool { |
| switch m { |
| - case HostsModeIncomplete, HostsModeActive, HostsModeInvalidated: |
| + case HostsModeOff, HostsModeIncomplete, HostsModeActive, HostsModeInvalidated: |
| return true |
| } |
| return false |
diff --git a/internal/provision/managed_fleets_2a_task5_census_test.go b/internal/provision/managed_fleets_2a_task5_census_test.go| new file mode 100644 |
| index 000000000..bc535f3a7 |
| --- /dev/null |
| +++ b/internal/provision/managed_fleets_2a_task5_census_test.go |
| @@ -0,0 +1,34 @@ |
| +package provision |
| + |
| +// The controller reviews these entries with the task-5 root census card. |
| +// NewServer supplies the lazy registry reader for managed reservations. |
| +// The two earlier-task entries cover the managed system-config door and |
| +// its route: operator-authorized writes of system/managed-fleets.json only. |
| +// Managed history admission calls the already-inventoried WriteHostsState; |
| +// preparation calls the already-inventoried Server.writeFleetOwner. Their |
| +// new call sites are internal/console/managedhistory.go, witnessed by |
| +// TestManagedBornExamined, TestManagedHistoryCASRace, |
| +// TestManagedHistoryBeforeRegistry and TestManagedPreparationStorageDrift. |
| +func managedFleets2aTask5WriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), probeBurstLimitWriteCensusInventory()...) |
| + for _, next := range []censusEntry{ |
| + {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "282105ef51198944b842b7a3940f5f7f4db5118fa1a0369b628b57dc6c3c1b02"}, |
| + {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "9007b0bf6786b5e652dc5306502c6353a66c9b08c96753af901e203a38ad8336"}, |
| + {"internal/console/system_managedfleets.go", "Server.handleAPISystemManagedSet", "nonrecord", "sel:Put", "34b04b9ee2234979fac66bcc82748ffadac69afa22e70f0a458ecbea7422949c"}, |
| + } { |
| + replaced := false |
| + for i, old := range entries { |
| + if old.File == next.File && old.Unit == next.Unit { |
| + if old.Class != next.Class || old.Kinds != next.Kinds { |
| + panic("managed task-5 census class changed") |
| + } |
| + entries[i] = next |
| + replaced = true |
| + } |
| + } |
| + if !replaced { |
| + entries = append(entries, next) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index e24ec464a..98f783289 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 := probeBurstLimitWriteCensusInventory() |
| + inventory := managedFleets2aTask5WriteCensusInventory() |
| 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 ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index ba8a9cdec..3e74d4f02 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -59,3 +59,4 @@ plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5 |
| plan14-root-reads-managed-fleets-2a-task-1.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc |
| plan14-root-reads-managed-fleets-2a-task-3.tsv 43389a9f6ddf3f5f2c23dbfaec9fd0df2f2f3a86efe3147da3d3d30fe4a4dd4e |
| plan14-root-reads-managed-fleets-2a-task-4.tsv 63ec311c20f67c064f2c2066f5aed2f7ddd9ecc545b385511485c480fceafb6f |
| +plan14-root-reads-managed-fleets-2a-task-5.tsv 19ad67bdbe2f4269fbfadd44bd36ca166118908e4e9d9da8f9b7a95916d013ee |
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-5.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-5.tsv| new file mode 100644 |
| index 000000000..154012f69 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-5.tsv |
| @@ -0,0 +1,10 @@ |
| +# Census overlay managed-fleets-2a-task-5, written by census-propose (#369). census-ruling-managed-fleets-2a-task-5, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-managed-fleets-2a-task-5.md. |
| +# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 3 new dispositions: 1 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 808170ebc3ae767d9c7b03b5654fe6b86e71c491b51bbea6ac7ed06200c97986 internal/registry/fleets.go Registry.DeleteEmptyManagedFleet legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-5;basis=Conditionally delete only the named owner's empty managed fleet; reject bucket, secret-key or box state. Caller holds fleet lock and checks console SQL has no ops or reservations. Witness TestManagedRegistryPreparationMethods (local and remote), TestManagedPrepareNameCleanup. file:Exec@273,registry:Changed@240,registry:remote@117,registry:remote@85,registry:sql@273,whole:Fleet@185,whole:remoteClient@119,whole:remoteClient@87 df78cda4562ee27a27197820af334e00e5dea4fbbea71cf870065a2ca1e0b74b |
| +@legacy 168dfc8ef17ad0f5dc44bfb1f6c6e41eeed08e588124919b2c76c94bb4654bad internal/registry/fleets.go Registry.SetManagedFleetBucket legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-5;basis=Only fill or confirm the named owner's managed bucket; reject drift, foreign owner and BYO. Preserve managed identity, secrets fields and created time, increment revision. Witness TestManagedRegistryPreparationMethods (local and remote), TestManagedPreparationStorageDrift. file:Exec@369,registry:Changed@336,registry:remote@167,registry:remote@199,registry:sql@369,whole:Fleet@265,whole:remoteClient@169,whole:remoteClient@201 6c86ce3861106730036695eae2cb8769cce719e2d03734582272b684702f4964 |
| +internal/registry/fleets.go Registry.DeleteEmptyManagedFleet legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-5;basis=Conditionally delete only the named owner's empty managed fleet; reject bucket, secret-key or box state. Caller holds fleet lock and checks console SQL has no ops or reservations. Witness TestManagedRegistryPreparationMethods (local and remote), TestManagedPrepareNameCleanup. file:Exec@273,registry:Changed@240,registry:remote@117,registry:remote@85,registry:sql@273,whole:Fleet@185,whole:remoteClient@119,whole:remoteClient@87 df78cda4562ee27a27197820af334e00e5dea4fbbea71cf870065a2ca1e0b74b |
| +internal/registry/fleets.go Registry.SetManagedFleetBucket legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-5;basis=Only fill or confirm the named owner's managed bucket; reject drift, foreign owner and BYO. Preserve managed identity, secrets fields and created time, increment revision. Witness TestManagedRegistryPreparationMethods (local and remote), TestManagedPreparationStorageDrift. file:Exec@369,registry:Changed@336,registry:remote@167,registry:remote@199,registry:sql@369,whole:Fleet@265,whole:remoteClient@169,whole:remoteClient@201 6c86ce3861106730036695eae2cb8769cce719e2d03734582272b684702f4964 |
| +internal/registry/remote_dispatch.go Registry.dispatchRemote hint E2 rev3=census-ruling-self-serve-moves-1;basis=the registry child (carlos __registry-child, the service user a root pass forks): plan14-root-reads-e's mixed declaration (E2 adds only the ArtifactHosts read; every other arm is the local method of the same name), with three more write arms, SetHoldIfSeq, ReleaseHoldSeq and InstallLifetimeIf, each calling the local setter; no read operation added; self-serve moves 1 Task 7;rev3=census-ruling-instance-egress-sizes-328-329;identity=the registry child (carlos __registry-child, the service user a root pass forks);basis=#328/#329 plan 1 Task 4: one more write arm, SetPolicy, calling the local Registry.SetPolicy with the request's Host, EgressAllow, Size and PolicyExpiresAt (remoteRequest fields sent by the remote handle's holder); the new kinds registry:EgressAllow, registry:Size and registry:PolicyExpiresAt, one site each, plus one more registry:Host site, all of the request; no read operation added; the read-only worker never reaches it (serveRemote's method gate); no production root pass sends SetPolicy;rev3=census-ruling-region-ha-p1a;basis=the registry child (carlos __registry-child, the service user a root pass forks): one more write arm, SetHA, calling the local Registry.SetHA with the request's Host (+registry:Host); no read operation added; only the provision pass sends it;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 2 and 8: two new remote methods, UpsertUnlessRootfs (carlos add's guarded write) and ResidentInstances (the residency sweep's list), each calling the same-named Registry method;rev3=census-ruling-regional-domains-447;basis=#447 Task 4: two more methods on the existing remote registry transport, ListRegional and ReplaceRegionalSet (request field RDs, response field Regional), each calling the local method of the same name, which validates its own input; no new kind of read;rev3=census-ruling-fleet-secrets-key;basis=one new case, SetFleetSecretsKey, reading the request's Name, Pub, KeyFP, By and At fields and calling SetFleetSecretsKey;rev3=census-ruling-fleet-public-routes;basis=fleet public routes (spec 2026-10-29 rev 4, §4.2 writer rule): Tasks 1-2: three new cases (SetFleetBoxIf reads the request's Fleet and answers Changed; PutForward reads TValue, a whole Route; DeleteForward reads Host and answers Changed); SetFleetBox gone (+registry:Changed x2, +registry:Fleet, +registry:Host, +registry:TValue, +whole:Route). Each case calls the local writer with its own guards.;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Tasks 2 and 6b): three more remote methods dispatched to their local forms, SetFleetBoxDraining (q.Fleet, q.Label, q.At, answering Number64), MarkFleetBoxLabelled (q.Fleet, q.Label, q.At) and SetFleetAssignment (q.Host, q.Assigned, q.Moved); remoteRequest gains Assigned and Moved. The registry child, not root.;rev3=census-ruling-managed-fleets-2a-task-5;basis=Expose the two owned managed preparation methods with Fleet envelope fields, preserving conditional result. Witness TestManagedRegistryPreparationMethods local/remote parity. registry:A@7733,registry:Account@2124,registry:Account@2223,registry:Account@4630,registry:Accounts@3292,registry:Addr@5207,registry:Addrs@5215,registry:Alias@7781,registry:Alias@7845,registry:Alias@7933,registry:Aliases@7655,registry:Alive@9608,registry:Args@7357,registry:AssetGen@5357,registry:AssetsOff@5344,registry:Assigned@5835,registry:At@2446,registry:At@2835,registry:At@2920,registry:At@6729,registry:At@7864,registry:At@7942,registry:At@9356,registry:Attempts@9378,registry:B@2495,registry:Backing@5026,registry:Bucket@2236,registry:BuildState@5594,registry:By@2440,registry:Changed@1996,registry:Changed@2069,registry:Changed@2170,registry:Changed@3715,registry:Changed@3802,registry:Changed@3891,registry:Changed@3962,registry:Changed@4066,registry:Changed@4153,registry:Changed@4246,registry:Changed@4328,registry:Changed@6182,registry:Changed@6319,registry:Changed@9288,registry:Channel@4690,registry:Channel@6025,registry:Channel@6574,registry:CheckedAt@6655,registry:Class@5145,registry:DoneBefore@9617,registry:Due@7058,registry:Due@7122,registry:Due@9400,registry:EgressAllow@5497,registry:Env@6093,registry:Env@6485,registry:Env@6585,registry:ExcludeHosts@9083,registry:ExcludeHosts@9178,registry:ExpectGood@6854,registry:ExpectOp@3770,registry:ExpectOp@4020,registry:ExpectPair@4200,registry:Expected@1250,registry:Expected@289,registry:Expected@762,registry:Expected@939,registry:F@1968,registry:F@2029,registry:F@2114,registry:F@2124,registry:F@2213,registry:F@2223,registry:F@2236,registry:Fleet@2268,registry:Fleet@2553,registry:Fleet@2635,registry:Fleet@2716,registry:Fleet@2817,registry:Fleet@2902,registry:Fleet@2991,registry:Fleet@6225,registry:FleetBoxes@2952,registry:Fleets@2326,registry:From@4801,registry:From@4862,registry:FromDB@4937,registry:FromOp@3858,registry:FromSock@4947,registry:Hash@5899,registry:Health@5224,registry:Host@1024,registry:Host@1135,registry:Host@272,registry:Host@3476,registry:Host@3517,registry:Host@3670,registry:Host@3746,registry:Host@3832,registry:Host@3924,registry:Host@3996,registry:Host@4102,registry:Host@4192,registry:Host@4280,registry:Host@4372,registry:Host@4622,registry:Host@4682,registry:Host@4740,registry:Host@4793,registry:Host@4854,registry:Host@4929,registry:Host@5018,registry:Host@5072,registry:Host@5137,registry:Host@5199,registry:Host@5277,registry:Host@5336,registry:Host@5424,registry:Host@5489,registry:Host@5586,registry:Host@5651,registry:Host@5712,registry:Host@5762,registry:Host@5827,registry:Host@5891,registry:Host@5952,registry:Host@6085,registry:Host@6139,registry:Host@6217,registry:Host@6354,registry:Host@6407,registry:Host@6637,registry:Host@6721,registry:Host@6778,registry:Host@6846,registry:Host@6935,registry:Host@6995,registry:Host@7050,registry:Host@7114,registry:Host@7298,registry:Host@7349,registry:Host@7416,registry:Host@7491,registry:Host@7554,registry:Host@8151,registry:Host@8277,registry:Host@8431,registry:Host@8719,registry:Host@8783,registry:Host@8842,registry:Host@8925,registry:Host@9008,registry:Host@9239,registry:Host@9324,registry:Host@9456,registry:Host@9537,registry:Host@9700,registry:Hosts@187,registry:Hosts@3355,registry:Hosts@6016,registry:Hosts@6476,registry:Hosts@6565,registry:Id@1244,registry:Id@1555,registry:Id@1654,registry:Id@1734,registry:Id@1885,registry:IdValue@3111,registry:Idle@7424,registry:Journal@1262,registry:Journal@1561,registry:Journal@1740,registry:Journal@442,registry:Keep@9716,registry:KeyFP@2431,registry:Kind@9545,registry:Kind@9708,registry:Label@2562,registry:Label@2644,registry:Label@2725,registry:Label@2826,registry:Label@2911,registry:Label@6234,registry:Limit@9074,registry:Limit@9169,registry:MaxRun@7432,registry:Method@151,registry:Moved@5847,registry:Ms@9372,registry:Name@1032,registry:Name@1143,registry:Name@2114,registry:Name@2213,registry:Name@2296,registry:Name@2416,registry:Name@3130,registry:Name@8791,registry:Name@8850,registry:Name@8933,registry:Name@9247,registry:Name@9332,registry:Name@9464,registry:Next@301,registry:NextAt@9390,registry:NextGood@6868,registry:NextValue@1814,registry:NextValue@1912,registry:Now@1167,registry:Now@7625,registry:Now@9067,registry:Now@9162,registry:Now@9255,registry:Number64@2775,registry:Number64@3218,registry:Number@9505,registry:Number@9576,registry:Number@9661,registry:Observed@365,registry:ObservedValue@643,registry:Old@1807,registry:Old@1905,registry:On@7003,registry:On@7499,registry:On@7562,registry:Op@3688,registry:Op@3764,registry:Op@3932,registry:Op@4014,registry:Op@4110,registry:Op@4288,registry:Op@4380,registry:Owner@280,registry:Owner@377,registry:Owner@660,registry:P@8385,registry:Pair@4032,registry:Pair@4116,registry:Pair@4214,registry:Path@8616,registry:Paths@8313,registry:PolicyExpiresAt@5520,registry:Prefix@8439,registry:Prev@6793,registry:Pub@2424,registry:RDs@8285,registry:RateLimit@5960,registry:Regional@8183,registry:Registration@1040,registry:Registration@1151,registry:Registration@8941,registry:Registration@9340,registry:Replica@5720,registry:Replicas@5659,registry:Retirement@1891,registry:Route@3453,registry:Routes@3411,registry:Routes@4406,registry:Routes@7156,registry:Routes@7223,registry:Routes@7592,registry:Rows@8727,registry:Seed@7306,registry:Size@5512,registry:Sqid@3122,registry:Sqid@3185,registry:Sqid@3264,registry:Status@1056,registry:Status@2734,registry:Status@3678,registry:Status@3754,registry:Status@3840,registry:Status@4004,registry:Status@4748,registry:Status@6645,registry:Status@7854,registry:Status@9362,registry:Status@9472,registry:Steering@5285,registry:StringMap@3028,registry:T@757,registry:T@851,registry:T@8667,registry:T@934,registry:TValue@3558,registry:TValue@3625,registry:TValue@6284,registry:Tags@2653,registry:Target@6415,registry:Targets@453,registry:Text@1460,registry:Text@1607,registry:Text@3232,registry:Text@8472,registry:Text@8535,registry:Timer@709,registry:Timer@8755,registry:Timer@891,registry:Timers@8978,registry:Timers@9037,registry:Timers@9126,registry:Times@9750,registry:To@4809,registry:To@4870,registry:ToDB@4959,registry:ToOp@3850,registry:ToSock@4967,registry:TokenHash@2571,registry:Tunnel@6147,registry:Unit@5080,registry:UpdateSettings@5432,registry:Ver@6786,registry:Ver@6943,registry:W@8085,registry:Wildcards@7979,whole:Account@3296,whole:ClaimOwnership@282,whole:ClaimOwnership@379,whole:ClaimOwnership@662,whole:ClaimRow@455,whole:ClaimRowArchive@561,whole:ClaimRowArchive@571,whole:ColdRows@1809,whole:ColdRows@1816,whole:ColdRows@1907,whole:ColdRows@1914,whole:Fleet@1970,whole:Fleet@2031,whole:Fleet@2116,whole:Fleet@2126,whole:Fleet@2215,whole:Fleet@2225,whole:Fleet@2238,whole:Fleet@2272,whole:Fleet@2330,whole:FleetBox@2497,whole:FleetBox@2956,whole:GoodBuild@6856,whole:GoodBuild@6870,whole:Pair@4034,whole:Pair@4118,whole:Pair@4202,whole:Pair@4216,whole:RegionalDomain@8187,whole:RegionalDomain@8287,whole:Route@3415,whole:Route@3457,whole:Route@3560,whole:Route@3627,whole:Route@367,whole:Route@4410,whole:Route@4565,whole:Route@4571,whole:Route@6286,whole:Route@7160,whole:Route@7227,whole:Route@7596,whole:RouteAlias@7659,whole:RouteAlias@7735,whole:RoutePath@8317,whole:RoutePath@8387,whole:Timer@645,whole:Timer@713,whole:Timer@759,whole:Timer@853,whole:Timer@8669,whole:Timer@8729,whole:Timer@8759,whole:Timer@895,whole:Timer@8982,whole:Timer@9041,whole:Timer@9130,whole:Timer@936,whole:WildcardDomain@7983,whole:WildcardDomain@8087 4d0f71618b343736ea8d04914f6dc6ad1b8adf2b6f28b839c2374fbbf7b68f93 |
| +@coverage internal/provision 9a0dfd729bf914b7bd91893aabecd5018a3e3ad3852fa1815c517342ed319a96 |
| +@coverage internal/registry 2812b9cdd82fb573d9b4be448790aabb8ed82aad0db5fe5c97972905b7afbe1d |
diff --git a/internal/registry/fleets.go b/internal/registry/fleets.go| index 85c3cbedb..c1ad84163 100644 |
| --- a/internal/registry/fleets.go |
| +++ b/internal/registry/fleets.go |
| @@ -760,3 +760,32 @@ func (r *Registry) FleetChannelAuth() (map[string]string, error) { |
| } |
| return out, rows.Err() |
| } |
| + |
| +func (r *Registry) DeleteEmptyManagedFleet(name, account string) (bool, error) { |
| + if r.remote != nil { |
| + out, err := r.remote.call(nil, remoteRequest{Method: "DeleteEmptyManagedFleet", F: Fleet{Name: name, Account: account}}, nil) |
| + return out.Changed, err |
| + } |
| + res, err := r.sql.Exec(`DELETE FROM fleets WHERE name=? AND account=? AND managed=1 AND bucket='' AND secrets_pubkey='' AND secrets_key_fp='' AND secrets_key_set_at=0 AND secrets_key_set_by='' AND NOT EXISTS(SELECT 1 FROM fleet_secrets_key_fps WHERE fleet=fleets.name) AND NOT EXISTS(SELECT 1 FROM fleet_boxes WHERE fleet=?)`, name, account, name) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + return n == 1, err |
| +} |
| + |
| +func (r *Registry) SetManagedFleetBucket(name, account, bucket string) (bool, error) { |
| + if bucket == "" { |
| + return false, errors.New("managed bucket is empty") |
| + } |
| + if r.remote != nil { |
| + out, err := r.remote.call(nil, remoteRequest{Method: "SetManagedFleetBucket", F: Fleet{Name: name, Account: account, Bucket: bucket}}, nil) |
| + return out.Changed, err |
| + } |
| + res, err := r.sql.Exec(`UPDATE fleets SET bucket=?,rev=rev+1 WHERE name=? AND account=? AND managed=1 AND (bucket='' OR bucket=?)`, bucket, name, account, bucket) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + return n == 1, err |
| +} |
diff --git a/internal/registry/fleets_test.go b/internal/registry/fleets_test.go| index 7cf1ec098..5b0bfc819 100644 |
| --- a/internal/registry/fleets_test.go |
| +++ b/internal/registry/fleets_test.go |
| @@ -789,3 +789,59 @@ func TestManagedRegistryRoundTrip(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +func TestManagedRegistryPreparationMethods(t *testing.T) { |
| + for _, remote := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "local", true: "remote"}[remote], func(t *testing.T) { |
| + var r *Registry |
| + if remote { |
| + r, _ = remoteTestRegistry(t) |
| + } else { |
| + r = openTestRegistry(t) |
| + } |
| + r.CreateFleet(Fleet{Name: "production", Account: "owner", Managed: true}) |
| + for _, account := range []string{"foreign", ""} { |
| + if ok, e := r.DeleteEmptyManagedFleet("production", account); e != nil || ok { |
| + t.Fatal("foreign delete", ok, e) |
| + } |
| + if ok, e := r.SetManagedFleetBucket("production", account, "bucket"); e != nil || ok { |
| + t.Fatal("foreign update", ok, e) |
| + } |
| + } |
| + if e := r.SetFleetSecretsKey("production", "pub", "fingerprint", "member", 123); e != nil { |
| + t.Fatal(e) |
| + } |
| + before, _ := r.GetFleet("production") |
| + if ok, e := r.SetManagedFleetBucket("production", "owner", "bucket"); e != nil || !ok { |
| + t.Fatal(ok, e) |
| + } |
| + after, _ := r.GetFleet("production") |
| + before.Bucket = "bucket" |
| + if *before != *after { |
| + t.Fatalf("changed fields %+v %+v", before, after) |
| + } |
| + if ok, e := r.SetManagedFleetBucket("production", "owner", "other"); e != nil || ok { |
| + t.Fatal("bucket drift", ok, e) |
| + } |
| + if ok, e := r.DeleteEmptyManagedFleet("production", "owner"); e != nil || ok { |
| + t.Fatal("deleted prepared", ok, e) |
| + } |
| + r.CreateFleet(Fleet{Name: "empty", Account: "owner", Managed: true}) |
| + if ok, e := r.DeleteEmptyManagedFleet("empty", "owner"); e != nil || !ok { |
| + t.Fatal(ok, e) |
| + } |
| + r.CreateFleet(Fleet{Name: "boxes", Account: "owner", Managed: true}) |
| + mustAddBox(t, r, "boxes", "box-1") |
| + if ok, e := r.DeleteEmptyManagedFleet("boxes", "owner"); e != nil || ok { |
| + t.Fatal("deleted with box", ok, e) |
| + } |
| + r.CreateFleet(Fleet{Name: "byo", Account: "owner"}) |
| + if ok, e := r.DeleteEmptyManagedFleet("byo", "owner"); e != nil || ok { |
| + t.Fatal("deleted BYO", ok, e) |
| + } |
| + if ok, e := r.SetManagedFleetBucket("byo", "owner", "bucket"); e != nil || ok { |
| + t.Fatal("updated BYO", ok, e) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go| index 3c2d4725c..377dcfdf8 100644 |
| --- a/internal/registry/remote_dispatch.go |
| +++ b/internal/registry/remote_dispatch.go |
| @@ -188,6 +188,10 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback |
| err = r.UpsertFleet(q.F) |
| case "CreateFleet": |
| out.Changed, err = r.CreateFleet(q.F) |
| + case "DeleteEmptyManagedFleet": |
| + out.Changed, err = r.DeleteEmptyManagedFleet(q.F.Name, q.F.Account) |
| + case "SetManagedFleetBucket": |
| + out.Changed, err = r.SetManagedFleetBucket(q.F.Name, q.F.Account, q.F.Bucket) |
| case "GetFleet": |
| out.Fleet, err = r.GetFleet(q.Name) |
| case "ListFleets": |