carlos / platform Public

test: prove managed fleet AWS recovery and isolation contracts

Task 7 of plan 2b-1 (#457 phase 2): composition, budget, disabled-state
and secret-surface proofs across the slice. Tests only; no production
change and no provider wiring.

- awsmanaged integration_test.go (external package): the real
  constructors through rootaws, seen only through compute.Provisioner and
  fleetstore.Provisioner, over one stateful wire-level EC2/S3/IAM
  stand-in. A lost RunInstances reply is recovered by paged discovery as
  the same instance; the frozen request bytes stay identical across
  adapter reconstruction; a token conflict is never a rejection; lost
  CreateBucket and CreateAccessKey replies recover; a live delivered key
  refuses before any reap or mint; no recoverable secret API; sentinels
  stay out of errors, diagnostics, logs and other requests.
- TestManaged2B1RecoveryMatrix: DB reopen after ambiguous launch,
  termination and publication; alias cap and replay; prepared error
  clearing, all observed through API show.
- TestManaged2B1Budget: 1/10/100 settled boxes (with needs-operator),
  follow polls, enrolled and delayed-publication read rates; no
  ListDeployment or ConsoleOutput caller.
- TestManaged2B1Disabled: no production provider wiring or adapter
  import; off or missing providers refuse; frozen work recovers with
  injected fakes; host claim refuses; BYO and app-store policy unchanged.
- TestManaged2B1SecretSurfaces: the console half of the secret proof;
  the enrolled credential stays id/secret.

This is a composed proof, not a real box, real IAM enforcement or
public-serving acceptance.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e7dc60107674105fd4ca41fe60e00c4a2081aec7 parent d137d10
4 files changed, +1,799 −0
  • internal/awsmanaged/integration_test.go +951 −0
  • internal/console/managed_e2e_test.go +421 −0
  • internal/console/managedbudget_test.go +218 −0
  • internal/console/managedrecovery_test.go +209 −0
diff --git a/internal/awsmanaged/integration_test.go b/internal/awsmanaged/integration_test.go
new file mode 100644
index 000000000..4c330a56f
--- /dev/null
+++ b/internal/awsmanaged/integration_test.go
@@ -0,0 +1,951 @@
+package awsmanaged_test
+
+// The adapters composed as the console uses them: the real constructors
+// (through rootaws), seen only through the provider-neutral contracts, with
+// every byte through one stateful wire-level stand-in for EC2, S3 and IAM.
+// This proves request and classification behaviour across adapter
+// reconstruction. It is not a real box, real IAM enforcement or a live
+// AWS answer; the console's durable lifecycle is proved separately in
+// internal/console with the same contracts.
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "maps"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/awsmanaged"
+ "github.com/carlosframework/platform/internal/compute"
+ "github.com/carlosframework/platform/internal/fleetstore"
+)
+
+const (
+ itAccount = "123456789012"
+ itRegion = "eu-west-1"
+ itDeployment = "production"
+ itFleet = "shop"
+ itImage = "ami-0123456789abcdef0"
+ itSubnet = "subnet-0123456789abcdef0"
+ itSG = "sg-0123456789abcdef0"
+ itUserPath = "/carlos-managed-fleet/"
+ itBoundary = "arn:aws:iam::" + itAccount + ":policy/carlos-managed-fleet-boundary"
+ itPrefix = "carlos-fleet-"
+
+ // Sentinels: what a box's user data, its serial console and AWS error
+ // messages may carry. None may leave the adapter.
+ itToken = "enrol-token-SENTINEL-7f3a9c"
+ itPrivateKey = "-----BEGIN PRIVATE KEY-----PRIVKEY-SENTINEL-41d2-----END PRIVATE KEY-----"
+ itAWSMessage = "aws-message-SENTINEL-echo"
+ itSecretMark = "SECRETSENTINEL"
+)
+
+func itIdentity() compute.Identity {
+ return compute.Identity{Deployment: itDeployment, Fleet: itFleet, Label: "box-1", Operation: "0123456789abcdef0123456789abcdef"}
+}
+
+func itSpec() compute.LaunchSpec {
+ return compute.LaunchSpec{
+ Identity: itIdentity(), Region: itRegion, InstanceType: "t4g.small", Image: itImage, Subnet: itSubnet,
+ SecurityGroups: []string{itSG}, RootGB: 20, ClientToken: "carlos-0123456789abcdef0123456789abcdef-1",
+ UserData: `{"token":"` + itToken + `","key":"` + itPrivateKey + `"}`,
+ }
+}
+
+func itComputeConfig() awsmanaged.ComputeConfig {
+ return awsmanaged.ComputeConfig{Deployment: itDeployment, AccountID: itAccount, Regions: []string{itRegion}}
+}
+
+func itStorageConfig() awsmanaged.StorageConfig {
+ return awsmanaged.StorageConfig{Deployment: itDeployment, AccountID: itAccount, IAMRegion: "us-east-1", BucketPrefix: itPrefix,
+ UserPath: itUserPath, BoundaryARN: itBoundary, Regions: []string{itRegion}}
+}
+
+// itEnv keeps the SDK off every ambient credential, profile and file.
+// Metadata stays enabled in the environment: the test constructors must
+// switch it off in process.
+func itEnv(t *testing.T) {
+ none := filepath.Join(t.TempDir(), "none")
+ for k, v := range map[string]string{"AWS_EC2_METADATA_DISABLED": "false", "AWS_PROFILE": "", "AWS_DEFAULT_PROFILE": "", "AWS_ACCESS_KEY_ID": "",
+ "AWS_SECRET_ACCESS_KEY": "", "AWS_SESSION_TOKEN": "", "AWS_CONFIG_FILE": none, "AWS_SHARED_CREDENTIALS_FILE": none,
+ "AWS_REGION": "ap-south-1", "AWS_DEFAULT_REGION": "ap-south-1"} {
+ t.Setenv(k, v)
+ }
+}
+
+type itInstance struct {
+ id, state string
+ tags [][2]string
+ form string
+}
+
+type itBucket struct {
+ region string
+ tags [][2]string
+ conf map[string][]byte // versioning, encryption, publicAccessBlock, lifecycle: last PUT body
+}
+
+type itKey struct {
+ id, status string
+ n int
+}
+
+type itUser struct {
+ path, boundary string
+ inline map[string]string
+ keys []itKey
+}
+
+type itFault struct {
+ status int
+ code string
+}
+
+// awsWorld is one account's EC2, S3 and IAM as seen over HTTP. It keeps
+// state across adapter reconstruction, answers in each service's wire
+// shape, and records every request and response so tests can say where a
+// byte travelled. Every error message echoes the sentinels, as AWS errors
+// can echo request content.
+type awsWorld struct {
+ t *testing.T
+ mu sync.Mutex
+
+ instances []*itInstance
+ tokens map[string]*itInstance
+ runForms []string
+ // splitPages answers every filtered DescribeInstances with an empty
+ // first page, then one reservation per page.
+ splitPages bool
+ failPage int // a DescribeInstances request for this page (1-based) is refused
+ console string
+ lose map[string]bool // the call takes effect, then its reply is lost
+ fail map[string]itFault
+ calls map[string]int
+ describeIDs []string // NextToken of each DescribeInstances request
+
+ buckets map[string]*itBucket
+ users map[string]*itUser
+ nextKey int
+ secrets map[string]string // key ID -> minted secret
+
+ requests []string // method, URL, headers and body of every request
+ responses []string // every response body, by request
+ actions []string // action or S3 operation of every request
+ mutations int // state changes (create, put, delete, launch, terminate)
+}
+
+func newAWSWorld(t *testing.T) *awsWorld {
+ return &awsWorld{t: t, tokens: map[string]*itInstance{}, lose: map[string]bool{}, fail: map[string]itFault{}, calls: map[string]int{},
+ buckets: map[string]*itBucket{}, users: map[string]*itUser{}, secrets: map[string]string{}}
+}
+
+func itReply(status int, body string) *http.Response {
+ return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"text/xml;charset=UTF-8"}}, Body: io.NopCloser(strings.NewReader(body))}
+}
+
+func (w *awsWorld) message() string {
+ return itAWSMessage + " " + itToken + " " + itPrivateKey + " " + strings.Join(slices.Sorted(maps.Values(w.secrets)), " ")
+}
+
+func (w *awsWorld) ec2Error(status int, code string) *http.Response {
+ return itReply(status, `<Response><Errors><Error><Code>`+code+`</Code><Message>`+xmlText(w.message())+`</Message></Error></Errors><RequestID>req</RequestID></Response>`)
+}
+
+func (w *awsWorld) s3Error(status int, code string) *http.Response {
+ return itReply(status, `<?xml version="1.0" encoding="UTF-8"?><Error><Code>`+code+`</Code><Message>`+xmlText(w.message())+`</Message><RequestId>r</RequestId></Error>`)
+}
+
+func (w *awsWorld) iamError(status int, code string) *http.Response {
+ return itReply(status, `<ErrorResponse><Error><Type>Sender</Type><Code>`+code+`</Code><Message>`+xmlText(w.message())+`</Message></Error><RequestId>r</RequestId></ErrorResponse>`)
+}
+
+func xmlText(s string) string {
+ var b bytes.Buffer
+ for _, r := range s {
+ switch r {
+ case '<':
+ b.WriteString("&lt;")
+ case '>':
+ b.WriteString("&gt;")
+ case '&':
+ b.WriteString("&amp;")
+ default:
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+// Do routes by host. Anything outside the three services is refused and
+// fails the test: every destination, IAM included, is intercepted.
+func (w *awsWorld) Do(r *http.Request) (*http.Response, error) {
+ var body []byte
+ if r.Body != nil {
+ body, _ = io.ReadAll(r.Body)
+ }
+ if !strings.HasPrefix(r.Header.Get("Authorization"), "AWS4-HMAC-SHA256 Credential=AKIDTEST/") {
+ w.t.Errorf("request to %s signed with %q", r.URL.Host, r.Header.Get("Authorization"))
+ }
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ var head bytes.Buffer
+ _ = r.Header.Write(&head)
+ w.requests = append(w.requests, r.Method+" "+r.URL.String()+"\n"+head.String()+"\n"+string(body))
+ var resp *http.Response
+ var action string
+ lost := false
+ switch host := r.URL.Host; {
+ case host == "ec2."+itRegion+".amazonaws.com":
+ form := parseForm(w.t, body)
+ action = form.Get("Action")
+ resp, lost = w.ec2(form)
+ case host == "iam.amazonaws.com":
+ form := parseForm(w.t, body)
+ action = form.Get("Action")
+ resp, lost = w.iam(form)
+ case strings.HasSuffix(host, ".s3."+itRegion+".amazonaws.com"):
+ bucket := strings.TrimSuffix(host, ".s3."+itRegion+".amazonaws.com")
+ action, resp, lost = w.s3(r, bucket, body)
+ default:
+ w.t.Errorf("request outside EC2, S3 and IAM: %s %s", r.Method, r.URL)
+ return nil, errors.New("blocked")
+ }
+ w.actions = append(w.actions, action)
+ w.calls[action]++
+ raw, _ := io.ReadAll(resp.Body)
+ resp.Body = io.NopCloser(bytes.NewReader(raw))
+ w.responses = append(w.responses, string(raw))
+ if lost {
+ return nil, errors.New("connection reset by peer")
+ }
+ return resp, nil
+}
+
+func parseForm(t *testing.T, body []byte) url.Values {
+ form, err := url.ParseQuery(string(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return form
+}
+
+var itStateCodes = map[string]string{"pending": "0", "running": "16", "shutting-down": "32", "terminated": "48"}
+
+func (w *awsWorld) instanceXML(in *itInstance) string {
+ var tags strings.Builder
+ for _, kv := range in.tags {
+ tags.WriteString(`<item><key>` + kv[0] + `</key><value>` + kv[1] + `</value></item>`)
+ }
+ return `<item><instanceId>` + in.id + `</instanceId><instanceState><code>` + itStateCodes[in.state] + `</code><name>` + in.state + `</name></instanceState>` +
+ `<placement><availabilityZone>` + itRegion + `a</availabilityZone></placement><launchTime>2026-11-08T12:00:00.000Z</launchTime><tagSet>` + tags.String() + `</tagSet></item>`
+}
+
+func (w *awsWorld) reservationXML(in *itInstance) string {
+ return `<item><reservationId>r-` + in.id[2:] + `</reservationId><ownerId>` + itAccount + `</ownerId><instancesSet>` + w.instanceXML(in) + `</instancesSet></item>`
+}
+
+func (in *itInstance) tag(k string) (string, bool) {
+ for _, kv := range in.tags {
+ if kv[0] == k {
+ return kv[1], true
+ }
+ }
+ return "", false
+}
+
+func (w *awsWorld) byID(id string) *itInstance {
+ for _, in := range w.instances {
+ if in.id == id {
+ return in
+ }
+ }
+ return nil
+}
+
+func indexed(form url.Values, prefix string) []string {
+ var out []string
+ for i := 1; form.Has(prefix + strconv.Itoa(i)); i++ {
+ out = append(out, form.Get(prefix+strconv.Itoa(i)))
+ }
+ return out
+}
+
+func (w *awsWorld) ec2(form url.Values) (*http.Response, bool) {
+ action := form.Get("Action")
+ if f, ok := w.fail[action]; ok {
+ return w.ec2Error(f.status, f.code), false
+ }
+ switch action {
+ case "DescribeImages":
+ return itReply(200, `<DescribeImagesResponse><requestId>req</requestId><imagesSet><item><imageId>`+itImage+`</imageId>`+
+ `<imageState>available</imageState><architecture>arm64</architecture><rootDeviceType>ebs</rootDeviceType><rootDeviceName>/dev/sda1</rootDeviceName>`+
+ `<blockDeviceMapping><item><deviceName>/dev/sda1</deviceName><ebs><snapshotId>snap-0123456789abcdef0</snapshotId><volumeSize>8</volumeSize></ebs></item></blockDeviceMapping>`+
+ `</item></imagesSet></DescribeImagesResponse>`), false
+ case "RunInstances":
+ norm := form.Encode()
+ w.runForms = append(w.runForms, norm)
+ token := form.Get("ClientToken")
+ in := w.tokens[token]
+ switch {
+ case in != nil && in.form != norm:
+ return w.ec2Error(400, "IdempotentParameterMismatch"), false
+ case in == nil:
+ in = &itInstance{id: fmt.Sprintf("i-%017x", 0xabc000+len(w.instances)), state: "pending", form: norm}
+ for i := 1; form.Has(fmt.Sprintf("TagSpecification.1.Tag.%d.Key", i)); i++ {
+ in.tags = append(in.tags, [2]string{form.Get(fmt.Sprintf("TagSpecification.1.Tag.%d.Key", i)), form.Get(fmt.Sprintf("TagSpecification.1.Tag.%d.Value", i))})
+ }
+ w.instances = append(w.instances, in)
+ w.tokens[token] = in
+ w.mutations++
+ }
+ return itReply(200, `<RunInstancesResponse><requestId>req</requestId><reservationId>r-1</reservationId><ownerId>`+itAccount+`</ownerId><instancesSet>`+
+ w.instanceXML(in)+`</instancesSet></RunInstancesResponse>`), w.lose[action]
+ case "DescribeInstances":
+ next := form.Get("NextToken")
+ w.describeIDs = append(w.describeIDs, next)
+ page := 0
+ if next != "" {
+ page, _ = strconv.Atoi(strings.TrimPrefix(next, "page-"))
+ }
+ if w.failPage != 0 && page+1 == w.failPage {
+ return w.ec2Error(403, "UnauthorizedOperation"), false
+ }
+ var match []*itInstance
+ if ids := indexed(form, "InstanceId."); len(ids) > 0 {
+ for _, id := range ids {
+ in := w.byID(id)
+ if in == nil {
+ return w.ec2Error(400, "InvalidInstanceID.NotFound"), false
+ }
+ match = append(match, in)
+ }
+ } else {
+ for _, in := range w.instances {
+ ok := true
+ for i := 1; form.Has(fmt.Sprintf("Filter.%d.Name", i)); i++ {
+ key, _ := strings.CutPrefix(form.Get(fmt.Sprintf("Filter.%d.Name", i)), "tag:")
+ v, has := in.tag(key)
+ ok = ok && has && slices.Contains(indexed(form, fmt.Sprintf("Filter.%d.Value.", i)), v)
+ }
+ if ok {
+ match = append(match, in)
+ }
+ }
+ }
+ var res strings.Builder
+ token := ""
+ if w.splitPages && len(indexed(form, "InstanceId.")) == 0 {
+ // Page 0 is empty; page n holds match[n-1].
+ if page > 0 && page <= len(match) {
+ res.WriteString(w.reservationXML(match[page-1]))
+ }
+ if page < len(match) {
+ token = "page-" + strconv.Itoa(page+1)
+ }
+ } else {
+ for _, in := range match {
+ res.WriteString(w.reservationXML(in))
+ }
+ }
+ out := `<DescribeInstancesResponse><requestId>req</requestId><reservationSet>` + res.String() + `</reservationSet>`
+ if token != "" {
+ out += `<nextToken>` + token + `</nextToken>`
+ }
+ return itReply(200, out+`</DescribeInstancesResponse>`), false
+ case "TerminateInstances":
+ id := form.Get("InstanceId.1")
+ in := w.byID(id)
+ if in == nil {
+ return w.ec2Error(400, "InvalidInstanceID.NotFound"), false
+ }
+ prev := in.state
+ in.state = "shutting-down"
+ w.mutations++
+ return itReply(200, `<TerminateInstancesResponse><requestId>req</requestId><instancesSet><item><instanceId>`+id+`</instanceId>`+
+ `<currentState><code>32</code><name>shutting-down</name></currentState><previousState><code>`+itStateCodes[prev]+`</code><name>`+prev+`</name></previousState>`+
+ `</item></instancesSet></TerminateInstancesResponse>`), w.lose[action]
+ case "GetConsoleOutput":
+ return itReply(200, `<GetConsoleOutputResponse><requestId>req</requestId><instanceId>`+form.Get("InstanceId")+`</instanceId>`+
+ `<timestamp>2026-11-08T12:00:00.000Z</timestamp><output>`+base64.StdEncoding.EncodeToString([]byte(w.console))+`</output></GetConsoleOutputResponse>`), false
+ }
+ w.t.Errorf("unexpected EC2 action %s", action)
+ return w.ec2Error(400, "UnexpectedAction"), false
+}
+
+var itTagRE = regexp.MustCompile(`<Tag><Key>([^<]*)</Key><Value>([^<]*)</Value></Tag>`)
+
+func (w *awsWorld) s3(r *http.Request, name string, body []byte) (string, *http.Response, bool) {
+ q := r.URL.Query()
+ sub := ""
+ for _, k := range []string{"location", "tagging", "versioning", "encryption", "publicAccessBlock", "lifecycle"} {
+ if q.Has(k) {
+ sub = k
+ }
+ }
+ op := r.Method + " " + sub
+ if f, ok := w.fail[op]; ok {
+ return op, w.s3Error(f.status, f.code), false
+ }
+ b := w.buckets[name]
+ if op == "PUT " {
+ if b != nil {
+ return op, w.s3Error(409, "BucketAlreadyOwnedByYou"), false
+ }
+ b = &itBucket{region: itRegion, conf: map[string][]byte{}}
+ if !bytes.Contains(body, []byte("<LocationConstraint>"+itRegion+"</LocationConstraint>")) {
+ w.t.Errorf("create without the region: %s", body)
+ }
+ for _, m := range itTagRE.FindAllSubmatch(body, -1) {
+ b.tags = append(b.tags, [2]string{string(m[1]), string(m[2])})
+ }
+ w.buckets[name] = b
+ w.mutations++
+ return op, itReply(200, ""), w.lose["CreateBucket"]
+ }
+ if r.Header.Get("X-Amz-Expected-Bucket-Owner") != itAccount {
+ w.t.Errorf("%s without the expected owner", op)
+ return op, w.s3Error(403, "AccessDenied"), false
+ }
+ if b == nil {
+ return op, w.s3Error(404, "NoSuchBucket"), false
+ }
+ switch {
+ case op == "GET location":
+ return op, itReply(200, `<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/">`+b.region+`</LocationConstraint>`), false
+ case op == "GET tagging":
+ var tags strings.Builder
+ for _, kv := range b.tags {
+ tags.WriteString(`<Tag><Key>` + kv[0] + `</Key><Value>` + kv[1] + `</Value></Tag>`)
+ }
+ return op, itReply(200, `<Tagging><TagSet>`+tags.String()+`</TagSet></Tagging>`), false
+ case r.Method == http.MethodPut && sub != "":
+ // The stored document is what the next GET answers: a readback
+ // sees exactly what the adapter wrote.
+ b.conf[sub] = body
+ w.mutations++
+ return op, itReply(200, ""), false
+ case r.Method == http.MethodGet && sub != "":
+ if raw, ok := b.conf[sub]; ok {
+ return op, itReply(200, string(raw)), false
+ }
+ switch sub {
+ case "versioning":
+ return op, itReply(200, `<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>`), false
+ case "encryption":
+ return op, w.s3Error(404, "ServerSideEncryptionConfigurationNotFoundError"), false
+ case "publicAccessBlock":
+ return op, w.s3Error(404, "NoSuchPublicAccessBlockConfiguration"), false
+ case "lifecycle":
+ return op, w.s3Error(404, "NoSuchLifecycleConfiguration"), false
+ }
+ }
+ w.t.Errorf("unexpected S3 request %s %s", r.Method, r.URL)
+ return op, w.s3Error(400, "UnexpectedRequest"), false
+}
+
+func iamOK(action, result string) *http.Response {
+ return itReply(200, `<`+action+`Response xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><`+action+`Result>`+result+`</`+action+`Result><ResponseMetadata><RequestId>r</RequestId></ResponseMetadata></`+action+`Response>`)
+}
+
+func (w *awsWorld) userXML(name string, u *itUser) string {
+ return `<User><UserName>` + name + `</UserName><Path>` + u.path + `</Path><Arn>arn:aws:iam::` + itAccount + `:user` + u.path + name + `</Arn>` +
+ `<UserId>AIDAEXAMPLE</UserId><CreateDate>2026-11-08T12:00:00Z</CreateDate><PermissionsBoundary><PermissionsBoundaryType>PermissionsBoundaryPolicy</PermissionsBoundaryType>` +
+ `<PermissionsBoundaryArn>` + u.boundary + `</PermissionsBoundaryArn></PermissionsBoundary></User>`
+}
+
+func keyMeta(user string, k itKey) string {
+ return `<member><UserName>` + user + `</UserName><AccessKeyId>` + k.id + `</AccessKeyId><Status>` + k.status + `</Status><CreateDate>2026-11-08T12:00:` +
+ fmt.Sprintf("%02d", k.n%60) + `Z</CreateDate></member>`
+}
+
+func (w *awsWorld) iam(form url.Values) (*http.Response, bool) {
+ action := form.Get("Action")
+ if f, ok := w.fail[action]; ok {
+ return w.iamError(f.status, f.code), false
+ }
+ name := form.Get("UserName")
+ u := w.users[name]
+ if action == "CreateUser" {
+ if u != nil {
+ return w.iamError(409, "EntityAlreadyExists"), false
+ }
+ u = &itUser{path: form.Get("Path"), boundary: form.Get("PermissionsBoundary"), inline: map[string]string{}}
+ w.users[name] = u
+ w.mutations++
+ return iamOK(action, w.userXML(name, u)), false
+ }
+ if u == nil {
+ return w.iamError(404, "NoSuchEntity"), false
+ }
+ switch action {
+ case "GetUser":
+ return iamOK(action, w.userXML(name, u)), false
+ case "PutUserPolicy":
+ u.inline[form.Get("PolicyName")] = form.Get("PolicyDocument")
+ w.mutations++
+ return iamOK(action, ""), false
+ case "GetUserPolicy":
+ doc, ok := u.inline[form.Get("PolicyName")]
+ if !ok {
+ return w.iamError(404, "NoSuchEntity"), false
+ }
+ return iamOK(action, `<UserName>`+name+`</UserName><PolicyName>`+form.Get("PolicyName")+`</PolicyName><PolicyDocument>`+url.PathEscape(doc)+`</PolicyDocument>`), false
+ case "ListUserPolicies":
+ var names strings.Builder
+ for _, n := range slices.Sorted(maps.Keys(u.inline)) {
+ names.WriteString(`<member>` + n + `</member>`)
+ }
+ return iamOK(action, `<PolicyNames>`+names.String()+`</PolicyNames><IsTruncated>false</IsTruncated>`), false
+ case "ListAttachedUserPolicies":
+ return iamOK(action, `<AttachedPolicies/><IsTruncated>false</IsTruncated>`), false
+ case "ListGroupsForUser":
+ return iamOK(action, `<Groups/><IsTruncated>false</IsTruncated>`), false
+ case "ListAccessKeys":
+ // One key per page: rotation must read them all.
+ i := 0
+ if m := form.Get("Marker"); m != "" {
+ i, _ = strconv.Atoi(strings.TrimPrefix(m, "m"))
+ }
+ var page, tail string
+ if i < len(u.keys) {
+ page = keyMeta(name, u.keys[i])
+ }
+ if i+1 < len(u.keys) {
+ tail = `<IsTruncated>true</IsTruncated><Marker>m` + strconv.Itoa(i+1) + `</Marker>`
+ } else {
+ tail = `<IsTruncated>false</IsTruncated>`
+ }
+ return iamOK(action, `<AccessKeyMetadata>`+page+`</AccessKeyMetadata>`+tail), false
+ case "DeleteAccessKey":
+ id := form.Get("AccessKeyId")
+ i := slices.IndexFunc(u.keys, func(k itKey) bool { return k.id == id })
+ if i < 0 {
+ return w.iamError(404, "NoSuchEntity"), false
+ }
+ u.keys = slices.Delete(u.keys, i, i+1)
+ w.mutations++
+ return iamOK(action, ""), false
+ case "CreateAccessKey":
+ w.nextKey++
+ k := itKey{id: fmt.Sprintf("AKIAFLEET%011d", w.nextKey), status: "Active", n: w.nextKey}
+ secret := fmt.Sprintf("wJalr%s%04dEXAMPLEKEY", itSecretMark, w.nextKey)
+ u.keys = append(u.keys, k)
+ w.secrets[k.id] = secret
+ w.mutations++
+ return iamOK(action, `<AccessKey><UserName>`+name+`</UserName><AccessKeyId>`+k.id+`</AccessKeyId><Status>Active</Status><SecretAccessKey>`+secret+
+ `</SecretAccessKey><CreateDate>2026-11-08T12:00:00Z</CreateDate></AccessKey>`), w.lose[action]
+ }
+ w.t.Errorf("unexpected IAM action %s", action)
+ return w.iamError(400, "UnexpectedAction"), false
+}
+
+func (w *awsWorld) snapshot() (mutations int, calls map[string]int) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.mutations, maps.Clone(w.calls)
+}
+
+func (w *awsWorld) liveKeys(t *testing.T) []string {
+ t.Helper()
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ var out []string
+ for _, u := range w.users {
+ for _, k := range u.keys {
+ out = append(out, k.id)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+func (w *awsWorld) deleteKey(id string) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ for _, u := range w.users {
+ u.keys = slices.DeleteFunc(u.keys, func(k itKey) bool { return k.id == id })
+ }
+}
+
+func newITCompute(t *testing.T, w *awsWorld) compute.Provisioner {
+ t.Helper()
+ c, err := awsmanaged.NewComputeWith(context.Background(), itComputeConfig(), w)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+func newITStorage(t *testing.T, w *awsWorld) fleetstore.Provisioner {
+ t.Helper()
+ s, err := awsmanaged.NewStorageWith(context.Background(), itStorageConfig(), w)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s
+}
+
+func itAmbiguous(t *testing.T, err error) {
+ t.Helper()
+ if err == nil || errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, compute.ErrLaunchConflict) || errors.Is(err, os.ErrNotExist) ||
+ errors.Is(err, compute.ErrIdentityMismatch) || errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) {
+ t.Fatalf("want an ambiguous error, got %v", err)
+ }
+}
+
+// TestAWSManagedAdapterRecovery: what the worker relies on after a lost
+// reply or a console restart, through the real constructors and the wire.
+func TestAWSManagedAdapterRecovery(t *testing.T) {
+ t.Run("compute", func(t *testing.T) {
+ itEnv(t)
+ w := newAWSWorld(t)
+ ctx := context.Background()
+ spec := itSpec()
+
+ // 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)
+ w.lose["RunInstances"] = false
+ if len(w.instances) != 1 || w.calls["RunInstances"] != 1 {
+ t.Fatalf("fixture: %d instances after %d launches", len(w.instances), w.calls["RunInstances"])
+ }
+ original := w.instances[0].id
+
+ // A restarted console's adapter discovers it by identity. The
+ // instance is only on the second page: a reader that stopped at the
+ // empty first page would see nothing and relaunch.
+ w.splitPages = true
+ p := newITCompute(t, w)
+ found, err := p.Find(ctx, itRegion, itIdentity())
+ if err != nil || len(found) != 1 || found[0].CloudID != original || found[0].Identity != itIdentity() {
+ t.Fatalf("discovery: %+v %v", found, err)
+ }
+ if !slices.Equal(w.describeIDs, []string{"", "page-1"}) || w.calls["RunInstances"] != 1 {
+ t.Fatalf("discovery read pages %q and launched %d times", w.describeIDs, w.calls["RunInstances"])
+ }
+
+ // A failed later page is never a usable absence.
+ w.failPage = 2
+ if got, err := newITCompute(t, w).Find(ctx, itRegion, itIdentity()); got != nil {
+ t.Fatalf("partial listing returned %+v", got)
+ } else {
+ itAmbiguous(t, err)
+ }
+ w.failPage = 0
+
+ // Discovery that lags (or a crash before it) relaunches the frozen
+ // spec under the same token: the same bytes, the same instance.
+ again, err := newITCompute(t, w).Launch(ctx, spec)
+ if err != nil || again.CloudID != original || len(w.instances) != 1 {
+ t.Fatalf("frozen relaunch: %+v %v (%d instances)", again, err, len(w.instances))
+ }
+ if len(w.runForms) != 2 || w.runForms[0] != w.runForms[1] {
+ t.Fatalf("frozen request changed across reconstruction:\n%s\n%s", w.runForms[0], w.runForms[len(w.runForms)-1])
+ }
+
+ // The same token with other parameters is a conflict, never a
+ // rejection: the original stays the only instance and still owned.
+ changed := spec
+ changed.RootGB = 30
+ _, err = newITCompute(t, w).Launch(ctx, changed)
+ if !errors.Is(err, compute.ErrLaunchConflict) || errors.Is(err, compute.ErrLaunchRejected) || len(w.instances) != 1 {
+ t.Fatalf("changed spec: %v (%d instances)", err, len(w.instances))
+ }
+ if found, err = newITCompute(t, w).Find(ctx, itRegion, itIdentity()); err != nil || len(found) != 1 || found[0].CloudID != original {
+ t.Fatalf("conflict lost the original: %+v %v", found, err)
+ }
+
+ // A lost terminate reply: the next adapter sees the instance going.
+ w.lose["TerminateInstances"] = true
+ itAmbiguous(t, newITCompute(t, w).Terminate(ctx, itRegion, original, itIdentity()))
+ w.lose["TerminateInstances"] = false
+ got, err := newITCompute(t, w).Lookup(ctx, itRegion, original)
+ if err != nil || got.CloudID != original || got.State != compute.StateShuttingDown {
+ t.Fatalf("after lost terminate reply: %+v %v", got, err)
+ }
+ // Only the exact ID's NotFound is absence.
+ if _, err = newITCompute(t, w).Lookup(ctx, itRegion, "i-0fffffffffffffff0"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("absent ID: %v", err)
+ }
+ if _, ok := p.(*awsmanaged.Compute); !ok {
+ t.Fatal("not the real adapter")
+ }
+ })
+
+ t.Run("storage", func(t *testing.T) {
+ itEnv(t)
+ w := newAWSWorld(t)
+ ctx := context.Background()
+
+ // The create reply is lost after S3 made the bucket with its tags.
+ w.lose["CreateBucket"] = true
+ _, err := newITStorage(t, w).EnsureFleetStorage(ctx, itFleet, itRegion)
+ itAmbiguous(t, err)
+ w.lose["CreateBucket"] = false
+ if len(w.buckets) != 1 || w.calls["PUT "] != 1 {
+ t.Fatalf("fixture: %d buckets after %d creates", len(w.buckets), w.calls["PUT "])
+ }
+
+ // A new adapter adopts it through its tags and finishes preparation.
+ got, err := newITStorage(t, w).EnsureFleetStorage(ctx, itFleet, itRegion)
+ if err != nil || got.Region != itRegion || w.buckets[got.Bucket] == nil || w.calls["PUT "] != 1 {
+ t.Fatalf("prepare after lost create: %+v %v (%d creates)", got, err, w.calls["PUT "])
+ }
+ b := w.buckets[got.Bucket]
+ for _, sub := range []string{"versioning", "encryption", "publicAccessBlock", "lifecycle"} {
+ if len(b.conf[sub]) == 0 {
+ t.Fatalf("bucket %s was never set", sub)
+ }
+ }
+ if len(w.users) != 1 {
+ t.Fatalf("users: %d", len(w.users))
+ }
+ for name, u := range w.users {
+ if u.path != itUserPath || u.boundary != itBoundary || len(u.inline) != 1 || len(u.keys) != 0 || !strings.HasPrefix(name, "managed-fleet-") {
+ t.Fatalf("fleet user %s: %+v", name, u)
+ }
+ }
+
+ // Preparation again, from another restart, changes nothing.
+ before, _ := w.snapshot()
+ again, err := newITStorage(t, w).EnsureFleetStorage(ctx, itFleet, itRegion)
+ if after, _ := w.snapshot(); err != nil || again != got || after != before {
+ t.Fatalf("second preparation: %+v %v, %d mutations", again, err, after-before)
+ }
+
+ // First rotation mints k1; the secret comes back from that call only.
+ k1, err := newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, "", nil)
+ if err != nil || k1.ID == "" || !strings.Contains(string(k1.Secret), itSecretMark) {
+ t.Fatalf("mint: %v", err)
+ }
+ // No recoverable secret: a restarted adapter names the key, never its secret.
+ named, err := newITStorage(t, w).FleetCredentials(ctx, itFleet)
+ if err != nil || named.ID != k1.ID || len(named.Secret) != 0 {
+ t.Fatalf("FleetCredentials: id %q, %d secret bytes, %v", named.ID, len(named.Secret), err)
+ }
+
+ // The mint reply is lost after IAM made the key. The next adapter
+ // reaps that undelivered key and keeps the delivered one.
+ w.lose["CreateAccessKey"] = true
+ _, err = newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, k1.ID, []string{k1.ID})
+ itAmbiguous(t, err)
+ w.lose["CreateAccessKey"] = false
+ if live := w.liveKeys(t); len(live) != 2 {
+ t.Fatalf("fixture: %v", live)
+ }
+ k2, err := newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, k1.ID, []string{k1.ID})
+ if err != nil || k2.ID == k1.ID || !slices.Equal(w.liveKeys(t), sortedPair(k1.ID, k2.ID)) {
+ t.Fatalf("rotation after lost mint: %v, live %v", err, w.liveKeys(t))
+ }
+
+ // k1 was delivered and is still live, and k2 is now the keep: a
+ // restarted adapter refuses before any reap or mint.
+ before, _ = w.snapshot()
+ _, err = newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, k2.ID, []string{k1.ID, k2.ID})
+ if after, _ := w.snapshot(); !errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) || after != before {
+ t.Fatalf("double loss: %v, %d mutations", err, after-before)
+ }
+ if strings.Contains(err.Error(), k1.ID) || strings.Contains(err.Error(), k2.ID) {
+ t.Fatalf("refusal names a key: %v", err)
+ }
+ // After an operator deletes k1, rotation keeps k2 and mints k3.
+ w.deleteKey(k1.ID)
+ k3, err := newITStorage(t, w).RotateFleetCredentials(ctx, itFleet, k2.ID, []string{k1.ID, k2.ID})
+ if err != nil || !slices.Equal(w.liveKeys(t), sortedPair(k2.ID, k3.ID)) {
+ t.Fatalf("after operator deletion: %v, live %v", err, w.liveKeys(t))
+ }
+
+ // Each minted secret travelled in exactly one response, its mint.
+ for id, secret := range w.secrets {
+ n := 0
+ for i, resp := range w.responses {
+ if strings.Contains(resp, secret) && !strings.Contains(w.responses[i], "<Error>") {
+ n++
+ if w.actions[i] != "CreateAccessKey" {
+ t.Fatalf("secret of %s in a %s response", id, w.actions[i])
+ }
+ }
+ }
+ if n != 1 {
+ t.Fatalf("secret of %s in %d responses", id, n)
+ }
+ }
+ })
+
+ t.Run("no recoverable secret API", func(t *testing.T) {
+ // The adapters' exported surface is exactly the contracts. Nothing
+ // lists, reads or re-derives a secret; FleetCredentials names a key.
+ for _, c := range []struct {
+ typ reflect.Type
+ iface reflect.Type
+ }{
+ {reflect.TypeFor[*awsmanaged.Compute](), reflect.TypeFor[compute.Provisioner]()},
+ {reflect.TypeFor[*awsmanaged.Storage](), reflect.TypeFor[fleetstore.Provisioner]()},
+ } {
+ var got, want []string
+ for i := 0; i < c.typ.NumMethod(); i++ {
+ got = append(got, c.typ.Method(i).Name)
+ }
+ for i := 0; i < c.iface.NumMethod(); i++ {
+ want = append(want, c.iface.Method(i).Name)
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("%v methods %v, want exactly %v", c.typ, got, want)
+ }
+ }
+ credFields := reflect.TypeFor[fleetstore.Credentials]()
+ if credFields.NumField() != 2 || credFields.Field(0).Tag.Get("json") != "id" || credFields.Field(1).Tag.Get("json") != "secret" {
+ t.Fatalf("credential wire shape changed: %v", credFields)
+ }
+ })
+}
+
+func sortedPair(a, b string) []string {
+ out := []string{a, b}
+ sort.Strings(out)
+ return out
+}
+
+// TestAWSManagedSecretSurfaces: the enrol token and private key in user
+// data, the minted secret, and every AWS error message stay out of adapter
+// errors, diagnostics, logs and every request other than their own.
+func TestAWSManagedSecretSurfaces(t *testing.T) {
+ itEnv(t)
+ var logs bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&logs)
+ defer log.SetOutput(old)
+ w := newAWSWorld(t)
+ ctx := context.Background()
+ p := newITCompute(t, w)
+ s := newITStorage(t, w)
+ var errs []error
+
+ inst, err := p.Launch(ctx, itSpec())
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Boot output carries the token, the key and near-miss breadcrumbs;
+ // only the exact known codes come back.
+ w.console = "cloud-init: token=" + itToken + "\nCARLOS_BOOT:enrol_pending\n" + itPrivateKey + "\nCARLOS_BOOT:joining " + itToken +
+ "\nCARLOS_BOOT:" + itToken + "\nCARLOS_BOOT:joining\r\n"
+ diag, err := p.ConsoleOutput(ctx, itRegion, inst.CloudID)
+ if err != nil || diag != "enrol_pending\njoining" {
+ t.Fatalf("diagnostics %q %v", diag, err)
+ }
+ if _, err = s.EnsureFleetStorage(ctx, itFleet, itRegion); err != nil {
+ t.Fatal(err)
+ }
+ cred, err := s.RotateFleetCredentials(ctx, itFleet, "", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Every failing call answers with a message that echoes the secrets.
+ for _, f := range []struct {
+ action string
+ fault itFault
+ call func() error
+ }{
+ {"DescribeImages", itFault{400, "InvalidAMIID.NotFound"}, func() error { _, err := p.Launch(ctx, itSpec()); return err }},
+ {"DescribeImages", itFault{403, "UnauthorizedOperation"}, func() error { _, err := p.Launch(ctx, itSpec()); return err }},
+ {"RunInstances", itFault{400, "InsufficientInstanceCapacity"}, func() error { _, err := p.Launch(ctx, itSpec()); return err }},
+ {"RunInstances", itFault{400, "IdempotentParameterMismatch"}, func() error { _, err := p.Launch(ctx, itSpec()); return err }},
+ {"RunInstances", itFault{403, "AuthFailure"}, func() error { _, err := p.Launch(ctx, itSpec()); return err }},
+ {"DescribeInstances", itFault{403, "UnauthorizedOperation"}, func() error { _, err := p.Find(ctx, itRegion, itIdentity()); return err }},
+ {"DescribeInstances", itFault{400, "InvalidInstanceID.NotFound"}, func() error { _, err := p.Lookup(ctx, itRegion, inst.CloudID); return err }},
+ {"DescribeInstances", itFault{400, "InvalidInstanceID.NotFound"}, func() error { return p.Terminate(ctx, itRegion, inst.CloudID, itIdentity()) }},
+ {"TerminateInstances", itFault{403, "UnauthorizedOperation"}, func() error { return p.Terminate(ctx, itRegion, inst.CloudID, itIdentity()) }},
+ {"GetConsoleOutput", itFault{403, "UnauthorizedOperation"}, func() error { _, err := p.ConsoleOutput(ctx, itRegion, inst.CloudID); return err }},
+ {"GET location", itFault{403, "AccessDenied"}, func() error { _, err := s.EnsureFleetStorage(ctx, itFleet, itRegion); return err }},
+ {"GET versioning", itFault{400, "InvalidRequest"}, func() error { _, err := s.EnsureFleetStorage(ctx, itFleet, itRegion); return err }},
+ {"GetUser", itFault{403, "AccessDenied"}, func() error { _, err := s.FleetCredentials(ctx, itFleet); return err }},
+ {"ListAccessKeys", itFault{400, "InvalidInput"}, func() error {
+ _, err := s.RotateFleetCredentials(ctx, itFleet, cred.ID, []string{cred.ID})
+ return err
+ }},
+ {"CreateAccessKey", itFault{409, "LimitExceeded"}, func() error {
+ _, err := s.RotateFleetCredentials(ctx, itFleet, cred.ID, []string{cred.ID})
+ return err
+ }},
+ } {
+ w.mu.Lock()
+ w.fail[f.action] = f.fault
+ w.mu.Unlock()
+ err := f.call()
+ w.mu.Lock()
+ delete(w.fail, f.action)
+ w.mu.Unlock()
+ if err == nil {
+ t.Fatalf("%s %s did not fail", f.action, f.fault.code)
+ }
+ errs = append(errs, err)
+ }
+ // The delivered-key refusal names no key.
+ w.mu.Lock()
+ for _, u := range w.users {
+ u.keys = append(u.keys, itKey{id: "AKIAFLEETOLDDELIVERED", status: "Inactive", n: 99})
+ }
+ w.mu.Unlock()
+ _, err = s.RotateFleetCredentials(ctx, itFleet, cred.ID, []string{"AKIAFLEETOLDDELIVERED", cred.ID})
+ if !errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) {
+ t.Fatal(err)
+ }
+ errs = append(errs, err)
+ named, err := s.FleetCredentials(ctx, itFleet)
+ if err != nil || len(named.Secret) != 0 {
+ t.Fatalf("FleetCredentials returned %d secret bytes: %v", len(named.Secret), err)
+ }
+
+ secrets := []string{itToken, itPrivateKey, "PRIVKEY-SENTINEL", itAWSMessage, string(cred.Secret), itSecretMark}
+ surfaces := map[string]string{"diagnostics": diag, "logs": logs.String()}
+ for i, err := range errs {
+ surfaces[fmt.Sprintf("error %d", i)] = err.Error()
+ if strings.Contains(err.Error(), "AKIAFLEETOLDDELIVERED") {
+ t.Errorf("error %d names a key: %v", i, err)
+ }
+ }
+ for name, text := range surfaces {
+ for _, secret := range secrets {
+ if strings.Contains(text, secret) {
+ t.Errorf("%s carries %q: %s", name, secret, text)
+ }
+ }
+ }
+ // On the wire: the token and key travel only inside RunInstances user
+ // data (base64), and no request ever carries a minted secret.
+ userData := base64.StdEncoding.EncodeToString([]byte(itSpec().UserData))
+ for i, req := range w.requests {
+ for _, secret := range []string{itToken, itPrivateKey, "PRIVKEY-SENTINEL", itSecretMark, string(cred.Secret)} {
+ if strings.Contains(req, secret) {
+ t.Errorf("%s request carries %q", w.actions[i], secret)
+ }
+ }
+ _, body, _ := strings.Cut(req, "\n\n")
+ form, _ := url.ParseQuery(body)
+ if strings.Contains(form.Get("UserData"), userData) != (w.actions[i] == "RunInstances") {
+ t.Errorf("%s request user data %q", w.actions[i], form.Get("UserData"))
+ }
+ if strings.Contains(req, userData) || strings.Contains(req, url.QueryEscape(userData)) {
+ if w.actions[i] != "RunInstances" {
+ t.Errorf("user data outside RunInstances: %s", w.actions[i])
+ }
+ }
+ }
+}
diff --git a/internal/console/managed_e2e_test.go b/internal/console/managed_e2e_test.go
index c4b01e426..2a291f14a 100644
--- a/internal/console/managed_e2e_test.go
+++ b/internal/console/managed_e2e_test.go
@@ -6,6 +6,11 @@ import (
"crypto/ed25519"
"encoding/base64"
"encoding/json"
+ "errors"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
"log"
"net/http"
"net/http/httptest"
@@ -19,6 +24,7 @@ import (
"github.com/carlosframework/platform/internal/compute"
"github.com/carlosframework/platform/internal/fleetstore"
+ "github.com/carlosframework/platform/internal/objstore"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/status"
)
@@ -414,3 +420,418 @@ func TestManagedSecretSurfaces(t *testing.T) {
}
}
}
+
+// managedProductionSources yields every non-test Go file in the module
+// outside the AWS adapter package itself.
+func managedProductionSources(t *testing.T, visit func(path string, src []byte)) {
+ t.Helper()
+ root := filepath.Join("..", "..")
+ adapter := filepath.Join(root, "internal", "awsmanaged")
+ err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ switch d.Name() {
+ case ".git", "node_modules", "testdata", "vendor":
+ return filepath.SkipDir
+ }
+ if path == adapter {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
+ return nil
+ }
+ src, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ visit(path, src)
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+// managedAppStorePolicies pins object storage's per-user inline policy, the
+// one part of the app-store effective policy built in Go. The slice changes
+// no objstore source; the region-host tofu tests pin the host and boundary
+// halves byte for byte.
+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"]}}}]}`,
+ `{"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:GetObject"],"Resource":"arn:aws:s3:::carlos-store-shop-0123/*","Condition":{"StringEquals":{"s3:ExistingObjectTag/carlos-scan":"infected"}}}]}`,
+ `{"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.
+func TestManaged2B1Disabled(t *testing.T) {
+ t.Run("no production providers", func(t *testing.T) {
+ files := 0
+ managedProductionSources(t, func(path string, src []byte) {
+ files++
+ if bytes.Contains(src, []byte("internal/awsmanaged")) {
+ f, err := parser.ParseFile(token.NewFileSet(), path, src, parser.ImportsOnly)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, imp := range f.Imports {
+ if strings.Trim(imp.Path.Value, `"`) == "github.com/carlosframework/platform/internal/awsmanaged" {
+ t.Errorf("%s imports the AWS adapters", path)
+ }
+ }
+ }
+ if !bytes.Contains(src, []byte("ManagedCompute")) && !bytes.Contains(src, []byte("ManagedStorage")) {
+ return
+ }
+ f, err := parser.ParseFile(token.NewFileSet(), path, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ named := func(e ast.Expr) bool {
+ var name string
+ switch v := e.(type) {
+ case *ast.Ident:
+ name = v.Name
+ case *ast.SelectorExpr:
+ name = v.Sel.Name
+ }
+ return name == "ManagedCompute" || name == "ManagedStorage"
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ switch v := n.(type) {
+ case *ast.KeyValueExpr:
+ if named(v.Key) {
+ t.Errorf("%s sets a managed provider", path)
+ }
+ case *ast.AssignStmt:
+ for _, lhs := range v.Lhs {
+ if named(lhs) {
+ t.Errorf("%s assigns a managed provider", path)
+ }
+ }
+ }
+ return true
+ })
+ })
+ if files < 1000 {
+ t.Fatalf("scanned only %d files", files)
+ }
+ var zero managedConfig
+ if zero.Enabled || (Config{}).ManagedCompute != nil || (Config{}).ManagedStorage != nil {
+ t.Fatal("managed fleets on by default")
+ }
+ })
+
+ t.Run("off refuses new reservations", func(t *testing.T) {
+ for _, mode := range []string{"no-config", "disabled", "no-compute", "no-storage"} {
+ t.Run(mode, func(t *testing.T) {
+ s := managedAPIFixture(t)
+ switch mode {
+ case "no-config":
+ s.managed.snapshot = managedConfigSnapshot{}
+ case "disabled":
+ s.managed.snapshot.Config.Enabled = false
+ case "no-compute":
+ s.cfg.ManagedCompute = nil
+ case "no-storage":
+ s.cfg.ManagedStorage = nil
+ }
+ for _, door := range []string{"plan", "create"} {
+ body := managedAPIBody("a", 2)
+ if door == "plan" {
+ body = strings.Replace(body, `"managed":true`, `"kind":"create"`, 1)
+ }
+ if w := managedAPICall(s, door, "abc", "", body); w.Code < 400 {
+ t.Fatalf("%s admitted: %d %s", door, w.Code, w.Body)
+ }
+ }
+ if managedCount(t, s, `SELECT count(*) FROM managed_ops`) != 0 || managedCount(t, s, `SELECT count(*) FROM managed_boxes`) != 0 {
+ t.Fatal("reserved while off")
+ }
+ reg, _ := openRegistry(s.cfg.Registry)
+ if f, _ := reg.GetFleet("production"); f != nil {
+ t.Fatal("claimed the fleet name while off")
+ }
+ })
+ }
+ })
+
+ t.Run("frozen operations stay recoverable", func(t *testing.T) {
+ s, p, now := managedE2E(t, 2)
+ p.LoseLaunchResponse = true
+ e2ePass(t, s, now)
+ p.LoseLaunchResponse = false
+ // Admission is switched off, the ceiling cut below what is held,
+ // and the compute provider removed.
+ s.managed.snapshot.Config.Enabled = false
+ s.managed.snapshot.Config.Ceiling = 1
+ s = restartManagedAPI(t, s)
+ s.cfg.ManagedCompute = nil
+ managedWokenPass(t, s, now.Add(10*time.Second))
+ for _, b := range e2eBoxes(t, s) {
+ if b.State != "launching" || b.CloudID != "" {
+ t.Fatalf("missing provider changed reserved work: %+v", b)
+ }
+ }
+ if managedHeld(t, s) != 2 || p.Calls()["Terminate"] != 0 {
+ t.Fatal("missing provider released or terminated reserved work")
+ }
+ if w := managedAPICall(s, "add", "abc", "production", `{"boxes":1,"request_id":"bbbbbbbbbbbbbbbbbbbbbb"}`); w.Code < 400 {
+ t.Fatalf("add admitted while off: %d %s", w.Code, w.Body)
+ }
+ // Injected again, the provider recovers the same instances under
+ // the frozen launch, and the operation completes while still off.
+ s.cfg.ManagedCompute = p
+ managedWokenPass(t, s, now.Add(20*time.Second))
+ for _, b := range e2eBoxes(t, s) {
+ if b.CloudID == "" {
+ t.Fatalf("not recovered: %+v", b)
+ }
+ e2eEnrol(t, s, b)
+ }
+ e2eReady(t, s, now.Add(time.Minute))
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation.State != "done" || out.Operation.Outcome != "success" || p.Calls()["Launch"] != 2 {
+ t.Fatalf("frozen operation: %+v %v", out.Operation, p.Calls())
+ }
+ if w := managedAPICall(s, "add", "abc", "production", `{"boxes":1,"request_id":"cccccccccccccccccccccc"}`); w.Code < 400 {
+ t.Fatalf("add admitted while off: %d %s", w.Code, w.Body)
+ }
+ if managedHeld(t, s) != 2 {
+ t.Fatal("held quota changed")
+ }
+ })
+
+ t.Run("host claim", func(t *testing.T) {
+ s, p, now := managedE2E(t, 1)
+ s.cfg.HostClaim = true
+ if err := s.RunManagedFleetsPass(context.Background(), now); !errors.Is(err, errManagedHostClaim) {
+ t.Fatalf("host-claim pass: %v", err)
+ }
+ for _, door := range []string{"create", "plan"} {
+ body := managedAPIBody("b", 1)
+ if door == "plan" {
+ body = strings.Replace(body, `"managed":true`, `"kind":"create"`, 1)
+ }
+ if w := managedAPICall(s, door, "abc", "", body); w.Code != 409 || !strings.Contains(w.Body.String(), errManagedHostClaim.Error()) {
+ t.Fatalf("host-claim %s: %d %s", door, w.Code, w.Body)
+ }
+ }
+ if w := managedAPICall(s, "add", "abc", "production", `{"boxes":1,"request_id":"bbbbbbbbbbbbbbbbbbbbbb"}`); w.Code != 409 {
+ t.Fatalf("host-claim add: %d %s", w.Code, w.Body)
+ }
+ if w := enrolHTTP(s, enrolBody(strings.Repeat("a", 64))); w.Code != 409 {
+ t.Fatalf("host-claim enrolment: %d %s", w.Code, w.Body)
+ }
+ if len(p.Calls()) != 0 || managedCount(t, s, `SELECT count(*) FROM managed_ops`) != 1 {
+ t.Fatal("host-claim console reached a provider or reserved", p.Calls())
+ }
+ s.cfg.HostClaim = false
+ e2ePass(t, s, now)
+ if p.Calls()["Launch"] != 1 {
+ t.Fatal("reserved work lost across host claim", p.Calls())
+ }
+ })
+
+ t.Run("byo unchanged", func(t *testing.T) {
+ var replies []string
+ for _, on := range []bool{true, false} {
+ s := managedAPIFixture(t)
+ if !on {
+ s.managed.snapshot = managedConfigSnapshot{}
+ s.cfg.ManagedCompute, s.cfg.ManagedStorage = nil, nil
+ }
+ created := managedAPICall(s, "create", "abc", "", `{"name":"edge","bucket":"byo-bucket-example"}`)
+ shown := managedAPICall(s, "show", "abc", "edge", "")
+ if created.Code >= 300 || shown.Code != 200 {
+ t.Fatalf("BYO (managed on=%v): %d %s / %d %s", on, created.Code, created.Body, shown.Code, shown.Body)
+ }
+ if strings.Contains(shown.Body.String(), "credential_") || strings.Contains(shown.Body.String(), `"operation"`) || strings.Contains(shown.Body.String(), `"managed":true`) {
+ t.Fatalf("BYO show carries managed fields: %s", shown.Body)
+ }
+ replies = append(replies, fmt.Sprint(created.Code, created.Body.String(), shown.Body.String()))
+ if managedCount(t, s, `SELECT count(*) FROM managed_ops`) != 0 {
+ t.Fatal("BYO create reserved managed work")
+ }
+ }
+ if replies[0] != replies[1] {
+ t.Fatalf("BYO behaviour depends on managed fleets:\n%s\n%s", replies[0], replies[1])
+ }
+ })
+
+ t.Run("app store policy unchanged", func(t *testing.T) {
+ p := objstore.NewMemProvisioner("eu-west-1")
+ for i, v := range []struct {
+ deny *objstore.DenyTag
+ denyWrites bool
+ }{{nil, false}, {&objstore.DenyTag{Key: objstore.TagVerdict, Value: "infected"}, false}, {nil, true}} {
+ user := fmt.Sprintf("store-user-%d", i)
+ if _, err := p.EnsureUser(context.Background(), user, "/carlos-store/", "arn:aws:s3:::carlos-store-shop-0123", v.deny, v.denyWrites); err != nil {
+ t.Fatal(err)
+ }
+ if got := p.PolicyFor(user); got != managedAppStorePolicies[i] {
+ t.Errorf("app store policy %d changed:\n%s", i, got)
+ }
+ }
+ })
+}
+
+// managedSecretStorage fails, while fail is set, with provider text that
+// carries secrets, as an SDK error can echo them.
+type managedSecretStorage struct {
+ *fleetstore.Fake
+ fail string
+}
+
+func (p *managedSecretStorage) EnsureFleetStorage(ctx context.Context, fleet, region string) (fleetstore.FleetStorage, error) {
+ if p.fail != "" {
+ return fleetstore.FleetStorage{}, errors.New("provider said: " + p.fail)
+ }
+ return p.Fake.EnsureFleetStorage(ctx, fleet, region)
+}
+func (p *managedSecretStorage) RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (fleetstore.Credentials, error) {
+ if p.fail != "" {
+ return fleetstore.Credentials{}, errors.New("provider said: " + p.fail)
+ }
+ return p.Fake.RotateFleetCredentials(ctx, fleet, keep, delivered)
+}
+
+// TestManaged2B1SecretSurfaces is the console half of the slice's secret
+// proof (the adapter half is awsmanaged's TestAWSManagedSecretSurfaces):
+// provider errors that echo secrets, enrolment tokens, tunnel tokens and
+// every minted secret stay out of persisted progress, show, the fleet page,
+// refusals and logs; the enrolled credential stays exactly id/secret.
+func TestManaged2B1SecretSurfaces(t *testing.T) {
+ const providerSecret = "provider-SENTINEL-9b1e wJalrSECRETSENTINEL -----BEGIN PRIVATE KEY-----PRIVSENTINEL"
+ var logs bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&logs)
+ defer log.SetOutput(old)
+ ctx := context.Background()
+ s, p, now := managedE2E(t, 2)
+ storage := &managedSecretStorage{Fake: s.cfg.ManagedStorage.(*fleetstore.Fake), fail: providerSecret}
+ s.cfg.ManagedStorage = storage
+ launches, finds := 0, 0
+ s.cfg.ManagedCompute = &managedComputeScript{Fake: p,
+ launch: func(ctx context.Context, spec compute.LaunchSpec) (compute.Instance, error) {
+ if launches++; launches == 1 {
+ return compute.Instance{}, errors.New("provider said: " + providerSecret)
+ }
+ return p.Launch(ctx, spec)
+ },
+ find: func(ctx context.Context, region string, id compute.Identity) ([]compute.Instance, error) {
+ if finds++; finds == 1 {
+ return nil, errors.New("provider said: " + providerSecret)
+ }
+ return p.Find(ctx, region, id)
+ },
+ }
+ // Preparation fails with provider text, then succeeds; the first launch
+ // and the discovery after it fail the same way before recovering.
+ // Enrolment runs on the wall clock, so the passes do too.
+ s.wakeManagedFleets()
+ _ = s.RunManagedFleetsPass(ctx, now)
+ storage.fail = ""
+ for i := 1; i <= 12; i++ {
+ s.wakeManagedFleets()
+ _ = s.RunManagedFleetsPass(ctx, time.Now().UTC())
+ done := true
+ for _, b := range e2eBoxes(t, s) {
+ done = done && b.CloudID != ""
+ }
+ if done {
+ break
+ }
+ }
+ var secrets [][]byte
+ keep := ""
+ for _, b := range e2eBoxes(t, s) {
+ if b.CloudID == "" {
+ t.Fatalf("not launched: %+v", b)
+ }
+ key, _, err := openManagedEnrolKey(s.cfg.AlertSealKeyPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ token, _ := deriveManagedEnrolToken(key, b.ClientToken)
+ w := enrolHTTP(s, enrolBody(token))
+ if w.Code != 200 {
+ t.Fatalf("enrol: %d %s", w.Code, w.Body)
+ }
+ var raw struct {
+ Credentials map[string]json.RawMessage `json:"credentials"`
+ }
+ var reply managedEnrolReply
+ if json.Unmarshal(w.Body.Bytes(), &raw) != nil || json.Unmarshal(w.Body.Bytes(), &reply) != nil {
+ t.Fatal("enrol reply")
+ }
+ if len(raw.Credentials) != 2 || raw.Credentials["id"] == nil || raw.Credentials["secret"] == nil {
+ t.Fatalf("enrolled credential shape: %s", w.Body)
+ }
+ keep = reply.Credentials.ID
+ secrets = append(secrets, []byte(token), []byte(reply.TunnelToken), reply.Credentials.Secret, []byte(base64.StdEncoding.EncodeToString(reply.Credentials.Secret)))
+ }
+ e2eReady(t, s, time.Now().UTC().Add(time.Minute))
+ // Another delivered key is still live: an add refuses for an operator,
+ // naming no key.
+ extra, err := storage.Fake.RotateFleetCredentials(ctx, "production", keep, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ secrets = append(secrets, extra.Secret, []byte(base64.StdEncoding.EncodeToString(extra.Secret)))
+ if _, err = s.store.db.Exec(`INSERT INTO managed_fleet_delivered_keys(fleet,account,key_id) VALUES('production','abc',?)`, extra.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.store.db.Exec(`UPDATE managed_fleet_storage SET credential_state=?,credential_reason=?`, managedNeedsOperator, managedReasonDeliveredKeyLive); err != nil {
+ t.Fatal(err)
+ }
+ refused := managedAPICall(s, "add", "abc", "production", `{"boxes":1,"request_id":"bbbbbbbbbbbbbbbbbbbbbb"}`)
+ if refused.Code != 409 || strings.Contains(refused.Body.String(), extra.ID) || strings.Contains(refused.Body.String(), keep) {
+ t.Fatalf("needs-operator refusal: %d %s", refused.Code, refused.Body)
+ }
+ show := managedAPICall(s, "show", "abc", "production", "")
+ if strings.Contains(show.Body.String(), extra.ID) || strings.Contains(show.Body.String(), keep) {
+ t.Fatalf("show names a key: %s", show.Body)
+ }
+ surfaces := map[string][]byte{"show": show.Body.Bytes(), "page": e2ePage(t, s), "refusal": refused.Body.Bytes()}
+ var seq int
+ var name, path string
+ if err = s.store.db.QueryRow(`PRAGMA database_list`).Scan(&seq, &name, &path); err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range []string{path, path + "-wal", path + "-shm"} {
+ raw, err := os.ReadFile(f)
+ if err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ surfaces[f] = raw
+ }
+ for _, b := range e2eBoxes(t, s) {
+ raw, _ := json.Marshal(b)
+ surfaces["box "+b.Label] = raw
+ if obj, _, err := s.cfg.Releases.Get(ctx, managedReadyKey(b)); err == nil {
+ surfaces["ready "+b.Label] = obj
+ }
+ }
+ surfaces["logs"] = logs.Bytes()
+ secrets = append(secrets, []byte("SENTINEL"))
+ for _, secret := range secrets {
+ if len(secret) == 0 {
+ t.Fatal("empty secret")
+ }
+ for where, raw := range surfaces {
+ if bytes.Contains(raw, secret) {
+ t.Errorf("%q in %s", secret, where)
+ }
+ }
+ }
+ if launches < 3 || finds < 2 {
+ t.Fatalf("the provider failure paths did not run: %d launches, %d finds", launches, finds)
+ }
+}
diff --git a/internal/console/managedbudget_test.go b/internal/console/managedbudget_test.go
index c8b54fcb4..2552efb86 100644
--- a/internal/console/managedbudget_test.go
+++ b/internal/console/managedbudget_test.go
@@ -5,11 +5,18 @@ import (
"database/sql"
"encoding/json"
"fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
"reflect"
+ "strings"
+ "sync"
"testing"
"time"
"github.com/carlosframework/platform/internal/compute"
+ "github.com/carlosframework/platform/internal/fleetstore"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
)
@@ -267,3 +274,214 @@ func TestManagedPublicationRefreshBudget(t *testing.T) {
}
})
}
+
+// managedStorageCount counts every fleet-storage provider call.
+type managedStorageCount struct {
+ fleetstore.Provisioner
+ mu sync.Mutex
+ calls int
+}
+
+func (c *managedStorageCount) note() { c.mu.Lock(); c.calls++; c.mu.Unlock() }
+func (c *managedStorageCount) total() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.calls
+}
+func (c *managedStorageCount) EnsureFleetStorage(ctx context.Context, fleet, region string) (fleetstore.FleetStorage, error) {
+ c.note()
+ return c.Provisioner.EnsureFleetStorage(ctx, fleet, region)
+}
+func (c *managedStorageCount) FleetCredentials(ctx context.Context, fleet string) (fleetstore.Credentials, error) {
+ c.note()
+ return c.Provisioner.FleetCredentials(ctx, fleet)
+}
+func (c *managedStorageCount) RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (fleetstore.Credentials, error) {
+ c.note()
+ return c.Provisioner.RotateFleetCredentials(ctx, fleet, keep, delivered)
+}
+
+func managedBudgetE2E(t *testing.T, n int) (*Server, *compute.Fake, *managedStorageCount, time.Time) {
+ t.Helper()
+ s, p, now := managedE2E(t, n)
+ storage := &managedStorageCount{Provisioner: s.cfg.ManagedStorage}
+ s.cfg.ManagedStorage = storage
+ return s, p, storage, now
+}
+
+func managedSettle(t *testing.T, s *Server, b managedBox, now time.Time) {
+ t.Helper()
+ next := b
+ next.State, next.ReadyAt, next.DrainClearCompleted = "ready", now, true
+ if ok, err := s.store.AdvanceManagedBox(context.Background(), b, next); err != nil || !ok {
+ t.Fatal(ok, err)
+ }
+}
+
+// managedNoInventoryPolling: neither the fake nor any console source asks
+// the provider for a deployment inventory or console output.
+func managedNoInventoryPolling(t *testing.T, p *compute.Fake) {
+ t.Helper()
+ if c := p.Calls(); c["ListDeployment"] != 0 || c["ConsoleOutput"] != 0 {
+ t.Fatal("background inventory or console-output polling", c)
+ }
+}
+
+// TestManaged2B1Budget: the request budget of spec §6 with the slice's
+// changes in place (delivered-key set, needs-operator, freshness refresh,
+// deadline scheduling). Settled fleets cost nothing; follow polls never
+// reach the store or a provider; enrolled boxes read at most one heartbeat a
+// minute even when woken every few seconds; a delayed publication's refresh
+// is counted on its own box only.
+func TestManaged2B1Budget(t *testing.T) {
+ t.Run("source", func(t *testing.T) {
+ entries, err := os.ReadDir(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range entries {
+ if !strings.HasSuffix(e.Name(), ".go") || strings.HasSuffix(e.Name(), "_test.go") {
+ continue
+ }
+ f, err := parser.ParseFile(token.NewFileSet(), e.Name(), nil, 0)
+ 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 _, n := range []int{1, 10, 100} {
+ t.Run(fmt.Sprintf("ready-%d", n), func(t *testing.T) {
+ s, p, storage, now := managedBudgetE2E(t, n)
+ e2ePass(t, s, now)
+ for _, b := range e2eBoxes(t, s) {
+ managedSettle(t, s, b, now)
+ }
+ // A settled fleet that needs an operator, with a delivered-key
+ // history, polls nothing either.
+ if _, err := s.store.db.Exec(`UPDATE managed_fleet_storage SET credential_state=?,credential_reason=?`, managedNeedsOperator, managedReasonDeliveredKeyLive); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`INSERT INTO managed_fleet_delivered_keys(fleet,account,key_id) VALUES('production','abc','gone-1')`); err != nil {
+ t.Fatal(err)
+ }
+ managedWokenPass(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, ensures := p.Calls(), storage.total()
+ for i := 0; i < 100; i++ {
+ e2ePass(t, s, now.Add(time.Duration(i+1)*time.Hour))
+ }
+ if db.calls != 0 || st.total() != 0 || !reflect.DeepEqual(before, p.Calls()) || storage.total() != ensures {
+ t.Fatal("idle calls", db.calls, st.snapshot(), p.Calls(), storage.total()-ensures)
+ }
+ // Woken passes (member operations wake the worker) may use SQL,
+ // which needs the raw pool for transactions, but never the store
+ // or a provider.
+ s.store.db = db.sqlHandle
+ for i := 0; i < 10; i++ {
+ managedWokenPass(t, s, now.Add(time.Duration(200+i)*time.Hour))
+ }
+ if st.total() != 0 || !reflect.DeepEqual(before, p.Calls()) || storage.total() != ensures {
+ t.Fatal("woken settled calls", st.snapshot(), p.Calls(), storage.total()-ensures)
+ }
+ managedNoInventoryPolling(t, p)
+ })
+ }
+ t.Run("follow", func(t *testing.T) {
+ s, p, storage, now := managedBudgetE2E(t, 3)
+ e2ePass(t, s, now)
+ for _, b := range e2eBoxes(t, s) {
+ e2eEnrol(t, s, b)
+ }
+ st := &opCountStore{Store: s.cfg.Releases}
+ s.cfg.Releases = st
+ before, ensures := p.Calls(), storage.total()
+ for i := 0; i < 100; i++ {
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if len(out.Boxes) != 3 || out.Operation == nil || out.Operation.State != "open" {
+ t.Fatalf("poll %d: %+v", i, out)
+ }
+ }
+ if st.total() != 0 || !reflect.DeepEqual(before, p.Calls()) || storage.total() != ensures {
+ t.Fatal("follow calls", st.snapshot(), p.Calls(), storage.total()-ensures)
+ }
+ managedNoInventoryPolling(t, p)
+ })
+ t.Run("enrolled", func(t *testing.T) {
+ s, p, storage, now := managedBudgetE2E(t, 3)
+ s.managedExtra = readyExtras{managedCheck{State: "pass"}, managedCheck{State: "pending"}}
+ e2ePass(t, s, now)
+ bs := e2eBoxes(t, s)
+ for _, b := range bs {
+ e2eEnrol(t, s, b)
+ }
+ st := countReadiness(s)
+ before, ensures := p.Calls(), storage.total()
+ start := now.Add(time.Minute)
+ const minutes = 10
+ for i := 0; i <= minutes*12; i++ {
+ managedWokenPass(t, s, start.Add(time.Duration(i)*5*time.Second))
+ }
+ for _, b := range bs {
+ beat := "fleets/" + b.Fleet + "/status/boxes/" + b.Label + ".json"
+ if n := st.gets[beat]; n < 1 || n > minutes+1 {
+ t.Fatalf("%s: %d heartbeat reads in %d minutes", b.Label, n, minutes)
+ }
+ }
+ if st.lists != 0 || st.puts != 0 || !reflect.DeepEqual(before, p.Calls()) || storage.total() != ensures {
+ t.Fatal("enrolled calls", st.lists, st.puts, p.Calls(), storage.total()-ensures)
+ }
+ managedNoInventoryPolling(t, p)
+ })
+ t.Run("delayed-publication", func(t *testing.T) {
+ s, p, storage, now := managedBudgetE2E(t, 3)
+ e2ePass(t, s, now)
+ bs := e2eBoxes(t, s)
+ e2eEnrol(t, s, bs[0])
+ for _, b := range bs[1:] {
+ managedSettle(t, s, b, now)
+ }
+ st := countReadiness(s)
+ st.failPut = true
+ at := now.Add(time.Minute)
+ readyBeatIn(t, st.Store, bs[0], status.Box{Label: bs[0].Label, GeneratedAt: at, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true}})
+ managedWokenPass(t, s, at)
+ if b := e2eBoxes(t, s)[0]; b.State != "publishing" || st.puts != 1 {
+ t.Fatalf("fixture: %+v puts=%d", b, st.puts)
+ }
+ st.failPut = false
+ // The stable release moved on, so refreshed checks never pass and
+ // the box stays a delayed publication.
+ readyStable(t, s, "v0.35.0")
+ st.gets, st.puts, st.lists = map[string]int{}, 0, 0
+ before, ensures := p.Calls(), storage.total()
+ const minutes = 6
+ start := at.Add(time.Minute)
+ for i := 0; i <= minutes*6; i++ {
+ pass := start.Add(time.Duration(i) * 10 * time.Second)
+ readyBeatIn(t, st.Store, bs[0], status.Box{Label: bs[0].Label, GeneratedAt: pass, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true}})
+ managedWokenPass(t, s, pass)
+ }
+ beat := func(b managedBox) int { return st.gets["fleets/"+b.Fleet+"/status/boxes/"+b.Label+".json"] }
+ if n := beat(bs[0]); n < 1 || n > minutes+1 {
+ t.Fatalf("delayed publication read %d heartbeats in %d minutes", n, minutes)
+ }
+ for _, b := range bs[1:] {
+ if beat(b) != 0 {
+ t.Fatalf("settled %s read with the delayed one: %v", b.Label, st.gets)
+ }
+ }
+ if st.puts != 0 || st.lists != 0 || st.gets[release.FleetOwnerKey(bs[0].Account, bs[0].Fleet)] != 0 || !reflect.DeepEqual(before, p.Calls()) || storage.total() != ensures {
+ t.Fatal("delayed publication calls", st.puts, st.lists, st.gets, p.Calls(), storage.total()-ensures)
+ }
+ managedNoInventoryPolling(t, p)
+ })
+}
diff --git a/internal/console/managedrecovery_test.go b/internal/console/managedrecovery_test.go
index e14e9d65b..b270025de 100644
--- a/internal/console/managedrecovery_test.go
+++ b/internal/console/managedrecovery_test.go
@@ -14,6 +14,9 @@ import (
"github.com/carlosframework/platform/internal/compute"
"github.com/carlosframework/platform/internal/fleetstore"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
)
func managedHeld(t *testing.T, s *Server) int {
@@ -642,3 +645,209 @@ func TestManagedCredentialFailureHoldsLaunch(t *testing.T) {
t.Fatal("recovered credentials did not launch", p.Calls())
}
}
+
+// managedWokenPass runs one worker pass as a wakeup would, whatever the
+// worker's own schedule says.
+func managedWokenPass(t *testing.T, s *Server, at time.Time) {
+ t.Helper()
+ s.wakeManagedFleets()
+ e2ePass(t, s, at)
+}
+
+// managedAliasRow adds a request ID for an operation the way a matching join
+// does, by copying the original alias row.
+func managedAliasRow(t *testing.T, s *Server, original, id string) {
+ t.Helper()
+ if _, err := s.store.db.Exec(`INSERT INTO managed_request_aliases(account,request_id,op_id,payload) SELECT account,?,op_id,payload FROM managed_request_aliases WHERE request_id=?`, id, original); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestManaged2B1RecoveryMatrix: the slice's recovery rules through a real
+// console database that is closed and reopened mid-flight, observed through
+// the existing API show. Providers and the store are the in-process fakes.
+func TestManaged2B1RecoveryMatrix(t *testing.T) {
+ t.Run("ambiguous-launch", func(t *testing.T) {
+ s, p, now := managedE2E(t, 3)
+ p.LoseLaunchResponse = true
+ e2ePass(t, s, now)
+ p.LoseLaunchResponse = false
+ for _, b := range e2eBoxes(t, s) {
+ if b.State != "launching" || b.CloudID != "" {
+ t.Fatalf("fixture: %+v", b)
+ }
+ }
+ s = restartManagedAPI(t, s)
+ // The member's retry after the restart replays the operation: no
+ // second batch, no new reservation.
+ retry := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 3)))
+ if managedCount(t, s, `SELECT count(*) FROM managed_ops`) != 1 || managedCount(t, s, `SELECT count(*) FROM managed_boxes`) != 3 || managedHeld(t, s) != 3 {
+ t.Fatal("retry after restart bought another batch")
+ }
+ managedWokenPass(t, s, now.Add(10*time.Second))
+ for _, b := range e2eBoxes(t, s) {
+ if b.CloudID == "" {
+ t.Fatalf("not recovered by identity: %+v", b)
+ }
+ }
+ if p.Calls()["Launch"] != 3 || p.Calls()["Find"] != 3 {
+ t.Fatal("relaunched instead of recovering", p.Calls())
+ }
+ s = restartManagedAPI(t, s)
+ for _, b := range e2eBoxes(t, s) {
+ e2eEnrol(t, s, b)
+ }
+ e2eReady(t, s, now.Add(time.Minute))
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation == nil || out.Operation.ID != retry.Operation.ID || out.Operation.State != "done" || out.Operation.Outcome != "success" || len(out.Boxes) != 3 {
+ t.Fatalf("show: %+v", out.Operation)
+ }
+ for _, b := range out.Boxes {
+ if b.State != "ready" {
+ t.Fatalf("show box: %+v", b)
+ }
+ }
+ if live, err := p.ListDeployment(context.Background(), "eu-west-1", s.cfg.ManagedDeployment); err != nil || len(live) != 3 || p.Calls()["Launch"] != 3 {
+ t.Fatal("duplicate instances", live, err)
+ }
+ })
+
+ t.Run("ambiguous-termination", func(t *testing.T) {
+ s, p, now := managedE2E(t, 1)
+ e2ePass(t, s, now)
+ cloudID := e2eBoxes(t, s)[0].CloudID
+ lost := true
+ s.cfg.ManagedCompute = &managedComputeScript{Fake: p, terminate: func(ctx context.Context, region, id string, want compute.Identity) error {
+ if err := p.Terminate(ctx, region, id, want); err != nil {
+ return err
+ }
+ // EC2 accepted it; the instance takes a while to go.
+ p.SetState(id, compute.StateShuttingDown)
+ if lost {
+ return errors.New("terminate response lost")
+ }
+ return nil
+ }}
+ // The box never enrols: its readiness deadline sends it to cleanup.
+ at := now.Add(21 * time.Minute)
+ for i := 0; i < 4 && p.Calls()["Terminate"] == 0; i++ {
+ managedWokenPass(t, s, at)
+ }
+ b := e2eBoxes(t, s)[0]
+ if p.Calls()["Terminate"] != 1 || b.State != "terminating" || !b.TerminateSentAt.IsZero() || managedHeld(t, s) != 1 {
+ t.Fatalf("lost terminate reply: %+v %v", b, p.Calls())
+ }
+ lost = false
+ for i := 1; i <= 3; i++ {
+ s = restartManagedAPI(t, s)
+ managedWokenPass(t, s, at.Add(time.Duration(i)*2*time.Hour))
+ if b = e2eBoxes(t, s)[0]; b.State == "terminated" || managedHeld(t, s) != 1 {
+ t.Fatalf("restart %d released quota while the instance remains: %+v", i, b)
+ }
+ }
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation == nil || out.Operation.Outcome != "failed" || len(out.Boxes) != 1 || out.Boxes[0].State == "ready" {
+ t.Fatalf("show while terminating: %+v %+v", out.Operation, out.Boxes)
+ }
+ p.SetState(cloudID, compute.StateTerminated)
+ s = restartManagedAPI(t, s)
+ managedWokenPass(t, s, at.Add(10*time.Hour))
+ if b = e2eBoxes(t, s)[0]; b.State != "terminated" || managedHeld(t, s) != 0 || p.Calls()["Launch"] != 1 {
+ t.Fatalf("confirmed termination: %+v %v", b, p.Calls())
+ }
+ })
+
+ t.Run("ambiguous-publication", func(t *testing.T) {
+ s, _, now := managedE2E(t, 1)
+ e2ePass(t, s, now)
+ b := e2eBoxes(t, s)[0]
+ e2eEnrol(t, s, b)
+ st := countReadiness(s)
+ // The create-only PUT lands, its reply is lost and the ready-object
+ // GETs fail until the restart: the worker cannot tell.
+ st.losePut = true
+ st.onPut = func() { st.failGet = true }
+ at := now.Add(time.Minute)
+ readyBeat(t, s, b, status.Box{Label: b.Label, GeneratedAt: at, Metrics: &status.BoxMetrics{Release: "v0.34.0", RootfsReady: true}})
+ managedWokenPass(t, s, at)
+ managedWokenPass(t, s, at.Add(10*time.Second))
+ if b = e2eBoxes(t, s)[0]; b.State != "publishing" || st.puts != 1 {
+ t.Fatalf("fixture: %+v puts=%d", b, st.puts)
+ }
+ st.losePut, st.failGet, st.onPut = false, false, nil
+ s = restartManagedAPI(t, s)
+ st.gets, st.puts, st.lists = map[string]int{}, 0, 0
+ // Ten minutes on the persisted checks are stale; the matching object
+ // still wins, with no readiness reads and no second PUT.
+ managedWokenPass(t, s, at.Add(10*time.Minute))
+ b = e2eBoxes(t, s)[0]
+ beat := "fleets/" + b.Fleet + "/status/boxes/" + b.Label + ".json"
+ if b.State != "ready" || st.puts != 0 || st.lists != 0 || st.gets[beat] != 0 ||
+ st.gets[release.SystemPointerKey("router", "stable")] != 0 || st.gets[release.FleetOwnerKey(b.Account, b.Fleet)] != 0 {
+ t.Fatalf("matching publication after restart: %+v puts=%d gets=%v", b, st.puts, st.gets)
+ }
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation.State != "done" || out.Operation.Outcome != "success" || out.Boxes[0].State != "ready" {
+ t.Fatalf("show: %+v %+v", out.Operation, out.Boxes)
+ }
+ })
+
+ t.Run("cap-replay", func(t *testing.T) {
+ s := managedAPIFixture(t)
+ first := managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 2)))
+ original := strings.Repeat("a", 22)
+ for i := 1; i < managedAliasLimit; i++ {
+ managedAliasRow(t, s, original, preflightID("join", i))
+ }
+ body := func(id string) string {
+ return fmt.Sprintf(`{"name":"production","managed":true,"region":"eu-west-1","size":"large","boxes":2,"request_id":%q}`, id)
+ }
+ ops, boxes := managedCount(t, s, `SELECT count(*) FROM managed_ops`), managedCount(t, s, `SELECT count(*) FROM managed_boxes`)
+ for round := 0; round < 2; round++ {
+ w := managedAPICall(s, "create", "abc", "", body(preflightID("new", round)))
+ if w.Code != 429 || !strings.Contains(w.Body.String(), msgManagedAliasLimit) || strings.Contains(w.Body.String(), first.Operation.ID) {
+ t.Fatalf("round %d: new ID at the cap: %d %s", round, w.Code, w.Body)
+ }
+ for _, id := range []string{original, preflightID("join", 1), preflightID("join", managedAliasLimit-1)} {
+ if got := managedAPIReply(t, managedAPICall(s, "create", "abc", "", body(id))); got.Operation.ID != first.Operation.ID {
+ t.Fatalf("round %d: replay %s answered %+v", round, id, got.Operation)
+ }
+ }
+ if managedCount(t, s, `SELECT count(*) FROM managed_ops`) != ops || managedCount(t, s, `SELECT count(*) FROM managed_boxes`) != boxes ||
+ managedCount(t, s, `SELECT count(*) FROM managed_request_aliases`) != managedAliasLimit {
+ t.Fatalf("round %d: the cap or a replay wrote rows", round)
+ }
+ s = restartManagedAPI(t, s)
+ }
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation == nil || out.Operation.ID != first.Operation.ID || len(out.Boxes) != 2 {
+ t.Fatalf("show: %+v", out)
+ }
+ })
+
+ t.Run("prepared-error", func(t *testing.T) {
+ s := managedAPIFixture(t)
+ setManagedHistory(t, s, provision.HostsState{Mode: provision.HostsModeIncomplete})
+ spy := &managedStorageSpy{Fake: fleetstore.NewFake(), fail: true}
+ s.cfg.ManagedStorage = spy
+ p := s.cfg.ManagedCompute.(*compute.Fake)
+ managedAPIReply(t, managedAPICall(s, "create", "abc", "", managedAPIBody("a", 1)))
+ now := time.Now().UTC()
+ s.wakeManagedFleets()
+ _ = s.RunManagedFleetsPass(context.Background(), now)
+ out := managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation.State != "open" || out.Operation.Error != errManagedPreparation.Error() || p.Calls()["Launch"] != 0 {
+ t.Fatalf("failed preparation: %+v %v", out.Operation, p.Calls())
+ }
+ s = restartManagedAPI(t, s)
+ spy.fail = false
+ managedWokenPass(t, s, now.Add(10*time.Second))
+ for i := 0; i < 2; i++ {
+ out = managedAPIReply(t, managedAPICall(s, "show", "abc", "production", ""))
+ if out.Operation.State != "open" || out.Operation.Error != "" || p.Calls()["Launch"] != 1 {
+ t.Fatalf("prepared error not cleared (reopen %d): %+v %v", i, out.Operation, p.Calls())
+ }
+ s = restartManagedAPI(t, s)
+ }
+ })
+}