carlos / platform Public

feat: configure managed fleets through the system API

Add operator-only conditional settings, generation-based snapshots, and
managed-fleets show/set commands. Freeze resolved launch inputs for later
reservations. Prepare the root census proposal for controller review.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 7a67c035181ad1b6825ad8580badc9872850618a parent d174f10
17 files changed, +957 −5
  • cmd/console/main.go +3 −0
  • docs/site/cli.md +34 −0
  • docs/superpowers/notes/census-proposal-managed-fleets-2a-task-3.md +25 −0
  • internal/console/authcli.go +4 −1
  • internal/console/managedconfig.go +241 −0
  • internal/console/managedconfig_test.go +278 −0
  • internal/console/server.go +2 −0
  • internal/console/svcroutes_test.go +5 −2
  • internal/console/system_managedfleets.go +98 −0
  • internal/console/system_managedfleets_test.go +85 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-3.tsv +9 −0
  • internal/release/changeindex.go +5 −1
  • internal/release/changeindex_test.go +10 −0
  • system.go +4 −1
  • system_managedfleets.go +89 −0
  • system_managedfleets_test.go +64 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go
index e13fd40cd..d54b5d9a8 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -660,6 +660,9 @@ func serve() {
go recordViewBackstopLoop(context.Background(), v)
edgesWatch = w
}
+ if err := srv.SetManagedConfigWatch(context.Background(), edgesWatch); err != nil {
+ log.Printf("console: managed configuration: %v", err)
+ }
// The region labels' name map (region labels spec §3.2): one edges read
// at start, then at most every 10 minutes on a generation change, else
// every 30 (±10%).
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 12d9f5691..8d5e4301d 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2638,6 +2638,40 @@ Two things that are true of the deployment rather than of one app: the
platform's own release channel, and the deployment-wide settings an operator
owns.
+<!-- COPY: managed fleet settings text awaits controller copy review. -->
+#### carlos system managed-fleets show
+
+Read the deployment's managed fleet settings through the console:
+
+```sh
+carlos system managed-fleets show
+```
+
+Only people listed in `CARLOS_SYSTEM_OPERATORS` can read or change these settings.
+Owning an account, including the ops account, does not grant access. An absent
+configuration means managed fleets are disabled, with zero capacity.
+
+#### carlos system managed-fleets set
+
+Replace the settings with a JSON file:
+
+```sh
+carlos system managed-fleets set --file f.json
+```
+
+The file contains `enabled`, `ceiling`, `account_limit` and `regions`. Each region
+has `image`, `subnets`, `security_groups`, `root_gb` and a `sizes` map from names
+such as `large` to approved ARM instance types such as `m7g.large`.
+`account_limit: 0` uses the deployment ceiling; otherwise both limits apply.
+Unknown fields and invalid values are refused before anything is written.
+
+The command reads the current revision before writing. If another operator
+changes it meanwhile, the write is refused: run `show`, check the settings,
+and try again. Enabling requires a usable change index. This configures the
+provider-neutral core; real managed launches remain off until the approved
+provider drill. Disabling admission leaves existing reservations and cleanup
+intact.
+
#### The platform's own binary
`update` promotes a public release (or, with `--file`, a binary you built) to
diff --git a/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-3.md b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-3.md
new file mode 100644
index 000000000..eeeef8fb9
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-managed-fleets-2a-task-3.md
@@ -0,0 +1,25 @@
+# Census approval: managed-fleets-2a-task-3
+
+Ruling `census-ruling-managed-fleets-2a-task-3`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `system.go` `runSystem` | body | unchanged (0) | Adds managed-fleets operator CLI dispatch; no direct read added; existing root command branches unchanged. |
+| `system.go` `systemVerb` | body | unchanged (0) | Recognizes managed-fleets as a CLI family; no read added. |
+
+Envelopes re-pinned: `.`, `internal/release`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `system.go` `runSystem`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added;rev3=census-ruling-nearest-region-a;basis=adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops the "join" case (host.RunSystemJoin, deleted with internal/host/joinroot.go, its only caller) and its line in the usage text; every other branch unchanged; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the system verb dispatch gains named-units, routed to host.RunSystemNamedUnits; no read of its own
+- `system.go` `systemVerb`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added;rev3=census-ruling-nearest-region-a;basis=adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops "join" from the verb list, so `carlos system join` now falls to the unknown-verb message; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the known-verb list gains named-units; no read of its own
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `system_managedfleets.go:runSystemManagedFleets`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
+
+Seal: `5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc` → `43389a9f6ddf3f5f2c23dbfaec9fd0df2f2f3a86efe3147da3d3d30fe4a4dd4e`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-3.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index c9b50defd..17d2d17df 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1122,7 +1122,10 @@ func (s *Server) registerCLIRoutes() {
// The update doors want an OWNER of the ops account or an address on
// CARLOS_SYSTEM_OPERATORS, with upload the owner's alone
// (apiSystemRoller); the antivirus doors want an address on
- // CARLOS_STORE_OPERATORS (apiSystemOperator).
+ // CARLOS_STORE_OPERATORS (apiSystemOperator). Managed fleet settings require
+ // a configured system operator, without the ops-owner exception.
+ s.cliRoute("GET /api/cli/system/managed-fleets", svcrole.Set{}, s.handleAPISystemManagedGet)
+ s.cliRoute("PUT /api/cli/system/managed-fleets", svcrole.Set{}, s.handleAPISystemManagedSet)
s.cliRoute("GET /api/cli/system/status", svcrole.Set{}, s.handleAPISystemStatus)
s.cliRoute("POST /api/cli/system/update", svcrole.Set{}, s.handleAPISystemUpdate)
s.cliRoute("GET /api/cli/system/jobs/{id}", svcrole.Set{}, s.handleAPISystemJob)
diff --git a/internal/console/managedconfig.go b/internal/console/managedconfig.go
new file mode 100644
index 000000000..55c0b15e9
--- /dev/null
+++ b/internal/console/managedconfig.go
@@ -0,0 +1,241 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "regexp"
+ "strings"
+ "sync"
+
+ "github.com/carlosframework/platform/internal/compute"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const managedConfigKey = "system/managed-fleets.json"
+
+type managedConfig struct {
+ Enabled bool `json:"enabled"`
+ Ceiling int `json:"ceiling"`
+ AccountLimit int `json:"account_limit"`
+ Regions map[string]managedRegion `json:"regions"`
+}
+type managedRegion struct {
+ Image string `json:"image"`
+ Subnets []string `json:"subnets"`
+ SecurityGroups []string `json:"security_groups"`
+ RootGB int `json:"root_gb"`
+ Sizes map[string]string `json:"sizes"`
+}
+type managedResolved struct {
+ Generation uint64
+ Region, Size string
+ Launch compute.LaunchSpec
+}
+type managedConfigSnapshot struct {
+ Config managedConfig
+ Generation uint64
+}
+
+// Reads and local writes share this lock. An old read cannot complete after
+// a newer write, and concurrent readers perform one GET per generation.
+type managedConfigState struct {
+ mu sync.Mutex
+ watch scopeGens // installed before serving requests or starting workers
+ snapshot managedConfigSnapshot
+ read bool
+ err error
+}
+
+var managedARMType = regexp.MustCompile(`^([a-z]+[0-9]+(?:g|gd|gn|gen))\.(nano|micro|small|medium|large|xlarge|(?:2|4|8|12|16|24|32|48|64|96|112)xlarge|metal)$`)
+var managedARMFamilies = map[string]bool{
+ "t4g": true,
+ "m6g": true, "m6gd": true, "m7g": true, "m7gd": true, "m8g": true,
+ "c6g": true, "c6gd": true, "c6gn": true, "c7g": true, "c7gd": true, "c7gn": true, "c8g": true,
+ "r6g": true, "r6gd": true, "r7g": true, "r7gd": true, "r8g": true,
+ "x2gd": true, "im4gn": true, "is4gen": true, "i4g": true,
+}
+
+// COPY: validation errors in this file await controller copy review.
+func validateManagedConfig(c managedConfig) error {
+ if c.Ceiling < 0 || c.AccountLimit < 0 {
+ return errors.New("managed fleet limits cannot be negative")
+ }
+ if c.Enabled && len(c.Regions) == 0 {
+ return errors.New("enabled managed fleets need at least one region")
+ }
+ for name, r := range c.Regions {
+ if strings.TrimSpace(name) == "" || strings.TrimSpace(r.Image) == "" || r.RootGB <= 0 || len(r.Subnets) == 0 || len(r.SecurityGroups) == 0 || len(r.Sizes) == 0 {
+ return fmt.Errorf("managed region %q needs an image, subnets, security groups, sizes and positive root_gb", name)
+ }
+ for _, v := range append(append([]string(nil), r.Subnets...), r.SecurityGroups...) {
+ if strings.TrimSpace(v) == "" {
+ return fmt.Errorf("managed region %q has an empty subnet or security group", name)
+ }
+ }
+ for size, typ := range r.Sizes {
+ m := managedARMType.FindStringSubmatch(typ)
+ if strings.TrimSpace(size) == "" || m == nil || !managedARMFamilies[m[1]] {
+ return fmt.Errorf("managed size %q must map to an allowlisted ARM instance type", size)
+ }
+ }
+ }
+ return nil
+}
+func decodeManagedConfig(b []byte) (managedConfig, error) {
+ var c managedConfig
+ d := json.NewDecoder(bytes.NewReader(b))
+ d.DisallowUnknownFields()
+ if err := d.Decode(&c); err != nil {
+ return c, err
+ }
+ if bytes.Equal(bytes.TrimSpace(b), []byte("null")) {
+ return c, errors.New("managed configuration must be a JSON object")
+ }
+ var extra any
+ if err := d.Decode(&extra); err != io.EOF {
+ return c, errors.New("managed configuration must contain one JSON object")
+ }
+ return c, validateManagedConfig(c)
+}
+func cloneManagedConfig(c managedConfig) managedConfig {
+ out := c
+ out.Regions = make(map[string]managedRegion, len(c.Regions))
+ for k, r := range c.Regions {
+ r.Subnets = append([]string(nil), r.Subnets...)
+ r.SecurityGroups = append([]string(nil), r.SecurityGroups...)
+ sizes := make(map[string]string, len(r.Sizes))
+ for k, v := range r.Sizes {
+ sizes[k] = v
+ }
+ r.Sizes = sizes
+ out.Regions[k] = r
+ }
+ return out
+}
+
+// SetManagedConfigWatch loads once at startup, without polling the shared
+// watch. Admission still requires a usable observation from that watch.
+func (s *Server) SetManagedConfigWatch(ctx context.Context, w *release.ChangeWatch) error {
+ if w != nil {
+ s.managed.watch = w
+ }
+ var gen uint64
+ if w != nil {
+ gen, _ = w.Gen(managedConfigKey)
+ }
+ return s.refreshManagedConfig(ctx, gen)
+}
+func (s *Server) refreshManagedConfig(ctx context.Context, generation uint64) error {
+ st := &s.managed
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ if st.read && generation <= st.snapshot.Generation {
+ return st.err
+ }
+ return s.readManagedConfigLocked(ctx, generation)
+}
+func (s *Server) readManagedConfigLocked(ctx context.Context, generation uint64) error {
+ st := &s.managed
+ for {
+ if st.watch != nil {
+ if observed, ok := st.watch.Gen(managedConfigKey); ok && observed > generation {
+ generation = observed
+ }
+ }
+ st.read = true
+ st.snapshot = managedConfigSnapshot{Generation: generation}
+ if s.cfg.Releases == nil {
+ st.err = errors.New("managed configuration store is unavailable")
+ return st.err
+ }
+ b, _, err := s.cfg.Releases.Get(ctx, managedConfigKey)
+ var c managedConfig
+ if errors.Is(err, os.ErrNotExist) {
+ err = nil
+ } else if err == nil {
+ c, err = decodeManagedConfig(b)
+ }
+ // A generation observed during this GET supersedes its result. Do not
+ // publish the old completion, even when it failed.
+ if st.watch != nil && ctx.Err() == nil {
+ if observed, ok := st.watch.Gen(managedConfigKey); ok && observed > generation {
+ generation = observed
+ continue
+ }
+ }
+ st.err = err
+ if err == nil {
+ st.snapshot.Config = cloneManagedConfig(c)
+ }
+ return err
+ }
+}
+
+// managedSnapshot is the admission/active-pass seam. Workers keep using their
+// frozen reservations even when this refuses a new admission.
+func (s *Server) managedSnapshot(ctx context.Context) (managedConfigSnapshot, error) {
+ st := &s.managed
+ for {
+ if err := ctx.Err(); err != nil {
+ return managedConfigSnapshot{}, err
+ }
+ if st.watch == nil {
+ return managedConfigSnapshot{}, errors.New("managed fleets need change-index support")
+ }
+ gen, ok := st.watch.Gen(managedConfigKey)
+ if !ok {
+ return managedConfigSnapshot{}, errors.New("managed fleet change index is unavailable")
+ }
+ if err := s.refreshManagedConfig(ctx, gen); err != nil {
+ return managedConfigSnapshot{}, err
+ }
+ st.mu.Lock()
+ latest, usable := st.watch.Gen(managedConfigKey)
+ if !usable {
+ st.mu.Unlock()
+ return managedConfigSnapshot{}, errors.New("managed fleet change index is unavailable")
+ }
+ if latest < st.snapshot.Generation {
+ st.mu.Unlock()
+ return managedConfigSnapshot{}, errors.New("managed fleet change index moved backwards")
+ }
+ if latest != st.snapshot.Generation {
+ st.mu.Unlock()
+ continue
+ }
+ if st.err != nil {
+ err := st.err
+ st.mu.Unlock()
+ return managedConfigSnapshot{}, err
+ }
+ snap := managedConfigSnapshot{Config: cloneManagedConfig(st.snapshot.Config), Generation: st.snapshot.Generation}
+ st.mu.Unlock()
+ if snap.Config.AccountLimit == 0 {
+ snap.Config.AccountLimit = snap.Config.Ceiling
+ }
+ return snap, nil
+ }
+}
+func resolveManagedConfig(snapshot managedConfigSnapshot, region, size string, boxNumber int) (managedResolved, error) {
+ c := snapshot.Config
+ if err := validateManagedConfig(c); err != nil {
+ return managedResolved{}, err
+ }
+ if !c.Enabled {
+ return managedResolved{}, errors.New("managed fleets are disabled")
+ }
+ r, ok := c.Regions[region]
+ if !ok {
+ return managedResolved{}, errors.New("managed fleet region is unavailable")
+ }
+ typ, ok := r.Sizes[size]
+ if !ok || boxNumber < 0 {
+ return managedResolved{}, errors.New("managed fleet size or box number is invalid")
+ }
+ return managedResolved{Generation: snapshot.Generation, Region: region, Size: size, Launch: compute.LaunchSpec{Region: region, InstanceType: typ, Image: r.Image, Subnet: r.Subnets[boxNumber%len(r.Subnets)], SecurityGroups: append([]string(nil), r.SecurityGroups...), RootGB: r.RootGB}}, nil
+}
diff --git a/internal/console/managedconfig_test.go b/internal/console/managedconfig_test.go
new file mode 100644
index 000000000..b1a8cedde
--- /dev/null
+++ b/internal/console/managedconfig_test.go
@@ -0,0 +1,278 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type managedTestStore struct {
+ release.Store
+ mu sync.Mutex
+ gets int
+ fail bool
+}
+
+func (m *managedTestStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if key == managedConfigKey {
+ m.mu.Lock()
+ m.gets++
+ fail := m.fail
+ m.mu.Unlock()
+ if fail {
+ return nil, "", errors.New("unreadable")
+ }
+ }
+ return m.Store.Get(ctx, key)
+}
+
+type managedTestWatch struct {
+ mu sync.Mutex
+ gen uint64
+ ok bool
+}
+
+func (w *managedTestWatch) Gen(string) (uint64, bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.gen, w.ok
+}
+func (w *managedTestWatch) set(gen uint64, ok bool) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ w.gen, w.ok = gen, ok
+}
+func validManagedConfig() managedConfig {
+ return managedConfig{Enabled: true, Ceiling: 10, Regions: map[string]managedRegion{"eu-west-1": {Image: "image", Subnets: []string{"subnet-a", "subnet-b"}, SecurityGroups: []string{"sg"}, RootGB: 20, Sizes: map[string]string{"large": "m7g.large"}}}}
+}
+func managedFixture(t *testing.T) (*Server, *managedTestStore, *managedTestWatch) {
+ t.Helper()
+ st := &managedTestStore{Store: release.NewDirStore(t.TempDir())}
+ w := &managedTestWatch{gen: 1, ok: true}
+ s := &Server{cfg: Config{Releases: st, SystemOperators: []string{" Operator@example.com "}}}
+ s.managed.watch = w
+ return s, st, w
+}
+func putManagedTest(t *testing.T, st release.Store, c managedConfig) {
+ t.Helper()
+ b, _ := json.Marshal(c)
+ _, etag, _ := st.Get(context.Background(), managedConfigKey)
+ if _, err := st.Put(context.Background(), managedConfigKey, b, etag); err != nil {
+ t.Fatal(err)
+ }
+}
+func TestManagedConfigValidation(t *testing.T) {
+ for _, typ := range []string{"m7g.large", "c7gd.2xlarge", "c7gn.16xlarge", "is4gen.2xlarge", "r8g.large"} {
+ c := validManagedConfig()
+ c.Regions["eu-west-1"].Sizes["large"] = typ
+ if err := validateManagedConfig(c); err != nil {
+ t.Fatal(typ, err)
+ }
+ }
+ for _, typ := range []string{"m7i.large", "z99g.large", "m7g.", "m7g.large.extra", "m7g.0xlarge", "m7g.garbage"} {
+ c := validManagedConfig()
+ c.Regions["eu-west-1"].Sizes["large"] = typ
+ if validateManagedConfig(c) == nil {
+ t.Fatalf("accepted %s", typ)
+ }
+ }
+ for _, edit := range []func(*managedConfig){func(c *managedConfig) { c.Ceiling = -1 }, func(c *managedConfig) { c.AccountLimit = -1 }, func(c *managedConfig) { r := c.Regions["eu-west-1"]; r.RootGB = 0; c.Regions["eu-west-1"] = r }, func(c *managedConfig) { c.Regions["eu-west-1"].Subnets[0] = "" }, func(c *managedConfig) { c.Regions["eu-west-1"].SecurityGroups[0] = " " }, func(c *managedConfig) { c.Regions[""] = c.Regions["eu-west-1"] }} {
+ c := validManagedConfig()
+ edit(&c)
+ if validateManagedConfig(c) == nil {
+ t.Fatal("accepted invalid configuration")
+ }
+ }
+}
+func TestManagedConfigGeneration(t *testing.T) {
+ s, st, w := managedFixture(t)
+ putManagedTest(t, st, validManagedConfig())
+ st.gets = 0
+ for _, n := range []int{1, 100} {
+ var wg sync.WaitGroup
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if _, err := s.managedSnapshot(context.Background()); err != nil {
+ t.Error(err)
+ }
+ }()
+ }
+ wg.Wait()
+ }
+ if st.gets != 1 {
+ t.Fatalf("GETs=%d", st.gets)
+ }
+ w.set(2, true)
+ if _, err := s.managedSnapshot(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if st.gets != 2 {
+ t.Fatalf("GETs=%d", st.gets)
+ }
+ if err := s.refreshManagedConfig(context.Background(), 1); err != nil {
+ t.Fatal(err)
+ }
+ if st.gets != 2 {
+ t.Fatal("older generation reread")
+ }
+ snap, _ := s.managedSnapshot(context.Background())
+ snap.Config.Regions["eu-west-1"].Subnets[0] = "changed"
+ snap.Config.Regions["eu-west-1"].Sizes["large"] = "changed"
+ snap, _ = s.managedSnapshot(context.Background())
+ resolved, err := resolveManagedConfig(snap, "eu-west-1", "large", 1)
+ if err != nil || resolved.Launch.Subnet != "subnet-b" || resolved.Generation != 2 || resolved.Launch.InstanceType != "m7g.large" || snap.Config.AccountLimit != 10 {
+ t.Fatalf("%+v %v", resolved, err)
+ }
+ resolved.Launch.SecurityGroups[0] = "changed"
+ if snap.Config.Regions["eu-west-1"].SecurityGroups[0] != "sg" {
+ t.Fatal("aliased launch")
+ }
+}
+func TestManagedConfigUnavailable(t *testing.T) {
+ s, st, w := managedFixture(t)
+ snap, err := s.managedSnapshot(context.Background())
+ if err != nil || snap.Config.Enabled || snap.Config.Ceiling != 0 {
+ t.Fatalf("absent: %+v %v", snap, err)
+ }
+ putManagedTest(t, st, validManagedConfig())
+ w.set(2, true)
+ if _, err = s.managedSnapshot(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ st.fail = true
+ w.set(3, true)
+ if _, err = s.managedSnapshot(context.Background()); err == nil {
+ t.Fatal("failed refresh authorized")
+ }
+ before := st.gets
+ if _, err = s.managedSnapshot(context.Background()); err == nil || st.gets != before {
+ t.Fatal("invalid generation retried or authorized")
+ }
+ st.fail = false
+ w.set(4, false)
+ if _, err = s.managedSnapshot(context.Background()); err == nil {
+ t.Fatal("unusable watch authorized")
+ }
+ _, etag, _ := st.Get(context.Background(), managedConfigKey)
+ st.Put(context.Background(), managedConfigKey, []byte(`{"enabled":true,"unknown":1}`), etag)
+ w.set(4, true)
+ if _, err = s.managedSnapshot(context.Background()); err == nil {
+ t.Fatal("corrupt config authorized")
+ }
+}
+
+// Block the first GET after capturing its bytes to exercise invalidation
+// during I/O, rather than relying on goroutine scheduling to create the race.
+type managedBlockedStore struct {
+ release.Store
+ entered, resume chan struct{}
+ once sync.Once
+}
+
+func (st *managedBlockedStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ b, e, err := st.Store.Get(ctx, key)
+ if key == managedConfigKey {
+ st.once.Do(func() { close(st.entered); <-st.resume })
+ }
+ return b, e, err
+}
+func TestManagedConfigRefreshDuringRead(t *testing.T) {
+ s, st, w := managedFixture(t)
+ putManagedTest(t, st, validManagedConfig())
+ st.gets = 0
+ blocked := &managedBlockedStore{Store: st, entered: make(chan struct{}), resume: make(chan struct{})}
+ s.cfg.Releases = blocked
+ done := make(chan managedConfigSnapshot, 1)
+ go func() {
+ snap, err := s.managedSnapshot(context.Background())
+ if err != nil {
+ t.Error(err)
+ }
+ done <- snap
+ }()
+ <-blocked.entered
+ c := validManagedConfig()
+ c.Ceiling = 3
+ putManagedTest(t, st.Store, c)
+ w.set(2, true)
+ close(blocked.resume)
+ snap := <-done
+ if snap.Generation != 2 || snap.Config.Ceiling != 3 || st.gets != 2 {
+ t.Fatalf("stale completion: %+v GETs %d", snap, st.gets)
+ }
+}
+func TestManagedConfigRealWatch(t *testing.T) {
+ ctx := context.Background()
+ store := release.NewDirStore(t.TempDir())
+ store.EnableChangeIndex()
+ watch := release.NewChangeWatch(store)
+ s := &Server{cfg: Config{Releases: store, SystemOperators: []string{"operator@example.com"}}}
+ if err := s.SetManagedConfigWatch(ctx, watch); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.managedSnapshot(ctx); err == nil {
+ t.Fatal("uninitialized watch authorized")
+ }
+ if _, err := watch.Poll(ctx); err != nil {
+ t.Fatal(err)
+ }
+ c := validManagedConfig()
+ b, _ := json.Marshal(c)
+ out := managedCall(s, "PUT", "operator@example.com", string(b), "")
+ if out.Code != 200 {
+ t.Fatal(out.Code, out.Body)
+ }
+ // The writer bumped the index, but the shared watch has not polled yet.
+ snap, err := s.managedSnapshot(ctx)
+ if err != nil || !snap.Config.Enabled {
+ t.Fatal("local write not visible", err)
+ }
+ if _, err := watch.Poll(ctx); err != nil {
+ t.Fatal(err)
+ }
+ snap, err = s.managedSnapshot(ctx)
+ if err != nil || snap.Generation != 1 {
+ t.Fatalf("%+v %v", snap, err)
+ }
+ // An unsupported index makes the next mutation's best-effort bump fail.
+ _, etag, _ := store.Get(ctx, release.ChangeIndexKey)
+ store.Put(ctx, release.ChangeIndexKey, []byte(`{"schema":999}`), etag)
+ c.Ceiling = 4
+ b, _ = json.Marshal(c)
+ out = managedCall(s, "PUT", "operator@example.com", string(b), out.Header().Get("ETag"))
+ if out.Code != 200 {
+ t.Fatal(out.Code, out.Body)
+ }
+ snap, err = s.managedSnapshot(ctx)
+ if err != nil || snap.Config.Ceiling != 4 {
+ t.Fatalf("failed bump hid write: %+v %v", snap, err)
+ }
+ if _, err := watch.Poll(ctx); err == nil {
+ t.Fatal("bad index accepted")
+ }
+ if _, err := s.managedSnapshot(ctx); err == nil {
+ t.Fatal("failed watch authorized")
+ }
+}
+
+func TestManagedConfigGenerationRegression(t *testing.T) {
+ s, st, w := managedFixture(t)
+ putManagedTest(t, st, validManagedConfig())
+ w.set(2, true)
+ if _, err := s.managedSnapshot(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ w.set(1, true)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if _, err := s.managedSnapshot(ctx); err == nil || errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("regression did not refuse promptly: %v", err)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index cfee8f035..390294852 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -969,6 +969,8 @@ type Config struct {
// Server is the console's http.Handler.
type Server struct {
+ managed managedConfigState
+
// manifestSeen is the sqids whose accounts/<sqid>/account.json this
// process has seen exist (read, or written by the backfill), so an app
// tab stops asking the bucket for it on every view. Keyed by sqid, value
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 0b5375ff3..d57712c43 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -100,6 +100,9 @@ var (
// Only an equality catches both; "no empty Sets" catches neither, and "these
// are empty" catches only the first.
var closedDoors = []string{
+ "GET /api/cli/fleets/{account}/{fleet}",
+ "GET /api/cli/system/managed-fleets",
+ "PUT /api/cli/system/managed-fleets",
// Deployment-wide scanning policy. There is no {account} to scope a
// service credential to, and enabling it starts reading tenant bytes
// across every store on the deployment — an owner's decision, not a
@@ -1150,8 +1153,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 76 {
- t.Errorf("walked %d closed doors, want all %d (and 76 today: three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
+ if seen != len(closedDoors) || seen != 79 {
+ t.Errorf("walked %d closed doors, want all %d (and 79 today: the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/system_managedfleets.go b/internal/console/system_managedfleets.go
new file mode 100644
index 000000000..5509717ad
--- /dev/null
+++ b/internal/console/system_managedfleets.go
@@ -0,0 +1,98 @@
+package console
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "os"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func (s *Server) managedOperator(w http.ResponseWriter, r *http.Request) bool {
+ p, ok := principalFrom(r.Context())
+ if !ok || p.Kind != PrincipalUser || !s.systemOperator(p.Address) {
+ http.NotFound(w, r)
+ return false
+ }
+ return true
+}
+
+// COPY: operator errors in this file await controller copy review.
+func (s *Server) handleAPISystemManagedGet(w http.ResponseWriter, r *http.Request) {
+ if !s.managedOperator(w, r) {
+ return
+ }
+ if s.cfg.Releases == nil {
+ jsonError(w, 503, "managed configuration store is unavailable")
+ return
+ }
+ b, etag, err := s.cfg.Releases.Get(r.Context(), managedConfigKey)
+ var c managedConfig
+ if errors.Is(err, os.ErrNotExist) {
+ err = nil
+ } else if err == nil {
+ c, err = decodeManagedConfig(b)
+ }
+ if err != nil {
+ jsonError(w, 503, "managed configuration cannot be read")
+ return
+ }
+ w.Header().Set("ETag", etag)
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(c)
+}
+func (s *Server) handleAPISystemManagedSet(w http.ResponseWriter, r *http.Request) {
+ if !s.managedOperator(w, r) {
+ return
+ }
+ b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
+ if err != nil {
+ jsonError(w, 400, "managed configuration is too large or unreadable")
+ return
+ }
+ c, err := decodeManagedConfig(b)
+ if err != nil {
+ jsonError(w, 400, err.Error())
+ return
+ }
+ st := &s.managed
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ var gen uint64
+ var usable bool
+ if st.watch != nil {
+ gen, usable = st.watch.Gen(managedConfigKey)
+ }
+ if c.Enabled && !usable {
+ jsonError(w, 503, "managed fleets need a usable change index before enabling")
+ return
+ }
+ if s.cfg.Releases == nil {
+ jsonError(w, 503, "managed configuration store is unavailable")
+ return
+ }
+ b, _ = json.Marshal(c)
+ etag, err := s.cfg.Releases.Put(r.Context(), managedConfigKey, b, r.Header.Get("If-Match"))
+ if errors.Is(err, release.ErrCASConflict) {
+ jsonError(w, 409, "managed configuration changed; show it again before setting it")
+ return
+ }
+ if err != nil {
+ jsonError(w, 503, "managed configuration could not be saved")
+ return
+ }
+ // Read after the successful write even if its best-effort generation bump
+ // failed. Holding the lock prevents a prior read from replacing this value.
+ if gen < st.snapshot.Generation {
+ gen = st.snapshot.Generation
+ }
+ if err = s.readManagedConfigLocked(r.Context(), gen); err != nil {
+ jsonError(w, 503, "managed configuration was saved but could not be refreshed")
+ return
+ }
+ w.Header().Set("ETag", etag)
+ w.Header().Set("Content-Type", "application/json")
+ json.NewEncoder(w).Encode(c)
+}
diff --git a/internal/console/system_managedfleets_test.go b/internal/console/system_managedfleets_test.go
new file mode 100644
index 000000000..71b73d981
--- /dev/null
+++ b/internal/console/system_managedfleets_test.go
@@ -0,0 +1,85 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func managedCall(s *Server, method, addr, body, etag string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, "/api/cli/system/managed-fleets", strings.NewReader(body))
+ r.Header.Set("If-Match", etag)
+ r = r.WithContext(context.WithValue(r.Context(), cliRouteKey{}, Principal{Kind: PrincipalUser, Address: addr}))
+ w := httptest.NewRecorder()
+ if method == "GET" {
+ s.handleAPISystemManagedGet(w, r)
+ } else {
+ s.handleAPISystemManagedSet(w, r)
+ }
+ return w
+}
+func TestManagedConfigOperatorsOnly(t *testing.T) {
+ s, _, _ := managedFixture(t)
+ b, _ := json.Marshal(validManagedConfig())
+ for _, addr := range []string{"member@example.com", "owner@example.com", "ops-owner@example.com"} {
+ for _, method := range []string{"GET", "PUT"} {
+ w := managedCall(s, method, addr, string(b), "")
+ if w.Code != 404 || w.Body.String() != "404 page not found\n" {
+ t.Fatalf("%s %s: %d %s", addr, method, w.Code, w.Body)
+ }
+ }
+ }
+ for _, method := range []string{"PUT", "GET"} {
+ w := managedCall(s, method, "operator@example.com", string(b), "")
+ if w.Code != 200 {
+ t.Fatalf("%s: %d %s", method, w.Code, w.Body)
+ }
+ }
+}
+func TestManagedConfigWriteVisibility(t *testing.T) {
+ s, st, w := managedFixture(t)
+ b, _ := json.Marshal(validManagedConfig())
+ out := managedCall(s, "PUT", "operator@example.com", string(b), "")
+ if out.Code != 200 {
+ t.Fatal(out.Code, out.Body)
+ }
+ old := out.Header().Get("ETag")
+ snap, err := s.managedSnapshot(context.Background())
+ if err != nil || !snap.Config.Enabled {
+ t.Fatalf("local write not visible: %v", err)
+ }
+ c := validManagedConfig()
+ c.Ceiling = 2
+ b, _ = json.Marshal(c)
+ out = managedCall(s, "PUT", "operator@example.com", string(b), old)
+ if out.Code != 200 {
+ t.Fatal(out.Code, out.Body)
+ }
+ out = managedCall(s, "PUT", "operator@example.com", `{"enabled":false}`, old)
+ if out.Code != http.StatusConflict {
+ t.Fatal("stale write", out.Code)
+ }
+ snap, err = s.managedSnapshot(context.Background())
+ if err != nil || snap.Config.Ceiling != 2 {
+ t.Fatalf("stale cache %+v %v", snap, err)
+ }
+ _, etag, _ := st.Get(context.Background(), managedConfigKey)
+ for _, body := range []string{`{"enabled":true,"unknown":1}`, `{"ceiling":-1}`, `{} {}`} {
+ out = managedCall(s, "PUT", "operator@example.com", body, etag)
+ if out.Code != 400 {
+ t.Fatalf("invalid write %d", out.Code)
+ }
+ _, after, _ := st.Get(context.Background(), managedConfigKey)
+ if after != etag {
+ t.Fatal("invalid write persisted")
+ }
+ }
+ w.set(1, false)
+ out = managedCall(s, "PUT", "operator@example.com", string(b), etag)
+ if out.Code != 503 {
+ t.Fatal("enabled without usable index", out.Code)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index d39f66d70..707dc83ea 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -57,3 +57,4 @@ plan14-root-reads-durability-3a-escrow.tsv 03a92257beb9b8aac421559e247d191bd69f2
plan14-root-reads-rootfs-default-home.tsv 7a0a3da3d6fe7e3c77abb22676db000af2a276c3d13ccae0f038190f51287ed5
plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc
plan14-root-reads-managed-fleets-2a-task-1.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc
+plan14-root-reads-managed-fleets-2a-task-3.tsv 43389a9f6ddf3f5f2c23dbfaec9fd0df2f2f3a86efe3147da3d3d30fe4a4dd4e
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-3.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-3.tsv
new file mode 100644
index 000000000..8c8189987
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-2a-task-3.tsv
@@ -0,0 +1,9 @@
+# Census overlay managed-fleets-2a-task-3, written by census-propose (#369). census-ruling-managed-fleets-2a-task-3, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-managed-fleets-2a-task-3.md.
+# 2 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 10e719811eadf88481ced5256007379cf23dc32ac56663af66727e02c1444a36 system_managedfleets.go runSystemManagedFleets legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-3;basis=Explicit operator CLI reads only the --file JSON settings input with os.ReadFile, then sends it to an authenticated configured-system-operator API; not called by a root unit or tenant request. file:ReadFile@813 48305c235d066c1399ebf2e43945b50a15ad16add856ea4b838143048f243ec3
+system.go runSystem authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added;rev3=census-ruling-nearest-region-a;basis=adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops the "join" case (host.RunSystemJoin, deleted with internal/host/joinroot.go, its only caller) and its line in the usage text; every other branch unchanged; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the system verb dispatch gains named-units, routed to host.RunSystemNamedUnits; no read of its own;rev3=census-ruling-managed-fleets-2a-task-3;basis=Adds managed-fleets operator CLI dispatch; no direct read added; existing root command branches unchanged. 5af2561fe77f868240508a14553fbf4b4dcab9f649cde4e0db64bc0d11669d48
+system.go systemVerb authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added;rev3=census-ruling-nearest-region-a;basis=adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added;rev3=census-ruling-region-ha-p1a;basis=explicit operator CLI and root units, uid 0: drops "join" from the verb list, so `carlos system join` now falls to the unknown-verb message; no read added;rev3=census-ruling-named-unit-delivery-114;basis=the known-verb list gains named-units; no read of its own;rev3=census-ruling-managed-fleets-2a-task-3;basis=Recognizes managed-fleets as a CLI family; no read added. d7a5b36d0d73c23520501aa6146e9acf9f8851f50b4b0c248af745a904911755
+system_managedfleets.go runSystemManagedFleets legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2a-task-3;basis=Explicit operator CLI reads only the --file JSON settings input with os.ReadFile, then sends it to an authenticated configured-system-operator API; not called by a root unit or tenant request. file:ReadFile@813 48305c235d066c1399ebf2e43945b50a15ad16add856ea4b838143048f243ec3
+@coverage . 267a1a675490fcdb403f13e745b580986ce5e1f59c59ed891ea1e1cf0a9a20eb
+@coverage internal/release 22068245606a33b085f1bdbc3178d2af079943f793b2eedcc02d32df8b71f269
diff --git a/internal/release/changeindex.go b/internal/release/changeindex.go
index 3088ee007..7a4cf851a 100644
--- a/internal/release/changeindex.go
+++ b/internal/release/changeindex.go
@@ -50,8 +50,12 @@ var dataPrefixes = map[string]bool{
// ChangeScope maps a bucket key to the scope whose generation a write to it
// bumps. The scopes are apps/<a>/<b> (except the data prefixes, and also
// bumped by that app's policy, control/app-policy/<a>/<b>.json), accounts/<a>,
-// control/certs and control/edges; every other key reports ok=false.
+// control/certs, control/edges and the exact system/managed-fleets.json key;
+// every other key reports ok=false.
func ChangeScope(key string) (scope string, ok bool) {
+ if key == "system/managed-fleets.json" {
+ return key, true
+ }
parts := strings.Split(key, "/")
switch parts[0] {
case "apps":
diff --git a/internal/release/changeindex_test.go b/internal/release/changeindex_test.go
index 4d389abb3..ec608193a 100644
--- a/internal/release/changeindex_test.go
+++ b/internal/release/changeindex_test.go
@@ -186,3 +186,13 @@ func mustEtag(t *testing.T, s Store) string {
}
return e
}
+
+func TestSystemManagedChangeScope(t *testing.T) {
+ for _, key := range []string{"system/managed-fleets.json", "system/managed-fleets.json/extra", "system/managed-fleets.jsonx", "system/other.json"} {
+ scope, ok := ChangeScope(key)
+ want := key == "system/managed-fleets.json"
+ if ok != want || (ok && scope != key) {
+ t.Fatalf("%s: %s %v", key, scope, ok)
+ }
+ }
+}
diff --git a/system.go b/system.go
index 5fa5241e0..9423ac8a4 100644
--- a/system.go
+++ b/system.go
@@ -52,7 +52,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) {
// untouched in rest for runSystemAntivirusVerb to read.
// layout is a family too: migrate|revert|status stay in rest for
// runSystemLayout.
- case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help":
+ case "managed-fleets", "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "host-env", "db-worker", "named-units", "help", "-h", "--help":
return args[0], args[1:], component
}
return "", args, component
@@ -61,6 +61,8 @@ func systemVerb(args []string) (verb string, rest []string, component string) {
func runSystem(args []string) {
verb, rest, _ := systemVerb(args)
switch verb {
+ case "managed-fleets":
+ runSystemManagedFleets(rest)
case "files":
host.RunSystemFiles(rest)
case "guard-arm":
@@ -143,6 +145,7 @@ func systemUnknownVerbMessage(args, rest []string) string {
func systemUsage() {
fmt.Fprint(os.Stderr, `usage: carlos system <verb> [flags]
carlos system router <verb> [flags]
+ carlos system managed-fleets <show|set --file f.json>
carlos system antivirus <status|enable|disable|rotate-webhook-key> [flags]
carlos system geoip <publish|status|off> [flags]
carlos system seeds-floor publish --min-release <release>
diff --git a/system_managedfleets.go b/system_managedfleets.go
new file mode 100644
index 000000000..c264f71c8
--- /dev/null
+++ b/system_managedfleets.go
@@ -0,0 +1,89 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+)
+
+const systemManagedPath = "/api/cli/system/managed-fleets"
+
+// COPY: help, errors and display in this file await controller copy review.
+const systemManagedUsage = `usage: carlos system managed-fleets show
+ carlos system managed-fleets set --file f.json
+
+Show or replace managed fleet settings. Requires a configured system operator.
+`
+
+func runSystemManagedFleets(args []string) {
+ if len(args) == 0 {
+ fmt.Fprint(os.Stderr, systemManagedUsage)
+ os.Exit(2)
+ }
+ if args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
+ fmt.Fprint(stdout, systemManagedUsage)
+ return
+ }
+ if args[0] != "show" && args[0] != "set" {
+ log.Fatal(systemManagedUsage)
+ }
+ fs := flag.NewFlagSet("system managed-fleets "+args[0], flag.ExitOnError)
+ console := consoleOption(fs, "console origin (default: the only logged-in one)")
+ file := fs.String("file", "", "JSON settings file (required for set)")
+ fs.Usage = flagUsage(fs, systemManagedUsage)
+ fs.Parse(args[1:])
+ if fs.NArg() != 0 || (args[0] == "set" && *file == "") || (args[0] == "show" && *file != "") {
+ log.Fatal(systemManagedUsage)
+ }
+ var config json.RawMessage
+ if args[0] == "set" {
+ b, err := os.ReadFile(*file)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if !json.Valid(b) {
+ log.Fatal("managed configuration must be valid JSON")
+ }
+ config = b
+ }
+ s := requireDeployAPISession(*console)
+ if err := s.systemManagedFleets(context.Background(), config, stdout); err != nil {
+ log.Fatal(err)
+ }
+}
+func (s *apiSession) systemManagedFleets(ctx context.Context, config json.RawMessage, w io.Writer) error {
+ st, h, b, err := s.sendJSONHeader(ctx, http.MethodGet, systemManagedPath, nil, nil)
+ if err != nil {
+ return err
+ }
+ if st != 200 {
+ return apiErrorFromBody(st, b)
+ }
+ if config != nil {
+ hdr := make(http.Header)
+ hdr.Set("If-Match", h.Get("ETag"))
+ st, _, b, err = s.sendJSONHeader(ctx, http.MethodPut, systemManagedPath, config, hdr)
+ if err != nil {
+ return err
+ }
+ if st == 409 {
+ return errors.New("managed configuration changed; show it again before setting it")
+ }
+ if st != 200 {
+ return apiErrorFromBody(st, b)
+ }
+ }
+ var pretty any
+ if err = json.Unmarshal(b, &pretty); err != nil {
+ return err
+ }
+ enc := json.NewEncoder(w)
+ enc.SetIndent("", " ")
+ return enc.Encode(pretty)
+}
diff --git a/system_managedfleets_test.go b/system_managedfleets_test.go
new file mode 100644
index 000000000..23514014c
--- /dev/null
+++ b/system_managedfleets_test.go
@@ -0,0 +1,64 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestSystemManagedDispatch(t *testing.T) {
+ verb, rest, _ := systemVerb([]string{"managed-fleets", "show"})
+ if verb != "managed-fleets" || len(rest) != 1 || rest[0] != "show" {
+ t.Fatalf("%s %v", verb, rest)
+ }
+}
+
+func TestSystemManagedConditionalWrite(t *testing.T) {
+ for _, conflict := range []bool{false, true} {
+ t.Run(fmt.Sprint(conflict), func(t *testing.T) {
+ calls := 0
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if r.URL.Path != systemManagedPath || r.Header.Get("Authorization") != "Bearer cli-token" {
+ t.Error("incorrect API request")
+ }
+ if r.Method == "GET" {
+ w.Header().Set("ETag", "revision-1")
+ fmt.Fprint(w, `{"enabled":false}`)
+ return
+ }
+ if r.Method != "PUT" || r.Header.Get("If-Match") != "revision-1" {
+ t.Error("missing conditional write")
+ }
+ b, _ := io.ReadAll(r.Body)
+ if string(b) != `{"enabled":true}` {
+ t.Errorf("body %s", b)
+ }
+ if conflict {
+ http.Error(w, "changed", 409)
+ return
+ }
+ fmt.Fprint(w, `{"enabled":true}`)
+ }))
+ defer ts.Close()
+ sess := &apiSession{c: newConsoleClient(ts.URL, "cli-token")}
+ var out bytes.Buffer
+ err := sess.systemManagedFleets(context.Background(), json.RawMessage(`{"enabled":true}`), &out)
+ if calls != 2 || (err != nil) != conflict {
+ t.Fatalf("calls=%d err=%v", calls, err)
+ }
+ if conflict && !strings.Contains(err.Error(), "show it again") {
+ t.Fatal(err)
+ }
+ if !conflict && !strings.Contains(out.String(), `"enabled": true`) {
+ t.Fatal(out.String())
+ }
+ })
+ }
+}