carlos / platform Public

feat: wire managed fleet providers behind an opt-in switch

Managed fleets 2b-2 Task 6. The console constructs the AWS compute and
storage providers only when CARLOS_MANAGED_FLEETS_BACKEND=aws, and refuses
to start when an opted-in setting (including CARLOS_TUNNEL_HOST and
CARLOS_RELEASE_KEY) is missing or invalid. NewServer builds the storage and
router probe bridge from the live server, nil without a hub host.

A box that misses its readiness deadline gets one console-output read in
cleanup; the sanitized breadcrumb codes are kept and show reports the last.
2b-1 carries: a failure before RunInstances is dispatched is a definite
not-launched outcome on the first dispatch (C1), and a proven-absent keep
key records needs-operator with its own reason (C2).

Tests: one box end to end through the real doors to root admission, key
failure status, consumed-but-uncertain publication, diagnostics, budget,
host claim, provider env, adapter recovery over the wire. Census: NewServer
record-write re-pin and the consolidated 2b-2 root-read overlay.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 40582b27323ba29498ecbdb09cf36eb5a81301e0 parent ef10f2f
26 files changed, +1,741 −32
  • apimode_managedfleets.go +3 −0
  • cmd/console/main.go +123 −0
  • cmd/console/managedfleets_test.go +115 −0
  • docs/site/cli.md +28 −0
  • fleets_managed.go +6 −0
  • fleets_managed_test.go +24 −0
  • internal/awsmanaged/clients.go +2 −3
  • internal/awsmanaged/compute.go +13 −3
  • internal/awsmanaged/compute_test.go +14 −2
  • internal/awsmanaged/credentials.go +4 −2
  • internal/awsmanaged/credentials_test.go +31 −2
  • internal/awsmanaged/integration_2b2_test.go +152 −0
  • internal/compute/provisioner.go +5 −0
  • internal/console/managed2b2_linux_test.go +263 −0
  • internal/console/managed2b2_test.go +703 −0
  • internal/console/managed_e2e_test.go +43 −4
  • internal/console/managedbudget_test.go +23 −6
  • internal/console/managedhistory.go +35 −5
  • internal/console/managedstore.go +9 −0
  • internal/console/managedview.go +35 −1
  • internal/console/managedworker.go +79 −0
  • internal/console/server.go +12 −0
  • internal/fleetstore/fake.go +1 −1
  • internal/fleetstore/provisioner.go +9 −1
  • internal/provision/managed_fleets_2b2_census_test.go +8 −1
  • internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv +1 −1
diff --git a/apimode_managedfleets.go b/apimode_managedfleets.go
index f698747d4..966474e16 100644
--- a/apimode_managedfleets.go
+++ b/apimode_managedfleets.go
@@ -22,6 +22,9 @@ type apiFleetShowBox struct {
Version string `json:"version"`
LastError string `json:"last_error"`
Checks map[string]apiManagedCheck `json:"checks"`
+ // Boot is the console's sentence for how far a box that missed its
+ // readiness deadline got. Absent otherwise.
+ Boot string `json:"boot,omitempty"`
}
type apiFleetShowPlan struct {
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 111f1f64f..7abce10dd 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -136,6 +136,7 @@ import (
"os"
"os/signal"
"path/filepath"
+ "regexp"
"sort"
"strconv"
"strings"
@@ -146,10 +147,13 @@ import (
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/alerting"
"github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/awsmanaged"
+ "github.com/carlosframework/platform/internal/compute"
"github.com/carlosframework/platform/internal/console"
"github.com/carlosframework/platform/internal/demo"
"github.com/carlosframework/platform/internal/dnsrec"
"github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/fleetstore"
"github.com/carlosframework/platform/internal/geo"
"github.com/carlosframework/platform/internal/geoip"
"github.com/carlosframework/platform/internal/lease"
@@ -638,6 +642,13 @@ func serve() {
cfg.WakeRetryReset = console.NewProductionWakeRetryReset()
}
cfg.Perf = rec
+ // Managed fleets' cloud providers (2b-2 Task 6), only on an explicit
+ // opt-in. Unset leaves both nil and admission answers 503; opted in but
+ // incomplete stops the console here, as the app-store backend does.
+ // system/managed-fleets.json "enabled" stays the admission switch.
+ if cfg.ManagedCompute, cfg.ManagedStorage, cfg.ManagedDeployment, err = managedProvidersFromEnv(context.Background(), os.Getenv); err != nil {
+ log.Fatalf("console: %v", err)
+ }
cfg.HADataStores = buildHADataStores(context.Background(), cfg, rec, release.NewS3StoreIn)
srv, err := console.NewServer(cfg, st)
if err != nil {
@@ -1081,6 +1092,118 @@ func storeBackend(rec *perf.Recorder) (objstore.Provisioner, objstore.Deployment
return p, objstore.Deployment{Backend: backend, Region: region, Endpoint: endpoint, BucketPrefix: prefix}
}
+// Managed fleet provider settings. The backend is the opt-in; every other
+// variable is required once it is set.
+var (
+ managedAccountRE = regexp.MustCompile(`^[0-9]{12}$`)
+ managedRegionRE = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]{1,2}$`)
+ managedTagRE = regexp.MustCompile(`^[A-Za-z0-9._:/=+@-]{1,256}$`)
+ managedPrefixRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,23}$`)
+ managedPathRE = regexp.MustCompile(`^/(?:[A-Za-z0-9+=,.@_-]+/)+$`)
+ managedPolicyRE = regexp.MustCompile(`^arn:aws:iam::([0-9]{12}):policy/(?:[A-Za-z0-9+=,.@_-]+/)*[A-Za-z0-9+=,.@_-]{1,128}$`)
+)
+
+// managedProvidersFromEnv builds the managed fleet compute and storage
+// providers and names the deployment they own. CARLOS_MANAGED_FLEETS_BACKEND
+// unset is nil, nil, "" with no error: managed fleets stay off and admission
+// answers 503. "aws" requires every CARLOS_MANAGED_FLEET_* variable, a hub
+// host (CARLOS_TUNNEL_HOST: boxes freeze it and probes go through it) and
+// CARLOS_RELEASE_KEY (the key that signs each box's ready record); any
+// missing or invalid one is an error naming it. Any other backend is an
+// error: a fake is never substituted. No network call is made here.
+func managedProvidersFromEnv(ctx context.Context, getenv func(string) string) (compute.Provisioner, fleetstore.Provisioner, string, error) {
+ get := func(k string) string { return strings.TrimSpace(getenv(k)) }
+ backend := get("CARLOS_MANAGED_FLEETS_BACKEND")
+ if backend == "" {
+ return nil, nil, "", nil
+ }
+ // COPY: every error below is shown to the operator at console start.
+ if backend != "aws" {
+ return nil, nil, "", fmt.Errorf("CARLOS_MANAGED_FLEETS_BACKEND %q is not a backend this build knows. the only value is \"aws\" (leave it unset to keep managed fleets off)", backend) // COPY
+ }
+ need := func(k, what string) (string, error) {
+ v := get(k)
+ if v == "" {
+ return "", fmt.Errorf("CARLOS_MANAGED_FLEETS_BACKEND is set. also set %s (%s)", k, what) // COPY
+ }
+ return v, nil
+ }
+ deployment, err := need("CARLOS_MANAGED_FLEET_DEPLOYMENT", "the deployment name every managed box is tagged with, such as dev") // COPY
+ if err != nil {
+ return nil, nil, "", err
+ }
+ if !managedTagRE.MatchString(deployment) {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEET_DEPLOYMENT must be letters, digits and . _ : / = + @ - only") // COPY
+ }
+ account, err := need("CARLOS_MANAGED_FLEET_ACCOUNT_ID", "the 12-digit AWS account managed boxes run in") // COPY
+ if err != nil {
+ return nil, nil, "", err
+ }
+ if !managedAccountRE.MatchString(account) {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEET_ACCOUNT_ID must be a 12-digit AWS account ID") // COPY
+ }
+ rawRegions, err := need("CARLOS_MANAGED_FLEET_REGIONS", "the AWS regions managed boxes may run in, comma-separated, such as eu-west-1") // COPY
+ if err != nil {
+ return nil, nil, "", err
+ }
+ var regions []string
+ seen := map[string]bool{}
+ for _, r := range strings.Split(rawRegions, ",") {
+ r = strings.TrimSpace(r)
+ if !managedRegionRE.MatchString(r) || seen[r] {
+ return nil, nil, "", fmt.Errorf("CARLOS_MANAGED_FLEET_REGIONS must list distinct AWS region names, such as eu-west-1; %q is not one", r) // COPY
+ }
+ seen[r] = true
+ regions = append(regions, r)
+ }
+ iamRegion, err := need("CARLOS_MANAGED_FLEET_IAM_REGION", "the region the console calls IAM through, such as us-east-1") // COPY
+ if err != nil {
+ return nil, nil, "", err
+ }
+ if !managedRegionRE.MatchString(iamRegion) {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEET_IAM_REGION must be an AWS region name, such as us-east-1") // COPY
+ }
+ prefix, err := need("CARLOS_MANAGED_FLEET_BUCKET_PREFIX", "the start of every fleet bucket name; the infrastructure module outputs it as managed_fleet_bucket_prefix") // COPY
+ if err != nil {
+ return nil, nil, "", err
+ }
+ if !managedPrefixRE.MatchString(prefix) {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEET_BUCKET_PREFIX must be up to 24 lowercase letters, digits or hyphens, starting with a letter or digit") // COPY
+ }
+ userPath, err := need("CARLOS_MANAGED_FLEET_USER_PATH", "the IAM path fleet users are created under; the infrastructure module outputs it as managed_fleet_user_path") // COPY
+ if err != nil {
+ return nil, nil, "", err
+ }
+ if !managedPathRE.MatchString(userPath) {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEET_USER_PATH must be an IAM path below the root, such as /carlos-managed-fleet/") // COPY
+ }
+ if strings.HasPrefix(userPath, "/carlos-store/") || strings.HasPrefix("/carlos-store/", userPath) {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEET_USER_PATH must not overlap the object storage user path /carlos-store/") // COPY
+ }
+ boundary, err := need("CARLOS_MANAGED_FLEET_BOUNDARY", "the permissions boundary fleet users are created under; the infrastructure module outputs it as managed_fleet_user_boundary_arn") // COPY
+ if err != nil {
+ return nil, nil, "", err
+ }
+ if m := managedPolicyRE.FindStringSubmatch(boundary); m == nil || m[1] != account {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEET_BOUNDARY must be an IAM policy ARN in the account CARLOS_MANAGED_FLEET_ACCOUNT_ID names") // COPY
+ }
+ if get("CARLOS_TUNNEL_HOST") == "" {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEETS_BACKEND is set. also set CARLOS_TUNNEL_HOST: managed boxes connect to the fleet hub there, and the console checks them through it") // COPY
+ }
+ if get("CARLOS_RELEASE_KEY") == "" {
+ return nil, nil, "", errors.New("CARLOS_MANAGED_FLEETS_BACKEND is set. also set CARLOS_RELEASE_KEY: the console signs each managed box's ready record with it") // COPY
+ }
+ c, err := awsmanaged.NewCompute(ctx, awsmanaged.ComputeConfig{Deployment: deployment, AccountID: account, Regions: regions})
+ if err != nil {
+ return nil, nil, "", fmt.Errorf("managed fleets: %w", err)
+ }
+ st, err := awsmanaged.NewStorage(ctx, awsmanaged.StorageConfig{Deployment: deployment, AccountID: account, IAMRegion: iamRegion, BucketPrefix: prefix, UserPath: userPath, BoundaryARN: boundary, Regions: regions})
+ if err != nil {
+ return nil, nil, "", fmt.Errorf("managed fleets: %w", err)
+ }
+ return c, st, deployment, nil
+}
+
// storeOperators parses CARLOS_STORE_OPERATORS (comma-separated addresses) —
// who may drive the GRANT door for an app's store, and only that one door;
// rotate is the member's own verb and destroy is the account owner's browser
diff --git a/cmd/console/managedfleets_test.go b/cmd/console/managedfleets_test.go
new file mode 100644
index 000000000..a7d42fc21
--- /dev/null
+++ b/cmd/console/managedfleets_test.go
@@ -0,0 +1,115 @@
+package main
+
+import (
+ "context"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/awsmanaged"
+)
+
+// TestManagedProvidersFromEnv: managed fleet providers exist only on an
+// explicit opt-in. Opted in, every missing or invalid setting is an error
+// naming its variable (the console stops, as the app-store backend does);
+// a backend other than aws is refused and never replaced by a fake.
+func TestManagedProvidersFromEnv(t *testing.T) {
+ // The SDK loads with dummy credentials, no shared files and no metadata
+ // service: nothing here may reach AWS.
+ dir := t.TempDir()
+ t.Setenv("AWS_ACCESS_KEY_ID", "AKIDEXAMPLE")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "example-secret")
+ t.Setenv("AWS_SESSION_TOKEN", "")
+ t.Setenv("AWS_PROFILE", "")
+ t.Setenv("AWS_DEFAULT_PROFILE", "")
+ t.Setenv("AWS_CONFIG_FILE", filepath.Join(dir, "none"))
+ t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(dir, "none"))
+ t.Setenv("AWS_EC2_METADATA_DISABLED", "true")
+ valid := map[string]string{
+ "CARLOS_MANAGED_FLEETS_BACKEND": "aws",
+ "CARLOS_MANAGED_FLEET_DEPLOYMENT": "dev",
+ "CARLOS_MANAGED_FLEET_ACCOUNT_ID": "123456789012",
+ "CARLOS_MANAGED_FLEET_REGIONS": "eu-west-1, us-east-1",
+ "CARLOS_MANAGED_FLEET_IAM_REGION": "us-east-1",
+ "CARLOS_MANAGED_FLEET_BUCKET_PREFIX": "carlos-dev-fleet-",
+ "CARLOS_MANAGED_FLEET_USER_PATH": "/carlos-managed-fleet/",
+ "CARLOS_MANAGED_FLEET_BOUNDARY": "arn:aws:iam::123456789012:policy/carlos-managed-fleet-boundary",
+ "CARLOS_TUNNEL_HOST": "tunnel.example.com",
+ "CARLOS_RELEASE_KEY": "set",
+ }
+ env := func(edit map[string]string) func(string) string {
+ m := map[string]string{}
+ for k, v := range valid {
+ m[k] = v
+ }
+ for k, v := range edit {
+ m[k] = v
+ }
+ return func(k string) string { return m[k] }
+ }
+ ctx := context.Background()
+
+ t.Run("off", func(t *testing.T) {
+ c, s, dep, err := managedProvidersFromEnv(ctx, env(map[string]string{"CARLOS_MANAGED_FLEETS_BACKEND": ""}))
+ if c != nil || s != nil || dep != "" || err != nil {
+ t.Fatalf("unset backend: %v %v %q %v", c, s, dep, err)
+ }
+ c, s, dep, err = managedProvidersFromEnv(ctx, func(string) string { return "" })
+ if c != nil || s != nil || dep != "" || err != nil {
+ t.Fatalf("empty environment: %v %v %q %v", c, s, dep, err)
+ }
+ })
+ t.Run("valid", func(t *testing.T) {
+ c, s, dep, err := managedProvidersFromEnv(ctx, env(nil))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := c.(*awsmanaged.Compute); !ok {
+ t.Fatalf("compute %T", c)
+ }
+ if _, ok := s.(*awsmanaged.Storage); !ok {
+ t.Fatalf("storage %T", s)
+ }
+ if dep != "dev" {
+ t.Fatalf("deployment %q", dep)
+ }
+ })
+ for _, c := range []struct {
+ name, key, value string
+ }{
+ {"fake backend", "CARLOS_MANAGED_FLEETS_BACKEND", "fake"},
+ {"other backend", "CARLOS_MANAGED_FLEETS_BACKEND", "gcp"},
+ {"no deployment", "CARLOS_MANAGED_FLEET_DEPLOYMENT", ""},
+ {"bad deployment", "CARLOS_MANAGED_FLEET_DEPLOYMENT", "dev box"},
+ {"no account", "CARLOS_MANAGED_FLEET_ACCOUNT_ID", ""},
+ {"short account", "CARLOS_MANAGED_FLEET_ACCOUNT_ID", "12345678901"},
+ {"lettered account", "CARLOS_MANAGED_FLEET_ACCOUNT_ID", "12345678901a"},
+ {"no regions", "CARLOS_MANAGED_FLEET_REGIONS", ""},
+ {"region not a region", "CARLOS_MANAGED_FLEET_REGIONS", "eu-west-1,europe"},
+ {"region twice", "CARLOS_MANAGED_FLEET_REGIONS", "eu-west-1,eu-west-1"},
+ {"empty region in list", "CARLOS_MANAGED_FLEET_REGIONS", "eu-west-1,"},
+ {"no iam region", "CARLOS_MANAGED_FLEET_IAM_REGION", ""},
+ {"bad iam region", "CARLOS_MANAGED_FLEET_IAM_REGION", "global"},
+ {"no prefix", "CARLOS_MANAGED_FLEET_BUCKET_PREFIX", ""},
+ {"upper prefix", "CARLOS_MANAGED_FLEET_BUCKET_PREFIX", "Carlos-"},
+ {"no user path", "CARLOS_MANAGED_FLEET_USER_PATH", ""},
+ {"root user path", "CARLOS_MANAGED_FLEET_USER_PATH", "/"},
+ {"store user path", "CARLOS_MANAGED_FLEET_USER_PATH", "/carlos-store/"},
+ {"store parent path", "CARLOS_MANAGED_FLEET_USER_PATH", "/carlos-store/fleets/"},
+ {"no boundary", "CARLOS_MANAGED_FLEET_BOUNDARY", ""},
+ {"boundary in another account", "CARLOS_MANAGED_FLEET_BOUNDARY", "arn:aws:iam::210987654321:policy/carlos-managed-fleet-boundary"},
+ {"boundary not a policy", "CARLOS_MANAGED_FLEET_BOUNDARY", "arn:aws:iam::123456789012:role/carlos"},
+ {"no hub host", "CARLOS_TUNNEL_HOST", ""},
+ {"no release key", "CARLOS_RELEASE_KEY", ""},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ p, s, dep, err := managedProvidersFromEnv(ctx, env(map[string]string{c.key: c.value}))
+ if err == nil || p != nil || s != nil || dep != "" {
+ t.Fatalf("accepted: %v %v %q %v", p, s, dep, err)
+ }
+ if !strings.Contains(err.Error(), c.key) {
+ t.Fatalf("error does not name %s: %v", c.key, err)
+ }
+ })
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 421f56a9b..c7a896144 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2847,6 +2847,34 @@ provider-neutral core; real managed launches remain off until the approved
provider drill. Disabling admission leaves existing reservations and cleanup
intact.
+<!-- COPY: managed fleet provider settings await controller copy review. -->
+#### Managed fleet providers on the console
+
+Managed fleets are off by default. The console starts no cloud provider for
+them unless its environment sets `CARLOS_MANAGED_FLEETS_BACKEND=aws`. With
+that set, the console also needs all of these, and refuses to start if any is
+missing or invalid:
+
+- `CARLOS_MANAGED_FLEET_DEPLOYMENT`: the deployment name every managed box is tagged with
+- `CARLOS_MANAGED_FLEET_ACCOUNT_ID`: the 12-digit AWS account managed boxes run in
+- `CARLOS_MANAGED_FLEET_REGIONS`: the regions boxes may run in, comma-separated
+- `CARLOS_MANAGED_FLEET_IAM_REGION`: the region the console calls IAM through
+- `CARLOS_MANAGED_FLEET_BUCKET_PREFIX`, `CARLOS_MANAGED_FLEET_USER_PATH` and
+ `CARLOS_MANAGED_FLEET_BOUNDARY`: the infrastructure module's
+ `managed_fleet_bucket_prefix`, `managed_fleet_user_path` and
+ `managed_fleet_user_boundary_arn` outputs
+- `CARLOS_TUNNEL_HOST` and `CARLOS_RELEASE_KEY`: boxes connect to the fleet hub,
+ and the console signs each box's ready record with the release key
+
+The providers only make launches possible. `enabled` in the settings above
+still decides whether the console accepts managed fleet requests.
+
+Every access key the console delivers to a box stays recorded. Deleting an
+earlier box's key in IAM removes that box's bucket access. If the key the
+fleet's boxes use now is deleted, `carlos fleets show` reports the fleet as
+`needs-operator` and no boxes can be added; giving the fleet a new key is not
+available yet.
+
#### The platform's own binary
`update` promotes a public release (or, with `--file`, a binary you built) to
diff --git a/fleets_managed.go b/fleets_managed.go
index 8bb18f04e..36e31491e 100644
--- a/fleets_managed.go
+++ b/fleets_managed.go
@@ -41,6 +41,7 @@ func runFleetsShow(args []string) {
// COPY: the credential state lines await controller copy review.
const msgFleetNeedsOperator = "Credentials: needs-operator. an access key delivered to an earlier box, other than the key boxes use now, is still live. an operator must delete that key in IAM before boxes can be added"
+const msgFleetKeyMissing = "Credentials: needs-operator. the access key this fleet's boxes use no longer exists in IAM. boxes cannot be added until the fleet is given a new key, which the console cannot do yet" // COPY
func printFleetShow(w io.Writer, out apiFleetShowReply) {
fmt.Fprintln(w, out.Name)
@@ -48,6 +49,8 @@ func printFleetShow(w io.Writer, out apiFleetShowReply) {
switch {
case out.CredentialState == "needs-operator" && out.CredentialReason == "delivered_key_other_than_keep_still_live":
fmt.Fprintln(w, msgFleetNeedsOperator)
+ case out.CredentialState == "needs-operator" && out.CredentialReason == "fleet_access_key_missing":
+ fmt.Fprintln(w, msgFleetKeyMissing)
case out.CredentialState != "":
fmt.Fprintf(w, "Credentials: %s %s\n", out.CredentialState, out.CredentialReason) // COPY
}
@@ -79,6 +82,9 @@ func printFleetShow(w io.Writer, out apiFleetShowReply) {
check := b.Checks[key]
fmt.Fprintf(w, " %s %s: %s %s\n", b.Label, key, check.State, check.Reason)
}
+ if b.Boot != "" {
+ fmt.Fprintf(w, " %s boot: %s\n", b.Label, b.Boot) // COPY
+ }
}
}
diff --git a/fleets_managed_test.go b/fleets_managed_test.go
index 49f0f72e0..e75cfbb12 100644
--- a/fleets_managed_test.go
+++ b/fleets_managed_test.go
@@ -227,3 +227,27 @@ func TestFleetsShowCredentialState(t *testing.T) {
t.Fatalf("normal fleet render changed:\n%q\nwant\n%q", got, want)
}
}
+
+// TestFleetsShowBootAndKeyMissing: the console's boot sentence for a box
+// that missed its readiness deadline is printed under the box, and a fleet
+// whose current access key is gone prints its own needs-operator line.
+func TestFleetsShowBootAndKeyMissing(t *testing.T) {
+ reply := `{"name":"production","managed":true,"boxes":[{"label":"box-1","state":"terminating","version":"","last_error":"managed_readiness_timeout","checks":{"storage":{"state":"fail","reason":"key"}},"boot":"the box could not enrol with the console"}],"credential_state":"needs-operator","credential_reason":"fleet_access_key_missing"}`
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, reply) }))
+ defer ts.Close()
+ out, err := newTestSession(ts.URL).showFleet(context.Background(), apiAcct{Seg: "chosen"}, "production")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var buf bytes.Buffer
+ printFleetShow(&buf, out)
+ got := buf.String()
+ for _, want := range []string{"production\n" + msgFleetKeyMissing + "\n", " box-1 storage: fail key\n box-1 boot: the box could not enrol with the console\n"} {
+ if !strings.Contains(got, want) {
+ t.Fatalf("missing %q in:\n%s", want, got)
+ }
+ }
+ if strings.Contains(got, msgFleetNeedsOperator) {
+ t.Fatal("the delivered-key line for a missing key")
+ }
+}
diff --git a/internal/awsmanaged/clients.go b/internal/awsmanaged/clients.go
index 130f83e1e..0e78acae2 100644
--- a/internal/awsmanaged/clients.go
+++ b/internal/awsmanaged/clients.go
@@ -1,9 +1,8 @@
// Package awsmanaged holds the AWS adapters behind the provider-neutral
// managed-fleet contracts (internal/compute and internal/fleetstore). It is
// the only managed fleet code that imports the AWS SDK, and it loads
-// credentials only through
-// internal/rootaws. Nothing in production constructs it yet: 2b-2 wires it
-// once the frozen cloud-init replaces today's JSON launch payload.
+// credentials only through internal/rootaws. The console constructs it only
+// when its operator opts in (CARLOS_MANAGED_FLEETS_BACKEND=aws).
package awsmanaged
import (
diff --git a/internal/awsmanaged/compute.go b/internal/awsmanaged/compute.go
index 7db12a96c..655a4e1bf 100644
--- a/internal/awsmanaged/compute.go
+++ b/internal/awsmanaged/compute.go
@@ -167,6 +167,15 @@ func uncertain(ctx context.Context, what string) error {
return fmt.Errorf("awsmanaged: %s: %w", what, errAmbiguous)
}
+// notSent marks a failure that provably precedes the RunInstances dispatch:
+// this call launched nothing, whatever the failed read would have said.
+func notSent(ctx context.Context, what string) error {
+ if err := ctx.Err(); err != nil {
+ return fmt.Errorf("awsmanaged: %s: %w: %w", what, compute.ErrLaunchNotSent, err)
+ }
+ return fmt.Errorf("awsmanaged: %s: %w", what, compute.ErrLaunchNotSent)
+}
+
func rejected(reason string) error {
return fmt.Errorf("awsmanaged: %w: %s", compute.ErrLaunchRejected, reason)
}
@@ -281,7 +290,8 @@ func (c *Compute) validateLaunch(s compute.LaunchSpec) (ec2API, error) {
// rootDevice describes the exact image and returns its root device name. It
// refuses anything but an available arm64 EBS image with one root mapping no
-// larger than the requested disk.
+// larger than the requested disk. It runs before RunInstances is sent, so a
+// failed or unreadable answer is compute.ErrLaunchNotSent, never ambiguity.
func rootDevice(ctx context.Context, api ec2API, s compute.LaunchSpec) (string, error) {
out, err := api.DescribeImages(ctx, &ec2.DescribeImagesInput{ImageIds: []string{s.Image}}, inRegion(s.Region))
if err != nil {
@@ -289,10 +299,10 @@ func rootDevice(ctx context.Context, api ec2API, s compute.LaunchSpec) (string,
case "InvalidAMIID.NotFound", "InvalidAMIID.Malformed", "InvalidAMIID.Unavailable":
return "", rejected("image is not available")
}
- return "", uncertain(ctx, "describe image")
+ return "", notSent(ctx, "describe image")
}
if out == nil || aws.ToString(out.NextToken) != "" || len(out.Images) != 1 || aws.ToString(out.Images[0].ImageId) != s.Image {
- return "", uncertain(ctx, "describe image answer")
+ return "", notSent(ctx, "describe image answer")
}
img := out.Images[0]
if img.Architecture != types.ArchitectureValuesArm64 || img.State != types.ImageStateAvailable || img.RootDeviceType != types.DeviceTypeEbs {
diff --git a/internal/awsmanaged/compute_test.go b/internal/awsmanaged/compute_test.go
index 10c26cd59..83759fe33 100644
--- a/internal/awsmanaged/compute_test.go
+++ b/internal/awsmanaged/compute_test.go
@@ -379,7 +379,17 @@ func ambiguous(t *testing.T, err error) {
if err == nil {
t.Fatal("accepted an unproven answer")
}
- if !errors.Is(err, errAmbiguous) || errors.Is(err, os.ErrNotExist) || errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, compute.ErrLaunchConflict) {
+ if !errors.Is(err, errAmbiguous) || errors.Is(err, os.ErrNotExist) || errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, compute.ErrLaunchConflict) || errors.Is(err, compute.ErrLaunchNotSent) {
+ t.Fatalf("misclassified: %v", err)
+ }
+ noLeak(t, err.Error())
+}
+
+// notSentErr is a failure before RunInstances was dispatched (2b-1 carry
+// C1): a definite not-launched outcome, never ambiguity or a rejection.
+func notSentErr(t *testing.T, err error) {
+ t.Helper()
+ if !errors.Is(err, compute.ErrLaunchNotSent) || errors.Is(err, errAmbiguous) || errors.Is(err, os.ErrNotExist) || errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, compute.ErrLaunchConflict) {
t.Fatalf("misclassified: %v", err)
}
noLeak(t, err.Error())
@@ -551,6 +561,8 @@ func TestAWSComputeLaunchRefusals(t *testing.T) {
for name, set := range map[string]func(*fakeEC2){
"image lookup throttled": func(f *fakeEC2) { f.imagesErr = apiErr("RequestLimitExceeded") },
"image lookup denied": func(f *fakeEC2) { f.imagesErr = apiErr("UnauthorizedOperation") },
+ "image lookup timeout": func(f *fakeEC2) { f.imagesErr = context.DeadlineExceeded },
+ "image lookup internal": func(f *fakeEC2) { f.imagesErr = apiErr("InternalError") },
"image list empty": func(f *fakeEC2) { f.imagesOutput = &ec2.DescribeImagesOutput{} },
"image list paged": func(f *fakeEC2) {
f.imagesOutput = &ec2.DescribeImagesOutput{Images: []types.Image{testImageFixture()}, NextToken: aws.String("more")}
@@ -565,7 +577,7 @@ func TestAWSComputeLaunchRefusals(t *testing.T) {
f := newFakeEC2(t, testRegion)
set(f)
_, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
- ambiguous(t, err)
+ notSentErr(t, err)
if f.callCount("RunInstances") != 0 {
t.Fatal("launched without a verified image")
}
diff --git a/internal/awsmanaged/credentials.go b/internal/awsmanaged/credentials.go
index ed3d5fb61..e4b58e287 100644
--- a/internal/awsmanaged/credentials.go
+++ b/internal/awsmanaged/credentials.go
@@ -251,7 +251,8 @@ func (s *Storage) FleetCredentials(ctx context.Context, fleet string) (fleetstor
// Under the fleet lock it verifies the user and reads the complete key
// inventory first. If any delivered key other than keep still exists, in
// any state, it returns fleetstore.ErrDeliveredKeyStillLive and changes
-// nothing. A nonempty keep must exist and be active. Deletions are
+// nothing. A nonempty keep must exist (else fleetstore.ErrKeepKeyMissing)
+// and be active. Deletions are
// confirmed by a second complete listing before the one CreateAccessKey,
// which is sent exactly once: a lost answer leaves an undelivered key the
// next rotation reaps. The secret is returned only from that mint.
@@ -294,7 +295,8 @@ func (s *Storage) RotateFleetCredentials(ctx context.Context, fleet, keep string
if keep != "" {
i := slices.IndexFunc(keys, func(k accessKey) bool { return k.id == keep })
if i < 0 {
- return fleetstore.Credentials{}, drift("key to keep does not exist")
+ // The listing is complete and succeeded: absence is proven.
+ return fleetstore.Credentials{}, fmt.Errorf("awsmanaged: %w", fleetstore.ErrKeepKeyMissing)
}
if !keys[i].active {
return fleetstore.Credentials{}, drift("key to keep is not active")
diff --git a/internal/awsmanaged/credentials_test.go b/internal/awsmanaged/credentials_test.go
index 4c103ccc3..ea1900215 100644
--- a/internal/awsmanaged/credentials_test.go
+++ b/internal/awsmanaged/credentials_test.go
@@ -447,14 +447,43 @@ func TestAWSFleetCredentialsDoubleLostRotation(t *testing.T) {
t.Run("missing keep changes nothing", func(t *testing.T) {
s, user := preparedStorage(t)
orphan := s.iam.addKey(user, iamtypes.StatusTypeActive)
- if _, err := s.RotateFleetCredentials(ctx, testFleet, "AKIA9999999999999999", []string{"AKIA9999999999999999"}); err == nil {
- t.Fatal("rotated without the key to keep")
+ _, err := s.RotateFleetCredentials(ctx, testFleet, "AKIA9999999999999999", []string{"AKIA9999999999999999"})
+ // A complete listing proves the keep key absent (2b-1 carry C2): the
+ // console turns exactly this sentinel into needs-operator.
+ if !errors.Is(err, fleetstore.ErrKeepKeyMissing) || errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) {
+ t.Fatalf("missing keep: %v", err)
}
+ noLeak(t, err.Error())
if s.iam.keyMutations() != 0 {
t.Fatal("reaped or minted without the key to keep")
}
sameKeys(t, s.iam.liveKeys(user), orphan)
})
+ t.Run("missing keep on a partial listing is not proven absent", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ s.iam.addKey(user, iamtypes.StatusTypeActive)
+ s.iam.addKey(user, iamtypes.StatusTypeActive)
+ s.iam.before = func(op string, n int) error {
+ if op == "ListAccessKeys" && n == 2 {
+ return apiErr("Throttling")
+ }
+ return nil
+ }
+ _, err := s.RotateFleetCredentials(ctx, testFleet, "AKIA9999999999999999", []string{"AKIA9999999999999999"})
+ if err == nil || errors.Is(err, fleetstore.ErrKeepKeyMissing) {
+ t.Fatalf("partial listing proved absence: %v", err)
+ }
+ if s.iam.keyMutations() != 0 {
+ t.Fatal("mutated keys on a partial inventory")
+ }
+ })
+ t.Run("inactive keep is not missing", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ keep := s.iam.addKey(user, iamtypes.StatusTypeInactive)
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, keep, []string{keep}); err == nil || errors.Is(err, fleetstore.ErrKeepKeyMissing) {
+ t.Fatalf("inactive keep: %v", err)
+ }
+ })
t.Run("second delivered key still live", func(t *testing.T) {
s, user := preparedStorage(t)
k1 := rotate(t, s, "").ID
diff --git a/internal/awsmanaged/integration_2b2_test.go b/internal/awsmanaged/integration_2b2_test.go
new file mode 100644
index 000000000..86a5fa07d
--- /dev/null
+++ b/internal/awsmanaged/integration_2b2_test.go
@@ -0,0 +1,152 @@
+package awsmanaged_test
+
+// The 2b-2 composition through the real constructors and the wire-level
+// stand-in: rendered cloud-init user data across a lost launch reply and a
+// restarted console, a pre-dispatch failure, one storage preparation, one
+// delivered key, and a keep key deleted outside the console.
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "net/url"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/compute"
+ "github.com/carlosframework/platform/internal/fleetstore"
+ "github.com/carlosframework/platform/internal/managedboot"
+)
+
+// itRenderedSpec is itSpec carrying the real frozen cloud-init script.
+func itRenderedSpec(t *testing.T) compute.LaunchSpec {
+ t.Helper()
+ id := itIdentity()
+ in := managedboot.LaunchInput{
+ Frozen: managedboot.Frozen{Format: managedboot.FormatV1, ConsoleOrigin: "https://console.example.com", TunnelHost: "tunnel.example.com",
+ ReleasePubkey: base64.StdEncoding.EncodeToString(make([]byte, 32)), SeedVersion: "v0.34.0",
+ SeedKey: "bootstrap/router/v0.34.0/carlos-" + managedboot.SeedArtifactPlatform, SeedSHA256: strings.Repeat("a", 64)},
+ Fleet: id.Fleet, Label: id.Label, Op: id.Operation, Token: strings.Repeat("e", 64),
+ Expires: time.Date(2026, 11, 9, 13, 0, 0, 0, time.UTC),
+ }
+ data, err := managedboot.RenderUserData(in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ spec := itSpec()
+ spec.UserData = data
+ return spec
+}
+
+func TestAWSManaged2B2Recovery(t *testing.T) {
+ t.Run("compute", func(t *testing.T) {
+ itEnv(t)
+ w := newAWSWorld(t)
+ ctx := context.Background()
+ spec := itRenderedSpec(t)
+
+ // 2b-1 carry C1: a failed image read precedes the launch request,
+ // so it is a definite not-sent outcome with nothing dispatched.
+ for _, f := range []itFault{{503, "Unavailable"}, {500, "InternalError"}, {403, "UnauthorizedOperation"}} {
+ w.fail["DescribeImages"] = f
+ before, calls := w.snapshot()
+ _, err := newITCompute(t, w).Launch(ctx, spec)
+ if !errors.Is(err, compute.ErrLaunchNotSent) || errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, compute.ErrLaunchConflict) {
+ t.Fatalf("image read %d %s: %v", f.status, f.code, err)
+ }
+ if after, now := w.snapshot(); after != before || now["RunInstances"] != calls["RunInstances"] || len(w.instances) != 0 {
+ t.Fatalf("image read %d: dispatched (%d mutations, %d launches)", f.status, after-before, now["RunInstances"])
+ }
+ }
+ delete(w.fail, "DescribeImages")
+
+ // The reply to the first dispatch is lost after EC2 acted on it.
+ w.lose["RunInstances"] = true
+ _, err := newITCompute(t, w).Launch(ctx, spec)
+ itAmbiguous(t, err)
+ if errors.Is(err, compute.ErrLaunchNotSent) {
+ t.Fatal("a dispatched launch classed as not sent")
+ }
+ w.lose["RunInstances"] = false
+ if len(w.instances) != 1 {
+ t.Fatalf("fixture: %d instances", len(w.instances))
+ }
+ original := w.instances[0].id
+
+ // A restarted console finds it by identity, then re-sends the frozen
+ // request: the same bytes, user data included, and the same instance.
+ found, err := newITCompute(t, w).Find(ctx, itRegion, itIdentity())
+ if err != nil || len(found) != 1 || found[0].CloudID != original {
+ t.Fatalf("discovery: %+v %v", found, err)
+ }
+ again, err := newITCompute(t, w).Launch(ctx, spec)
+ if err != nil || again.CloudID != original || len(w.instances) != 1 {
+ t.Fatalf("frozen relaunch: %+v %v", again, err)
+ }
+ if len(w.runForms) != 2 || w.runForms[0] != w.runForms[1] {
+ t.Fatal("the frozen request changed across reconstruction")
+ }
+ form, err := url.ParseQuery(w.runForms[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ wire, err := base64.StdEncoding.DecodeString(form.Get("UserData"))
+ if err != nil || string(wire) != spec.UserData {
+ t.Fatalf("user data on the wire differs from the rendered script (%v)", err)
+ }
+ })
+
+ t.Run("storage", func(t *testing.T) {
+ itEnv(t)
+ w := newAWSWorld(t)
+ ctx := context.Background()
+ got, err := newITStorage(t, w).EnsureFleetStorage(ctx, itFleet, itRegion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, _ := w.snapshot()
+ if again, err := newITStorage(t, w).EnsureFleetStorage(ctx, itFleet, itRegion); err != nil || again != got {
+ t.Fatalf("second preparation: %+v %v", again, err)
+ }
+ if after, calls := w.snapshot(); after != before || calls["PUT "] != 1 {
+ t.Fatalf("storage prepared again: %d mutations, %d creates", after-before, calls["PUT "])
+ }
+
+ // One delivery: the first box's key is minted once.
+ k1, err := newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, "", nil)
+ if err != nil || k1.ID == "" {
+ t.Fatal(err)
+ }
+ if _, calls := w.snapshot(); calls["CreateAccessKey"] != 1 {
+ t.Fatalf("mints: %d", calls["CreateAccessKey"])
+ }
+ named, err := newITStorage(t, w).FleetCredentials(ctx, itFleet)
+ if err != nil || named.ID != k1.ID || len(named.Secret) != 0 {
+ t.Fatalf("FleetCredentials: %q %v", named.ID, err)
+ }
+
+ // 2b-1 carry C2: k1 is deleted outside the console. A complete
+ // listing proves it absent: the dedicated sentinel, nothing reaped
+ // or minted, and no key or secret in the error.
+ w.deleteKey(k1.ID)
+ before, _ = w.snapshot()
+ _, err = newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, k1.ID, []string{k1.ID})
+ if !errors.Is(err, fleetstore.ErrKeepKeyMissing) || errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) {
+ t.Fatalf("missing keep: %v", err)
+ }
+ if after, _ := w.snapshot(); after != before || strings.Contains(err.Error(), k1.ID) {
+ t.Fatalf("missing keep changed IAM or named the key: %d %v", after-before, err)
+ }
+ // A listing that fails proves nothing.
+ w.fail["ListAccessKeys"] = itFault{500, "ServiceFailure"}
+ if _, err = newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, k1.ID, []string{k1.ID}); err == nil || errors.Is(err, fleetstore.ErrKeepKeyMissing) {
+ t.Fatalf("failed listing: %v", err)
+ }
+ delete(w.fail, "ListAccessKeys")
+ if live := w.liveKeys(t); len(live) != 0 || slices.Contains(live, k1.ID) {
+ t.Fatalf("live keys: %v", live)
+ }
+ })
+}
diff --git a/internal/compute/provisioner.go b/internal/compute/provisioner.go
index b1e427900..28ad1b810 100644
--- a/internal/compute/provisioner.go
+++ b/internal/compute/provisioner.go
@@ -10,9 +10,14 @@ import (
// effect. It says nothing about an earlier dispatch of the same token.
// ErrLaunchConflict means the client token was already used with other
// parameters: an instance may exist, so it is ambiguity, never a rejection.
+// ErrLaunchNotSent means the call failed before the launch request was
+// dispatched (a pre-launch read failed, for one): this call launched
+// nothing. Like ErrLaunchRejected it says nothing about an earlier dispatch
+// of the same token.
var (
ErrLaunchRejected = errors.New("launch rejected")
ErrLaunchConflict = errors.New("launch conflict")
+ ErrLaunchNotSent = errors.New("launch not sent")
ErrIdentityMismatch = errors.New("instance identity mismatch")
)
diff --git a/internal/console/managed2b2_linux_test.go b/internal/console/managed2b2_linux_test.go
new file mode 100644
index 000000000..c9acfeed1
--- /dev/null
+++ b/internal/console/managed2b2_linux_test.go
@@ -0,0 +1,263 @@
+//go:build linux
+
+package console
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/managedboot/boottest"
+)
+
+// managedFakeRoot is a box root owned by the test's own uid, laid out as
+// the first boot's commit leaves it: the identity the console sent and an
+// empty root-only admission directory. Root's real admission code runs
+// against it with the test's uid standing in for root.
+type managedFakeRoot struct {
+ root string
+ owner managedboot.RootOwner
+}
+
+func newManagedFakeRoot(t *testing.T, id managedboot.Identity) managedFakeRoot {
+ t.Helper()
+ r := managedFakeRoot{root: managedTestRoot(t), owner: managedboot.RootOwner{UID: os.Getuid(), GID: os.Getgid()}}
+ for _, d := range []struct {
+ p string
+ mode os.FileMode
+ }{{"etc", 0o755}, {"etc/carlos", 0o755}, {"var", 0o755}, {"var/lib", 0o755}, {managedboot.RootAdmissionDir, 0o700}} {
+ p := filepath.Join(r.root, d.p)
+ if err := os.Mkdir(p, d.mode); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(p, d.mode); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if st, err := os.Stat(filepath.Join(r.root, managedboot.RootAdmissionDir)); err == nil {
+ r.owner.GID = int(st.Sys().(*syscall.Stat_t).Gid)
+ }
+ body, err := managedboot.EncodeIdentity(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p := filepath.Join(r.root, managedboot.IdentityPath)
+ if err = os.WriteFile(p, body, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Chmod(p, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+// joining is the box's live answer: managed and not admitted by root.
+func (r managedFakeRoot) joining(t *testing.T) bool {
+ t.Helper()
+ managed, admitted, err := managedboot.RootAdmissionAs(r.root, r.owner)
+ if err != nil || !managed {
+ t.Fatalf("root admission: %v %v", managed, err)
+ }
+ return !admitted
+}
+func (r managedFakeRoot) commit(wire []byte) error {
+ return managedboot.CommitAdmissionAs(r.root, wire, r.owner)
+}
+
+// TestManaged2B2OneBox drives one managed box from create to root's
+// admission through the real console doors, worker and probe bridge, and
+// the box's real managedboot code: the frozen user data decodes to the
+// stored boot, the seed matches its frozen digest, the token trades once,
+// the reply passes the box's checks, the first box's key registers, a
+// joining heartbeat and an exactly attested probe pass all six checks, and
+// the signed ready object verifies with the frozen release key. Root
+// admits only that object; nothing counts as admitted before it.
+func TestManaged2B2OneBox(t *testing.T) {
+ g := newOneBox(t)
+ g.launch(func(script string) []byte {
+ if req := boottest.Heredoc(script, "SEEDREQUEST"); !strings.Contains(req, `"token"`) {
+ t.Fatalf("seed request %q", req)
+ }
+ return []byte(boottest.Heredoc(script, "BOOTINPUT"))
+ })
+ g.seedAndTrade()
+ id := managedboot.IdentityOf(g.in)
+ root := newManagedFakeRoot(t, id)
+ if !root.joining(t) {
+ t.Fatal("admitted before anything")
+ }
+ g.mintKey()
+ reg, err := openRegistry(g.s.cfg.Registry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fleet, err := reg.GetFleet(g.in.Fleet)
+ if err != nil || fleet == nil || fleet.SecretsKeyFP != g.key.Fingerprint {
+ t.Fatalf("registered key: %+v %v", fleet, err)
+ }
+ if b := g.box(); b.State != "enrolled" {
+ t.Fatalf("after trade: %s", b.State)
+ }
+
+ // A minute of joining: heartbeat and probe from the box itself.
+ at := g.now.Add(time.Minute)
+ g.joining(at, managedboot.KeyStatusOK)
+ // Before the ready object exists, a forged one is refused by root.
+ _, other, _ := ed25519.GenerateKey(nil)
+ forged, err := managedboot.SignReady(other, managedboot.ReadyRecord{Schema: 1, Kind: managedboot.ReadyKind, Fleet: id.Fleet, Label: id.Label, Op: id.Op, ReadyAt: at})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = root.commit(forged); !errors.Is(err, managedboot.ErrAdmissionRefused) || !root.joining(t) {
+ t.Fatal("root admitted a ready object the console did not sign", err)
+ }
+ e2ePass(t, g.s, at)
+ e2ePass(t, g.s, at.Add(10*time.Second))
+ b := g.box()
+ if b.State != "ready" || !b.DrainClearCompleted {
+ t.Fatalf("not ready: %s %+v", b.State, b.Checks)
+ }
+ for _, name := range managedReadinessChecks {
+ if b.Checks[name].State != "pass" {
+ t.Fatalf("%s: %+v", name, b.Checks[name])
+ }
+ }
+ if g.hub.calls.Load() == 0 || g.hub.badAuth.Load() != 0 || g.hub.last.Fleet != id.Fleet || g.hub.last.Label != id.Label || g.hub.last.Op != id.Op {
+ t.Fatalf("probe: %d calls, %d bad, %+v", g.hub.calls.Load(), g.hub.badAuth.Load(), g.hub.last)
+ }
+ out := managedAPIReply(t, managedAPICall(g.s, "show", "abc", "production", ""))
+ if out.Operation == nil || out.Operation.State != "done" || out.Operation.Outcome != "success" || out.Boxes[0].State != "ready" {
+ t.Fatalf("show: %+v", out)
+ }
+ boxes, err := reg.ListFleetBoxes(g.in.Fleet)
+ if err != nil || len(boxes) != 1 || boxes[0].DrainingSince != 0 {
+ t.Fatalf("registry box: %+v %v", boxes, err)
+ }
+
+ // The agent relays the published object; root verifies and commits.
+ if !root.joining(t) {
+ t.Fatal("admitted before root's record")
+ }
+ raw, _, err := g.s.cfg.Releases.Get(context.Background(), managedReadyKey(b))
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := base64.StdEncoding.DecodeString(g.in.Frozen.ReleasePubkey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec, err := managedboot.VerifyReady(pub, raw, id)
+ if err != nil || !rec.ReadyAt.Equal(b.ReadyAt) {
+ t.Fatalf("ready object: %+v %v", rec, err)
+ }
+ if err = root.commit(raw); err != nil {
+ t.Fatal("root refused the console's ready object:", err)
+ }
+ if root.joining(t) {
+ t.Fatal("not admitted after root's commit")
+ }
+ // Admission is one-way: the object's later absence changes nothing.
+ if err = g.s.cfg.Releases.Delete(context.Background(), managedReadyKey(b)); err != nil {
+ t.Fatal(err)
+ }
+ if root.joining(t) {
+ t.Fatal("admission depends on the published object")
+ }
+}
+
+// TestManaged2B2ConsumedPublicationUncertain (review focus 2, C08): the PUT
+// succeeds and root commits admission, but the console's verifying GET is
+// lost, then reads a mismatch. The console stays publishing and uncertain,
+// holds quota, and never revokes or terminates; the box stays admitted.
+// The next clean verify resolves to ready with no second PUT.
+func TestManaged2B2ConsumedPublicationUncertain(t *testing.T) {
+ g := newOneBox(t)
+ g.launch(func(script string) []byte { return []byte(boottest.Heredoc(script, "BOOTINPUT")) })
+ g.seedAndTrade()
+ g.mintKey()
+ id := managedboot.IdentityOf(g.in)
+ root := newManagedFakeRoot(t, id)
+ b := g.box()
+ st := &publishCountStore{Store: g.s.cfg.Releases, key: managedReadyKey(b)}
+ g.s.cfg.Releases = st
+ reg, err := openRegistry(g.s.cfg.Registry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, err := reg.ListFleetBoxes(id.Fleet)
+ if err != nil || len(before) != 1 {
+ t.Fatal(before, err)
+ }
+ at := g.now.Add(time.Minute)
+ g.joining(at, managedboot.KeyStatusOK)
+ // Fail exactly the GET that follows the PUT.
+ armed := false
+ g.s.cfg.Releases = &armAfterPut{publishCountStore: st, arm: func() { armed = true; st.failGets.Store(1) }}
+ e2ePass(t, g.s, at)
+ if !armed || st.puts.Load() != 1 {
+ t.Fatalf("publication: armed %v, %d puts", armed, st.puts.Load())
+ }
+ b = g.box()
+ if b.State != "publishing" {
+ t.Fatalf("lost verify: %s", b.State)
+ }
+ // The box read the object and root committed it.
+ raw, _, err := st.Store.Get(context.Background(), managedReadyKey(b))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = root.commit(raw); err != nil || root.joining(t) {
+ t.Fatal("root did not admit", err)
+ }
+ // Then the verify reads a mismatch for a while.
+ st.lose.Store(true)
+ for i := 1; i <= 3; i++ {
+ g.s.wakeManagedFleets()
+ e2ePass(t, g.s, at.Add(time.Duration(i)*10*time.Second))
+ }
+ b = g.box()
+ if b.State != "publishing" || b.LastError != "uncertain" || managedHeld(t, g.s) != 1 {
+ t.Fatalf("mismatch: %s %q held %d", b.State, b.LastError, managedHeld(t, g.s))
+ }
+ if c := g.cloud.Calls(); c["Terminate"] != 0 || st.puts.Load() != 1 {
+ t.Fatal("uncertainty terminated or re-published", c, st.puts.Load())
+ }
+ after, err := reg.ListFleetBoxes(id.Fleet)
+ if err != nil || len(after) != 1 || after[0].TokenHash != before[0].TokenHash || after[0].Status != before[0].Status {
+ t.Fatalf("uncertainty revoked the box: %+v -> %+v", before, after)
+ }
+ if root.joining(t) {
+ t.Fatal("box left admission")
+ }
+ // The next clean verify settles it, with no second PUT.
+ st.lose.Store(false)
+ g.s.wakeManagedFleets()
+ e2ePass(t, g.s, at.Add(time.Minute))
+ b = g.box()
+ if b.State != "ready" || b.LastError != "" || st.puts.Load() != 1 {
+ t.Fatalf("resolution: %s %q %d puts", b.State, b.LastError, st.puts.Load())
+ }
+}
+
+// armAfterPut arms the store's GET failure when the ready object is PUT,
+// so exactly the verifying GET that follows the write is lost.
+type armAfterPut struct {
+ *publishCountStore
+ arm func()
+}
+
+func (a *armAfterPut) Put(ctx context.Context, k string, body []byte, ifMatch string) (string, error) {
+ tag, err := a.publishCountStore.Put(ctx, k, body, ifMatch)
+ if k == a.key {
+ a.arm()
+ }
+ return tag, err
+}
diff --git a/internal/console/managed2b2_test.go b/internal/console/managed2b2_test.go
new file mode 100644
index 000000000..11aa9702f
--- /dev/null
+++ b/internal/console/managed2b2_test.go
@@ -0,0 +1,703 @@
+package console
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/compute"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgeproof"
+ "github.com/carlosframework/platform/internal/fleetstore"
+ "github.com/carlosframework/platform/internal/managedboot"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// awsShapedStorage is the fake fleet store with AWS-shaped answers, so the
+// box's own reply checks (managedboot.CheckReply) accept what the console
+// delivers: a 24-character bucket suffix and AKIA key IDs.
+type awsShapedStorage struct {
+ *fleetstore.Fake
+ mu sync.Mutex
+ toAWS map[string]string
+ toFak map[string]string
+}
+
+func newAWSShapedStorage() *awsShapedStorage {
+ return &awsShapedStorage{Fake: fleetstore.NewFake(), toAWS: map[string]string{}, toFak: map[string]string{}}
+}
+func (p *awsShapedStorage) EnsureFleetStorage(ctx context.Context, fleet, region string) (fleetstore.FleetStorage, error) {
+ got, err := p.Fake.EnsureFleetStorage(ctx, fleet, region)
+ if err != nil {
+ return got, err
+ }
+ sum := sha256.Sum256([]byte(fleet))
+ return fleetstore.FleetStorage{Bucket: "carlos-fleet-" + hex.EncodeToString(sum[:])[:24], Region: got.Region}, nil
+}
+func (p *awsShapedStorage) RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (fleetstore.Credentials, error) {
+ p.mu.Lock()
+ keepFake := p.toFak[keep]
+ var fakeDelivered []string
+ for _, id := range delivered {
+ fakeDelivered = append(fakeDelivered, p.toFak[id])
+ }
+ p.mu.Unlock()
+ if keep != "" && keepFake == "" {
+ keepFake = "unknown-" + keep
+ }
+ c, err := p.Fake.RotateFleetCredentials(ctx, fleet, keepFake, fakeDelivered)
+ if err != nil {
+ return c, err
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ id := fmt.Sprintf("AKIAEXAMPLE%09d", len(p.toAWS)+1)
+ p.toAWS[c.ID], p.toFak[id] = id, c.ID
+ return fleetstore.Credentials{ID: id, Secret: []byte(fmt.Sprintf("examplesecret%027d", len(p.toAWS)))}, nil
+}
+
+// DeleteAWSKey removes one delivered key, as an operator deleting it in IAM.
+func (p *awsShapedStorage) DeleteAWSKey(fleet, id string) {
+ p.mu.Lock()
+ fake := p.toFak[id]
+ p.mu.Unlock()
+ p.Fake.DeleteKey(fleet, fake)
+}
+
+// launchSpecs records every Launch's frozen request.
+type launchSpecs struct {
+ *compute.Fake
+ mu sync.Mutex
+ specs []compute.LaunchSpec
+ console func() (string, error)
+ outputs atomic.Int32
+ findErr atomic.Bool
+}
+
+func (l *launchSpecs) Launch(ctx context.Context, spec compute.LaunchSpec) (compute.Instance, error) {
+ l.mu.Lock()
+ l.specs = append(l.specs, spec)
+ l.mu.Unlock()
+ return l.Fake.Launch(ctx, spec)
+}
+func (l *launchSpecs) Find(ctx context.Context, region string, id compute.Identity) ([]compute.Instance, error) {
+ if l.findErr.Load() {
+ return nil, errors.New("describe failed")
+ }
+ return l.Fake.Find(ctx, region, id)
+}
+func (l *launchSpecs) ConsoleOutput(ctx context.Context, region, cloudID string) (string, error) {
+ l.outputs.Add(1)
+ if _, err := l.Fake.ConsoleOutput(ctx, region, cloudID); err != nil {
+ return "", err
+ }
+ if l.console == nil {
+ return "", nil
+ }
+ return l.console()
+}
+
+// oneBox is a console with the real doors, worker and probe bridge, a fake
+// cloud, a fake fleet hub whose answers are the box's, and the box's own
+// view of everything the console sent it.
+type oneBox struct {
+ t *testing.T
+ s *Server
+ cloud *launchSpecs
+ storage *awsShapedStorage
+ hub *fakeProbeHub
+ now time.Time
+
+ in managedboot.LaunchInput
+ reply managedboot.EnrolReply
+ key managedboot.FleetKey
+}
+
+func newOneBox(t *testing.T) *oneBox {
+ t.Helper()
+ s := managedAPIFixture(t)
+ setManagedHistory(t, s, provision.HostsState{Mode: provision.HostsModeIncomplete})
+ s.cfg.SecretsPub, _ = mustTestSecretsKey()
+ storage := newAWSShapedStorage()
+ s.cfg.ManagedStorage = storage
+ cloud := &launchSpecs{Fake: s.cfg.ManagedCompute.(*compute.Fake)}
+ s.cfg.ManagedCompute = cloud
+ ctx := context.Background()
+ if err := edge.MintMeshKey(ctx, s.cfg.Releases); err != nil {
+ t.Fatal(err)
+ }
+ cur, _, err := edgeproof.LoadKeys(ctx, s.cfg.Releases)
+ if err != nil || len(cur) == 0 {
+ t.Fatal("mesh key", err)
+ }
+ h := &fakeProbeHub{t: t, key: cur}
+ h.answer = func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }
+ h.srv = httptest.NewServer(h)
+ t.Cleanup(h.srv.Close)
+ // The production bridge, built from the live server as NewServer does.
+ p := managedExtraFor(s).(*managedProbeChecks)
+ p.url = h.srv.URL + edge.FleetProbePath
+ s.managedExtra = p
+ g := &oneBox{t: t, s: s, cloud: cloud, storage: storage, hub: h, now: time.Now().UTC()}
+ out := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 1)))
+ if out.Operation == nil || out.Operation.State != "open" {
+ t.Fatalf("create: %+v", out)
+ }
+ return g
+}
+
+func (g *oneBox) box() managedBox {
+ g.t.Helper()
+ bs := e2eBoxes(g.t, g.s)
+ if len(bs) != 1 {
+ g.t.Fatalf("boxes: %d", len(bs))
+ }
+ return bs[0]
+}
+
+// launch runs the first pass and decodes the launched user data the way
+// the box's cloud-init does.
+func (g *oneBox) launch(boot func(script string) []byte) {
+ t := g.t
+ t.Helper()
+ e2ePass(t, g.s, g.now)
+ b := g.box()
+ if (b.State != "launching" && b.State != "booting") || b.CloudID == "" || b.Boot.IsZero() || len(g.cloud.specs) != 1 {
+ t.Fatalf("launch: %s %v", b.State, len(g.cloud.specs))
+ }
+ in, err := managedboot.DecodeLaunchInput(boot(g.cloud.specs[0].UserData))
+ if err != nil {
+ t.Fatal("boot input:", err)
+ }
+ if in.Frozen != b.Boot || in.Fleet != b.Fleet || in.Label != b.Label || in.Op != b.OpID {
+ t.Fatalf("frozen boot differs: %+v %+v", in, b.Boot)
+ }
+ g.in = in
+}
+
+// seedAndTrade fetches the seed with the one-time token, checks its digest
+// as the script does, and trades the token once.
+func (g *oneBox) seedAndTrade() {
+ t := g.t
+ t.Helper()
+ w := seedHTTP(g.s, seedBody(g.in.Token), "192.0.2.10")
+ sum := sha256.Sum256(w.Body.Bytes())
+ if w.Code != 200 || hex.EncodeToString(sum[:]) != g.in.Frozen.SeedSHA256 {
+ t.Fatalf("seed: %d", w.Code)
+ }
+ e := enrolHTTP(g.s, enrolBody(g.in.Token))
+ if e.Code != 200 {
+ t.Fatalf("trade: %d %s", e.Code, e.Body)
+ }
+ if err := json.Unmarshal(e.Body.Bytes(), &g.reply); err != nil {
+ t.Fatal(err)
+ }
+ if err := managedboot.CheckReply(g.in, g.reply); err != nil {
+ t.Fatal("box refuses the reply:", err)
+ }
+ id := managedboot.IdentityOf(g.in)
+ env, err := managedboot.ManagedHostEnv(id, g.reply, g.in.Frozen, "")
+ if err != nil || len(env) == 0 {
+ t.Fatal("host.env:", err)
+ }
+ creds, err := managedboot.RenderCredentials(g.reply.Credentials)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if kid, err := managedboot.CredentialsKeyID(creds); err != nil || kid != g.reply.Credentials.ID {
+ t.Fatal("credentials file", kid, err)
+ }
+ if again := enrolHTTP(g.s, enrolBody(g.in.Token)); again.Code != 403 {
+ t.Fatal("token traded twice", again.Code)
+ }
+}
+
+// mintKey is the first box's key: minted locally, registered at the door.
+func (g *oneBox) mintKey() {
+ t := g.t
+ t.Helper()
+ k, err := managedboot.MintFleetKey(managedboot.IdentityOf(g.in))
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := g.box()
+ w := keyDoorHTTP(g.s, g.reply.TunnelToken, keyDoorBody(b, k.Public))
+ var reply managedboot.FleetKeyReply
+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &reply) != nil || reply.Fingerprint != k.Fingerprint || !reply.Changed {
+ t.Fatalf("key door: %d %s", w.Code, w.Body)
+ }
+ g.key = k
+}
+
+// joining is the box's heartbeat and its probe responder: the delivered
+// key, the given managed_key status and the installed key's fingerprint.
+func (g *oneBox) joining(at time.Time, keyStatus string) {
+ g.t.Helper()
+ b := g.box()
+ readyBeat(g.t, g.s, b, status.Box{Label: b.Label, GeneratedAt: at, ManagedKey: keyStatus, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true, Tunnel: "connected"}})
+ fp := g.key.Fingerprint
+ kid := g.reply.Credentials.ID
+ g.hub.set(func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ attest(w, req.Channel(), probeEcho(req, fp, func(r *managedboot.ProbeReply) { r.Storage.KeyID = kid }))
+ })
+}
+
+// TestManagedExtraWired: NewServer builds the probe bridge from the live
+// server when a hub host is configured; without one the bridge is a true
+// nil interface, so storage and router stay pending.
+func TestManagedExtraWired(t *testing.T) {
+ rel := release.NewDirStore(t.TempDir())
+ st := openGatedStore(t)
+ wired, err := NewServer(Config{Origin: "https://console.example", Keymail: "https://keymail.example", Releases: rel, TunnelHost: "tunnel.example.com",
+ ManagedCompute: compute.NewFake(), ManagedStorage: fleetstore.NewFake(), ManagedDeployment: "test"}, st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p, ok := wired.managedExtra.(*managedProbeChecks)
+ if !ok || p.s != wired || p.url != "https://tunnel.example.com"+edge.FleetProbePath {
+ t.Fatalf("bridge: %#v", wired.managedExtra)
+ }
+ bare, err := NewServer(Config{Origin: "https://console.example", Keymail: "https://keymail.example", Releases: rel,
+ ManagedCompute: compute.NewFake(), ManagedStorage: fleetstore.NewFake(), ManagedDeployment: "test"}, st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bare.managedExtra != nil {
+ t.Fatalf("no hub host, bridge %#v", bare.managedExtra)
+ }
+ b := managedBox{State: "enrolled", Fleet: "shop", Label: "box-1"}
+ checks, _, err := bare.observeManagedReadiness(context.Background(), b, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if checks["storage"].State != "pending" || checks["router_probe"].State != "pending" {
+ t.Fatalf("checks without a bridge: %+v", checks)
+ }
+}
+
+// TestManaged2B2LaunchNotSent (2b-1 carry C1): a failure that provably
+// precedes the launch dispatch, on the dispatch that directly follows the
+// launching commit, fails the box with its reason and releases the quota.
+// After any possible earlier dispatch it stays ambiguity and holds quota.
+func TestManaged2B2LaunchNotSent(t *testing.T) {
+ notSent := fmt.Errorf("adapter: describe image: %w", compute.ErrLaunchNotSent)
+ t.Run("first", func(t *testing.T) {
+ s, p, _, now := managedWorkerFixture(t)
+ s.cfg.ManagedCompute = &managedComputeScript{Fake: p, launch: func(context.Context, compute.LaunchSpec) (compute.Instance, error) {
+ return compute.Instance{}, notSent
+ }}
+ b := workerStep(t, s, now)
+ if b.State != "terminated" || b.LastError != "managed_launch_not_sent" || managedHeld(t, s) != 0 || b.CloudID != "" {
+ t.Fatalf("not sent: %+v", b)
+ }
+ view, err := s.managedFleetView(context.Background(), b.Account, b.Fleet, nil)
+ if err != nil || len(view.Boxes) != 1 || view.Boxes[0].LastError != "managed_launch_not_sent" || view.Operation == nil {
+ t.Fatalf("show: %+v %v", view, err)
+ }
+ // Nothing more happens to it: no Find, no Terminate.
+ for i := 1; i <= 3; i++ {
+ workerStep(t, s, now.Add(time.Duration(i)*time.Hour))
+ }
+ if c := p.Calls(); c["Find"] != 0 || c["Terminate"] != 0 || c["Lookup"] != 0 {
+ t.Fatal("terminated box polled", c)
+ }
+ })
+ t.Run("crash-after-commit", func(t *testing.T) {
+ s, p, b, now := managedWorkerFixture(t)
+ workerAdvance(t, s, b, func(b *managedBox) {
+ b.State = "launching"
+ b.LaunchStartedAt = now
+ b.EnrolExpires = now.Add(30 * time.Minute)
+ b.Boot = managedExpectedBoot(s, "v0.34.0", managedTestSeed)
+ })
+ s = restartManagedWorker(t, s)
+ s.cfg.ManagedCompute = &managedComputeScript{Fake: p, launch: func(context.Context, compute.LaunchSpec) (compute.Instance, error) {
+ return compute.Instance{}, notSent
+ }}
+ b = workerStep(t, s, now.Add(time.Second))
+ if b.State == "terminated" || managedHeld(t, s) != 1 {
+ t.Fatalf("recovery not-sent released quota: %+v", b)
+ }
+ })
+}
+
+// TestManaged2B2KeepKeyMissing (2b-1 carry C2): when a complete key listing
+// proves the key boxes use absent, the fleet records needs-operator with a
+// reason naming that, show and the add refusal say so, and nothing reaps,
+// mints or launches. An ambiguous recheck keeps the state.
+func TestManaged2B2KeepKeyMissing(t *testing.T) {
+ s, p, _ := managedE2E(t, 1)
+ storage := &keepKeyStorage{Fake: s.cfg.ManagedStorage.(*fleetstore.Fake)}
+ s.cfg.ManagedStorage = storage
+ clock := func() time.Time { return time.Now().UTC() }
+ e2ePass(t, s, clock())
+ k1 := e2eEnrol(t, s, e2eBoxes(t, s)[0]).Credentials.ID
+ e2eReady(t, s, clock())
+ storage.DeleteKey("production", k1)
+ if _, err := s.store.db.Exec(`UPDATE managed_fleet_storage SET credential_sealed=X'00'`); err != nil {
+ t.Fatal(err)
+ }
+ add := func(id string) *httptest.ResponseRecorder {
+ return managedAPICall(s, "add", "abc", "production", fmt.Sprintf(`{"boxes":1,"request_id":%q}`, strings.Repeat(id, 22)))
+ }
+ launches, mints := p.Calls()["Launch"], storage.mints
+ managedAPIReply(t, add("b"))
+ e2ePass(t, s, clock())
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.CredentialState != managedNeedsOperator || out.CredentialReason != managedReasonKeepKeyMissing {
+ t.Fatalf("show: %+v", out)
+ }
+ if out.Operation == nil || out.Operation.State != "failed" || out.Operation.Error != managedReasonKeepKeyMissing {
+ t.Fatalf("operation: %+v", out.Operation)
+ }
+ if p.Calls()["Launch"] != launches || storage.mints != mints {
+ t.Fatal("launched or minted without the key boxes use", p.Calls(), storage.mints)
+ }
+ w := add("c")
+ if w.Code != 409 || !strings.Contains(w.Body.String(), msgManagedKeepKeyMissing) {
+ t.Fatalf("add: %d %s", w.Code, w.Body)
+ }
+ storage.ambiguous = true
+ if w = add("d"); w.Code == 202 || w.Code == 200 {
+ t.Fatalf("ambiguous recheck admitted: %d %s", w.Code, w.Body)
+ }
+ out = managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.CredentialState != managedNeedsOperator || out.CredentialReason != managedReasonKeepKeyMissing {
+ t.Fatalf("ambiguity changed the state: %+v", out)
+ }
+ if p.Calls()["Launch"] != launches || storage.mints != mints {
+ t.Fatal("launched or minted while needs-operator")
+ }
+}
+
+// keepKeyStorage counts mints and can answer every rotation ambiguously.
+type keepKeyStorage struct {
+ *fleetstore.Fake
+ ambiguous bool
+ mints int
+}
+
+func (k *keepKeyStorage) RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (fleetstore.Credentials, error) {
+ if k.ambiguous {
+ return fleetstore.Credentials{}, errors.New("listing failed")
+ }
+ c, err := k.Fake.RotateFleetCredentials(ctx, fleet, keep, delivered)
+ if err == nil {
+ k.mints++
+ }
+ return c, err
+}
+
+// TestManaged2B2KeyFailureStatus: the box enrols and joins, but its fleet
+// key object is malformed. The heartbeat's managed_key fails storage with
+// the key reason, show says so, no ready object is written and no workload
+// can be admitted; the readiness deadline cleans the box up.
+func TestManaged2B2KeyFailureStatus(t *testing.T) {
+ g := newOneBox(t)
+ g.launch(func(script string) []byte { return []byte(managedTestHeredoc(t, script, "BOOTINPUT")) })
+ g.seedAndTrade()
+ at := g.now.Add(time.Minute)
+ g.joining(at, managedboot.KeyStatusObjectInvalid)
+ e2ePass(t, g.s, at)
+ b := g.box()
+ want := managedCheck{State: "fail", Reason: managedKeyReasons[managedboot.KeyStatusObjectInvalid]}
+ if b.State != "enrolled" || b.Checks["storage"] != want {
+ t.Fatalf("box %s %+v", b.State, b.Checks)
+ }
+ shown := managedAPICall(g.s, "show", "abc", "production", "")
+ out := managedAPIReply(t, shown)
+ if len(out.Boxes) != 1 || out.Boxes[0].State != "joining" || out.Boxes[0].Checks["storage"] != want {
+ t.Fatalf("show: %+v", out.Boxes)
+ }
+ if _, _, err := g.s.cfg.Releases.Get(context.Background(), managedReadyKey(b)); err == nil {
+ t.Fatal("ready object written for a box whose key failed")
+ }
+ g.cloud.console = func() (string, error) { return managedboot.CodeJoining, nil }
+ e2ePass(t, g.s, b.LaunchStartedAt.Add(20*time.Minute))
+ e2ePass(t, g.s, b.LaunchStartedAt.Add(20*time.Minute+10*time.Second))
+ b = g.box()
+ if b.State != "terminating" || b.LastError != "managed_readiness_timeout" || g.cloud.Calls()["Terminate"] != 1 {
+ t.Fatalf("deadline cleanup: %s %s %v", b.State, b.LastError, g.cloud.Calls())
+ }
+ out = managedAPIReply(t, managedAPICall(g.s, "show", "abc", "production", ""))
+ if out.Boxes[0].Boot != managedBootText[managedboot.CodeJoining] {
+ t.Fatalf("boot: %q", out.Boxes[0].Boot)
+ }
+}
+
+// managedTestHeredoc is the named heredoc's body in a rendered script.
+func managedTestHeredoc(t *testing.T, script, name string) string {
+ t.Helper()
+ open := "<<'" + name + "'\n"
+ i := strings.Index(script, open)
+ if i < 0 {
+ t.Fatalf("no heredoc %s", name)
+ }
+ body, _, ok := strings.Cut(script[i+len(open):], "\n"+name+"\n")
+ if !ok {
+ t.Fatalf("unterminated heredoc %s", name)
+ }
+ return body + "\n"
+}
+
+// publishCountStore counts ready-object PUTs and GETs and can fail GETs.
+type publishCountStore struct {
+ release.Store
+ key string
+ puts, gets atomic.Int32
+ failGets atomic.Int32
+ lose atomic.Bool
+}
+
+func (p *publishCountStore) Get(ctx context.Context, k string) ([]byte, string, error) {
+ if k == p.key {
+ p.gets.Add(1)
+ if p.failGets.Load() > 0 {
+ p.failGets.Add(-1)
+ return nil, "", errors.New("verify read lost")
+ }
+ if p.lose.Load() {
+ return []byte(`{"payload":"other","sig":"x"}`), "etag", nil
+ }
+ }
+ return p.Store.Get(ctx, k)
+}
+func (p *publishCountStore) Put(ctx context.Context, k string, b []byte, ifMatch string) (string, error) {
+ if k == p.key {
+ p.puts.Add(1)
+ }
+ return p.Store.Put(ctx, k, b, ifMatch)
+}
+
+// TestManaged2B2Diagnostics: a launched box that misses its readiness
+// deadline gets exactly one console-output read, inside cleanup. Only the
+// fixed breadcrumb codes are persisted and show reports the last one; the
+// tokens and keys the console printed never reach show, logs or rows. A
+// healthy box is never read.
+func TestManaged2B2Diagnostics(t *testing.T) {
+ g := newOneBox(t)
+ g.launch(func(script string) []byte { return []byte(managedTestHeredoc(t, script, "BOOTINPUT")) })
+ b := g.box()
+ secrets := []string{g.in.Token, "tunnel-token-0123", "AKIAEXAMPLE000000009", "-----BEGIN PRIVATE KEY-----"}
+ noisy := strings.Join([]string{
+ "cloud-init: token " + g.in.Token,
+ managedboot.CodeSeedVerified,
+ "export TUNNEL=" + secrets[1],
+ managedboot.CodeEnrolPending,
+ "aws_access_key_id=" + secrets[2],
+ managedboot.CodeEnrolFailed,
+ secrets[3],
+ managedboot.Breadcrumb(managedboot.CodeJoining),
+ "enrol_failed " + secrets[1],
+ }, "\n")
+ // The adapter returns bare codes only; a provider that returned other
+ // text still yields only the lines that are exactly a known code.
+ g.cloud.console = func() (string, error) { return noisy, nil }
+ var logs strings.Builder
+ logOut(t, &logs)
+ for i := 0; i < 10; i++ {
+ e2ePass(t, g.s, g.now.Add(time.Duration(i)*time.Minute))
+ }
+ if n := g.cloud.outputs.Load(); n != 0 {
+ t.Fatalf("console output read while healthy: %d", n)
+ }
+ deadline := b.LaunchStartedAt.Add(20 * time.Minute)
+ e2ePass(t, g.s, deadline)
+ for i := 1; i <= 5; i++ {
+ g.s.wakeManagedFleets()
+ e2ePass(t, g.s, deadline.Add(time.Duration(i)*time.Hour))
+ }
+ if n := g.cloud.outputs.Load(); n != 1 {
+ t.Fatalf("console output reads: %d", n)
+ }
+ b = g.box()
+ if b.BootBreadcrumbs != "seed_verified\nenrol_pending\nenrol_failed" || !b.BootDiagnosed {
+ t.Fatalf("breadcrumbs %q", b.BootBreadcrumbs)
+ }
+ shown := managedAPICall(g.s, "show", "abc", "production", "")
+ out := managedAPIReply(t, shown)
+ if out.Boxes[0].Boot != managedBootText[managedboot.CodeEnrolFailed] {
+ t.Fatalf("boot %q", out.Boxes[0].Boot)
+ }
+ var rows strings.Builder
+ r, err := g.s.store.db.Query(`SELECT launch FROM managed_boxes`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for r.Next() {
+ var raw []byte
+ if err := r.Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ rows.Write(raw)
+ }
+ r.Close()
+ for _, where := range []struct{ name, text string }{{"show", shown.Body.String()}, {"logs", logs.String()}, {"rows", rows.String()}} {
+ for _, secret := range secrets {
+ if strings.Contains(where.text, secret) {
+ t.Fatalf("%s carries console text %q", where.name, secret)
+ }
+ }
+ if strings.Contains(where.text, "cloud-init:") {
+ t.Fatalf("%s carries console text", where.name)
+ }
+ }
+ // A failed read records nothing and is never repeated, even while
+ // cleanup itself keeps retrying (every Find fails, so nothing is
+ // terminated and the box stays failed for hours).
+ g2 := newOneBox(t)
+ g2.launch(func(script string) []byte { return []byte(managedTestHeredoc(t, script, "BOOTINPUT")) })
+ g2.cloud.console = func() (string, error) { return "", errors.New("uncertain") }
+ g2.cloud.findErr.Store(true)
+ b2 := g2.box()
+ for i := 0; i < 4; i++ {
+ g2.s.wakeManagedFleets()
+ e2ePass(t, g2.s, b2.LaunchStartedAt.Add(20*time.Minute+time.Duration(i)*time.Hour))
+ }
+ b2 = g2.box()
+ if g2.cloud.outputs.Load() != 1 || !b2.BootDiagnosed || b2.BootBreadcrumbs != "" || b2.State != "failed" || g2.cloud.Calls()["Terminate"] != 0 {
+ t.Fatalf("failed read: %d %+v", g2.cloud.outputs.Load(), b2)
+ }
+ if out := managedAPIReply(t, managedAPICall(g2.s, "show", "abc", "production", "")); out.Boxes[0].Boot != managedBootNoProgress {
+ t.Fatalf("boot %q", out.Boxes[0].Boot)
+ }
+}
+
+// logOut captures the standard logger for the test.
+func logOut(t *testing.T, w *strings.Builder) {
+ t.Helper()
+ var mu sync.Mutex
+ prev := log.Writer()
+ log.SetOutput(writerFunc(func(p []byte) (int, error) { mu.Lock(); defer mu.Unlock(); return w.Write(p) }))
+ t.Cleanup(func() { log.SetOutput(prev) })
+}
+
+type writerFunc func([]byte) (int, error)
+
+func (f writerFunc) Write(p []byte) (int, error) { return f(p) }
+
+// TestManaged2B2Budget: settled boxes cost nothing through the production
+// bridge, and an enrolled box costs at most one heartbeat GET and one probe
+// a minute, with no fleet-wide listing or console-output timer.
+func TestManaged2B2Budget(t *testing.T) {
+ for _, n := range []int{1, 10, 100} {
+ t.Run(fmt.Sprint(n), func(t *testing.T) {
+ s, p, now := managedE2E(t, n)
+ h := &fakeProbeHub{t: t}
+ h.srv = httptest.NewServer(h)
+ t.Cleanup(h.srv.Close)
+ s.cfg.TunnelHost = "tunnel.example.com"
+ bridge := managedExtraFor(s).(*managedProbeChecks)
+ bridge.url = h.srv.URL + edge.FleetProbePath
+ s.managedExtra = bridge
+ e2ePass(t, s, now)
+ for _, b := range e2eBoxes(t, s) {
+ next := b
+ next.State = "ready"
+ next.ReadyAt = now
+ next.DrainClearCompleted = true
+ if ok, err := s.store.AdvanceManagedBox(context.Background(), b, next); err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+ }
+ e2ePass(t, s, now.Add(time.Minute))
+ st := &opCountStore{Store: s.cfg.Releases}
+ s.cfg.Releases = st
+ db := &managedSQLCounter{sqlHandle: s.store.db}
+ s.store.db = db
+ before := p.Calls()
+ for i := 0; i < 100; i++ {
+ e2ePass(t, s, now.Add(time.Duration(i+1)*time.Hour))
+ }
+ if st.total() != 0 || db.calls != 0 || !reflect.DeepEqual(before, p.Calls()) || h.calls.Load() != 0 {
+ t.Fatal("settled calls", db.calls, st.snapshot(), p.Calls(), h.calls.Load())
+ }
+ })
+ }
+ t.Run("enrolled", func(t *testing.T) {
+ g := newOneBox(t)
+ g.launch(func(script string) []byte { return []byte(managedTestHeredoc(t, script, "BOOTINPUT")) })
+ g.seedAndTrade()
+ g.hub.set(func(req managedboot.ProbeRequest, w http.ResponseWriter) {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ })
+ b := g.box()
+ st := countReadiness(g.s)
+ beat := "fleets/" + b.Fleet + "/status/boxes/" + b.Label + ".json"
+ // Ten minutes of passes every ten seconds, the box never ready.
+ for i := 0; i < 60; i++ {
+ at := g.now.Add(time.Duration(i) * 10 * time.Second)
+ readyBeatIn(t, st.Store, b, status.Box{Label: b.Label, GeneratedAt: at, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true, Tunnel: "connected"}})
+ g.s.wakeManagedFleets()
+ e2ePass(t, g.s, at)
+ }
+ if probes, gets := g.hub.calls.Load(), st.gets[beat]; probes > 10 || gets > 10 || probes == 0 {
+ t.Fatalf("enrolled box over 10 minutes: %d probes, %d heartbeat GETs", probes, gets)
+ }
+ if c := g.cloud.Calls(); c["ListDeployment"] != 0 || g.cloud.outputs.Load() != 0 {
+ t.Fatal("timers", c, g.cloud.outputs.Load())
+ }
+ })
+}
+
+// TestManaged2B2HostClaim: a host-claim console refuses every managed door
+// added for the box side and runs no worker pass or probe.
+func TestManaged2B2HostClaim(t *testing.T) {
+ g := newOneBox(t)
+ g.launch(func(script string) []byte { return []byte(managedTestHeredoc(t, script, "BOOTINPUT")) })
+ g.s.cfg.HostClaim = true
+ if w := seedHTTP(g.s, seedBody(g.in.Token), "192.0.2.11"); w.Code != http.StatusConflict {
+ t.Fatalf("seed door: %d", w.Code)
+ }
+ if w := enrolHTTP(g.s, enrolBody(g.in.Token)); w.Code != http.StatusConflict {
+ t.Fatalf("enrol door: %d", w.Code)
+ }
+ b := g.box()
+ if w := keyDoorHTTP(g.s, strings.Repeat("a", 64), keyDoorBody(b, "x")); w.Code != http.StatusConflict {
+ t.Fatalf("key door: %d", w.Code)
+ }
+ if err := g.s.RunManagedFleetsPass(context.Background(), g.now.Add(time.Minute)); !errors.Is(err, errManagedHostClaim) {
+ t.Fatal("worker pass on a host-claim console", err)
+ }
+ if err := g.s.stepManagedBox(context.Background(), b, g.now.Add(time.Minute)); !errors.Is(err, errManagedHostClaim) {
+ t.Fatal("worker step on a host-claim console", err)
+ }
+ enrolled := b
+ enrolled.State = "enrolled"
+ storage, router, err := g.s.managedExtra.Checks(context.Background(), enrolled)
+ if err != nil || storage.State != "pending" || router.State != "pending" || g.hub.calls.Load() != 0 {
+ t.Fatalf("probe on a host-claim console: %+v %+v %v %d", storage, router, err, g.hub.calls.Load())
+ }
+ if after := g.box(); after.State != b.State || !after.EnrolUsedAt.IsZero() {
+ t.Fatalf("host-claim refusal changed the box: %+v", after)
+ }
+}
+
+// managedTestRoot is a scratch directory for a fake box root, removed by
+// the test.
+func managedTestRoot(t *testing.T) string {
+ t.Helper()
+ dir := filepath.Join(t.TempDir(), "root")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return dir
+}
diff --git a/internal/console/managed_e2e_test.go b/internal/console/managed_e2e_test.go
index 9beeeef85..b449230ae 100644
--- a/internal/console/managed_e2e_test.go
+++ b/internal/console/managed_e2e_test.go
@@ -469,15 +469,51 @@ var managedAppStorePolicies = []string{
`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":"arn:aws:s3:::carlos-store-shop-0123"},{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:GetObjectTagging"],"Resource":"arn:aws:s3:::carlos-store-shop-0123/*"},{"Effect":"Deny","Action":["s3:PutObjectTagging","s3:DeleteObjectTagging","s3:PutObjectVersionTagging","s3:DeleteObjectVersionTagging"],"Resource":"arn:aws:s3:::carlos-store-shop-0123/*"},{"Effect":"Deny","Action":["s3:PutObject"],"Resource":"arn:aws:s3:::carlos-store-shop-0123/*","Condition":{"ForAnyValue:StringEquals":{"s3:RequestObjectTagKeys":["carlos-scan","carlos-scan-version","carlos-scan-at"]}}},{"Effect":"Deny","Action":["s3:PutObject"],"Resource":"arn:aws:s3:::carlos-store-shop-0123/*"}]}`,
}
-// TestManaged2B1Disabled: 2b-1 ships off. Production wires no provider,
-// off or missing providers refuse new work, reserved work stays recoverable
-// with injected fakes, a host-claim console refuses everything managed, and
-// BYO fleets and app stores behave the same either way.
+// TestManaged2B1Disabled: 2b-1 ships off. Production wires providers in
+// exactly one place, the console's opt-in (2b-2 Task 6), off or missing
+// providers refuse new work, reserved work stays recoverable with injected
+// fakes, a host-claim console refuses everything managed, and BYO fleets and
+// app stores behave the same either way.
func TestManaged2B1Disabled(t *testing.T) {
t.Run("no production providers", func(t *testing.T) {
files := 0
+ // The one wiring site: cmd/console/main.go assigns both providers
+ // from managedProvidersFromEnv, which is nil unless opted in.
+ wiring, err := filepath.Abs("../../cmd/console/main.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ wired := 0
managedProductionSources(t, func(path string, src []byte) {
files++
+ if abs, _ := filepath.Abs(path); abs == wiring {
+ f, err := parser.ParseFile(token.NewFileSet(), path, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ a, ok := n.(*ast.AssignStmt)
+ if !ok {
+ return true
+ }
+ for _, lhs := range a.Lhs {
+ sel, ok := lhs.(*ast.SelectorExpr)
+ if !ok || (sel.Sel.Name != "ManagedCompute" && sel.Sel.Name != "ManagedStorage") {
+ continue
+ }
+ wired++
+ var fun ast.Expr
+ if call, ok := a.Rhs[0].(*ast.CallExpr); ok && len(a.Rhs) == 1 {
+ fun = call.Fun
+ }
+ if id, ok := fun.(*ast.Ident); !ok || id.Name != "managedProvidersFromEnv" {
+ t.Errorf("%s assigns a managed provider other than from managedProvidersFromEnv", path)
+ }
+ }
+ return true
+ })
+ return
+ }
if bytes.Contains(src, []byte("internal/awsmanaged")) {
f, err := parser.ParseFile(token.NewFileSet(), path, src, parser.ImportsOnly)
if err != nil {
@@ -525,6 +561,9 @@ func TestManaged2B1Disabled(t *testing.T) {
if files < 1000 {
t.Fatalf("scanned only %d files", files)
}
+ if wired != 2 {
+ t.Fatalf("the console's opt-in wires %d providers, want 2", wired)
+ }
var zero managedConfig
if zero.Enabled || (Config{}).ManagedCompute != nil || (Config{}).ManagedStorage != nil {
t.Fatal("managed fleets on by default")
diff --git a/internal/console/managedbudget_test.go b/internal/console/managedbudget_test.go
index 17d46677a..485b3d638 100644
--- a/internal/console/managedbudget_test.go
+++ b/internal/console/managedbudget_test.go
@@ -334,6 +334,7 @@ func managedNoInventoryPolling(t *testing.T, p *compute.Fake) {
// is counted on its own box only.
func TestManaged2B1Budget(t *testing.T) {
t.Run("source", func(t *testing.T) {
+ outputs := 0
entries, err := os.ReadDir(".")
if err != nil {
t.Fatal(err)
@@ -346,12 +347,28 @@ func TestManaged2B1Budget(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- ast.Inspect(f, func(n ast.Node) bool {
- if sel, ok := n.(*ast.SelectorExpr); ok && (sel.Sel.Name == "ListDeployment" || sel.Sel.Name == "ConsoleOutput") {
- t.Errorf("%s calls %s", e.Name(), sel.Sel.Name)
- }
- return true
- })
+ for _, d := range f.Decls {
+ fn, _ := d.(*ast.FuncDecl)
+ ast.Inspect(d, func(n ast.Node) bool {
+ sel, ok := n.(*ast.SelectorExpr)
+ if !ok {
+ return true
+ }
+ // The one console-output read: a box that missed its
+ // readiness deadline, inside cleanup (2b-2 Task 6).
+ if sel.Sel.Name == "ConsoleOutput" && e.Name() == "managedworker.go" && fn != nil && fn.Name.Name == "recordManagedBreadcrumbs" {
+ outputs++
+ return true
+ }
+ if sel.Sel.Name == "ListDeployment" || sel.Sel.Name == "ConsoleOutput" {
+ t.Errorf("%s calls %s", e.Name(), sel.Sel.Name)
+ }
+ return true
+ })
+ }
+ }
+ if outputs != 1 {
+ t.Errorf("console-output call sites: %d, want 1", outputs)
}
})
for _, n := range []int{1, 10, 100} {
diff --git a/internal/console/managedhistory.go b/internal/console/managedhistory.go
index 53eda27ed..bdbf7839f 100644
--- a/internal/console/managedhistory.go
+++ b/internal/console/managedhistory.go
@@ -35,6 +35,26 @@ const msgManagedNeedsOperator = "this fleet needs an operator (needs-operator):
var errManagedNeedsOperator = errors.New(managedReasonDeliveredKeyLive)
+// COPY: the keep-key reason code and refusal await controller review. A
+// complete key listing proved the key boxes use absent (2b-1 carry C2): it
+// was deleted outside the console. Minting a replacement is 2c key
+// replacement, so the fleet waits for an operator rather than holding
+// silently.
+const managedReasonKeepKeyMissing = "fleet_access_key_missing"
+const msgManagedKeepKeyMissing = "this fleet needs an operator (needs-operator): the access key this fleet's boxes use no longer exists in IAM. boxes cannot be added until the fleet is given a new key, which the console cannot do yet"
+
+var errManagedKeepKeyMissing = fmt.Errorf("%w: %s", errManagedNeedsOperator, managedReasonKeepKeyMissing)
+
+// managedNeedsOperatorReason is the reason code and refusal for a
+// needs-operator error; both are the delivered-key ones unless err is the
+// missing keep key.
+func managedNeedsOperatorReason(err error) (reason, msg string) {
+ if errors.Is(err, errManagedKeepKeyMissing) {
+ return managedReasonKeepKeyMissing, msgManagedKeepKeyMissing
+ }
+ return managedReasonDeliveredKeyLive, msgManagedNeedsOperator
+}
+
// 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 {
@@ -324,7 +344,8 @@ func (s *Server) prepareManagedFleet(ctx context.Context, op managedOp, boxes []
// boxes are released; every other error stays a retryable failure.
func (s *Server) managedCredentialRefusal(ctx context.Context, op managedOp, err error) error {
if errors.Is(err, errManagedNeedsOperator) {
- if e := s.store.failManagedPreparation(context.WithoutCancel(ctx), op, managedReasonDeliveredKeyLive); e != nil {
+ reason, _ := managedNeedsOperatorReason(err)
+ if e := s.store.failManagedPreparation(context.WithoutCancel(ctx), op, reason); e != nil {
return e
}
}
@@ -393,11 +414,19 @@ func (s *Server) rotateManagedCredentials(ctx context.Context, fleet, account, k
return fleetstore.Credentials{}, e
}
cred, e := s.cfg.ManagedStorage.RotateFleetCredentials(ctx, fleet, keep, delivered)
- if errors.Is(e, fleetstore.ErrDeliveredKeyStillLive) {
- if _, e = s.store.db.ExecContext(ctx, `UPDATE managed_fleet_storage SET credential_state=?,credential_reason=? WHERE fleet=? AND account=?`, managedNeedsOperator, managedReasonDeliveredKeyLive, fleet, account); e != nil {
+ var stuck error
+ switch {
+ case errors.Is(e, fleetstore.ErrDeliveredKeyStillLive):
+ stuck = errManagedNeedsOperator
+ case keep != "" && errors.Is(e, fleetstore.ErrKeepKeyMissing):
+ stuck = errManagedKeepKeyMissing
+ }
+ if stuck != nil {
+ reason, _ := managedNeedsOperatorReason(stuck)
+ if _, e = s.store.db.ExecContext(ctx, `UPDATE managed_fleet_storage SET credential_state=?,credential_reason=? WHERE fleet=? AND account=?`, managedNeedsOperator, reason, fleet, account); e != nil {
return fleetstore.Credentials{}, e
}
- return fleetstore.Credentials{}, errManagedNeedsOperator
+ return fleetstore.Credentials{}, stuck
}
if e != nil || cred.ID == "" || len(cred.Secret) == 0 {
return fleetstore.Credentials{}, errManagedPreparation
@@ -434,7 +463,8 @@ func (s *Server) managedRecheckCredentials(ctx context.Context, fleet, account s
defer cancel()
_, e = s.rotateManagedCredentials(call, fleet, account, keep, seal)
if errors.Is(e, errManagedNeedsOperator) {
- return managedRefusal(409, msgManagedNeedsOperator, "")
+ _, msg := managedNeedsOperatorReason(e)
+ return managedRefusal(409, msg, "")
}
return e
}
diff --git a/internal/console/managedstore.go b/internal/console/managedstore.go
index d49b65427..c6e9defa0 100644
--- a/internal/console/managedstore.go
+++ b/internal/console/managedstore.go
@@ -55,6 +55,12 @@ type managedBox struct {
// Boot is frozen in the reserved-to-launching commit and never changes:
// every launch retry renders the same user data from it.
Boot managedboot.Frozen `json:"boot"`
+ // BootDiagnosed records, before the call, the one console-output read a
+ // box that missed its readiness deadline gets; BootBreadcrumbs holds the
+ // sanitized breadcrumb codes that read returned (newline-separated,
+ // fixed codes only). Both are set once.
+ BootDiagnosed bool `json:"boot_diagnosed,omitempty"`
+ BootBreadcrumbs string `json:"boot_breadcrumbs,omitempty"`
}
type managedRequest struct {
@@ -422,6 +428,9 @@ func (s *Store) AdvanceManagedBox(ctx context.Context, before, after managedBox)
if before.Boot.IsZero() && !after.Boot.IsZero() && (!before.LaunchStartedAt.IsZero() || after.LaunchStartedAt.IsZero() || after.Boot.Validate() != nil) {
return false, errors.New("managed boot inputs are frozen only at launch")
}
+ if before.BootDiagnosed && !after.BootDiagnosed || before.BootBreadcrumbs != "" && before.BootBreadcrumbs != after.BootBreadcrumbs || after.BootBreadcrumbs != "" && !after.BootDiagnosed {
+ return false, errors.New("managed boot diagnostics are recorded once")
+ }
if before.CloudID != "" && before.CloudID != after.CloudID {
return false, errors.New("managed cloud identity is immutable")
}
diff --git a/internal/console/managedview.go b/internal/console/managedview.go
index ddc475341..a70c9ca76 100644
--- a/internal/console/managedview.go
+++ b/internal/console/managedview.go
@@ -5,6 +5,9 @@ import (
"database/sql"
"log"
"net/http"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/managedboot"
)
type managedCheck struct {
@@ -18,6 +21,9 @@ type fleetShowBox struct {
Version string `json:"version"`
LastError string `json:"last_error"`
Checks map[string]managedCheck `json:"checks"`
+ // Boot explains how far a box that missed its readiness deadline got,
+ // from the last breadcrumb its console output carried. Managed only.
+ Boot string `json:"boot,omitempty"`
}
type fleetShowPlan struct {
@@ -170,7 +176,35 @@ func (s *Server) managedFleetView(ctx context.Context, account, name string, sel
if checks == nil {
checks = map[string]managedCheck{}
}
- out.Boxes = append(out.Boxes, fleetShowBox{Label: b.Label, State: state, Version: b.ObservedVersion, LastError: b.LastError, Checks: checks})
+ out.Boxes = append(out.Boxes, fleetShowBox{Label: b.Label, State: state, Version: b.ObservedVersion, LastError: b.LastError, Checks: checks, Boot: managedBootShow(b)})
}
return out, nil
}
+
+// managedBootShow is show's sentence for b's last boot breadcrumb, once the
+// one console-output read has happened; "" before that.
+func managedBootShow(b managedBox) string {
+ if !b.BootDiagnosed {
+ return ""
+ }
+ last := b.BootBreadcrumbs
+ if i := strings.LastIndexByte(last, '\n'); i >= 0 {
+ last = last[i+1:]
+ }
+ if text, ok := managedBootText[last]; ok {
+ return text
+ }
+ return managedBootNoProgress
+}
+
+// COPY: boot progress sentences await controller copy review.
+const managedBootNoProgress = "the box left no boot progress on its console" // COPY
+
+var managedBootText = map[string]string{
+ managedboot.CodeSeedVerified: "the box verified its first binary but did not start enrolling", // COPY
+ managedboot.CodeEnrolPending: "the box was still waiting to enrol with the console", // COPY
+ managedboot.CodeEnrolFailed: "the box could not enrol with the console", // COPY
+ managedboot.CodeStableVerified: "the box installed the current release but did not start joining", // COPY
+ managedboot.CodeJoining: "the box started joining its fleet but did not pass its readiness checks", // COPY
+ managedboot.CodeBootstrapFailed: "the box could not verify or install its release", // COPY
+}
diff --git a/internal/console/managedworker.go b/internal/console/managedworker.go
index b001a48a1..afefd7aa6 100644
--- a/internal/console/managedworker.go
+++ b/internal/console/managedworker.go
@@ -11,6 +11,7 @@ import (
"errors"
"log"
"os"
+ "strings"
"sync"
"time"
@@ -577,6 +578,14 @@ func (s *Server) launchManagedBox(ctx context.Context, b managedBox, now time.Ti
next.State = "terminated"
next.LastError = "managed_launch_rejected"
return s.saveManagedBox(ctx, b, next, now)
+ case errors.Is(launchErr, compute.ErrLaunchNotSent) && firstDispatch:
+ // The request was never dispatched and nothing came before it
+ // (2b-1 carry C1): no instance can exist, so the quota is released.
+ // After any possible earlier dispatch it stays ambiguity (below).
+ next := b
+ next.State = "terminated"
+ next.LastError = "managed_launch_not_sent"
+ return s.saveManagedBox(ctx, b, next, now)
case errors.Is(launchErr, compute.ErrLaunchRejected):
return s.failManagedBoxHeld(ctx, b, "managed_launch_uncertain", now)
case launchErr != nil:
@@ -688,6 +697,9 @@ func (s *Server) cleanupManagedBox(ctx context.Context, b managedBox, now time.T
if s.cfg.ManagedCompute == nil {
return s.managedRetry(ctx, b, "managed_provider_unavailable", now, true)
}
+ if b, err = s.recordManagedBreadcrumbs(ctx, b, now); err != nil {
+ return err
+ }
var found []compute.Instance
var findErr error
if err = s.managedOutsideLock(ctx, b, func(c context.Context) { found, findErr = s.findManagedBox(c, b) }); err != nil {
@@ -779,6 +791,73 @@ func (s *Server) cleanupManagedBox(ctx context.Context, b managedBox, now time.T
next.TerminateSentAt = now
return s.saveManagedBox(ctx, b, next, now)
}
+
+// managedBreadcrumbsWanted reports whether b is a launched box that missed
+// its readiness deadline and has not had its one console-output read.
+func managedBreadcrumbsWanted(b managedBox) bool {
+ return b.State == "failed" && b.LastError == "managed_readiness_timeout" && b.CloudID != "" && !b.BootDiagnosed && !b.TerminationConfirmed && b.TerminateAttemptedAt.IsZero()
+}
+
+// recordManagedBreadcrumbs is the only ConsoleOutput call site. Inside the
+// cleanup step, before termination, a box that missed its readiness
+// deadline gets exactly one read: the intent is committed first, so a crash
+// or a failed read never leads to a second one. The call runs outside the
+// fleet lock, and only the fixed breadcrumb codes are kept (the provider
+// already sanitizes; this keeps the console's own copy just as narrow).
+// A failed read records nothing more; cleanup continues either way.
+func (s *Server) recordManagedBreadcrumbs(ctx context.Context, b managedBox, now time.Time) (managedBox, error) {
+ if !managedBreadcrumbsWanted(b) {
+ return b, nil
+ }
+ next := b
+ next.BootDiagnosed = true
+ if err := s.saveManagedBox(ctx, b, next, now); err != nil {
+ return b, err
+ }
+ b, err := s.loadManagedBox(ctx, b)
+ if err != nil {
+ return b, err
+ }
+ var out string
+ var outErr error
+ if err = s.managedOutsideLock(ctx, b, func(c context.Context) { out, outErr = s.cfg.ManagedCompute.ConsoleOutput(c, b.Region, b.CloudID) }); err != nil {
+ return b, err
+ }
+ codes := managedBreadcrumbCodes(out)
+ if outErr != nil || codes == "" {
+ return b, nil
+ }
+ next = b
+ next.BootBreadcrumbs = codes
+ if err = s.saveManagedBox(ctx, b, next, now); err != nil {
+ return b, err
+ }
+ return s.loadManagedBox(ctx, b)
+}
+
+// managedBreadcrumbLimit matches the provider sanitizer's line bound.
+const managedBreadcrumbLimit = 32
+
+var managedBreadcrumbKnown = map[string]bool{
+ managedboot.CodeSeedVerified: true, managedboot.CodeEnrolPending: true, managedboot.CodeEnrolFailed: true,
+ managedboot.CodeStableVerified: true, managedboot.CodeJoining: true, managedboot.CodeBootstrapFailed: true,
+}
+
+// managedBreadcrumbCodes keeps the last managedBreadcrumbLimit lines of out
+// that are exactly a known code, joined by newlines.
+func managedBreadcrumbCodes(out string) string {
+ var codes []string
+ for _, line := range strings.Split(out, "\n") {
+ if managedBreadcrumbKnown[line] {
+ codes = append(codes, line)
+ }
+ }
+ if len(codes) > managedBreadcrumbLimit {
+ codes = codes[len(codes)-managedBreadcrumbLimit:]
+ }
+ return strings.Join(codes, "\n")
+}
+
func managedReadyKey(b managedBox) string {
return "fleets/" + b.Fleet + "/boxes/" + b.Label + "/ready.json"
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 00e5e08b0..fc94aeb19 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2310,9 +2310,21 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
if cfg.Releases != nil {
s.geoip = newGeoipPublisher(cfg.Releases, cfg.GeoipStagingDir)
}
+ s.managedExtra = managedExtraFor(s)
return s, nil
}
+// managedExtraFor is the storage and router readiness bridge, built from
+// the live server it probes for. With no hub host there is nothing to probe
+// through, and the result is a true nil interface (never a typed nil), so
+// both checks stay pending.
+func managedExtraFor(s *Server) managedExtraChecks {
+ if s.cfg.TunnelHost == "" {
+ return nil
+ }
+ return newManagedProbeChecks(s)
+}
+
// PublishMovesConsole writes control/moves-console.json: the moves
// protocol this console speaks and the fingerprint of its
// CARLOS_SECRETS_PUBKEY (empty when unset), so a box can check the console
diff --git a/internal/fleetstore/fake.go b/internal/fleetstore/fake.go
index c57cc1817..83ad9c7bb 100644
--- a/internal/fleetstore/fake.go
+++ b/internal/fleetstore/fake.go
@@ -58,7 +58,7 @@ func (f *Fake) RotateFleetCredentials(ctx context.Context, fleet, keep string, d
}
}
if keep != "" && !keys[keep] {
- return Credentials{}, errors.New("fleet credential to keep not found")
+ return Credentials{}, ErrKeepKeyMissing
}
if keys == nil {
keys = make(map[string]bool)
diff --git a/internal/fleetstore/provisioner.go b/internal/fleetstore/provisioner.go
index f1c137014..748635c98 100644
--- a/internal/fleetstore/provisioner.go
+++ b/internal/fleetstore/provisioner.go
@@ -9,6 +9,12 @@ import (
// minted, while a delivered key other than keep still exists.
var ErrDeliveredKeyStillLive = errors.New("delivered key still live")
+// ErrKeepKeyMissing refuses a rotation, before any key is removed or minted,
+// when a complete key listing succeeded and the nonempty keep key is not in
+// it: the key boxes use was deleted outside the console. Only a listing that
+// proves absence returns it; a failed or partial listing is another error.
+var ErrKeepKeyMissing = errors.New("key to keep does not exist")
+
type Credentials struct {
ID string `json:"id"`
Secret []byte `json:"secret"`
@@ -20,6 +26,8 @@ type Provisioner interface {
// RotateFleetCredentials keeps keep, removes every other key and mints
// one. delivered is every key ID ever handed to a box; if any of them
// other than keep still exists it returns ErrDeliveredKeyStillLive and
- // changes nothing. Implementations check a complete key listing.
+ // changes nothing. If keep is nonempty and a complete listing proves it
+ // absent it returns ErrKeepKeyMissing and changes nothing.
+ // Implementations check a complete key listing.
RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (Credentials, error)
}
diff --git a/internal/provision/managed_fleets_2b2_census_test.go b/internal/provision/managed_fleets_2b2_census_test.go
index c4d24358a..e2060783b 100644
--- a/internal/provision/managed_fleets_2b2_census_test.go
+++ b/internal/provision/managed_fleets_2b2_census_test.go
@@ -69,13 +69,20 @@ package provision
// hub's channel attestation from demo requests (two names added to its
// header scrub list); its gzip-pool Put is unchanged. Witnessed by
// TestFleetProbeAuth.
+//
+// Task 6 adds no record write and re-pins NewServer:
+// - NewServer sets managedExtra to the storage and router probe bridge
+// built from the live server (managedExtraFor), nil without a hub host.
+// The bridge only signs and POSTs probes to the hub and reads SQL and
+// the registry; it writes no SQL row, store object or record. The
+// instances literal stays key-site. Witnessed by TestManagedExtraWired.
func managedFleets2b2WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), managedFleets2b1WriteCensusInventory()...)
entries = append(entries, censusEntry{"internal/managedboot/hostenv.go", "ManagedHostEnv", "key-site", "lit:instances", "475c33aef5f55a5ffcaa97f8caa8eb30b0027a0d19486e88f1980909e468b5f5"})
entries = append(entries, censusEntry{"internal/host/managedkey.go", "ensureFleetKey", "nonrecord", "sel:Put", "2c319a1f3d4c4920f120b91e1b9f5063257225d161399934160d08a23c6b9984"})
entries = append(entries, censusEntry{"internal/host/managedprobe.go", "managedProber.challenge", "nonrecord", "sel:Put", "53a26637a4adf4b07a8f5aace39443f5b1abe83226b5ed1f498c9d4a327184d2"})
repins := []censusEntry{
- {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "30ef695663c7c0807d1dd8c20e66c32adb9a607d40ec6e30624c6ca403cee281"},
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "06f2a8d34b558ca67274496f5fb2baddcdae3fdc6d2edb1a496b10c330d8246e"},
{"internal/console/managedworker.go", "Server.managedPublishFresh", "nonrecord", "sel:Put", "a9345cd73b16e931e72637adf34274479ce2c7ad001eb8d53d088844a8af9c53"},
{"internal/provision/reconcile.go", "Reconcile", "key-site", "key:RecordKey", "5da0a14b597609fa3d212c7e79a3d2895426e238cace01b5770653d9ab9e97fe"},
{"internal/provision/sidecar_reconcile.go", "ReconcileSidecars", "key-site", "key:ParseSidecarKey,key:SidecarRecordKey,lit:sidecars", "5e3401e3cb68a5bd7688a0e53aa0791fa5ac54b4d14bcd7bcc6cd3daf521db5e"},
diff --git a/internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv b/internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv
index 8fa128e65..9c05c56b3 100644
--- a/internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv
+++ b/internal/provision/testdata/plan14-root-reads-managed-fleets-2b2.tsv
@@ -110,7 +110,7 @@ internal/managedboot/cloudinit_v1.sh.tmpl external legacy accepted-legacy accept
internal/managedboot/identity_linux.go readRootOwned legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=the O_NOFOLLOW openat walk moved out of loadIdentity unchanged (every component owned by the expected uid, not g/o writable; regular, nlink 1, size cap), parameterised by path and limit; callers: loadIdentity (/etc/carlos/managed-box.json, 4 KiB) and loadKeyStatus (/etc/carlos/managed-key-status.json, 1 KiB) file:Fstat@775,file:Open@130,file:Openat@532,file:ReadAll@1099 3f2a099882de9ffaac6189a3a844f3a3026cf02398ed7d6d247ae9461de29a09
internal/managedboot/probe.go NewProbeNonce legacy accepted-legacy accepted-legacy;rev3=census-ruling-managed-fleets-2b2;basis=new: 32 bytes from crypto/rand, hex; no file read file:Read@76 9cda7dd058dd62cc5928b9c7c58f0d66a1ea59c4cd023e0fb50b63c3d0917b18
internal/host/namedrecovery_pass.go namedUnitRecovery.passOption authority B3,E1 Production recovery wrapper preserves main exit status for per-host failures; only remaining named routes can probe the census for history selection. Ordinary routes make no census or binding-store reads. Fixtures: TestPlan14ERecoveryOrdinaryPass, TestPlan14Fix4AdoptPerHostFailureExitsZero, TestPlan14Fix5MainEquivalence.;rev3=census-ruling-managed-fleets-2b2;basis=asks refusedByGate before recover; on refusal recovers nothing; the whole:Route site is the route handed to refusedByGate for its log line, no new read registry:Host@333,registry:Host@557,registry:Unit@510,registry:Unit@527,whole:Route@273,whole:Route@470,whole:Route@502 3e50e426466ebfd148adea21d70fba68fa86cf5d9e4d226953f6fe4abe3a5ea5
-@coverage . 1dcaf53ecd6db0cc4870833eda8d18c2a1604e48c316e16eb153f80f612daefb
+@coverage . 98732a5cd3008a88366bff6577e3148ec514d72bf960dfa2fe5c7ed0b5369bbd
@coverage internal/appconfig 7238cd97ab717ace4651cd2fbf236b8c923e76d5bddfd5235d7ed0d11d1bf325
@coverage internal/edge eae9918f14a21f508008346a242692364b29b5aeb67bb6dd64f6496034f5623b
@coverage internal/host 02ed999cc2400765c0820d2aa5152f13d8ef687d88f597798e5358438931eb2d