carlos / platform Public

media: ECS, STS and S3 adapters

internal/mediaaws implements media.Engine over ECS, media.Grants over
STS and S3, and storecfg.Buckets over S3's bucket configuration calls.

RunTask pins Fargate and overrides only the environment and scratch
size. A launch is rejected only when the API proves no task exists; a
used idempotency token stays ambiguous. Grants narrow one session to
one execution and refuse any transfer whose conditions the signature
does not cover. The SDK drops Content-Type from presigned PUTs, so it
is put back before signing. Adapter errors never quote a URL, query,
header, credential or session policy.

mediahandler exports Download and Upload for the MinIO contract test,
which CI runs from 30-minio-contract.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5eb966785d9e5c5b977e0fed7152681052095a40 parent a492692
11 files changed, +4,523 −0
  • .amadan/ci.d/30-minio-contract +41 −0
  • docs/superpowers/notes/media-conversion-copy-deck.md +28 −0
  • go.mod +1 −0
  • go.sum +2 −0
  • internal/mediaaws/buckets.go +334 −0
  • internal/mediaaws/config.go +301 −0
  • internal/mediaaws/engine.go +408 −0
  • internal/mediaaws/grants.go +613 −0
  • internal/mediaaws/mediaaws_test.go +2,530 −0
  • internal/mediaaws/minio_test.go +221 −0
  • internal/mediahandler/transfers.go +44 −0
diff --git a/.amadan/ci.d/30-minio-contract b/.amadan/ci.d/30-minio-contract
index bcb0e5c98..6f3876795 100755
--- a/.amadan/ci.d/30-minio-contract
+++ b/.amadan/ci.d/30-minio-contract
@@ -544,6 +544,47 @@ if ! grep -q '^--- PASS: TestDBForwardMinio (' "$out4"; then
exit 1
fi
+# The media transfers (media conversion plan 3, Task 9): the handler's own
+# download and upload on presigned URLs rebuilt from the compact payload,
+# with temporary credentials from this server's STS, because a presigned
+# transfer must carry a session token. The user may do anything in the two
+# buckets; each session the test assumes is narrowed by its session policy.
+"$mc" --quiet mb local/media-transfers local/media-transfer-results
+cat >"$rundir/media-transfers.json" <<'EOF'
+{"Version": "2012-10-17", "Statement": [
+ {"Effect": "Allow", "Action": ["s3:*"], "Resource": [
+ "arn:aws:s3:::media-transfers", "arn:aws:s3:::media-transfers/*",
+ "arn:aws:s3:::media-transfer-results", "arn:aws:s3:::media-transfer-results/*"
+ ]}
+]}
+EOF
+"$mc" --quiet admin policy create local media-transfers "$rundir/media-transfers.json"
+"$mc" --quiet admin user add local mediatransfers mediatransferssecret1
+"$mc" --quiet admin policy attach local media-transfers --user mediatransfers
+
+out_media=$rundir/test-media-transfers.log
+set +e
+CARLOS_MINIO_TEST=1 \
+ MINIO_ENDPOINT="http://127.0.0.1:$port" \
+ MEDIA_MINIO_KEY=mediatransfers \
+ MEDIA_MINIO_SECRET=mediatransferssecret1 \
+ MEDIA_MINIO_BUCKET=media-transfers \
+ MEDIA_MINIO_RESULTS=media-transfer-results \
+ go test ./internal/mediaaws/ -run 'TestMediaTransfersMinio' -count=1 -v >"$out_media" 2>&1
+test_status=$?
+set -e
+cat "$out_media"
+if [ "$test_status" -ne 0 ]; then
+ exit "$test_status"
+fi
+if ! grep -q '^--- PASS: TestMediaTransfersMinio (' "$out_media"; then
+ echo >&2
+ echo "the media transfers test did not PASS: it was skipped, filtered out, or renamed." >&2
+ echo "It skips unless CARLOS_MINIO_TEST=1. Check the env block above and that" >&2
+ echo "TestMediaTransfersMinio still exists in internal/mediaaws." >&2
+ exit 1
+fi
+
# The planned handover witnesses (region HA §25.10, held-requests Task 8):
# two real activators and three real edges in one process, the HA lease,
# litestream replication and the files store against this MinIO, as the
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index a6199c9b7..dea4cb5dd 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -660,3 +660,31 @@ or an output's name: never a credential, a URL or a header. `%s` and
| `script.endpoint_drill.restore` | `cleaned %s`, `NOT CLEANED %s` (an item: `engine-policies`, `fixture`, `input`) (pending Luna pass; plan 3 Task 7 fix 2). On stdout |
| `script.endpoint_drill.refused` | `media-endpoint-drill: refusing to run with xtrace on: it would print the drill's secrets`; `media-endpoint-drill: refusing to run with BASH_XTRACEFD set: it would print the drill's secrets`; `media-endpoint-drill: %s/drill.conf is damaged; nothing was changed. Restore the engine root and destroy the fixture by hand.`; `media-endpoint-drill: the engine root's normal media_engine_drill input is not null: its next ordinary apply would reopen the drill`; `media-endpoint-drill: the fixture's first apply did not finish, so a resource may exist that tofu never saved.`; `media-endpoint-drill: look for the user carlos-media-drill-%s and the log group carlos-media-endpoint-drill-%s in the foreign account, and the bucket %s in dev`; `media-endpoint-drill: delete what you find, then remove %s` (pending Luna pass; plan 3 Task 7 fixes 2 and 3). On stderr |
| `script.endpoint_drill.error` | `media-endpoint-drill: ` then one of: `--engine-root is not a directory`; `--engine-root has characters the drill cannot record`; `--cluster is not a cluster ARN`; `the dev profile does not answer`; `the dev profile is not the cluster's account`; `the foreign profile does not answer`; `the foreign profile has no account`; `the foreign profile is the dev account: the drill needs an unrelated account`; `the task definition cannot be read`; `the codec image is not pinned by digest`; `the codec image is not from --repository`; `the codec container has no awslogs group and prefix`; `no run directory`; `no run id`; `the run directory cannot be written`; `the engine root declares no media_engine_drill variable`; `the engine root does not initialise`; `TF_VAR_media_engine_drill is set; unset it first`; `the engine root's normal media_engine_drill input is not null; set it back first`; `the engine root's policies have changes pending; apply or revert them first`; `the engine root's variables cannot be written`; `the engine root was not applied`; `the fixture cannot be copied`; `the fixture's variables cannot be written`; `the fixture does not initialise`; `the fixture was not applied`; `the fixture has no user`; `the fixture's user is not the expected one`; `the user's key was not created`; `the GET was not presigned`; `the registry token was not minted`; `the log stream was not created`; `a minted value cannot be written as JSON`; `the drill's input cannot be written`; `a drill task did not start`; `the drill task did not stop in time`; `the drill task's output is incomplete` (pending Luna pass; plan 3 Task 7 fix 2). On stderr |
+
+### AWS adapter diagnostics: `internal/mediaaws` (plan 3 Task 9)
+
+Operator-facing text: these errors reach the console's log and `carlos system
+media status` verbatim. Every line is fixed words, an AWS operation, an API
+code or an HTTP status. None ever holds a URL, a query, a header, a credential
+or a session policy. `CARLOS_MEDIA_ENGINE` refusals at startup are diagnostics
+for whoever deploys the console and are not listed here.
+
+| Key | Text |
+|---|---|
+| `engine.aws.error` | `media: %s: %s`, an operation (`ecs RunTask`, `ecs DescribeTasks`, `ecs ListTasks`, `ecs StopTask`, `ecs DescribeTaskDefinition`, `sts AssumeRole`, `assume the conversion role`, `presign a transfer`, `grant`, `load AWS configuration`, or `s3 ` and the S3 call) and one of the `engine.aws.cause.*` or `engine.aws.grant.*` texts (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.canceled` | `canceled` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.timeout` | `timed out` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.api` | `%s (HTTP %d)` or `%s` (an AWS error code), or `HTTP %d` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.transport` | `the request failed before an answer came back` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.task_unreadable` | `a task could not be read: %s`, the reason ECS gave (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.other_revision` | `the answer is not about the revision asked for` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.no_etag` | `the answer holds no ETag` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.listed_key` | `a listed key is not URL encoded` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.outside_derived` | `refused a key outside derived/` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.canonical_rule` | `the canonical rule cannot be read` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.no_credentials` | `media: sts AssumeRole: the answer holds no complete credentials` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.no_expiry` | `the session has no expiry` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.cause.policy` | `the session policy cannot be built` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.grant.request` | `the bucket is not a bucket name`, `the execution is not 32 hex characters`, `the source key is not valid`, `the source ETag is not valid`, `the output prefix is not a directory under derived/`, `the grant does not name %d outputs`, `an output's name or content type is not one the engine writes` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.grant.presign` | `the presigned transfers do not share one credential`, `an output's URL is not under the output prefix`, `a presigned URL does not have the expected shape`, `a presigned URL does not sign the expected headers` (pending Luna pass; plan 3 Task 9) |
+| `engine.aws.rejected` | The reason in `engine rejected the launch: %s`: an AWS error code, the reason ECS gave, `no task definition for this class`, `no task and no failure reported`, `no reason reported`, `a reason that cannot be shown`, or `the API refused the request` (pending Luna pass; plan 3 Task 9) |
diff --git a/go.mod b/go.mod
index a93f38095..2ee19db4b 100644
--- a/go.mod
+++ b/go.mod
@@ -11,6 +11,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
+ github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.59.0
github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0
diff --git a/go.sum b/go.sum
index 05db7882e..da48d34e6 100644
--- a/go.sum
+++ b/go.sum
@@ -50,6 +50,8 @@ github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 h1:hiJJTfio1+i/xnfLwu6
github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5/go.mod h1:gy1JJMsby9XLbrwMhJcMu0IuMJF4DvDe4pD1wqMmwkk=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0 h1:A1hZCv8Ev0jc8o7pGqnjprJokn21pGmPWZrzPJ5Sp+E=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0/go.mod h1:6eOsONObU8u+Edct3ZmszxCTACyTeITJG7yPbbqp3L8=
+github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0 h1:uL925L3SbZ6cspHpORKWOgfTpXc5pmBo2R9jRhfo0ts=
+github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0/go.mod h1:qG7hNYoyvzJvrJqVaeTvouqfH3s5M+4cBMI9gVsa8MI=
github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.59.0 h1:H3vlr3Gl9tv5DvI+Z+hphz9X7BGYcMEP46L39VW2S2Q=
github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.59.0/go.mod h1:2WTv8huhRUxCeLfI9Vtb/5ncA5GJ0Hj5Lt5KH00G/jY=
github.com/aws/aws-sdk-go-v2/service/iam v1.58.2 h1:/6iRcqrC6k1rMA6uCZMzFE9inOrBpNmhbrZ90X8qH50=
diff --git a/internal/mediaaws/buckets.go b/internal/mediaaws/buckets.go
new file mode 100644
index 000000000..bd58212af
--- /dev/null
+++ b/internal/mediaaws/buckets.go
@@ -0,0 +1,334 @@
+package mediaaws
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "reflect"
+ "slices"
+ "strings"
+ "unicode"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ smithyhttp "github.com/aws/smithy-go/transport/http"
+
+ "github.com/carlosframework/platform/internal/storecfg"
+)
+
+// buckets is storecfg.Buckets over S3. Every call names the account expected
+// to own the bucket, writes included, so no read or write ever lands on a
+// bucket another account has taken the name of.
+type buckets struct {
+ account string
+ api S3API
+}
+
+// NewBuckets is the bucket settings adapter for buckets in accountID.
+func NewBuckets(accountID string, api S3API) storecfg.Buckets {
+ return &buckets{account: accountID, api: api}
+}
+
+func (b *buckets) owner() *string { return aws.String(b.account) }
+
+// Inspect reads what the bucket holds. A bucket of another account or in
+// another region is an answer, not an error: Inspect stops there with the
+// facts read so far, and Verify names the check that failed. Any other failed
+// read is an error, because a setting that could not be read is not absent.
+func (b *buckets) Inspect(ctx context.Context, bucket string) (storecfg.Facts, error) {
+ var f storecfg.Facts
+ if _, err := b.api.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()}); err != nil {
+ if isForbidden(err) {
+ return f, nil
+ }
+ if region := redirectedRegion(err); region != "" {
+ f.Region = region
+ return f, nil
+ }
+ return f, opError("s3 HeadBucket", err)
+ }
+ f.Owner = b.account
+
+ loc, err := b.api.GetBucketLocation(ctx, &s3.GetBucketLocationInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()})
+ if err != nil {
+ return f, opError("s3 GetBucketLocation", err)
+ }
+ f.Region = regionOf(loc.LocationConstraint)
+ if want := b.api.Options().Region; want != "" && f.Region != want {
+ return f, nil
+ }
+
+ if f.Encryption, err = b.encryption(ctx, bucket); err != nil {
+ return f, err
+ }
+ versioning, err := b.api.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()})
+ if err != nil {
+ return f, opError("s3 GetBucketVersioning", err)
+ }
+ f.Versioning = string(versioning.Status)
+ _, err = b.api.GetBucketPolicy(ctx, &s3.GetBucketPolicyInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()})
+ switch {
+ case err == nil:
+ f.HasPolicy = true
+ case !isCode(err, "NoSuchBucketPolicy"):
+ return f, opError("s3 GetBucketPolicy", err)
+ }
+ if f.Lifecycle, err = b.lifecycle(ctx, bucket); err != nil {
+ return f, err
+ }
+ if f.CORS, err = b.cors(ctx, bucket); err != nil {
+ return f, err
+ }
+ return f, nil
+}
+
+// redirectedRegion is the region S3 names when a bucket is not in the
+// client's: HeadBucket answers 301 with no body and this header.
+func redirectedRegion(err error) string {
+ var re *smithyhttp.ResponseError
+ if !errors.As(err, &re) || re.Response == nil || re.HTTPStatusCode() != http.StatusMovedPermanently {
+ return ""
+ }
+ return re.Response.Header.Get("X-Amz-Bucket-Region")
+}
+
+// regionOf reads GetBucketLocation's answer: us-east-1 is the empty location
+// and the legacy "EU" is eu-west-1.
+func regionOf(c s3types.BucketLocationConstraint) string {
+ switch c {
+ case "":
+ return "us-east-1"
+ case s3types.BucketLocationConstraintEu:
+ return "eu-west-1"
+ }
+ return string(c)
+}
+
+// encryption is the default encryption's algorithm, every KMS variant being
+// "aws:kms".
+func (b *buckets) encryption(ctx context.Context, bucket string) (string, error) {
+ out, err := b.api.GetBucketEncryption(ctx, &s3.GetBucketEncryptionInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()})
+ if isCode(err, "ServerSideEncryptionConfigurationNotFoundError") {
+ return "", nil
+ }
+ if err != nil {
+ return "", opError("s3 GetBucketEncryption", err)
+ }
+ if out.ServerSideEncryptionConfiguration == nil {
+ return "", nil
+ }
+ algorithm := ""
+ for _, r := range out.ServerSideEncryptionConfiguration.Rules {
+ if r.ApplyServerSideEncryptionByDefault == nil {
+ continue
+ }
+ a := string(r.ApplyServerSideEncryptionByDefault.SSEAlgorithm)
+ if strings.HasPrefix(a, "aws:kms") {
+ return "aws:kms", nil
+ }
+ if algorithm == "" {
+ algorithm = a
+ }
+ }
+ return algorithm, nil
+}
+
+func (b *buckets) lifecycle(ctx context.Context, bucket string) ([]byte, error) {
+ out, err := b.api.GetBucketLifecycleConfiguration(ctx, &s3.GetBucketLifecycleConfigurationInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()})
+ if isCode(err, "NoSuchLifecycleConfiguration") {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, opError("s3 GetBucketLifecycleConfiguration", err)
+ }
+ rules := make([]storecfg.LifecycleRule, 0, len(out.Rules))
+ for _, r := range out.Rules {
+ rules = append(rules, canonicalRule(r))
+ }
+ return storecfg.CanonicalLifecycle(rules), nil
+}
+
+// canonicalRule is one lifecycle rule in storecfg's canonical form.
+func canonicalRule(r s3types.LifecycleRule) storecfg.LifecycleRule {
+ out := storecfg.LifecycleRule{ID: aws.ToString(r.ID), Status: string(r.Status), Prefix: aws.ToString(r.Prefix), Other: unmodelled(r)}
+ if r.Filter != nil && aws.ToString(r.Filter.Prefix) != "" {
+ if out.Prefix != "" && out.Prefix != aws.ToString(r.Filter.Prefix) {
+ out.Other = append(out.Other, "prefix")
+ }
+ out.Prefix = aws.ToString(r.Filter.Prefix)
+ }
+ if abort := r.AbortIncompleteMultipartUpload; abort != nil {
+ if abort.DaysAfterInitiation == nil {
+ out.Other = append(out.Other, "abort_incomplete_multipart_upload")
+ }
+ out.AbortIncompleteMultipartUploadDays = int(aws.ToInt32(abort.DaysAfterInitiation))
+ }
+ return out
+}
+
+// modelledRuleFields are the LifecycleRule settings the canonical form holds.
+var modelledRuleFields = map[string]bool{"ID": true, "Status": true, "Prefix": true, "Filter": true, "AbortIncompleteMultipartUpload": true}
+
+// unmodelled names every setting the canonical form does not hold, so a rule
+// carrying one can never canonicalise to the platform's own. It reads the
+// SDK's structs by reflection rather than listing today's fields: a setting
+// an SDK upgrade adds is named without anyone remembering to add it here.
+func unmodelled(r s3types.LifecycleRule) []string {
+ other := setFields(reflect.ValueOf(r), "", modelledRuleFields)
+ if r.Filter != nil {
+ other = append(other, setFields(reflect.ValueOf(*r.Filter), "filter.", map[string]bool{"Prefix": true})...)
+ }
+ return other
+}
+
+// setFields names the exported fields of struct v that hold a value.
+func setFields(v reflect.Value, prefix string, skip map[string]bool) []string {
+ var names []string
+ for i := range v.NumField() {
+ field := v.Type().Field(i)
+ if !field.IsExported() || skip[field.Name] {
+ continue
+ }
+ value := v.Field(i)
+ if value.IsZero() || (value.Kind() == reflect.Slice && value.Len() == 0) {
+ continue
+ }
+ names = append(names, prefix+snakeCase(field.Name))
+ }
+ return names
+}
+
+// snakeCase is NoncurrentVersionExpiration as noncurrent_version_expiration.
+func snakeCase(s string) string {
+ var b strings.Builder
+ for i, r := range s {
+ if unicode.IsUpper(r) && i > 0 {
+ b.WriteByte('_')
+ }
+ b.WriteRune(unicode.ToLower(r))
+ }
+ return b.String()
+}
+
+func (b *buckets) cors(ctx context.Context, bucket string) ([]byte, error) {
+ out, err := b.api.GetBucketCors(ctx, &s3.GetBucketCorsInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()})
+ if isCode(err, "NoSuchCORSConfiguration") {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, opError("s3 GetBucketCors", err)
+ }
+ rules := make([]storecfg.CORSRule, 0, len(out.CORSRules))
+ for _, r := range out.CORSRules {
+ rules = append(rules, storecfg.CORSRule{
+ ID: aws.ToString(r.ID),
+ AllowedHeaders: r.AllowedHeaders,
+ AllowedMethods: r.AllowedMethods,
+ AllowedOrigins: r.AllowedOrigins,
+ ExposeHeaders: r.ExposeHeaders,
+ MaxAgeSeconds: int(aws.ToInt32(r.MaxAgeSeconds)),
+ })
+ }
+ return storecfg.CanonicalCORS(rules), nil
+}
+
+// PutUploads writes the platform's CORS and lifecycle rules, built from the
+// same canonical JSON Verify later compares against.
+func (b *buckets) PutUploads(ctx context.Context, bucket string, origins []string) error {
+ var corsRules []storecfg.CORSRule
+ if err := json.Unmarshal(storecfg.UploadsCORS(origins), &corsRules); err != nil {
+ return &adapterError{op: "s3 PutBucketCors", what: "the canonical rule cannot be read"}
+ }
+ var lifecycleRules []storecfg.LifecycleRule
+ if err := json.Unmarshal(storecfg.UploadsLifecycle(), &lifecycleRules); err != nil {
+ return &adapterError{op: "s3 PutBucketLifecycleConfiguration", what: "the canonical rule cannot be read"}
+ }
+ cors := make([]s3types.CORSRule, 0, len(corsRules))
+ for _, r := range corsRules {
+ rule := s3types.CORSRule{
+ AllowedHeaders: r.AllowedHeaders,
+ AllowedMethods: r.AllowedMethods,
+ AllowedOrigins: r.AllowedOrigins,
+ ExposeHeaders: r.ExposeHeaders,
+ MaxAgeSeconds: aws.Int32(int32(r.MaxAgeSeconds)),
+ }
+ if r.ID != "" {
+ rule.ID = aws.String(r.ID)
+ }
+ cors = append(cors, rule)
+ }
+ lifecycle := make([]s3types.LifecycleRule, 0, len(lifecycleRules))
+ for _, r := range lifecycleRules {
+ lifecycle = append(lifecycle, s3types.LifecycleRule{
+ ID: aws.String(r.ID),
+ Status: s3types.ExpirationStatus(r.Status),
+ Filter: &s3types.LifecycleRuleFilter{Prefix: aws.String(r.Prefix)},
+ AbortIncompleteMultipartUpload: &s3types.AbortIncompleteMultipartUpload{DaysAfterInitiation: aws.Int32(int32(r.AbortIncompleteMultipartUploadDays))},
+ })
+ }
+ if _, err := b.api.PutBucketCors(ctx, &s3.PutBucketCorsInput{
+ Bucket: aws.String(bucket),
+ ExpectedBucketOwner: b.owner(),
+ CORSConfiguration: &s3types.CORSConfiguration{CORSRules: cors},
+ }); err != nil {
+ return opError("s3 PutBucketCors", err)
+ }
+ if _, err := b.api.PutBucketLifecycleConfiguration(ctx, &s3.PutBucketLifecycleConfigurationInput{
+ Bucket: aws.String(bucket),
+ ExpectedBucketOwner: b.owner(),
+ LifecycleConfiguration: &s3types.BucketLifecycleConfiguration{Rules: lifecycle},
+ }); err != nil {
+ return opError("s3 PutBucketLifecycleConfiguration", err)
+ }
+ return nil
+}
+
+// DeleteUploads removes the bucket's CORS and lifecycle configuration.
+func (b *buckets) DeleteUploads(ctx context.Context, bucket string) error {
+ if _, err := b.api.DeleteBucketCors(ctx, &s3.DeleteBucketCorsInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()}); err != nil {
+ return opError("s3 DeleteBucketCors", err)
+ }
+ if _, err := b.api.DeleteBucketLifecycle(ctx, &s3.DeleteBucketLifecycleInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()}); err != nil {
+ return opError("s3 DeleteBucketLifecycle", err)
+ }
+ return nil
+}
+
+// BucketTags answers every tag on the bucket; none is an empty map.
+func (b *buckets) BucketTags(ctx context.Context, bucket string) (map[string]string, error) {
+ out, err := b.api.GetBucketTagging(ctx, &s3.GetBucketTaggingInput{Bucket: aws.String(bucket), ExpectedBucketOwner: b.owner()})
+ if isCode(err, "NoSuchTagSet") {
+ return map[string]string{}, nil
+ }
+ if err != nil {
+ return nil, opError("s3 GetBucketTagging", err)
+ }
+ tags := make(map[string]string, len(out.TagSet))
+ for _, t := range out.TagSet {
+ tags[aws.ToString(t.Key)] = aws.ToString(t.Value)
+ }
+ return tags, nil
+}
+
+// PutBucketTags replaces the bucket's whole tag set with tags.
+func (b *buckets) PutBucketTags(ctx context.Context, bucket string, tags map[string]string) error {
+ keys := make([]string, 0, len(tags))
+ for k := range tags {
+ keys = append(keys, k)
+ }
+ slices.Sort(keys)
+ set := make([]s3types.Tag, 0, len(keys))
+ for _, k := range keys {
+ set = append(set, s3types.Tag{Key: aws.String(k), Value: aws.String(tags[k])})
+ }
+ if _, err := b.api.PutBucketTagging(ctx, &s3.PutBucketTaggingInput{
+ Bucket: aws.String(bucket),
+ ExpectedBucketOwner: b.owner(),
+ Tagging: &s3types.Tagging{TagSet: set},
+ }); err != nil {
+ return opError("s3 PutBucketTagging", err)
+ }
+ return nil
+}
diff --git a/internal/mediaaws/config.go b/internal/mediaaws/config.go
new file mode 100644
index 000000000..ab1013301
--- /dev/null
+++ b/internal/mediaaws/config.go
@@ -0,0 +1,301 @@
+// Package mediaaws is media conversion's AWS adapter (spec §5.4, §5.5, §8):
+// media.Engine over ECS, media.Grants over STS and S3, and storecfg.Buckets
+// over S3's bucket configuration calls. It is the one package on the
+// conversion path that imports the AWS SDK; the core packages see only those
+// three interfaces.
+//
+// Every error it answers is safe to show an operator (preflight F6): the
+// text names the operation and an API code or a kind of failure, never a
+// URL, a query, a header, a credential or a session policy. See adapterError.
+package mediaaws
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "regexp"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/ecs"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/sts"
+ "github.com/aws/smithy-go"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/rootaws"
+)
+
+// Config is the media-engine module's output, the console's
+// CARLOS_MEDIA_ENGINE. TaskDefinitions is keyed by media.ClassKey.String().
+type Config struct {
+ V int `json:"v"`
+ Region string `json:"region"`
+ Cluster string `json:"cluster"`
+ TaskDefinitions map[string]string `json:"task_definitions"`
+ Subnets []string `json:"subnets"`
+ SecurityGroup string `json:"security_group"`
+ ConversionRole string `json:"conversion_role"`
+ ResultsBucket string `json:"results_bucket"`
+ StorePrefix string `json:"store_prefix"`
+ AccountID string `json:"account_id"`
+ Image media.ImageInfo `json:"image"`
+}
+
+var (
+ regionPattern = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]+$`)
+ accountPattern = regexp.MustCompile(`^[0-9]{12}$`)
+ digestPattern = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
+ bucketPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$`)
+)
+
+// configClasses are the four classes a config must name, exactly.
+func configClasses() []string {
+ var out []string
+ for _, preset := range []string{media.PresetVideo720p, media.PresetAudioAAC} {
+ for _, class := range []string{media.ClassShort, media.ClassLong} {
+ out = append(out, media.ClassKey{Preset: preset, Class: class}.String())
+ }
+ }
+ slices.Sort(out)
+ return out
+}
+
+// ParseConfig decodes CARLOS_MEDIA_ENGINE strictly: no unknown field, nothing
+// after the object, version 1, exactly the four classes, each a task
+// definition ARN pinned to a revision in this region and account, at least
+// one subnet, and an image pinned by digest. Its errors are diagnostics for
+// whoever deploys the console.
+func ParseConfig(v string) (Config, error) {
+ dec := json.NewDecoder(bytes.NewReader([]byte(v)))
+ dec.DisallowUnknownFields()
+ var c Config
+ if err := dec.Decode(&c); err != nil {
+ return Config{}, errors.New("media engine config: not a JSON object of the expected shape")
+ }
+ if _, err := dec.Token(); !errors.Is(err, io.EOF) {
+ return Config{}, errors.New("media engine config: data after the object")
+ }
+ if err := c.validate(); err != nil {
+ return Config{}, fmt.Errorf("media engine config: %w", err)
+ }
+ return c, nil
+}
+
+func (c Config) validate() error {
+ switch {
+ case c.V != 1:
+ return errors.New("v is not 1")
+ case !regionPattern.MatchString(c.Region):
+ return errors.New("region is not an AWS region")
+ case !accountPattern.MatchString(c.AccountID):
+ return errors.New("account_id is not 12 digits")
+ case strings.TrimSpace(c.Cluster) == "":
+ return errors.New("cluster is empty")
+ case strings.TrimSpace(c.SecurityGroup) == "":
+ return errors.New("security_group is empty")
+ case !bucketPattern.MatchString(c.ResultsBucket):
+ return errors.New("results_bucket is not a bucket name")
+ case strings.TrimSpace(c.StorePrefix) == "":
+ return errors.New("store_prefix is empty")
+ case !digestPattern.MatchString(c.Image.Digest):
+ return errors.New("image digest is not sha256 and 64 lower-case hex characters")
+ case len(c.Subnets) == 0:
+ return errors.New("no subnets")
+ }
+ for _, s := range c.Subnets {
+ if strings.TrimSpace(s) == "" {
+ return errors.New("a subnet is empty")
+ }
+ }
+ role := regexp.MustCompile(`^arn:aws[a-z-]*:iam::` + c.AccountID + `:role/[A-Za-z0-9+=,.@_/-]+$`)
+ if !role.MatchString(c.ConversionRole) {
+ return errors.New("conversion_role is not a role in this account")
+ }
+ return c.validateTaskDefinitions()
+}
+
+func (c Config) validateTaskDefinitions() error {
+ var keys []string
+ for k := range c.TaskDefinitions {
+ keys = append(keys, k)
+ }
+ slices.Sort(keys)
+ if !slices.Equal(keys, configClasses()) {
+ return fmt.Errorf("task_definitions must name exactly %s", strings.Join(configClasses(), ", "))
+ }
+ revision := regexp.MustCompile(`^arn:aws[a-z-]*:ecs:` + regexp.QuoteMeta(c.Region) + `:` + c.AccountID + `:task-definition/[A-Za-z0-9_-]{1,255}:[1-9][0-9]*$`)
+ for _, k := range keys {
+ if !revision.MatchString(c.TaskDefinitions[k]) {
+ return fmt.Errorf("task_definitions[%s] is not a task definition ARN with a revision in this region and account", k)
+ }
+ }
+ return nil
+}
+
+// ECSAPI is the part of the ECS client the engine uses.
+type ECSAPI interface {
+ RunTask(context.Context, *ecs.RunTaskInput, ...func(*ecs.Options)) (*ecs.RunTaskOutput, error)
+ DescribeTasks(context.Context, *ecs.DescribeTasksInput, ...func(*ecs.Options)) (*ecs.DescribeTasksOutput, error)
+ ListTasks(context.Context, *ecs.ListTasksInput, ...func(*ecs.Options)) (*ecs.ListTasksOutput, error)
+ StopTask(context.Context, *ecs.StopTaskInput, ...func(*ecs.Options)) (*ecs.StopTaskOutput, error)
+ DescribeTaskDefinition(context.Context, *ecs.DescribeTaskDefinitionInput, ...func(*ecs.Options)) (*ecs.DescribeTaskDefinitionOutput, error)
+}
+
+// STSAPI is the part of the STS client the grants use.
+type STSAPI interface {
+ AssumeRole(context.Context, *sts.AssumeRoleInput, ...func(*sts.Options)) (*sts.AssumeRoleOutput, error)
+}
+
+// S3API is the part of the S3 client the grants and the bucket settings use.
+// Options reports the client's region, which Inspect compares a bucket's
+// location with.
+type S3API interface {
+ Options() s3.Options
+
+ ListObjectsV2(context.Context, *s3.ListObjectsV2Input, ...func(*s3.Options)) (*s3.ListObjectsV2Output, error)
+ HeadObject(context.Context, *s3.HeadObjectInput, ...func(*s3.Options)) (*s3.HeadObjectOutput, error)
+ GetObject(context.Context, *s3.GetObjectInput, ...func(*s3.Options)) (*s3.GetObjectOutput, error)
+ DeleteObject(context.Context, *s3.DeleteObjectInput, ...func(*s3.Options)) (*s3.DeleteObjectOutput, error)
+
+ HeadBucket(context.Context, *s3.HeadBucketInput, ...func(*s3.Options)) (*s3.HeadBucketOutput, error)
+ GetBucketLocation(context.Context, *s3.GetBucketLocationInput, ...func(*s3.Options)) (*s3.GetBucketLocationOutput, error)
+ GetBucketEncryption(context.Context, *s3.GetBucketEncryptionInput, ...func(*s3.Options)) (*s3.GetBucketEncryptionOutput, error)
+ GetBucketVersioning(context.Context, *s3.GetBucketVersioningInput, ...func(*s3.Options)) (*s3.GetBucketVersioningOutput, error)
+ GetBucketPolicy(context.Context, *s3.GetBucketPolicyInput, ...func(*s3.Options)) (*s3.GetBucketPolicyOutput, error)
+ GetBucketLifecycleConfiguration(context.Context, *s3.GetBucketLifecycleConfigurationInput, ...func(*s3.Options)) (*s3.GetBucketLifecycleConfigurationOutput, error)
+ GetBucketCors(context.Context, *s3.GetBucketCorsInput, ...func(*s3.Options)) (*s3.GetBucketCorsOutput, error)
+ PutBucketCors(context.Context, *s3.PutBucketCorsInput, ...func(*s3.Options)) (*s3.PutBucketCorsOutput, error)
+ PutBucketLifecycleConfiguration(context.Context, *s3.PutBucketLifecycleConfigurationInput, ...func(*s3.Options)) (*s3.PutBucketLifecycleConfigurationOutput, error)
+ DeleteBucketCors(context.Context, *s3.DeleteBucketCorsInput, ...func(*s3.Options)) (*s3.DeleteBucketCorsOutput, error)
+ DeleteBucketLifecycle(context.Context, *s3.DeleteBucketLifecycleInput, ...func(*s3.Options)) (*s3.DeleteBucketLifecycleOutput, error)
+ GetBucketTagging(context.Context, *s3.GetBucketTaggingInput, ...func(*s3.Options)) (*s3.GetBucketTaggingOutput, error)
+ PutBucketTagging(context.Context, *s3.PutBucketTaggingInput, ...func(*s3.Options)) (*s3.PutBucketTaggingOutput, error)
+}
+
+// New builds the engine and the grants on real clients from the console's
+// default AWS configuration, in the config's region.
+func New(ctx context.Context, c Config) (media.Engine, media.Grants, error) {
+ cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(c.Region))
+ if err != nil {
+ return nil, nil, opError("load AWS configuration", err)
+ }
+ assume := assumeRole(sts.NewFromConfig(cfg), c.ConversionRole)
+ return NewEngine(c, ecs.NewFromConfig(cfg)), NewGrants(c, assume, s3.NewFromConfig(cfg)), nil
+}
+
+// sessionSeconds is the life of every assumed session: the longest a role
+// assumed from a role may last, and the grant's lifetime (spec §5.4).
+const sessionSeconds = int32(media.GrantLifetime / time.Second)
+
+// assumeRole is the grants' assume function over STS: one session on role,
+// narrowed by policy.
+func assumeRole(api STSAPI, role string) func(ctx context.Context, sessionName, policy string) (aws.Credentials, error) {
+ return func(ctx context.Context, sessionName, policy string) (aws.Credentials, error) {
+ out, err := api.AssumeRole(ctx, &sts.AssumeRoleInput{
+ RoleArn: aws.String(role),
+ RoleSessionName: aws.String(sessionName),
+ DurationSeconds: aws.Int32(sessionSeconds),
+ Policy: aws.String(policy),
+ })
+ if err != nil {
+ return aws.Credentials{}, opError("sts AssumeRole", err)
+ }
+ cr := out.Credentials
+ if cr == nil || cr.AccessKeyId == nil || cr.SecretAccessKey == nil || cr.SessionToken == nil || cr.Expiration == nil {
+ return aws.Credentials{}, errors.New("media: sts AssumeRole: the answer holds no complete credentials")
+ }
+ return aws.Credentials{
+ AccessKeyID: *cr.AccessKeyId,
+ SecretAccessKey: *cr.SecretAccessKey,
+ SessionToken: *cr.SessionToken,
+ CanExpire: true,
+ Expires: *cr.Expiration,
+ Source: "media-conversion-session",
+ }, nil
+ }
+}
+
+// adapterError is what the adapters answer in place of an SDK error. An SDK
+// error's text can hold a request URL (a transport failure quotes it whole)
+// and an API message can echo the request, and engine errors reach operators
+// verbatim, so neither is ever kept. The only thing it unwraps to is the
+// context's own error, so a caller can still tell a timeout from the rest.
+type adapterError struct {
+ op, what string
+ ctxErr error
+}
+
+func (e *adapterError) Error() string { return "media: " + e.op + ": " + e.what }
+
+func (e *adapterError) Unwrap() error { return e.ctxErr }
+
+// opError turns err from op into an adapterError.
+func opError(op string, err error) error {
+ out := &adapterError{op: op, what: describe(err)}
+ switch {
+ case errors.Is(err, context.Canceled):
+ out.ctxErr = context.Canceled
+ case errors.Is(err, context.DeadlineExceeded):
+ out.ctxErr = context.DeadlineExceeded
+ }
+ return out
+}
+
+// describe names err without quoting it: the context's end, or an API code
+// and HTTP status, or a bare status, or that the request failed.
+func describe(err error) string {
+ switch {
+ case errors.Is(err, context.Canceled):
+ return "canceled"
+ case errors.Is(err, context.DeadlineExceeded):
+ return "timed out"
+ }
+ status := httpStatus(err)
+ if code := apiCode(err); code != "" {
+ if status != 0 {
+ return code + " (HTTP " + strconv.Itoa(status) + ")"
+ }
+ return code
+ }
+ if status != 0 {
+ return "HTTP " + strconv.Itoa(status)
+ }
+ return "the request failed before an answer came back"
+}
+
+// apiCodePattern is the shape of an AWS error code. Anything else is not
+// repeated: it did not come from the API's own vocabulary.
+var apiCodePattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
+
+// apiCode is err's API error code, "" when it has none or an unusable one.
+func apiCode(err error) string {
+ var api smithy.APIError
+ if !errors.As(err, &api) {
+ return ""
+ }
+ if code := api.ErrorCode(); apiCodePattern.MatchString(code) {
+ return code
+ }
+ return ""
+}
+
+// isCode reports whether err is the API error code. Codes are the API's
+// contract; messages are not, and are never compared.
+func isCode(err error, code string) bool { return apiCode(err) == code }
+
+// httpStatus is the HTTP status err carries, 0 when it never got an answer.
+func httpStatus(err error) int {
+ var re interface{ HTTPStatusCode() int }
+ if errors.As(err, &re) {
+ return re.HTTPStatusCode()
+ }
+ return 0
+}
diff --git a/internal/mediaaws/engine.go b/internal/mediaaws/engine.go
new file mode 100644
index 000000000..4e155ab9b
--- /dev/null
+++ b/internal/mediaaws/engine.go
@@ -0,0 +1,408 @@
+package mediaaws
+
+import (
+ "context"
+ "errors"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ecs"
+ ecstypes "github.com/aws/aws-sdk-go-v2/service/ecs/types"
+ "github.com/aws/smithy-go"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+const (
+ // fargatePlatform pins the Fargate platform version, so a new LATEST
+ // cannot change the task's environment under a running deployment.
+ fargatePlatform = "1.4.0"
+ // describeBatch is how many tasks one DescribeTasks may name.
+ describeBatch = 100
+ // statusStopped is ECS's lastStatus of a task whose containers have all
+ // exited and whose exit codes are final.
+ statusStopped = "STOPPED"
+ // failureMissing is DescribeTasks' reason for a task it has no record of.
+ failureMissing = "MISSING"
+)
+
+// engine is media.Engine over ECS. It is safe for concurrent use: the job
+// table's checks run concurrently (preflight F5).
+type engine struct {
+ c Config
+ api ECSAPI
+
+ mu sync.Mutex
+ verdicts map[string]error // revision ARN → nil or *media.Misconfigured
+}
+
+// NewEngine is the engine on api.
+func NewEngine(c Config, api ECSAPI) media.Engine {
+ return &engine{c: c, api: api, verdicts: map[string]error{}}
+}
+
+// runTaskInput is the one RunTask of an execution. Overrides carry the
+// environment and the scratch size and nothing else: the gate compared the
+// revision's own entry point and command, so neither is ever overridden.
+// The execution is both startedBy (how recovery finds the task) and the
+// idempotency token (a retried call cannot start a second task).
+func runTaskInput(c Config, taskDefinition string, req media.RunRequest) *ecs.RunTaskInput {
+ overrides := &ecstypes.TaskOverride{ContainerOverrides: []ecstypes.ContainerOverride{
+ {
+ Name: aws.String(media.ContainerCodec),
+ Environment: []ecstypes.KeyValuePair{{Name: aws.String(media.PayloadEnv), Value: aws.String(string(req.Payload))}},
+ },
+ {
+ Name: aws.String(media.ContainerDeadline),
+ Environment: []ecstypes.KeyValuePair{
+ {Name: aws.String(media.DeadlineEnv), Value: aws.String(strconv.FormatInt(req.DeadlineS, 10))},
+ {Name: aws.String(media.ExpiryEnv), Value: aws.String(strconv.FormatInt(req.GrantExpiry.Unix(), 10))},
+ },
+ },
+ }}
+ if req.EphemeralGiB > 0 {
+ overrides.EphemeralStorage = &ecstypes.EphemeralStorage{SizeInGiB: int32(req.EphemeralGiB)}
+ }
+ return &ecs.RunTaskInput{
+ Cluster: aws.String(c.Cluster),
+ TaskDefinition: aws.String(taskDefinition),
+ LaunchType: ecstypes.LaunchTypeFargate,
+ PlatformVersion: aws.String(fargatePlatform),
+ Count: aws.Int32(1),
+ StartedBy: aws.String(req.Execution),
+ ClientToken: aws.String(req.Execution),
+ EnableExecuteCommand: false,
+ NetworkConfiguration: &ecstypes.NetworkConfiguration{AwsvpcConfiguration: &ecstypes.AwsVpcConfiguration{
+ Subnets: c.Subnets,
+ SecurityGroups: []string{c.SecurityGroup},
+ AssignPublicIp: ecstypes.AssignPublicIpDisabled,
+ }},
+ Overrides: overrides,
+ }
+}
+
+// Run starts the execution's task. *media.Rejected means ECS created no
+// task; any other error is ambiguous, and the job table recovers the row by
+// its startedBy.
+func (e *engine) Run(ctx context.Context, req media.RunRequest) (string, error) {
+ td, ok := e.c.TaskDefinitions[req.Class.String()]
+ if !ok {
+ return "", &media.Rejected{Reason: "no task definition for this class"}
+ }
+ out, err := e.api.RunTask(ctx, runTaskInput(e.c, td, req))
+ if err != nil {
+ return "", runError(err)
+ }
+ for _, t := range out.Tasks {
+ if arn := aws.ToString(t.TaskArn); arn != "" {
+ return arn, nil
+ }
+ }
+ return "", rejectedByFailures(out.Failures)
+}
+
+// rejectedByFailures is a RunTask that answered with no task. A shortage of
+// resources or capacity may clear; anything else will not.
+func rejectedByFailures(failures []ecstypes.Failure) *media.Rejected {
+ rej := &media.Rejected{Reason: "no task and no failure reported"}
+ for i, f := range failures {
+ reason := aws.ToString(f.Reason)
+ if i == 0 {
+ rej.Reason = safeReason(reason)
+ }
+ if strings.HasPrefix(reason, "RESOURCE:") || strings.Contains(reason, "Capacity") {
+ rej.Retryable = true
+ }
+ }
+ return rej
+}
+
+// safeReason keeps a failure's reason to one short printable line. A reason
+// that holds a URL is dropped whole: ECS's reasons are short phrases, and
+// this one is not.
+func safeReason(reason string) string {
+ if reason == "" {
+ return "no reason reported"
+ }
+ if strings.Contains(reason, "://") {
+ return "a reason that cannot be shown"
+ }
+ clean := strings.Map(func(r rune) rune {
+ if r < 0x20 || r > 0x7e {
+ return -1
+ }
+ return r
+ }, reason)
+ if len(clean) > 200 {
+ clean = clean[:200]
+ }
+ return clean
+}
+
+// runError classifies a failed RunTask. Only an answer that proves no task
+// exists becomes *media.Rejected: a client fault the API refused outright.
+//
+// ECS models few of its errors. ThrottlingException and AccessDeniedException
+// reach the SDK unmodelled, with an unknown fault, so the HTTP status decides
+// and the modelled fault is the fallback for an error that has no response.
+// ConflictException is a client fault that proves the opposite: the
+// idempotency token is already in use, so a task may exist.
+func runError(err error) error {
+ var api smithy.APIError
+ if !errors.As(err, &api) || isCode(err, "ConflictException") || !clientFault(err, api) {
+ return opError("ecs RunTask", err)
+ }
+ code := apiCode(err)
+ if code == "" {
+ code = "the API refused the request"
+ }
+ return &media.Rejected{Retryable: code == "ThrottlingException", Reason: code}
+}
+
+// clientFault reports whether the API refused the request without acting on
+// it. 408 is a request that timed out and 409 a conflict: neither says the
+// request had no effect.
+func clientFault(err error, api smithy.APIError) bool {
+ if status := httpStatus(err); status != 0 {
+ return status >= 400 && status < 500 && status != 408 && status != 409
+ }
+ return api.ErrorFault() == smithy.FaultClient || api.ErrorCode() == "ThrottlingException"
+}
+
+// Describe reads the tasks in batches. MISSING is an answer, the task's
+// record is gone; any other failure is an error, because it says nothing
+// about the task.
+func (e *engine) Describe(ctx context.Context, arns []string) ([]media.Task, []string, error) {
+ var found []media.Task
+ var missing []string
+ for batch := range slices.Chunk(arns, describeBatch) {
+ out, err := e.api.DescribeTasks(ctx, &ecs.DescribeTasksInput{Cluster: aws.String(e.c.Cluster), Tasks: batch})
+ if err != nil {
+ return nil, nil, opError("ecs DescribeTasks", err)
+ }
+ for _, t := range out.Tasks {
+ found = append(found, taskOf(t))
+ }
+ for _, f := range out.Failures {
+ if aws.ToString(f.Reason) != failureMissing || aws.ToString(f.Arn) == "" {
+ return nil, nil, &adapterError{op: "ecs DescribeTasks", what: "a task could not be read: " + safeReason(aws.ToString(f.Reason))}
+ }
+ missing = append(missing, aws.ToString(f.Arn))
+ }
+ }
+ return found, missing, nil
+}
+
+// taskOf maps one ECS task. Exit codes are found by container name, because
+// ECS does not promise their order.
+func taskOf(t ecstypes.Task) media.Task {
+ out := media.Task{
+ ARN: aws.ToString(t.TaskArn),
+ StartedBy: aws.ToString(t.StartedBy),
+ StopCode: string(t.StopCode),
+ Stopped: aws.ToString(t.LastStatus) == statusStopped,
+ StartedAt: aws.ToTime(t.StartedAt),
+ StoppedAt: aws.ToTime(t.StoppedAt),
+ }
+ for _, c := range t.Containers {
+ if c.ExitCode == nil {
+ continue
+ }
+ code := int(*c.ExitCode)
+ switch aws.ToString(c.Name) {
+ case media.ContainerCodec:
+ out.CodecExit = &code
+ case media.ContainerDeadline:
+ out.DeadlineExit = &code
+ }
+ }
+ return out
+}
+
+// ListByStartedBy finds the execution's task. RUNNING is read before STOPPED,
+// so a task that stops between the two reads is still seen in one of them.
+// The listing's filter narrows the search; the described task's own startedBy
+// decides.
+func (e *engine) ListByStartedBy(ctx context.Context, execution string) (media.Task, bool, error) {
+ for _, status := range []ecstypes.DesiredStatus{ecstypes.DesiredStatusRunning, ecstypes.DesiredStatusStopped} {
+ var token *string
+ for {
+ if err := ctx.Err(); err != nil {
+ return media.Task{}, false, opError("ecs ListTasks", err)
+ }
+ out, err := e.api.ListTasks(ctx, &ecs.ListTasksInput{
+ Cluster: aws.String(e.c.Cluster),
+ DesiredStatus: status,
+ StartedBy: aws.String(execution),
+ NextToken: token,
+ })
+ if err != nil {
+ return media.Task{}, false, opError("ecs ListTasks", err)
+ }
+ found, _, err := e.Describe(ctx, out.TaskArns)
+ if err != nil {
+ return media.Task{}, false, err
+ }
+ for _, t := range found {
+ if t.StartedBy == execution {
+ return t, true, nil
+ }
+ }
+ if aws.ToString(out.NextToken) == "" {
+ break
+ }
+ token = out.NextToken
+ }
+ }
+ return media.Task{}, false, nil
+}
+
+// Stop stops the task. ECS answers InvalidParameterException for a task it
+// no longer knows, and for much else, and its message is not a contract
+// (preflight F32), so the task itself is read to decide: gone or stopped is
+// success, anything else is the original error.
+func (e *engine) Stop(ctx context.Context, arn, reason string) error {
+ _, err := e.api.StopTask(ctx, &ecs.StopTaskInput{Cluster: aws.String(e.c.Cluster), Task: aws.String(arn), Reason: aws.String(reason)})
+ if err == nil {
+ return nil
+ }
+ if !isCode(err, "InvalidParameterException") {
+ return opError("ecs StopTask", err)
+ }
+ found, missing, derr := e.Describe(ctx, []string{arn})
+ if derr != nil {
+ return derr
+ }
+ if slices.Contains(missing, arn) {
+ return nil
+ }
+ for _, t := range found {
+ if t.ARN == arn && t.Stopped {
+ return nil
+ }
+ }
+ return opError("ecs StopTask", err)
+}
+
+// CheckRevision answers the refusal gate's verdict on the class's revision.
+// A revision is immutable, so its verdict is cached for the life of the
+// process; a read that fails is no verdict and is not cached.
+func (e *engine) CheckRevision(ctx context.Context, class media.ClassKey) error {
+ revision, ok := e.c.TaskDefinitions[class.String()]
+ if !ok {
+ return &media.Misconfigured{Revision: class.String(), Check: "containers"}
+ }
+ e.mu.Lock()
+ verdict, seen := e.verdicts[revision]
+ e.mu.Unlock()
+ if seen {
+ return verdict
+ }
+ out, err := e.api.DescribeTaskDefinition(ctx, &ecs.DescribeTaskDefinitionInput{TaskDefinition: aws.String(revision)})
+ if err != nil {
+ return opError("ecs DescribeTaskDefinition", err)
+ }
+ if out.TaskDefinition == nil || aws.ToString(out.TaskDefinition.TaskDefinitionArn) != revision {
+ return &adapterError{op: "ecs DescribeTaskDefinition", what: "the answer is not about the revision asked for"}
+ }
+ verdict = media.CheckTaskDefinition(taskDefinition(out.TaskDefinition))
+ e.mu.Lock()
+ e.verdicts[revision] = verdict
+ e.mu.Unlock()
+ return verdict
+}
+
+// taskDefinition is what the gate reads of a revision. The gate trusts these
+// summaries, so each is filled conservatively: an absent setting is never
+// read as the safe value.
+func taskDefinition(td *ecstypes.TaskDefinition) media.TaskDefinition {
+ out := media.TaskDefinition{
+ ARN: aws.ToString(td.TaskDefinitionArn),
+ TaskRoleARN: aws.ToString(td.TaskRoleArn),
+ PIDMode: string(td.PidMode),
+ }
+ if td.RuntimePlatform != nil {
+ out.CPUArchitecture = string(td.RuntimePlatform.CpuArchitecture)
+ }
+ byName := make(map[string]ecstypes.ContainerDefinition, len(td.ContainerDefinitions))
+ for _, c := range td.ContainerDefinitions {
+ byName[aws.ToString(c.Name)] = c
+ }
+ for _, c := range td.ContainerDefinitions {
+ def := media.ContainerDef{
+ Name: aws.ToString(c.Name),
+ Image: aws.ToString(c.Image),
+ User: aws.ToString(c.User),
+ Essential: aws.ToBool(c.Essential),
+ ReadOnlyRoot: aws.ToBool(c.ReadonlyRootFilesystem),
+ DropsAll: dropsAll(c.LinuxParameters),
+ RestartPolicy: c.RestartPolicy != nil && aws.ToBool(c.RestartPolicy.Enabled),
+ Volumes: reachableVolumes(c, byName),
+ EntryPoint: c.EntryPoint,
+ Command: c.Command,
+ }
+ if c.StopTimeout != nil {
+ timeout := int(*c.StopTimeout)
+ def.StopTimeout = &timeout
+ }
+ for _, d := range c.DependsOn {
+ def.DependsOn = append(def.DependsOn, media.Dependency{Container: aws.ToString(d.ContainerName), Condition: string(d.Condition)})
+ }
+ out.Containers = append(out.Containers, def)
+ }
+ return out
+}
+
+// dropsAll is true only when the container drops ALL and adds nothing back.
+func dropsAll(p *ecstypes.LinuxParameters) bool {
+ if p == nil || p.Capabilities == nil {
+ return false
+ }
+ return slices.Contains(p.Capabilities.Drop, "ALL") && len(p.Capabilities.Add) == 0
+}
+
+// reachableVolumes is every volume c can reach, sorted: its own mount points
+// and, through volumesFrom, those of each container it names and of each
+// container that one names in turn. A volumesFrom that shows no named volume
+// still counts, as "volumes-from:<container>": the source may be absent, or
+// share a volume its image declares, which the definition cannot show.
+func reachableVolumes(c ecstypes.ContainerDefinition, byName map[string]ecstypes.ContainerDefinition) []string {
+ reached := map[string]bool{}
+ visited := map[string]bool{aws.ToString(c.Name): true}
+ var walk func(ecstypes.ContainerDefinition)
+ walk = func(from ecstypes.ContainerDefinition) {
+ for _, m := range from.MountPoints {
+ reached[aws.ToString(m.SourceVolume)] = true
+ }
+ for _, v := range from.VolumesFrom {
+ name := aws.ToString(v.SourceContainer)
+ source, ok := byName[name]
+ if !ok {
+ reached["volumes-from:"+name] = true
+ continue
+ }
+ if visited[name] {
+ continue
+ }
+ visited[name] = true
+ before := len(reached)
+ walk(source)
+ if len(reached) == before {
+ reached["volumes-from:"+name] = true
+ }
+ }
+ }
+ walk(c)
+ if len(reached) == 0 {
+ return nil
+ }
+ out := make([]string, 0, len(reached))
+ for v := range reached {
+ out = append(out, v)
+ }
+ slices.Sort(out)
+ return out
+}
diff --git a/internal/mediaaws/grants.go b/internal/mediaaws/grants.go
new file mode 100644
index 000000000..e9d579e45
--- /dev/null
+++ b/internal/mediaaws/grants.go
@@ -0,0 +1,613 @@
+package mediaaws
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "maps"
+ "net/http"
+ "net/url"
+ "slices"
+ "strings"
+ "sync"
+ "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/s3"
+ s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ "github.com/aws/smithy-go/middleware"
+ smithyhttp "github.com/aws/smithy-go/transport/http"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/rootaws"
+)
+
+const (
+ // headSessionName names the one session per bucket Head uses.
+ headSessionName = "media-head"
+ // headSessionMargin is how long before it expires a Head session is
+ // replaced.
+ headSessionMargin = 15 * time.Minute
+ // outputsPerGrant is how many outputs every preset writes.
+ outputsPerGrant = 3
+ // derivedPrefix is where every output lives. It is the only place the
+ // conversion role may write, and the only place DeleteOutputs deletes.
+ derivedPrefix = "derived/"
+)
+
+// presignRequest is one transfer to presign.
+type presignRequest struct {
+ Method, Bucket, Key, IfMatch, IfNoneMatch, ContentType string
+}
+
+// presignFunc presigns one transfer with one session's credentials.
+type presignFunc func(ctx context.Context, creds aws.Credentials, r presignRequest) (*v4.PresignedHTTPRequest, error)
+
+// grants is media.Grants over STS and S3. It is safe for concurrent use.
+type grants struct {
+ c Config
+ assume func(ctx context.Context, sessionName, policy string) (aws.Credentials, error)
+ console S3API
+ presign presignFunc
+ sessionS3 func(creds aws.Credentials, bucket string) S3API
+ now func() time.Time
+
+ mu sync.Mutex
+ heads map[string]*headSession // one per store bucket the console has asked about
+}
+
+// headSession is one bucket's Head session. refreshing is held while the
+// session is replaced, so concurrent callers assume the role once; waiting
+// for it honours each caller's own context.
+type headSession struct {
+ refreshing chan struct{}
+ api S3API
+ expires time.Time
+}
+
+// GrantsOption changes how NewGrants reaches S3.
+type GrantsOption func(*grantsOptions)
+
+type grantsOptions struct {
+ endpoint string
+ presign presignFunc
+ sessionS3 func(aws.Credentials, string) S3API
+ now func() time.Time
+}
+
+// WithS3Endpoint points presigned URLs and Head sessions at an S3-compatible
+// server, path-style. Production never sets it: the local runner's end to end
+// test and the MinIO contract test do.
+func WithS3Endpoint(endpoint string) GrantsOption {
+ return func(o *grantsOptions) { o.endpoint = endpoint }
+}
+
+func withPresigner(f presignFunc) GrantsOption {
+ return func(o *grantsOptions) { o.presign = f }
+}
+
+func withSessionS3(f func(aws.Credentials, string) S3API) GrantsOption {
+ return func(o *grantsOptions) { o.sessionS3 = f }
+}
+
+func withClock(now func() time.Time) GrantsOption {
+ return func(o *grantsOptions) { o.now = now }
+}
+
+// NewGrants is the grants on the console's own S3 client. assume returns a
+// session on the conversion role narrowed by the given policy.
+func NewGrants(c Config, assume func(ctx context.Context, sessionName, policy string) (aws.Credentials, error), console S3API, opts ...GrantsOption) media.Grants {
+ var o grantsOptions
+ for _, opt := range opts {
+ opt(&o)
+ }
+ client := rootaws.BoundedHTTPClient()
+ if o.presign == nil {
+ o.presign = realPresigner(c.Region, o.endpoint, client)
+ }
+ if o.sessionS3 == nil {
+ o.sessionS3 = func(creds aws.Credentials, bucket string) S3API {
+ return s3.New(sessionOptions(c.Region, o.endpoint, client, creds, bucket))
+ }
+ }
+ if o.now == nil {
+ o.now = time.Now
+ }
+ return &grants{c: c, assume: assume, console: console, presign: o.presign, sessionS3: o.sessionS3, now: o.now, heads: map[string]*headSession{}}
+}
+
+// sessionOptions are an S3 client's options for one session and one bucket.
+// A bucket name with a dot cannot use virtual-hosted style over TLS: the
+// wildcard certificate covers one label.
+func sessionOptions(region, endpoint string, client aws.HTTPClient, creds aws.Credentials, bucket string) s3.Options {
+ o := s3.Options{
+ Region: region,
+ Credentials: credentials.StaticCredentialsProvider{Value: creds},
+ HTTPClient: client,
+ UsePathStyle: strings.Contains(bucket, "."),
+ }
+ if endpoint != "" {
+ o.BaseEndpoint = aws.String(endpoint)
+ o.UsePathStyle = true
+ }
+ return o
+}
+
+// realPresigner presigns with the SDK. Nothing here touches the network.
+func realPresigner(region, endpoint string, client aws.HTTPClient) presignFunc {
+ return func(ctx context.Context, creds aws.Credentials, r presignRequest) (*v4.PresignedHTTPRequest, error) {
+ pc := s3.NewPresignClient(s3.New(sessionOptions(region, endpoint, client, creds, r.Bucket)), s3.WithPresignExpires(media.GrantLifetime))
+ if r.Method == http.MethodGet {
+ return pc.PresignGetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(r.Bucket), Key: aws.String(r.Key), IfMatch: aws.String(r.IfMatch)})
+ }
+ return pc.PresignPutObject(ctx, &s3.PutObjectInput{
+ Bucket: aws.String(r.Bucket),
+ Key: aws.String(r.Key),
+ IfNoneMatch: aws.String(r.IfNoneMatch),
+ ContentType: aws.String(r.ContentType),
+ }, func(o *s3.PresignOptions) {
+ o.ClientOptions = append(o.ClientOptions, func(c *s3.Options) {
+ c.APIOptions = append(c.APIOptions, func(stack *middleware.Stack) error {
+ return stack.Build.Add(signContentType{r.ContentType}, middleware.After)
+ })
+ })
+ })
+ }
+}
+
+// signContentType puts the Content-Type back on a presigned PUT. The SDK's
+// PresignPutObject removes it from the request before signing, which would
+// let whoever holds the URL store an output under any type they like: a
+// compromised codec could publish text/html from a tenant's bucket. Added
+// after the SDK's own remover, so the header is there when the request is
+// signed, and S3 then refuses any other value.
+type signContentType struct{ value string }
+
+func (signContentType) ID() string { return "MediaSignContentType" }
+
+func (m signContentType) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) (middleware.BuildOutput, middleware.Metadata, error) {
+ req, ok := in.Request.(*smithyhttp.Request)
+ if !ok {
+ return middleware.BuildOutput{}, middleware.Metadata{}, errors.New("media: presign: unexpected request type")
+ }
+ req.Header.Set("Content-Type", m.value)
+ return next.HandleBuild(ctx, in)
+}
+
+// policyDocument is an IAM policy. Resource is a string or a list of them.
+type policyDocument struct {
+ Version string `json:"Version"`
+ Statement []policyStatement `json:"Statement"`
+}
+
+type policyStatement struct {
+ Effect string `json:"Effect"`
+ Action string `json:"Action"`
+ Resource any `json:"Resource"`
+}
+
+func marshalPolicy(statements ...policyStatement) (string, error) {
+ b, err := json.Marshal(policyDocument{Version: "2012-10-17", Statement: statements})
+ return string(b), err
+}
+
+// grantPolicy narrows the conversion role to one execution: read the store's
+// objects, write under its derived/ prefix, and write this execution's one
+// result object.
+func grantPolicy(bucket, results, execution string) (string, error) {
+ return marshalPolicy(
+ policyStatement{Effect: "Allow", Action: "s3:GetObject", Resource: "arn:aws:s3:::" + bucket + "/*"},
+ policyStatement{Effect: "Allow", Action: "s3:PutObject", Resource: []string{
+ "arn:aws:s3:::" + bucket + "/" + derivedPrefix + "*",
+ "arn:aws:s3:::" + results + "/" + media.ResultKey(execution),
+ }},
+ )
+}
+
+// headPolicy narrows the conversion role to reading one bucket.
+func headPolicy(bucket string) (string, error) {
+ return marshalPolicy(policyStatement{Effect: "Allow", Action: "s3:GetObject", Resource: "arn:aws:s3:::" + bucket + "/*"})
+}
+
+// checkGrantRequest refuses a request before any credential exists for it.
+// The bucket and the execution are written into an IAM policy, where "*" and
+// "?" are wildcards, so their shape is part of the policy's meaning.
+func checkGrantRequest(r media.GrantRequest) error {
+ switch {
+ case !bucketPattern.MatchString(r.Bucket):
+ return errors.New("the bucket is not a bucket name")
+ case !validExecution(r.Execution):
+ return errors.New("the execution is not 32 hex characters")
+ case !media.ValidKey(r.SourceKey):
+ return errors.New("the source key is not valid")
+ case !validETag(r.SourceETag):
+ return errors.New("the source ETag is not valid")
+ case !strings.HasPrefix(r.OutputPrefix, derivedPrefix) || !strings.HasSuffix(r.OutputPrefix, "/"):
+ return errors.New("the output prefix is not a directory under derived/")
+ case len(r.Outputs) != outputsPerGrant:
+ return fmt.Errorf("the grant does not name %d outputs", outputsPerGrant)
+ }
+ for _, o := range r.Outputs {
+ if want := media.ContentType(o.Name); want == "" || o.ContentType != want {
+ return errors.New("an output's name or content type is not one the engine writes")
+ }
+ }
+ return nil
+}
+
+func validExecution(s string) bool {
+ if len(s) != 32 {
+ return false
+ }
+ for i := range len(s) {
+ if !(s[i] >= '0' && s[i] <= '9' || s[i] >= 'a' && s[i] <= 'f') {
+ return false
+ }
+ }
+ return true
+}
+
+// validETag is an unquoted strong ETag's value: printable ASCII, no quote.
+func validETag(s string) bool {
+ if s == "" || len(s) > 256 {
+ return false
+ }
+ for i := range len(s) {
+ if s[i] < 0x21 || s[i] > 0x7e || s[i] == '"' {
+ return false
+ }
+ }
+ return true
+}
+
+// Grant presigns one execution's five transfers with a session narrowed to
+// that execution, and answers them and the session's expiry.
+func (g *grants) Grant(ctx context.Context, r media.GrantRequest) (media.Transfers, time.Time, error) {
+ if err := checkGrantRequest(r); err != nil {
+ return media.Transfers{}, time.Time{}, &adapterError{op: "grant", what: err.Error()}
+ }
+ policy, err := grantPolicy(r.Bucket, g.c.ResultsBucket, r.Execution)
+ if err != nil {
+ return media.Transfers{}, time.Time{}, &adapterError{op: "grant", what: "the session policy cannot be built"}
+ }
+ creds, err := g.assumeSession(ctx, "media-"+r.Execution, policy)
+ if err != nil {
+ return media.Transfers{}, time.Time{}, err
+ }
+ t, err := g.presignAll(ctx, creds, r)
+ if errors.Is(err, errCredentialMoved) {
+ // The five signatures straddled midnight UTC, the credential scope's
+ // date. The next round is on one day.
+ t, err = g.presignAll(ctx, creds, r)
+ }
+ if err != nil {
+ return media.Transfers{}, time.Time{}, err
+ }
+ return t, creds.Expires, nil
+}
+
+// assumeSession assumes the role and refuses credentials with no expiry: the
+// grant's expiry is the session's, and the payload carries it.
+func (g *grants) assumeSession(ctx context.Context, name, policy string) (aws.Credentials, error) {
+ creds, err := g.assume(ctx, name, policy)
+ if err != nil {
+ return aws.Credentials{}, opError("assume the conversion role", err)
+ }
+ if !creds.CanExpire || creds.Expires.IsZero() {
+ return aws.Credentials{}, &adapterError{op: "assume the conversion role", what: "the session has no expiry"}
+ }
+ return creds, nil
+}
+
+// errCredentialMoved is five presigned URLs whose shared parameters differ.
+var errCredentialMoved = &adapterError{op: "grant", what: "the presigned transfers do not share one credential"}
+
+// presignAll presigns the five transfers and compacts them.
+func (g *grants) presignAll(ctx context.Context, creds aws.Credentials, r media.GrantRequest) (media.Transfers, error) {
+ var t media.Transfers
+ sign := func(req presignRequest) (media.Transfer, error) {
+ x, shared, err := g.signOne(ctx, creds, req)
+ if err != nil {
+ return media.Transfer{}, err
+ }
+ if t.Shared == "" {
+ t.Shared = shared
+ } else if shared != t.Shared {
+ return media.Transfer{}, errCredentialMoved
+ }
+ return x, nil
+ }
+ source, err := sign(presignRequest{Method: http.MethodGet, Bucket: r.Bucket, Key: r.SourceKey, IfMatch: `"` + r.SourceETag + `"`})
+ if err != nil {
+ return media.Transfers{}, err
+ }
+ t.Source = source
+ for i, o := range r.Outputs {
+ x, err := sign(presignRequest{Method: http.MethodPut, Bucket: r.Bucket, Key: r.OutputPrefix + o.Name, IfNoneMatch: "*", ContentType: o.ContentType})
+ if err != nil {
+ return media.Transfers{}, err
+ }
+ if i == 0 {
+ prefix, ok := strings.CutSuffix(x.URL, o.Name)
+ if !ok {
+ return media.Transfers{}, errOutputOffPrefix
+ }
+ t.OutPrefix = prefix
+ }
+ if x.URL != t.OutPrefix+o.Name {
+ return media.Transfers{}, errOutputOffPrefix
+ }
+ x.URL, x.Name = "", o.Name
+ t.Outputs = append(t.Outputs, x)
+ }
+ result, err := sign(presignRequest{Method: http.MethodPut, Bucket: g.c.ResultsBucket, Key: media.ResultKey(r.Execution), IfNoneMatch: "*", ContentType: "application/json"})
+ if err != nil {
+ return media.Transfers{}, err
+ }
+ t.Result = result
+ return t, nil
+}
+
+var (
+ errOutputOffPrefix = &adapterError{op: "grant", what: "an output's URL is not under the output prefix"}
+ errPresignShape = &adapterError{op: "grant", what: "a presigned URL does not have the expected shape"}
+ errPresignHeaders = &adapterError{op: "grant", what: "a presigned URL does not sign the expected headers"}
+)
+
+// signOne presigns one transfer and splits it into its compact form.
+func (g *grants) signOne(ctx context.Context, creds aws.Credentials, req presignRequest) (media.Transfer, string, error) {
+ p, err := g.presign(ctx, creds, req)
+ if err != nil {
+ return media.Transfer{}, "", opError("presign a transfer", err)
+ }
+ if p.Method != req.Method {
+ return media.Transfer{}, "", errPresignShape
+ }
+ base, shared, rest, err := media.SplitPresigned(p.URL)
+ if err != nil {
+ // SplitPresigned's error names query parameters: not repeated here.
+ return media.Transfer{}, "", errPresignShape
+ }
+ header, err := signedHeaders(p, req, rest)
+ if err != nil {
+ return media.Transfer{}, "", err
+ }
+ return media.Transfer{URL: base, Method: p.Method, Query: rest, Header: header}, shared, nil
+}
+
+// signedHeaders is the transfer's headers less Host. They must be exactly the
+// conditions this transfer was asked to carry, and the signature must cover
+// each: a condition the store does not verify is no condition at all, and the
+// create-only PUT and the source's If-Match are what the design rests on.
+func signedHeaders(p *v4.PresignedHTTPRequest, req presignRequest, rawQuery string) (map[string]string, error) {
+ want := map[string]string{}
+ for name, value := range map[string]string{"If-Match": req.IfMatch, "If-None-Match": req.IfNoneMatch, "Content-Type": req.ContentType} {
+ if value != "" {
+ want[name] = value
+ }
+ }
+ got := map[string]string{}
+ for name, values := range p.SignedHeader {
+ canonical := http.CanonicalHeaderKey(name)
+ if canonical == "Host" {
+ continue
+ }
+ if len(values) != 1 {
+ return nil, errPresignHeaders
+ }
+ got[canonical] = values[0]
+ }
+ if !maps.Equal(got, want) {
+ return nil, errPresignHeaders
+ }
+ q, err := url.ParseQuery(rawQuery)
+ if err != nil {
+ return nil, errPresignShape
+ }
+ signed := strings.Split(q.Get("X-Amz-SignedHeaders"), ";")
+ for name := range want {
+ if !slices.Contains(signed, strings.ToLower(name)) {
+ return nil, errPresignHeaders
+ }
+ }
+ return got, nil
+}
+
+// Head answers an object's size and ETag as the conversion role sees it.
+//
+// The role has no s3:ListBucket, so S3 answers it 403 for an absent key and
+// 403 alone cannot tell absent from denied. The console's own client, which
+// can list, decides whether the key exists; the role's HEAD then decides
+// whether conversion may read it. The listing is the first key at or after
+// the prefix, so an exact match is always the one answered.
+func (g *grants) Head(ctx context.Context, bucket, key string) (media.ObjectHead, error) {
+ exists, err := g.listed(ctx, bucket, key)
+ if err != nil {
+ return media.ObjectHead{}, err
+ }
+ if !exists {
+ return media.ObjectHead{}, media.ErrNotFound
+ }
+ api, err := g.headClient(ctx, bucket)
+ if err != nil {
+ return media.ObjectHead{}, err
+ }
+ out, err := api.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), ExpectedBucketOwner: aws.String(g.c.AccountID)})
+ switch {
+ case err == nil:
+ case isForbidden(err):
+ // The infected-tag Deny, or the object deleted since the listing.
+ return media.ObjectHead{}, media.ErrDenied
+ case httpStatus(err) == http.StatusNotFound:
+ return media.ObjectHead{}, media.ErrNotFound
+ default:
+ return media.ObjectHead{}, opError("s3 HeadObject", err)
+ }
+ etag := strings.TrimSuffix(strings.TrimPrefix(aws.ToString(out.ETag), `"`), `"`)
+ if etag == "" {
+ return media.ObjectHead{}, &adapterError{op: "s3 HeadObject", what: "the answer holds no ETag"}
+ }
+ return media.ObjectHead{Size: aws.ToInt64(out.ContentLength), ETag: etag}, nil
+}
+
+// isForbidden is a 403, by status or, with no response to read, by code.
+func isForbidden(err error) bool {
+ return httpStatus(err) == http.StatusForbidden || isCode(err, "AccessDenied") || isCode(err, "Forbidden")
+}
+
+// listed reports whether the bucket holds exactly key. Keys come back URL
+// encoded, because XML 1.0 cannot carry every character a key may hold.
+func (g *grants) listed(ctx context.Context, bucket, key string) (bool, error) {
+ out, err := g.console.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
+ Bucket: aws.String(bucket),
+ Prefix: aws.String(key),
+ MaxKeys: aws.Int32(1),
+ EncodingType: s3types.EncodingTypeUrl,
+ ExpectedBucketOwner: aws.String(g.c.AccountID),
+ })
+ if isCode(err, "NoSuchBucket") {
+ return false, nil
+ }
+ if err != nil {
+ return false, opError("s3 ListObjectsV2", err)
+ }
+ for _, o := range out.Contents {
+ name, err := url.QueryUnescape(aws.ToString(o.Key))
+ if err != nil {
+ return false, &adapterError{op: "s3 ListObjectsV2", what: "a listed key is not URL encoded"}
+ }
+ if name == key {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+// headClient is the bucket's Head session, assumed once however many callers
+// want it, and replaced headSessionMargin before it expires. STS is called
+// with no lock held, under the caller's context.
+func (g *grants) headClient(ctx context.Context, bucket string) (S3API, error) {
+ g.mu.Lock()
+ s := g.heads[bucket]
+ if s == nil {
+ s = &headSession{refreshing: make(chan struct{}, 1)}
+ g.heads[bucket] = s
+ }
+ api := g.freshHead(s)
+ g.mu.Unlock()
+ if api != nil {
+ return api, nil
+ }
+
+ select {
+ case s.refreshing <- struct{}{}:
+ defer func() { <-s.refreshing }()
+ case <-ctx.Done():
+ return nil, opError("assume the conversion role", ctx.Err())
+ }
+ // Whoever held the slot may have just replaced the session.
+ g.mu.Lock()
+ api = g.freshHead(s)
+ g.mu.Unlock()
+ if api != nil {
+ return api, nil
+ }
+
+ policy, err := headPolicy(bucket)
+ if err != nil {
+ return nil, &adapterError{op: "s3 HeadObject", what: "the session policy cannot be built"}
+ }
+ creds, err := g.assumeSession(ctx, headSessionName, policy)
+ if err != nil {
+ return nil, err
+ }
+ api = g.sessionS3(creds, bucket)
+ g.mu.Lock()
+ s.api, s.expires = api, creds.Expires
+ g.mu.Unlock()
+ return api, nil
+}
+
+// freshHead is s's client while it is in date, else nil. The caller holds mu.
+func (g *grants) freshHead(s *headSession) S3API {
+ if s.api != nil && g.now().Before(s.expires.Add(-headSessionMargin)) {
+ return s.api
+ }
+ return nil
+}
+
+// ReadResult reads the result object with the console's role, at most one
+// byte past the limit, so an oversized object is recognised without being
+// read. The range is not trusted to have been honoured.
+func (g *grants) ReadResult(ctx context.Context, execution string) ([]byte, error) {
+ out, err := g.console.GetObject(ctx, &s3.GetObjectInput{
+ Bucket: aws.String(g.c.ResultsBucket),
+ Key: aws.String(media.ResultKey(execution)),
+ Range: aws.String(fmt.Sprintf("bytes=0-%d", media.MaxResultBytes)),
+ ExpectedBucketOwner: aws.String(g.c.AccountID),
+ })
+ switch {
+ case err == nil:
+ case isCode(err, "NoSuchKey"):
+ return nil, media.ErrNotFound
+ case isCode(err, "InvalidRange"):
+ // S3's answer to any range over an empty object. The object exists
+ // and holds nothing, which ParseResult refuses as a bad result.
+ return []byte{}, nil
+ default:
+ return nil, opError("s3 GetObject", err)
+ }
+ defer out.Body.Close()
+ b, err := io.ReadAll(io.LimitReader(out.Body, media.MaxResultBytes+1))
+ if err != nil {
+ return nil, opError("s3 GetObject", err)
+ }
+ if len(b) > media.MaxResultBytes {
+ return nil, media.ErrResultTooLarge
+ }
+ return b, nil
+}
+
+// DeleteResult deletes the result object; absent is success. A deployment
+// bucket that is gone is not: that is a broken deployment, not a clean one.
+func (g *grants) DeleteResult(ctx context.Context, execution string) error {
+ _, err := g.console.DeleteObject(ctx, &s3.DeleteObjectInput{
+ Bucket: aws.String(g.c.ResultsBucket),
+ Key: aws.String(media.ResultKey(execution)),
+ ExpectedBucketOwner: aws.String(g.c.AccountID),
+ })
+ if err != nil && !isCode(err, "NoSuchKey") {
+ return opError("s3 DeleteObject", err)
+ }
+ return nil
+}
+
+// DeleteOutputs deletes outputs with the console's role. An absent key is
+// success, and so is an absent bucket: a destroyed store's retired rows must
+// still clear their cleanup. Every key is checked before the first delete,
+// because this runs with the console's own authority over tenant buckets.
+func (g *grants) DeleteOutputs(ctx context.Context, bucket string, keys []string) error {
+ for _, key := range keys {
+ if !strings.HasPrefix(key, derivedPrefix) {
+ return &adapterError{op: "s3 DeleteObject", what: "refused a key outside derived/"}
+ }
+ }
+ for _, key := range keys {
+ _, err := g.console.DeleteObject(ctx, &s3.DeleteObjectInput{
+ Bucket: aws.String(bucket),
+ Key: aws.String(key),
+ ExpectedBucketOwner: aws.String(g.c.AccountID),
+ })
+ if isCode(err, "NoSuchBucket") {
+ return nil
+ }
+ if err != nil && !isCode(err, "NoSuchKey") {
+ return opError("s3 DeleteObject", err)
+ }
+ }
+ return nil
+}
diff --git a/internal/mediaaws/mediaaws_test.go b/internal/mediaaws/mediaaws_test.go
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)
+ }
+}
diff --git a/internal/mediaaws/minio_test.go b/internal/mediaaws/minio_test.go
new file mode 100644
index 000000000..e2ad5751e
--- /dev/null
+++ b/internal/mediaaws/minio_test.go
@@ -0,0 +1,221 @@
+package mediaaws
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "errors"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/sts"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediahandler"
+)
+
+// minioRegion is the region MinIO answers for when none is configured.
+const minioRegion = "us-east-1"
+
+// sendTransfer makes one presigned request by hand, on the URL rebuilt from
+// the compact form, with the transfer's signed headers and any changed ones.
+func sendTransfer(t *testing.T, tr media.Transfers, x media.Transfer, body []byte, change map[string]string) int {
+ t.Helper()
+ req, err := http.NewRequest(x.Method, tr.URL(x), bytes.NewReader(body))
+ if err != nil {
+ t.Fatal("the rebuilt URL does not parse")
+ }
+ for k, v := range x.Header {
+ req.Header.Set(k, v)
+ }
+ for k, v := range change {
+ req.Header.Set(k, v)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal("the request did not complete")
+ }
+ defer resp.Body.Close()
+ io.Copy(io.Discard, resp.Body)
+ return resp.StatusCode
+}
+
+// TestMediaTransfersMinio is the transfers' contract with a real
+// S3-compatible server: temporary credentials from its STS (SplitPresigned
+// requires a session token, as production always has one), the handler's own
+// download and upload, and every URL rebuilt from the compact payload, never
+// the SDK's originals. .amadan/ci.d/30-minio-contract stands the server up.
+func TestMediaTransfersMinio(t *testing.T) {
+ if os.Getenv("CARLOS_MINIO_TEST") != "1" {
+ t.Skip("set CARLOS_MINIO_TEST=1 (with a running MinIO and the MINIO_* env vars) to run the media transfers against MinIO; see .amadan/ci.d/30-minio-contract")
+ }
+ env := map[string]string{}
+ for _, name := range []string{"MINIO_ENDPOINT", "MEDIA_MINIO_KEY", "MEDIA_MINIO_SECRET", "MEDIA_MINIO_BUCKET", "MEDIA_MINIO_RESULTS"} {
+ if env[name] = os.Getenv(name); env[name] == "" {
+ t.Fatalf("%s is not set (required when CARLOS_MINIO_TEST=1)", name)
+ }
+ }
+ ctx := context.Background()
+ endpoint, bucket := env["MINIO_ENDPOINT"], env["MEDIA_MINIO_BUCKET"]
+ user := credentials.NewStaticCredentialsProvider(env["MEDIA_MINIO_KEY"], env["MEDIA_MINIO_SECRET"], "")
+ console := s3.New(s3.Options{Region: minioRegion, BaseEndpoint: aws.String(endpoint), UsePathStyle: true, Credentials: user})
+ stsClient := sts.New(sts.Options{Region: minioRegion, BaseEndpoint: aws.String(endpoint), Credentials: user})
+
+ c := testConfig()
+ c.Region, c.ResultsBucket = minioRegion, env["MEDIA_MINIO_RESULTS"]
+ g := NewGrants(c, assumeRole(stsClient, "arn:minio:iam:::role/media-conversion"), console, WithS3Endpoint(endpoint))
+
+ execution, err := media.NewExecutionID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ source := make([]byte, 256<<10)
+ if _, err := rand.Read(source); err != nil {
+ t.Fatal(err)
+ }
+ // A key that needs escaping in a path, under a prefix of this run's own.
+ key := "uploads/" + execution + "/a clip+é.mov"
+ put := func(k string, b []byte) {
+ t.Helper()
+ if _, err := console.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(k), Body: bytes.NewReader(b)}); err != nil {
+ t.Fatalf("seed %s: %v", k, err)
+ }
+ }
+ put(key, source)
+ etag := md5Hex(source)
+ prefix := media.OutputPrefix(key, etag, media.PresetVideo720p, execution)
+
+ // Head: the console's listing and a narrowed session on the object.
+ h, err := g.Head(ctx, bucket, key)
+ if err != nil || h.ETag != etag || h.Size != int64(len(source)) {
+ t.Fatalf("Head = %+v, %v", h, err)
+ }
+ if _, err := g.Head(ctx, bucket, key+".absent"); !errors.Is(err, media.ErrNotFound) {
+ t.Fatalf("Head of an absent key: %v", err)
+ }
+
+ r := media.GrantRequest{Bucket: bucket, SourceKey: key, SourceETag: etag, OutputPrefix: prefix, Execution: execution}
+ for _, n := range media.OutputNames(media.PresetVideo720p) {
+ r.Outputs = append(r.Outputs, media.OutputFile{Name: n, ContentType: media.ContentType(n)})
+ }
+ tr, expiry, err := g.Grant(ctx, r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p := media.Payload{V: 1, Execution: execution, 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}
+
+ // The presigned GET downloads under the right If-Match.
+ dst := filepath.Join(dir, "source")
+ if err := mediahandler.Download(ctx, cfg, p, dst); err != nil {
+ t.Fatalf("download: %v", err)
+ }
+ got, err := os.ReadFile(dst)
+ if err != nil || !bytes.Equal(got, source) {
+ t.Fatalf("downloaded %d bytes of %d: %v", len(got), len(source), err)
+ }
+ // If-Match is signed: another value is refused by the signature.
+ if status := sendTransfer(t, tr, tr.Source, nil, map[string]string{"If-Match": `"` + strings.Repeat("0", 32) + `"`}); status != http.StatusForbidden {
+ t.Fatalf("GET with another If-Match = %d, want 403", status)
+ }
+ // Rewritten, the same URL answers 412 and the handler names it.
+ put(key, append([]byte("rewritten "), source...))
+ if status := sendTransfer(t, tr, tr.Source, nil, nil); status != http.StatusPreconditionFailed {
+ t.Fatalf("GET after a rewrite = %d, want 412", status)
+ }
+ err = mediahandler.Download(ctx, cfg, p, filepath.Join(dir, "again"))
+ if code := mediahandler.TransferCode(err); code != media.CodeSourceChanged {
+ t.Fatalf("download after a rewrite: %v (code %q)", err, code)
+ }
+
+ // Each output PUT succeeds once, and its ETag is the MD5 of its bytes,
+ // which the console's Track requires of a single-part PUT.
+ for _, o := range tr.Outputs {
+ content := []byte("output " + o.Name + " " + execution)
+ path := filepath.Join(dir, o.Name)
+ if err := os.WriteFile(path, content, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ // Content-Type is signed: a compromised codec cannot choose another.
+ if status := sendTransfer(t, tr, o, content, map[string]string{"Content-Type": "text/html"}); status != http.StatusForbidden {
+ t.Fatalf("PUT %s with another Content-Type = %d, want 403", o.Name, status)
+ }
+ sum, err := mediahandler.Upload(ctx, cfg, p, o, path)
+ if err != nil {
+ t.Fatalf("upload %s: %v", o.Name, err)
+ }
+ if sum != md5Hex(content) {
+ t.Fatalf("upload %s answered %q", o.Name, sum)
+ }
+ h, err := g.Head(ctx, bucket, prefix+o.Name)
+ if err != nil || h.ETag != sum || h.Size != int64(len(content)) {
+ t.Fatalf("Head of %s = %+v, %v; want the MD5 %s", o.Name, h, err, sum)
+ }
+ head, err := console.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(prefix + o.Name)})
+ if err != nil || aws.ToString(head.ContentType) != media.ContentType(o.Name) {
+ t.Fatalf("%s is stored as %q: %v", o.Name, aws.ToString(head.ContentType), err)
+ }
+ if status := sendTransfer(t, tr, o, content, nil); status != http.StatusPreconditionFailed {
+ t.Fatalf("a second PUT of %s = %d, want 412", o.Name, status)
+ }
+ if _, err := mediahandler.Upload(ctx, cfg, p, o, path); mediahandler.TransferCode(err) != media.CodeEngineFailed {
+ t.Fatalf("a second upload of %s: %v", o.Name, err)
+ }
+ }
+
+ // The result object: create-only, read back bounded, deleted once.
+ if _, err := g.ReadResult(ctx, execution); !errors.Is(err, media.ErrNotFound) {
+ t.Fatalf("ReadResult before the PUT: %v", err)
+ }
+ result := []byte(`{"v":1}`)
+ if status := sendTransfer(t, tr, tr.Result, result, nil); status != http.StatusOK {
+ t.Fatalf("result PUT = %d", status)
+ }
+ if status := sendTransfer(t, tr, tr.Result, result, nil); status != http.StatusPreconditionFailed {
+ t.Fatalf("a second result PUT = %d, want 412", status)
+ }
+ b, err := g.ReadResult(ctx, execution)
+ if err != nil || !bytes.Equal(b, result) {
+ t.Fatalf("ReadResult = %q, %v", b, err)
+ }
+ for range 2 {
+ if err := g.DeleteResult(ctx, execution); err != nil {
+ t.Fatalf("DeleteResult: %v", err)
+ }
+ }
+ if _, err := g.ReadResult(ctx, execution); !errors.Is(err, media.ErrNotFound) {
+ t.Fatalf("ReadResult after the delete: %v", err)
+ }
+
+ // Cleanup through the adapter: absent keys are success the second time.
+ var keys []string
+ for _, n := range media.OutputNames(media.PresetVideo720p) {
+ keys = append(keys, prefix+n)
+ }
+ for range 2 {
+ if err := g.DeleteOutputs(ctx, bucket, keys); err != nil {
+ t.Fatalf("DeleteOutputs: %v", err)
+ }
+ }
+ if _, err := g.Head(ctx, bucket, keys[0]); !errors.Is(err, media.ErrNotFound) {
+ t.Fatalf("Head of a deleted output: %v", err)
+ }
+ if err := g.DeleteOutputs(ctx, "media-no-such-bucket-"+execution[:8], keys); err != nil {
+ t.Fatalf("DeleteOutputs on a missing bucket: %v", err)
+ }
+ if _, err := console.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}); err != nil {
+ t.Fatalf("remove the source: %v", err)
+ }
+}
diff --git a/internal/mediahandler/transfers.go b/internal/mediahandler/transfers.go
new file mode 100644
index 000000000..15d065f5b
--- /dev/null
+++ b/internal/mediahandler/transfers.go
@@ -0,0 +1,44 @@
+package mediahandler
+
+import (
+ "context"
+ "errors"
+ "os"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// Download is the handler's source download, for the storage adapters'
+// contract tests: internal/mediaaws runs it against a real S3-compatible
+// server on URLs rebuilt from the compact payload.
+func Download(ctx context.Context, cfg Config, p media.Payload, dst string) error {
+ return download(ctx, cfg.withDefaults(), p, dst)
+}
+
+// Upload is the handler's create-only output PUT of the file at path with
+// transfer t, for the same tests. It answers the MD5 of the bytes sent.
+func Upload(ctx context.Context, cfg Config, p media.Payload, t media.Transfer, path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer f.Close()
+ fi, err := f.Stat()
+ if err != nil {
+ return "", err
+ }
+ return upload(ctx, cfg.withDefaults(), p, t, collected{Name: t.Name, File: f, Size: fi.Size()})
+}
+
+// TransferCode is the job error code a Download or Upload failed with: one
+// of media.HandlerCodes, media.CodeGrantExpired, or "" for any other error.
+func TransferCode(err error) string {
+ if errors.Is(err, errGrantExpired) {
+ return media.CodeGrantExpired
+ }
+ var j jobError
+ if errors.As(err, &j) {
+ return j.code
+ }
+ return ""
+}