carlos / platform Public

feat: provision managed fleet buckets and bounded credentials

Plan 2b-1 Task 4: the AWS fleetstore adapter in internal/awsmanaged,
unwired. Each fleet gets a bucket and an IAM user named from
SHA-256(deployment/fleet). The bucket is created with its identity tags
in the CreateBucket request (us-east-1 included), then proven to be
this account's, in the requested region, with exactly those tags before
any setting is written: versioning, AES256, all four public-access
blocks, and one lifecycle rule (noncurrent 7 days, multipart abort 7
days, no current expiry). Each setting is read back. A foreign,
untagged or mis-tagged bucket, or foreign lifecycle rules, are refused
and never adopted or replaced.

The user is created under the configured path and permissions
boundary. An existing user must match name, account, path and boundary
exactly, with no managed policy, no group and no other inline policy.
The carlos-fleet-data policy (testdata/fleet-data-policy.json) is
installed only on an otherwise valid user, and a different document is
refused. It grants this one bucket only and ends with an s3:* Deny
outside it.

Rotation reads the complete key inventory under a per-fleet lock and
refuses with ErrDeliveredKeyStillLive before any change while a
delivered key other than keep exists. It confirms deletions with a
second listing and sends CreateAccessKey once.

The fleet bucket prefix is capped at 24 characters so the policy fits
IAM's 2048-character inline limit. Tests use fake SDK clients and a mock
transport only. IMDS is off in process.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev aedea9cfbc5ee7642dc4df504a63fd32d7086539 parent 6f78e60
9 files changed, +3,118 −10
  • internal/awsmanaged/clients.go +197 −8
  • internal/awsmanaged/credentials.go +329 −0
  • internal/awsmanaged/credentials_test.go +713 −0
  • internal/awsmanaged/export_test.go +12 −2
  • internal/awsmanaged/policy.go +166 −0
  • internal/awsmanaged/policy_test.go +497 −0
  • internal/awsmanaged/storage.go +450 −0
  • internal/awsmanaged/storage_test.go +672 −0
  • internal/awsmanaged/testdata/fleet-data-policy.json +82 −0
diff --git a/internal/awsmanaged/clients.go b/internal/awsmanaged/clients.go
index f70f3c042..130f83e1e 100644
--- a/internal/awsmanaged/clients.go
+++ b/internal/awsmanaged/clients.go
@@ -1,6 +1,7 @@
// 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
+// managed-fleet contracts (internal/compute and internal/fleetstore). It is
+// the only managed fleet code that imports the AWS SDK, and it loads
+// credentials only through
// internal/rootaws. Nothing in production constructs it yet: 2b-2 wires it
// once the frozen cloud-init replaces today's JSON launch payload.
package awsmanaged
@@ -9,8 +10,11 @@ import (
"context"
"fmt"
+ "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/iam"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/carlosframework/platform/internal/rootaws"
)
@@ -55,18 +59,203 @@ func (m ec2Methods) GetConsoleOutput(ctx context.Context, in *ec2.GetConsoleOutp
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) {
+// loadRegional loads one region's config 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 loadRegional(ctx context.Context, region string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, 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)
+ return aws.Config{}, 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)
+ return aws.Config{}, fmt.Errorf("awsmanaged: AWS config for %s resolved another region", region)
+ }
+ return cfg, nil
+}
+
+// loadEC2 builds one region's EC2 client.
+func loadEC2(ctx context.Context, region string, opts ...func(*awsconfig.LoadOptions) error) (ec2API, error) {
+ cfg, err := loadRegional(ctx, region, opts...)
+ if err != nil {
+ return nil, err
}
c := ec2.NewFromConfig(cfg)
return ec2Methods{run: c.RunInstances, describe: c.DescribeInstances, images: c.DescribeImages, terminate: c.TerminateInstances, console: c.GetConsoleOutput}, nil
}
+
+// s3API is every S3 call the fleet storage adapter makes. Only bucket
+// preparation uses it; credentials and enrolment never touch S3. There is
+// no delete, no bucket policy and no object call.
+type s3API interface {
+ CreateBucket(context.Context, *awss3.CreateBucketInput, ...func(*awss3.Options)) (*awss3.CreateBucketOutput, error)
+ GetBucketLocation(context.Context, *awss3.GetBucketLocationInput, ...func(*awss3.Options)) (*awss3.GetBucketLocationOutput, error)
+ GetBucketTagging(context.Context, *awss3.GetBucketTaggingInput, ...func(*awss3.Options)) (*awss3.GetBucketTaggingOutput, error)
+ GetBucketVersioning(context.Context, *awss3.GetBucketVersioningInput, ...func(*awss3.Options)) (*awss3.GetBucketVersioningOutput, error)
+ PutBucketVersioning(context.Context, *awss3.PutBucketVersioningInput, ...func(*awss3.Options)) (*awss3.PutBucketVersioningOutput, error)
+ GetBucketEncryption(context.Context, *awss3.GetBucketEncryptionInput, ...func(*awss3.Options)) (*awss3.GetBucketEncryptionOutput, error)
+ PutBucketEncryption(context.Context, *awss3.PutBucketEncryptionInput, ...func(*awss3.Options)) (*awss3.PutBucketEncryptionOutput, error)
+ GetPublicAccessBlock(context.Context, *awss3.GetPublicAccessBlockInput, ...func(*awss3.Options)) (*awss3.GetPublicAccessBlockOutput, error)
+ PutPublicAccessBlock(context.Context, *awss3.PutPublicAccessBlockInput, ...func(*awss3.Options)) (*awss3.PutPublicAccessBlockOutput, error)
+ GetBucketLifecycleConfiguration(context.Context, *awss3.GetBucketLifecycleConfigurationInput, ...func(*awss3.Options)) (*awss3.GetBucketLifecycleConfigurationOutput, error)
+ PutBucketLifecycleConfiguration(context.Context, *awss3.PutBucketLifecycleConfigurationInput, ...func(*awss3.Options)) (*awss3.PutBucketLifecycleConfigurationOutput, error)
+}
+
+// iamAPI is every IAM call the fleet storage adapter makes. Nothing here
+// changes or removes a permissions boundary, attaches a managed policy,
+// deletes a user or reads back a secret: CreateAccessKey is the only call
+// whose answer carries one.
+type iamAPI interface {
+ CreateUser(context.Context, *iam.CreateUserInput, ...func(*iam.Options)) (*iam.CreateUserOutput, error)
+ GetUser(context.Context, *iam.GetUserInput, ...func(*iam.Options)) (*iam.GetUserOutput, error)
+ PutUserPolicy(context.Context, *iam.PutUserPolicyInput, ...func(*iam.Options)) (*iam.PutUserPolicyOutput, error)
+ GetUserPolicy(context.Context, *iam.GetUserPolicyInput, ...func(*iam.Options)) (*iam.GetUserPolicyOutput, error)
+ ListUserPolicies(context.Context, *iam.ListUserPoliciesInput, ...func(*iam.Options)) (*iam.ListUserPoliciesOutput, error)
+ ListAttachedUserPolicies(context.Context, *iam.ListAttachedUserPoliciesInput, ...func(*iam.Options)) (*iam.ListAttachedUserPoliciesOutput, error)
+ ListGroupsForUser(context.Context, *iam.ListGroupsForUserInput, ...func(*iam.Options)) (*iam.ListGroupsForUserOutput, error)
+ ListAccessKeys(context.Context, *iam.ListAccessKeysInput, ...func(*iam.Options)) (*iam.ListAccessKeysOutput, error)
+ DeleteAccessKey(context.Context, *iam.DeleteAccessKeyInput, ...func(*iam.Options)) (*iam.DeleteAccessKeyOutput, error)
+ CreateAccessKey(context.Context, *iam.CreateAccessKeyInput, ...func(*iam.Options)) (*iam.CreateAccessKeyOutput, error)
+}
+
+// s3Methods and iamMethods hold method values, as ec2Methods does.
+type s3Methods struct {
+ create func(context.Context, *awss3.CreateBucketInput, ...func(*awss3.Options)) (*awss3.CreateBucketOutput, error)
+ location func(context.Context, *awss3.GetBucketLocationInput, ...func(*awss3.Options)) (*awss3.GetBucketLocationOutput, error)
+ tagging func(context.Context, *awss3.GetBucketTaggingInput, ...func(*awss3.Options)) (*awss3.GetBucketTaggingOutput, error)
+ versioning func(context.Context, *awss3.GetBucketVersioningInput, ...func(*awss3.Options)) (*awss3.GetBucketVersioningOutput, error)
+ putVersioning func(context.Context, *awss3.PutBucketVersioningInput, ...func(*awss3.Options)) (*awss3.PutBucketVersioningOutput, error)
+ encryption func(context.Context, *awss3.GetBucketEncryptionInput, ...func(*awss3.Options)) (*awss3.GetBucketEncryptionOutput, error)
+ putEncryption func(context.Context, *awss3.PutBucketEncryptionInput, ...func(*awss3.Options)) (*awss3.PutBucketEncryptionOutput, error)
+ publicBlock func(context.Context, *awss3.GetPublicAccessBlockInput, ...func(*awss3.Options)) (*awss3.GetPublicAccessBlockOutput, error)
+ putPublicBlock func(context.Context, *awss3.PutPublicAccessBlockInput, ...func(*awss3.Options)) (*awss3.PutPublicAccessBlockOutput, error)
+ lifecycle func(context.Context, *awss3.GetBucketLifecycleConfigurationInput, ...func(*awss3.Options)) (*awss3.GetBucketLifecycleConfigurationOutput, error)
+ putLifecycle func(context.Context, *awss3.PutBucketLifecycleConfigurationInput, ...func(*awss3.Options)) (*awss3.PutBucketLifecycleConfigurationOutput, error)
+}
+
+func (m s3Methods) CreateBucket(ctx context.Context, in *awss3.CreateBucketInput, opts ...func(*awss3.Options)) (*awss3.CreateBucketOutput, error) {
+ return m.create(ctx, in, opts...)
+}
+
+func (m s3Methods) GetBucketLocation(ctx context.Context, in *awss3.GetBucketLocationInput, opts ...func(*awss3.Options)) (*awss3.GetBucketLocationOutput, error) {
+ return m.location(ctx, in, opts...)
+}
+
+func (m s3Methods) GetBucketTagging(ctx context.Context, in *awss3.GetBucketTaggingInput, opts ...func(*awss3.Options)) (*awss3.GetBucketTaggingOutput, error) {
+ return m.tagging(ctx, in, opts...)
+}
+
+func (m s3Methods) GetBucketVersioning(ctx context.Context, in *awss3.GetBucketVersioningInput, opts ...func(*awss3.Options)) (*awss3.GetBucketVersioningOutput, error) {
+ return m.versioning(ctx, in, opts...)
+}
+
+func (m s3Methods) PutBucketVersioning(ctx context.Context, in *awss3.PutBucketVersioningInput, opts ...func(*awss3.Options)) (*awss3.PutBucketVersioningOutput, error) {
+ return m.putVersioning(ctx, in, opts...)
+}
+
+func (m s3Methods) GetBucketEncryption(ctx context.Context, in *awss3.GetBucketEncryptionInput, opts ...func(*awss3.Options)) (*awss3.GetBucketEncryptionOutput, error) {
+ return m.encryption(ctx, in, opts...)
+}
+
+func (m s3Methods) PutBucketEncryption(ctx context.Context, in *awss3.PutBucketEncryptionInput, opts ...func(*awss3.Options)) (*awss3.PutBucketEncryptionOutput, error) {
+ return m.putEncryption(ctx, in, opts...)
+}
+
+func (m s3Methods) GetPublicAccessBlock(ctx context.Context, in *awss3.GetPublicAccessBlockInput, opts ...func(*awss3.Options)) (*awss3.GetPublicAccessBlockOutput, error) {
+ return m.publicBlock(ctx, in, opts...)
+}
+
+func (m s3Methods) PutPublicAccessBlock(ctx context.Context, in *awss3.PutPublicAccessBlockInput, opts ...func(*awss3.Options)) (*awss3.PutPublicAccessBlockOutput, error) {
+ return m.putPublicBlock(ctx, in, opts...)
+}
+
+func (m s3Methods) GetBucketLifecycleConfiguration(ctx context.Context, in *awss3.GetBucketLifecycleConfigurationInput, opts ...func(*awss3.Options)) (*awss3.GetBucketLifecycleConfigurationOutput, error) {
+ return m.lifecycle(ctx, in, opts...)
+}
+
+func (m s3Methods) PutBucketLifecycleConfiguration(ctx context.Context, in *awss3.PutBucketLifecycleConfigurationInput, opts ...func(*awss3.Options)) (*awss3.PutBucketLifecycleConfigurationOutput, error) {
+ return m.putLifecycle(ctx, in, opts...)
+}
+
+type iamMethods struct {
+ createUser func(context.Context, *iam.CreateUserInput, ...func(*iam.Options)) (*iam.CreateUserOutput, error)
+ getUser func(context.Context, *iam.GetUserInput, ...func(*iam.Options)) (*iam.GetUserOutput, error)
+ putPolicy func(context.Context, *iam.PutUserPolicyInput, ...func(*iam.Options)) (*iam.PutUserPolicyOutput, error)
+ getPolicy func(context.Context, *iam.GetUserPolicyInput, ...func(*iam.Options)) (*iam.GetUserPolicyOutput, error)
+ listPolicies func(context.Context, *iam.ListUserPoliciesInput, ...func(*iam.Options)) (*iam.ListUserPoliciesOutput, error)
+ listAttached func(context.Context, *iam.ListAttachedUserPoliciesInput, ...func(*iam.Options)) (*iam.ListAttachedUserPoliciesOutput, error)
+ listGroups func(context.Context, *iam.ListGroupsForUserInput, ...func(*iam.Options)) (*iam.ListGroupsForUserOutput, error)
+ listKeys func(context.Context, *iam.ListAccessKeysInput, ...func(*iam.Options)) (*iam.ListAccessKeysOutput, error)
+ deleteKey func(context.Context, *iam.DeleteAccessKeyInput, ...func(*iam.Options)) (*iam.DeleteAccessKeyOutput, error)
+ createKey func(context.Context, *iam.CreateAccessKeyInput, ...func(*iam.Options)) (*iam.CreateAccessKeyOutput, error)
+}
+
+func (m iamMethods) CreateUser(ctx context.Context, in *iam.CreateUserInput, opts ...func(*iam.Options)) (*iam.CreateUserOutput, error) {
+ return m.createUser(ctx, in, opts...)
+}
+
+func (m iamMethods) GetUser(ctx context.Context, in *iam.GetUserInput, opts ...func(*iam.Options)) (*iam.GetUserOutput, error) {
+ return m.getUser(ctx, in, opts...)
+}
+
+func (m iamMethods) PutUserPolicy(ctx context.Context, in *iam.PutUserPolicyInput, opts ...func(*iam.Options)) (*iam.PutUserPolicyOutput, error) {
+ return m.putPolicy(ctx, in, opts...)
+}
+
+func (m iamMethods) GetUserPolicy(ctx context.Context, in *iam.GetUserPolicyInput, opts ...func(*iam.Options)) (*iam.GetUserPolicyOutput, error) {
+ return m.getPolicy(ctx, in, opts...)
+}
+
+func (m iamMethods) ListUserPolicies(ctx context.Context, in *iam.ListUserPoliciesInput, opts ...func(*iam.Options)) (*iam.ListUserPoliciesOutput, error) {
+ return m.listPolicies(ctx, in, opts...)
+}
+
+func (m iamMethods) ListAttachedUserPolicies(ctx context.Context, in *iam.ListAttachedUserPoliciesInput, opts ...func(*iam.Options)) (*iam.ListAttachedUserPoliciesOutput, error) {
+ return m.listAttached(ctx, in, opts...)
+}
+
+func (m iamMethods) ListGroupsForUser(ctx context.Context, in *iam.ListGroupsForUserInput, opts ...func(*iam.Options)) (*iam.ListGroupsForUserOutput, error) {
+ return m.listGroups(ctx, in, opts...)
+}
+
+func (m iamMethods) ListAccessKeys(ctx context.Context, in *iam.ListAccessKeysInput, opts ...func(*iam.Options)) (*iam.ListAccessKeysOutput, error) {
+ return m.listKeys(ctx, in, opts...)
+}
+
+func (m iamMethods) DeleteAccessKey(ctx context.Context, in *iam.DeleteAccessKeyInput, opts ...func(*iam.Options)) (*iam.DeleteAccessKeyOutput, error) {
+ return m.deleteKey(ctx, in, opts...)
+}
+
+func (m iamMethods) CreateAccessKey(ctx context.Context, in *iam.CreateAccessKeyInput, opts ...func(*iam.Options)) (*iam.CreateAccessKeyOutput, error) {
+ return m.createKey(ctx, in, opts...)
+}
+
+// loadS3 builds one region's S3 client.
+func loadS3(ctx context.Context, region string, opts ...func(*awsconfig.LoadOptions) error) (s3API, error) {
+ cfg, err := loadRegional(ctx, region, opts...)
+ if err != nil {
+ return nil, err
+ }
+ c := awss3.NewFromConfig(cfg)
+ return s3Methods{
+ create: c.CreateBucket, location: c.GetBucketLocation, tagging: c.GetBucketTagging,
+ versioning: c.GetBucketVersioning, putVersioning: c.PutBucketVersioning,
+ encryption: c.GetBucketEncryption, putEncryption: c.PutBucketEncryption,
+ publicBlock: c.GetPublicAccessBlock, putPublicBlock: c.PutPublicAccessBlock,
+ lifecycle: c.GetBucketLifecycleConfiguration, putLifecycle: c.PutBucketLifecycleConfiguration,
+ }, nil
+}
+
+// loadIAM builds the IAM client. IAM is global; region only signs.
+func loadIAM(ctx context.Context, region string, opts ...func(*awsconfig.LoadOptions) error) (iamAPI, error) {
+ cfg, err := loadRegional(ctx, region, opts...)
+ if err != nil {
+ return nil, err
+ }
+ c := iam.NewFromConfig(cfg)
+ return iamMethods{
+ createUser: c.CreateUser, getUser: c.GetUser, putPolicy: c.PutUserPolicy, getPolicy: c.GetUserPolicy,
+ listPolicies: c.ListUserPolicies, listAttached: c.ListAttachedUserPolicies, listGroups: c.ListGroupsForUser,
+ listKeys: c.ListAccessKeys, deleteKey: c.DeleteAccessKey, createKey: c.CreateAccessKey,
+ }, nil
+}
diff --git a/internal/awsmanaged/credentials.go b/internal/awsmanaged/credentials.go
new file mode 100644
index 000000000..76742985d
--- /dev/null
+++ b/internal/awsmanaged/credentials.go
@@ -0,0 +1,329 @@
+package awsmanaged
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "regexp"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/iam"
+ iamtypes "github.com/aws/aws-sdk-go-v2/service/iam/types"
+ "github.com/carlosframework/platform/internal/fleetstore"
+)
+
+var accessKeyRE = regexp.MustCompile(`^[A-Z0-9]{16,128}$`)
+
+// listAll reads every page of one IAM listing or fails as a whole: a
+// partial inventory could hide the key or the policy that matters.
+func listAll[T any](ctx context.Context, what string, page func(marker *string) ([]T, bool, *string, error)) ([]T, error) {
+ var out []T
+ var marker *string
+ seen := map[string]bool{}
+ for pages := 0; ; pages++ {
+ if pages == maxListPages {
+ return nil, uncertain(ctx, what+": too many pages")
+ }
+ items, truncated, next, err := page(marker)
+ if err != nil {
+ return nil, uncertain(ctx, what)
+ }
+ out = append(out, items...)
+ if !truncated {
+ return out, nil
+ }
+ m := aws.ToString(next)
+ if m == "" || seen[m] {
+ return nil, uncertain(ctx, what+": bad page marker")
+ }
+ seen[m] = true
+ marker = aws.String(m)
+ }
+}
+
+func (s *Storage) userARN(user string) string {
+ return "arn:aws:iam::" + s.cfg.AccountID + ":user" + s.cfg.UserPath + user
+}
+
+// ensureFleetUser creates the fleet user under the exact path and boundary,
+// or proves an existing one is exactly that user with no other authority,
+// then installs the fleet-data policy if it is missing and reads it back.
+// It never changes a boundary and never replaces a different policy.
+func (s *Storage) ensureFleetUser(ctx context.Context, fleet string) error {
+ bucket, user, err := fleetResourceNames(s.cfg, fleet)
+ if err != nil {
+ return err
+ }
+ want, err := fleetDataPolicy("arn:aws:s3:::" + bucket)
+ if err != nil {
+ return err
+ }
+ _, err = s.users.CreateUser(ctx, &iam.CreateUserInput{
+ UserName: aws.String(user), Path: aws.String(s.cfg.UserPath), PermissionsBoundary: aws.String(s.cfg.BoundaryARN),
+ })
+ if err != nil && apiCode(err) != "EntityAlreadyExists" {
+ return uncertain(ctx, "create fleet user")
+ }
+ has, err := s.inspectUser(ctx, user, want)
+ if err != nil {
+ return err
+ }
+ if !has {
+ if _, err := s.users.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
+ UserName: aws.String(user), PolicyName: aws.String(fleetPolicyName), PolicyDocument: aws.String(want),
+ }); err != nil {
+ return uncertain(ctx, "put fleet data policy")
+ }
+ }
+ _, err = s.verifyFleetUser(ctx, fleet)
+ return err
+}
+
+// verifyFleetUser proves the fleet's IAM user is exactly the one this
+// adapter makes: name, account, path and boundary, no managed policy, no
+// group, and only the fleet-data inline policy with exactly the wanted
+// document. It returns the user name, never a key.
+func (s *Storage) verifyFleetUser(ctx context.Context, fleet string) (string, error) {
+ bucket, user, err := fleetResourceNames(s.cfg, fleet)
+ if err != nil {
+ return "", err
+ }
+ want, err := fleetDataPolicy("arn:aws:s3:::" + bucket)
+ if err != nil {
+ return "", err
+ }
+ has, err := s.inspectUser(ctx, user, want)
+ if err != nil {
+ return "", err
+ }
+ if !has {
+ return "", uncertain(ctx, "fleet data policy is not in place")
+ }
+ return user, nil
+}
+
+// inspectUser checks everything verifyFleetUser does except that the
+// fleet-data policy may be absent; it reports whether it is present.
+func (s *Storage) inspectUser(ctx context.Context, user, want string) (bool, error) {
+ got, err := s.users.GetUser(ctx, &iam.GetUserInput{UserName: aws.String(user)})
+ if err != nil || got == nil || got.User == nil {
+ return false, uncertain(ctx, "get fleet user")
+ }
+ u := got.User
+ b := u.PermissionsBoundary
+ if aws.ToString(u.UserName) != user || aws.ToString(u.Path) != s.cfg.UserPath || aws.ToString(u.Arn) != s.userARN(user) ||
+ b == nil || aws.ToString(b.PermissionsBoundaryArn) != s.cfg.BoundaryARN || b.PermissionsBoundaryType != iamtypes.PermissionsBoundaryAttachmentTypePolicy {
+ return false, drift("fleet user identity or boundary")
+ }
+ attached, err := listAll(ctx, "list attached policies", func(m *string) ([]iamtypes.AttachedPolicy, bool, *string, error) {
+ out, err := s.users.ListAttachedUserPolicies(ctx, &iam.ListAttachedUserPoliciesInput{UserName: aws.String(user), Marker: m})
+ if err != nil || out == nil {
+ return nil, false, nil, errAmbiguous
+ }
+ return out.AttachedPolicies, out.IsTruncated, out.Marker, nil
+ })
+ if err != nil {
+ return false, err
+ }
+ if len(attached) != 0 {
+ return false, drift("fleet user has a managed policy")
+ }
+ groups, err := listAll(ctx, "list groups", func(m *string) ([]iamtypes.Group, bool, *string, error) {
+ out, err := s.users.ListGroupsForUser(ctx, &iam.ListGroupsForUserInput{UserName: aws.String(user), Marker: m})
+ if err != nil || out == nil {
+ return nil, false, nil, errAmbiguous
+ }
+ return out.Groups, out.IsTruncated, out.Marker, nil
+ })
+ if err != nil {
+ return false, err
+ }
+ if len(groups) != 0 {
+ return false, drift("fleet user is in a group")
+ }
+ names, err := listAll(ctx, "list inline policies", func(m *string) ([]string, bool, *string, error) {
+ out, err := s.users.ListUserPolicies(ctx, &iam.ListUserPoliciesInput{UserName: aws.String(user), Marker: m})
+ if err != nil || out == nil {
+ return nil, false, nil, errAmbiguous
+ }
+ return out.PolicyNames, out.IsTruncated, out.Marker, nil
+ })
+ if err != nil {
+ return false, err
+ }
+ has := false
+ for _, name := range names {
+ if name != fleetPolicyName || has {
+ return false, drift("fleet user has another inline policy")
+ }
+ has = true
+ }
+ if !has {
+ return false, nil
+ }
+ doc, err := s.users.GetUserPolicy(ctx, &iam.GetUserPolicyInput{UserName: aws.String(user), PolicyName: aws.String(fleetPolicyName)})
+ if err != nil || doc == nil {
+ return false, uncertain(ctx, "get fleet data policy")
+ }
+ // IAM answers the document URL-encoded (RFC 3986).
+ text, err := url.PathUnescape(aws.ToString(doc.PolicyDocument))
+ if err != nil {
+ return false, uncertain(ctx, "fleet data policy encoding")
+ }
+ if !samePolicy(text, want) {
+ return false, drift("fleet data policy differs")
+ }
+ return true, nil
+}
+
+type accessKey struct {
+ id string
+ active bool
+ created time.Time
+}
+
+// listKeys is the user's complete key inventory, or an error.
+func (s *Storage) listKeys(ctx context.Context, user string) ([]accessKey, error) {
+ meta, err := listAll(ctx, "list access keys", func(m *string) ([]iamtypes.AccessKeyMetadata, bool, *string, error) {
+ out, err := s.users.ListAccessKeys(ctx, &iam.ListAccessKeysInput{UserName: aws.String(user), Marker: m})
+ if err != nil || out == nil {
+ return nil, false, nil, errAmbiguous
+ }
+ return out.AccessKeyMetadata, out.IsTruncated, out.Marker, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ keys := make([]accessKey, 0, len(meta))
+ seen := map[string]bool{}
+ for _, k := range meta {
+ id := aws.ToString(k.AccessKeyId)
+ if !accessKeyRE.MatchString(id) || seen[id] || aws.ToString(k.UserName) != user {
+ return nil, uncertain(ctx, "access key listing answer")
+ }
+ seen[id] = true
+ switch k.Status {
+ case iamtypes.StatusTypeActive, iamtypes.StatusTypeInactive, iamtypes.StatusTypeExpired:
+ default:
+ return nil, uncertain(ctx, "access key listing answer")
+ }
+ keys = append(keys, accessKey{id: id, active: k.Status == iamtypes.StatusTypeActive, created: aws.ToTime(k.CreateDate)})
+ }
+ return keys, nil
+}
+
+// FleetCredentials names the newest active key (by creation time, then ID)
+// with no secret. It is advisory: rotation never takes keep from it, and
+// nothing here can recover a secret already handed out.
+func (s *Storage) FleetCredentials(ctx context.Context, fleet string) (fleetstore.Credentials, error) {
+ if _, _, err := fleetResourceNames(s.cfg, fleet); err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ unlock, err := s.lockFleet(ctx, fleet)
+ if err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ defer unlock()
+ user, err := s.verifyFleetUser(ctx, fleet)
+ if err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ keys, err := s.listKeys(ctx, user)
+ if err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ var best *accessKey
+ for i := range keys {
+ k := &keys[i]
+ if k.active && (best == nil || k.created.After(best.created) || k.created.Equal(best.created) && k.id > best.id) {
+ best = k
+ }
+ }
+ if best == nil {
+ return fleetstore.Credentials{}, nil
+ }
+ return fleetstore.Credentials{ID: best.id}, nil
+}
+
+// RotateFleetCredentials keeps keep, reaps every other key and mints one.
+// Under the fleet lock it verifies the user and reads the complete key
+// inventory first. If any delivered key other than keep still exists, in
+// any state, it returns fleetstore.ErrDeliveredKeyStillLive and changes
+// nothing. A nonempty keep must exist and be active. Deletions are
+// confirmed by a second complete listing before the one CreateAccessKey,
+// which is sent exactly once: a lost answer leaves an undelivered key the
+// next rotation reaps. The secret is returned only from that mint.
+func (s *Storage) RotateFleetCredentials(ctx context.Context, fleet, keep string, delivered []string) (fleetstore.Credentials, error) {
+ if _, _, err := fleetResourceNames(s.cfg, fleet); err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ if keep != "" && !accessKeyRE.MatchString(keep) {
+ return fleetstore.Credentials{}, fmt.Errorf("awsmanaged: key to keep is not an access key ID")
+ }
+ protected := map[string]bool{}
+ for _, id := range delivered {
+ if !accessKeyRE.MatchString(id) {
+ return fleetstore.Credentials{}, fmt.Errorf("awsmanaged: delivered key is not an access key ID")
+ }
+ if id != keep {
+ protected[id] = true
+ }
+ }
+ unlock, err := s.lockFleet(ctx, fleet)
+ if err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ defer unlock()
+ user, err := s.verifyFleetUser(ctx, fleet)
+ if err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ keys, err := s.listKeys(ctx, user)
+ if err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ keptActive := false
+ for _, k := range keys {
+ if protected[k.id] {
+ return fleetstore.Credentials{}, fmt.Errorf("awsmanaged: %w", fleetstore.ErrDeliveredKeyStillLive)
+ }
+ if k.id == keep {
+ keptActive = k.active
+ if !k.active {
+ return fleetstore.Credentials{}, drift("key to keep is not active")
+ }
+ }
+ }
+ if keep != "" && !keptActive {
+ return fleetstore.Credentials{}, drift("key to keep does not exist")
+ }
+ for _, k := range keys {
+ if k.id == keep {
+ continue
+ }
+ if _, err := s.users.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{UserName: aws.String(user), AccessKeyId: aws.String(k.id)}); err != nil && apiCode(err) != "NoSuchEntity" {
+ return fleetstore.Credentials{}, uncertain(ctx, "delete undelivered key")
+ }
+ }
+ left, err := s.listKeys(ctx, user)
+ if err != nil {
+ return fleetstore.Credentials{}, err
+ }
+ if len(left) > 1 || len(left) == 1 && (left[0].id != keep || !left[0].active) || len(left) == 0 && keep != "" {
+ return fleetstore.Credentials{}, uncertain(ctx, "keys left after reaping")
+ }
+ out, err := s.users.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{UserName: aws.String(user)}, func(o *iam.Options) { o.RetryMaxAttempts = 1 })
+ if err != nil {
+ return fleetstore.Credentials{}, uncertain(ctx, "create access key")
+ }
+ if out == nil || out.AccessKey == nil {
+ return fleetstore.Credentials{}, uncertain(ctx, "create access key answer")
+ }
+ k := out.AccessKey
+ id, secret := aws.ToString(k.AccessKeyId), aws.ToString(k.SecretAccessKey)
+ if !accessKeyRE.MatchString(id) || id == keep || secret == "" || aws.ToString(k.UserName) != user || k.Status != iamtypes.StatusTypeActive {
+ return fleetstore.Credentials{}, uncertain(ctx, "create access key answer")
+ }
+ return fleetstore.Credentials{ID: id, Secret: []byte(secret)}, nil
+}
diff --git a/internal/awsmanaged/credentials_test.go b/internal/awsmanaged/credentials_test.go
new file mode 100644
index 000000000..fba8127f4
--- /dev/null
+++ b/internal/awsmanaged/credentials_test.go
@@ -0,0 +1,713 @@
+package awsmanaged
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/url"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/iam"
+ iamtypes "github.com/aws/aws-sdk-go-v2/service/iam/types"
+ "github.com/carlosframework/platform/internal/fleetstore"
+)
+
+type fakeKey struct {
+ id, secret string
+ status iamtypes.StatusType
+ created time.Time
+}
+
+type fakeUser struct {
+ name, path, arn string
+ boundary *iamtypes.AttachedPermissionsBoundary
+ inline map[string]string
+ attached []string
+ groups []string
+ keys []*fakeKey
+}
+
+// fakeIAM pages every listing one item at a time, so any item can sit on a
+// later page. before fails a call with no effect; after applies it and
+// loses the answer. hold, when set, is called outside the lock at the
+// start of every call.
+type fakeIAM struct {
+ t *testing.T
+ mu sync.Mutex
+ users map[string]*fakeUser
+ counts map[string]int
+ before, after func(op string, n int) error
+ hold func(op, user string)
+ dropPolicyPut bool
+ dropDeletes bool
+ nextKey int
+ clock time.Time
+ keyAttempts []int
+}
+
+func newFakeIAM(t *testing.T) *fakeIAM {
+ return &fakeIAM{t: t, users: map[string]*fakeUser{}, counts: map[string]int{}, clock: fixedLaunch}
+}
+
+func (f *fakeIAM) count(op string) int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.counts[op]
+}
+
+func (f *fakeIAM) total() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ n := 0
+ for _, c := range f.counts {
+ n += c
+ }
+ return n
+}
+
+func (f *fakeIAM) keyMutations() int { return f.count("DeleteAccessKey") + f.count("CreateAccessKey") }
+
+func (f *fakeIAM) liveKeys(user string) []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []string
+ if u := f.users[user]; u != nil {
+ for _, k := range u.keys {
+ out = append(out, k.id)
+ }
+ }
+ return out
+}
+
+// addKey seeds a key as an operator or an earlier run would have left it.
+func (f *fakeIAM) addKey(user string, status iamtypes.StatusType) string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.mintLocked(f.users[user], status).id
+}
+
+func (f *fakeIAM) mintLocked(u *fakeUser, status iamtypes.StatusType) *fakeKey {
+ f.nextKey++
+ f.clock = f.clock.Add(time.Minute)
+ k := &fakeKey{id: fmt.Sprintf("AKIA%016d", f.nextKey), secret: fmt.Sprintf("%s-%d", secretText, f.nextKey), status: status, created: f.clock}
+ u.keys = append(u.keys, k)
+ return k
+}
+
+func (f *fakeIAM) call(op, user string, effect func(u *fakeUser) error) error {
+ if f.hold != nil {
+ f.hold(op, user)
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.counts[op]++
+ n := f.counts[op]
+ if f.before != nil {
+ if err := f.before(op, n); err != nil {
+ return err
+ }
+ }
+ u := f.users[user]
+ if op != "CreateUser" && u == nil {
+ return &iamtypes.NoSuchEntityException{Message: aws.String("no user " + secretText)}
+ }
+ if err := effect(u); err != nil {
+ return err
+ }
+ if f.after != nil {
+ return f.after(op, n)
+ }
+ return nil
+}
+
+// page returns item i of items as one page.
+func page1[T any](items []T, marker *string) ([]T, bool, *string) {
+ i := 0
+ if marker != nil {
+ i, _ = strconv.Atoi(strings.TrimPrefix(*marker, "m"))
+ }
+ if i >= len(items) {
+ return nil, false, nil
+ }
+ if i+1 < len(items) {
+ return items[i : i+1], true, aws.String("m" + strconv.Itoa(i+1))
+ }
+ return items[i : i+1], false, nil
+}
+
+func (f *fakeIAM) CreateUser(ctx context.Context, in *iam.CreateUserInput, _ ...func(*iam.Options)) (*iam.CreateUserOutput, error) {
+ name := aws.ToString(in.UserName)
+ err := f.call("CreateUser", name, func(u *fakeUser) error {
+ if u != nil {
+ return &iamtypes.EntityAlreadyExistsException{Message: aws.String("exists")}
+ }
+ nu := &fakeUser{name: name, path: aws.ToString(in.Path), arn: "arn:aws:iam::" + testAccount + ":user" + aws.ToString(in.Path) + name, inline: map[string]string{}}
+ if in.PermissionsBoundary != nil {
+ nu.boundary = &iamtypes.AttachedPermissionsBoundary{PermissionsBoundaryArn: in.PermissionsBoundary, PermissionsBoundaryType: iamtypes.PermissionsBoundaryAttachmentTypePolicy}
+ }
+ f.users[name] = nu
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &iam.CreateUserOutput{}, nil
+}
+
+func (f *fakeIAM) GetUser(ctx context.Context, in *iam.GetUserInput, _ ...func(*iam.Options)) (*iam.GetUserOutput, error) {
+ out := &iam.GetUserOutput{}
+ return out, f.call("GetUser", aws.ToString(in.UserName), func(u *fakeUser) error {
+ out.User = &iamtypes.User{UserName: aws.String(u.name), Path: aws.String(u.path), Arn: aws.String(u.arn), PermissionsBoundary: u.boundary}
+ return nil
+ })
+}
+
+func (f *fakeIAM) PutUserPolicy(ctx context.Context, in *iam.PutUserPolicyInput, _ ...func(*iam.Options)) (*iam.PutUserPolicyOutput, error) {
+ return &iam.PutUserPolicyOutput{}, f.call("PutUserPolicy", aws.ToString(in.UserName), func(u *fakeUser) error {
+ if !f.dropPolicyPut {
+ u.inline[aws.ToString(in.PolicyName)] = aws.ToString(in.PolicyDocument)
+ }
+ return nil
+ })
+}
+
+func (f *fakeIAM) GetUserPolicy(ctx context.Context, in *iam.GetUserPolicyInput, _ ...func(*iam.Options)) (*iam.GetUserPolicyOutput, error) {
+ out := &iam.GetUserPolicyOutput{}
+ return out, f.call("GetUserPolicy", aws.ToString(in.UserName), func(u *fakeUser) error {
+ doc, ok := u.inline[aws.ToString(in.PolicyName)]
+ if !ok {
+ return &iamtypes.NoSuchEntityException{}
+ }
+ // IAM answers RFC 3986 encoding.
+ out.PolicyDocument = aws.String(strings.ReplaceAll(url.QueryEscape(doc), "+", "%20"))
+ return nil
+ })
+}
+
+func (f *fakeIAM) ListUserPolicies(ctx context.Context, in *iam.ListUserPoliciesInput, _ ...func(*iam.Options)) (*iam.ListUserPoliciesOutput, error) {
+ out := &iam.ListUserPoliciesOutput{}
+ return out, f.call("ListUserPolicies", aws.ToString(in.UserName), func(u *fakeUser) error {
+ var names []string
+ for n := range u.inline {
+ names = append(names, n)
+ }
+ sort.Strings(names)
+ out.PolicyNames, out.IsTruncated, out.Marker = page1(names, in.Marker)
+ return nil
+ })
+}
+
+func (f *fakeIAM) ListAttachedUserPolicies(ctx context.Context, in *iam.ListAttachedUserPoliciesInput, _ ...func(*iam.Options)) (*iam.ListAttachedUserPoliciesOutput, error) {
+ out := &iam.ListAttachedUserPoliciesOutput{}
+ return out, f.call("ListAttachedUserPolicies", aws.ToString(in.UserName), func(u *fakeUser) error {
+ var items []iamtypes.AttachedPolicy
+ for _, a := range u.attached {
+ items = append(items, iamtypes.AttachedPolicy{PolicyArn: aws.String(a)})
+ }
+ out.AttachedPolicies, out.IsTruncated, out.Marker = page1(items, in.Marker)
+ return nil
+ })
+}
+
+func (f *fakeIAM) ListGroupsForUser(ctx context.Context, in *iam.ListGroupsForUserInput, _ ...func(*iam.Options)) (*iam.ListGroupsForUserOutput, error) {
+ out := &iam.ListGroupsForUserOutput{}
+ return out, f.call("ListGroupsForUser", aws.ToString(in.UserName), func(u *fakeUser) error {
+ var items []iamtypes.Group
+ for _, g := range u.groups {
+ items = append(items, iamtypes.Group{GroupName: aws.String(g)})
+ }
+ out.Groups, out.IsTruncated, out.Marker = page1(items, in.Marker)
+ return nil
+ })
+}
+
+func (f *fakeIAM) ListAccessKeys(ctx context.Context, in *iam.ListAccessKeysInput, _ ...func(*iam.Options)) (*iam.ListAccessKeysOutput, error) {
+ out := &iam.ListAccessKeysOutput{}
+ return out, f.call("ListAccessKeys", aws.ToString(in.UserName), func(u *fakeUser) error {
+ var items []iamtypes.AccessKeyMetadata
+ for _, k := range u.keys {
+ items = append(items, iamtypes.AccessKeyMetadata{AccessKeyId: aws.String(k.id), Status: k.status, CreateDate: aws.Time(k.created), UserName: aws.String(u.name)})
+ }
+ out.AccessKeyMetadata, out.IsTruncated, out.Marker = page1(items, in.Marker)
+ return nil
+ })
+}
+
+func (f *fakeIAM) DeleteAccessKey(ctx context.Context, in *iam.DeleteAccessKeyInput, _ ...func(*iam.Options)) (*iam.DeleteAccessKeyOutput, error) {
+ return &iam.DeleteAccessKeyOutput{}, f.call("DeleteAccessKey", aws.ToString(in.UserName), func(u *fakeUser) error {
+ for i, k := range u.keys {
+ if k.id == aws.ToString(in.AccessKeyId) {
+ if !f.dropDeletes {
+ u.keys = append(u.keys[:i:i], u.keys[i+1:]...)
+ }
+ return nil
+ }
+ }
+ return &iamtypes.NoSuchEntityException{}
+ })
+}
+
+func (f *fakeIAM) CreateAccessKey(ctx context.Context, in *iam.CreateAccessKeyInput, optFns ...func(*iam.Options)) (*iam.CreateAccessKeyOutput, error) {
+ var o iam.Options
+ for _, fn := range optFns {
+ fn(&o)
+ }
+ out := &iam.CreateAccessKeyOutput{}
+ return out, f.call("CreateAccessKey", aws.ToString(in.UserName), func(u *fakeUser) error {
+ f.keyAttempts = append(f.keyAttempts, o.RetryMaxAttempts)
+ if len(u.keys) >= 2 {
+ return apiErr("LimitExceeded")
+ }
+ k := f.mintLocked(u, iamtypes.StatusTypeActive)
+ out.AccessKey = &iamtypes.AccessKey{AccessKeyId: aws.String(k.id), SecretAccessKey: aws.String(k.secret), Status: k.status, UserName: aws.String(u.name), CreateDate: aws.Time(k.created)}
+ return nil
+ })
+}
+
+// preparedStorage is a Storage whose fleet bucket and user exist.
+func preparedStorage(t *testing.T) (testStorage, string) {
+ t.Helper()
+ s := newTestStorage(t)
+ if _, err := s.EnsureFleetStorage(context.Background(), testFleet, testRegion); err != nil {
+ t.Fatal(err)
+ }
+ _, user := testNames(t, testFleet)
+ return s, user
+}
+
+func rotate(t *testing.T, s testStorage, keep string, delivered ...string) fleetstore.Credentials {
+ t.Helper()
+ return rotateFleet(t, s, testFleet, keep, delivered...)
+}
+
+func rotateFleet(t *testing.T, s testStorage, fleet, keep string, delivered ...string) fleetstore.Credentials {
+ t.Helper()
+ c, err := s.RotateFleetCredentials(context.Background(), fleet, keep, delivered)
+ if err != nil {
+ t.Fatalf("rotate keep=%q: %v", keep, err)
+ }
+ if c.ID == "" || !strings.HasPrefix(string(c.Secret), secretText) {
+ t.Fatalf("rotation returned %q", c.ID)
+ }
+ return c
+}
+
+func sameKeys(t *testing.T, got []string, want ...string) {
+ t.Helper()
+ sort.Strings(got)
+ sort.Strings(want)
+ if !reflect.DeepEqual(got, want) && !(len(got) == 0 && len(want) == 0) {
+ t.Fatalf("keys %v, want %v", got, want)
+ }
+}
+
+func TestAWSFleetExistingUserDrift(t *testing.T) {
+ ctx := context.Background()
+ bucket, user := testNames(t, testFleet)
+ good, err := fleetDataPolicy("arn:aws:s3:::" + bucket)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cases := map[string]func(u *fakeUser){
+ "wrong path": func(u *fakeUser) { u.path = "/other/"; u.arn = "arn:aws:iam::" + testAccount + ":user/other/" + user },
+ "wrong account in ARN": func(u *fakeUser) { u.arn = "arn:aws:iam::" + foreignAcct + ":user" + testUserPath + user },
+ "wrong boundary": func(u *fakeUser) {
+ u.boundary.PermissionsBoundaryArn = aws.String("arn:aws:iam::" + testAccount + ":policy/wide")
+ },
+ "no boundary": func(u *fakeUser) { u.boundary = nil },
+ "extra inline policy": func(u *fakeUser) { u.inline["admin"] = `{"Version":"2012-10-17","Statement":[]}` },
+ "managed attachment": func(u *fakeUser) { u.attached = []string{"arn:aws:iam::aws:policy/AdministratorAccess"} },
+ "attachment on page 2": func(u *fakeUser) { u.attached = []string{"", "arn:aws:iam::aws:policy/AdministratorAccess"} },
+ "group membership": func(u *fakeUser) { u.groups = []string{"admins"} },
+ "different policy": func(u *fakeUser) { u.inline[fleetPolicyName] = strings.Replace(good, `"s3:ListBucket"`, `"s3:*"`, 1) },
+ "policy with unknown field": func(u *fakeUser) {
+ u.inline[fleetPolicyName] = strings.Replace(good, `"Sid":"Bucket",`, `"Sid":"Bucket","Principal":"*",`, 1)
+ },
+ }
+ for name, mutate := range cases {
+ t.Run(name, func(t *testing.T) {
+ s, _ := preparedStorage(t)
+ k1 := rotate(t, s, "").ID
+ s.iam.mu.Lock()
+ u := s.iam.users[user]
+ if name != "different policy" && name != "policy with unknown field" {
+ delete(u.inline, fleetPolicyName) // missing, so only validation can stop a Put
+ }
+ mutate(u)
+ s.iam.mu.Unlock()
+ puts, keys := s.iam.count("PutUserPolicy"), s.iam.keyMutations()
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err == nil {
+ t.Fatal("prepared a drifted user")
+ } else {
+ noLeak(t, err.Error())
+ }
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, k1, []string{k1}); err == nil {
+ t.Fatal("rotated keys on a drifted user")
+ }
+ if _, err := s.FleetCredentials(ctx, testFleet); err == nil {
+ t.Fatal("named a key on a drifted user")
+ }
+ if s.iam.count("PutUserPolicy") != puts || s.iam.keyMutations() != keys {
+ t.Fatal("mutated a drifted user")
+ }
+ sameKeys(t, s.iam.liveKeys(user), k1)
+ })
+ }
+ t.Run("missing policy installed on a valid user", func(t *testing.T) {
+ s, _ := preparedStorage(t)
+ s.iam.mu.Lock()
+ delete(s.iam.users[user].inline, fleetPolicyName)
+ s.iam.mu.Unlock()
+ puts := s.iam.count("PutUserPolicy")
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err != nil {
+ t.Fatal(err)
+ }
+ if s.iam.count("PutUserPolicy") != puts+1 {
+ t.Fatal("did not reinstall the policy")
+ }
+ if _, err := s.verifyFleetUser(ctx, testFleet); err != nil {
+ t.Fatal(err)
+ }
+ })
+ t.Run("created user carries path and boundary", func(t *testing.T) {
+ s, _ := preparedStorage(t)
+ u := s.iam.users[user]
+ if u.path != testUserPath || aws.ToString(u.boundary.PermissionsBoundaryArn) != testBoundary {
+ t.Fatalf("%+v", u)
+ }
+ })
+ for _, op := range []string{"ListUserPolicies", "ListAttachedUserPolicies", "ListGroupsForUser"} {
+ t.Run(op+" failure is not empty", func(t *testing.T) {
+ s, _ := preparedStorage(t)
+ s.iam.mu.Lock()
+ delete(s.iam.users[user].inline, fleetPolicyName)
+ s.iam.mu.Unlock()
+ puts := s.iam.count("PutUserPolicy")
+ s.iam.before = func(o string, _ int) error {
+ if o == op {
+ return apiErr("Throttling")
+ }
+ return nil
+ }
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err == nil || s.iam.count("PutUserPolicy") != puts {
+ t.Fatalf("treated a failed %s as empty", op)
+ }
+ })
+ }
+ t.Run("truncated page with no marker", func(t *testing.T) {
+ s, _ := preparedStorage(t)
+ bad := iamMethods{getUser: s.iam.GetUser, listAttached: s.iam.ListAttachedUserPolicies, listGroups: s.iam.ListGroupsForUser, getPolicy: s.iam.GetUserPolicy,
+ listPolicies: func(context.Context, *iam.ListUserPoliciesInput, ...func(*iam.Options)) (*iam.ListUserPoliciesOutput, error) {
+ return &iam.ListUserPoliciesOutput{IsTruncated: true}, nil
+ }}
+ s.users = bad
+ if _, err := s.verifyFleetUser(ctx, testFleet); err == nil {
+ t.Fatal("accepted a truncated listing")
+ }
+ })
+ t.Run("empty boundary refuses construction", func(t *testing.T) {
+ cfg := testStorageConfig()
+ cfg.BoundaryARN = ""
+ if _, err := newStorage(cfg, map[string]s3API{}, newFakeIAM(t)); err == nil {
+ t.Fatal("constructed with no boundary")
+ }
+ })
+}
+
+func TestAWSFleetCredentialsDoubleLostRotation(t *testing.T) {
+ ctx := context.Background()
+ t.Run("lost seal twice keeps K1", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ k1 := rotate(t, s, "").ID
+ // K1 is delivered. K2 is minted, then its seal is lost.
+ k2 := rotate(t, s, k1, k1).ID
+ sameKeys(t, s.iam.liveKeys(user), k1, k2)
+ k3 := rotate(t, s, k1, k1).ID
+ sameKeys(t, s.iam.liveKeys(user), k1, k3)
+ k4 := rotate(t, s, k1, k1).ID
+ sameKeys(t, s.iam.liveKeys(user), k1, k4)
+ })
+ t.Run("keep on page 2 survives", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ orphan := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ keep := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ c := rotate(t, s, keep, keep)
+ sameKeys(t, s.iam.liveKeys(user), keep, c.ID)
+ if c.ID == orphan {
+ t.Fatal("reused the orphan")
+ }
+ })
+ t.Run("missing keep changes nothing", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ orphan := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, "AKIA9999999999999999", []string{"AKIA9999999999999999"}); err == nil {
+ t.Fatal("rotated without the key to keep")
+ }
+ if s.iam.keyMutations() != 0 {
+ t.Fatal("reaped or minted without the key to keep")
+ }
+ sameKeys(t, s.iam.liveKeys(user), orphan)
+ })
+ t.Run("second delivered key still live", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ k1 := rotate(t, s, "").ID
+ k2 := rotate(t, s, k1, k1).ID // seal lost after K1; K2 then delivered too
+ muts := s.iam.keyMutations()
+ _, err := s.RotateFleetCredentials(ctx, testFleet, k2, []string{k1, k2})
+ if !errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) {
+ t.Fatalf("got %v", err)
+ }
+ noLeak(t, err.Error())
+ if strings.Contains(err.Error(), k1) {
+ t.Fatal("error names the key")
+ }
+ if s.iam.keyMutations() != muts {
+ t.Fatal("reaped or minted past a live delivered key")
+ }
+ sameKeys(t, s.iam.liveKeys(user), k1, k2)
+ })
+ t.Run("delivered key on page 2", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ keep := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ old := s.iam.addKey(user, iamtypes.StatusTypeInactive) // inactive is still protected
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, keep, []string{old, keep}); !errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) {
+ t.Fatalf("got %v", err)
+ }
+ if s.iam.keyMutations() != 0 {
+ t.Fatal("mutated keys")
+ }
+ })
+ t.Run("delivered key gone is no obstacle", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ k1 := rotate(t, s, "").ID
+ k2 := rotate(t, s, k1, k1).ID
+ s.iam.mu.Lock()
+ s.iam.users[user].keys = s.iam.users[user].keys[1:] // an operator deleted K1
+ s.iam.mu.Unlock()
+ k3 := rotate(t, s, k2, k1, k2).ID
+ sameKeys(t, s.iam.liveKeys(user), k2, k3)
+ })
+ t.Run("empty keep reaps only undelivered orphans", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ s.iam.addKey(user, iamtypes.StatusTypeActive) // an undelivered orphan
+ c := rotate(t, s, "")
+ sameKeys(t, s.iam.liveKeys(user), c.ID)
+ delivered := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, "", []string{delivered}); !errors.Is(err, fleetstore.ErrDeliveredKeyStillLive) {
+ t.Fatalf("got %v", err)
+ }
+ })
+ t.Run("partial key listing refuses", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ k1 := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ s.iam.addKey(user, iamtypes.StatusTypeActive)
+ s.iam.before = func(op string, n int) error {
+ if op == "ListAccessKeys" && n == 2 { // page 2 of the first listing
+ return apiErr("Throttling")
+ }
+ return nil
+ }
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, k1, []string{k1}); err == nil {
+ t.Fatal("rotated on a partial inventory")
+ }
+ if s.iam.keyMutations() != 0 {
+ t.Fatal("mutated keys on a partial inventory")
+ }
+ })
+}
+
+func TestAWSFleetKeyFailures(t *testing.T) {
+ ctx := context.Background()
+ t.Run("failed deletion mints nothing", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ k1 := rotate(t, s, "").ID
+ orphan := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ s.iam.before = func(op string, _ int) error {
+ if op == "DeleteAccessKey" {
+ return apiErr("ServiceFailure")
+ }
+ return nil
+ }
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, k1, []string{k1}); err == nil {
+ t.Fatal("rotated past a failed deletion")
+ }
+ if s.iam.count("CreateAccessKey") != 1 {
+ t.Fatal("minted after a failed deletion")
+ }
+ sameKeys(t, s.iam.liveKeys(user), k1, orphan)
+ })
+ t.Run("unconfirmed deletion mints nothing", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ k1 := rotate(t, s, "").ID
+ orphan := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ s.iam.dropDeletes = true
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, k1, []string{k1}); err == nil || s.iam.count("CreateAccessKey") != 1 {
+ t.Fatal("minted while a reaped key still listed")
+ }
+ sameKeys(t, s.iam.liveKeys(user), k1, orphan)
+ })
+ t.Run("lost mint answer is reaped next time", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ k1 := rotate(t, s, "").ID
+ s.iam.after = func(op string, _ int) error {
+ if op == "CreateAccessKey" {
+ return apiErr("ServiceUnavailable")
+ }
+ return nil
+ }
+ _, err := s.RotateFleetCredentials(ctx, testFleet, k1, []string{k1})
+ ambiguous(t, err)
+ if n := len(s.iam.keyAttempts); n != 2 || s.iam.keyAttempts[1] != 1 {
+ t.Fatalf("CreateAccessKey attempts %v; want a single-attempt send", s.iam.keyAttempts)
+ }
+ if len(s.iam.liveKeys(user)) != 2 {
+ t.Fatal("the lost mint left no orphan to prove the test")
+ }
+ s.iam.after = nil
+ k3 := rotate(t, s, k1, k1).ID
+ sameKeys(t, s.iam.liveKeys(user), k1, k3)
+ })
+ t.Run("inactive kept key refuses", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ keep := s.iam.addKey(user, iamtypes.StatusTypeInactive)
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, keep, []string{keep}); err == nil || s.iam.keyMutations() != 0 {
+ t.Fatal("rotated around an inactive key")
+ }
+ })
+ t.Run("malformed IDs refuse", func(t *testing.T) {
+ s, _ := preparedStorage(t)
+ for _, c := range [][2]string{{"not a key", ""}, {"", "not a key"}} {
+ var delivered []string
+ if c[1] != "" {
+ delivered = []string{c[1]}
+ }
+ if _, err := s.RotateFleetCredentials(ctx, testFleet, c[0], delivered); err == nil || s.iam.keyMutations() != 0 {
+ t.Fatalf("accepted %q", c)
+ }
+ }
+ })
+ t.Run("same fleet serialized, other fleet not blocked", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ if _, err := s.EnsureFleetStorage(ctx, "shop-2", testRegion); err != nil {
+ t.Fatal(err)
+ }
+ _, user2 := testNames(t, "shop-2")
+ k1 := rotate(t, s, "").ID
+ other := rotateFleet(t, s, "shop-2", "").ID
+ release := make(chan struct{})
+ entered := make(chan struct{}, 4)
+ var mu sync.Mutex
+ inFlight := 0
+ // A rotation runs from its GetUser to its CreateAccessKey, both
+ // inside the fleet lock.
+ s.iam.hold = func(op, u string) {
+ if u != user {
+ return
+ }
+ if op == "CreateAccessKey" {
+ mu.Lock()
+ inFlight--
+ mu.Unlock()
+ return
+ }
+ if op != "GetUser" {
+ return
+ }
+ mu.Lock()
+ inFlight++
+ n := inFlight
+ mu.Unlock()
+ if n > 1 {
+ t.Error("two rotations of one fleet ran at once")
+ }
+ entered <- struct{}{}
+ if n == 1 {
+ <-release
+ }
+ }
+ done := make(chan error, 2)
+ for range 2 {
+ go func() {
+ _, err := s.RotateFleetCredentials(ctx, testFleet, k1, []string{k1})
+ done <- err
+ }()
+ }
+ <-entered
+ // The other fleet proceeds while this one is held.
+ if _, err := s.RotateFleetCredentials(ctx, "shop-2", other, []string{other}); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(20 * time.Millisecond)
+ mu.Lock()
+ if inFlight != 1 {
+ t.Errorf("%d rotations in flight", inFlight)
+ }
+ mu.Unlock()
+ close(release)
+ for range 2 {
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ }
+ keys := s.iam.liveKeys(user)
+ if len(keys) != 2 || !strings.Contains(strings.Join(keys, ","), k1) {
+ t.Fatalf("keys %v", keys)
+ }
+ if ks := s.iam.liveKeys(user2); len(ks) != 2 || !strings.Contains(strings.Join(ks, ","), other) {
+ t.Fatalf("other fleet keys %v", ks)
+ }
+ })
+ t.Run("FleetCredentials names the newest active key without a secret", func(t *testing.T) {
+ s, user := preparedStorage(t)
+ if c, err := s.FleetCredentials(ctx, testFleet); err != nil || c.ID != "" || c.Secret != nil {
+ t.Fatalf("%+v %v", c, err)
+ }
+ older := s.iam.addKey(user, iamtypes.StatusTypeActive)
+ s.iam.addKey(user, iamtypes.StatusTypeInactive)
+ c, err := s.FleetCredentials(ctx, testFleet)
+ if err != nil || c.ID != older || c.Secret != nil {
+ t.Fatalf("%+v %v", c, err)
+ }
+ newer := rotate(t, s, older, older).ID
+ s.iam.mu.Lock()
+ for _, k := range s.iam.users[user].keys {
+ k.created = fixedLaunch // a tie falls to the ID
+ }
+ s.iam.mu.Unlock()
+ muts := s.iam.keyMutations()
+ if c, err := s.FleetCredentials(ctx, testFleet); err != nil || c.ID != max(older, newer) || c.Secret != nil {
+ t.Fatalf("%+v %v", c, err)
+ }
+ if s.iam.keyMutations() != muts {
+ t.Fatal("FleetCredentials changed keys")
+ }
+ })
+ t.Run("client surfaces", func(t *testing.T) {
+ // No SDK call here returns an existing secret: CreateAccessKey is the
+ // only source, and S3 has no object, delete or policy call at all.
+ methods := func(v any) []string {
+ ty := reflect.TypeOf(v).Elem()
+ var out []string
+ for i := range ty.NumMethod() {
+ out = append(out, ty.Method(i).Name)
+ }
+ return out
+ }
+ wantIAM := []string{"CreateAccessKey", "CreateUser", "DeleteAccessKey", "GetUser", "GetUserPolicy", "ListAccessKeys", "ListAttachedUserPolicies", "ListGroupsForUser", "ListUserPolicies", "PutUserPolicy"}
+ wantS3 := []string{"CreateBucket", "GetBucketEncryption", "GetBucketLifecycleConfiguration", "GetBucketLocation", "GetBucketTagging", "GetBucketVersioning",
+ "GetPublicAccessBlock", "PutBucketEncryption", "PutBucketLifecycleConfiguration", "PutBucketVersioning", "PutPublicAccessBlock"}
+ if got := methods((*iamAPI)(nil)); !reflect.DeepEqual(got, wantIAM) {
+ t.Errorf("iamAPI %v", got)
+ }
+ if got := methods((*s3API)(nil)); !reflect.DeepEqual(got, wantS3) {
+ t.Errorf("s3API %v", got)
+ }
+ })
+}
diff --git a/internal/awsmanaged/export_test.go b/internal/awsmanaged/export_test.go
index 35b81d87e..20fc72485 100644
--- a/internal/awsmanaged/export_test.go
+++ b/internal/awsmanaged/export_test.go
@@ -19,7 +19,17 @@ type HTTPClient interface {
// process (as rootaws.LoadStaticConfig does), so no test can reach AWS or
// the metadata service whatever its environment.
func NewComputeWith(ctx context.Context, cfg ComputeConfig, transport HTTPClient) (*Compute, error) {
- return loadCompute(ctx, cfg,
+ return loadCompute(ctx, cfg, testLoadOptions(transport)...)
+}
+
+// NewStorageWith is NewStorage with the same isolation as NewComputeWith,
+// applied to every S3 client and to the IAM client alike.
+func NewStorageWith(ctx context.Context, cfg StorageConfig, transport HTTPClient) (*Storage, error) {
+ return loadStorage(ctx, cfg, testLoadOptions(transport)...)
+}
+
+func testLoadOptions(transport HTTPClient) []func(*awsconfig.LoadOptions) error {
+ return []func(*awsconfig.LoadOptions) error{
awsconfig.WithHTTPClient(transport),
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("AKIDTEST", "test-secret", "")),
awsconfig.WithSharedConfigFiles([]string{}), awsconfig.WithSharedCredentialsFiles([]string{}),
@@ -30,5 +40,5 @@ func NewComputeWith(ctx context.Context, cfg ComputeConfig, transport HTTPClient
o.DefaultsModeOptions.IMDSClient = imds.New(imds.Options{ClientEnableState: imds.ClientDisabled})
return nil
},
- )
+ }
}
diff --git a/internal/awsmanaged/policy.go b/internal/awsmanaged/policy.go
new file mode 100644
index 000000000..7b894bf26
--- /dev/null
+++ b/internal/awsmanaged/policy.go
@@ -0,0 +1,166 @@
+package awsmanaged
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "regexp"
+ "sort"
+ "strings"
+)
+
+// fleetPolicyName is the one inline policy a fleet user carries. It is not
+// objstore's carlos-store: a fleet user's data powers (versions, multipart,
+// the secrets-key object) are not an app store's, and neither policy is
+// ever widened to stand in for the other.
+const fleetPolicyName = "carlos-fleet-data"
+
+// fleetSecretsKeyObject is the private half of the fleet's secrets key,
+// written once by the first box (spec Phase 2 addendum 2; 2b-2 writes it).
+const fleetSecretsKeyObject = "system/fleet-secrets-key.json"
+
+// maxInlinePolicy is IAM's limit on all of one user's inline policies
+// together, whitespace excluded. The document is built compact.
+const maxInlinePolicy = 2048
+
+// fleetDataPrefixes are the box's data consumers in internal/lease: leases,
+// replicas and files live under instances/<host>/; restore and move staging
+// use moves/ and move-snapshots/ with exact versions. The same three
+// prefixes the region-host HA grant scopes version access to.
+var fleetDataPrefixes = []string{"instances/*", "moves/*", "move-snapshots/*"}
+
+// fleetProbePrefix is the storage challenge's namespace (2b-2 writes it).
+const fleetProbePrefix = "_carlos/probes/*"
+
+var bucketARNRE = regexp.MustCompile(`^arn:aws:s3:::([a-z0-9][a-z0-9-]{1,61}[a-z0-9])$`)
+
+type policyDoc struct {
+ Version string `json:"Version"`
+ Statement []policyStatement `json:"Statement"`
+}
+
+type policyStatement struct {
+ Sid string `json:"Sid"`
+ Effect string `json:"Effect"`
+ Action stringSet `json:"Action"`
+ Resource stringSet `json:"Resource,omitempty"`
+ NotResource stringSet `json:"NotResource,omitempty"`
+ Condition map[string]map[string]stringSet `json:"Condition,omitempty"`
+}
+
+// stringSet is an IAM value that may be written as one string or a list.
+// It decodes both forms and is compared sorted, as IAM evaluates it.
+type stringSet []string
+
+func (s *stringSet) UnmarshalJSON(b []byte) error {
+ var one string
+ if err := json.Unmarshal(b, &one); err == nil {
+ *s = stringSet{one}
+ return nil
+ }
+ var many []string
+ if err := json.Unmarshal(b, &many); err != nil {
+ return err
+ }
+ *s = many
+ return nil
+}
+
+// fleetDataPolicy is the fleet user's inline policy for exactly one bucket.
+// Bucket-level actions name only the bucket ARN and object actions only
+// object ARNs under it. ListBucket carries no prefix condition, so a GET of
+// a missing key answers 404 rather than 403. The secrets-key object may be
+// created only by a request carrying If-None-Match: *, so the first writer
+// wins and nothing overwrites it. No DeleteObjectVersion: lease release
+// deletes a bare key, and destructive version paths stay refused. The final
+// Deny keeps every other bucket out of reach even if some resource policy
+// elsewhere would allow it.
+func fleetDataPolicy(bucketARN string) (string, error) {
+ if !bucketARNRE.MatchString(bucketARN) {
+ return "", errors.New("awsmanaged: fleet bucket ARN is invalid")
+ }
+ objects := func(prefixes ...string) stringSet {
+ var out stringSet
+ for _, p := range prefixes {
+ out = append(out, bucketARN+"/"+p)
+ }
+ return out
+ }
+ versionPrefixes := append(append(stringSet{}, fleetDataPrefixes...), fleetProbePrefix, fleetSecretsKeyObject)
+ doc := policyDoc{Version: "2012-10-17", Statement: []policyStatement{
+ {Sid: "Bucket", Effect: "Allow", Action: stringSet{"s3:GetBucketLocation", "s3:ListBucket"}, Resource: stringSet{bucketARN}},
+ {Sid: "Versions", Effect: "Allow", Action: stringSet{"s3:ListBucketVersions"}, Resource: stringSet{bucketARN},
+ Condition: map[string]map[string]stringSet{"StringLike": {"s3:prefix": versionPrefixes}}},
+ {Sid: "Uploads", Effect: "Allow", Action: stringSet{"s3:ListBucketMultipartUploads"}, Resource: stringSet{bucketARN},
+ Condition: map[string]map[string]stringSet{"StringLike": {"s3:prefix": append(stringSet{}, fleetDataPrefixes...)}}},
+ {Sid: "Data", Effect: "Allow", Action: stringSet{
+ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:GetObjectVersion",
+ "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts",
+ }, Resource: objects(fleetDataPrefixes...)},
+ {Sid: "Probes", Effect: "Allow", Action: stringSet{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, Resource: objects(fleetProbePrefix)},
+ {Sid: "KeyRead", Effect: "Allow", Action: stringSet{"s3:GetObject"}, Resource: objects(fleetSecretsKeyObject)},
+ {Sid: "KeyCreate", Effect: "Allow", Action: stringSet{"s3:PutObject"}, Resource: objects(fleetSecretsKeyObject),
+ Condition: map[string]map[string]stringSet{"StringEquals": {"s3:if-none-match": {"*"}}}},
+ {Sid: "OnlyThisBucket", Effect: "Deny", Action: stringSet{"s3:*"}, NotResource: stringSet{bucketARN, bucketARN + "/*"}},
+ }}
+ var b bytes.Buffer
+ enc := json.NewEncoder(&b)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(doc); err != nil {
+ return "", errors.New("awsmanaged: encode fleet data policy")
+ }
+ out := strings.TrimSuffix(b.String(), "\n")
+ if len(out) > maxInlinePolicy {
+ return "", errors.New("awsmanaged: fleet data policy is too long")
+ }
+ return out, nil
+}
+
+// canonicalPolicy decodes an IAM policy document strictly (an unknown field
+// such as Principal or NotAction is an error, never silently dropped) and
+// returns it with every set sorted and statements ordered by Sid, so two
+// documents IAM evaluates identically compare equal.
+func canonicalPolicy(doc string) (policyDoc, error) {
+ dec := json.NewDecoder(strings.NewReader(doc))
+ dec.DisallowUnknownFields()
+ var p policyDoc
+ if err := dec.Decode(&p); err != nil {
+ return policyDoc{}, errors.New("awsmanaged: policy document is not a recognised shape")
+ }
+ if dec.More() {
+ return policyDoc{}, errors.New("awsmanaged: policy document has trailing data")
+ }
+ seen := map[string]bool{}
+ for i := range p.Statement {
+ st := &p.Statement[i]
+ if st.Sid == "" || seen[st.Sid] {
+ return policyDoc{}, errors.New("awsmanaged: policy statements need distinct Sids")
+ }
+ seen[st.Sid] = true
+ for _, set := range []stringSet{st.Action, st.Resource, st.NotResource} {
+ sort.Strings(set)
+ }
+ for _, keys := range st.Condition {
+ for _, set := range keys {
+ sort.Strings(set)
+ }
+ }
+ }
+ sort.Slice(p.Statement, func(i, j int) bool { return p.Statement[i].Sid < p.Statement[j].Sid })
+ return p, nil
+}
+
+// samePolicy reports whether got is structurally want.
+func samePolicy(got, want string) bool {
+ g, err := canonicalPolicy(got)
+ if err != nil {
+ return false
+ }
+ w, err := canonicalPolicy(want)
+ if err != nil {
+ return false
+ }
+ gb, _ := json.Marshal(g)
+ wb, _ := json.Marshal(w)
+ return bytes.Equal(gb, wb)
+}
diff --git a/internal/awsmanaged/policy_test.go b/internal/awsmanaged/policy_test.go
new file mode 100644
index 000000000..c27df3f65
--- /dev/null
+++ b/internal/awsmanaged/policy_test.go
@@ -0,0 +1,497 @@
+package awsmanaged
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/carlosframework/platform/internal/rootaws"
+)
+
+const fixtureBucketARN = "arn:aws:s3:::carlos-fleet-0123456789abcdef01234567"
+
+func loadFixture(t *testing.T) string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join("testdata", "fleet-data-policy.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var b bytes.Buffer
+ if err := json.Compact(&b, raw); err != nil {
+ t.Fatal(err)
+ }
+ return b.String()
+}
+
+// arnMatches is S3 ARN wildcard matching: * spans any characters, '/'
+// included.
+func arnMatches(pattern, arn string) bool {
+ re := "^" + strings.ReplaceAll(regexp.QuoteMeta(pattern), `\*`, ".*") + "$"
+ return regexp.MustCompile(re).MatchString(arn)
+}
+
+// grants reports whether doc has an Allow for action on resource whose
+// conditions ctx satisfies, and no Deny that applies. It is a structural
+// reading of this document's own shape, not an IAM simulation.
+func grants(doc policyDoc, action, resource string, ctx map[string]string) bool {
+ matchAny := func(set stringSet, v string) bool {
+ for _, p := range set {
+ if arnMatches(p, v) {
+ return true
+ }
+ }
+ return false
+ }
+ condOK := func(c map[string]map[string]stringSet) bool {
+ for op, keys := range c {
+ for k, vals := range keys {
+ got, ok := ctx[k]
+ if !ok {
+ return false
+ }
+ hit := false
+ for _, v := range vals {
+ if op == "StringEquals" && v == got || op == "StringLike" && arnMatches(v, got) {
+ hit = true
+ }
+ }
+ if !hit {
+ return false
+ }
+ }
+ }
+ return true
+ }
+ allowed := false
+ for _, st := range doc.Statement {
+ if !matchAny(st.Action, action) {
+ continue
+ }
+ applies := matchAny(st.Resource, resource) || len(st.NotResource) > 0 && !matchAny(st.NotResource, resource)
+ if !applies || !condOK(st.Condition) {
+ continue
+ }
+ if st.Effect == "Deny" {
+ return false
+ }
+ allowed = true
+ }
+ return allowed
+}
+
+func TestAWSFleetDataPolicyIsolation(t *testing.T) {
+ got, err := fleetDataPolicy(fixtureBucketARN)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := loadFixture(t); got != want {
+ t.Fatalf("policy differs from testdata/fleet-data-policy.json:\n got %s\nwant %s", got, want)
+ }
+ doc, err := canonicalPolicy(got)
+ if err != nil {
+ t.Fatal(err)
+ }
+ bucket, objects := fixtureBucketARN, fixtureBucketARN+"/"
+ bucketActions := map[string]bool{"s3:GetBucketLocation": true, "s3:ListBucket": true, "s3:ListBucketVersions": true, "s3:ListBucketMultipartUploads": true}
+ objectActions := map[string]bool{"s3:GetObject": true, "s3:PutObject": true, "s3:DeleteObject": true, "s3:GetObjectVersion": true,
+ "s3:AbortMultipartUpload": true, "s3:ListMultipartUploadParts": true}
+ denies := 0
+ for _, st := range doc.Statement {
+ if st.Effect == "Deny" {
+ denies++
+ if !reflectEqual(st.Action, stringSet{"s3:*"}) || !reflectEqual(st.NotResource, stringSet{bucket, bucket + "/*"}) || len(st.Resource) != 0 || st.Condition != nil {
+ t.Errorf("cross-bucket deny is %+v", st)
+ }
+ continue
+ }
+ if st.Effect != "Allow" || len(st.NotResource) != 0 {
+ t.Errorf("statement %s: %+v", st.Sid, st)
+ }
+ for _, a := range st.Action {
+ if strings.Contains(a, "*") || !bucketActions[a] && !objectActions[a] {
+ t.Errorf("statement %s allows %s", st.Sid, a)
+ }
+ for _, r := range st.Resource {
+ switch {
+ case bucketActions[a] && r != bucket:
+ t.Errorf("bucket action %s on %s", a, r)
+ case objectActions[a] && (!strings.HasPrefix(r, objects) || r == objects+"*"):
+ t.Errorf("object action %s on %s", a, r)
+ }
+ }
+ }
+ }
+ if denies != 1 {
+ t.Fatalf("%d deny statements", denies)
+ }
+ byAction := func(a string) []policyStatement {
+ var out []policyStatement
+ for _, st := range doc.Statement {
+ for _, x := range st.Action {
+ if x == a && st.Effect == "Allow" {
+ out = append(out, st)
+ }
+ }
+ }
+ return out
+ }
+ if l := byAction("s3:ListBucket"); len(l) != 1 || l[0].Condition != nil {
+ t.Errorf("ListBucket must be unconditioned on the exact bucket: %+v", l)
+ }
+ for a, want := range map[string]stringSet{
+ "s3:ListBucketVersions": {"_carlos/probes/*", "instances/*", "move-snapshots/*", "moves/*", "system/fleet-secrets-key.json"},
+ "s3:ListBucketMultipartUploads": {"instances/*", "move-snapshots/*", "moves/*"},
+ } {
+ l := byAction(a)
+ if len(l) != 1 || len(l[0].Condition) != 1 || !reflectEqual(l[0].Condition["StringLike"]["s3:prefix"], want) {
+ t.Errorf("%s prefix condition %+v", a, l)
+ }
+ }
+ key := objects + fleetSecretsKeyObject
+ puts := 0
+ for _, st := range byAction("s3:PutObject") {
+ for _, r := range st.Resource {
+ if arnMatches(r, key) {
+ puts++
+ if !reflectEqual(st.Condition["StringEquals"]["s3:if-none-match"], stringSet{"*"}) || len(st.Condition) != 1 {
+ t.Errorf("unconditional key write in %s", st.Sid)
+ }
+ }
+ }
+ }
+ if puts != 1 {
+ t.Errorf("%d PutObject grants reach the key", puts)
+ }
+ ifNoneMatch := map[string]string{"s3:if-none-match": "*"}
+ for _, c := range []struct {
+ action, resource string
+ ctx map[string]string
+ want bool
+ }{
+ // Lease, replica and files under instances/<host>/.
+ {"s3:GetObject", objects + "instances/h1/lock.json", nil, true},
+ {"s3:PutObject", objects + "instances/h1/lock.json", nil, true},
+ {"s3:DeleteObject", objects + "instances/h1/lock.json", nil, true},
+ {"s3:PutObject", objects + "instances/h1/files/0/a", nil, true},
+ // Restore and move staging read exact versions.
+ {"s3:GetObjectVersion", objects + "instances/h1/db.ltx", nil, true},
+ {"s3:GetObjectVersion", objects + "move-snapshots/m1/x", nil, true},
+ {"s3:PutObject", objects + "moves/m1/x", nil, true},
+ {"s3:AbortMultipartUpload", objects + "instances/h1/big", nil, true},
+ {"s3:ListBucket", bucket, nil, true},
+ {"s3:ListBucketVersions", bucket, map[string]string{"s3:prefix": "instances/h1/"}, true},
+ {"s3:ListBucketVersions", bucket, map[string]string{"s3:prefix": ""}, false},
+ {"s3:ListBucketMultipartUploads", bucket, map[string]string{"s3:prefix": "_carlos/probes/"}, false},
+ {"s3:GetObject", objects + "_carlos/probes/p1", nil, true},
+ {"s3:DeleteObject", objects + "_carlos/probes/p1", nil, true},
+ // The secrets key: read, first write only, never delete.
+ {"s3:GetObject", key, nil, true},
+ {"s3:PutObject", key, nil, false},
+ {"s3:PutObject", key, ifNoneMatch, true},
+ {"s3:DeleteObject", key, nil, false},
+ {"s3:GetObjectVersion", key, nil, false},
+ // Nothing outside the reserved prefixes, and no destruction of versions.
+ {"s3:PutObject", objects + "other/x", nil, false},
+ {"s3:DeleteObjectVersion", objects + "instances/h1/lock.json", nil, false},
+ {"s3:PutObjectTagging", objects + "instances/h1/lock.json", nil, false},
+ {"s3:PutBucketPolicy", bucket, nil, false},
+ {"s3:PutBucketVersioning", bucket, nil, false},
+ {"s3:DeleteBucket", bucket, nil, false},
+ {"iam:CreateAccessKey", "*", nil, false},
+ {"ec2:RunInstances", "*", nil, false},
+ // CopyObject: source GetObject and destination PutObject are each
+ // this bucket only; a sibling fleet or deployment bucket gets neither.
+ {"s3:GetObject", "arn:aws:s3:::carlos-fleet-ffffffffffffffffffffffff/instances/h1/lock.json", nil, false},
+ {"s3:GetObjectVersion", "arn:aws:s3:::carlos-fleet-ffffffffffffffffffffffff/instances/h1/lock.json", nil, false},
+ {"s3:PutObject", "arn:aws:s3:::carlos-production-123456789012/instances/h1/lock.json", nil, false},
+ {"s3:ListBucket", "arn:aws:s3:::carlos-production-123456789012", nil, false},
+ } {
+ if got := grants(doc, c.action, c.resource, c.ctx); got != c.want {
+ t.Errorf("%s on %s (%v) = %v, want %v", c.action, c.resource, c.ctx, got, c.want)
+ }
+ }
+ // The cross-bucket deny is what refuses a foreign bucket even when
+ // something else allows it.
+ wide := doc
+ wide.Statement = append(append([]policyStatement(nil), doc.Statement...), policyStatement{Sid: "Elsewhere", Effect: "Allow", Action: stringSet{"s3:GetObject"}, Resource: stringSet{"arn:aws:s3:::*"}})
+ if grants(wide, "s3:GetObject", "arn:aws:s3:::carlos-production-123456789012/x", nil) {
+ t.Error("another Allow reaches a foreign bucket")
+ }
+ t.Run("size and shape", func(t *testing.T) {
+ longest := "arn:aws:s3:::" + strings.Repeat("a", 24) + strings.Repeat("0", 24)
+ p, err := fleetDataPolicy(longest)
+ if err != nil || len(p) > maxInlinePolicy {
+ t.Fatalf("longest bucket: %d %v", len(p), err)
+ }
+ for _, bad := range []string{"", "arn:aws:s3:::*", "arn:aws:s3:::" + strings.Repeat("a", 24) + "/*", "arn:aws:s3:::Bad", "arn:aws:iam::123456789012:user/x"} {
+ if _, err := fleetDataPolicy(bad); err == nil {
+ t.Errorf("accepted %q", bad)
+ }
+ }
+ if !samePolicy(got, loadFixture(t)) || samePolicy(got, strings.Replace(got, `"s3:GetBucketLocation",`, "", 1)) {
+ t.Error("structural comparison")
+ }
+ // IAM may hand back single values as strings and lists in any order.
+ reordered := strings.Replace(got, `"Action":["s3:GetBucketLocation","s3:ListBucket"]`, `"Action":["s3:ListBucket","s3:GetBucketLocation"]`, 1)
+ reordered = strings.Replace(reordered, `"Action":["s3:ListBucketVersions"]`, `"Action":"s3:ListBucketVersions"`, 1)
+ if !samePolicy(reordered, got) {
+ t.Error("equivalent spelling compared unequal")
+ }
+ })
+}
+
+func reflectEqual(a, b stringSet) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func s3XMLError(status int, code string) *http.Response {
+ return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": []string{"application/xml"}},
+ Body: io.NopCloser(strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?><Error><Code>` + code + `</Code><Message>` + secretText + `</Message><RequestId>r</RequestId></Error>`))}
+}
+
+// TestAWSFleetMissingKey uses minted fleet credentials, as a box would, for
+// a GET of a key that does not exist. The mock answers as S3 does: 404 when
+// the caller may ListBucket on the bucket, 403 when it may not. It reads the
+// installed inline policy for that, so it pins the unconditioned ListBucket
+// grant; it is not proof that live IAM enforces it.
+func TestAWSFleetMissingKey(t *testing.T) {
+ for k, v := range map[string]string{"AWS_PROFILE": "", "AWS_DEFAULT_PROFILE": "", "AWS_EC2_METADATA_DISABLED": "false"} {
+ t.Setenv(k, v)
+ }
+ s, user := preparedStorage(t)
+ cred := rotate(t, s, "")
+ bucket, _ := testNames(t, testFleet)
+ ctx := context.Background()
+ var gets int
+ transport := transportFunc(func(r *http.Request) (*http.Response, error) {
+ if r.URL.Host != bucket+".s3."+testRegion+".amazonaws.com" {
+ t.Errorf("request to %s", r.URL)
+ return nil, errors.New("blocked")
+ }
+ if !strings.Contains(r.Header.Get("Authorization"), "Credential="+cred.ID+"/") {
+ t.Errorf("not signed with the fleet key: %q", r.Header.Get("Authorization"))
+ }
+ gets++
+ s.iam.mu.Lock()
+ raw := s.iam.users[user].inline[fleetPolicyName]
+ s.iam.mu.Unlock()
+ doc, err := canonicalPolicy(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mayList := false
+ for _, st := range doc.Statement {
+ if st.Effect == "Allow" && st.Condition == nil && reflectEqual(st.Resource, stringSet{"arn:aws:s3:::" + bucket}) {
+ for _, a := range st.Action {
+ mayList = mayList || a == "s3:ListBucket"
+ }
+ }
+ }
+ if mayList {
+ return s3XMLError(404, "NoSuchKey"), nil
+ }
+ return s3XMLError(403, "AccessDenied"), nil
+ })
+ cfg, err := rootaws.LoadStaticConfig(ctx, cred.ID, string(cred.Secret), awsconfig.WithRegion(testRegion), awsconfig.WithHTTPClient(transport))
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := awss3.NewFromConfig(cfg)
+ _, err = c.GetObject(ctx, &awss3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String("instances/h1/lock.json")})
+ var missing *s3types.NoSuchKey
+ if !errors.As(err, &missing) {
+ t.Fatalf("missing key answered %v", err)
+ }
+ // The same request under a prefix-conditioned ListBucket is a 403.
+ s.iam.mu.Lock()
+ s.iam.users[user].inline[fleetPolicyName] = strings.Replace(s.iam.users[user].inline[fleetPolicyName],
+ `"Resource":["arn:aws:s3:::`+bucket+`"]},`, `"Resource":["arn:aws:s3:::`+bucket+`"],"Condition":{"StringLike":{"s3:prefix":["instances/*"]}}},`, 1)
+ s.iam.mu.Unlock()
+ _, err = c.GetObject(ctx, &awss3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String("instances/h1/lock.json")})
+ if errors.As(err, &missing) || gets != 2 {
+ t.Fatalf("conditioned ListBucket still answered 404 (%d gets)", gets)
+ }
+}
+
+func TestAWSFleetStorageConfig(t *testing.T) {
+ fi := newFakeIAM(t)
+ clients := map[string]s3API{}
+ for _, r := range testStorageConfig().Regions {
+ clients[r] = &fakeS3{w: newFakeS3World(t), region: r}
+ }
+ for name, mutate := range map[string]func(*StorageConfig){
+ "no deployment": func(c *StorageConfig) { c.Deployment = "" },
+ "bad account": func(c *StorageConfig) { c.AccountID = "1234" },
+ "bad IAM region": func(c *StorageConfig) { c.IAMRegion = "" },
+ "no regions": func(c *StorageConfig) { c.Regions = nil },
+ "empty prefix": func(c *StorageConfig) { c.BucketPrefix = "" },
+ "long prefix": func(c *StorageConfig) { c.BucketPrefix = strings.Repeat("a", 25) },
+ "dotted prefix": func(c *StorageConfig) { c.BucketPrefix = "carlos.fleet-" },
+ "reserved prefix": func(c *StorageConfig) { c.BucketPrefix = "xn--fleet" },
+ "root path": func(c *StorageConfig) { c.UserPath = "/" },
+ "unterminated path": func(c *StorageConfig) { c.UserPath = "/carlos-managed-fleet" },
+ "app-store path": func(c *StorageConfig) { c.UserPath = "/carlos-store/" },
+ "inside app-store path": func(c *StorageConfig) { c.UserPath = "/carlos-store/fleets/" },
+ "empty boundary": func(c *StorageConfig) { c.BoundaryARN = "" },
+ "foreign boundary": func(c *StorageConfig) { c.BoundaryARN = "arn:aws:iam::" + foreignAcct + ":policy/b" },
+ "AWS-managed boundary": func(c *StorageConfig) { c.BoundaryARN = "arn:aws:iam::aws:policy/AdministratorAccess" },
+ "missing region client": func(c *StorageConfig) { c.Regions = append(c.Regions, "ap-south-1") },
+ } {
+ t.Run(name, func(t *testing.T) {
+ cfg := testStorageConfig()
+ mutate(&cfg)
+ if _, err := newStorage(cfg, clients, fi); err == nil {
+ t.Fatal("accepted")
+ }
+ })
+ }
+ if _, err := newStorage(testStorageConfig(), clients, nil); err == nil {
+ t.Fatal("accepted no IAM client")
+ }
+ if _, err := NewStorage(context.Background(), StorageConfig{Deployment: testDeployment, AccountID: testAccount}); err == nil {
+ t.Fatal("loaded an invalid configuration")
+ }
+}
+
+// TestAWSFleetTransport is the serialization witness: real SDK clients
+// loaded through rootaws, every byte through a mock transport, metadata off
+// in process. It checks the us-east-1 create carries Tags and no location,
+// ExpectedBucketOwner reaches the wire, and CreateAccessKey is sent once.
+func TestAWSFleetTransport(t *testing.T) {
+ none := filepath.Join(t.TempDir(), "none")
+ for k, v := range map[string]string{"AWS_EC2_METADATA_DISABLED": "false", "AWS_PROFILE": "", "AWS_DEFAULT_PROFILE": "", "AWS_ACCESS_KEY_ID": "", "AWS_SECRET_ACCESS_KEY": "",
+ "AWS_SESSION_TOKEN": "", "AWS_CONFIG_FILE": none, "AWS_SHARED_CREDENTIALS_FILE": none, "AWS_REGION": otherRegion, "AWS_DEFAULT_REGION": otherRegion} {
+ t.Setenv(k, v)
+ }
+ bucket, user := testNames(t, testFleet)
+ policy, err := fleetDataPolicy("arn:aws:s3:::" + bucket)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var mu sync.Mutex
+ counts := map[string]int{}
+ var createBody string
+ ok := func(body string) *http.Response {
+ return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/xml"}}, Body: io.NopCloser(strings.NewReader(body))}
+ }
+ iamOK := func(action, result string) *http.Response {
+ return ok(`<` + action + `Response xmlns="https://iam.amazonaws.com/doc/2010-05-08/"><` + action + `Result>` + result + `</` + action + `Result><ResponseMetadata><RequestId>r</RequestId></ResponseMetadata></` + action + `Response>`)
+ }
+ userXML := `<User><UserName>` + user + `</UserName><Path>` + testUserPath + `</Path><Arn>arn:aws:iam::` + testAccount + `:user` + testUserPath + user + `</Arn>` +
+ `<UserId>AIDAEXAMPLE</UserId><CreateDate>2026-11-08T12:00:00Z</CreateDate><PermissionsBoundary><PermissionsBoundaryType>PermissionsBoundaryPolicy</PermissionsBoundaryType>` +
+ `<PermissionsBoundaryArn>` + testBoundary + `</PermissionsBoundaryArn></PermissionsBoundary></User>`
+ transport := transportFunc(func(r *http.Request) (*http.Response, error) {
+ var body []byte
+ if r.Body != nil {
+ body, _ = io.ReadAll(r.Body)
+ }
+ if !strings.HasPrefix(r.Header.Get("Authorization"), "AWS4-HMAC-SHA256 Credential=AKIDTEST/") {
+ t.Errorf("signed with %q", r.Header.Get("Authorization"))
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ switch {
+ case r.URL.Host == bucket+".s3.us-east-1.amazonaws.com":
+ q := r.URL.Query()
+ op := r.Method + " " + r.URL.RawQuery
+ if r.Method != http.MethodPut || r.URL.RawQuery != "" {
+ if r.Header.Get("X-Amz-Expected-Bucket-Owner") != testAccount {
+ t.Errorf("%s without the expected owner", op)
+ }
+ }
+ counts[op]++
+ switch {
+ case r.Method == http.MethodPut && r.URL.RawQuery == "":
+ createBody = string(body)
+ return ok(""), nil
+ case q.Has("location"):
+ return ok(`<LocationConstraint xmlns="http://s3.amazonaws.com/doc/2006-03-01/"></LocationConstraint>`), nil
+ case q.Has("tagging"):
+ return ok(`<Tagging><TagSet><Tag><Key>carlos:deployment</Key><Value>` + testDeployment + `</Value></Tag><Tag><Key>carlos:fleet</Key><Value>` + testFleet + `</Value></Tag></TagSet></Tagging>`), nil
+ case q.Has("versioning"):
+ return ok(`<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>`), nil
+ case q.Has("encryption"):
+ return ok(`<ServerSideEncryptionConfiguration><Rule><ApplyServerSideEncryptionByDefault><SSEAlgorithm>AES256</SSEAlgorithm></ApplyServerSideEncryptionByDefault></Rule></ServerSideEncryptionConfiguration>`), nil
+ case q.Has("publicAccessBlock"):
+ return ok(`<PublicAccessBlockConfiguration><BlockPublicAcls>true</BlockPublicAcls><IgnorePublicAcls>true</IgnorePublicAcls><BlockPublicPolicy>true</BlockPublicPolicy><RestrictPublicBuckets>true</RestrictPublicBuckets></PublicAccessBlockConfiguration>`), nil
+ case q.Has("lifecycle"):
+ return ok(`<LifecycleConfiguration><Rule><ID>` + lifecycleRuleID + `</ID><Filter></Filter><Status>Enabled</Status><NoncurrentVersionExpiration><NoncurrentDays>7</NoncurrentDays></NoncurrentVersionExpiration>` +
+ `<AbortIncompleteMultipartUpload><DaysAfterInitiation>7</DaysAfterInitiation></AbortIncompleteMultipartUpload></Rule></LifecycleConfiguration>`), nil
+ }
+ case r.URL.Host == "iam.amazonaws.com":
+ form, err := url.ParseQuery(string(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ action := form.Get("Action")
+ counts[action]++
+ switch action {
+ case "CreateUser":
+ return iamOK(action, userXML), nil
+ case "GetUser":
+ return iamOK(action, userXML), nil
+ case "ListAttachedUserPolicies":
+ return iamOK(action, `<AttachedPolicies/><IsTruncated>false</IsTruncated>`), nil
+ case "ListGroupsForUser":
+ return iamOK(action, `<Groups/><IsTruncated>false</IsTruncated>`), nil
+ case "ListUserPolicies":
+ return iamOK(action, `<PolicyNames><member>`+fleetPolicyName+`</member></PolicyNames><IsTruncated>false</IsTruncated>`), nil
+ case "GetUserPolicy":
+ return iamOK(action, `<UserName>`+user+`</UserName><PolicyName>`+fleetPolicyName+`</PolicyName><PolicyDocument>`+url.PathEscape(policy)+`</PolicyDocument>`), nil
+ case "ListAccessKeys":
+ return iamOK(action, `<AccessKeyMetadata/><IsTruncated>false</IsTruncated>`), nil
+ case "CreateAccessKey":
+ return &http.Response{StatusCode: 503, Header: http.Header{"Content-Type": []string{"text/xml"}}, Body: io.NopCloser(strings.NewReader(
+ `<ErrorResponse><Error><Type>Receiver</Type><Code>ServiceFailure</Code><Message>` + secretText + `</Message></Error><RequestId>r</RequestId></ErrorResponse>`))}, nil
+ }
+ }
+ t.Errorf("unexpected %s %s", r.Method, r.URL)
+ return nil, errors.New("blocked")
+ })
+ cfg := testStorageConfig()
+ cfg.Regions = []string{"us-east-1"}
+ s, err := NewStorageWith(context.Background(), cfg, transport)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.EnsureFleetStorage(context.Background(), testFleet, "us-east-1")
+ if err != nil || got.Bucket != bucket {
+ t.Fatalf("%+v %v", got, err)
+ }
+ if strings.Contains(createBody, "LocationConstraint") || !strings.Contains(createBody, "<Key>carlos:deployment</Key><Value>"+testDeployment+"</Value>") ||
+ !strings.Contains(createBody, "<Key>carlos:fleet</Key><Value>"+testFleet+"</Value>") {
+ t.Errorf("us-east-1 create body %s", createBody)
+ }
+ _, err = s.RotateFleetCredentials(context.Background(), testFleet, "", nil)
+ ambiguous(t, err)
+ if counts["CreateAccessKey"] != 1 {
+ t.Fatalf("CreateAccessKey sent %d times", counts["CreateAccessKey"])
+ }
+ for op, n := range counts {
+ if strings.HasPrefix(op, "PUT ") && op != "PUT " {
+ t.Errorf("rewrote a setting already in place: %s x%d", op, n)
+ }
+ }
+}
diff --git a/internal/awsmanaged/storage.go b/internal/awsmanaged/storage.go
new file mode 100644
index 000000000..8cf4cc756
--- /dev/null
+++ b/internal/awsmanaged/storage.go
@@ -0,0 +1,450 @@
+package awsmanaged
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/carlosframework/platform/internal/fleetstore"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// errDrift marks an existing AWS resource that is not provably this
+// deployment's for this fleet: a foreign or untagged bucket, another region,
+// an IAM user with the wrong path, boundary or extra authority. It is always
+// returned before any write to that resource.
+var errDrift = errors.New("existing resource does not match this fleet")
+
+func drift(what string) error { return fmt.Errorf("awsmanaged: %s: %w", what, errDrift) }
+
+const (
+ // fleetUserPrefix names every fleet IAM user; the suffix is the hash.
+ fleetUserPrefix = "managed-fleet-"
+ // appStoreUserPath is the object-storage default user path
+ // (infra/modules/region-host store_user_path). Fleet users never share it.
+ appStoreUserPath = "/carlos-store/"
+ // lifecycleRuleID is the one lifecycle rule a fleet bucket carries.
+ lifecycleRuleID = "carlos-fleet-retention"
+ retentionDays = 7
+ maxListPages = 100
+ suffixLen = 24
+)
+
+var (
+ // A fleet bucket name is at most 48 characters, so the fleet-data policy
+ // (which names the bucket 13 times) stays inside IAM's inline limit.
+ bucketPrefixRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,23}$`)
+ userPathRE = regexp.MustCompile(`^/(?:[A-Za-z0-9+=,.@_-]+/)+$`)
+ boundaryRE = regexp.MustCompile(`^arn:aws:iam::([0-9]{12}):policy/(?:[A-Za-z0-9+=,.@_-]+/)*[A-Za-z0-9+=,.@_-]{1,128}$`)
+)
+
+// StorageConfig names the deployment whose fleet buckets and users this
+// adapter owns, the account they live in, the bucket-name prefix and IAM
+// user path reserved for them, the permissions boundary every fleet user is
+// made under, and the regions buckets may be created in.
+type StorageConfig struct {
+ Deployment, AccountID, IAMRegion, BucketPrefix, UserPath, BoundaryARN string
+ Regions []string
+}
+
+// Storage is fleetstore.Provisioner on S3 and IAM. A fleet's bucket and
+// user are named from the deployment and fleet alone, so a retry or a
+// restarted console finds the same ones, and every existing resource is
+// verified as this deployment's before anything is written to it.
+//
+// Its per-fleet lock serializes one process's calls. Two consoles serving
+// one deployment from different databases are unsupported; this is not a
+// distributed lock.
+type Storage struct {
+ cfg StorageConfig
+ buckets map[string]s3API
+ users iamAPI
+
+ mu sync.Mutex
+ locks map[string]chan struct{}
+}
+
+var _ fleetstore.Provisioner = (*Storage)(nil)
+
+// NewStorage loads one S3 client per configured region and one IAM client
+// through rootaws.
+func NewStorage(ctx context.Context, cfg StorageConfig) (*Storage, error) {
+ return loadStorage(ctx, cfg)
+}
+
+func loadStorage(ctx context.Context, cfg StorageConfig, opts ...func(*awsconfig.LoadOptions) error) (*Storage, error) {
+ if err := validateStorageConfig(cfg); err != nil {
+ return nil, err
+ }
+ buckets := make(map[string]s3API, len(cfg.Regions))
+ for _, region := range cfg.Regions {
+ api, err := loadS3(ctx, region, opts...)
+ if err != nil {
+ return nil, err
+ }
+ buckets[region] = api
+ }
+ users, err := loadIAM(ctx, cfg.IAMRegion, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return newStorage(cfg, buckets, users)
+}
+
+// newStorage copies cfg and keeps exactly one S3 client per configured
+// region and the IAM client.
+func newStorage(cfg StorageConfig, buckets map[string]s3API, users iamAPI) (*Storage, error) {
+ if err := validateStorageConfig(cfg); err != nil {
+ return nil, err
+ }
+ if users == nil {
+ return nil, errors.New("awsmanaged: no IAM client")
+ }
+ cfg.Regions = slices.Clone(cfg.Regions)
+ s := &Storage{cfg: cfg, buckets: make(map[string]s3API, len(cfg.Regions)), users: users, locks: map[string]chan struct{}{}}
+ for _, region := range cfg.Regions {
+ api := buckets[region]
+ if api == nil {
+ return nil, fmt.Errorf("awsmanaged: no S3 client for region %s", region)
+ }
+ s.buckets[region] = api
+ }
+ return s, nil
+}
+
+func validateStorageConfig(cfg StorageConfig) error {
+ if err := validateConfig(ComputeConfig{Deployment: cfg.Deployment, AccountID: cfg.AccountID, Regions: cfg.Regions}); err != nil {
+ return err
+ }
+ if !regionRE.MatchString(cfg.IAMRegion) {
+ return errors.New("awsmanaged: IAM region is not an AWS region name")
+ }
+ p := cfg.BucketPrefix
+ if !bucketPrefixRE.MatchString(p) || strings.HasPrefix(p, "xn--") || strings.HasPrefix(p, "sthree-") || strings.HasPrefix(p, "amzn-s3-demo-") {
+ return errors.New("awsmanaged: fleet bucket prefix must be up to 24 lowercase letters, digits or hyphens")
+ }
+ if len(cfg.UserPath) > 512 || !userPathRE.MatchString(cfg.UserPath) {
+ return errors.New("awsmanaged: fleet user path must be an IAM path below the root, such as /carlos-managed-fleet/")
+ }
+ if strings.HasPrefix(cfg.UserPath, appStoreUserPath) || strings.HasPrefix(appStoreUserPath, cfg.UserPath) {
+ return errors.New("awsmanaged: fleet user path overlaps the object storage user path")
+ }
+ m := boundaryRE.FindStringSubmatch(cfg.BoundaryARN)
+ if m == nil || m[1] != cfg.AccountID {
+ return errors.New("awsmanaged: permissions boundary must be a policy ARN in this account")
+ }
+ return nil
+}
+
+// fleetResourceNames derives a fleet's bucket and IAM user name from the
+// first 24 hex characters of SHA-256(deployment + "/" + fleet).
+func fleetResourceNames(cfg StorageConfig, fleet string) (bucket, user string, err error) {
+ if !registry.ValidTunnelName(fleet) || !tagValueRE.MatchString(fleet) {
+ return "", "", errors.New("awsmanaged: fleet name is invalid")
+ }
+ if !tagValueRE.MatchString(cfg.Deployment) || !bucketPrefixRE.MatchString(cfg.BucketPrefix) {
+ return "", "", errors.New("awsmanaged: storage configuration is invalid")
+ }
+ sum := sha256.Sum256([]byte(cfg.Deployment + "/" + fleet))
+ suffix := hex.EncodeToString(sum[:])[:suffixLen]
+ return cfg.BucketPrefix + suffix, fleetUserPrefix + suffix, nil
+}
+
+// lockFleet serializes this process's calls for one fleet.
+func (s *Storage) lockFleet(ctx context.Context, fleet string) (func(), error) {
+ s.mu.Lock()
+ l := s.locks[fleet]
+ if l == nil {
+ l = make(chan struct{}, 1)
+ s.locks[fleet] = l
+ }
+ s.mu.Unlock()
+ select {
+ case l <- struct{}{}:
+ return func() { <-l }, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+}
+
+func bucketTags(deployment, fleet string) []s3types.Tag {
+ return []s3types.Tag{
+ {Key: aws.String(tagDeployment), Value: aws.String(deployment)},
+ {Key: aws.String(tagFleet), Value: aws.String(fleet)},
+ }
+}
+
+// EnsureFleetStorage makes or verifies the fleet's bucket in region and its
+// bounded IAM user with the fleet-data policy. It succeeds only when every
+// bucket setting and the user's policy have been read back as wanted; a
+// bucket alone is not prepared storage. It never mints a key.
+func (s *Storage) EnsureFleetStorage(ctx context.Context, fleet, region string) (fleetstore.FleetStorage, error) {
+ bucket, _, err := fleetResourceNames(s.cfg, fleet)
+ if err != nil {
+ return fleetstore.FleetStorage{}, err
+ }
+ api := s.buckets[region]
+ if api == nil {
+ return fleetstore.FleetStorage{}, errors.New("awsmanaged: region is not configured")
+ }
+ unlock, err := s.lockFleet(ctx, fleet)
+ if err != nil {
+ return fleetstore.FleetStorage{}, err
+ }
+ defer unlock()
+ if err := s.ensureBucket(ctx, api, bucket, fleet, region); err != nil {
+ return fleetstore.FleetStorage{}, err
+ }
+ if err := s.ensureFleetUser(ctx, fleet); err != nil {
+ return fleetstore.FleetStorage{}, err
+ }
+ return fleetstore.FleetStorage{Bucket: bucket, Region: region}, nil
+}
+
+// ensureBucket creates the bucket with its identity tags in the one
+// request, then proves it is this account's, in region, carrying exactly
+// this deployment's and fleet's tags before it configures anything. A lost
+// creation reply is recovered through those tags; an untagged or foreign
+// bucket is never relabelled or adopted.
+func (s *Storage) ensureBucket(ctx context.Context, api s3API, bucket, fleet, region string) error {
+ conf := &s3types.CreateBucketConfiguration{Tags: bucketTags(s.cfg.Deployment, fleet)}
+ if region != "us-east-1" {
+ conf.LocationConstraint = s3types.BucketLocationConstraint(region)
+ }
+ if _, err := api.CreateBucket(ctx, &awss3.CreateBucketInput{Bucket: aws.String(bucket), CreateBucketConfiguration: conf}); err != nil {
+ switch apiCode(err) {
+ case "BucketAlreadyOwnedByYou":
+ // Ours by name only: the checks below decide.
+ case "BucketAlreadyExists":
+ return drift("bucket name belongs to another account")
+ case "AccessDenied":
+ return drift("bucket creation was refused")
+ default:
+ return uncertain(ctx, "create bucket")
+ }
+ }
+ if err := s.checkBucketIdentity(ctx, api, bucket, fleet, region); err != nil {
+ return err
+ }
+ for _, step := range []func(context.Context, s3API, string) error{s.ensureVersioning, s.ensureEncryption, s.ensurePublicBlock, s.ensureLifecycle} {
+ if err := step(ctx, api, bucket); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (s *Storage) owner() *string { return aws.String(s.cfg.AccountID) }
+
+func (s *Storage) checkBucketIdentity(ctx context.Context, api s3API, bucket, fleet, region string) error {
+ loc, err := api.GetBucketLocation(ctx, &awss3.GetBucketLocationInput{Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner()})
+ if err != nil {
+ if apiCode(err) == "AccessDenied" {
+ return drift("bucket is not this account's")
+ }
+ return uncertain(ctx, "bucket location")
+ }
+ if loc == nil {
+ return uncertain(ctx, "bucket location answer")
+ }
+ got := string(loc.LocationConstraint)
+ switch got {
+ case "":
+ got = "us-east-1"
+ case "EU":
+ got = "eu-west-1"
+ }
+ if got != region {
+ return drift("bucket is in another region")
+ }
+ tags, err := api.GetBucketTagging(ctx, &awss3.GetBucketTaggingInput{Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner()})
+ if err != nil {
+ switch apiCode(err) {
+ case "NoSuchTagSet":
+ return drift("bucket carries no deployment tags")
+ case "AccessDenied":
+ return drift("bucket is not this account's")
+ }
+ return uncertain(ctx, "bucket tags")
+ }
+ if tags == nil {
+ return uncertain(ctx, "bucket tags answer")
+ }
+ want := map[string]string{tagDeployment: s.cfg.Deployment, tagFleet: fleet}
+ seen := map[string]bool{}
+ for _, t := range tags.TagSet {
+ k := aws.ToString(t.Key)
+ if seen[k] || want[k] == "" || aws.ToString(t.Value) != want[k] {
+ return drift("bucket tags are not this fleet's")
+ }
+ seen[k] = true
+ }
+ if len(seen) != len(want) {
+ return drift("bucket tags are not this fleet's")
+ }
+ return nil
+}
+
+func (s *Storage) ensureVersioning(ctx context.Context, api s3API, bucket string) error {
+ read := func() (bool, error) {
+ out, err := api.GetBucketVersioning(ctx, &awss3.GetBucketVersioningInput{Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner()})
+ if err != nil || out == nil {
+ return false, uncertain(ctx, "bucket versioning")
+ }
+ if out.MFADelete != "" && out.MFADelete != s3types.MFADeleteStatusDisabled {
+ return false, drift("bucket versioning uses MFA delete")
+ }
+ switch out.Status {
+ case s3types.BucketVersioningStatusEnabled:
+ return true, nil
+ case "", s3types.BucketVersioningStatusSuspended:
+ return false, nil
+ }
+ return false, uncertain(ctx, "bucket versioning answer")
+ }
+ ok, err := read()
+ if err != nil || ok {
+ return err
+ }
+ if _, err := api.PutBucketVersioning(ctx, &awss3.PutBucketVersioningInput{
+ Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner(),
+ VersioningConfiguration: &s3types.VersioningConfiguration{Status: s3types.BucketVersioningStatusEnabled},
+ }); err != nil {
+ return uncertain(ctx, "set bucket versioning")
+ }
+ return readBack(ctx, "bucket versioning", read)
+}
+
+func (s *Storage) ensureEncryption(ctx context.Context, api s3API, bucket string) error {
+ read := func() (bool, error) {
+ out, err := api.GetBucketEncryption(ctx, &awss3.GetBucketEncryptionInput{Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner()})
+ if apiCode(err) == "ServerSideEncryptionConfigurationNotFoundError" {
+ return false, nil
+ }
+ if err != nil || out == nil {
+ return false, uncertain(ctx, "bucket encryption")
+ }
+ c := out.ServerSideEncryptionConfiguration
+ if c == nil || len(c.Rules) != 1 {
+ return false, nil
+ }
+ d := c.Rules[0].ApplyServerSideEncryptionByDefault
+ return d != nil && d.SSEAlgorithm == s3types.ServerSideEncryptionAes256 && aws.ToString(d.KMSMasterKeyID) == "", nil
+ }
+ ok, err := read()
+ if err != nil || ok {
+ return err
+ }
+ if _, err := api.PutBucketEncryption(ctx, &awss3.PutBucketEncryptionInput{
+ Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner(),
+ ServerSideEncryptionConfiguration: &s3types.ServerSideEncryptionConfiguration{Rules: []s3types.ServerSideEncryptionRule{{
+ ApplyServerSideEncryptionByDefault: &s3types.ServerSideEncryptionByDefault{SSEAlgorithm: s3types.ServerSideEncryptionAes256},
+ }}},
+ }); err != nil {
+ return uncertain(ctx, "set bucket encryption")
+ }
+ return readBack(ctx, "bucket encryption", read)
+}
+
+func (s *Storage) ensurePublicBlock(ctx context.Context, api s3API, bucket string) error {
+ read := func() (bool, error) {
+ out, err := api.GetPublicAccessBlock(ctx, &awss3.GetPublicAccessBlockInput{Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner()})
+ if apiCode(err) == "NoSuchPublicAccessBlockConfiguration" {
+ return false, nil
+ }
+ if err != nil || out == nil {
+ return false, uncertain(ctx, "bucket public access block")
+ }
+ c := out.PublicAccessBlockConfiguration
+ return c != nil && aws.ToBool(c.BlockPublicAcls) && aws.ToBool(c.IgnorePublicAcls) && aws.ToBool(c.BlockPublicPolicy) && aws.ToBool(c.RestrictPublicBuckets), nil
+ }
+ ok, err := read()
+ if err != nil || ok {
+ return err
+ }
+ if _, err := api.PutPublicAccessBlock(ctx, &awss3.PutPublicAccessBlockInput{
+ Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner(),
+ PublicAccessBlockConfiguration: &s3types.PublicAccessBlockConfiguration{
+ BlockPublicAcls: aws.Bool(true), IgnorePublicAcls: aws.Bool(true), BlockPublicPolicy: aws.Bool(true), RestrictPublicBuckets: aws.Bool(true),
+ },
+ }); err != nil {
+ return uncertain(ctx, "set bucket public access block")
+ }
+ return readBack(ctx, "bucket public access block", read)
+}
+
+// fleetLifecycleRule keeps noncurrent versions seven days (the restore
+// window) and aborts multipart uploads left seven days. Current objects
+// never expire.
+func fleetLifecycleRule() s3types.LifecycleRule {
+ return s3types.LifecycleRule{
+ ID: aws.String(lifecycleRuleID), Status: s3types.ExpirationStatusEnabled,
+ Filter: &s3types.LifecycleRuleFilter{Prefix: aws.String("")},
+ NoncurrentVersionExpiration: &s3types.NoncurrentVersionExpiration{NoncurrentDays: aws.Int32(retentionDays)},
+ AbortIncompleteMultipartUpload: &s3types.AbortIncompleteMultipartUpload{DaysAfterInitiation: aws.Int32(retentionDays)},
+ }
+}
+
+// isFleetLifecycleRule reports whether r is exactly fleetLifecycleRule as
+// S3 reads it back (an empty filter may come back with or without Prefix).
+func isFleetLifecycleRule(r s3types.LifecycleRule) bool {
+ f := r.Filter
+ return aws.ToString(r.ID) == lifecycleRuleID && r.Status == s3types.ExpirationStatusEnabled && r.Prefix == nil &&
+ f != nil && f.And == nil && f.Tag == nil && f.ObjectSizeGreaterThan == nil && f.ObjectSizeLessThan == nil && aws.ToString(f.Prefix) == "" &&
+ r.Expiration == nil && len(r.Transitions) == 0 && len(r.NoncurrentVersionTransitions) == 0 &&
+ r.NoncurrentVersionExpiration != nil && aws.ToInt32(r.NoncurrentVersionExpiration.NoncurrentDays) == retentionDays &&
+ r.NoncurrentVersionExpiration.NewerNoncurrentVersions == nil &&
+ r.AbortIncompleteMultipartUpload != nil && aws.ToInt32(r.AbortIncompleteMultipartUpload.DaysAfterInitiation) == retentionDays
+}
+
+// ensureLifecycle installs the rule on a bucket with none. Any other rule
+// set is refused rather than replaced: a put overwrites every rule.
+func (s *Storage) ensureLifecycle(ctx context.Context, api s3API, bucket string) error {
+ read := func() (bool, error) {
+ out, err := api.GetBucketLifecycleConfiguration(ctx, &awss3.GetBucketLifecycleConfigurationInput{Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner()})
+ if apiCode(err) == "NoSuchLifecycleConfiguration" {
+ return false, nil
+ }
+ if err != nil || out == nil {
+ return false, uncertain(ctx, "bucket lifecycle")
+ }
+ if len(out.Rules) == 1 && isFleetLifecycleRule(out.Rules[0]) {
+ return true, nil
+ }
+ return false, drift("bucket has lifecycle rules this deployment did not write")
+ }
+ ok, err := read()
+ if err != nil || ok {
+ return err
+ }
+ if _, err := api.PutBucketLifecycleConfiguration(ctx, &awss3.PutBucketLifecycleConfigurationInput{
+ Bucket: aws.String(bucket), ExpectedBucketOwner: s.owner(),
+ LifecycleConfiguration: &s3types.BucketLifecycleConfiguration{Rules: []s3types.LifecycleRule{fleetLifecycleRule()}},
+ }); err != nil {
+ return uncertain(ctx, "set bucket lifecycle")
+ }
+ return readBack(ctx, "bucket lifecycle", read)
+}
+
+// readBack requires a setting just written to read back as wanted. Not yet
+// visible is uncertainty, retried by the next pass.
+func readBack(ctx context.Context, what string, read func() (bool, error)) error {
+ ok, err := read()
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return uncertain(ctx, what+" readback")
+ }
+ return nil
+}
diff --git a/internal/awsmanaged/storage_test.go b/internal/awsmanaged/storage_test.go
new file mode 100644
index 000000000..88eb5ec05
--- /dev/null
+++ b/internal/awsmanaged/storage_test.go
@@ -0,0 +1,672 @@
+package awsmanaged
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/carlosframework/platform/internal/fleetstore"
+)
+
+const (
+ testIAMRegion = "us-east-1"
+ testPrefix = "carlos-fleet-"
+ testUserPath = "/carlos-managed-fleet/"
+ testBoundary = "arn:aws:iam::" + testAccount + ":policy/carlos-managed-fleet-boundary"
+ foreignAcct = "999999999999"
+ testFleet = "shop"
+)
+
+func testStorageConfig() StorageConfig {
+ return StorageConfig{
+ Deployment: testDeployment, AccountID: testAccount, IAMRegion: testIAMRegion, BucketPrefix: testPrefix,
+ UserPath: testUserPath, BoundaryARN: testBoundary, Regions: []string{testRegion, otherRegion, "us-east-1"},
+ }
+}
+
+// fakeBucket is one bucket's whole state. A nil field is "not configured".
+type fakeBucket struct {
+ region, owner string
+ tags []s3types.Tag
+ versioning s3types.BucketVersioningStatus
+ mfa s3types.MFADeleteStatus
+ enc *s3types.ServerSideEncryptionConfiguration
+ pab *s3types.PublicAccessBlockConfiguration
+ rules []s3types.LifecycleRule
+}
+
+// fakeS3World is S3's global bucket namespace; fakeS3 is one region's
+// client onto it. before fails a call with no effect; after applies the
+// call and then loses its answer.
+type fakeS3World struct {
+ t *testing.T
+ mu sync.Mutex
+ buckets map[string]*fakeBucket
+ counts map[string]int
+ before func(op string, n int) error
+ after func(op string, n int) error
+ dropPuts map[string]bool // a put answers success and changes nothing
+ legacyEU bool
+ creates []*awss3.CreateBucketInput
+ regions []string // region of each CreateBucket call
+}
+
+type fakeS3 struct {
+ w *fakeS3World
+ region string
+}
+
+func newFakeS3World(t *testing.T) *fakeS3World {
+ return &fakeS3World{t: t, buckets: map[string]*fakeBucket{}, counts: map[string]int{}, dropPuts: map[string]bool{}}
+}
+
+func (w *fakeS3World) count(op string) int {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.counts[op]
+}
+
+func (w *fakeS3World) puts() int {
+ n := 0
+ for _, op := range []string{"PutBucketVersioning", "PutBucketEncryption", "PutPublicAccessBlock", "PutBucketLifecycleConfiguration"} {
+ n += w.count(op)
+ }
+ return n
+}
+
+func (w *fakeS3World) bucket(name string) *fakeBucket {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.buckets[name]
+}
+
+// call runs one operation under the world lock: before, effect, after.
+func (w *fakeS3World) call(op string, effect func() error) error {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ w.counts[op]++
+ n := w.counts[op]
+ if w.before != nil {
+ if err := w.before(op, n); err != nil {
+ return err
+ }
+ }
+ if err := effect(); err != nil {
+ return err
+ }
+ if w.after != nil {
+ return w.after(op, n)
+ }
+ return nil
+}
+
+// owned finds bucket and checks ExpectedBucketOwner, which every call but
+// CreateBucket must carry.
+func (w *fakeS3World) owned(name, owner *string) (*fakeBucket, error) {
+ if owner == nil {
+ w.t.Errorf("call on %s without ExpectedBucketOwner", aws.ToString(name))
+ return nil, apiErr("AccessDenied")
+ }
+ b := w.buckets[aws.ToString(name)]
+ if b == nil {
+ return nil, apiErr("NoSuchBucket")
+ }
+ if b.owner != aws.ToString(owner) {
+ return nil, apiErr("AccessDenied")
+ }
+ return b, nil
+}
+
+func (f *fakeS3) CreateBucket(ctx context.Context, in *awss3.CreateBucketInput, _ ...func(*awss3.Options)) (*awss3.CreateBucketOutput, error) {
+ w := f.w
+ err := w.call("CreateBucket", func() error {
+ w.creates = append(w.creates, in)
+ w.regions = append(w.regions, f.region)
+ var lc string
+ var tags []s3types.Tag
+ if c := in.CreateBucketConfiguration; c != nil {
+ lc, tags = string(c.LocationConstraint), c.Tags
+ }
+ switch {
+ case f.region == "us-east-1" && lc != "":
+ return apiErr("InvalidLocationConstraint")
+ case f.region != "us-east-1" && lc != f.region:
+ return apiErr("IllegalLocationConstraintException")
+ }
+ name := aws.ToString(in.Bucket)
+ if b := w.buckets[name]; b != nil {
+ if b.owner != testAccount {
+ return apiErr("BucketAlreadyExists")
+ }
+ if b.region == "us-east-1" && f.region == "us-east-1" {
+ return nil
+ }
+ return apiErr("BucketAlreadyOwnedByYou")
+ }
+ w.buckets[name] = &fakeBucket{region: f.region, owner: testAccount, tags: append([]s3types.Tag(nil), tags...)}
+ if len(tags) == 0 {
+ w.buckets[name].tags = nil
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &awss3.CreateBucketOutput{}, nil
+}
+
+func (f *fakeS3) GetBucketLocation(ctx context.Context, in *awss3.GetBucketLocationInput, _ ...func(*awss3.Options)) (*awss3.GetBucketLocationOutput, error) {
+ out := &awss3.GetBucketLocationOutput{}
+ return out, f.w.call("GetBucketLocation", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ switch {
+ case b.region == "us-east-1":
+ case b.region == "eu-west-1" && f.w.legacyEU:
+ out.LocationConstraint = "EU"
+ default:
+ out.LocationConstraint = s3types.BucketLocationConstraint(b.region)
+ }
+ return nil
+ })
+}
+
+func (f *fakeS3) GetBucketTagging(ctx context.Context, in *awss3.GetBucketTaggingInput, _ ...func(*awss3.Options)) (*awss3.GetBucketTaggingOutput, error) {
+ out := &awss3.GetBucketTaggingOutput{}
+ return out, f.w.call("GetBucketTagging", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if b.tags == nil {
+ return apiErr("NoSuchTagSet")
+ }
+ out.TagSet = append(out.TagSet, b.tags...)
+ return nil
+ })
+}
+
+func (f *fakeS3) GetBucketVersioning(ctx context.Context, in *awss3.GetBucketVersioningInput, _ ...func(*awss3.Options)) (*awss3.GetBucketVersioningOutput, error) {
+ out := &awss3.GetBucketVersioningOutput{}
+ return out, f.w.call("GetBucketVersioning", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ out.Status, out.MFADelete = b.versioning, s3types.MFADeleteStatus(b.mfa)
+ return nil
+ })
+}
+
+func (f *fakeS3) PutBucketVersioning(ctx context.Context, in *awss3.PutBucketVersioningInput, _ ...func(*awss3.Options)) (*awss3.PutBucketVersioningOutput, error) {
+ return &awss3.PutBucketVersioningOutput{}, f.w.call("PutBucketVersioning", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if !f.w.dropPuts["PutBucketVersioning"] {
+ b.versioning = in.VersioningConfiguration.Status
+ }
+ return nil
+ })
+}
+
+func (f *fakeS3) GetBucketEncryption(ctx context.Context, in *awss3.GetBucketEncryptionInput, _ ...func(*awss3.Options)) (*awss3.GetBucketEncryptionOutput, error) {
+ out := &awss3.GetBucketEncryptionOutput{}
+ return out, f.w.call("GetBucketEncryption", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if b.enc == nil {
+ return apiErr("ServerSideEncryptionConfigurationNotFoundError")
+ }
+ out.ServerSideEncryptionConfiguration = b.enc
+ return nil
+ })
+}
+
+func (f *fakeS3) PutBucketEncryption(ctx context.Context, in *awss3.PutBucketEncryptionInput, _ ...func(*awss3.Options)) (*awss3.PutBucketEncryptionOutput, error) {
+ return &awss3.PutBucketEncryptionOutput{}, f.w.call("PutBucketEncryption", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if !f.w.dropPuts["PutBucketEncryption"] {
+ b.enc = in.ServerSideEncryptionConfiguration
+ }
+ return nil
+ })
+}
+
+func (f *fakeS3) GetPublicAccessBlock(ctx context.Context, in *awss3.GetPublicAccessBlockInput, _ ...func(*awss3.Options)) (*awss3.GetPublicAccessBlockOutput, error) {
+ out := &awss3.GetPublicAccessBlockOutput{}
+ return out, f.w.call("GetPublicAccessBlock", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if b.pab == nil {
+ return apiErr("NoSuchPublicAccessBlockConfiguration")
+ }
+ out.PublicAccessBlockConfiguration = b.pab
+ return nil
+ })
+}
+
+func (f *fakeS3) PutPublicAccessBlock(ctx context.Context, in *awss3.PutPublicAccessBlockInput, _ ...func(*awss3.Options)) (*awss3.PutPublicAccessBlockOutput, error) {
+ return &awss3.PutPublicAccessBlockOutput{}, f.w.call("PutPublicAccessBlock", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if !f.w.dropPuts["PutPublicAccessBlock"] {
+ b.pab = in.PublicAccessBlockConfiguration
+ }
+ return nil
+ })
+}
+
+func (f *fakeS3) GetBucketLifecycleConfiguration(ctx context.Context, in *awss3.GetBucketLifecycleConfigurationInput, _ ...func(*awss3.Options)) (*awss3.GetBucketLifecycleConfigurationOutput, error) {
+ out := &awss3.GetBucketLifecycleConfigurationOutput{}
+ return out, f.w.call("GetBucketLifecycleConfiguration", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if b.rules == nil {
+ return apiErr("NoSuchLifecycleConfiguration")
+ }
+ out.Rules = append(out.Rules, b.rules...)
+ return nil
+ })
+}
+
+func (f *fakeS3) PutBucketLifecycleConfiguration(ctx context.Context, in *awss3.PutBucketLifecycleConfigurationInput, _ ...func(*awss3.Options)) (*awss3.PutBucketLifecycleConfigurationOutput, error) {
+ return &awss3.PutBucketLifecycleConfigurationOutput{}, f.w.call("PutBucketLifecycleConfiguration", func() error {
+ b, err := f.w.owned(in.Bucket, in.ExpectedBucketOwner)
+ if err != nil {
+ return err
+ }
+ if f.w.dropPuts["PutBucketLifecycleConfiguration"] {
+ return nil
+ }
+ // S3 reads an empty prefix filter back as a bare <Filter/>.
+ b.rules = nil
+ for _, r := range in.LifecycleConfiguration.Rules {
+ if r.Filter != nil && aws.ToString(r.Filter.Prefix) == "" {
+ f := *r.Filter
+ f.Prefix = nil
+ r.Filter = &f
+ }
+ b.rules = append(b.rules, r)
+ }
+ return nil
+ })
+}
+
+type testStorage struct {
+ *Storage
+ s3 *fakeS3World
+ iam *fakeIAM
+}
+
+func newTestStorage(t *testing.T) testStorage {
+ t.Helper()
+ w, fi := newFakeS3World(t), newFakeIAM(t)
+ cfg := testStorageConfig()
+ clients := map[string]s3API{}
+ for _, r := range cfg.Regions {
+ clients[r] = &fakeS3{w: w, region: r}
+ }
+ s, err := newStorage(cfg, clients, fi)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return testStorage{Storage: s, s3: w, iam: fi}
+}
+
+func testNames(t *testing.T, fleet string) (string, string) {
+ t.Helper()
+ b, u, err := fleetResourceNames(testStorageConfig(), fleet)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b, u
+}
+
+// ownTags is the tag set this deployment writes on fleet's bucket.
+func ownTags(fleet string) []s3types.Tag {
+ return []s3types.Tag{{Key: aws.String("carlos:deployment"), Value: aws.String(testDeployment)}, {Key: aws.String("carlos:fleet"), Value: aws.String(fleet)}}
+}
+
+// drifted is the refusal an unproven existing resource must get.
+func drifted(t *testing.T, err error) {
+ t.Helper()
+ if !errors.Is(err, errDrift) {
+ t.Fatalf("want a drift refusal, got %v", err)
+ }
+ noLeak(t, err.Error())
+}
+
+// wantPrepared checks every fixed bucket setting.
+func wantPrepared(t *testing.T, b *fakeBucket, region string) {
+ t.Helper()
+ if b == nil || b.region != region || b.owner != testAccount {
+ t.Fatalf("bucket %+v", b)
+ }
+ if b.versioning != s3types.BucketVersioningStatusEnabled {
+ t.Errorf("versioning %q", b.versioning)
+ }
+ if b.enc == nil || len(b.enc.Rules) != 1 || b.enc.Rules[0].ApplyServerSideEncryptionByDefault.SSEAlgorithm != s3types.ServerSideEncryptionAes256 ||
+ b.enc.Rules[0].ApplyServerSideEncryptionByDefault.KMSMasterKeyID != nil {
+ t.Errorf("encryption %+v", b.enc)
+ }
+ if p := b.pab; p == nil || !aws.ToBool(p.BlockPublicAcls) || !aws.ToBool(p.IgnorePublicAcls) || !aws.ToBool(p.BlockPublicPolicy) || !aws.ToBool(p.RestrictPublicBuckets) {
+ t.Errorf("public access block %+v", b.pab)
+ }
+ if len(b.rules) != 1 {
+ t.Fatalf("lifecycle %+v", b.rules)
+ }
+ r := b.rules[0]
+ if r.Status != s3types.ExpirationStatusEnabled || aws.ToInt32(r.NoncurrentVersionExpiration.NoncurrentDays) != 7 ||
+ aws.ToInt32(r.AbortIncompleteMultipartUpload.DaysAfterInitiation) != 7 || r.Expiration != nil || len(r.Transitions) != 0 {
+ t.Errorf("lifecycle rule %+v", r)
+ }
+}
+
+func TestAWSFleetBucketContract(t *testing.T) {
+ ctx := context.Background()
+ t.Run("names", func(t *testing.T) {
+ sum := sha256.Sum256([]byte(testDeployment + "/" + testFleet))
+ suffix := hex.EncodeToString(sum[:])[:24]
+ b, u := testNames(t, testFleet)
+ // The literal pins the hash rule itself: SHA-256 of "production/shop",
+ // first 24 hex characters.
+ if b != testPrefix+suffix || u != "managed-fleet-"+suffix || b != "carlos-fleet-393916115501bd63d8e58b67" {
+ t.Fatalf("%s %s", b, u)
+ }
+ other := testStorageConfig()
+ other.Deployment = "staging"
+ b2, _, _ := fleetResourceNames(other, testFleet)
+ b3, _ := testNames(t, "shop-2")
+ if b2 == b || b3 == b {
+ t.Fatal("names collide across deployments or fleets")
+ }
+ for _, bad := range []string{"", "Shop", "shop/x", "../shop", strings.Repeat("a", 64)} {
+ if _, _, err := fleetResourceNames(testStorageConfig(), bad); err == nil {
+ t.Errorf("accepted fleet %q", bad)
+ }
+ }
+ })
+ t.Run("create", func(t *testing.T) {
+ s := newTestStorage(t)
+ got, err := s.EnsureFleetStorage(ctx, testFleet, testRegion)
+ bucket, _ := testNames(t, testFleet)
+ if err != nil || got != (fleetstore.FleetStorage{Bucket: bucket, Region: testRegion}) {
+ t.Fatalf("%+v %v", got, err)
+ }
+ wantPrepared(t, s.s3.bucket(bucket), testRegion)
+ in := s.s3.creates[0]
+ c := in.CreateBucketConfiguration
+ if c == nil || c.LocationConstraint != testRegion || len(c.Tags) != 2 || aws.ToString(c.Tags[0].Key) != "carlos:deployment" ||
+ aws.ToString(c.Tags[0].Value) != testDeployment || aws.ToString(c.Tags[1].Key) != "carlos:fleet" || aws.ToString(c.Tags[1].Value) != testFleet {
+ t.Fatalf("create request %+v", c)
+ }
+ if in.ACL != "" || in.ObjectLockEnabledForBucket != nil || in.GrantFullControl != nil || in.GrantWrite != nil {
+ t.Fatal("create request grants access")
+ }
+ if s.iam.count("CreateAccessKey") != 0 {
+ t.Fatal("preparing storage minted a key")
+ }
+ // A retry converges with no writes.
+ puts, policyPuts := s.s3.puts(), s.iam.count("PutUserPolicy")
+ again, err := s.EnsureFleetStorage(ctx, testFleet, testRegion)
+ if err != nil || again != got || s.s3.puts() != puts || s.iam.count("PutUserPolicy") != policyPuts {
+ t.Fatalf("retry %+v %v, puts %d->%d", again, err, puts, s.s3.puts())
+ }
+ })
+ t.Run("us-east-1", func(t *testing.T) {
+ s := newTestStorage(t)
+ got, err := s.EnsureFleetStorage(ctx, testFleet, "us-east-1")
+ if err != nil || got.Region != "us-east-1" {
+ t.Fatalf("%+v %v", got, err)
+ }
+ c := s.s3.creates[0].CreateBucketConfiguration
+ if c == nil || c.LocationConstraint != "" || len(c.Tags) != 2 {
+ t.Fatalf("us-east-1 create request %+v", c)
+ }
+ // us-east-1 answers a repeated create with success: tags decide.
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, "us-east-1"); err != nil {
+ t.Fatal(err)
+ }
+ })
+ t.Run("legacy EU location", func(t *testing.T) {
+ s := newTestStorage(t)
+ s.s3.legacyEU = true
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, "eu-west-1"); err != nil {
+ t.Fatal(err)
+ }
+ })
+ t.Run("aws defaults need no writes", func(t *testing.T) {
+ s := newTestStorage(t)
+ bucket, _ := testNames(t, testFleet)
+ s.s3.buckets[bucket] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags(testFleet),
+ enc: &s3types.ServerSideEncryptionConfiguration{Rules: []s3types.ServerSideEncryptionRule{{
+ ApplyServerSideEncryptionByDefault: &s3types.ServerSideEncryptionByDefault{SSEAlgorithm: s3types.ServerSideEncryptionAes256}, BucketKeyEnabled: aws.Bool(false)}}},
+ pab: &s3types.PublicAccessBlockConfiguration{BlockPublicAcls: aws.Bool(true), IgnorePublicAcls: aws.Bool(true), BlockPublicPolicy: aws.Bool(true), RestrictPublicBuckets: aws.Bool(true)}}
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err != nil {
+ t.Fatal(err)
+ }
+ if s.s3.count("PutBucketEncryption") != 0 || s.s3.count("PutPublicAccessBlock") != 0 {
+ t.Fatal("rewrote settings already in place")
+ }
+ })
+ t.Run("repairs settings on an owned bucket", func(t *testing.T) {
+ s := newTestStorage(t)
+ bucket, _ := testNames(t, testFleet)
+ s.s3.buckets[bucket] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags(testFleet), versioning: s3types.BucketVersioningStatusSuspended,
+ enc: &s3types.ServerSideEncryptionConfiguration{Rules: []s3types.ServerSideEncryptionRule{{
+ ApplyServerSideEncryptionByDefault: &s3types.ServerSideEncryptionByDefault{SSEAlgorithm: s3types.ServerSideEncryptionAwsKms, KMSMasterKeyID: aws.String("k")}}}},
+ pab: &s3types.PublicAccessBlockConfiguration{BlockPublicAcls: aws.Bool(true)}}
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err != nil {
+ t.Fatal(err)
+ }
+ wantPrepared(t, s.s3.bucket(bucket), testRegion)
+ })
+ // Every refusal below happens before any bucket write or IAM call.
+ refusals := map[string]struct {
+ region string
+ seed func(w *fakeS3World, bucket string)
+ }{
+ "other region": {otherRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags(testFleet)}
+ }},
+ "foreign owner": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: foreignAcct, tags: ownTags(testFleet)}
+ }},
+ "foreign owner answered as ours": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: foreignAcct, tags: ownTags(testFleet)}
+ w.before = func(op string, _ int) error {
+ if op == "CreateBucket" {
+ return apiErr("BucketAlreadyOwnedByYou")
+ }
+ return nil
+ }
+ }},
+ "other deployment tag": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: []s3types.Tag{
+ {Key: aws.String("carlos:deployment"), Value: aws.String("staging")}, {Key: aws.String("carlos:fleet"), Value: aws.String(testFleet)}}}
+ }},
+ "other fleet tag": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags("shop-2")}
+ }},
+ "extra tag": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: append(ownTags(testFleet), s3types.Tag{Key: aws.String("team"), Value: aws.String("x")})}
+ }},
+ "duplicate tag": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: append(ownTags(testFleet), ownTags(testFleet)[1])}
+ }},
+ "one tag missing": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags(testFleet)[:1]}
+ }},
+ "foreign lifecycle rule": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags(testFleet), rules: []s3types.LifecycleRule{
+ {ID: aws.String("expire-all"), Status: s3types.ExpirationStatusEnabled, Filter: &s3types.LifecycleRuleFilter{}, Expiration: &s3types.LifecycleExpiration{Days: aws.Int32(1)}}}}
+ }},
+ "our rule with other days": {testRegion, func(w *fakeS3World, b string) {
+ r := fleetLifecycleRule()
+ r.NoncurrentVersionExpiration = &s3types.NoncurrentVersionExpiration{NoncurrentDays: aws.Int32(30)}
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags(testFleet), rules: []s3types.LifecycleRule{r}}
+ }},
+ "our rule plus another": {testRegion, func(w *fakeS3World, b string) {
+ w.buckets[b] = &fakeBucket{region: testRegion, owner: testAccount, tags: ownTags(testFleet), rules: []s3types.LifecycleRule{fleetLifecycleRule(),
+ {ID: aws.String("x"), Status: s3types.ExpirationStatusDisabled, Filter: &s3types.LifecycleRuleFilter{}}}}
+ }},
+ }
+ for name, tc := range refusals {
+ t.Run(name, func(t *testing.T) {
+ s := newTestStorage(t)
+ bucket, _ := testNames(t, testFleet)
+ tc.seed(s.s3, bucket)
+ before := *s.s3.buckets[bucket]
+ got, err := s.EnsureFleetStorage(ctx, testFleet, tc.region)
+ if err == nil || got != (fleetstore.FleetStorage{}) {
+ t.Fatalf("accepted: %+v", got)
+ }
+ drifted(t, err)
+ lifecycleCase := strings.Contains(name, "lifecycle") || strings.Contains(name, "rule")
+ if lifecycleCase && s.s3.count("PutBucketLifecycleConfiguration") != 0 {
+ t.Fatal("replaced lifecycle rules it did not write")
+ }
+ if !lifecycleCase {
+ after := s.s3.buckets[bucket]
+ if s.s3.puts() != 0 || after.versioning != before.versioning || after.enc != before.enc || after.pab != before.pab {
+ t.Fatal("configured a bucket it does not own")
+ }
+ }
+ if s.iam.total() != 0 {
+ t.Fatal("touched IAM before the bucket was proven")
+ }
+ })
+ }
+ t.Run("region not configured", func(t *testing.T) {
+ s := newTestStorage(t)
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, "ap-south-1"); err == nil || s.s3.count("CreateBucket") != 0 {
+ t.Fatal("used an unconfigured region")
+ }
+ })
+}
+
+// fleetPrepOps is every call preparation makes, in order.
+var fleetPrepOps = []string{
+ "CreateBucket", "GetBucketLocation", "GetBucketTagging",
+ "GetBucketVersioning", "PutBucketVersioning", "GetBucketEncryption", "PutBucketEncryption",
+ "GetPublicAccessBlock", "PutPublicAccessBlock", "GetBucketLifecycleConfiguration", "PutBucketLifecycleConfiguration",
+ "CreateUser", "GetUser", "ListAttachedUserPolicies", "ListGroupsForUser", "ListUserPolicies", "PutUserPolicy", "GetUserPolicy",
+}
+
+func TestAWSFleetBucketPartialFailure(t *testing.T) {
+ ctx := context.Background()
+ for _, op := range fleetPrepOps {
+ for _, mode := range []string{"before", "after"} {
+ t.Run(op+"/"+mode, func(t *testing.T) {
+ s := newTestStorage(t)
+ bucket, _ := testNames(t, testFleet)
+ // before fails the first call; after loses the answer of the
+ // first call that took effect (for a Get on a fresh bucket,
+ // its readback).
+ fired := false
+ fail := func(o string, n int) error {
+ if o == op && !fired {
+ fired = true
+ return apiErr("ServiceUnavailable")
+ }
+ return nil
+ }
+ if mode == "before" {
+ s.s3.before, s.iam.before = fail, fail
+ } else {
+ s.s3.after, s.iam.after = fail, fail
+ }
+ got, err := s.EnsureFleetStorage(ctx, testFleet, testRegion)
+ if !fired {
+ t.Fatalf("%s never failed", op)
+ }
+ if err == nil || got != (fleetstore.FleetStorage{}) {
+ t.Fatalf("a failed %s returned prepared storage %+v", op, got)
+ }
+ noLeak(t, err.Error())
+ s.s3.before, s.s3.after, s.iam.before, s.iam.after = nil, nil, nil, nil
+ got, err = s.EnsureFleetStorage(ctx, testFleet, testRegion)
+ if err != nil || got.Bucket != bucket {
+ t.Fatalf("retry after %s: %+v %v", op, got, err)
+ }
+ wantPrepared(t, s.s3.bucket(bucket), testRegion)
+ if s.iam.count("CreateAccessKey") != 0 {
+ t.Fatal("preparation minted a key")
+ }
+ })
+ }
+ }
+ for _, op := range []string{"PutBucketVersioning", "PutBucketEncryption", "PutPublicAccessBlock", "PutBucketLifecycleConfiguration"} {
+ t.Run(op+"/unread", func(t *testing.T) {
+ s := newTestStorage(t)
+ s.s3.dropPuts[op] = true
+ if got, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err == nil || got != (fleetstore.FleetStorage{}) {
+ t.Fatalf("a setting that did not read back was accepted: %+v", got)
+ }
+ if s.iam.total() != 0 {
+ t.Fatal("went on to IAM after a failed readback")
+ }
+ delete(s.s3.dropPuts, op)
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+ t.Run("policy unread", func(t *testing.T) {
+ s := newTestStorage(t)
+ s.iam.dropPolicyPut = true
+ if got, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err == nil || got != (fleetstore.FleetStorage{}) {
+ t.Fatalf("a policy that did not read back was accepted: %+v", got)
+ }
+ })
+ t.Run("untagged existing bucket", func(t *testing.T) {
+ s := newTestStorage(t)
+ bucket, _ := testNames(t, testFleet)
+ s.s3.buckets[bucket] = &fakeBucket{region: testRegion, owner: testAccount}
+ for range 2 {
+ _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion)
+ drifted(t, err)
+ }
+ if s.s3.puts() != 0 || s.iam.total() != 0 || s.s3.buckets[bucket].tags != nil {
+ t.Fatal("adopted or relabelled an untagged bucket")
+ }
+ })
+ t.Run("lost create reply", func(t *testing.T) {
+ s := newTestStorage(t)
+ s.s3.after = func(op string, n int) error {
+ if op == "CreateBucket" {
+ return apiErr("RequestTimeout")
+ }
+ return nil
+ }
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err == nil {
+ t.Fatal("accepted a lost reply")
+ }
+ s.s3.after = nil
+ if _, err := s.EnsureFleetStorage(ctx, testFleet, testRegion); err != nil {
+ t.Fatalf("did not recover the bucket through its tags: %v", err)
+ }
+ })
+}
diff --git a/internal/awsmanaged/testdata/fleet-data-policy.json b/internal/awsmanaged/testdata/fleet-data-policy.json
new file mode 100644
index 000000000..c3a6c3d92
--- /dev/null
+++ b/internal/awsmanaged/testdata/fleet-data-policy.json
@@ -0,0 +1,82 @@
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "Bucket",
+ "Effect": "Allow",
+ "Action": ["s3:GetBucketLocation", "s3:ListBucket"],
+ "Resource": ["arn:aws:s3:::carlos-fleet-0123456789abcdef01234567"]
+ },
+ {
+ "Sid": "Versions",
+ "Effect": "Allow",
+ "Action": ["s3:ListBucketVersions"],
+ "Resource": ["arn:aws:s3:::carlos-fleet-0123456789abcdef01234567"],
+ "Condition": {
+ "StringLike": {
+ "s3:prefix": ["instances/*", "moves/*", "move-snapshots/*", "_carlos/probes/*", "system/fleet-secrets-key.json"]
+ }
+ }
+ },
+ {
+ "Sid": "Uploads",
+ "Effect": "Allow",
+ "Action": ["s3:ListBucketMultipartUploads"],
+ "Resource": ["arn:aws:s3:::carlos-fleet-0123456789abcdef01234567"],
+ "Condition": {
+ "StringLike": {
+ "s3:prefix": ["instances/*", "moves/*", "move-snapshots/*"]
+ }
+ }
+ },
+ {
+ "Sid": "Data",
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetObject",
+ "s3:PutObject",
+ "s3:DeleteObject",
+ "s3:GetObjectVersion",
+ "s3:AbortMultipartUpload",
+ "s3:ListMultipartUploadParts"
+ ],
+ "Resource": [
+ "arn:aws:s3:::carlos-fleet-0123456789abcdef01234567/instances/*",
+ "arn:aws:s3:::carlos-fleet-0123456789abcdef01234567/moves/*",
+ "arn:aws:s3:::carlos-fleet-0123456789abcdef01234567/move-snapshots/*"
+ ]
+ },
+ {
+ "Sid": "Probes",
+ "Effect": "Allow",
+ "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
+ "Resource": ["arn:aws:s3:::carlos-fleet-0123456789abcdef01234567/_carlos/probes/*"]
+ },
+ {
+ "Sid": "KeyRead",
+ "Effect": "Allow",
+ "Action": ["s3:GetObject"],
+ "Resource": ["arn:aws:s3:::carlos-fleet-0123456789abcdef01234567/system/fleet-secrets-key.json"]
+ },
+ {
+ "Sid": "KeyCreate",
+ "Effect": "Allow",
+ "Action": ["s3:PutObject"],
+ "Resource": ["arn:aws:s3:::carlos-fleet-0123456789abcdef01234567/system/fleet-secrets-key.json"],
+ "Condition": {
+ "StringEquals": {
+ "s3:if-none-match": ["*"]
+ }
+ }
+ },
+ {
+ "Sid": "OnlyThisBucket",
+ "Effect": "Deny",
+ "Action": ["s3:*"],
+ "NotResource": [
+ "arn:aws:s3:::carlos-fleet-0123456789abcdef01234567",
+ "arn:aws:s3:::carlos-fleet-0123456789abcdef01234567/*"
+ ]
+ }
+ ]
+}