| 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()) |
| +} |