carlos / platform Public

feat: add managed fleet AWS compute adapter

Add internal/awsmanaged, an EC2 implementation of compute.Provisioner.
It is not wired into production; 2b-2 wires it once frozen cloud-init
replaces today's JSON launch payload.

- Clients load per explicit region through rootaws only. Each call is
  bound to its region and RunInstances/TerminateInstances send exactly
  one attempt.
- Launch validates the frozen spec, describes the pinned AMI (arm64,
  available, EBS, one root mapping no larger than RootGB) and sends one
  deterministic request: encrypted gp3 root, IMDSv2 hop limit 1, one ENI
  in the frozen subnet and groups, no profile, key, template or spot,
  four identity tags on instance and volume.
- IdempotentParameterMismatch is ErrLaunchConflict; only the allowlisted
  codes are ErrLaunchRejected; everything else is ambiguous.
- Discovery reads every page or fails as a whole. Only an exact-ID
  InvalidInstanceID.NotFound in Lookup is os.ErrNotExist.
- Terminate re-reads the exact ID and refuses unless all four tags match.
- ConsoleOutput returns only recognized CARLOS_BOOT codes; errors never
  carry AWS text or user data.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e64845351b9b20759650685f6c59040a6f5f52a9 parent 1445228
6 files changed, +2,207 −0
  • internal/awsmanaged/clients.go +72 −0
  • internal/awsmanaged/compute.go +604 −0
  • internal/awsmanaged/compute_test.go +1,293 −0
  • internal/awsmanaged/diagnostics.go +51 −0
  • internal/awsmanaged/diagnostics_test.go +161 −0
  • internal/awsmanaged/export_test.go +26 −0
diff --git a/internal/awsmanaged/clients.go b/internal/awsmanaged/clients.go
new file mode 100644
index 000000000..f70f3c042
--- /dev/null
+++ b/internal/awsmanaged/clients.go
@@ -0,0 +1,72 @@
+// Package awsmanaged holds the AWS adapters behind the provider-neutral
+// managed-fleet contracts (internal/compute today). 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.
+package awsmanaged
+
+import (
+ "context"
+ "fmt"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/carlosframework/platform/internal/rootaws"
+)
+
+// ec2API is every EC2 call the compute adapter makes, and nothing else, so a
+// test fake stands in for a live client and a new call is a visible change.
+type ec2API interface {
+ RunInstances(context.Context, *ec2.RunInstancesInput, ...func(*ec2.Options)) (*ec2.RunInstancesOutput, error)
+ DescribeInstances(context.Context, *ec2.DescribeInstancesInput, ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error)
+ DescribeImages(context.Context, *ec2.DescribeImagesInput, ...func(*ec2.Options)) (*ec2.DescribeImagesOutput, error)
+ TerminateInstances(context.Context, *ec2.TerminateInstancesInput, ...func(*ec2.Options)) (*ec2.TerminateInstancesOutput, error)
+ GetConsoleOutput(context.Context, *ec2.GetConsoleOutputInput, ...func(*ec2.Options)) (*ec2.GetConsoleOutputOutput, error)
+}
+
+// ec2Methods stores method values rather than the *ec2.Client, for the
+// reason internal/awsinv/clients.go gives: an SDK client held in an
+// interface keeps every one of its methods in the binary.
+type ec2Methods struct {
+ run func(context.Context, *ec2.RunInstancesInput, ...func(*ec2.Options)) (*ec2.RunInstancesOutput, error)
+ describe func(context.Context, *ec2.DescribeInstancesInput, ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error)
+ images func(context.Context, *ec2.DescribeImagesInput, ...func(*ec2.Options)) (*ec2.DescribeImagesOutput, error)
+ terminate func(context.Context, *ec2.TerminateInstancesInput, ...func(*ec2.Options)) (*ec2.TerminateInstancesOutput, error)
+ console func(context.Context, *ec2.GetConsoleOutputInput, ...func(*ec2.Options)) (*ec2.GetConsoleOutputOutput, error)
+}
+
+func (m ec2Methods) RunInstances(ctx context.Context, in *ec2.RunInstancesInput, opts ...func(*ec2.Options)) (*ec2.RunInstancesOutput, error) {
+ return m.run(ctx, in, opts...)
+}
+
+func (m ec2Methods) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, opts ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ return m.describe(ctx, in, opts...)
+}
+
+func (m ec2Methods) DescribeImages(ctx context.Context, in *ec2.DescribeImagesInput, opts ...func(*ec2.Options)) (*ec2.DescribeImagesOutput, error) {
+ return m.images(ctx, in, opts...)
+}
+
+func (m ec2Methods) TerminateInstances(ctx context.Context, in *ec2.TerminateInstancesInput, opts ...func(*ec2.Options)) (*ec2.TerminateInstancesOutput, error) {
+ return m.terminate(ctx, in, opts...)
+}
+
+func (m ec2Methods) GetConsoleOutput(ctx context.Context, in *ec2.GetConsoleOutputInput, opts ...func(*ec2.Options)) (*ec2.GetConsoleOutputOutput, error) {
+ return m.console(ctx, in, opts...)
+}
+
+// loadEC2 builds one region's client through rootaws with that region set
+// explicitly. A loaded region other than the one asked for refuses, so no
+// environment or shared-file default can move the client elsewhere.
+func loadEC2(ctx context.Context, region string, opts ...func(*awsconfig.LoadOptions) error) (ec2API, error) {
+ opts = append(append([]func(*awsconfig.LoadOptions) error(nil), opts...), awsconfig.WithRegion(region))
+ cfg, err := rootaws.LoadDefaultConfig(ctx, opts...)
+ if err != nil {
+ return nil, fmt.Errorf("awsmanaged: load AWS config for %s: %w", region, err)
+ }
+ if cfg.Region != region {
+ return nil, fmt.Errorf("awsmanaged: AWS config for %s resolved another region", region)
+ }
+ c := ec2.NewFromConfig(cfg)
+ return ec2Methods{run: c.RunInstances, describe: c.DescribeInstances, images: c.DescribeImages, terminate: c.TerminateInstances, console: c.GetConsoleOutput}, nil
+}
diff --git a/internal/awsmanaged/compute.go b/internal/awsmanaged/compute.go
new file mode 100644
index 000000000..67a0d6420
--- /dev/null
+++ b/internal/awsmanaged/compute.go
@@ -0,0 +1,604 @@
+package awsmanaged
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "os"
+ "regexp"
+ "slices"
+ "sort"
+ "strings"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/aws/smithy-go"
+ "github.com/carlosframework/platform/internal/compute"
+)
+
+// errAmbiguous marks every answer that proves nothing: a failed or partial
+// read, an unexpected shape, or a write whose outcome is unknown. It is never
+// absence (os.ErrNotExist), a rejection or a conflict. Errors carry fixed
+// text only: AWS messages can echo the request, user data included.
+var errAmbiguous = errors.New("cloud state is uncertain")
+
+// errNotFound is EC2's InvalidInstanceID.NotFound for one exact ID. Only
+// Lookup turns it into os.ErrNotExist; every other caller treats it as
+// ambiguity.
+var errNotFound = errors.New("instance not found")
+
+const (
+ tagDeployment = "carlos:deployment"
+ tagFleet = "carlos:fleet"
+ tagLabel = "carlos:label"
+ tagOperation = "carlos:operation"
+
+ maxUserData = 16 << 10
+ maxRootGB = 16384 // gp3's largest volume, GiB
+ maxSecurityGroups = 16
+ maxDescribePages = 100
+)
+
+// launchRejections are the RunInstances codes that prove this request had
+// no side effect. The worker still releases quota only on a first dispatch.
+var launchRejections = map[string]bool{
+ "InvalidAMIID.Malformed": true, "InvalidSubnetID.NotFound": true, "InvalidGroup.NotFound": true,
+ "InvalidParameterValue": true, "Unsupported": true, "UnauthorizedOperation": true,
+ "InsufficientInstanceCapacity": true, "InstanceLimitExceeded": true,
+}
+
+var (
+ accountRE = regexp.MustCompile(`^[0-9]{12}$`)
+ regionRE = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]{1,2}$`)
+ instanceRE = regexp.MustCompile(`^i-([0-9a-f]{8}|[0-9a-f]{17})$`)
+ imageRE = regexp.MustCompile(`^ami-([0-9a-f]{8}|[0-9a-f]{17})$`)
+ subnetRE = regexp.MustCompile(`^subnet-([0-9a-f]{8}|[0-9a-f]{17})$`)
+ groupRE = regexp.MustCompile(`^sg-([0-9a-f]{8}|[0-9a-f]{17})$`)
+ tokenRE = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
+ tagValueRE = regexp.MustCompile(`^[A-Za-z0-9._:/=+@-]{1,256}$`)
+)
+
+// armTypeRE and armFamilies repeat the console's admission allowlist
+// (internal/console/managedconfig.go). The adapter checks the frozen shape
+// again because it is the last code before money is spent.
+var armTypeRE = regexp.MustCompile(`^([a-z]+[0-9]+(?:g|gd|gn|gen))\.(nano|micro|small|medium|large|xlarge|(?:2|4|8|12|16|24|32|48|64|96|112)xlarge|metal)$`)
+var armFamilies = map[string]bool{
+ "t4g": true,
+ "m6g": true, "m6gd": true, "m7g": true, "m7gd": true, "m8g": true,
+ "c6g": true, "c6gd": true, "c6gn": true, "c7g": true, "c7gd": true, "c7gn": true, "c8g": true,
+ "r6g": true, "r6gd": true, "r7g": true, "r7gd": true, "r8g": true,
+ "x2gd": true, "im4gn": true, "is4gen": true, "i4g": true,
+}
+
+// ComputeConfig names the deployment whose instances this adapter owns, the
+// AWS account they must belong to, and every region it may use.
+type ComputeConfig struct {
+ Deployment, AccountID string
+ Regions []string
+}
+
+// Compute is compute.Provisioner on EC2. Every call names its region and
+// only reaches that region's client; nothing falls back to a default.
+type Compute struct {
+ deployment, account string
+ clients map[string]ec2API
+}
+
+var _ compute.Provisioner = (*Compute)(nil)
+
+// NewCompute loads one EC2 client per configured region through rootaws.
+func NewCompute(ctx context.Context, cfg ComputeConfig) (*Compute, error) {
+ return loadCompute(ctx, cfg)
+}
+
+func loadCompute(ctx context.Context, cfg ComputeConfig, opts ...func(*awsconfig.LoadOptions) error) (*Compute, error) {
+ if err := validateConfig(cfg); err != nil {
+ return nil, err
+ }
+ clients := make(map[string]ec2API, len(cfg.Regions))
+ for _, region := range cfg.Regions {
+ api, err := loadEC2(ctx, region, opts...)
+ if err != nil {
+ return nil, err
+ }
+ clients[region] = api
+ }
+ return newCompute(cfg, clients)
+}
+
+// newCompute copies cfg and keeps exactly one client per configured region.
+func newCompute(cfg ComputeConfig, clients map[string]ec2API) (*Compute, error) {
+ if err := validateConfig(cfg); err != nil {
+ return nil, err
+ }
+ c := &Compute{deployment: cfg.Deployment, account: cfg.AccountID, clients: make(map[string]ec2API, len(cfg.Regions))}
+ for _, region := range cfg.Regions {
+ api := clients[region]
+ if api == nil {
+ return nil, fmt.Errorf("awsmanaged: no EC2 client for region %s", region)
+ }
+ c.clients[region] = api
+ }
+ return c, nil
+}
+
+func validateConfig(cfg ComputeConfig) error {
+ if !tagValueRE.MatchString(cfg.Deployment) {
+ return errors.New("awsmanaged: deployment name is not a valid tag value")
+ }
+ if !accountRE.MatchString(cfg.AccountID) {
+ return errors.New("awsmanaged: AWS account ID must be 12 digits")
+ }
+ if len(cfg.Regions) == 0 {
+ return errors.New("awsmanaged: configure at least one region")
+ }
+ seen := map[string]bool{}
+ for _, region := range cfg.Regions {
+ if !regionRE.MatchString(region) || seen[region] {
+ return errors.New("awsmanaged: regions must be distinct AWS region names")
+ }
+ seen[region] = true
+ }
+ return nil
+}
+
+func (c *Compute) client(region string) (ec2API, error) {
+ if api := c.clients[region]; api != nil && regionRE.MatchString(region) {
+ return api, nil
+ }
+ return nil, errors.New("awsmanaged: region is not configured")
+}
+
+func inRegion(region string) func(*ec2.Options) {
+ return func(o *ec2.Options) { o.Region = region }
+}
+
+// singleAttempt keeps the SDK from re-sending a write: each worker attempt
+// must be exactly one request, or its evidence means nothing.
+func singleAttempt(o *ec2.Options) { o.RetryMaxAttempts = 1 }
+
+func uncertain(ctx context.Context, what string) error {
+ if err := ctx.Err(); err != nil {
+ return fmt.Errorf("awsmanaged: %s: %w: %w", what, errAmbiguous, err)
+ }
+ return fmt.Errorf("awsmanaged: %s: %w", what, errAmbiguous)
+}
+
+func rejected(reason string) error {
+ return fmt.Errorf("awsmanaged: %w: %s", compute.ErrLaunchRejected, reason)
+}
+
+func mismatch(what string) error {
+ return fmt.Errorf("awsmanaged: %s: %w", what, compute.ErrIdentityMismatch)
+}
+
+func apiCode(err error) string {
+ var ae smithy.APIError
+ if errors.As(err, &ae) {
+ return ae.ErrorCode()
+ }
+ return ""
+}
+
+func (c *Compute) ownIdentity(id compute.Identity) bool {
+ for _, v := range []string{id.Deployment, id.Fleet, id.Label, id.Operation} {
+ if !tagValueRE.MatchString(v) {
+ return false
+ }
+ }
+ return id.Deployment == c.deployment
+}
+
+func identityTagList(id compute.Identity) []types.Tag {
+ return []types.Tag{
+ {Key: aws.String(tagDeployment), Value: aws.String(id.Deployment)},
+ {Key: aws.String(tagFleet), Value: aws.String(id.Fleet)},
+ {Key: aws.String(tagLabel), Value: aws.String(id.Label)},
+ {Key: aws.String(tagOperation), Value: aws.String(id.Operation)},
+ }
+}
+
+// Launch sends one RunInstances for the frozen spec. The request is built
+// from s and the pinned image's own root device name alone, so a retry or a
+// restarted console sends the same bytes under the same ClientToken.
+func (c *Compute) Launch(ctx context.Context, s compute.LaunchSpec) (compute.Instance, error) {
+ api, err := c.validateLaunch(s)
+ if err != nil {
+ return compute.Instance{}, err
+ }
+ root, err := rootDevice(ctx, api, s)
+ if err != nil {
+ return compute.Instance{}, err
+ }
+ out, err := api.RunInstances(ctx, launchInput(s, root), inRegion(s.Region), singleAttempt)
+ if err != nil {
+ code := apiCode(err)
+ switch {
+ case code == "IdempotentParameterMismatch":
+ return compute.Instance{}, fmt.Errorf("awsmanaged: client token was used with other parameters: %w", compute.ErrLaunchConflict)
+ case launchRejections[code]:
+ return compute.Instance{}, rejected(code)
+ }
+ return compute.Instance{}, uncertain(ctx, "launch")
+ }
+ if out == nil || len(out.Instances) != 1 {
+ return compute.Instance{}, uncertain(ctx, "launch answer")
+ }
+ o, err := c.observe(s.Region, out.OwnerId, out.Instances[0])
+ if err != nil {
+ return compute.Instance{}, uncertain(ctx, "launch answer")
+ }
+ // The tags travel in the launch request itself, so an answer that omits
+ // them all still names the requested identity. Any tag it does carry
+ // must agree with the request.
+ switch {
+ case o.present == 0 && !o.dup:
+ o.inst.Identity = s.Identity
+ case o.dup || o.inst.Identity != s.Identity:
+ return compute.Instance{}, uncertain(ctx, "launch answer")
+ }
+ return o.inst, nil
+}
+
+func (c *Compute) validateLaunch(s compute.LaunchSpec) (ec2API, error) {
+ if !c.ownIdentity(s.Identity) {
+ return nil, rejected("launch identity is invalid")
+ }
+ api, err := c.client(s.Region)
+ if err != nil {
+ return nil, rejected("region is not configured")
+ }
+ if m := armTypeRE.FindStringSubmatch(s.InstanceType); m == nil || !armFamilies[m[1]] {
+ return nil, rejected("instance type is not an approved ARM type")
+ }
+ if !imageRE.MatchString(s.Image) || !subnetRE.MatchString(s.Subnet) {
+ return nil, rejected("image or subnet ID is invalid")
+ }
+ if len(s.SecurityGroups) == 0 || len(s.SecurityGroups) > maxSecurityGroups {
+ return nil, rejected("security groups are missing or too many")
+ }
+ seen := map[string]bool{}
+ for _, g := range s.SecurityGroups {
+ if !groupRE.MatchString(g) || seen[g] {
+ return nil, rejected("security group IDs are invalid")
+ }
+ seen[g] = true
+ }
+ if s.RootGB <= 0 || s.RootGB > maxRootGB {
+ return nil, rejected("root disk size is out of range")
+ }
+ if len(s.UserData) == 0 || len(s.UserData) > maxUserData {
+ return nil, rejected("user data is empty or longer than 16 KiB")
+ }
+ if !tokenRE.MatchString(s.ClientToken) {
+ return nil, rejected("client token is invalid")
+ }
+ return api, nil
+}
+
+// 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.
+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 {
+ switch apiCode(err) {
+ case "InvalidAMIID.NotFound", "InvalidAMIID.Malformed", "InvalidAMIID.Unavailable":
+ return "", rejected("image is not available")
+ }
+ return "", uncertain(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")
+ }
+ img := out.Images[0]
+ if img.Architecture != types.ArchitectureValuesArm64 || img.State != types.ImageStateAvailable || img.RootDeviceType != types.DeviceTypeEbs {
+ return "", rejected("image is not an available arm64 EBS image")
+ }
+ root := aws.ToString(img.RootDeviceName)
+ if root == "" || len(img.BlockDeviceMappings) != 1 {
+ return "", rejected("image block device mappings are not supported")
+ }
+ m := img.BlockDeviceMappings[0]
+ if aws.ToString(m.DeviceName) != root || m.Ebs == nil || aws.ToInt32(m.Ebs.VolumeSize) <= 0 || m.VirtualName != nil || m.NoDevice != nil {
+ return "", rejected("image block device mappings are not supported")
+ }
+ if int(aws.ToInt32(m.Ebs.VolumeSize)) > s.RootGB {
+ return "", rejected("root disk is smaller than the image")
+ }
+ return root, nil
+}
+
+func launchInput(s compute.LaunchSpec, root string) *ec2.RunInstancesInput {
+ return &ec2.RunInstancesInput{
+ ImageId: aws.String(s.Image), InstanceType: types.InstanceType(s.InstanceType),
+ MinCount: aws.Int32(1), MaxCount: aws.Int32(1), ClientToken: aws.String(s.ClientToken),
+ UserData: aws.String(base64.StdEncoding.EncodeToString([]byte(s.UserData))),
+ BlockDeviceMappings: []types.BlockDeviceMapping{{DeviceName: aws.String(root), Ebs: &types.EbsBlockDevice{
+ VolumeSize: aws.Int32(int32(s.RootGB)), VolumeType: types.VolumeTypeGp3, Encrypted: aws.Bool(true), DeleteOnTermination: aws.Bool(true),
+ }}},
+ MetadataOptions: &types.InstanceMetadataOptionsRequest{
+ HttpEndpoint: types.InstanceMetadataEndpointStateEnabled, HttpTokens: types.HttpTokensStateRequired, HttpPutResponseHopLimit: aws.Int32(1),
+ },
+ NetworkInterfaces: []types.InstanceNetworkInterfaceSpecification{{
+ DeviceIndex: aws.Int32(0), SubnetId: aws.String(s.Subnet), Groups: slices.Clone(s.SecurityGroups),
+ AssociatePublicIpAddress: aws.Bool(true), DeleteOnTermination: aws.Bool(true),
+ }},
+ TagSpecifications: []types.TagSpecification{
+ {ResourceType: types.ResourceTypeInstance, Tags: identityTagList(s.Identity)},
+ {ResourceType: types.ResourceTypeVolume, Tags: identityTagList(s.Identity)},
+ },
+ }
+}
+
+// instanceStates maps every EC2 state; an unlisted one is a malformed answer.
+var instanceStates = map[types.InstanceStateName]compute.State{
+ types.InstanceStateNamePending: compute.StatePending, types.InstanceStateNameRunning: compute.StateRunning,
+ types.InstanceStateNameStopping: compute.StateStopping, types.InstanceStateNameStopped: compute.StateStopped,
+ types.InstanceStateNameShuttingDown: compute.StateShuttingDown, types.InstanceStateNameTerminated: compute.StateTerminated,
+}
+
+// observed is one validated instance. present counts identity tag keys and
+// dup marks a key seen twice; callers decide what an incomplete identity
+// means for them.
+type observed struct {
+ inst compute.Instance
+ present int
+ dup bool
+}
+
+func (c *Compute) observe(region string, owner *string, in types.Instance) (observed, error) {
+ id := aws.ToString(in.InstanceId)
+ if aws.ToString(owner) != c.account || !instanceRE.MatchString(id) || in.State == nil || in.Placement == nil {
+ return observed{}, errAmbiguous
+ }
+ state, ok := instanceStates[in.State.Name]
+ if !ok {
+ return observed{}, errAmbiguous
+ }
+ zone, ok := strings.CutPrefix(aws.ToString(in.Placement.AvailabilityZone), region)
+ if !ok || zone == "" || !(zone[0] == '-' || zone[0] >= 'a' && zone[0] <= 'z') {
+ return observed{}, errAmbiguous
+ }
+ o := observed{inst: compute.Instance{CloudID: id, Region: region, State: state, LaunchedAt: aws.ToTime(in.LaunchTime)}}
+ seen := map[string]bool{}
+ for _, tag := range in.Tags {
+ key := aws.ToString(tag.Key)
+ var field *string
+ switch key {
+ case tagDeployment:
+ field = &o.inst.Identity.Deployment
+ case tagFleet:
+ field = &o.inst.Identity.Fleet
+ case tagLabel:
+ field = &o.inst.Identity.Label
+ case tagOperation:
+ field = &o.inst.Identity.Operation
+ default:
+ continue
+ }
+ if seen[key] {
+ o.dup = true
+ continue
+ }
+ seen[key] = true
+ o.present++
+ *field = aws.ToString(tag.Value)
+ }
+ return o, nil
+}
+
+// describeAll reads every page of one DescribeInstances query or fails as a
+// whole: a partial listing could hide the instance that matters. A NotFound
+// for a single exact ID comes back as errNotFound.
+func (c *Compute) describeAll(ctx context.Context, api ec2API, region string, query ec2.DescribeInstancesInput) ([]observed, error) {
+ var out []observed
+ ids := map[string]bool{}
+ tokens := map[string]bool{}
+ for pages := 0; ; pages++ {
+ if pages == maxDescribePages {
+ return nil, uncertain(ctx, "describe instances: too many pages")
+ }
+ in := query
+ page, err := api.DescribeInstances(ctx, &in, inRegion(region))
+ if err != nil {
+ if apiCode(err) == "InvalidInstanceID.NotFound" && len(query.InstanceIds) == 1 && len(query.Filters) == 0 && pages == 0 {
+ return nil, errNotFound
+ }
+ return nil, uncertain(ctx, "describe instances")
+ }
+ if page == nil {
+ return nil, uncertain(ctx, "describe instances answer")
+ }
+ for _, r := range page.Reservations {
+ for _, inst := range r.Instances {
+ o, err := c.observe(region, r.OwnerId, inst)
+ if err != nil || ids[o.inst.CloudID] {
+ return nil, uncertain(ctx, "describe instances answer")
+ }
+ ids[o.inst.CloudID] = true
+ out = append(out, o)
+ }
+ }
+ next := aws.ToString(page.NextToken)
+ if next == "" {
+ return out, nil
+ }
+ if tokens[next] {
+ return nil, uncertain(ctx, "describe instances: repeated page token")
+ }
+ tokens[next] = true
+ query.NextToken = aws.String(next)
+ }
+}
+
+func instances(found []observed) []compute.Instance {
+ var out []compute.Instance
+ for _, o := range found {
+ out = append(out, o.inst)
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].CloudID < out[j].CloudID })
+ return out
+}
+
+// Find lists every instance carrying all four identity tags in region,
+// terminated ones included. An empty answer is not proof of anything.
+func (c *Compute) Find(ctx context.Context, region string, id compute.Identity) ([]compute.Instance, error) {
+ api, err := c.client(region)
+ if err != nil {
+ return nil, err
+ }
+ if !c.ownIdentity(id) {
+ return nil, errors.New("awsmanaged: find identity is invalid")
+ }
+ var filters []types.Filter
+ for _, tag := range identityTagList(id) {
+ filters = append(filters, types.Filter{Name: aws.String("tag:" + aws.ToString(tag.Key)), Values: []string{aws.ToString(tag.Value)}})
+ }
+ found, err := c.describeAll(ctx, api, region, ec2.DescribeInstancesInput{Filters: filters})
+ if err != nil {
+ return nil, err
+ }
+ for _, o := range found {
+ if o.dup || o.inst.Identity != id {
+ return nil, uncertain(ctx, "find answer")
+ }
+ }
+ return instances(found), nil
+}
+
+// exact describes one cloud ID with no tag filter.
+func (c *Compute) exact(ctx context.Context, api ec2API, region, cloudID string) (observed, error) {
+ found, err := c.describeAll(ctx, api, region, ec2.DescribeInstancesInput{InstanceIds: []string{cloudID}})
+ if err != nil {
+ return observed{}, err
+ }
+ if len(found) != 1 || found[0].inst.CloudID != cloudID {
+ return observed{}, uncertain(ctx, "lookup answer")
+ }
+ return found[0], nil
+}
+
+func (c *Compute) exactClient(region, cloudID string) (ec2API, error) {
+ api, err := c.client(region)
+ if err != nil {
+ return nil, err
+ }
+ if !instanceRE.MatchString(cloudID) {
+ return nil, errors.New("awsmanaged: instance ID is invalid")
+ }
+ return api, nil
+}
+
+// Lookup addresses exactly cloudID. Only EC2's InvalidInstanceID.NotFound
+// for it is absence; an empty or odd success is ambiguity.
+func (c *Compute) Lookup(ctx context.Context, region, cloudID string) (compute.Instance, error) {
+ api, err := c.exactClient(region, cloudID)
+ if err != nil {
+ return compute.Instance{}, err
+ }
+ o, err := c.exact(ctx, api, region, cloudID)
+ if errors.Is(err, errNotFound) {
+ return compute.Instance{}, fmt.Errorf("awsmanaged: instance is absent: %w", os.ErrNotExist)
+ }
+ if err != nil {
+ return compute.Instance{}, err
+ }
+ if o.dup {
+ return compute.Instance{}, uncertain(ctx, "lookup answer")
+ }
+ return o.inst, nil
+}
+
+// Terminate re-reads cloudID and sends one TerminateInstances only when all
+// four identity tags equal want. A nil return means AWS accepted the request,
+// not that the instance is gone.
+func (c *Compute) Terminate(ctx context.Context, region, cloudID string, want compute.Identity) error {
+ api, err := c.exactClient(region, cloudID)
+ if err != nil {
+ return err
+ }
+ if !c.ownIdentity(want) {
+ return mismatch("terminate identity is invalid")
+ }
+ o, err := c.exact(ctx, api, region, cloudID)
+ if errors.Is(err, errNotFound) {
+ // Nothing was sent, so not seeing the instance proves nothing.
+ return uncertain(ctx, "instance not visible before terminate")
+ }
+ if err != nil {
+ return err
+ }
+ if o.dup || o.inst.Identity != want {
+ return mismatch("terminate")
+ }
+ out, err := api.TerminateInstances(ctx, &ec2.TerminateInstancesInput{InstanceIds: []string{cloudID}}, inRegion(region), singleAttempt)
+ if err != nil {
+ return uncertain(ctx, "terminate")
+ }
+ if out == nil || len(out.TerminatingInstances) != 1 || aws.ToString(out.TerminatingInstances[0].InstanceId) != cloudID {
+ return uncertain(ctx, "terminate answer")
+ }
+ return nil
+}
+
+// ListDeployment lists this deployment's managed instances in region. An
+// instance missing any identity tag (the region host among them) is not a
+// managed instance and is left out.
+func (c *Compute) ListDeployment(ctx context.Context, region, deployment string) ([]compute.Instance, error) {
+ api, err := c.client(region)
+ if err != nil {
+ return nil, err
+ }
+ if deployment != c.deployment {
+ return nil, errors.New("awsmanaged: deployment is not this adapter's")
+ }
+ found, err := c.describeAll(ctx, api, region, ec2.DescribeInstancesInput{
+ Filters: []types.Filter{{Name: aws.String("tag:" + tagDeployment), Values: []string{deployment}}},
+ })
+ if err != nil {
+ return nil, err
+ }
+ var managed []observed
+ for _, o := range found {
+ id := o.inst.Identity
+ if o.dup || id.Deployment != deployment {
+ return nil, uncertain(ctx, "list answer")
+ }
+ if id.Fleet != "" && id.Label != "" && id.Operation != "" {
+ managed = append(managed, o)
+ }
+ }
+ return instances(managed), nil
+}
+
+// ConsoleOutput returns only recognized boot breadcrumb codes from a managed
+// instance of this deployment; see sanitizeConsoleOutput.
+func (c *Compute) ConsoleOutput(ctx context.Context, region, cloudID string) (string, error) {
+ api, err := c.exactClient(region, cloudID)
+ if err != nil {
+ return "", err
+ }
+ o, err := c.exact(ctx, api, region, cloudID)
+ if errors.Is(err, errNotFound) {
+ return "", uncertain(ctx, "instance not visible")
+ }
+ if err != nil {
+ return "", err
+ }
+ id := o.inst.Identity
+ if o.dup || id.Deployment != c.deployment || id.Fleet == "" || id.Label == "" || id.Operation == "" {
+ return "", mismatch("console output")
+ }
+ out, err := api.GetConsoleOutput(ctx, &ec2.GetConsoleOutputInput{InstanceId: aws.String(cloudID)}, inRegion(region))
+ if err != nil {
+ return "", uncertain(ctx, "console output")
+ }
+ if out == nil || aws.ToString(out.InstanceId) != cloudID {
+ return "", uncertain(ctx, "console output answer")
+ }
+ return sanitizeConsoleOutput(aws.ToString(out.Output))
+}
diff --git a/internal/awsmanaged/compute_test.go b/internal/awsmanaged/compute_test.go
new file mode 100644
index 000000000..602b99210
--- /dev/null
+++ b/internal/awsmanaged/compute_test.go
@@ -0,0 +1,1293 @@
+package awsmanaged
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/aws/smithy-go"
+ "github.com/carlosframework/platform/internal/compute"
+)
+
+const (
+ testAccount = "123456789012"
+ testRegion = "eu-west-1"
+ otherRegion = "eu-central-1"
+ testDeployment = "production"
+ testImage = "ami-0123456789abcdef0"
+ testSubnet = "subnet-0123456789abcdef0"
+ testSG = "sg-0123456789abcdef0"
+ testSG2 = "sg-0fedcba9876543210"
+ testRootDevice = "/dev/sda1"
+ // secretText stands for anything AWS or the box might echo back: user
+ // data, tokens, service messages. No error or diagnostic may carry it.
+ secretText = "SECRET-SENTINEL-7f3a"
+)
+
+var fixedLaunch = time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)
+
+func testIdentity() compute.Identity {
+ return compute.Identity{Deployment: testDeployment, Fleet: "shop", Label: "box-1", Operation: "0123456789abcdef0123456789abcdef"}
+}
+
+func testSpec() compute.LaunchSpec {
+ return compute.LaunchSpec{
+ Identity: testIdentity(), Region: testRegion, InstanceType: "t4g.small", Image: testImage, Subnet: testSubnet,
+ SecurityGroups: []string{testSG, testSG2}, RootGB: 20,
+ UserData: "#cloud-config\n# " + secretText + "\n",
+ ClientToken: "0123456789abcdef0123456789abcdef",
+ }
+}
+
+func identityTags(id compute.Identity) map[string]string {
+ return map[string]string{"carlos:deployment": id.Deployment, "carlos:fleet": id.Fleet, "carlos:label": id.Label, "carlos:operation": id.Operation}
+}
+
+func apiErr(code string) error {
+ return &smithy.GenericAPIError{Code: code, Message: "message carrying " + secretText, Fault: smithy.FaultClient}
+}
+
+type fakeInstance struct {
+ id, owner, az string
+ state types.InstanceStateName
+ tags []types.Tag
+}
+
+type fakeToken struct {
+ in *ec2.RunInstancesInput
+ id string
+}
+
+// fakeEC2 is one region's EC2: an idempotent RunInstances keyed by
+// ClientToken, tag-filtered and paginated DescribeInstances, and hooks that
+// replace an answer wholesale.
+type fakeEC2 struct {
+ t *testing.T
+ region, account string
+ mu sync.Mutex
+ images map[string]types.Image
+ instances []*fakeInstance
+ tokens map[string]fakeToken
+ pageSize int
+ calls map[string]int
+ retries map[string]int
+ runInputs []*ec2.RunInstancesInput
+ describeInputs []*ec2.DescribeInstancesInput
+ imageInputs []*ec2.DescribeImagesInput
+ terminateInputs []*ec2.TerminateInstancesInput
+ consoleInputs []*ec2.GetConsoleOutputInput
+ runErr error
+ runLost bool
+ runOutput func(*ec2.RunInstancesOutput) *ec2.RunInstancesOutput
+ imagesErr error
+ imagesOutput *ec2.DescribeImagesOutput
+ describeErr error
+ describeHook func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error)
+ terminateErr error
+ terminateOutput *ec2.TerminateInstancesOutput
+ consoleOutput *ec2.GetConsoleOutputOutput
+ consoleErr error
+}
+
+func newFakeEC2(t *testing.T, region string) *fakeEC2 {
+ return &fakeEC2{
+ t: t, region: region, account: testAccount, pageSize: 1000,
+ images: map[string]types.Image{testImage: testImageFixture()},
+ tokens: map[string]fakeToken{}, calls: map[string]int{}, retries: map[string]int{},
+ }
+}
+
+func testImageFixture() types.Image {
+ return types.Image{
+ ImageId: aws.String(testImage), Architecture: types.ArchitectureValuesArm64, State: types.ImageStateAvailable,
+ RootDeviceType: types.DeviceTypeEbs, RootDeviceName: aws.String(testRootDevice),
+ BlockDeviceMappings: []types.BlockDeviceMapping{{DeviceName: aws.String(testRootDevice), Ebs: &types.EbsBlockDevice{
+ SnapshotId: aws.String("snap-0123456789abcdef0"), VolumeSize: aws.Int32(8), VolumeType: types.VolumeTypeGp2,
+ }}},
+ }
+}
+
+func (f *fakeEC2) opts(op string, optFns []func(*ec2.Options)) {
+ o := ec2.Options{Region: "unbound"}
+ for _, fn := range optFns {
+ fn(&o)
+ }
+ if o.Region != f.region {
+ f.t.Errorf("%s sent to region %q through the %s client", op, o.Region, f.region)
+ }
+ f.retries[op] = o.RetryMaxAttempts
+ f.calls[op]++
+}
+
+func (f *fakeEC2) callCount(op string) int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.calls[op]
+}
+
+func (f *fakeEC2) totalCalls() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ n := 0
+ for _, v := range f.calls {
+ n += v
+ }
+ return n
+}
+
+func (f *fakeEC2) add(tags map[string]string, state types.InstanceStateName) *fakeInstance {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.addLocked(tagList(tags), state)
+}
+
+func (f *fakeEC2) addLocked(tags []types.Tag, state types.InstanceStateName) *fakeInstance {
+ in := &fakeInstance{id: fmt.Sprintf("i-%017x", len(f.instances)+1), owner: f.account, az: f.region + "a", state: state, tags: tags}
+ f.instances = append(f.instances, in)
+ return in
+}
+
+func tagList(tags map[string]string) []types.Tag {
+ var out []types.Tag
+ for _, k := range []string{"carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation", "carlos:region", "Name"} {
+ if v, ok := tags[k]; ok {
+ out = append(out, types.Tag{Key: aws.String(k), Value: aws.String(v)})
+ }
+ }
+ return out
+}
+
+func (f *fakeEC2) view(in *fakeInstance) types.Instance {
+ return types.Instance{
+ InstanceId: aws.String(in.id), State: &types.InstanceState{Name: in.state},
+ Placement: &types.Placement{AvailabilityZone: aws.String(in.az)}, Tags: append([]types.Tag(nil), in.tags...),
+ LaunchTime: aws.Time(fixedLaunch),
+ }
+}
+
+func (f *fakeEC2) RunInstances(ctx context.Context, in *ec2.RunInstancesInput, optFns ...func(*ec2.Options)) (*ec2.RunInstancesOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.opts("RunInstances", optFns)
+ f.runInputs = append(f.runInputs, in)
+ if f.runErr != nil && !f.runLost {
+ return nil, f.runErr
+ }
+ token := aws.ToString(in.ClientToken)
+ var inst *fakeInstance
+ if prior, ok := f.tokens[token]; ok {
+ if !reflect.DeepEqual(prior.in, in) {
+ return nil, apiErr("IdempotentParameterMismatch")
+ }
+ for _, i := range f.instances {
+ if i.id == prior.id {
+ inst = i
+ }
+ }
+ } else {
+ var tags []types.Tag
+ for _, spec := range in.TagSpecifications {
+ if spec.ResourceType == types.ResourceTypeInstance {
+ tags = append(tags, spec.Tags...)
+ }
+ }
+ inst = f.addLocked(tags, types.InstanceStateNamePending)
+ f.tokens[token] = fakeToken{in: in, id: inst.id}
+ }
+ if f.runLost {
+ return nil, f.runErr
+ }
+ out := &ec2.RunInstancesOutput{OwnerId: aws.String(f.account), ReservationId: aws.String("r-0123456789abcdef0"), Instances: []types.Instance{f.view(inst)}}
+ if f.runOutput != nil {
+ out = f.runOutput(out)
+ }
+ return out, nil
+}
+
+func (f *fakeEC2) DescribeImages(ctx context.Context, in *ec2.DescribeImagesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeImagesOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.opts("DescribeImages", optFns)
+ f.imageInputs = append(f.imageInputs, in)
+ if f.imagesErr != nil {
+ return nil, f.imagesErr
+ }
+ if f.imagesOutput != nil {
+ return f.imagesOutput, nil
+ }
+ var out []types.Image
+ for _, id := range in.ImageIds {
+ img, ok := f.images[id]
+ if !ok {
+ return nil, apiErr("InvalidAMIID.NotFound")
+ }
+ out = append(out, img)
+ }
+ return &ec2.DescribeImagesOutput{Images: out}, nil
+}
+
+func (f *fakeEC2) DescribeInstances(ctx context.Context, in *ec2.DescribeInstancesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeInstancesOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.opts("DescribeInstances", optFns)
+ f.describeInputs = append(f.describeInputs, in)
+ if f.describeHook != nil {
+ return f.describeHook(in, len(f.describeInputs))
+ }
+ if f.describeErr != nil {
+ return nil, f.describeErr
+ }
+ var matched []*fakeInstance
+ if len(in.InstanceIds) > 0 {
+ for _, id := range in.InstanceIds {
+ found := false
+ for _, i := range f.instances {
+ if i.id == id {
+ matched, found = append(matched, i), true
+ }
+ }
+ if !found {
+ return nil, apiErr("InvalidInstanceID.NotFound")
+ }
+ }
+ } else {
+ matched = f.instances
+ }
+ var filtered []*fakeInstance
+ for _, i := range matched {
+ if f.matches(i, in.Filters) {
+ filtered = append(filtered, i)
+ }
+ }
+ start, _ := strconv.Atoi(aws.ToString(in.NextToken))
+ end := min(start+f.pageSize, len(filtered))
+ out := &ec2.DescribeInstancesOutput{}
+ for _, i := range filtered[start:end] {
+ out.Reservations = append(out.Reservations, types.Reservation{OwnerId: aws.String(i.owner), Instances: []types.Instance{f.view(i)}})
+ }
+ if end < len(filtered) {
+ out.NextToken = aws.String(strconv.Itoa(end))
+ }
+ return out, nil
+}
+
+func (f *fakeEC2) matches(i *fakeInstance, filters []types.Filter) bool {
+ for _, filter := range filters {
+ name := aws.ToString(filter.Name)
+ key, ok := strings.CutPrefix(name, "tag:")
+ if !ok {
+ f.t.Errorf("unexpected filter %q", name)
+ return false
+ }
+ hit := false
+ for _, tag := range i.tags {
+ for _, v := range filter.Values {
+ if aws.ToString(tag.Key) == key && aws.ToString(tag.Value) == v {
+ hit = true
+ }
+ }
+ }
+ if !hit {
+ return false
+ }
+ }
+ return true
+}
+
+func (f *fakeEC2) TerminateInstances(ctx context.Context, in *ec2.TerminateInstancesInput, optFns ...func(*ec2.Options)) (*ec2.TerminateInstancesOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.opts("TerminateInstances", optFns)
+ f.terminateInputs = append(f.terminateInputs, in)
+ if f.terminateErr != nil {
+ return nil, f.terminateErr
+ }
+ if f.terminateOutput != nil {
+ return f.terminateOutput, nil
+ }
+ out := &ec2.TerminateInstancesOutput{}
+ for _, id := range in.InstanceIds {
+ for _, i := range f.instances {
+ if i.id == id {
+ prev := i.state
+ i.state = types.InstanceStateNameShuttingDown
+ out.TerminatingInstances = append(out.TerminatingInstances, types.InstanceStateChange{
+ InstanceId: aws.String(id), PreviousState: &types.InstanceState{Name: prev}, CurrentState: &types.InstanceState{Name: i.state},
+ })
+ }
+ }
+ }
+ return out, nil
+}
+
+func (f *fakeEC2) GetConsoleOutput(ctx context.Context, in *ec2.GetConsoleOutputInput, optFns ...func(*ec2.Options)) (*ec2.GetConsoleOutputOutput, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.opts("GetConsoleOutput", optFns)
+ f.consoleInputs = append(f.consoleInputs, in)
+ if f.consoleErr != nil {
+ return nil, f.consoleErr
+ }
+ if f.consoleOutput != nil {
+ return f.consoleOutput, nil
+ }
+ return &ec2.GetConsoleOutputOutput{InstanceId: in.InstanceId}, nil
+}
+
+func newTestCompute(t *testing.T, fakes ...*fakeEC2) *Compute {
+ t.Helper()
+ cfg := ComputeConfig{Deployment: testDeployment, AccountID: testAccount}
+ clients := map[string]ec2API{}
+ for _, f := range fakes {
+ cfg.Regions = append(cfg.Regions, f.region)
+ clients[f.region] = f
+ }
+ c, err := newCompute(cfg, clients)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+// noLeak fails when an error or output carries the sentinel text.
+func noLeak(t *testing.T, s string) {
+ t.Helper()
+ if strings.Contains(s, secretText) || strings.Contains(s, "cloud-config") {
+ t.Fatalf("leaked private text: %q", s)
+ }
+}
+
+// ambiguous is the classification every unproven answer must get: an error
+// that is neither absence nor a rejection nor a conflict.
+func ambiguous(t *testing.T, err error) {
+ t.Helper()
+ 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) {
+ t.Fatalf("misclassified: %v", err)
+ }
+ noLeak(t, err.Error())
+}
+
+func TestAWSComputeLaunch(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ c := newTestCompute(t, f)
+ spec := testSpec()
+ got, err := c.Launch(context.Background(), spec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(f.instances) != 1 {
+ t.Fatalf("%d instances", len(f.instances))
+ }
+ want := compute.Instance{CloudID: f.instances[0].id, Region: testRegion, Identity: spec.Identity, State: compute.StatePending, LaunchedAt: fixedLaunch}
+ if got != want {
+ t.Fatalf("got %+v, want %+v", got, want)
+ }
+ // Exactly the pinned image check and one launch; nothing else is fetched.
+ if f.callCount("DescribeImages") != 1 || f.callCount("RunInstances") != 1 || f.totalCalls() != 2 {
+ t.Fatalf("calls %v", f.calls)
+ }
+ if img := f.imageInputs[0]; !reflect.DeepEqual(img.ImageIds, []string{testImage}) || img.Filters != nil || img.Owners != nil {
+ t.Fatalf("image query %+v", img)
+ }
+ if f.retries["RunInstances"] != 1 {
+ t.Fatalf("RunInstances may retry %d times", f.retries["RunInstances"])
+ }
+ in := f.runInputs[0]
+ if aws.ToString(in.ClientToken) != spec.ClientToken || aws.ToString(in.ImageId) != testImage || in.InstanceType != "t4g.small" {
+ t.Fatalf("request %+v", in)
+ }
+ if aws.ToInt32(in.MinCount) != 1 || aws.ToInt32(in.MaxCount) != 1 {
+ t.Fatal("count is not exactly one")
+ }
+ if aws.ToString(in.UserData) != base64.StdEncoding.EncodeToString([]byte(spec.UserData)) {
+ t.Fatal("user data is not the frozen bytes encoded once")
+ }
+ if in.IamInstanceProfile != nil || in.KeyName != nil || in.LaunchTemplate != nil || in.InstanceMarketOptions != nil ||
+ in.SubnetId != nil || in.SecurityGroupIds != nil || in.SecurityGroups != nil || in.PrivateIpAddress != nil {
+ t.Fatalf("request carries a profile, key, template, spot or top-level network field: %+v", in)
+ }
+ md := in.MetadataOptions
+ if md == nil || md.HttpTokens != types.HttpTokensStateRequired || aws.ToInt32(md.HttpPutResponseHopLimit) != 1 || md.HttpEndpoint != types.InstanceMetadataEndpointStateEnabled {
+ t.Fatalf("metadata options %+v", md)
+ }
+ if len(in.BlockDeviceMappings) != 1 {
+ t.Fatalf("block devices %+v", in.BlockDeviceMappings)
+ }
+ root := in.BlockDeviceMappings[0]
+ if aws.ToString(root.DeviceName) != testRootDevice || root.Ebs == nil || aws.ToInt32(root.Ebs.VolumeSize) != 20 ||
+ root.Ebs.VolumeType != types.VolumeTypeGp3 || !aws.ToBool(root.Ebs.Encrypted) || !aws.ToBool(root.Ebs.DeleteOnTermination) ||
+ root.Ebs.SnapshotId != nil || root.Ebs.KmsKeyId != nil || root.NoDevice != nil || root.VirtualName != nil {
+ t.Fatalf("root mapping %+v %+v", root, root.Ebs)
+ }
+ if len(in.NetworkInterfaces) != 1 {
+ t.Fatalf("interfaces %+v", in.NetworkInterfaces)
+ }
+ eni := in.NetworkInterfaces[0]
+ if aws.ToInt32(eni.DeviceIndex) != 0 || aws.ToString(eni.SubnetId) != testSubnet || !reflect.DeepEqual(eni.Groups, []string{testSG, testSG2}) ||
+ !aws.ToBool(eni.DeleteOnTermination) || !aws.ToBool(eni.AssociatePublicIpAddress) || eni.NetworkInterfaceId != nil {
+ t.Fatalf("interface %+v", eni)
+ }
+ if len(in.TagSpecifications) != 2 {
+ t.Fatalf("tag specifications %+v", in.TagSpecifications)
+ }
+ wantTags := tagList(identityTags(spec.Identity))
+ for i, rt := range []types.ResourceType{types.ResourceTypeInstance, types.ResourceTypeVolume} {
+ ts := in.TagSpecifications[i]
+ if ts.ResourceType != rt || !reflect.DeepEqual(ts.Tags, wantTags) {
+ t.Fatalf("tags for %s: %+v", rt, ts)
+ }
+ }
+}
+
+func TestAWSComputeLaunchRefusals(t *testing.T) {
+ long := strings.Repeat("a", 257)
+ for name, mutate := range map[string]func(*compute.LaunchSpec){
+ "no deployment": func(s *compute.LaunchSpec) { s.Deployment = "" },
+ "other deployment": func(s *compute.LaunchSpec) { s.Deployment = "staging" },
+ "no fleet": func(s *compute.LaunchSpec) { s.Fleet = "" },
+ "no label": func(s *compute.LaunchSpec) { s.Label = "" },
+ "no operation": func(s *compute.LaunchSpec) { s.Operation = "" },
+ "control in fleet": func(s *compute.LaunchSpec) { s.Fleet = "shop\nx" },
+ "long label": func(s *compute.LaunchSpec) { s.Label = long },
+ "no region": func(s *compute.LaunchSpec) { s.Region = "" },
+ "unconfigured region": func(s *compute.LaunchSpec) { s.Region = "us-east-1" },
+ "x86 type": func(s *compute.LaunchSpec) { s.InstanceType = "m5.large" },
+ "unknown family": func(s *compute.LaunchSpec) { s.InstanceType = "a1.large" },
+ "bad size": func(s *compute.LaunchSpec) { s.InstanceType = "t4g.huge" },
+ "bad image": func(s *compute.LaunchSpec) { s.Image = "ami-123" },
+ "bad subnet": func(s *compute.LaunchSpec) { s.Subnet = "subnet-x" },
+ "no groups": func(s *compute.LaunchSpec) { s.SecurityGroups = nil },
+ "bad group": func(s *compute.LaunchSpec) { s.SecurityGroups = []string{"sg-nope"} },
+ "duplicate group": func(s *compute.LaunchSpec) { s.SecurityGroups = []string{testSG, testSG} },
+ "zero disk": func(s *compute.LaunchSpec) { s.RootGB = 0 },
+ "negative disk": func(s *compute.LaunchSpec) { s.RootGB = -1 },
+ "huge disk": func(s *compute.LaunchSpec) { s.RootGB = 16385 },
+ "no user data": func(s *compute.LaunchSpec) { s.UserData = "" },
+ "user data too long": func(s *compute.LaunchSpec) { s.UserData = strings.Repeat("x", 16385) },
+ "no token": func(s *compute.LaunchSpec) { s.ClientToken = "" },
+ "long token": func(s *compute.LaunchSpec) { s.ClientToken = strings.Repeat("a", 65) },
+ "spaced token": func(s *compute.LaunchSpec) { s.ClientToken = "a b" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ c := newTestCompute(t, f)
+ spec := testSpec()
+ mutate(&spec)
+ _, err := c.Launch(context.Background(), spec)
+ if !errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, compute.ErrLaunchConflict) {
+ t.Fatalf("got %v", err)
+ }
+ noLeak(t, err.Error())
+ if f.totalCalls() != 0 {
+ t.Fatalf("calls %v", f.calls)
+ }
+ })
+ }
+ t.Run("16 KiB user data is accepted", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ spec := testSpec()
+ spec.UserData = strings.Repeat("x", 16384)
+ if _, err := newTestCompute(t, f).Launch(context.Background(), spec); err != nil {
+ t.Fatal(err)
+ }
+ })
+ for name, mutate := range map[string]func(*types.Image){
+ "x86 image": func(i *types.Image) { i.Architecture = types.ArchitectureValuesX8664 },
+ "pending image": func(i *types.Image) { i.State = types.ImageStatePending },
+ "instance store": func(i *types.Image) { i.RootDeviceType = types.DeviceTypeInstanceStore },
+ "no root name": func(i *types.Image) { i.RootDeviceName = nil },
+ "root not mapped": func(i *types.Image) { i.RootDeviceName = aws.String("/dev/xvda") },
+ "root without ebs": func(i *types.Image) { i.BlockDeviceMappings[0].Ebs = nil },
+ "root without size": func(i *types.Image) { i.BlockDeviceMappings[0].Ebs.VolumeSize = nil },
+ "source too large": func(i *types.Image) { i.BlockDeviceMappings[0].Ebs.VolumeSize = aws.Int32(21) },
+ "extra mapping": func(i *types.Image) {
+ i.BlockDeviceMappings = append(i.BlockDeviceMappings, types.BlockDeviceMapping{DeviceName: aws.String("/dev/sdb"), VirtualName: aws.String("ephemeral0")})
+ },
+ "duplicate root": func(i *types.Image) {
+ i.BlockDeviceMappings = append(i.BlockDeviceMappings, i.BlockDeviceMappings[0])
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ img := testImageFixture()
+ mutate(&img)
+ f.images[testImage] = img
+ _, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ if !errors.Is(err, compute.ErrLaunchRejected) {
+ t.Fatalf("got %v", err)
+ }
+ if f.callCount("RunInstances") != 0 {
+ t.Fatal("launched on an unsupported image")
+ }
+ })
+ }
+ t.Run("missing image", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ delete(f.images, testImage)
+ _, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ if !errors.Is(err, compute.ErrLaunchRejected) || f.callCount("RunInstances") != 0 {
+ t.Fatalf("got %v, calls %v", err, f.calls)
+ }
+ noLeak(t, err.Error())
+ })
+ 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 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")}
+ },
+ "other image": func(f *fakeEC2) {
+ img := testImageFixture()
+ img.ImageId = aws.String("ami-0aaaaaaaaaaaaaaaa")
+ f.imagesOutput = &ec2.DescribeImagesOutput{Images: []types.Image{img}}
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ set(f)
+ _, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ ambiguous(t, err)
+ if f.callCount("RunInstances") != 0 {
+ t.Fatal("launched without a verified image")
+ }
+ })
+ }
+}
+
+func TestAWSComputeLaunchErrors(t *testing.T) {
+ for _, code := range []string{"InvalidAMIID.Malformed", "InvalidSubnetID.NotFound", "InvalidGroup.NotFound", "InvalidParameterValue", "Unsupported", "UnauthorizedOperation", "InsufficientInstanceCapacity", "InstanceLimitExceeded"} {
+ t.Run(code, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.runErr = apiErr(code)
+ _, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ if !errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, compute.ErrLaunchConflict) || errors.Is(err, errAmbiguous) {
+ t.Fatalf("got %v", err)
+ }
+ noLeak(t, err.Error())
+ })
+ }
+ for _, code := range []string{"InternalError", "RequestLimitExceeded", "ServiceUnavailable", "InvalidAMIID.NotFound", "SomethingNew"} {
+ t.Run(code, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.runErr = apiErr(code)
+ _, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ ambiguous(t, err)
+ })
+ }
+ t.Run("timeout", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.runErr = context.DeadlineExceeded
+ _, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ ambiguous(t, err)
+ })
+ t.Run("lost response", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.runErr, f.runLost = errors.New("connection reset "+secretText), true
+ c := newTestCompute(t, f)
+ _, err := c.Launch(context.Background(), testSpec())
+ ambiguous(t, err)
+ found, err := c.Find(context.Background(), testRegion, testIdentity())
+ if err != nil || len(found) != 1 || found[0].CloudID != f.instances[0].id {
+ t.Fatalf("lost launch not discoverable: %v %v", found, err)
+ }
+ })
+ for name, edit := range map[string]func(*ec2.RunInstancesOutput) *ec2.RunInstancesOutput{
+ "nil output": func(*ec2.RunInstancesOutput) *ec2.RunInstancesOutput { return nil },
+ "no instance": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput { o.Instances = nil; return o },
+ "two instances": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput {
+ o.Instances = append(o.Instances, o.Instances[0])
+ return o
+ },
+ "other owner": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput {
+ o.OwnerId = aws.String("999999999999")
+ return o
+ },
+ "bad id": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput {
+ o.Instances[0].InstanceId = aws.String("i-zz")
+ return o
+ },
+ "no state": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput { o.Instances[0].State = nil; return o },
+ "other region": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput {
+ o.Instances[0].Placement.AvailabilityZone = aws.String(otherRegion + "a")
+ return o
+ },
+ "other identity": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput {
+ o.Instances[0].Tags[1].Value = aws.String("other")
+ return o
+ },
+ "partial identity": func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput {
+ o.Instances[0].Tags = o.Instances[0].Tags[:3]
+ return o
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.runOutput = edit
+ _, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ ambiguous(t, err)
+ })
+ }
+ t.Run("untagged response trusts the tagged request", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.runOutput = func(o *ec2.RunInstancesOutput) *ec2.RunInstancesOutput { o.Instances[0].Tags = nil; return o }
+ got, err := newTestCompute(t, f).Launch(context.Background(), testSpec())
+ if err != nil || got.Identity != testIdentity() {
+ t.Fatalf("%+v %v", got, err)
+ }
+ })
+}
+
+func TestAWSComputeFrozenRequest(t *testing.T) {
+ regions := []string{testRegion}
+ f1 := newFakeEC2(t, testRegion)
+ c1, err := newCompute(ComputeConfig{Deployment: testDeployment, AccountID: testAccount, Regions: regions}, map[string]ec2API{testRegion: f1})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The caller's configuration source changes after construction.
+ regions[0] = otherRegion
+ spec := testSpec()
+ first, err := c1.Launch(context.Background(), spec)
+ if err != nil {
+ t.Fatal(err)
+ }
+ spec.SecurityGroups[0] = "sg-0aaaaaaaaaaaaaaaa"
+ if g := f1.runInputs[0].NetworkInterfaces[0].Groups; g[0] != testSG {
+ t.Fatal("request shares the caller's slice")
+ }
+ retry, err := c1.Launch(context.Background(), testSpec())
+ if err != nil || retry != first {
+ t.Fatalf("retry %+v %v", retry, err)
+ }
+ if len(f1.instances) != 1 || !reflect.DeepEqual(f1.runInputs[0], f1.runInputs[1]) {
+ t.Fatal("retry changed the request")
+ }
+ // A recreated adapter (a console restart) builds the same bytes.
+ f2 := newFakeEC2(t, testRegion)
+ c2 := newTestCompute(t, f2)
+ if _, err := c2.Launch(context.Background(), testSpec()); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(f1.runInputs[0], f2.runInputs[0]) {
+ t.Fatalf("recreated adapter built another request:\n%+v\n%+v", f1.runInputs[0], f2.runInputs[0])
+ }
+}
+
+func TestAWSComputeClientTokenConflict(t *testing.T) {
+ for name, mutate := range map[string]func(*compute.LaunchSpec){
+ "user data": func(s *compute.LaunchSpec) { s.UserData += "changed\n" },
+ "root disk": func(s *compute.LaunchSpec) { s.RootGB = 30 },
+ "groups": func(s *compute.LaunchSpec) { s.SecurityGroups = []string{testSG} },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ c := newTestCompute(t, f)
+ first, err := c.Launch(context.Background(), testSpec())
+ if err != nil {
+ t.Fatal(err)
+ }
+ changed := testSpec()
+ mutate(&changed)
+ _, err = c.Launch(context.Background(), changed)
+ if !errors.Is(err, compute.ErrLaunchConflict) || errors.Is(err, compute.ErrLaunchRejected) || errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("got %v", err)
+ }
+ noLeak(t, err.Error())
+ found, err := c.Find(context.Background(), testRegion, testIdentity())
+ if err != nil || len(found) != 1 || found[0].CloudID != first.CloudID {
+ t.Fatalf("earlier instance not discoverable: %v %v", found, err)
+ }
+ exact, err := c.Lookup(context.Background(), testRegion, first.CloudID)
+ if err != nil || exact.CloudID != first.CloudID || exact.Identity != testIdentity() {
+ t.Fatalf("lookup %+v %v", exact, err)
+ }
+ })
+ }
+}
+
+func page(owner string, insts ...types.Instance) types.Reservation {
+ return types.Reservation{OwnerId: aws.String(owner), Instances: insts}
+}
+
+func managedView(id string, ident compute.Identity, state types.InstanceStateName) types.Instance {
+ return types.Instance{InstanceId: aws.String(id), State: &types.InstanceState{Name: state},
+ Placement: &types.Placement{AvailabilityZone: aws.String(testRegion + "b")}, Tags: tagList(identityTags(ident)), LaunchTime: aws.Time(fixedLaunch)}
+}
+
+func TestAWSComputeDescribeComplete(t *testing.T) {
+ ctx := context.Background()
+ idA, idB := "i-0aaaaaaaaaaaaaaaa", "i-0bbbbbbbbbbbbbbbb"
+ t.Run("instance on a later page", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.describeHook = func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ if call == 1 {
+ return &ec2.DescribeInstancesOutput{NextToken: aws.String("t2")}, nil
+ }
+ return &ec2.DescribeInstancesOutput{Reservations: []types.Reservation{page(testAccount, managedView(idA, testIdentity(), types.InstanceStateNameRunning))}}, nil
+ }
+ found, err := newTestCompute(t, f).Find(ctx, testRegion, testIdentity())
+ if err != nil || len(found) != 1 || found[0].CloudID != idA || found[0].State != compute.StateRunning {
+ t.Fatalf("%v %v", found, err)
+ }
+ if len(f.describeInputs) != 2 || aws.ToString(f.describeInputs[1].NextToken) != "t2" || !reflect.DeepEqual(f.describeInputs[0].Filters, f.describeInputs[1].Filters) {
+ t.Fatalf("pages %+v", f.describeInputs)
+ }
+ filters := map[string][]string{}
+ for _, fl := range f.describeInputs[0].Filters {
+ filters[aws.ToString(fl.Name)] = fl.Values
+ }
+ want := map[string][]string{}
+ for k, v := range identityTags(testIdentity()) {
+ want["tag:"+k] = []string{v}
+ }
+ if !reflect.DeepEqual(filters, want) || f.describeInputs[0].InstanceIds != nil {
+ t.Fatalf("filters %v", filters)
+ }
+ })
+ t.Run("deployment listing walks every page", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.pageSize = 1
+ for i := range 3 {
+ id := testIdentity()
+ id.Label = fmt.Sprintf("box-%d", i+1)
+ f.add(identityTags(id), types.InstanceStateNameRunning)
+ }
+ got, err := newTestCompute(t, f).ListDeployment(ctx, testRegion, testDeployment)
+ if err != nil || len(got) != 3 || f.callCount("DescribeInstances") != 3 {
+ t.Fatalf("%v %v %v", got, err, f.calls)
+ }
+ })
+ broken := map[string]func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error){
+ "next page fails": func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ if in.NextToken == nil {
+ return &ec2.DescribeInstancesOutput{Reservations: []types.Reservation{page(testAccount, managedView(idA, testIdentity(), types.InstanceStateNameRunning))}, NextToken: aws.String("t2")}, nil
+ }
+ return nil, apiErr("RequestLimitExceeded")
+ },
+ "repeated token": func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ return &ec2.DescribeInstancesOutput{Reservations: []types.Reservation{page(testAccount, managedView(fmt.Sprintf("i-%017x", call), testIdentity(), types.InstanceStateNameRunning))}, NextToken: aws.String("same")}, nil
+ },
+ "token cycle": func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ return &ec2.DescribeInstancesOutput{NextToken: aws.String([]string{"a", "b"}[call%2])}, nil
+ },
+ "endless pages": func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ return &ec2.DescribeInstancesOutput{NextToken: aws.String(fmt.Sprintf("t%d", call))}, nil
+ },
+ "nil page": func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ return nil, nil
+ },
+ "duplicate across pages": func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ out := &ec2.DescribeInstancesOutput{Reservations: []types.Reservation{page(testAccount, managedView(idA, testIdentity(), types.InstanceStateNameRunning))}}
+ if in.NextToken == nil {
+ out.NextToken = aws.String("t2")
+ }
+ return out, nil
+ },
+ "conflicting duplicate": func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ return &ec2.DescribeInstancesOutput{Reservations: []types.Reservation{page(testAccount,
+ managedView(idA, testIdentity(), types.InstanceStateNameRunning), managedView(idA, testIdentity(), types.InstanceStateNameTerminated))}}, nil
+ },
+ }
+ malformed := map[string]func(*types.Reservation){
+ "other owner": func(r *types.Reservation) { r.OwnerId = aws.String("999999999999") },
+ "no owner": func(r *types.Reservation) { r.OwnerId = nil },
+ "no id": func(r *types.Reservation) { r.Instances[0].InstanceId = nil },
+ "malformed id": func(r *types.Reservation) { r.Instances[0].InstanceId = aws.String("i-zzz") },
+ "no state": func(r *types.Reservation) { r.Instances[0].State = nil },
+ "unknown state": func(r *types.Reservation) { r.Instances[0].State.Name = "rebooting" },
+ "other region": func(r *types.Reservation) { r.Instances[0].Placement.AvailabilityZone = aws.String(otherRegion + "a") },
+ "no placement": func(r *types.Reservation) { r.Instances[0].Placement = nil },
+ "other identity": func(r *types.Reservation) { r.Instances[0].Tags[2].Value = aws.String("box-9") },
+ "duplicate tag": func(r *types.Reservation) { r.Instances[0].Tags = append(r.Instances[0].Tags, r.Instances[0].Tags[1]) },
+ }
+ for name, edit := range malformed {
+ broken[name] = func(in *ec2.DescribeInstancesInput, call int) (*ec2.DescribeInstancesOutput, error) {
+ r := page(testAccount, managedView(idA, testIdentity(), types.InstanceStateNameRunning))
+ edit(&r)
+ return &ec2.DescribeInstancesOutput{Reservations: []types.Reservation{r}}, nil
+ }
+ }
+ for name, hook := range broken {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.describeHook = hook
+ c := newTestCompute(t, f)
+ found, err := c.Find(ctx, testRegion, testIdentity())
+ if found != nil {
+ t.Fatalf("usable prefix %v", found)
+ }
+ ambiguous(t, err)
+ n := f.callCount("DescribeInstances")
+ if n > maxDescribePages || (name == "repeated token" && n != 2) || (name == "token cycle" && n != 3) {
+ t.Fatalf("%d pages", n)
+ }
+ if name == "other identity" {
+ return // a deployment listing or an exact lookup may legitimately see this
+ }
+ list, err := c.ListDeployment(ctx, testRegion, testDeployment)
+ if list != nil {
+ t.Fatalf("usable prefix %v", list)
+ }
+ ambiguous(t, err)
+ _, err = c.Lookup(ctx, testRegion, idA)
+ ambiguous(t, err)
+ })
+ }
+ t.Run("exact lookup has no tag filter", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ inst := f.add(map[string]string{"Name": "untagged"}, types.InstanceStateNameRunning)
+ got, err := newTestCompute(t, f).Lookup(ctx, testRegion, inst.id)
+ if err != nil || got.CloudID != inst.id || got.Identity != (compute.Identity{}) || got.Region != testRegion {
+ t.Fatalf("%+v %v", got, err)
+ }
+ in := f.describeInputs[0]
+ if !reflect.DeepEqual(in.InstanceIds, []string{inst.id}) || in.Filters != nil || in.NextToken != nil {
+ t.Fatalf("lookup query %+v", in)
+ }
+ })
+ for name, out := range map[string]*ec2.DescribeInstancesOutput{
+ "lookup empty success": {},
+ "lookup other id": {Reservations: []types.Reservation{page(testAccount, managedView(idB, testIdentity(), types.InstanceStateNameRunning))}},
+ "lookup two": {Reservations: []types.Reservation{page(testAccount, managedView(idA, testIdentity(), types.InstanceStateNameRunning)), page(testAccount, managedView(idB, testIdentity(), types.InstanceStateNameRunning))}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.describeHook = func(*ec2.DescribeInstancesInput, int) (*ec2.DescribeInstancesOutput, error) { return out, nil }
+ _, err := newTestCompute(t, f).Lookup(ctx, testRegion, idA)
+ ambiguous(t, err)
+ })
+ }
+}
+
+func TestAWSComputeAbsence(t *testing.T) {
+ ctx := context.Background()
+ t.Run("empty find is not absence", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ found, err := newTestCompute(t, f).Find(ctx, testRegion, testIdentity())
+ if err != nil || len(found) != 0 {
+ t.Fatalf("%v %v", found, err)
+ }
+ })
+ t.Run("exact NotFound is absence", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ _, err := newTestCompute(t, f).Lookup(ctx, testRegion, "i-0aaaaaaaaaaaaaaaa")
+ if !errors.Is(err, os.ErrNotExist) || errors.Is(err, errAmbiguous) {
+ t.Fatalf("got %v", err)
+ }
+ noLeak(t, err.Error())
+ })
+ for name, err := range map[string]error{
+ "throttle": apiErr("RequestLimitExceeded"),
+ "server error": &smithy.GenericAPIError{Code: "InternalError", Message: secretText, Fault: smithy.FaultServer},
+ "unavailable": apiErr("Unavailable"),
+ "access denied": apiErr("UnauthorizedOperation"),
+ "malformed id": apiErr("InvalidInstanceID.Malformed"),
+ "similar code": apiErr("InvalidInstanceID.NotFound.Extra"),
+ "timeout": context.DeadlineExceeded,
+ "transport failed": errors.New("dial tcp: " + secretText),
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.describeErr = err
+ c := newTestCompute(t, f)
+ _, got := c.Lookup(ctx, testRegion, "i-0aaaaaaaaaaaaaaaa")
+ ambiguous(t, got)
+ found, got := c.Find(ctx, testRegion, testIdentity())
+ if found != nil {
+ t.Fatal(found)
+ }
+ ambiguous(t, got)
+ list, got := c.ListDeployment(ctx, testRegion, testDeployment)
+ if list != nil {
+ t.Fatal(list)
+ }
+ ambiguous(t, got)
+ })
+ }
+ t.Run("cancelled context", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.describeErr = context.Canceled
+ cctx, cancel := context.WithCancel(ctx)
+ cancel()
+ _, err := newTestCompute(t, f).Lookup(cctx, testRegion, "i-0aaaaaaaaaaaaaaaa")
+ ambiguous(t, err)
+ })
+ for state, want := range map[types.InstanceStateName]compute.State{
+ types.InstanceStateNamePending: compute.StatePending, types.InstanceStateNameRunning: compute.StateRunning,
+ types.InstanceStateNameStopping: compute.StateStopping, types.InstanceStateNameStopped: compute.StateStopped,
+ types.InstanceStateNameShuttingDown: compute.StateShuttingDown, types.InstanceStateNameTerminated: compute.StateTerminated,
+ } {
+ t.Run(string(state), func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ inst := f.add(identityTags(testIdentity()), state)
+ c := newTestCompute(t, f)
+ found, err := c.Find(ctx, testRegion, testIdentity())
+ if err != nil || len(found) != 1 || found[0].State != want {
+ t.Fatalf("%v %v", found, err)
+ }
+ exact, err := c.Lookup(ctx, testRegion, inst.id)
+ if err != nil || exact.State != want || exact.Identity != testIdentity() {
+ t.Fatalf("%+v %v", exact, err)
+ }
+ })
+ }
+}
+
+func TestAWSComputeTerminateIdentity(t *testing.T) {
+ ctx := context.Background()
+ keys := []string{"carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation"}
+ for _, key := range keys {
+ for kind, edit := range map[string]func([]types.Tag) []types.Tag{
+ "mismatch": func(tags []types.Tag) []types.Tag {
+ for i := range tags {
+ if aws.ToString(tags[i].Key) == key {
+ tags[i].Value = aws.String("other")
+ }
+ }
+ return tags
+ },
+ "missing": func(tags []types.Tag) []types.Tag {
+ var out []types.Tag
+ for _, tag := range tags {
+ if aws.ToString(tag.Key) != key {
+ out = append(out, tag)
+ }
+ }
+ return out
+ },
+ "empty": func(tags []types.Tag) []types.Tag {
+ for i := range tags {
+ if aws.ToString(tags[i].Key) == key {
+ tags[i].Value = aws.String("")
+ }
+ }
+ return tags
+ },
+ "duplicate": func(tags []types.Tag) []types.Tag {
+ return append(tags, types.Tag{Key: aws.String(key), Value: aws.String("other")})
+ },
+ "duplicate same value": func(tags []types.Tag) []types.Tag {
+ for _, tag := range tags {
+ if aws.ToString(tag.Key) == key {
+ return append(tags, tag)
+ }
+ }
+ return tags
+ },
+ } {
+ t.Run(key+" "+kind, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ inst := f.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ inst.tags = edit(inst.tags)
+ err := newTestCompute(t, f).Terminate(ctx, testRegion, inst.id, testIdentity())
+ if !errors.Is(err, compute.ErrIdentityMismatch) || errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("got %v", err)
+ }
+ if f.callCount("TerminateInstances") != 0 {
+ t.Fatal("terminated a mismatched instance")
+ }
+ })
+ }
+ }
+ for name, call := range map[string]func(c *Compute, id string) error{
+ "want other deployment": func(c *Compute, id string) error {
+ want := testIdentity()
+ want.Deployment = "staging"
+ return c.Terminate(ctx, testRegion, id, want)
+ },
+ "want empty operation": func(c *Compute, id string) error {
+ want := testIdentity()
+ want.Operation = ""
+ return c.Terminate(ctx, testRegion, id, want)
+ },
+ "unconfigured region": func(c *Compute, id string) error { return c.Terminate(ctx, "us-east-1", id, testIdentity()) },
+ "invalid id": func(c *Compute, id string) error { return c.Terminate(ctx, testRegion, "i-nope", testIdentity()) },
+ "empty id": func(c *Compute, id string) error { return c.Terminate(ctx, testRegion, "", testIdentity()) },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ inst := f.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ err := call(newTestCompute(t, f), inst.id)
+ if err == nil || errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("got %v", err)
+ }
+ if f.callCount("TerminateInstances") != 0 {
+ t.Fatal("terminate sent")
+ }
+ })
+ }
+ t.Run("wrong region client", func(t *testing.T) {
+ home, other := newFakeEC2(t, testRegion), newFakeEC2(t, otherRegion)
+ inst := home.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ err := newTestCompute(t, home, other).Terminate(ctx, otherRegion, inst.id, testIdentity())
+ ambiguous(t, err)
+ if home.callCount("TerminateInstances")+other.callCount("TerminateInstances") != 0 {
+ t.Fatal("terminate sent")
+ }
+ })
+ t.Run("pre-lookup NotFound is ambiguity", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ err := newTestCompute(t, f).Terminate(ctx, testRegion, "i-0aaaaaaaaaaaaaaaa", testIdentity())
+ ambiguous(t, err)
+ if f.callCount("TerminateInstances") != 0 {
+ t.Fatal("terminate sent")
+ }
+ })
+ t.Run("pre-lookup failure", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.describeErr = apiErr("RequestLimitExceeded")
+ err := newTestCompute(t, f).Terminate(ctx, testRegion, "i-0aaaaaaaaaaaaaaaa", testIdentity())
+ ambiguous(t, err)
+ if f.callCount("TerminateInstances") != 0 {
+ t.Fatal("terminate sent")
+ }
+ })
+ t.Run("exact match terminates one id", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ f.add(identityTags(compute.Identity{Deployment: testDeployment, Fleet: "shop", Label: "box-2", Operation: "x"}), types.InstanceStateNameRunning)
+ inst := f.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ c := newTestCompute(t, f)
+ if err := c.Terminate(ctx, testRegion, inst.id, testIdentity()); err != nil {
+ t.Fatal(err)
+ }
+ if len(f.terminateInputs) != 1 || !reflect.DeepEqual(f.terminateInputs[0].InstanceIds, []string{inst.id}) || f.retries["TerminateInstances"] != 1 {
+ t.Fatalf("terminate %+v retries %d", f.terminateInputs, f.retries["TerminateInstances"])
+ }
+ if in := f.describeInputs[0]; !reflect.DeepEqual(in.InstanceIds, []string{inst.id}) || in.Filters != nil {
+ t.Fatalf("pre-lookup %+v", in)
+ }
+ // Acceptance is not an observation of termination.
+ got, err := c.Lookup(ctx, testRegion, inst.id)
+ if err != nil || got.State != compute.StateShuttingDown {
+ t.Fatalf("%+v %v", got, err)
+ }
+ })
+ for name, set := range map[string]func(*fakeEC2){
+ "terminate throttled": func(f *fakeEC2) { f.terminateErr = apiErr("RequestLimitExceeded") },
+ "terminate NotFound": func(f *fakeEC2) { f.terminateErr = apiErr("InvalidInstanceID.NotFound") },
+ "terminate other id": func(f *fakeEC2) {
+ f.terminateOutput = &ec2.TerminateInstancesOutput{TerminatingInstances: []types.InstanceStateChange{{InstanceId: aws.String("i-0bbbbbbbbbbbbbbbb")}}}
+ },
+ "terminate empty answer": func(f *fakeEC2) { f.terminateOutput = &ec2.TerminateInstancesOutput{} },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ set(f)
+ inst := f.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ err := newTestCompute(t, f).Terminate(ctx, testRegion, inst.id, testIdentity())
+ ambiguous(t, err)
+ if f.callCount("TerminateInstances") != 1 {
+ t.Fatal("terminate count")
+ }
+ })
+ }
+}
+
+func TestAWSComputeManagedTags(t *testing.T) {
+ ctx := context.Background()
+ f := newFakeEC2(t, testRegion)
+ // The region host carries deployment and region only (group.tf group_tags).
+ host := f.add(map[string]string{"carlos:deployment": testDeployment, "carlos:region": testRegion, "Name": "region-host"}, types.InstanceStateNameRunning)
+ managed := f.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ for _, key := range []string{"carlos:fleet", "carlos:label", "carlos:operation"} {
+ tags := identityTags(testIdentity())
+ delete(tags, key)
+ f.add(tags, types.InstanceStateNameRunning)
+ tags = identityTags(testIdentity())
+ tags[key] = ""
+ f.add(tags, types.InstanceStateNameRunning)
+ }
+ other := testIdentity()
+ other.Deployment = "staging"
+ f.add(identityTags(other), types.InstanceStateNameRunning)
+ c := newTestCompute(t, f)
+ got, err := c.ListDeployment(ctx, testRegion, testDeployment)
+ if err != nil || len(got) != 1 || got[0].CloudID != managed.id || got[0].Identity != testIdentity() {
+ t.Fatalf("%v %v", got, err)
+ }
+ if _, err := c.ListDeployment(ctx, testRegion, "staging"); err == nil {
+ t.Fatal("listed another deployment")
+ }
+ if err := c.Terminate(ctx, testRegion, host.id, compute.Identity{Deployment: testDeployment, Fleet: "shop", Label: "box-1", Operation: "x"}); !errors.Is(err, compute.ErrIdentityMismatch) {
+ t.Fatalf("got %v", err)
+ }
+ if _, err := c.ConsoleOutput(ctx, testRegion, host.id); !errors.Is(err, compute.ErrIdentityMismatch) {
+ t.Fatalf("got %v", err)
+ }
+ if f.callCount("TerminateInstances") != 0 || f.callCount("GetConsoleOutput") != 0 {
+ t.Fatalf("calls %v", f.calls)
+ }
+}
+
+func TestAWSComputeConfig(t *testing.T) {
+ fake := newFakeEC2(t, testRegion)
+ for name, cfg := range map[string]ComputeConfig{
+ "no deployment": {AccountID: testAccount, Regions: []string{testRegion}},
+ "bad account": {Deployment: testDeployment, AccountID: "12345", Regions: []string{testRegion}},
+ "no regions": {Deployment: testDeployment, AccountID: testAccount},
+ "bad region": {Deployment: testDeployment, AccountID: testAccount, Regions: []string{"Europe"}},
+ "duplicate region": {Deployment: testDeployment, AccountID: testAccount, Regions: []string{testRegion, testRegion}},
+ "missing client": {Deployment: testDeployment, AccountID: testAccount, Regions: []string{testRegion, otherRegion}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ if _, err := newCompute(cfg, map[string]ec2API{testRegion: fake}); err == nil {
+ t.Fatal("accepted")
+ }
+ })
+ }
+ if _, err := NewCompute(context.Background(), ComputeConfig{Deployment: testDeployment, AccountID: testAccount}); err == nil {
+ t.Fatal("loaded without an explicit region")
+ }
+}
+
+type transportFunc func(*http.Request) (*http.Response, error)
+
+func (f transportFunc) Do(r *http.Request) (*http.Response, error) { return f(r) }
+
+func xmlResponse(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 xmlError(status int, code string) *http.Response {
+ return xmlResponse(status, `<Response><Errors><Error><Code>`+code+`</Code><Message>user data `+secretText+`</Message></Error></Errors><RequestID>req</RequestID></Response>`)
+}
+
+const xmlInstance = `<item><instanceId>i-0123456789abcdef0</instanceId><instanceState><code>0</code><name>pending</name></instanceState>` +
+ `<placement><availabilityZone>eu-west-1a</availabilityZone></placement><launchTime>2026-11-08T12:00:00.000Z</launchTime><tagSet>` +
+ `<item><key>carlos:deployment</key><value>production</value></item><item><key>carlos:fleet</key><value>shop</value></item>` +
+ `<item><key>carlos:label</key><value>box-1</value></item><item><key>carlos:operation</key><value>0123456789abcdef0123456789abcdef</value></item>` +
+ `</tagSet></item>`
+
+// TestAWSComputeTransport is the serialization witness: the real SDK client,
+// loaded through rootaws, with every byte through a mock transport.
+func TestAWSComputeTransport(t *testing.T) {
+ none := filepath.Join(t.TempDir(), "none")
+ for k, v := range map[string]string{"AWS_EC2_METADATA_DISABLED": "true", "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": otherRegion, "AWS_DEFAULT_REGION": otherRegion} {
+ t.Setenv(k, v)
+ }
+ var mu sync.Mutex
+ counts := map[string]int{}
+ var runForm url.Values
+ respond := map[string]func() *http.Response{
+ "DescribeImages": func() *http.Response {
+ return xmlResponse(200, `<DescribeImagesResponse><requestId>req</requestId><imagesSet><item><imageId>`+testImage+`</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>`)
+ },
+ "RunInstances": func() *http.Response {
+ return xmlResponse(200, `<RunInstancesResponse><requestId>req</requestId><reservationId>r-1</reservationId><ownerId>`+testAccount+`</ownerId><instancesSet>`+xmlInstance+`</instancesSet></RunInstancesResponse>`)
+ },
+ "DescribeInstances": func() *http.Response {
+ return xmlResponse(200, `<DescribeInstancesResponse><requestId>req</requestId><reservationSet><item><reservationId>r-1</reservationId><ownerId>`+testAccount+`</ownerId><instancesSet>`+xmlInstance+`</instancesSet></item></reservationSet></DescribeInstancesResponse>`)
+ },
+ "TerminateInstances": func() *http.Response { return xmlError(503, "Unavailable") },
+ }
+ transport := transportFunc(func(r *http.Request) (*http.Response, error) {
+ if r.URL.Scheme != "https" || r.URL.Host != "ec2."+testRegion+".amazonaws.com" {
+ t.Errorf("request to %s", r.URL)
+ return nil, errors.New("blocked")
+ }
+ if !strings.HasPrefix(r.Header.Get("Authorization"), "AWS4-HMAC-SHA256 Credential=AKIDTEST/") {
+ t.Errorf("signed with %q", r.Header.Get("Authorization"))
+ }
+ body, _ := io.ReadAll(r.Body)
+ form, err := url.ParseQuery(string(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ action := form.Get("Action")
+ mu.Lock()
+ defer mu.Unlock()
+ counts[action]++
+ if action == "RunInstances" {
+ runForm = form
+ }
+ h, ok := respond[action]
+ if !ok {
+ t.Errorf("unexpected %s", action)
+ return xmlError(400, "UnexpectedAction"), nil
+ }
+ return h(), nil
+ })
+ c, err := NewComputeWith(context.Background(), ComputeConfig{Deployment: testDeployment, AccountID: testAccount, Regions: []string{testRegion}}, transport)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := c.Launch(context.Background(), testSpec())
+ if err != nil || got.CloudID != "i-0123456789abcdef0" || got.Identity != testIdentity() || got.State != compute.StatePending {
+ t.Fatalf("%+v %v", got, err)
+ }
+ want := map[string]string{
+ "ClientToken": testSpec().ClientToken, "ImageId": testImage, "InstanceType": "t4g.small", "MinCount": "1", "MaxCount": "1",
+ "UserData": base64.StdEncoding.EncodeToString([]byte(testSpec().UserData)),
+ "MetadataOptions.HttpTokens": "required", "MetadataOptions.HttpPutResponseHopLimit": "1", "MetadataOptions.HttpEndpoint": "enabled",
+ "BlockDeviceMapping.1.DeviceName": testRootDevice, "BlockDeviceMapping.1.Ebs.VolumeSize": "20", "BlockDeviceMapping.1.Ebs.VolumeType": "gp3",
+ "BlockDeviceMapping.1.Ebs.Encrypted": "true", "BlockDeviceMapping.1.Ebs.DeleteOnTermination": "true",
+ "NetworkInterface.1.DeviceIndex": "0", "NetworkInterface.1.SubnetId": testSubnet, "NetworkInterface.1.SecurityGroupId.1": testSG,
+ "NetworkInterface.1.SecurityGroupId.2": testSG2, "NetworkInterface.1.AssociatePublicIpAddress": "true", "NetworkInterface.1.DeleteOnTermination": "true",
+ "TagSpecification.1.ResourceType": "instance", "TagSpecification.2.ResourceType": "volume",
+ }
+ for i, k := range []string{"carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation"} {
+ for spec := 1; spec <= 2; spec++ {
+ want[fmt.Sprintf("TagSpecification.%d.Tag.%d.Key", spec, i+1)] = k
+ want[fmt.Sprintf("TagSpecification.%d.Tag.%d.Value", spec, i+1)] = identityTags(testIdentity())[k]
+ }
+ }
+ for k, v := range want {
+ if runForm.Get(k) != v {
+ t.Errorf("%s = %q, want %q", k, runForm.Get(k), v)
+ }
+ }
+ for k := range runForm {
+ if _, ok := want[k]; !ok && k != "Action" && k != "Version" {
+ t.Errorf("unexpected request field %s", k)
+ }
+ }
+ // A 4xx token conflict is a conflict, sent once, with no AWS text.
+ respond["RunInstances"] = func() *http.Response { return xmlError(400, "IdempotentParameterMismatch") }
+ counts["RunInstances"] = 0
+ _, err = c.Launch(context.Background(), testSpec())
+ if !errors.Is(err, compute.ErrLaunchConflict) || errors.Is(err, compute.ErrLaunchRejected) || counts["RunInstances"] != 1 {
+ t.Fatalf("%v after %d attempts", err, counts["RunInstances"])
+ }
+ noLeak(t, err.Error())
+ // A retryable 503 is sent exactly once and stays ambiguous.
+ respond["RunInstances"] = func() *http.Response { return xmlError(503, "Unavailable") }
+ counts["RunInstances"] = 0
+ _, err = c.Launch(context.Background(), testSpec())
+ ambiguous(t, err)
+ if counts["RunInstances"] != 1 {
+ t.Fatalf("RunInstances sent %d times", counts["RunInstances"])
+ }
+ err = c.Terminate(context.Background(), testRegion, "i-0123456789abcdef0", testIdentity())
+ ambiguous(t, err)
+ if counts["TerminateInstances"] != 1 {
+ t.Fatalf("TerminateInstances sent %d times", counts["TerminateInstances"])
+ }
+ respond["DescribeInstances"] = func() *http.Response { return xmlError(400, "InvalidInstanceID.NotFound") }
+ if _, err = c.Lookup(context.Background(), testRegion, "i-0123456789abcdef0"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("got %v", err)
+ }
+ noLeak(t, err.Error())
+}
diff --git a/internal/awsmanaged/diagnostics.go b/internal/awsmanaged/diagnostics.go
new file mode 100644
index 000000000..0df4e2e32
--- /dev/null
+++ b/internal/awsmanaged/diagnostics.go
@@ -0,0 +1,51 @@
+package awsmanaged
+
+import (
+ "encoding/base64"
+ "errors"
+ "strings"
+)
+
+const (
+ maxEncodedConsole = 128 << 10
+ maxDecodedConsole = 64 << 10
+ maxBreadcrumbs = 32
+ breadcrumbPrefix = "CARLOS_BOOT:"
+)
+
+// breadcrumbCodes are the only words console output can contribute. A box's
+// serial console also carries whatever its boot printed, tokens and shell
+// traces included, so nothing else from it is ever returned.
+var breadcrumbCodes = [...]string{"seed_verified", "enrol_pending", "enrol_failed", "stable_verified", "joining", "bootstrap_failed"}
+
+// sanitizeConsoleOutput decodes EC2's base64 console output and keeps the
+// last maxBreadcrumbs lines that are exactly CARLOS_BOOT:<code> for a known
+// code, as those fixed codes joined by newlines. Its errors name no content.
+func sanitizeConsoleOutput(encoded string) (string, error) {
+ if len(encoded) > maxEncodedConsole {
+ return "", errors.New("awsmanaged: console output is too long")
+ }
+ raw, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ return "", errors.New("awsmanaged: console output is not valid base64")
+ }
+ if len(raw) > maxDecodedConsole {
+ return "", errors.New("awsmanaged: console output is too long")
+ }
+ var codes []string
+ for _, line := range strings.Split(string(raw), "\n") {
+ got, ok := strings.CutPrefix(strings.TrimSuffix(line, "\r"), breadcrumbPrefix)
+ if !ok {
+ continue
+ }
+ for _, code := range breadcrumbCodes {
+ if got == code {
+ codes = append(codes, code)
+ }
+ }
+ }
+ if len(codes) > maxBreadcrumbs {
+ codes = codes[len(codes)-maxBreadcrumbs:]
+ }
+ return strings.Join(codes, "\n"), nil
+}
diff --git a/internal/awsmanaged/diagnostics_test.go b/internal/awsmanaged/diagnostics_test.go
new file mode 100644
index 000000000..e072066f4
--- /dev/null
+++ b/internal/awsmanaged/diagnostics_test.go
@@ -0,0 +1,161 @@
+package awsmanaged
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/carlosframework/platform/internal/compute"
+)
+
+func encode(lines ...string) string {
+ return base64.StdEncoding.EncodeToString([]byte(strings.Join(lines, "\n")))
+}
+
+func TestAWSComputeConsoleOutput(t *testing.T) {
+ private := []string{
+ "enrol token " + secretText + "-enrol",
+ "CARLOS_TUNNEL_TOKEN=" + secretText + "-tunnel",
+ "AWS_SECRET_ACCESS_KEY=" + secretText + "-access",
+ "-----BEGIN PRIVATE KEY-----" + secretText + "-private",
+ "+ curl -H 'Authorization: Bearer " + secretText + "-trace' https://example.com",
+ "CARLOS_BOOT:enrol_pending " + secretText,
+ "CARLOS_BOOT:" + secretText,
+ "CARLOS_BOOT:unknown_code",
+ " CARLOS_BOOT:joining",
+ "xCARLOS_BOOT:joining",
+ "CARLOS_BOOT:joining:" + secretText,
+ "carlos_boot:joining",
+ }
+ t.Run("recognized codes only", func(t *testing.T) {
+ in := append([]string{"[ 1.0] boot", "CARLOS_BOOT:seed_verified"}, private...)
+ in = append(in, "CARLOS_BOOT:enrol_pending\r", "CARLOS_BOOT:enrol_failed", "CARLOS_BOOT:stable_verified", "CARLOS_BOOT:joining", "CARLOS_BOOT:bootstrap_failed")
+ got, err := sanitizeConsoleOutput(encode(in...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := "seed_verified\nenrol_pending\nenrol_failed\nstable_verified\njoining\nbootstrap_failed"; got != want {
+ t.Fatalf("got %q", got)
+ }
+ noLeak(t, got)
+ })
+ t.Run("only private lines", func(t *testing.T) {
+ got, err := sanitizeConsoleOutput(encode(private...))
+ if err != nil || got != "" {
+ t.Fatalf("%q %v", got, err)
+ }
+ })
+ t.Run("empty", func(t *testing.T) {
+ if got, err := sanitizeConsoleOutput(""); err != nil || got != "" {
+ t.Fatalf("%q %v", got, err)
+ }
+ })
+ t.Run("at most 32 codes", func(t *testing.T) {
+ var in []string
+ for i := range 40 {
+ in = append(in, []string{"CARLOS_BOOT:seed_verified", "CARLOS_BOOT:joining"}[i%2])
+ }
+ in = append(in, "CARLOS_BOOT:bootstrap_failed")
+ got, err := sanitizeConsoleOutput(encode(in...))
+ codes := strings.Split(got, "\n")
+ if err != nil || len(codes) != maxBreadcrumbs || codes[len(codes)-1] != "bootstrap_failed" {
+ t.Fatalf("%d codes %q %v", len(codes), got, err)
+ }
+ })
+ for name, encoded := range map[string]string{
+ "malformed base64": "!!!" + secretText,
+ "encoded too long": strings.Repeat("A", maxEncodedConsole+4),
+ "decoded too long": base64.StdEncoding.EncodeToString([]byte(strings.Repeat(secretText+"\n", maxDecodedConsole/len(secretText)+1))),
+ } {
+ t.Run(name, func(t *testing.T) {
+ got, err := sanitizeConsoleOutput(encoded)
+ if err == nil || got != "" {
+ t.Fatalf("%q %v", got, err)
+ }
+ noLeak(t, err.Error())
+ })
+ }
+ t.Run("64 KiB decoded is accepted", func(t *testing.T) {
+ body := strings.Repeat("x", maxDecodedConsole-len("\nCARLOS_BOOT:joining")) + "\nCARLOS_BOOT:joining"
+ got, err := sanitizeConsoleOutput(base64.StdEncoding.EncodeToString([]byte(body)))
+ if err != nil || got != "joining" {
+ t.Fatalf("%q %v", got, err)
+ }
+ })
+
+ ctx := context.Background()
+ t.Run("adapter checks the instance first", func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ inst := f.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ f.consoleOutput = &ec2.GetConsoleOutputOutput{InstanceId: aws.String(inst.id), Output: aws.String(encode(append(private, "CARLOS_BOOT:joining")...))}
+ got, err := newTestCompute(t, f).ConsoleOutput(ctx, testRegion, inst.id)
+ if err != nil || got != "joining" {
+ t.Fatalf("%q %v", got, err)
+ }
+ if f.callCount("DescribeInstances") != 1 || f.callCount("GetConsoleOutput") != 1 || aws.ToString(f.consoleInputs[0].InstanceId) != inst.id {
+ t.Fatalf("calls %v", f.calls)
+ }
+ if in := f.describeInputs[0]; in.Filters != nil || len(in.InstanceIds) != 1 || in.InstanceIds[0] != inst.id {
+ t.Fatalf("describe %+v", in)
+ }
+ })
+ for name, tags := range map[string]map[string]string{
+ "other deployment": identityTags(compute.Identity{Deployment: "staging", Fleet: "shop", Label: "box-1", Operation: "x"}),
+ "no fleet": {"carlos:deployment": testDeployment, "carlos:label": "box-1", "carlos:operation": "x"},
+ "no label": {"carlos:deployment": testDeployment, "carlos:fleet": "shop", "carlos:operation": "x"},
+ "no operation": {"carlos:deployment": testDeployment, "carlos:fleet": "shop", "carlos:label": "box-1"},
+ "empty operation": {"carlos:deployment": testDeployment, "carlos:fleet": "shop", "carlos:label": "box-1", "carlos:operation": ""},
+ "untagged": {"Name": "other"},
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ inst := f.add(tags, types.InstanceStateNameRunning)
+ _, err := newTestCompute(t, f).ConsoleOutput(ctx, testRegion, inst.id)
+ if !errors.Is(err, compute.ErrIdentityMismatch) || f.callCount("GetConsoleOutput") != 0 {
+ t.Fatalf("%v calls %v", err, f.calls)
+ }
+ })
+ }
+ for name, set := range map[string]func(f *fakeEC2, id string){
+ "not found": func(f *fakeEC2, id string) { f.instances = nil },
+ "describe throttled": func(f *fakeEC2, id string) { f.describeErr = apiErr("RequestLimitExceeded") },
+ "output error": func(f *fakeEC2, id string) { f.consoleErr = apiErr("UnauthorizedOperation") },
+ "output for other id": func(f *fakeEC2, id string) {
+ f.consoleOutput = &ec2.GetConsoleOutputOutput{InstanceId: aws.String("i-0bbbbbbbbbbbbbbbb"), Output: aws.String(encode("CARLOS_BOOT:joining"))}
+ },
+ "malformed output": func(f *fakeEC2, id string) {
+ f.consoleOutput = &ec2.GetConsoleOutputOutput{InstanceId: aws.String(id), Output: aws.String("%%" + secretText)}
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ inst := f.add(identityTags(testIdentity()), types.InstanceStateNameRunning)
+ set(f, inst.id)
+ got, err := newTestCompute(t, f).ConsoleOutput(ctx, testRegion, inst.id)
+ if err == nil || got != "" || errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("%q %v", got, err)
+ }
+ noLeak(t, err.Error())
+ })
+ }
+ for name, call := range map[string]func(c *Compute) error{
+ "unconfigured region": func(c *Compute) error { _, err := c.ConsoleOutput(ctx, "us-east-1", "i-0aaaaaaaaaaaaaaaa"); return err },
+ "invalid id": func(c *Compute) error { _, err := c.ConsoleOutput(ctx, testRegion, "i-"+secretText); return err },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newFakeEC2(t, testRegion)
+ err := call(newTestCompute(t, f))
+ if err == nil || f.totalCalls() != 0 {
+ t.Fatal(fmt.Sprint(err, f.calls))
+ }
+ noLeak(t, err.Error())
+ })
+ }
+}
diff --git a/internal/awsmanaged/export_test.go b/internal/awsmanaged/export_test.go
new file mode 100644
index 000000000..250c8ff66
--- /dev/null
+++ b/internal/awsmanaged/export_test.go
@@ -0,0 +1,26 @@
+package awsmanaged
+
+import (
+ "context"
+ "net/http"
+
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+)
+
+// HTTPClient is the transport a test puts under the real SDK clients.
+type HTTPClient interface {
+ Do(*http.Request) (*http.Response, error)
+}
+
+// NewComputeWith is NewCompute with every request sent through transport,
+// static dummy credentials and no shared files, so no test can reach AWS
+// or the metadata service. Tests also set AWS_EC2_METADATA_DISABLED.
+func NewComputeWith(ctx context.Context, cfg ComputeConfig, transport HTTPClient) (*Compute, error) {
+ return loadCompute(ctx, cfg,
+ awsconfig.WithHTTPClient(transport),
+ awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("AKIDTEST", "test-secret", "")),
+ awsconfig.WithSharedConfigFiles([]string{}), awsconfig.WithSharedCredentialsFiles([]string{}),
+ awsconfig.WithSharedConfigProfile(""),
+ )
+}