| new file mode 100644 |
| index 000000000..f449eb14f |
| --- /dev/null |
| +++ b/internal/mediaaws/mediaaws_test.go |
| @@ -0,0 +1,2530 @@ |
| +package mediaaws |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/md5" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/aws/aws-sdk-go-v2/service/ecs" |
| + ecstypes "github.com/aws/aws-sdk-go-v2/service/ecs/types" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| + ststypes "github.com/aws/aws-sdk-go-v2/service/sts/types" |
| + "github.com/aws/smithy-go" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| + "github.com/carlosframework/platform/internal/mediahandler" |
| + "github.com/carlosframework/platform/internal/storecfg" |
| +) |
| + |
| +const ( |
| + testExec = "0123456789abcdef0123456789abcdef" |
| + testAccount = "123456789012" |
| + testRegion = "eu-west-1" |
| + testResults = "carlos-deployment-results" |
| + testBucket = "carlos-store-abc" |
| + testToken = "IQoJb3JpZ2luX2VjEFAKE+token/with+plus/slash==" |
| +) |
| + |
| +func revisionARN(name string, rev int) string { |
| + return fmt.Sprintf("arn:aws:ecs:%s:%s:task-definition/%s:%d", testRegion, testAccount, name, rev) |
| +} |
| + |
| +func testConfig() Config { |
| + return Config{ |
| + V: 1, |
| + Region: testRegion, |
| + Cluster: "arn:aws:ecs:" + testRegion + ":" + testAccount + ":cluster/media", |
| + TaskDefinitions: map[string]string{ |
| + "video-720p/short": revisionARN("media-video-short", 3), |
| + "video-720p/long": revisionARN("media-video-long", 3), |
| + "audio-aac/short": revisionARN("media-audio-short", 3), |
| + "audio-aac/long": revisionARN("media-audio-long", 3), |
| + }, |
| + Subnets: []string{"subnet-aaa", "subnet-bbb"}, |
| + SecurityGroup: "sg-123", |
| + ConversionRole: "arn:aws:iam::" + testAccount + ":role/media-conversion", |
| + ResultsBucket: testResults, |
| + StorePrefix: "carlos-store-", |
| + AccountID: testAccount, |
| + Image: media.ImageInfo{Digest: "sha256:" + strings.Repeat("a", 64), BuiltAt: "2026-11-16T12:00:00Z", FFmpeg: "7.1.5"}, |
| + } |
| +} |
| + |
| +// stubECS records every input and answers through its funcs. |
| +type stubECS struct { |
| + mu sync.Mutex |
| + runs []*ecs.RunTaskInput |
| + describes []*ecs.DescribeTasksInput |
| + lists []*ecs.ListTasksInput |
| + stops []*ecs.StopTaskInput |
| + revisions []string |
| + |
| + run func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) |
| + describe func(*ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) |
| + list func(*ecs.ListTasksInput) (*ecs.ListTasksOutput, error) |
| + stop func(*ecs.StopTaskInput) (*ecs.StopTaskOutput, error) |
| + taskDef func(*ecs.DescribeTaskDefinitionInput) (*ecs.DescribeTaskDefinitionOutput, error) |
| +} |
| + |
| +func (s *stubECS) RunTask(_ context.Context, in *ecs.RunTaskInput, _ ...func(*ecs.Options)) (*ecs.RunTaskOutput, error) { |
| + s.mu.Lock() |
| + s.runs = append(s.runs, in) |
| + s.mu.Unlock() |
| + if s.run == nil { |
| + return &ecs.RunTaskOutput{Tasks: []ecstypes.Task{{TaskArn: aws.String("arn:task/1")}}}, nil |
| + } |
| + return s.run(in) |
| +} |
| + |
| +func (s *stubECS) DescribeTasks(_ context.Context, in *ecs.DescribeTasksInput, _ ...func(*ecs.Options)) (*ecs.DescribeTasksOutput, error) { |
| + s.mu.Lock() |
| + s.describes = append(s.describes, in) |
| + s.mu.Unlock() |
| + return s.describe(in) |
| +} |
| + |
| +func (s *stubECS) ListTasks(_ context.Context, in *ecs.ListTasksInput, _ ...func(*ecs.Options)) (*ecs.ListTasksOutput, error) { |
| + s.mu.Lock() |
| + s.lists = append(s.lists, in) |
| + s.mu.Unlock() |
| + return s.list(in) |
| +} |
| + |
| +func (s *stubECS) StopTask(_ context.Context, in *ecs.StopTaskInput, _ ...func(*ecs.Options)) (*ecs.StopTaskOutput, error) { |
| + s.mu.Lock() |
| + s.stops = append(s.stops, in) |
| + s.mu.Unlock() |
| + if s.stop == nil { |
| + return &ecs.StopTaskOutput{}, nil |
| + } |
| + return s.stop(in) |
| +} |
| + |
| +func (s *stubECS) DescribeTaskDefinition(_ context.Context, in *ecs.DescribeTaskDefinitionInput, _ ...func(*ecs.Options)) (*ecs.DescribeTaskDefinitionOutput, error) { |
| + s.mu.Lock() |
| + s.revisions = append(s.revisions, aws.ToString(in.TaskDefinition)) |
| + s.mu.Unlock() |
| + return s.taskDef(in) |
| +} |
| + |
| +// stubS3 answers the operations a test sets; any other panics on the nil |
| +// embedded interface. calls records each operation with its expected |
| +// bucket owner, so a test can see that every call sent one. |
| +type stubS3 struct { |
| + S3API |
| + mu sync.Mutex |
| + region string |
| + owners map[string]string |
| + |
| + listObjects func(*s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) |
| + headObject func(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) |
| + getObject func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) |
| + deleteObject func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) |
| + |
| + headBucket func(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) |
| + location func(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) |
| + encryption func(*s3.GetBucketEncryptionInput) (*s3.GetBucketEncryptionOutput, error) |
| + versioning func(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error) |
| + policy func(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error) |
| + lifecycle func(*s3.GetBucketLifecycleConfigurationInput) (*s3.GetBucketLifecycleConfigurationOutput, error) |
| + cors func(*s3.GetBucketCorsInput) (*s3.GetBucketCorsOutput, error) |
| + putCORS func(*s3.PutBucketCorsInput) (*s3.PutBucketCorsOutput, error) |
| + putLifecycle func(*s3.PutBucketLifecycleConfigurationInput) (*s3.PutBucketLifecycleConfigurationOutput, error) |
| + delCORS func(*s3.DeleteBucketCorsInput) (*s3.DeleteBucketCorsOutput, error) |
| + delLifecycle func(*s3.DeleteBucketLifecycleInput) (*s3.DeleteBucketLifecycleOutput, error) |
| + tagging func(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) |
| + putTagging func(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error) |
| +} |
| + |
| +func (s *stubS3) saw(op string, owner *string) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if s.owners == nil { |
| + s.owners = map[string]string{} |
| + } |
| + s.owners[op] = aws.ToString(owner) |
| +} |
| + |
| +func (s *stubS3) Options() s3.Options { return s3.Options{Region: s.region} } |
| + |
| +func (s *stubS3) ListObjectsV2(_ context.Context, in *s3.ListObjectsV2Input, _ ...func(*s3.Options)) (*s3.ListObjectsV2Output, error) { |
| + s.saw("ListObjectsV2", in.ExpectedBucketOwner) |
| + return s.listObjects(in) |
| +} |
| + |
| +func (s *stubS3) HeadObject(_ context.Context, in *s3.HeadObjectInput, _ ...func(*s3.Options)) (*s3.HeadObjectOutput, error) { |
| + s.saw("HeadObject", in.ExpectedBucketOwner) |
| + return s.headObject(in) |
| +} |
| + |
| +func (s *stubS3) GetObject(_ context.Context, in *s3.GetObjectInput, _ ...func(*s3.Options)) (*s3.GetObjectOutput, error) { |
| + s.saw("GetObject", in.ExpectedBucketOwner) |
| + return s.getObject(in) |
| +} |
| + |
| +func (s *stubS3) DeleteObject(_ context.Context, in *s3.DeleteObjectInput, _ ...func(*s3.Options)) (*s3.DeleteObjectOutput, error) { |
| + s.saw("DeleteObject", in.ExpectedBucketOwner) |
| + return s.deleteObject(in) |
| +} |
| + |
| +func (s *stubS3) HeadBucket(_ context.Context, in *s3.HeadBucketInput, _ ...func(*s3.Options)) (*s3.HeadBucketOutput, error) { |
| + s.saw("HeadBucket", in.ExpectedBucketOwner) |
| + return s.headBucket(in) |
| +} |
| + |
| +func (s *stubS3) GetBucketLocation(_ context.Context, in *s3.GetBucketLocationInput, _ ...func(*s3.Options)) (*s3.GetBucketLocationOutput, error) { |
| + s.saw("GetBucketLocation", in.ExpectedBucketOwner) |
| + return s.location(in) |
| +} |
| + |
| +func (s *stubS3) GetBucketEncryption(_ context.Context, in *s3.GetBucketEncryptionInput, _ ...func(*s3.Options)) (*s3.GetBucketEncryptionOutput, error) { |
| + s.saw("GetBucketEncryption", in.ExpectedBucketOwner) |
| + return s.encryption(in) |
| +} |
| + |
| +func (s *stubS3) GetBucketVersioning(_ context.Context, in *s3.GetBucketVersioningInput, _ ...func(*s3.Options)) (*s3.GetBucketVersioningOutput, error) { |
| + s.saw("GetBucketVersioning", in.ExpectedBucketOwner) |
| + return s.versioning(in) |
| +} |
| + |
| +func (s *stubS3) GetBucketPolicy(_ context.Context, in *s3.GetBucketPolicyInput, _ ...func(*s3.Options)) (*s3.GetBucketPolicyOutput, error) { |
| + s.saw("GetBucketPolicy", in.ExpectedBucketOwner) |
| + return s.policy(in) |
| +} |
| + |
| +func (s *stubS3) GetBucketLifecycleConfiguration(_ context.Context, in *s3.GetBucketLifecycleConfigurationInput, _ ...func(*s3.Options)) (*s3.GetBucketLifecycleConfigurationOutput, error) { |
| + s.saw("GetBucketLifecycleConfiguration", in.ExpectedBucketOwner) |
| + return s.lifecycle(in) |
| +} |
| + |
| +func (s *stubS3) GetBucketCors(_ context.Context, in *s3.GetBucketCorsInput, _ ...func(*s3.Options)) (*s3.GetBucketCorsOutput, error) { |
| + s.saw("GetBucketCors", in.ExpectedBucketOwner) |
| + return s.cors(in) |
| +} |
| + |
| +func (s *stubS3) PutBucketCors(_ context.Context, in *s3.PutBucketCorsInput, _ ...func(*s3.Options)) (*s3.PutBucketCorsOutput, error) { |
| + s.saw("PutBucketCors", in.ExpectedBucketOwner) |
| + return s.putCORS(in) |
| +} |
| + |
| +func (s *stubS3) PutBucketLifecycleConfiguration(_ context.Context, in *s3.PutBucketLifecycleConfigurationInput, _ ...func(*s3.Options)) (*s3.PutBucketLifecycleConfigurationOutput, error) { |
| + s.saw("PutBucketLifecycleConfiguration", in.ExpectedBucketOwner) |
| + return s.putLifecycle(in) |
| +} |
| + |
| +func (s *stubS3) DeleteBucketCors(_ context.Context, in *s3.DeleteBucketCorsInput, _ ...func(*s3.Options)) (*s3.DeleteBucketCorsOutput, error) { |
| + s.saw("DeleteBucketCors", in.ExpectedBucketOwner) |
| + return s.delCORS(in) |
| +} |
| + |
| +func (s *stubS3) DeleteBucketLifecycle(_ context.Context, in *s3.DeleteBucketLifecycleInput, _ ...func(*s3.Options)) (*s3.DeleteBucketLifecycleOutput, error) { |
| + s.saw("DeleteBucketLifecycle", in.ExpectedBucketOwner) |
| + return s.delLifecycle(in) |
| +} |
| + |
| +func (s *stubS3) GetBucketTagging(_ context.Context, in *s3.GetBucketTaggingInput, _ ...func(*s3.Options)) (*s3.GetBucketTaggingOutput, error) { |
| + s.saw("GetBucketTagging", in.ExpectedBucketOwner) |
| + return s.tagging(in) |
| +} |
| + |
| +func (s *stubS3) PutBucketTagging(_ context.Context, in *s3.PutBucketTaggingInput, _ ...func(*s3.Options)) (*s3.PutBucketTaggingOutput, error) { |
| + s.saw("PutBucketTagging", in.ExpectedBucketOwner) |
| + return s.putTagging(in) |
| +} |
| + |
| +// httpFunc is a stubbed transport for a real SDK client. |
| +type httpFunc func(*http.Request) (*http.Response, error) |
| + |
| +func (f httpFunc) Do(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +func answer(r *http.Request, status int, header map[string]string, body string) *http.Response { |
| + h := http.Header{} |
| + for k, v := range header { |
| + h.Set(k, v) |
| + } |
| + return &http.Response{StatusCode: status, Status: strconv.Itoa(status), Header: h, Body: io.NopCloser(strings.NewReader(body)), ContentLength: int64(len(body)), Request: r} |
| +} |
| + |
| +func realECS(f httpFunc) *ecs.Client { |
| + return ecs.New(ecs.Options{Region: testRegion, Credentials: credentials.NewStaticCredentialsProvider("AKIDEXAMPLE", "secret", ""), HTTPClient: f, RetryMaxAttempts: 1}) |
| +} |
| + |
| +func realS3(f httpFunc) *s3.Client { |
| + return s3.New(s3.Options{Region: testRegion, Credentials: credentials.NewStaticCredentialsProvider("AKIDEXAMPLE", "secret", ""), HTTPClient: f, UsePathStyle: true, RetryMaxAttempts: 1}) |
| +} |
| + |
| +func sessionCreds(expires time.Time) aws.Credentials { |
| + return aws.Credentials{AccessKeyID: "ASIAEXAMPLEEXAMPLE12", SecretAccessKey: "session-secret", SessionToken: testToken, CanExpire: true, Expires: expires} |
| +} |
| + |
| +func staticAssume(expires time.Time) func(context.Context, string, string) (aws.Credentials, error) { |
| + return func(context.Context, string, string) (aws.Credentials, error) { return sessionCreds(expires), nil } |
| +} |
| + |
| +func grantRequest() media.GrantRequest { |
| + key := "uploads/a b+c/é.mov" |
| + etag := "9b2cf535f27731c974343645a3985328" |
| + r := media.GrantRequest{Bucket: testBucket, SourceKey: key, SourceETag: etag, Execution: testExec, |
| + OutputPrefix: media.OutputPrefix(key, etag, media.PresetVideo720p, testExec)} |
| + for _, n := range media.OutputNames(media.PresetVideo720p) { |
| + r.Outputs = append(r.Outputs, media.OutputFile{Name: n, ContentType: media.ContentType(n)}) |
| + } |
| + return r |
| +} |
| + |
| +func TestParseConfig(t *testing.T) { |
| + good, err := json.Marshal(testConfig()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, err := ParseConfig(string(good)) |
| + if err != nil { |
| + t.Fatalf("a valid config was refused: %v", err) |
| + } |
| + if !reflect.DeepEqual(c, testConfig()) { |
| + t.Fatalf("round trip changed the config: %+v", c) |
| + } |
| + mutate := func(f func(*Config)) string { |
| + c := testConfig() |
| + f(&c) |
| + b, err := json.Marshal(c) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| + } |
| + bad := map[string]string{ |
| + "empty": "", |
| + "not json": "{", |
| + "unknown field": strings.Replace(string(good), `{"v":1`, `{"extra":1,"v":1`, 1), |
| + "trailing data": string(good) + "{}", |
| + "version 0": mutate(func(c *Config) { c.V = 0 }), |
| + "version 2": mutate(func(c *Config) { c.V = 2 }), |
| + "no region": mutate(func(c *Config) { c.Region = "" }), |
| + "no cluster": mutate(func(c *Config) { c.Cluster = "" }), |
| + "class missing": mutate(func(c *Config) { delete(c.TaskDefinitions, "audio-aac/long") }), |
| + "class unknown": mutate(func(c *Config) { c.TaskDefinitions["video-1080p/short"] = revisionARN("x", 1) }), |
| + "class renamed": mutate(func(c *Config) { |
| + delete(c.TaskDefinitions, "audio-aac/long") |
| + c.TaskDefinitions["audio-aac/huge"] = revisionARN("x", 1) |
| + }), |
| + "no revision": mutate(func(c *Config) { |
| + c.TaskDefinitions["audio-aac/long"] = "arn:aws:ecs:eu-west-1:123456789012:task-definition/media" |
| + }), |
| + "latest revision": mutate(func(c *Config) { |
| + c.TaskDefinitions["audio-aac/long"] = "arn:aws:ecs:eu-west-1:123456789012:task-definition/media:latest" |
| + }), |
| + "revision zero": mutate(func(c *Config) { |
| + c.TaskDefinitions["audio-aac/long"] = "arn:aws:ecs:eu-west-1:123456789012:task-definition/media:0" |
| + }), |
| + "family only": mutate(func(c *Config) { c.TaskDefinitions["audio-aac/long"] = "media:3" }), |
| + "no subnets": mutate(func(c *Config) { c.Subnets = nil }), |
| + "blank subnet": mutate(func(c *Config) { c.Subnets = []string{""} }), |
| + "no security group": mutate(func(c *Config) { c.SecurityGroup = "" }), |
| + "no role": mutate(func(c *Config) { c.ConversionRole = "" }), |
| + "no results bucket": mutate(func(c *Config) { c.ResultsBucket = "" }), |
| + "no store prefix": mutate(func(c *Config) { c.StorePrefix = "" }), |
| + "no account": mutate(func(c *Config) { c.AccountID = "" }), |
| + "short account": mutate(func(c *Config) { c.AccountID = "12345" }), |
| + "no digest": mutate(func(c *Config) { c.Image.Digest = "" }), |
| + "short digest": mutate(func(c *Config) { c.Image.Digest = "sha256:abc" }), |
| + "upper digest": mutate(func(c *Config) { c.Image.Digest = "sha256:" + strings.Repeat("A", 64) }), |
| + "other algorithm": mutate(func(c *Config) { c.Image.Digest = "sha512:" + strings.Repeat("a", 64) }), |
| + } |
| + for name, v := range bad { |
| + if _, err := ParseConfig(v); err == nil { |
| + t.Errorf("%s: accepted", name) |
| + } |
| + } |
| +} |
| + |
| +func runRequest() media.RunRequest { |
| + return media.RunRequest{ |
| + Execution: testExec, |
| + Class: media.ClassKey{Preset: media.PresetVideo720p, Class: media.ClassLong}, |
| + Payload: []byte(`{"v":1,"secret":"payload"}`), |
| + DeadlineS: 3000, |
| + GrantExpiry: time.Unix(1795352400, 0), |
| + } |
| +} |
| + |
| +func envOf(o ecstypes.ContainerOverride) map[string]string { |
| + m := map[string]string{} |
| + for _, kv := range o.Environment { |
| + m[aws.ToString(kv.Name)] = aws.ToString(kv.Value) |
| + } |
| + return m |
| +} |
| + |
| +func TestRunTaskInput(t *testing.T) { |
| + api := &stubECS{} |
| + c := testConfig() |
| + req := runRequest() |
| + req.EphemeralGiB = 48 |
| + arn, err := NewEngine(c, api).Run(context.Background(), req) |
| + if err != nil || arn != "arn:task/1" { |
| + t.Fatalf("Run = %q, %v", arn, err) |
| + } |
| + in := api.runs[0] |
| + if aws.ToString(in.Cluster) != c.Cluster || |
| + aws.ToString(in.TaskDefinition) != c.TaskDefinitions["video-720p/long"] || |
| + in.LaunchType != ecstypes.LaunchTypeFargate || |
| + aws.ToString(in.PlatformVersion) != "1.4.0" || |
| + aws.ToInt32(in.Count) != 1 || |
| + aws.ToString(in.StartedBy) != testExec || |
| + aws.ToString(in.ClientToken) != testExec { |
| + t.Fatalf("RunTask input: %+v", in) |
| + } |
| + if in.CapacityProviderStrategy != nil { |
| + t.Fatalf("a capacity provider would displace the Fargate launch type: %+v", in.CapacityProviderStrategy) |
| + } |
| + if in.EnableExecuteCommand { |
| + t.Fatal("EnableExecuteCommand must be false") |
| + } |
| + vpc := in.NetworkConfiguration.AwsvpcConfiguration |
| + if !slices.Equal(vpc.Subnets, c.Subnets) || !slices.Equal(vpc.SecurityGroups, []string{c.SecurityGroup}) || vpc.AssignPublicIp != ecstypes.AssignPublicIpDisabled { |
| + t.Fatalf("network: %+v", vpc) |
| + } |
| + if got := in.Overrides.EphemeralStorage.SizeInGiB; got != 48 { |
| + t.Fatalf("ephemeral storage = %d", got) |
| + } |
| + if in.Overrides.TaskRoleArn != nil || in.Overrides.ExecutionRoleArn != nil || in.Overrides.Cpu != nil || in.Overrides.Memory != nil { |
| + t.Fatalf("task overrides beyond storage: %+v", in.Overrides) |
| + } |
| + if len(in.Overrides.ContainerOverrides) != 2 { |
| + t.Fatalf("container overrides: %+v", in.Overrides.ContainerOverrides) |
| + } |
| + byName := map[string]ecstypes.ContainerOverride{} |
| + for _, o := range in.Overrides.ContainerOverrides { |
| + byName[aws.ToString(o.Name)] = o |
| + } |
| + codec, deadline := envOf(byName[media.ContainerCodec]), envOf(byName[media.ContainerDeadline]) |
| + if !reflect.DeepEqual(codec, map[string]string{media.PayloadEnv: string(req.Payload)}) { |
| + t.Fatalf("codec environment: %v", codec) |
| + } |
| + if !reflect.DeepEqual(deadline, map[string]string{media.DeadlineEnv: "3000", media.ExpiryEnv: "1795352400"}) { |
| + t.Fatalf("deadline environment: %v", deadline) |
| + } |
| + // No override may change what either container runs: the gate compared |
| + // the task definition's own entry point and command. |
| + for name, o := range byName { |
| + if o.Command != nil { |
| + t.Errorf("%s: Command override %v", name, o.Command) |
| + } |
| + if f := reflect.ValueOf(o).FieldByName("EntryPoint"); f.IsValid() && !f.IsNil() { |
| + t.Errorf("%s: EntryPoint override", name) |
| + } |
| + if o.EnvironmentFiles != nil || o.Cpu != nil || o.Memory != nil || o.MemoryReservation != nil || o.ResourceRequirements != nil { |
| + t.Errorf("%s: an override beyond the environment: %+v", name, o) |
| + } |
| + } |
| + |
| + req.EphemeralGiB = 0 |
| + if _, err := NewEngine(c, api).Run(context.Background(), req); err != nil { |
| + t.Fatal(err) |
| + } |
| + if api.runs[1].Overrides.EphemeralStorage != nil { |
| + t.Fatal("ephemeral storage sent with no size") |
| + } |
| +} |
| + |
| +// TestRunTaskOverrideFits measures what the real SDK puts on the wire for |
| +// the worst case: the longest admitted key, a multipart ETag, the longest |
| +// bucket names and a 1,400-character session token (plan 2's stand-in |
| +// until plan 1 measures the real one), presigned by the real presigner. |
| +func TestRunTaskOverrideFits(t *testing.T) { |
| + key := "uploads/" + strings.Repeat("€", 168) |
| + if len(key) != 512 || !media.ValidKey(key) { |
| + t.Fatalf("key is %d bytes", len(key)) |
| + } |
| + const etag = "9b2cf535f27731c974343645a3985328-10000" |
| + c := testConfig() |
| + c.Region = "ap-southeast-2" |
| + c.ResultsBucket = "carlos-deployment-bucket-with-a-long-name-0123456789" |
| + bucket := "carlos-" + strings.Repeat("b", 56) |
| + token := strings.Repeat("IQoJb3JpZ2luX2VjE+/=", 70) |
| + if len(token) != 1400 { |
| + t.Fatalf("token is %d characters", len(token)) |
| + } |
| + expires := time.Now().Add(time.Hour) |
| + assume := func(context.Context, string, string) (aws.Credentials, error) { |
| + cr := sessionCreds(expires) |
| + cr.SessionToken = token |
| + return cr, nil |
| + } |
| + r := media.GrantRequest{Bucket: bucket, SourceKey: key, SourceETag: etag, Execution: testExec, |
| + OutputPrefix: media.OutputPrefix(key, etag, media.PresetVideo720p, testExec)} |
| + for _, n := range media.OutputNames(media.PresetVideo720p) { |
| + r.Outputs = append(r.Outputs, media.OutputFile{Name: n, ContentType: media.ContentType(n)}) |
| + } |
| + transfers, expiry, err := NewGrants(c, assume, &stubS3{}).Grant(context.Background(), r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := media.Payload{V: 1, Execution: testExec, Preset: media.PresetVideo720p, |
| + Limits: media.JobLimits{SourceBytes: 40 << 30, GrantedMS: 7200000, GrantedBy: "allowance", MaxMS: 7200000, MaxHiMS: 1800000, OutputBytes: media.MaxPutBytes}, |
| + Expiry: expiry.Unix(), Transfers: transfers} |
| + if err := p.Validate(); err != nil { |
| + t.Fatal(err) |
| + } |
| + payload, err := json.Marshal(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var wire []byte |
| + client := realECS(func(req *http.Request) (*http.Response, error) { |
| + wire, _ = io.ReadAll(req.Body) |
| + return answer(req, 200, map[string]string{"Content-Type": "application/x-amz-json-1.1"}, `{"tasks":[{"taskArn":"arn:task/1"}],"failures":[]}`), nil |
| + }) |
| + _, err = NewEngine(c, client).Run(context.Background(), media.RunRequest{Execution: testExec, Class: media.ClassKey{Preset: media.PresetVideo720p, Class: media.ClassLong}, |
| + Payload: payload, DeadlineS: 3000, GrantExpiry: expiry, EphemeralGiB: 48}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var sent struct { |
| + Overrides json.RawMessage `json:"overrides"` |
| + } |
| + if err := json.Unmarshal(wire, &sent); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Logf("payload %d bytes; overrides on the wire %d of %d", len(payload), len(sent.Overrides), media.MaxOverrideBytes) |
| + if len(sent.Overrides) == 0 || len(sent.Overrides) > media.MaxOverrideBytes { |
| + t.Fatalf("the worst-case overrides are %d bytes, over %d", len(sent.Overrides), media.MaxOverrideBytes) |
| + } |
| +} |
| + |
| +func TestRunErrorsClassified(t *testing.T) { |
| + type want struct { |
| + rejected, retryable bool |
| + } |
| + failure := func(reason string) func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { |
| + return func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { |
| + return &ecs.RunTaskOutput{Failures: []ecstypes.Failure{{Reason: aws.String(reason)}}}, nil |
| + } |
| + } |
| + stubbed := map[string]struct { |
| + run func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) |
| + want want |
| + }{ |
| + "RESOURCE:CPU": {failure("RESOURCE:CPU"), want{true, true}}, |
| + "RESOURCE:MEMORY": {failure("RESOURCE:MEMORY"), want{true, true}}, |
| + "capacity": {failure("Capacity is unavailable at this time"), want{true, true}}, |
| + "other failure": {failure("MISSING"), want{true, false}}, |
| + "no task, no failure": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { return &ecs.RunTaskOutput{}, nil }, want{true, false}}, |
| + "modelled client": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { |
| + return nil, &ecstypes.InvalidParameterException{Message: aws.String("no")} |
| + }, want{true, false}}, |
| + "modelled server": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { |
| + return nil, &ecstypes.ServerException{Message: aws.String("no")} |
| + }, want{}}, |
| + "token already used": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { |
| + return nil, &ecstypes.ConflictException{Message: aws.String("no")} |
| + }, want{}}, |
| + "a timeout": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { return nil, context.DeadlineExceeded }, want{}}, |
| + "a transport error": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { return nil, errors.New("connection reset") }, want{}}, |
| + } |
| + check := func(t *testing.T, err error, w want) { |
| + t.Helper() |
| + var rej *media.Rejected |
| + if got := errors.As(err, &rej); got != w.rejected { |
| + t.Fatalf("rejected = %v (%v), want %v", got, err, w.rejected) |
| + } |
| + if err == nil { |
| + t.Fatal("no error") |
| + } |
| + if w.rejected && rej.Retryable != w.retryable { |
| + t.Fatalf("retryable = %v, want %v", rej.Retryable, w.retryable) |
| + } |
| + } |
| + for name, tc := range stubbed { |
| + t.Run(name, func(t *testing.T) { |
| + _, err := NewEngine(testConfig(), &stubECS{run: tc.run}).Run(context.Background(), runRequest()) |
| + check(t, err, tc.want) |
| + }) |
| + } |
| + // Through the real SDK: ECS does not model ThrottlingException, so it |
| + // reaches the adapter as an unmodelled error with an unknown fault. |
| + wire := map[string]struct { |
| + status int |
| + body string |
| + want want |
| + }{ |
| + "ThrottlingException": {400, `{"__type":"ThrottlingException","message":"Rate exceeded"}`, want{true, true}}, |
| + "InvalidParameterException": {400, `{"__type":"InvalidParameterException","message":"bad"}`, want{true, false}}, |
| + "AccessDeniedException": {400, `{"__type":"AccessDeniedException","message":"no"}`, want{true, false}}, |
| + "ClusterNotFoundException": {400, `{"__type":"ClusterNotFoundException","message":"no"}`, want{true, false}}, |
| + "ConflictException": {400, `{"__type":"ConflictException","message":"token in use"}`, want{}}, |
| + "an unmodelled client code": {400, `{"__type":"UnrecognizedClientException","message":"no"}`, want{true, false}}, |
| + "a request timeout": {408, `{"__type":"RequestTimeout","message":"slow"}`, want{}}, |
| + "a 409 of no known code": {409, `{"__type":"SomethingElse","message":"busy"}`, want{}}, |
| + "ServerException": {500, `{"__type":"ServerException","message":"oops"}`, want{}}, |
| + "an unnamed 503": {503, `<html>busy</html>`, want{}}, |
| + } |
| + for name, tc := range wire { |
| + t.Run("wire "+name, func(t *testing.T) { |
| + client := realECS(func(r *http.Request) (*http.Response, error) { |
| + return answer(r, tc.status, map[string]string{"Content-Type": "application/x-amz-json-1.1"}, tc.body), nil |
| + }) |
| + _, err := NewEngine(testConfig(), client).Run(context.Background(), runRequest()) |
| + check(t, err, tc.want) |
| + }) |
| + } |
| + t.Run("wire transport error", func(t *testing.T) { |
| + client := realECS(func(*http.Request) (*http.Response, error) { return nil, errors.New("connection reset") }) |
| + _, err := NewEngine(testConfig(), client).Run(context.Background(), runRequest()) |
| + check(t, err, want{}) |
| + }) |
| + t.Run("a timeout stays a timeout", func(t *testing.T) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + client := realECS(func(r *http.Request) (*http.Response, error) { return nil, r.Context().Err() }) |
| + _, err := NewEngine(testConfig(), client).Run(ctx, runRequest()) |
| + check(t, err, want{}) |
| + if !errors.Is(err, context.Canceled) { |
| + t.Fatalf("the context's error was lost: %v", err) |
| + } |
| + }) |
| + t.Run("an unknown class calls nothing", func(t *testing.T) { |
| + api := &stubECS{} |
| + req := runRequest() |
| + req.Class.Class = "huge" |
| + _, err := NewEngine(testConfig(), api).Run(context.Background(), req) |
| + check(t, err, want{true, false}) |
| + if len(api.runs) != 0 { |
| + t.Fatal("RunTask called for an unknown class") |
| + } |
| + }) |
| +} |
| + |
| +func ecsTask(arn, startedBy, status string, codec, deadline *int32) ecstypes.Task { |
| + return ecstypes.Task{TaskArn: aws.String(arn), StartedBy: aws.String(startedBy), LastStatus: aws.String(status), |
| + Containers: []ecstypes.Container{ |
| + {Name: aws.String(media.ContainerDeadline), ExitCode: deadline}, |
| + {Name: aws.String(media.ContainerCodec), ExitCode: codec}, |
| + }} |
| +} |
| + |
| +func TestDescribeBatchesAndMapsTasks(t *testing.T) { |
| + var arns []string |
| + for i := range 250 { |
| + arns = append(arns, fmt.Sprintf("arn:task/%d", i)) |
| + } |
| + started, stopped := time.Unix(100, 0), time.Unix(200, 0) |
| + api := &stubECS{describe: func(in *ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { |
| + out := &ecs.DescribeTasksOutput{} |
| + for _, a := range in.Tasks { |
| + switch a { |
| + case "arn:task/7": |
| + out.Failures = append(out.Failures, ecstypes.Failure{Arn: aws.String(a), Reason: aws.String("MISSING")}) |
| + case "arn:task/120": |
| + tk := ecsTask(a, testExec, "STOPPED", aws.Int32(75), aws.Int32(143)) |
| + tk.StartedAt, tk.StoppedAt, tk.StopCode = &started, &stopped, ecstypes.TaskStopCodeEssentialContainerExited |
| + out.Tasks = append(out.Tasks, tk) |
| + default: |
| + out.Tasks = append(out.Tasks, ecsTask(a, "x", "RUNNING", nil, nil)) |
| + } |
| + } |
| + return out, nil |
| + }} |
| + found, missing, err := NewEngine(testConfig(), api).Describe(context.Background(), arns) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(api.describes) != 3 || len(api.describes[0].Tasks) != 100 || len(api.describes[2].Tasks) != 50 { |
| + t.Fatalf("batches: %d", len(api.describes)) |
| + } |
| + if aws.ToString(api.describes[0].Cluster) != testConfig().Cluster { |
| + t.Fatal("no cluster on DescribeTasks") |
| + } |
| + if !slices.Equal(missing, []string{"arn:task/7"}) || len(found) != 249 { |
| + t.Fatalf("found %d, missing %v", len(found), missing) |
| + } |
| + i := slices.IndexFunc(found, func(x media.Task) bool { return x.ARN == "arn:task/120" }) |
| + got := found[i] |
| + if !got.Stopped || got.StartedBy != testExec || got.StopCode != "EssentialContainerExited" || |
| + !got.StartedAt.Equal(started) || !got.StoppedAt.Equal(stopped) || |
| + got.CodecExit == nil || *got.CodecExit != 75 || got.DeadlineExit == nil || *got.DeadlineExit != 143 { |
| + t.Fatalf("mapped task: %+v", got) |
| + } |
| + if r := found[0]; r.Stopped || r.CodecExit != nil || r.DeadlineExit != nil { |
| + t.Fatalf("a running task: %+v", r) |
| + } |
| + |
| + api.describe = func(*ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { |
| + return &ecs.DescribeTasksOutput{Failures: []ecstypes.Failure{{Arn: aws.String("arn:task/1"), Reason: aws.String("ACCESS_DENIED")}}}, nil |
| + } |
| + if _, _, err := NewEngine(testConfig(), api).Describe(context.Background(), []string{"arn:task/1"}); err == nil { |
| + t.Fatal("a failure other than MISSING was swallowed") |
| + } |
| +} |
| + |
| +func TestListByStartedByReadsBothLists(t *testing.T) { |
| + api := &stubECS{} |
| + api.list = func(in *ecs.ListTasksInput) (*ecs.ListTasksOutput, error) { |
| + switch { |
| + case in.DesiredStatus == ecstypes.DesiredStatusRunning: |
| + return &ecs.ListTasksOutput{}, nil |
| + case in.NextToken == nil: |
| + return &ecs.ListTasksOutput{TaskArns: []string{"arn:task/other"}, NextToken: aws.String("page2")}, nil |
| + default: |
| + return &ecs.ListTasksOutput{TaskArns: []string{"arn:task/mine"}}, nil |
| + } |
| + } |
| + api.describe = func(in *ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { |
| + if in.Tasks[0] == "arn:task/other" { |
| + // A listing that answers a task of another execution is not an |
| + // answer: only startedBy decides. |
| + return &ecs.DescribeTasksOutput{Tasks: []ecstypes.Task{ecsTask(in.Tasks[0], "another", "STOPPED", nil, nil)}}, nil |
| + } |
| + return &ecs.DescribeTasksOutput{Tasks: []ecstypes.Task{ecsTask(in.Tasks[0], testExec, "STOPPED", aws.Int32(0), aws.Int32(143))}}, nil |
| + } |
| + got, ok, err := NewEngine(testConfig(), api).ListByStartedBy(context.Background(), testExec) |
| + if err != nil || !ok || got.ARN != "arn:task/mine" { |
| + t.Fatalf("ListByStartedBy = %+v, %v, %v", got, ok, err) |
| + } |
| + var statuses []ecstypes.DesiredStatus |
| + for _, in := range api.lists { |
| + statuses = append(statuses, in.DesiredStatus) |
| + if aws.ToString(in.Cluster) != testConfig().Cluster || aws.ToString(in.StartedBy) != testExec { |
| + t.Fatalf("list input: %+v", in) |
| + } |
| + } |
| + if !slices.Equal(statuses, []ecstypes.DesiredStatus{ecstypes.DesiredStatusRunning, ecstypes.DesiredStatusStopped, ecstypes.DesiredStatusStopped}) { |
| + t.Fatalf("lists read: %v", statuses) |
| + } |
| + |
| + none := &stubECS{list: func(*ecs.ListTasksInput) (*ecs.ListTasksOutput, error) { return &ecs.ListTasksOutput{}, nil }} |
| + if _, ok, err := NewEngine(testConfig(), none).ListByStartedBy(context.Background(), testExec); ok || err != nil { |
| + t.Fatalf("an empty listing: %v, %v", ok, err) |
| + } |
| + if len(none.lists) != 2 { |
| + t.Fatalf("an empty listing read %d lists", len(none.lists)) |
| + } |
| +} |
| + |
| +func TestStopDecidesAMissingTaskByDescribingIt(t *testing.T) { |
| + invalid := func(*ecs.StopTaskInput) (*ecs.StopTaskOutput, error) { |
| + return nil, &ecstypes.InvalidParameterException{Message: aws.String("The referenced task was not found.")} |
| + } |
| + tests := map[string]struct { |
| + stop func(*ecs.StopTaskInput) (*ecs.StopTaskOutput, error) |
| + describe func(*ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) |
| + wantErr bool |
| + describs int |
| + }{ |
| + "stopped by the call": {stop: nil}, |
| + "missing": {stop: invalid, describs: 1, describe: func(in *ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { |
| + return &ecs.DescribeTasksOutput{Failures: []ecstypes.Failure{{Arn: aws.String(in.Tasks[0]), Reason: aws.String("MISSING")}}}, nil |
| + }}, |
| + "already stopped": {stop: invalid, describs: 1, describe: func(in *ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { |
| + return &ecs.DescribeTasksOutput{Tasks: []ecstypes.Task{ecsTask(in.Tasks[0], testExec, "STOPPED", nil, nil)}}, nil |
| + }}, |
| + "still running": {stop: invalid, describs: 1, wantErr: true, describe: func(in *ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { |
| + return &ecs.DescribeTasksOutput{Tasks: []ecstypes.Task{ecsTask(in.Tasks[0], testExec, "RUNNING", nil, nil)}}, nil |
| + }}, |
| + "describe fails": {stop: invalid, describs: 1, wantErr: true, describe: func(*ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { |
| + return nil, errors.New("reset") |
| + }}, |
| + "another error is not looked into": {wantErr: true, stop: func(*ecs.StopTaskInput) (*ecs.StopTaskOutput, error) { |
| + return nil, &ecstypes.ServerException{Message: aws.String("The referenced task was not found.")} |
| + }}, |
| + } |
| + for name, tc := range tests { |
| + t.Run(name, func(t *testing.T) { |
| + api := &stubECS{stop: tc.stop, describe: tc.describe} |
| + err := NewEngine(testConfig(), api).Stop(context.Background(), "arn:task/1", "media job retired") |
| + if (err != nil) != tc.wantErr { |
| + t.Fatalf("Stop = %v, want error %v", err, tc.wantErr) |
| + } |
| + if len(api.describes) != tc.describs { |
| + t.Fatalf("described %d times, want %d", len(api.describes), tc.describs) |
| + } |
| + in := api.stops[0] |
| + if aws.ToString(in.Cluster) != testConfig().Cluster || aws.ToString(in.Task) != "arn:task/1" || aws.ToString(in.Reason) != "media job retired" { |
| + t.Fatalf("StopTask input: %+v", in) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// goodContainers are the two containers of a revision the gate accepts. |
| +func goodContainers() []ecstypes.ContainerDefinition { |
| + image := "123456789012.dkr.ecr.eu-west-1.amazonaws.com/media@sha256:" + strings.Repeat("a", 64) |
| + base := func(name, command string) ecstypes.ContainerDefinition { |
| + return ecstypes.ContainerDefinition{ |
| + Name: aws.String(name), Image: aws.String(image), User: aws.String("65534:65534"), |
| + Essential: aws.Bool(true), ReadonlyRootFilesystem: aws.Bool(true), StopTimeout: aws.Int32(30), |
| + EntryPoint: []string{media.EngineEntryPoint}, Command: []string{command}, |
| + LinuxParameters: &ecstypes.LinuxParameters{Capabilities: &ecstypes.KernelCapabilities{Drop: []string{"ALL"}}}, |
| + } |
| + } |
| + codec := base(media.ContainerCodec, media.CodecCommand) |
| + codec.DependsOn = []ecstypes.ContainerDependency{{ContainerName: aws.String(media.ContainerDeadline), Condition: ecstypes.ContainerConditionStart}} |
| + codec.MountPoints = []ecstypes.MountPoint{{SourceVolume: aws.String("scratch"), ContainerPath: aws.String("/scratch")}} |
| + return []ecstypes.ContainerDefinition{base(media.ContainerDeadline, media.DeadlineCommand), codec} |
| +} |
| + |
| +func goodRevision(arn string) *ecstypes.TaskDefinition { |
| + return &ecstypes.TaskDefinition{TaskDefinitionArn: aws.String(arn), |
| + RuntimePlatform: &ecstypes.RuntimePlatform{CpuArchitecture: ecstypes.CPUArchitectureArm64}, |
| + ContainerDefinitions: goodContainers()} |
| +} |
| + |
| +func revisionStub(td func(string) *ecstypes.TaskDefinition) *stubECS { |
| + return &stubECS{taskDef: func(in *ecs.DescribeTaskDefinitionInput) (*ecs.DescribeTaskDefinitionOutput, error) { |
| + return &ecs.DescribeTaskDefinitionOutput{TaskDefinition: td(aws.ToString(in.TaskDefinition))}, nil |
| + }} |
| +} |
| + |
| +func TestCheckRevisionCachesPerRevision(t *testing.T) { |
| + class := media.ClassKey{Preset: media.PresetVideo720p, Class: media.ClassShort} |
| + c := testConfig() |
| + api := revisionStub(goodRevision) |
| + e := NewEngine(c, api) |
| + for range 3 { |
| + if err := e.CheckRevision(context.Background(), class); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if len(api.revisions) != 1 || api.revisions[0] != c.TaskDefinitions[class.String()] { |
| + t.Fatalf("revisions read: %v", api.revisions) |
| + } |
| + other := media.ClassKey{Preset: media.PresetAudioAAC, Class: media.ClassLong} |
| + if err := e.CheckRevision(context.Background(), other); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(api.revisions) != 2 { |
| + t.Fatalf("a second revision was answered from the first's verdict: %v", api.revisions) |
| + } |
| + |
| + // A refusal is a verdict on that revision, cached like a pass. |
| + refused := revisionStub(func(arn string) *ecstypes.TaskDefinition { |
| + td := goodRevision(arn) |
| + td.TaskRoleArn = aws.String("arn:aws:iam::123456789012:role/x") |
| + return td |
| + }) |
| + e = NewEngine(c, refused) |
| + for range 2 { |
| + var m *media.Misconfigured |
| + err := e.CheckRevision(context.Background(), class) |
| + if !errors.As(err, &m) || m.Check != "task_role" || m.Revision != c.TaskDefinitions[class.String()] { |
| + t.Fatalf("CheckRevision = %v", err) |
| + } |
| + } |
| + if len(refused.revisions) != 1 { |
| + t.Fatalf("a refusal was not cached: %d reads", len(refused.revisions)) |
| + } |
| + |
| + // A failed read is no verdict: it is not cached and never *Misconfigured. |
| + calls := 0 |
| + flaky := &stubECS{taskDef: func(in *ecs.DescribeTaskDefinitionInput) (*ecs.DescribeTaskDefinitionOutput, error) { |
| + calls++ |
| + if calls == 1 { |
| + return nil, errors.New("reset") |
| + } |
| + return &ecs.DescribeTaskDefinitionOutput{TaskDefinition: goodRevision(aws.ToString(in.TaskDefinition))}, nil |
| + }} |
| + e = NewEngine(c, flaky) |
| + var m *media.Misconfigured |
| + if err := e.CheckRevision(context.Background(), class); err == nil || errors.As(err, &m) { |
| + t.Fatalf("a failed read answered %v", err) |
| + } |
| + if err := e.CheckRevision(context.Background(), class); err != nil || calls != 2 { |
| + t.Fatalf("after a failed read: %v, %d calls", err, calls) |
| + } |
| + |
| + // ECS answering for another revision is no verdict on this one. |
| + wrong := revisionStub(func(string) *ecstypes.TaskDefinition { return goodRevision(revisionARN("somewhere-else", 9)) }) |
| + e = NewEngine(c, wrong) |
| + if err := e.CheckRevision(context.Background(), class); err == nil { |
| + t.Fatal("an answer about another revision passed the gate") |
| + } |
| + if err := e.CheckRevision(context.Background(), class); err == nil || len(wrong.revisions) != 2 { |
| + t.Fatalf("an answer about another revision was cached: %v, %d reads", err, len(wrong.revisions)) |
| + } |
| +} |
| + |
| +func TestCheckRevisionFill(t *testing.T) { |
| + const arn = "arn:aws:ecs:eu-west-1:123456789012:task-definition/media:3" |
| + find := func(td media.TaskDefinition, name string) media.ContainerDef { |
| + for _, c := range td.Containers { |
| + if c.Name == name { |
| + return c |
| + } |
| + } |
| + t.Fatalf("no container %s", name) |
| + return media.ContainerDef{} |
| + } |
| + good := taskDefinition(goodRevision(arn)) |
| + if err := media.CheckTaskDefinition(good); err != nil { |
| + t.Fatalf("the good revision is refused: %v", err) |
| + } |
| + d := find(good, media.ContainerDeadline) |
| + if !slices.Equal(d.EntryPoint, []string{media.EngineEntryPoint}) || !slices.Equal(d.Command, []string{media.DeadlineCommand}) || |
| + d.User != "65534:65534" || !d.Essential || !d.ReadOnlyRoot || !d.DropsAll || d.RestartPolicy || d.StopTimeout == nil || *d.StopTimeout != 30 { |
| + t.Fatalf("deadline fill: %+v", d) |
| + } |
| + c := find(good, media.ContainerCodec) |
| + if !slices.Equal(c.Volumes, []string{"scratch"}) || !reflect.DeepEqual(c.DependsOn, []media.Dependency{{Container: media.ContainerDeadline, Condition: "START"}}) { |
| + t.Fatalf("codec fill: %+v", c) |
| + } |
| + if good.ARN != arn || good.CPUArchitecture != "ARM64" || good.TaskRoleARN != "" || good.PIDMode != "" { |
| + t.Fatalf("task fill: %+v", good) |
| + } |
| + |
| + unset := taskDefinition(&ecstypes.TaskDefinition{ContainerDefinitions: []ecstypes.ContainerDefinition{{Name: aws.String("x")}}}) |
| + if u := unset.Containers[0]; u.EntryPoint != nil || u.Command != nil || u.StopTimeout != nil || u.Essential || u.DropsAll || u.Volumes != nil { |
| + t.Fatalf("unset fields must stay unset: %+v", u) |
| + } |
| + |
| + refusals := map[string]struct { |
| + edit func(*ecstypes.TaskDefinition, *ecstypes.ContainerDefinition, *ecstypes.ContainerDefinition) |
| + check string |
| + }{ |
| + "capabilities added to deadline": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { |
| + d.LinuxParameters.Capabilities.Add = []string{"SYS_PTRACE"} |
| + }, "capabilities"}, |
| + "capabilities added to codec": {func(_ *ecstypes.TaskDefinition, _, c *ecstypes.ContainerDefinition) { |
| + c.LinuxParameters.Capabilities.Add = []string{"KILL"} |
| + }, "capabilities"}, |
| + "drop list without ALL": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { |
| + d.LinuxParameters.Capabilities.Drop = []string{"KILL"} |
| + }, "capabilities"}, |
| + "no linux parameters": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { d.LinuxParameters = nil }, "capabilities"}, |
| + "deadline mounts a volume": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { |
| + d.MountPoints = []ecstypes.MountPoint{{SourceVolume: aws.String("scratch")}} |
| + }, "shared_volume"}, |
| + "deadline borrows codec's volumes": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { |
| + d.VolumesFrom = []ecstypes.VolumeFrom{{SourceContainer: aws.String(media.ContainerCodec)}} |
| + }, "shared_volume"}, |
| + "deadline borrows from a container with no named volume": {func(_ *ecstypes.TaskDefinition, d, c *ecstypes.ContainerDefinition) { |
| + c.MountPoints = nil |
| + d.VolumesFrom = []ecstypes.VolumeFrom{{SourceContainer: aws.String(media.ContainerCodec)}} |
| + }, "shared_volume"}, |
| + "deadline borrows from a container that is not there": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { |
| + d.VolumesFrom = []ecstypes.VolumeFrom{{SourceContainer: aws.String("ghost")}} |
| + }, "shared_volume"}, |
| + "deadline restarts": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { |
| + d.RestartPolicy = &ecstypes.ContainerRestartPolicy{Enabled: aws.Bool(true)} |
| + }, "restart_policy"}, |
| + "codec restarts": {func(_ *ecstypes.TaskDefinition, _, c *ecstypes.ContainerDefinition) { |
| + c.RestartPolicy = &ecstypes.ContainerRestartPolicy{Enabled: aws.Bool(true)} |
| + }, "restart_policy"}, |
| + "no command": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) { d.Command = nil }, "command"}, |
| + "no entry point": {func(_ *ecstypes.TaskDefinition, _, c *ecstypes.ContainerDefinition) { c.EntryPoint = nil }, "command"}, |
| + "pid mode": {func(td *ecstypes.TaskDefinition, _, _ *ecstypes.ContainerDefinition) { |
| + td.PidMode = ecstypes.PidModeTask |
| + }, "pid_mode"}, |
| + "x86": {func(td *ecstypes.TaskDefinition, _, _ *ecstypes.ContainerDefinition) { |
| + td.RuntimePlatform.CpuArchitecture = ecstypes.CPUArchitectureX8664 |
| + }, "arm64"}, |
| + "no runtime platform": {func(td *ecstypes.TaskDefinition, _, _ *ecstypes.ContainerDefinition) { td.RuntimePlatform = nil }, "arm64"}, |
| + } |
| + for name, tc := range refusals { |
| + t.Run(name, func(t *testing.T) { |
| + td := goodRevision(arn) |
| + tc.edit(td, &td.ContainerDefinitions[0], &td.ContainerDefinitions[1]) |
| + var m *media.Misconfigured |
| + if err := media.CheckTaskDefinition(taskDefinition(td)); !errors.As(err, &m) || m.Check != tc.check { |
| + t.Fatalf("gate = %v, want check %s", err, tc.check) |
| + } |
| + }) |
| + } |
| + |
| + t.Run("volumesFrom is followed through a chain and a cycle", func(t *testing.T) { |
| + td := &ecstypes.TaskDefinition{ContainerDefinitions: []ecstypes.ContainerDefinition{ |
| + {Name: aws.String("a"), VolumesFrom: []ecstypes.VolumeFrom{{SourceContainer: aws.String("b")}}}, |
| + {Name: aws.String("b"), VolumesFrom: []ecstypes.VolumeFrom{{SourceContainer: aws.String("c")}}, MountPoints: []ecstypes.MountPoint{{SourceVolume: aws.String("vb")}}}, |
| + {Name: aws.String("c"), VolumesFrom: []ecstypes.VolumeFrom{{SourceContainer: aws.String("a")}}, MountPoints: []ecstypes.MountPoint{{SourceVolume: aws.String("vc")}}}, |
| + }} |
| + if got := taskDefinition(td).Containers[0].Volumes; !slices.Equal(got, []string{"vb", "vc"}) { |
| + t.Fatalf("volumes = %v", got) |
| + } |
| + }) |
| +} |
| + |
| +func TestGrantSessionPolicy(t *testing.T) { |
| + var session, policy string |
| + assume := func(_ context.Context, s, p string) (aws.Credentials, error) { |
| + session, policy = s, p |
| + return sessionCreds(time.Now().Add(time.Hour)), nil |
| + } |
| + if _, _, err := NewGrants(testConfig(), assume, &stubS3{}).Grant(context.Background(), grantRequest()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if session != "media-"+testExec { |
| + t.Fatalf("session name = %q", session) |
| + } |
| + want := `{"Version":"2012-10-17","Statement":[` + |
| + `{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::carlos-store-abc/*"},` + |
| + `{"Effect":"Allow","Action":"s3:PutObject","Resource":["arn:aws:s3:::carlos-store-abc/derived/*",` + |
| + `"arn:aws:s3:::carlos-deployment-results/media-results/` + testExec + `.json"]}]}` |
| + if policy != want { |
| + t.Fatalf("session policy:\n got %s\nwant %s", policy, want) |
| + } |
| +} |
| + |
| +func TestAssumeRoleAsksForOneHour(t *testing.T) { |
| + expires := time.Now().Add(time.Hour).UTC().Truncate(time.Second) |
| + api := &stubSTS{out: &sts.AssumeRoleOutput{Credentials: &ststypes.Credentials{ |
| + AccessKeyId: aws.String("ASIAEXAMPLE"), SecretAccessKey: aws.String("s"), SessionToken: aws.String("t"), Expiration: &expires}}} |
| + creds, err := assumeRole(api, "arn:aws:iam::123456789012:role/media")(context.Background(), "media-x", `{"p":1}`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !creds.CanExpire || !creds.Expires.Equal(expires) || creds.SessionToken != "t" { |
| + t.Fatalf("credentials: %+v", creds) |
| + } |
| + in := api.in |
| + if aws.ToString(in.RoleArn) != "arn:aws:iam::123456789012:role/media" || aws.ToString(in.RoleSessionName) != "media-x" || |
| + aws.ToInt32(in.DurationSeconds) != 3600 || aws.ToString(in.Policy) != `{"p":1}` { |
| + t.Fatalf("AssumeRole input: %+v", in) |
| + } |
| + api.out = &sts.AssumeRoleOutput{} |
| + if _, err := assumeRole(api, "r")(context.Background(), "s", "p"); err == nil { |
| + t.Fatal("an answer with no credentials was accepted") |
| + } |
| +} |
| + |
| +type stubSTS struct { |
| + in *sts.AssumeRoleInput |
| + out *sts.AssumeRoleOutput |
| + err error |
| +} |
| + |
| +func (s *stubSTS) AssumeRole(_ context.Context, in *sts.AssumeRoleInput, _ ...func(*sts.Options)) (*sts.AssumeRoleOutput, error) { |
| + s.in = in |
| + return s.out, s.err |
| +} |
| + |
| +func queryOf(t *testing.T, raw string) url.Values { |
| + t.Helper() |
| + q, err := url.ParseQuery(raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return q |
| +} |
| + |
| +func TestGrantTransfersShareOneCredential(t *testing.T) { |
| + expires := time.Now().Add(50 * time.Minute).UTC().Truncate(time.Second) |
| + r := grantRequest() |
| + tr, expiry, err := NewGrants(testConfig(), staticAssume(expires), &stubS3{}).Grant(context.Background(), r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !expiry.Equal(expires) { |
| + t.Fatalf("expiry = %s, want the credentials' %s", expiry, expires) |
| + } |
| + shared := queryOf(t, tr.Shared) |
| + if len(shared) != 4 || shared.Get("X-Amz-Expires") != "3600" || shared.Get("X-Amz-Security-Token") != testToken || |
| + shared.Get("X-Amz-Algorithm") != "AWS4-HMAC-SHA256" || !strings.HasPrefix(shared.Get("X-Amz-Credential"), "ASIAEXAMPLEEXAMPLE12/") { |
| + t.Fatalf("shared: %v", shared) |
| + } |
| + all := append([]media.Transfer{tr.Source, tr.Result}, tr.Outputs...) |
| + for _, x := range all { |
| + q := queryOf(t, x.Query) |
| + for name := range shared { |
| + if q.Has(name) { |
| + t.Errorf("%s is repeated in a transfer's own query", name) |
| + } |
| + } |
| + if q.Get("X-Amz-Signature") == "" || q.Get("X-Amz-Date") == "" || q.Get("X-Amz-SignedHeaders") == "" || q.Get("x-id") == "" { |
| + t.Errorf("a transfer's query is missing its own parameters: %v", q) |
| + } |
| + for name := range q { |
| + if strings.HasPrefix(strings.ToLower(name), "x-amz-checksum") || strings.ToLower(name) == "x-amz-sdk-checksum-algorithm" { |
| + t.Errorf("a checksum parameter is signed into the transfer: %s", name) |
| + } |
| + } |
| + if _, ok := x.Header["Host"]; ok { |
| + t.Error("Host is in a transfer's headers") |
| + } |
| + } |
| + |
| + if tr.Source.Method != "GET" || tr.Source.Header["If-Match"] != `"`+r.SourceETag+`"` || len(tr.Source.Header) != 1 { |
| + t.Fatalf("source: %+v", tr.Source) |
| + } |
| + if got := queryOf(t, tr.Source.Query).Get("X-Amz-SignedHeaders"); got != "host;if-match" { |
| + t.Fatalf("source signs %q", got) |
| + } |
| + wantBase := "https://" + testBucket + ".s3." + testRegion + ".amazonaws.com/uploads/a%20b%2Bc/%C3%A9.mov" |
| + if tr.Source.URL != wantBase { |
| + t.Fatalf("source base = %q", tr.Source.URL) |
| + } |
| + if len(tr.Outputs) != 3 { |
| + t.Fatalf("outputs: %d", len(tr.Outputs)) |
| + } |
| + if !strings.HasPrefix(tr.OutPrefix, "https://"+testBucket+".s3."+testRegion+".amazonaws.com/derived/uploads/a%20b%2Bc/%C3%A9.mov/") || !strings.HasSuffix(tr.OutPrefix, "/"+testExec+"/") { |
| + t.Fatalf("output prefix = %q", tr.OutPrefix) |
| + } |
| + for i, o := range tr.Outputs { |
| + if o.URL != "" || o.Method != "PUT" || o.Name != r.Outputs[i].Name { |
| + t.Fatalf("output %d: %+v", i, o) |
| + } |
| + want := map[string]string{"Content-Type": media.ContentType(o.Name), "If-None-Match": "*"} |
| + if !reflect.DeepEqual(o.Header, want) { |
| + t.Fatalf("output %s headers: %v", o.Name, o.Header) |
| + } |
| + if got := queryOf(t, o.Query).Get("X-Amz-SignedHeaders"); got != "content-type;host;if-none-match" { |
| + t.Fatalf("output %s signs %q", o.Name, got) |
| + } |
| + } |
| + res := tr.Result |
| + if res.Method != "PUT" || res.URL != "https://"+testResults+".s3."+testRegion+".amazonaws.com/media-results/"+testExec+".json" || |
| + !reflect.DeepEqual(res.Header, map[string]string{"Content-Type": "application/json", "If-None-Match": "*"}) { |
| + t.Fatalf("result: %+v", res) |
| + } |
| + payload := media.Payload{V: 1, Execution: testExec, Preset: media.PresetVideo720p, Transfers: tr} |
| + if err := payload.Validate(); err != nil { |
| + t.Fatalf("the transfers do not make a valid payload: %v", err) |
| + } |
| +} |
| + |
| +func TestGrantPathStyleOnlyForADottedBucket(t *testing.T) { |
| + r := grantRequest() |
| + r.Bucket = "carlos.store.abc" |
| + c := testConfig() |
| + c.ResultsBucket = "results.with.dots" |
| + tr, _, err := NewGrants(c, staticAssume(time.Now().Add(time.Hour)), &stubS3{}).Grant(context.Background(), r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasPrefix(tr.Source.URL, "https://s3."+testRegion+".amazonaws.com/carlos.store.abc/uploads/") { |
| + t.Fatalf("source base = %q", tr.Source.URL) |
| + } |
| + if tr.Result.URL != "https://s3."+testRegion+".amazonaws.com/results.with.dots/media-results/"+testExec+".json" { |
| + t.Fatalf("result base = %q", tr.Result.URL) |
| + } |
| + // Each bucket chooses for itself: the dotted store does not move an |
| + // undotted results bucket onto a path. |
| + c = testConfig() |
| + tr, _, err = NewGrants(c, staticAssume(time.Now().Add(time.Hour)), &stubS3{}).Grant(context.Background(), r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasPrefix(tr.Result.URL, "https://"+testResults+".s3.") { |
| + t.Fatalf("result base = %q", tr.Result.URL) |
| + } |
| +} |
| + |
| +// fakePresigner signs nothing: it answers a presigned URL of the right |
| +// shape, with the headers the request asked to be signed. |
| +func fakePresigner(mutate func(call int, r presignRequest, p *v4.PresignedHTTPRequest)) (presignFunc, *atomic.Int32) { |
| + var calls atomic.Int32 |
| + return func(_ context.Context, _ aws.Credentials, r presignRequest) (*v4.PresignedHTTPRequest, error) { |
| + n := int(calls.Add(1)) |
| + h := http.Header{"Host": {"example"}} |
| + signed := "host" |
| + if r.IfMatch != "" { |
| + h.Set("If-Match", r.IfMatch) |
| + signed += "%3Bif-match" |
| + } |
| + if r.IfNoneMatch != "" { |
| + h.Set("If-None-Match", r.IfNoneMatch) |
| + signed = "content-type%3B" + signed + "%3Bif-none-match" |
| + } |
| + if r.ContentType != "" { |
| + h.Set("Content-Type", r.ContentType) |
| + } |
| + p := &v4.PresignedHTTPRequest{Method: r.Method, SignedHeader: h, |
| + URL: "https://" + r.Bucket + ".s3.test/" + url.PathEscape(r.Key) + |
| + "?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAFAKE%2F20261118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Date=20261118T000000Z" + |
| + "&X-Amz-Expires=3600&X-Amz-Security-Token=tok&X-Amz-SignedHeaders=" + signed + "&x-id=Op&X-Amz-Signature=abc"} |
| + p.URL = strings.ReplaceAll(p.URL, "%2F", "/") |
| + p.URL = strings.Replace(p.URL, "ASIAFAKE/20261118/eu-west-1/s3/aws4_request", "ASIAFAKE%2F20261118%2Feu-west-1%2Fs3%2Faws4_request", 1) |
| + if mutate != nil { |
| + mutate(n, r, p) |
| + } |
| + return p, nil |
| + }, &calls |
| +} |
| + |
| +func TestGrantPresignsOnceMoreWhenTheCredentialScopeMoves(t *testing.T) { |
| + expires := time.Now().Add(time.Hour) |
| + // The first round crosses midnight on its last transfer; the second |
| + // round is all on one day. |
| + f, calls := fakePresigner(func(n int, _ presignRequest, p *v4.PresignedHTTPRequest) { |
| + if n == 5 { |
| + p.URL = strings.Replace(p.URL, "20261118%2F", "20261119%2F", 1) |
| + } |
| + }) |
| + tr, _, err := NewGrants(testConfig(), staticAssume(expires), &stubS3{}, withPresigner(f)).Grant(context.Background(), grantRequest()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if calls.Load() != 10 { |
| + t.Fatalf("presigned %d times, want two rounds of five", calls.Load()) |
| + } |
| + if strings.Contains(tr.Shared, "20261119") { |
| + t.Fatalf("the shared parameters came from the failed round: %s", tr.Shared) |
| + } |
| + |
| + always, calls := fakePresigner(func(n int, _ presignRequest, p *v4.PresignedHTTPRequest) { |
| + if n%5 == 0 { |
| + p.URL = strings.Replace(p.URL, "20261118%2F", "20261119%2F", 1) |
| + } |
| + }) |
| + if _, _, err := NewGrants(testConfig(), staticAssume(expires), &stubS3{}, withPresigner(always)).Grant(context.Background(), grantRequest()); err == nil { |
| + t.Fatal("transfers that never share one credential were granted") |
| + } |
| + if calls.Load() != 10 { |
| + t.Fatalf("presigned %d times, want exactly one more round", calls.Load()) |
| + } |
| +} |
| + |
| +func TestGrantRefusesWhatItCannotStandBehind(t *testing.T) { |
| + expires := time.Now().Add(time.Hour) |
| + mutated := func(f func(presignRequest, *v4.PresignedHTTPRequest)) presignFunc { |
| + p, _ := fakePresigner(func(_ int, r presignRequest, p *v4.PresignedHTTPRequest) { f(r, p) }) |
| + return p |
| + } |
| + presigners := map[string]presignFunc{ |
| + "If-Match left unsigned": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { p.SignedHeader.Del("If-Match") }), |
| + "If-Match signed with another value": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { |
| + if r.IfMatch != "" { |
| + p.SignedHeader.Set("If-Match", `"other"`) |
| + } |
| + }), |
| + "If-Match sent but outside the signature": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { |
| + p.URL = strings.Replace(p.URL, "%3Bif-match", "", 1) |
| + }), |
| + "If-None-Match sent but outside the signature": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { |
| + p.URL = strings.Replace(p.URL, "%3Bif-none-match", "", 1) |
| + }), |
| + "Content-Type sent but outside the signature": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { |
| + p.URL = strings.Replace(p.URL, "content-type%3B", "", 1) |
| + }), |
| + "If-None-Match left unsigned": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { p.SignedHeader.Del("If-None-Match") }), |
| + "Content-Type left unsigned": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { p.SignedHeader.Del("Content-Type") }), |
| + "If-Match signed twice": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { |
| + if r.IfMatch != "" { |
| + p.SignedHeader["If-Match"] = []string{r.IfMatch, `"other"`} |
| + } |
| + }), |
| + "a header with two values": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { p.SignedHeader["X-Extra"] = []string{"a", "b"} }), |
| + "another method": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { p.Method = "POST" }), |
| + "an output off the prefix": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { |
| + if strings.HasSuffix(r.Key, "poster.jpg") { |
| + p.URL = strings.Replace(p.URL, "poster.jpg", "elsewhere/poster.jpg", 1) |
| + } |
| + }), |
| + "no session token": mutated(func(r presignRequest, p *v4.PresignedHTTPRequest) { |
| + p.URL = strings.Replace(p.URL, "&X-Amz-Security-Token=tok", "", 1) |
| + }), |
| + } |
| + for name, f := range presigners { |
| + t.Run(name, func(t *testing.T) { |
| + if _, _, err := NewGrants(testConfig(), staticAssume(expires), &stubS3{}, withPresigner(f)).Grant(context.Background(), grantRequest()); err == nil { |
| + t.Fatal("granted") |
| + } |
| + }) |
| + } |
| + |
| + requests := map[string]func(*media.GrantRequest){ |
| + "a bucket that is a wildcard": func(r *media.GrantRequest) { r.Bucket = "carlos-*" }, |
| + "a bucket with a quote": func(r *media.GrantRequest) { r.Bucket = `carlos"x` }, |
| + "an empty bucket": func(r *media.GrantRequest) { r.Bucket = "" }, |
| + "a short execution": func(r *media.GrantRequest) { r.Execution = "abc" }, |
| + "an execution with a wildcard": func(r *media.GrantRequest) { r.Execution = strings.Repeat("*", 32) }, |
| + "an invalid source key": func(r *media.GrantRequest) { r.SourceKey = "derived/x" }, |
| + "an ETag with a quote": func(r *media.GrantRequest) { r.SourceETag = `abc"def` }, |
| + "no ETag": func(r *media.GrantRequest) { r.SourceETag = "" }, |
| + "a prefix outside derived": func(r *media.GrantRequest) { r.OutputPrefix = "uploads/x/" }, |
| + "a prefix with no slash": func(r *media.GrantRequest) { r.OutputPrefix = "derived/x" }, |
| + "two outputs": func(r *media.GrantRequest) { r.Outputs = r.Outputs[:2] }, |
| + "an output that is no output": func(r *media.GrantRequest) { r.Outputs[0].Name = "evil.html" }, |
| + "the wrong content type": func(r *media.GrantRequest) { r.Outputs[0].ContentType = "text/html" }, |
| + } |
| + for name, edit := range requests { |
| + t.Run(name, func(t *testing.T) { |
| + assumed := false |
| + assume := func(context.Context, string, string) (aws.Credentials, error) { |
| + assumed = true |
| + return sessionCreds(expires), nil |
| + } |
| + r := grantRequest() |
| + edit(&r) |
| + if _, _, err := NewGrants(testConfig(), assume, &stubS3{}).Grant(context.Background(), r); err == nil { |
| + t.Fatal("granted") |
| + } |
| + if assumed { |
| + t.Fatal("the role was assumed for a request that is refused") |
| + } |
| + }) |
| + } |
| + |
| + t.Run("credentials that never expire", func(t *testing.T) { |
| + assume := func(context.Context, string, string) (aws.Credentials, error) { |
| + return aws.Credentials{AccessKeyID: "AKIA", SecretAccessKey: "s", SessionToken: "t"}, nil |
| + } |
| + if _, _, err := NewGrants(testConfig(), assume, &stubS3{}).Grant(context.Background(), grantRequest()); err == nil { |
| + t.Fatal("granted with no expiry") |
| + } |
| + }) |
| +} |
| + |
| +// headWorld is S3 as a role without s3:ListBucket sees it: the console's |
| +// own client lists, the conversion session gets 403 for an absent key. |
| +type headWorld struct { |
| + objects map[string]string // key → ETag |
| + denied map[string]bool |
| + listErr int |
| +} |
| + |
| +func (w *headWorld) console() *s3.Client { |
| + return realS3(func(r *http.Request) (*http.Response, error) { |
| + if w.listErr != 0 { |
| + return answer(r, w.listErr, map[string]string{"Content-Type": "application/xml"}, `<Error><Code>InternalError</Code><Message>no</Message></Error>`), nil |
| + } |
| + prefix := r.URL.Query().Get("prefix") |
| + var match []string |
| + for k := range w.objects { |
| + if strings.HasPrefix(k, prefix) { |
| + match = append(match, k) |
| + } |
| + } |
| + slices.Sort(match) |
| + body := `<?xml version="1.0"?><ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><IsTruncated>false</IsTruncated>` |
| + if len(match) > 0 { |
| + body += `<Contents><Key>` + url.QueryEscape(match[0]) + `</Key></Contents>` |
| + } |
| + return answer(r, 200, map[string]string{"Content-Type": "application/xml"}, body+`</ListBucketResult>`), nil |
| + }) |
| +} |
| + |
| +func (w *headWorld) session() *s3.Client { |
| + return realS3(func(r *http.Request) (*http.Response, error) { |
| + key, _ := url.PathUnescape(strings.TrimPrefix(r.URL.EscapedPath(), "/"+testBucket+"/")) |
| + etag, ok := w.objects[key] |
| + if !ok || w.denied[key] { |
| + return answer(r, 403, nil, ""), nil |
| + } |
| + return answer(r, 200, map[string]string{"ETag": `"` + etag + `"`, "Content-Length": "1234"}, ""), nil |
| + }) |
| +} |
| + |
| +func TestHeadClassifiesErrors(t *testing.T) { |
| + const key = "uploads/a b+c/é.mov" |
| + w := &headWorld{ |
| + objects: map[string]string{key: "abc123", "uploads/infected": "bad", "uploads/near-miss.bak": "x"}, |
| + denied: map[string]bool{"uploads/infected": true}, |
| + } |
| + var assumed atomic.Int32 |
| + assume := func(context.Context, string, string) (aws.Credentials, error) { |
| + assumed.Add(1) |
| + return sessionCreds(time.Now().Add(time.Hour)), nil |
| + } |
| + g := NewGrants(testConfig(), assume, w.console(), withSessionS3(func(aws.Credentials, string) S3API { return w.session() })) |
| + |
| + h, err := g.Head(context.Background(), testBucket, key) |
| + if err != nil || h.ETag != "abc123" || h.Size != 1234 { |
| + t.Fatalf("Head = %+v, %v", h, err) |
| + } |
| + if _, err := g.Head(context.Background(), testBucket, "uploads/infected"); !errors.Is(err, media.ErrDenied) { |
| + t.Fatalf("a listed but denied object: %v", err) |
| + } |
| + before := assumed.Load() |
| + if _, err := g.Head(context.Background(), testBucket, "uploads/absent"); !errors.Is(err, media.ErrNotFound) { |
| + t.Fatalf("an absent key: %v", err) |
| + } |
| + if _, err := g.Head(context.Background(), testBucket, "uploads/near-miss"); !errors.Is(err, media.ErrNotFound) { |
| + t.Fatalf("a key that is only a prefix of another: %v", err) |
| + } |
| + if assumed.Load() != before { |
| + t.Fatal("the conversion role was asked about a key the listing already answered") |
| + } |
| + |
| + // Deleted between the listing and the HEAD: the conversion session has |
| + // no ListBucket, so S3 answers 403. |
| + raced := &headWorld{objects: map[string]string{"uploads/gone": "x"}} |
| + g = NewGrants(testConfig(), assume, raced.console(), withSessionS3(func(aws.Credentials, string) S3API { |
| + return (&headWorld{objects: map[string]string{}}).session() |
| + })) |
| + if _, err := g.Head(context.Background(), testBucket, "uploads/gone"); !errors.Is(err, media.ErrDenied) { |
| + t.Fatalf("an object deleted in between: %v", err) |
| + } |
| + |
| + // A listing that fails decides nothing. |
| + failing := &headWorld{listErr: 500} |
| + g = NewGrants(testConfig(), assume, failing.console(), withSessionS3(func(aws.Credentials, string) S3API { return w.session() })) |
| + _, err = g.Head(context.Background(), testBucket, key) |
| + if err == nil || errors.Is(err, media.ErrNotFound) || errors.Is(err, media.ErrDenied) { |
| + t.Fatalf("a failed listing: %v", err) |
| + } |
| + |
| + // The session's own answers, by status. |
| + for status, want := range map[int]error{404: media.ErrNotFound, 403: media.ErrDenied} { |
| + session := realS3(func(r *http.Request) (*http.Response, error) { return answer(r, status, nil, ""), nil }) |
| + g = NewGrants(testConfig(), assume, w.console(), withSessionS3(func(aws.Credentials, string) S3API { return session })) |
| + if _, err := g.Head(context.Background(), testBucket, key); !errors.Is(err, want) { |
| + t.Fatalf("HEAD %d: %v", status, err) |
| + } |
| + } |
| + session := realS3(func(r *http.Request) (*http.Response, error) { return answer(r, 500, nil, ""), nil }) |
| + g = NewGrants(testConfig(), assume, w.console(), withSessionS3(func(aws.Credentials, string) S3API { return session })) |
| + if _, err := g.Head(context.Background(), testBucket, key); err == nil || errors.Is(err, media.ErrDenied) || errors.Is(err, media.ErrNotFound) { |
| + t.Fatalf("HEAD 500: %v", err) |
| + } |
| +} |
| + |
| +func TestHeadListingAskForExactlyOneKey(t *testing.T) { |
| + var in *s3.ListObjectsV2Input |
| + api := &stubS3{listObjects: func(i *s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { |
| + in = i |
| + return &s3.ListObjectsV2Output{}, nil |
| + }} |
| + if _, err := NewGrants(testConfig(), staticAssume(time.Now()), api).Head(context.Background(), testBucket, "uploads/x"); !errors.Is(err, media.ErrNotFound) { |
| + t.Fatal(err) |
| + } |
| + if aws.ToString(in.Bucket) != testBucket || aws.ToString(in.Prefix) != "uploads/x" || aws.ToInt32(in.MaxKeys) != 1 || |
| + in.EncodingType != s3types.EncodingTypeUrl || aws.ToString(in.ExpectedBucketOwner) != testAccount { |
| + t.Fatalf("listing input: %+v", in) |
| + } |
| + missing := &stubS3{listObjects: func(*s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { return nil, &s3types.NoSuchBucket{} }} |
| + if _, err := NewGrants(testConfig(), staticAssume(time.Now()), missing).Head(context.Background(), testBucket, "uploads/x"); !errors.Is(err, media.ErrNotFound) { |
| + t.Fatalf("a bucket that is gone: %v", err) |
| + } |
| +} |
| + |
| +func TestHeadSessionPerBucketRenewedBeforeItExpires(t *testing.T) { |
| + start := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) |
| + now := start |
| + var mu sync.Mutex |
| + clock := func() time.Time { mu.Lock(); defer mu.Unlock(); return now } |
| + var policies []string |
| + var sessions []string |
| + assume := func(_ context.Context, s, p string) (aws.Credentials, error) { |
| + sessions, policies = append(sessions, s), append(policies, p) |
| + return sessionCreds(clock().Add(time.Hour)), nil |
| + } |
| + session := &stubS3{headObject: func(in *s3.HeadObjectInput) (*s3.HeadObjectOutput, error) { |
| + return &s3.HeadObjectOutput{ContentLength: aws.Int64(1), ETag: aws.String(`"e"`)}, nil |
| + }} |
| + console := &stubS3{listObjects: func(in *s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { |
| + return &s3.ListObjectsV2Output{Contents: []s3types.Object{{Key: in.Prefix}}}, nil |
| + }} |
| + g := NewGrants(testConfig(), assume, console, withClock(clock), withSessionS3(func(aws.Credentials, string) S3API { return session })) |
| + head := func(bucket string) { |
| + t.Helper() |
| + if _, err := g.Head(context.Background(), bucket, "k"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + head("bucket-one") |
| + head("bucket-one") |
| + mu.Lock() |
| + now = start.Add(45*time.Minute - time.Second) |
| + mu.Unlock() |
| + head("bucket-one") |
| + if len(sessions) != 1 { |
| + t.Fatalf("assumed %d times inside the session's life", len(sessions)) |
| + } |
| + mu.Lock() |
| + now = start.Add(45 * time.Minute) |
| + mu.Unlock() |
| + head("bucket-one") |
| + if len(sessions) != 2 { |
| + t.Fatalf("assumed %d times: the session must be renewed 15 minutes before it expires", len(sessions)) |
| + } |
| + head("bucket-two") |
| + if len(sessions) != 3 { |
| + t.Fatalf("a second bucket shared a session: %d", len(sessions)) |
| + } |
| + if sessions[0] != "media-head" { |
| + t.Fatalf("session name = %q", sessions[0]) |
| + } |
| + want := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::bucket-two/*"}]}` |
| + if policies[2] != want { |
| + t.Fatalf("head policy:\n got %s\nwant %s", policies[2], want) |
| + } |
| + if owner := session.owners["HeadObject"]; owner != testAccount { |
| + t.Fatalf("HeadObject expected owner = %q", owner) |
| + } |
| +} |
| + |
| +// TestCompactRoundTrip: the real presigner, offline. The URL Transfers.URL |
| +// rebuilds from the compact form has exactly the original query, x-id |
| +// included, byte for byte, for a GET and a PUT. |
| +func TestCompactRoundTrip(t *testing.T) { |
| + var originals []*v4.PresignedHTTPRequest |
| + real := realPresigner(testConfig().Region, "", nil) |
| + record := func(ctx context.Context, cr aws.Credentials, r presignRequest) (*v4.PresignedHTTPRequest, error) { |
| + p, err := real(ctx, cr, r) |
| + if err == nil { |
| + originals = append(originals, p) |
| + } |
| + return p, err |
| + } |
| + tr, _, err := NewGrants(testConfig(), staticAssume(time.Now().Add(time.Hour)), &stubS3{}, withPresigner(record)).Grant(context.Background(), grantRequest()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + transfers := append(append([]media.Transfer{tr.Source}, tr.Outputs...), tr.Result) |
| + if len(originals) != len(transfers) { |
| + t.Fatalf("%d presigned, %d transfers", len(originals), len(transfers)) |
| + } |
| + methods := map[string]bool{} |
| + for i, x := range transfers { |
| + orig := originals[i] |
| + rebuilt := tr.URL(x) |
| + origBase, origQuery, _ := strings.Cut(orig.URL, "?") |
| + base, query, _ := strings.Cut(rebuilt, "?") |
| + if base != origBase { |
| + t.Fatalf("transfer %d base:\n got %s\nwant %s", i, base, origBase) |
| + } |
| + got, want := strings.Split(query, "&"), strings.Split(origQuery, "&") |
| + slices.Sort(got) |
| + slices.Sort(want) |
| + if !slices.Equal(got, want) { |
| + t.Fatalf("transfer %d query:\n got %v\nwant %v", i, got, want) |
| + } |
| + if !strings.Contains(query, "x-id=") { |
| + t.Fatalf("transfer %d lost x-id", i) |
| + } |
| + methods[x.Method] = true |
| + } |
| + if !methods["GET"] || !methods["PUT"] { |
| + t.Fatalf("methods covered: %v", methods) |
| + } |
| +} |
| + |
| +// countingReader counts the bytes read through it. |
| +type countingReader struct { |
| + r io.Reader |
| + n int |
| +} |
| + |
| +func (c *countingReader) Read(p []byte) (int, error) { |
| + n, err := c.r.Read(p) |
| + c.n += n |
| + return n, err |
| +} |
| + |
| +func TestReadResultBounded(t *testing.T) { |
| + body := func(n int) func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) { |
| + return func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) { |
| + return &s3.GetObjectOutput{Body: io.NopCloser(bytes.NewReader(bytes.Repeat([]byte("x"), n)))}, nil |
| + } |
| + } |
| + read := func(get func(*s3.GetObjectInput) (*s3.GetObjectOutput, error)) ([]byte, error) { |
| + return NewGrants(testConfig(), staticAssume(time.Now()), &stubS3{getObject: get}).ReadResult(context.Background(), testExec) |
| + } |
| + var in *s3.GetObjectInput |
| + got, err := read(func(i *s3.GetObjectInput) (*s3.GetObjectOutput, error) { in = i; return body(10)(i) }) |
| + if err != nil || len(got) != 10 { |
| + t.Fatalf("ReadResult = %d bytes, %v", len(got), err) |
| + } |
| + if aws.ToString(in.Bucket) != testResults || aws.ToString(in.Key) != media.ResultKey(testExec) || |
| + aws.ToString(in.Range) != "bytes=0-65536" || aws.ToString(in.ExpectedBucketOwner) != testAccount { |
| + t.Fatalf("GetObject input: %+v", in) |
| + } |
| + if got, err := read(body(media.MaxResultBytes)); err != nil || len(got) != media.MaxResultBytes { |
| + t.Fatalf("exactly at the limit: %d, %v", len(got), err) |
| + } |
| + if _, err := read(body(media.MaxResultBytes + 1)); !errors.Is(err, media.ErrResultTooLarge) { |
| + t.Fatalf("one byte over: %v", err) |
| + } |
| + // A store that ignores the range is cut off one byte past the limit: the |
| + // console never holds an oversized object in memory. |
| + huge := &countingReader{r: bytes.NewReader(make([]byte, 10*media.MaxResultBytes))} |
| + _, err = read(func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) { |
| + return &s3.GetObjectOutput{Body: io.NopCloser(huge)}, nil |
| + }) |
| + if !errors.Is(err, media.ErrResultTooLarge) { |
| + t.Fatalf("a store ignoring the range: %v", err) |
| + } |
| + if huge.n > media.MaxResultBytes+1 { |
| + t.Fatalf("read %d bytes of an oversized result", huge.n) |
| + } |
| + if _, err := read(func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) { return nil, &s3types.NoSuchKey{} }); !errors.Is(err, media.ErrNotFound) { |
| + t.Fatalf("no result: %v", err) |
| + } |
| + // S3 answers a range over an empty object with 416: the object is |
| + // there and holds nothing, which ParseResult then refuses. |
| + empty := realS3(func(r *http.Request) (*http.Response, error) { |
| + return answer(r, 416, map[string]string{"Content-Type": "application/xml"}, `<Error><Code>InvalidRange</Code><Message>no</Message></Error>`), nil |
| + }) |
| + b, err := NewGrants(testConfig(), staticAssume(time.Now()), empty).ReadResult(context.Background(), testExec) |
| + if err != nil || len(b) != 0 { |
| + t.Fatalf("an empty result object: %q, %v", b, err) |
| + } |
| + denied := func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "AccessDenied", Message: "no"} |
| + } |
| + if _, err := read(denied); err == nil || errors.Is(err, media.ErrNotFound) || errors.Is(err, media.ErrResultTooLarge) { |
| + t.Fatalf("a denied read: %v", err) |
| + } |
| +} |
| + |
| +func TestDeletes(t *testing.T) { |
| + var deleted []string |
| + ok := func(in *s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { |
| + deleted = append(deleted, aws.ToString(in.Bucket)+"/"+aws.ToString(in.Key)) |
| + return &s3.DeleteObjectOutput{}, nil |
| + } |
| + api := &stubS3{deleteObject: ok} |
| + g := NewGrants(testConfig(), staticAssume(time.Now()), api) |
| + if err := g.DeleteResult(context.Background(), testExec); err != nil { |
| + t.Fatal(err) |
| + } |
| + keys := []string{"derived/a/video.mp4", "derived/a/video.m3u8"} |
| + if err := g.DeleteOutputs(context.Background(), testBucket, keys); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{testResults + "/" + media.ResultKey(testExec), testBucket + "/derived/a/video.mp4", testBucket + "/derived/a/video.m3u8"} |
| + if !slices.Equal(deleted, want) { |
| + t.Fatalf("deleted %v", deleted) |
| + } |
| + if api.owners["DeleteObject"] != testAccount { |
| + t.Fatalf("DeleteObject expected owner = %q", api.owners["DeleteObject"]) |
| + } |
| + |
| + cases := map[string]struct { |
| + err error |
| + fail bool |
| + }{ |
| + "absent": {&s3types.NoSuchKey{}, false}, |
| + "bucket gone": {&s3types.NoSuchBucket{}, false}, |
| + "bucket gone, by code": {&smithy.GenericAPIError{Code: "NoSuchBucket"}, false}, |
| + "denied": {&smithy.GenericAPIError{Code: "AccessDenied"}, true}, |
| + "transport": {errors.New("reset"), true}, |
| + } |
| + for name, tc := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + api := &stubS3{deleteObject: func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { return nil, tc.err }} |
| + err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteOutputs(context.Background(), testBucket, keys) |
| + if (err != nil) != tc.fail { |
| + t.Fatalf("DeleteOutputs = %v", err) |
| + } |
| + }) |
| + } |
| + t.Run("a result bucket that is gone is not success", func(t *testing.T) { |
| + api := &stubS3{deleteObject: func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { return nil, &s3types.NoSuchBucket{} }} |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteResult(context.Background(), testExec); err == nil { |
| + t.Fatal("a missing deployment bucket passed as a deleted result") |
| + } |
| + }) |
| + t.Run("nothing outside derived is ever deleted", func(t *testing.T) { |
| + calls := 0 |
| + api := &stubS3{deleteObject: func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { |
| + calls++ |
| + return &s3.DeleteObjectOutput{}, nil |
| + }} |
| + err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteOutputs(context.Background(), testBucket, []string{"derived/a/video.mp4", "uploads/source.mov"}) |
| + if err == nil || calls != 0 { |
| + t.Fatalf("DeleteOutputs = %v after %d deletes", err, calls) |
| + } |
| + }) |
| +} |
| + |
| +// bucketWorld is one bucket's settings behind a stubS3. |
| +func bucketWorld() *stubS3 { |
| + return &stubS3{ |
| + region: testRegion, |
| + headBucket: func(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) { return &s3.HeadBucketOutput{}, nil }, |
| + location: func(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) { |
| + return &s3.GetBucketLocationOutput{LocationConstraint: s3types.BucketLocationConstraintEuWest1}, nil |
| + }, |
| + encryption: func(*s3.GetBucketEncryptionInput) (*s3.GetBucketEncryptionOutput, error) { |
| + return encryptionOf(s3types.ServerSideEncryptionAes256), nil |
| + }, |
| + versioning: func(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error) { |
| + return &s3.GetBucketVersioningOutput{}, nil |
| + }, |
| + policy: func(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "NoSuchBucketPolicy"} |
| + }, |
| + lifecycle: func(*s3.GetBucketLifecycleConfigurationInput) (*s3.GetBucketLifecycleConfigurationOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "NoSuchLifecycleConfiguration"} |
| + }, |
| + cors: func(*s3.GetBucketCorsInput) (*s3.GetBucketCorsOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "NoSuchCORSConfiguration"} |
| + }, |
| + } |
| +} |
| + |
| +func encryptionOf(alg s3types.ServerSideEncryption) *s3.GetBucketEncryptionOutput { |
| + return &s3.GetBucketEncryptionOutput{ServerSideEncryptionConfiguration: &s3types.ServerSideEncryptionConfiguration{ |
| + Rules: []s3types.ServerSideEncryptionRule{{ApplyServerSideEncryptionByDefault: &s3types.ServerSideEncryptionByDefault{SSEAlgorithm: alg}}}}} |
| +} |
| + |
| +func TestInspectAPlainBucket(t *testing.T) { |
| + api := bucketWorld() |
| + f, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := storecfg.Facts{Owner: testAccount, Region: testRegion, Encryption: "AES256"} |
| + if !reflect.DeepEqual(f, want) { |
| + t.Fatalf("facts: %+v", f) |
| + } |
| + for _, op := range []string{"HeadBucket", "GetBucketLocation", "GetBucketEncryption", "GetBucketVersioning", "GetBucketPolicy", "GetBucketLifecycleConfiguration", "GetBucketCors"} { |
| + if got, ok := api.owners[op]; !ok || got != testAccount { |
| + t.Errorf("%s expected owner = %q (called: %v)", op, got, ok) |
| + } |
| + } |
| + verdict := storecfg.Verify(f, storecfg.Want{Bucket: testBucket, MintedName: testBucket, Account: testAccount, Region: testRegion}) |
| + if verdict != "" { |
| + t.Fatalf("a plain bucket fails %q", verdict) |
| + } |
| +} |
| + |
| +func TestInspectReadsEachSetting(t *testing.T) { |
| + t.Run("locations", func(t *testing.T) { |
| + for constraint, region := range map[s3types.BucketLocationConstraint]string{"": "us-east-1", "EU": "eu-west-1", "ap-south-1": "ap-south-1"} { |
| + api := bucketWorld() |
| + api.region = region |
| + api.location = func(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) { |
| + return &s3.GetBucketLocationOutput{LocationConstraint: constraint}, nil |
| + } |
| + f, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket) |
| + if err != nil || f.Region != region { |
| + t.Fatalf("%q: %q, %v", constraint, f.Region, err) |
| + } |
| + } |
| + }) |
| + t.Run("encryption", func(t *testing.T) { |
| + for alg, want := range map[s3types.ServerSideEncryption]string{ |
| + s3types.ServerSideEncryptionAes256: "AES256", |
| + s3types.ServerSideEncryptionAwsKms: "aws:kms", |
| + s3types.ServerSideEncryptionAwsKmsDsse: "aws:kms", |
| + "aws:kms:future": "aws:kms", |
| + } { |
| + api := bucketWorld() |
| + api.encryption = func(*s3.GetBucketEncryptionInput) (*s3.GetBucketEncryptionOutput, error) { |
| + return encryptionOf(alg), nil |
| + } |
| + f, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket) |
| + if err != nil || f.Encryption != want { |
| + t.Fatalf("%s: %q, %v", alg, f.Encryption, err) |
| + } |
| + } |
| + api := bucketWorld() |
| + api.encryption = func(*s3.GetBucketEncryptionInput) (*s3.GetBucketEncryptionOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "ServerSideEncryptionConfigurationNotFoundError"} |
| + } |
| + f, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket) |
| + if err != nil || f.Encryption != "" { |
| + t.Fatalf("no encryption: %q, %v", f.Encryption, err) |
| + } |
| + }) |
| + t.Run("versioning and policy", func(t *testing.T) { |
| + api := bucketWorld() |
| + api.versioning = func(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error) { |
| + return &s3.GetBucketVersioningOutput{Status: s3types.BucketVersioningStatusSuspended}, nil |
| + } |
| + api.policy = func(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error) { |
| + return &s3.GetBucketPolicyOutput{Policy: aws.String("{}")}, nil |
| + } |
| + f, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket) |
| + if err != nil || f.Versioning != "Suspended" || !f.HasPolicy { |
| + t.Fatalf("%+v, %v", f, err) |
| + } |
| + }) |
| + t.Run("a read that fails is an error, not an absence", func(t *testing.T) { |
| + denied := &smithy.GenericAPIError{Code: "AccessDenied"} |
| + edits := map[string]func(*stubS3){ |
| + "location": func(s *stubS3) { |
| + s.location = func(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) { return nil, denied } |
| + }, |
| + "encryption": func(s *stubS3) { |
| + s.encryption = func(*s3.GetBucketEncryptionInput) (*s3.GetBucketEncryptionOutput, error) { return nil, denied } |
| + }, |
| + "versioning": func(s *stubS3) { |
| + s.versioning = func(*s3.GetBucketVersioningInput) (*s3.GetBucketVersioningOutput, error) { return nil, denied } |
| + }, |
| + "policy": func(s *stubS3) { |
| + s.policy = func(*s3.GetBucketPolicyInput) (*s3.GetBucketPolicyOutput, error) { return nil, denied } |
| + }, |
| + "lifecycle": func(s *stubS3) { |
| + s.lifecycle = func(*s3.GetBucketLifecycleConfigurationInput) (*s3.GetBucketLifecycleConfigurationOutput, error) { |
| + return nil, denied |
| + } |
| + }, |
| + "cors": func(s *stubS3) { |
| + s.cors = func(*s3.GetBucketCorsInput) (*s3.GetBucketCorsOutput, error) { return nil, denied } |
| + }, |
| + } |
| + for name, edit := range edits { |
| + api := bucketWorld() |
| + edit(api) |
| + if _, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket); err == nil { |
| + t.Errorf("%s: a denied read passed", name) |
| + } |
| + } |
| + }) |
| +} |
| + |
| +func TestInspectStopsAtAForeignOrCrossRegionBucket(t *testing.T) { |
| + onlyHead := func(head func(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error)) *stubS3 { |
| + return &stubS3{region: testRegion, headBucket: head} |
| + } |
| + t.Run("403 is another owner", func(t *testing.T) { |
| + client := realS3(func(r *http.Request) (*http.Response, error) { |
| + if r.Method != http.MethodHead { |
| + t.Errorf("%s after the owner check failed", r.Method) |
| + } |
| + return answer(r, 403, nil, ""), nil |
| + }) |
| + f, err := NewBuckets(testAccount, client).Inspect(context.Background(), testBucket) |
| + if err != nil || f.Owner != "" { |
| + t.Fatalf("%+v, %v", f, err) |
| + } |
| + if got := storecfg.Verify(f, storecfg.Want{Bucket: testBucket, MintedName: testBucket, Account: testAccount, Region: testRegion}); got != storecfg.CheckOwner { |
| + t.Fatalf("verify = %q", got) |
| + } |
| + }) |
| + t.Run("the region mismatch stops the reads", func(t *testing.T) { |
| + api := bucketWorld() |
| + api.location = func(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) { |
| + return &s3.GetBucketLocationOutput{LocationConstraint: "ap-south-1"}, nil |
| + } |
| + api.encryption = nil // reading it would panic |
| + f, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket) |
| + if err != nil || f.Region != "ap-south-1" || f.Owner != testAccount { |
| + t.Fatalf("%+v, %v", f, err) |
| + } |
| + if got := storecfg.Verify(f, storecfg.Want{Bucket: testBucket, MintedName: testBucket, Account: testAccount, Region: testRegion}); got != storecfg.CheckRegion { |
| + t.Fatalf("verify = %q", got) |
| + } |
| + }) |
| + t.Run("a redirect names the bucket's region", func(t *testing.T) { |
| + client := realS3(func(r *http.Request) (*http.Response, error) { |
| + return answer(r, 301, map[string]string{"X-Amz-Bucket-Region": "us-west-2"}, ""), nil |
| + }) |
| + f, err := NewBuckets(testAccount, client).Inspect(context.Background(), testBucket) |
| + if err != nil || f.Region != "us-west-2" || f.Owner != "" { |
| + t.Fatalf("%+v, %v", f, err) |
| + } |
| + }) |
| + t.Run("a bucket that is gone is an error", func(t *testing.T) { |
| + api := onlyHead(func(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) { return nil, &s3types.NotFound{} }) |
| + if _, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket); err == nil { |
| + t.Fatal("no error") |
| + } |
| + }) |
| +} |
| + |
| +func TestInspectNamesLifecycleSettingsItDoesNotModel(t *testing.T) { |
| + platform := func() s3types.LifecycleRule { |
| + return s3types.LifecycleRule{ID: aws.String(storecfg.UploadsLifecycleID), Status: s3types.ExpirationStatusEnabled, |
| + Filter: &s3types.LifecycleRuleFilter{Prefix: aws.String("")}, |
| + AbortIncompleteMultipartUpload: &s3types.AbortIncompleteMultipartUpload{DaysAfterInitiation: aws.Int32(1)}} |
| + } |
| + inspect := func(r s3types.LifecycleRule) []byte { |
| + t.Helper() |
| + api := bucketWorld() |
| + api.lifecycle = func(*s3.GetBucketLifecycleConfigurationInput) (*s3.GetBucketLifecycleConfigurationOutput, error) { |
| + return &s3.GetBucketLifecycleConfigurationOutput{Rules: []s3types.LifecycleRule{r}}, nil |
| + } |
| + f, err := NewBuckets(testAccount, api).Inspect(context.Background(), testBucket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return f.Lifecycle |
| + } |
| + own := storecfg.Hash(storecfg.UploadsLifecycle()) |
| + if got := storecfg.Hash(inspect(platform())); got != own { |
| + t.Fatalf("the platform's own rule does not canonicalise to itself: %s", inspect(platform())) |
| + } |
| + // The deprecated top-level prefix is the same thing as the filter's. |
| + deprecated := platform() |
| + deprecated.Filter, deprecated.Prefix = nil, aws.String("") |
| + if got := storecfg.Hash(inspect(deprecated)); got != own { |
| + t.Fatalf("a deprecated empty prefix differs: %s", inspect(deprecated)) |
| + } |
| + |
| + foreign := map[string]func(*s3types.LifecycleRule){ |
| + "expiration": func(r *s3types.LifecycleRule) { r.Expiration = &s3types.LifecycleExpiration{Days: aws.Int32(1)} }, |
| + "transition": func(r *s3types.LifecycleRule) { r.Transitions = []s3types.Transition{{Days: aws.Int32(1)}} }, |
| + "noncurrent expiration": func(r *s3types.LifecycleRule) { |
| + r.NoncurrentVersionExpiration = &s3types.NoncurrentVersionExpiration{NoncurrentDays: aws.Int32(1)} |
| + }, |
| + "noncurrent transition": func(r *s3types.LifecycleRule) { |
| + r.NoncurrentVersionTransitions = []s3types.NoncurrentVersionTransition{{NoncurrentDays: aws.Int32(1)}} |
| + }, |
| + "tag filter": func(r *s3types.LifecycleRule) { |
| + r.Filter = &s3types.LifecycleRuleFilter{Tag: &s3types.Tag{Key: aws.String("k"), Value: aws.String("v")}} |
| + }, |
| + "size filter above": func(r *s3types.LifecycleRule) { |
| + r.Filter = &s3types.LifecycleRuleFilter{ObjectSizeGreaterThan: aws.Int64(1)} |
| + }, |
| + "size filter below": func(r *s3types.LifecycleRule) { |
| + r.Filter = &s3types.LifecycleRuleFilter{ObjectSizeLessThan: aws.Int64(1)} |
| + }, |
| + "and filter": func(r *s3types.LifecycleRule) { |
| + r.Filter = &s3types.LifecycleRuleFilter{And: &s3types.LifecycleRuleAndOperator{}} |
| + }, |
| + "a prefix": func(r *s3types.LifecycleRule) { |
| + r.Filter = &s3types.LifecycleRuleFilter{Prefix: aws.String("uploads/")} |
| + }, |
| + "a deprecated prefix": func(r *s3types.LifecycleRule) { r.Filter, r.Prefix = nil, aws.String("uploads/") }, |
| + "disabled": func(r *s3types.LifecycleRule) { r.Status = s3types.ExpirationStatusDisabled }, |
| + "another id": func(r *s3types.LifecycleRule) { r.ID = aws.String("theirs") }, |
| + "another day count": func(r *s3types.LifecycleRule) { |
| + r.AbortIncompleteMultipartUpload = &s3types.AbortIncompleteMultipartUpload{DaysAfterInitiation: aws.Int32(7)} |
| + }, |
| + "an abort with no days": func(r *s3types.LifecycleRule) { |
| + r.AbortIncompleteMultipartUpload = &s3types.AbortIncompleteMultipartUpload{} |
| + }, |
| + } |
| + for name, edit := range foreign { |
| + t.Run(name, func(t *testing.T) { |
| + r := platform() |
| + edit(&r) |
| + if got := inspect(r); storecfg.Hash(got) == own { |
| + t.Fatalf("a foreign rule canonicalised to the platform's: %s", got) |
| + } |
| + }) |
| + } |
| + t.Run("each unmodelled setting is named", func(t *testing.T) { |
| + r := platform() |
| + r.Expiration = &s3types.LifecycleExpiration{Days: aws.Int32(1)} |
| + r.Filter = &s3types.LifecycleRuleFilter{Tag: &s3types.Tag{Key: aws.String("k")}} |
| + var rules []storecfg.LifecycleRule |
| + if err := json.Unmarshal(inspect(r), &rules); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.Equal(rules[0].Other, []string{"expiration", "filter.tag"}) { |
| + t.Fatalf("other = %v", rules[0].Other) |
| + } |
| + r = platform() |
| + r.AbortIncompleteMultipartUpload = &s3types.AbortIncompleteMultipartUpload{} |
| + if err := json.Unmarshal(inspect(r), &rules); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.Equal(rules[0].Other, []string{"abort_incomplete_multipart_upload"}) { |
| + t.Fatalf("an abort with no days: other = %v", rules[0].Other) |
| + } |
| + }) |
| +} |
| + |
| +// TestLifecycleCoversEverySDKField fails when an SDK upgrade adds a setting |
| +// the canonical form neither models nor names by reflection. |
| +func TestLifecycleCoversEverySDKField(t *testing.T) { |
| + r := s3types.LifecycleRule{} |
| + v := reflect.ValueOf(&r).Elem() |
| + for i := range v.NumField() { |
| + f := v.Type().Field(i) |
| + if !f.IsExported() || modelledRuleFields[f.Name] { |
| + continue |
| + } |
| + r2 := s3types.LifecycleRule{} |
| + fv := reflect.ValueOf(&r2).Elem().Field(i) |
| + switch fv.Kind() { |
| + case reflect.Pointer: |
| + fv.Set(reflect.New(fv.Type().Elem())) |
| + case reflect.Slice: |
| + fv.Set(reflect.MakeSlice(fv.Type(), 1, 1)) |
| + default: |
| + t.Fatalf("field %s has kind %s, which unmodelled does not handle", f.Name, fv.Kind()) |
| + } |
| + if len(unmodelled(r2)) == 0 { |
| + t.Errorf("field %s is not named", f.Name) |
| + } |
| + } |
| +} |
| + |
| +func TestBucketsCanonicalRoundTrip(t *testing.T) { |
| + origins := []string{"https://b.example.com", "https://a.example.com"} |
| + var cors *s3.PutBucketCorsInput |
| + var life *s3.PutBucketLifecycleConfigurationInput |
| + api := bucketWorld() |
| + api.putCORS = func(in *s3.PutBucketCorsInput) (*s3.PutBucketCorsOutput, error) { |
| + cors = in |
| + return &s3.PutBucketCorsOutput{}, nil |
| + } |
| + api.putLifecycle = func(in *s3.PutBucketLifecycleConfigurationInput) (*s3.PutBucketLifecycleConfigurationOutput, error) { |
| + life = in |
| + return &s3.PutBucketLifecycleConfigurationOutput{}, nil |
| + } |
| + b := NewBuckets(testAccount, api) |
| + if err := b.PutUploads(context.Background(), testBucket, origins); err != nil { |
| + t.Fatal(err) |
| + } |
| + if aws.ToString(cors.Bucket) != testBucket || aws.ToString(life.Bucket) != testBucket { |
| + t.Fatal("the writes named another bucket") |
| + } |
| + if api.owners["PutBucketCors"] != testAccount || api.owners["PutBucketLifecycleConfiguration"] != testAccount { |
| + t.Fatalf("expected owners on the writes: %v", api.owners) |
| + } |
| + api.cors = func(*s3.GetBucketCorsInput) (*s3.GetBucketCorsOutput, error) { |
| + return &s3.GetBucketCorsOutput{CORSRules: cors.CORSConfiguration.CORSRules}, nil |
| + } |
| + api.lifecycle = func(*s3.GetBucketLifecycleConfigurationInput) (*s3.GetBucketLifecycleConfigurationOutput, error) { |
| + return &s3.GetBucketLifecycleConfigurationOutput{Rules: life.LifecycleConfiguration.Rules}, nil |
| + } |
| + f, err := b.Inspect(context.Background(), testBucket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if storecfg.Hash(f.CORS) != storecfg.Hash(storecfg.UploadsCORS(origins)) { |
| + t.Fatalf("CORS:\n got %s\nwant %s", f.CORS, storecfg.UploadsCORS(origins)) |
| + } |
| + if storecfg.Hash(f.Lifecycle) != storecfg.Hash(storecfg.UploadsLifecycle()) { |
| + t.Fatalf("lifecycle:\n got %s\nwant %s", f.Lifecycle, storecfg.UploadsLifecycle()) |
| + } |
| + verdict := storecfg.Verify(f, storecfg.Want{Bucket: testBucket, MintedName: testBucket, Account: testAccount, Region: testRegion, |
| + LifecycleHash: storecfg.Hash(storecfg.UploadsLifecycle()), CORSHash: storecfg.Hash(storecfg.UploadsCORS(origins))}) |
| + if verdict != "" { |
| + t.Fatalf("the platform's own settings fail %q", verdict) |
| + } |
| + |
| + var removed []string |
| + api.delCORS = func(in *s3.DeleteBucketCorsInput) (*s3.DeleteBucketCorsOutput, error) { |
| + removed = append(removed, "cors") |
| + return &s3.DeleteBucketCorsOutput{}, nil |
| + } |
| + api.delLifecycle = func(in *s3.DeleteBucketLifecycleInput) (*s3.DeleteBucketLifecycleOutput, error) { |
| + removed = append(removed, "lifecycle") |
| + return &s3.DeleteBucketLifecycleOutput{}, nil |
| + } |
| + if err := b.DeleteUploads(context.Background(), testBucket); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.Equal(removed, []string{"cors", "lifecycle"}) || api.owners["DeleteBucketCors"] != testAccount || api.owners["DeleteBucketLifecycle"] != testAccount { |
| + t.Fatalf("removed %v, owners %v", removed, api.owners) |
| + } |
| +} |
| + |
| +func TestBucketTags(t *testing.T) { |
| + api := &stubS3{} |
| + b := NewBuckets(testAccount, api) |
| + api.tagging = func(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) { |
| + return &s3.GetBucketTaggingOutput{TagSet: []s3types.Tag{{Key: aws.String("a"), Value: aws.String("1")}, {Key: aws.String(storecfg.IncarnationTag), Value: aws.String("inc")}}}, nil |
| + } |
| + tags, err := b.BucketTags(context.Background(), testBucket) |
| + if err != nil || !reflect.DeepEqual(tags, map[string]string{"a": "1", storecfg.IncarnationTag: "inc"}) { |
| + t.Fatalf("tags = %v, %v", tags, err) |
| + } |
| + if api.owners["GetBucketTagging"] != testAccount { |
| + t.Fatal("no expected owner on the read") |
| + } |
| + api.tagging = func(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "NoSuchTagSet"} |
| + } |
| + tags, err = b.BucketTags(context.Background(), testBucket) |
| + if err != nil || tags == nil || len(tags) != 0 { |
| + t.Fatalf("no tags: %v, %v", tags, err) |
| + } |
| + api.tagging = func(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "AccessDenied"} |
| + } |
| + if _, err := b.BucketTags(context.Background(), testBucket); err == nil { |
| + t.Fatal("a denied read answered no tags") |
| + } |
| + |
| + var in *s3.PutBucketTaggingInput |
| + api.putTagging = func(i *s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error) { |
| + in = i |
| + return &s3.PutBucketTaggingOutput{}, nil |
| + } |
| + if err := b.PutBucketTags(context.Background(), testBucket, map[string]string{"b": "2", "a": "1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + var keys []string |
| + for _, tag := range in.Tagging.TagSet { |
| + keys = append(keys, aws.ToString(tag.Key)+"="+aws.ToString(tag.Value)) |
| + } |
| + if !slices.Equal(keys, []string{"a=1", "b=2"}) || api.owners["PutBucketTagging"] != testAccount { |
| + t.Fatalf("tag set %v, owners %v", keys, api.owners) |
| + } |
| + |
| + // WriteIncarnation over this adapter keeps the tags the platform does |
| + // not own. |
| + api.tagging = func(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) { |
| + return &s3.GetBucketTaggingOutput{TagSet: []s3types.Tag{{Key: aws.String("theirs"), Value: aws.String("kept")}}}, nil |
| + } |
| + inc := strings.Repeat("ab", 16) |
| + if err := storecfg.WriteIncarnation(context.Background(), b, testBucket, inc); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(in.Tagging.TagSet) != 2 { |
| + t.Fatalf("tag set after WriteIncarnation: %+v", in.Tagging.TagSet) |
| + } |
| +} |
| + |
| +// secretText is what no adapter error may ever hold. |
| +var secretText = []string{"X-Amz-Signature", "X-Amz-Security-Token", "X-Amz-Credential", "ASIA", "https://", "session-secret", "s3:GetObject", testToken} |
| + |
| +func assertClean(t *testing.T, name string, err error) { |
| + t.Helper() |
| + if err == nil { |
| + t.Errorf("%s: no error", name) |
| + return |
| + } |
| + for e := err; e != nil; e = errors.Unwrap(e) { |
| + for _, s := range secretText { |
| + if strings.Contains(e.Error(), s) { |
| + t.Errorf("%s: error text holds %q: %s", name, s, e.Error()) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestAdapterErrorsCarryNoSecrets(t *testing.T) { |
| + leaky := &url.Error{Op: "Get", URL: "https://bucket.s3.amazonaws.com/k?X-Amz-Credential=ASIAEXAMPLE&X-Amz-Security-Token=" + testToken + "&X-Amz-Signature=abc", |
| + Err: errors.New("dial tcp: connection refused")} |
| + apiLeak := &ecstypes.InvalidParameterException{Message: aws.String("bad override " + leaky.URL)} |
| + expires := time.Now().Add(time.Hour) |
| + |
| + presignFail := func(context.Context, aws.Credentials, presignRequest) (*v4.PresignedHTTPRequest, error) { |
| + return nil, leaky |
| + } |
| + noToken, _ := fakePresigner(func(_ int, _ presignRequest, p *v4.PresignedHTTPRequest) { |
| + p.URL = strings.Replace(p.URL, "&X-Amz-Security-Token=tok", "", 1) |
| + }) |
| + neverShared, _ := fakePresigner(func(n int, _ presignRequest, p *v4.PresignedHTTPRequest) { |
| + p.URL = strings.Replace(p.URL, "20261118%2F", fmt.Sprintf("2026111%d%%2F", n%10), 1) |
| + }) |
| + grantErr := func(f presignFunc, assume func(context.Context, string, string) (aws.Credentials, error)) error { |
| + _, _, err := NewGrants(testConfig(), assume, &stubS3{}, withPresigner(f)).Grant(context.Background(), grantRequest()) |
| + return err |
| + } |
| + assertClean(t, "presign failure", grantErr(presignFail, staticAssume(expires))) |
| + assertClean(t, "split failure", grantErr(noToken, staticAssume(expires))) |
| + assertClean(t, "retry exhausted", grantErr(neverShared, staticAssume(expires))) |
| + assertClean(t, "assume failure", grantErr(presignFail, func(context.Context, string, string) (aws.Credentials, error) { |
| + return aws.Credentials{}, leaky |
| + })) |
| + |
| + api := &stubECS{ |
| + run: func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { return nil, leaky }, |
| + describe: func(*ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) { return nil, leaky }, |
| + list: func(*ecs.ListTasksInput) (*ecs.ListTasksOutput, error) { return nil, leaky }, |
| + stop: func(*ecs.StopTaskInput) (*ecs.StopTaskOutput, error) { return nil, leaky }, |
| + taskDef: func(*ecs.DescribeTaskDefinitionInput) (*ecs.DescribeTaskDefinitionOutput, error) { return nil, leaky }, |
| + } |
| + e := NewEngine(testConfig(), api) |
| + _, err := e.Run(context.Background(), runRequest()) |
| + assertClean(t, "Run", err) |
| + _, _, err = e.Describe(context.Background(), []string{"arn:task/1"}) |
| + assertClean(t, "Describe", err) |
| + _, _, err = e.ListByStartedBy(context.Background(), testExec) |
| + assertClean(t, "ListByStartedBy", err) |
| + assertClean(t, "Stop", e.Stop(context.Background(), "arn:task/1", "r")) |
| + assertClean(t, "CheckRevision", e.CheckRevision(context.Background(), media.ClassKey{Preset: media.PresetVideo720p, Class: media.ClassShort})) |
| + |
| + rejected := &stubECS{run: func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { return nil, apiLeak }} |
| + _, err = NewEngine(testConfig(), rejected).Run(context.Background(), runRequest()) |
| + var rej *media.Rejected |
| + if !errors.As(err, &rej) { |
| + t.Fatalf("a client fault was not rejected: %v", err) |
| + } |
| + assertClean(t, "a rejection quoting the request", err) |
| + failed := &stubECS{run: func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) { |
| + return &ecs.RunTaskOutput{Failures: []ecstypes.Failure{{Reason: aws.String("RESOURCE:CPU"), Detail: aws.String(leaky.URL), Arn: aws.String(leaky.URL)}}}, nil |
| + }} |
| + _, err = NewEngine(testConfig(), failed).Run(context.Background(), runRequest()) |
| + assertClean(t, "a failure's detail", err) |
| + |
| + s := &stubS3{ |
| + region: testRegion, |
| + listObjects: func(*s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { return nil, leaky }, |
| + getObject: func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) { return nil, leaky }, |
| + deleteObject: func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { return nil, leaky }, |
| + headBucket: func(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) { return nil, leaky }, |
| + tagging: func(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) { return nil, leaky }, |
| + putTagging: func(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error) { return nil, leaky }, |
| + putCORS: func(*s3.PutBucketCorsInput) (*s3.PutBucketCorsOutput, error) { return nil, leaky }, |
| + delCORS: func(*s3.DeleteBucketCorsInput) (*s3.DeleteBucketCorsOutput, error) { return nil, leaky }, |
| + } |
| + g := NewGrants(testConfig(), staticAssume(expires), s) |
| + _, err = g.Head(context.Background(), testBucket, "k") |
| + assertClean(t, "Head listing", err) |
| + _, err = g.ReadResult(context.Background(), testExec) |
| + assertClean(t, "ReadResult", err) |
| + assertClean(t, "DeleteResult", g.DeleteResult(context.Background(), testExec)) |
| + assertClean(t, "DeleteOutputs", g.DeleteOutputs(context.Background(), testBucket, []string{"derived/x"})) |
| + listed := &stubS3{listObjects: func(in *s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { |
| + return &s3.ListObjectsV2Output{Contents: []s3types.Object{{Key: in.Prefix}}}, nil |
| + }} |
| + session := &stubS3{headObject: func(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) { return nil, leaky }} |
| + _, err = NewGrants(testConfig(), staticAssume(expires), listed, withSessionS3(func(aws.Credentials, string) S3API { return session })).Head(context.Background(), testBucket, "k") |
| + assertClean(t, "Head session", err) |
| + _, err = NewGrants(testConfig(), func(context.Context, string, string) (aws.Credentials, error) { return aws.Credentials{}, leaky }, listed).Head(context.Background(), testBucket, "k") |
| + assertClean(t, "Head assume", err) |
| + |
| + b := NewBuckets(testAccount, s) |
| + _, err = b.Inspect(context.Background(), testBucket) |
| + assertClean(t, "Inspect", err) |
| + _, err = b.BucketTags(context.Background(), testBucket) |
| + assertClean(t, "BucketTags", err) |
| + assertClean(t, "PutBucketTags", b.PutBucketTags(context.Background(), testBucket, map[string]string{"a": "b"})) |
| + assertClean(t, "PutUploads", b.PutUploads(context.Background(), testBucket, []string{"https://a.example.com"})) |
| + assertClean(t, "DeleteUploads", b.DeleteUploads(context.Background(), testBucket)) |
| +} |
| + |
| +// TestAdaptersConcurrent: the two caches under concurrent use (run with |
| +// -race). One STS session per bucket however many callers want it at once. |
| +func TestAdaptersConcurrent(t *testing.T) { |
| + api := revisionStub(goodRevision) |
| + e := NewEngine(testConfig(), api) |
| + var assumes atomic.Int32 |
| + release := make(chan struct{}) |
| + assume := func(ctx context.Context, _, _ string) (aws.Credentials, error) { |
| + assumes.Add(1) |
| + select { |
| + case <-release: |
| + case <-ctx.Done(): |
| + return aws.Credentials{}, ctx.Err() |
| + } |
| + return sessionCreds(time.Now().Add(time.Hour)), nil |
| + } |
| + session := &stubS3{headObject: func(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) { |
| + return &s3.HeadObjectOutput{ContentLength: aws.Int64(1), ETag: aws.String(`"e"`)}, nil |
| + }} |
| + console := &stubS3{listObjects: func(in *s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { |
| + return &s3.ListObjectsV2Output{Contents: []s3types.Object{{Key: in.Prefix}}}, nil |
| + }} |
| + g := NewGrants(testConfig(), assume, console, withSessionS3(func(aws.Credentials, string) S3API { return session })) |
| + |
| + var wg sync.WaitGroup |
| + errs := make(chan error, 64) |
| + classes := []media.ClassKey{{Preset: media.PresetVideo720p, Class: media.ClassShort}, {Preset: media.PresetAudioAAC, Class: media.ClassLong}} |
| + for i := range 32 { |
| + wg.Add(2) |
| + go func() { |
| + defer wg.Done() |
| + errs <- e.CheckRevision(context.Background(), classes[i%2]) |
| + }() |
| + go func() { |
| + defer wg.Done() |
| + _, err := g.Head(context.Background(), testBucket, "k") |
| + errs <- err |
| + }() |
| + } |
| + close(release) |
| + wg.Wait() |
| + close(errs) |
| + for err := range errs { |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if assumes.Load() != 1 { |
| + t.Fatalf("%d sessions assumed for one bucket", assumes.Load()) |
| + } |
| +} |
| + |
| +// TestHeadSessionRenewedOnceByConcurrentCallers: a caller that found the |
| +// session stale, and then waited behind the renewal in progress, uses the |
| +// renewed session rather than assuming the role again. |
| +func TestHeadSessionRenewedOnceByConcurrentCallers(t *testing.T) { |
| + start := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) |
| + var nowNanos atomic.Int64 |
| + nowNanos.Store(start.UnixNano()) |
| + var armed atomic.Bool |
| + checked := make(chan struct{}, 16) |
| + clock := func() time.Time { |
| + if armed.Load() { |
| + select { |
| + case checked <- struct{}{}: |
| + default: |
| + } |
| + } |
| + return time.Unix(0, nowNanos.Load()).UTC() |
| + } |
| + var assumes atomic.Int32 |
| + entered := make(chan struct{}, 4) |
| + release := make(chan struct{}) |
| + assume := func(ctx context.Context, _, _ string) (aws.Credentials, error) { |
| + if assumes.Add(1) > 1 { |
| + entered <- struct{}{} |
| + select { |
| + case <-release: |
| + case <-ctx.Done(): |
| + return aws.Credentials{}, ctx.Err() |
| + } |
| + } |
| + return sessionCreds(time.Unix(0, nowNanos.Load()).Add(time.Hour)), nil |
| + } |
| + session := &stubS3{headObject: func(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) { |
| + return &s3.HeadObjectOutput{ContentLength: aws.Int64(1), ETag: aws.String(`"e"`)}, nil |
| + }} |
| + console := &stubS3{listObjects: func(in *s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { |
| + return &s3.ListObjectsV2Output{Contents: []s3types.Object{{Key: in.Prefix}}}, nil |
| + }} |
| + g := NewGrants(testConfig(), assume, console, withClock(clock), withSessionS3(func(aws.Credentials, string) S3API { return session })) |
| + if _, err := g.Head(context.Background(), testBucket, "k"); err != nil { |
| + t.Fatal(err) |
| + } |
| + nowNanos.Store(start.Add(50 * time.Minute).UnixNano()) // inside the renewal margin |
| + |
| + done := make(chan error, 2) |
| + head := func() { |
| + _, err := g.Head(context.Background(), testBucket, "k") |
| + done <- err |
| + } |
| + go head() |
| + <-entered // the first caller is renewing |
| + armed.Store(true) |
| + go head() |
| + <-checked // the second has found the session stale |
| + close(release) |
| + for range 2 { |
| + if err := <-done; err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if got := assumes.Load(); got != 2 { |
| + t.Fatalf("assumed %d times: one at the start and one renewal", got) |
| + } |
| +} |
| + |
| +func TestHeadSessionRefreshHonoursCancellation(t *testing.T) { |
| + entered := make(chan struct{}, 8) |
| + assume := func(ctx context.Context, _, _ string) (aws.Credentials, error) { |
| + entered <- struct{}{} |
| + <-ctx.Done() |
| + return aws.Credentials{}, ctx.Err() |
| + } |
| + console := &stubS3{listObjects: func(in *s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { |
| + return &s3.ListObjectsV2Output{Contents: []s3types.Object{{Key: in.Prefix}}}, nil |
| + }} |
| + g := NewGrants(testConfig(), assume, console) |
| + |
| + holder, stopHolder := context.WithCancel(context.Background()) |
| + defer stopHolder() |
| + holderDone := make(chan error, 1) |
| + go func() { |
| + _, err := g.Head(holder, testBucket, "k") |
| + holderDone <- err |
| + }() |
| + <-entered |
| + |
| + // A second caller waits behind the refresh in progress, and leaves as |
| + // soon as its own context ends, without assuming anything. |
| + waiter, stopWaiter := context.WithCancel(context.Background()) |
| + waiterDone := make(chan error, 1) |
| + go func() { |
| + _, err := g.Head(waiter, testBucket, "k") |
| + waiterDone <- err |
| + }() |
| + stopWaiter() |
| + if err := <-waiterDone; !errors.Is(err, context.Canceled) { |
| + t.Fatalf("the waiter answered %v", err) |
| + } |
| + stopHolder() |
| + if err := <-holderDone; !errors.Is(err, context.Canceled) { |
| + t.Fatalf("the holder answered %v", err) |
| + } |
| + if len(entered) != 0 { |
| + t.Fatal("the waiter assumed a session after its context ended") |
| + } |
| +} |
| + |
| +// signingStore is an in-process S3 that checks each presigned request the |
| +// way S3 does: it recomputes the SigV4 signature from what actually arrived. |
| +// A rebuilt URL that lost a parameter, or a handler that sent a header other |
| +// than the signed one, is a 403 here. |
| +type signingStore struct { |
| + t *testing.T |
| + creds aws.Credentials |
| + mu sync.Mutex |
| + objects map[string][]byte |
| + seen []string |
| +} |
| + |
| +func md5Hex(b []byte) string { |
| + sum := md5.Sum(b) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +func (s *signingStore) signatureValid(r *http.Request) bool { |
| + q := r.URL.Query() |
| + when, err := time.Parse("20060102T150405Z", q.Get("X-Amz-Date")) |
| + if err != nil { |
| + return false |
| + } |
| + u := *r.URL |
| + u.Scheme, u.Host = "http", r.Host |
| + keep := url.Values{"X-Amz-Expires": {q.Get("X-Amz-Expires")}} |
| + if q.Has("x-id") { |
| + keep.Set("x-id", q.Get("x-id")) |
| + } |
| + u.RawQuery = keep.Encode() |
| + req, err := http.NewRequest(r.Method, u.String(), nil) |
| + if err != nil { |
| + return false |
| + } |
| + req.Host = r.Host |
| + for _, name := range strings.Split(q.Get("X-Amz-SignedHeaders"), ";") { |
| + if name != "host" { |
| + req.Header.Set(name, r.Header.Get(name)) |
| + } |
| + } |
| + signer := v4.NewSigner(func(o *v4.SignerOptions) { o.DisableURIPathEscaping = true }) |
| + signed, _, err := signer.PresignHTTP(context.Background(), s.creds, req, "UNSIGNED-PAYLOAD", "s3", testRegion, when) |
| + if err != nil { |
| + return false |
| + } |
| + parsed, err := url.Parse(signed) |
| + return err == nil && parsed.Query().Get("X-Amz-Signature") == q.Get("X-Amz-Signature") |
| +} |
| + |
| +func (s *signingStore) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.seen = append(s.seen, r.Method+" "+r.URL.Query().Get("x-id")) |
| + if !s.signatureValid(r) { |
| + w.WriteHeader(http.StatusForbidden) |
| + return |
| + } |
| + key := r.URL.Path |
| + obj, exists := s.objects[key] |
| + switch r.Method { |
| + case http.MethodGet: |
| + if !exists { |
| + w.WriteHeader(http.StatusNotFound) |
| + return |
| + } |
| + etag := `"` + md5Hex(obj) + `"` |
| + w.Header().Set("ETag", etag) |
| + if r.Header.Get("If-Match") != etag { |
| + w.WriteHeader(http.StatusPreconditionFailed) |
| + return |
| + } |
| + w.Header().Set("Content-Length", strconv.Itoa(len(obj))) |
| + w.Write(obj) |
| + case http.MethodPut: |
| + if exists && r.Header.Get("If-None-Match") == "*" { |
| + w.WriteHeader(http.StatusPreconditionFailed) |
| + return |
| + } |
| + s.objects[key] = body |
| + w.Header().Set("ETag", `"`+md5Hex(body)+`"`) |
| + } |
| +} |
| + |
| +func (s *signingStore) put(path string, b []byte) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.objects[path] = b |
| +} |
| + |
| +// TestHandlerTransfersAgainstASigningStore runs the handler's own download |
| +// and upload on the URLs rebuilt from the compact payload, against a store |
| +// that verifies every signature. |
| +func TestHandlerTransfersAgainstASigningStore(t *testing.T) { |
| + expires := time.Now().Add(time.Hour) |
| + creds := sessionCreds(expires) |
| + store := &signingStore{t: t, creds: creds, objects: map[string][]byte{}} |
| + srv := httptest.NewServer(store) |
| + defer srv.Close() |
| + |
| + source := bytes.Repeat([]byte("source bytes "), 4096) |
| + r := grantRequest() |
| + r.SourceETag = md5Hex(source) |
| + r.OutputPrefix = media.OutputPrefix(r.SourceKey, r.SourceETag, media.PresetVideo720p, testExec) |
| + store.put("/"+testBucket+"/"+r.SourceKey, source) |
| + |
| + c := testConfig() |
| + g := NewGrants(c, func(context.Context, string, string) (aws.Credentials, error) { return creds, nil }, &stubS3{}, WithS3Endpoint(srv.URL)) |
| + tr, expiry, err := g.Grant(context.Background(), r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := media.Payload{V: 1, Execution: testExec, Preset: media.PresetVideo720p, Expiry: expiry.Unix(), Transfers: tr, |
| + Limits: media.JobLimits{SourceBytes: 1 << 30, OutputBytes: media.MaxPutBytes}} |
| + if err := p.Validate(); err != nil { |
| + t.Fatal(err) |
| + } |
| + dir := t.TempDir() |
| + cfg := mediahandler.Config{Scratch: dir, Logf: t.Logf} |
| + |
| + dst := filepath.Join(dir, "source") |
| + if err := mediahandler.Download(context.Background(), cfg, p, dst); err != nil { |
| + t.Fatalf("download: %v (requests %v)", err, store.seen) |
| + } |
| + got, err := os.ReadFile(dst) |
| + if err != nil || !bytes.Equal(got, source) { |
| + t.Fatalf("downloaded %d bytes, %v", len(got), err) |
| + } |
| + |
| + store.put("/"+testBucket+"/"+r.SourceKey, []byte("rewritten")) |
| + err = mediahandler.Download(context.Background(), cfg, p, filepath.Join(dir, "again")) |
| + if mediahandler.TransferCode(err) != media.CodeSourceChanged { |
| + t.Fatalf("a rewritten source: %v", err) |
| + } |
| + |
| + for _, o := range tr.Outputs { |
| + content := []byte("output " + o.Name) |
| + path := filepath.Join(dir, o.Name) |
| + if err := os.WriteFile(path, content, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + sum, err := mediahandler.Upload(context.Background(), cfg, p, o, path) |
| + if err != nil || sum != md5Hex(content) { |
| + t.Fatalf("upload %s: %q, %v", o.Name, sum, err) |
| + } |
| + if _, err := mediahandler.Upload(context.Background(), cfg, p, o, path); mediahandler.TransferCode(err) != media.CodeEngineFailed { |
| + t.Fatalf("a second upload of %s: %v", o.Name, err) |
| + } |
| + } |
| + key := r.OutputPrefix + "video.mp4" |
| + if obj := store.objects["/"+testBucket+"/"+key]; string(obj) != "output video.mp4" { |
| + t.Fatalf("stored output: %q", obj) |
| + } |
| + |
| + // A header other than the signed one is refused by the signature. |
| + req, err := http.NewRequest(http.MethodPut, tr.URL(tr.Result), strings.NewReader("{}")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Content-Type", "text/plain") |
| + req.Header.Set("If-None-Match", "*") |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusForbidden { |
| + t.Fatalf("an unsigned Content-Type: %d", resp.StatusCode) |
| + } |
| + for _, want := range []int{http.StatusOK, http.StatusPreconditionFailed} { |
| + req, err := http.NewRequest(http.MethodPut, tr.URL(tr.Result), strings.NewReader("{}")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range tr.Result.Header { |
| + req.Header.Set(k, v) |
| + } |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != want { |
| + t.Fatalf("result PUT = %d, want %d", resp.StatusCode, want) |
| + } |
| + } |
| + if !slices.Contains(store.seen, "GET GetObject") || !slices.Contains(store.seen, "PUT PutObject") { |
| + t.Fatalf("x-id did not arrive: %v", store.seen) |
| + } |
| +} |