carlos / platform Public

media: one RunTask attempt, and adapter review fixes

The SDK's retries could turn a launch that created a task into a
rejection: a lost reply followed by a throttled retry read as "no task",
and the job table then orphaned the task. RunTask now makes one attempt
and the job table owns retry and recovery.

ListTasks no longer combines startedBy with desiredStatus, which AWS
refuses; each described task's startedBy decides. STS failures keep
their code through Grant and Head. Grant, Head and DeleteOutputs refuse
a bucket outside the store prefix. Every volumesFrom entry counts, 429
and expired tokens are retryable refusals, and NewBuckets refuses an
empty account. The MinIO test gets a designated absent bucket.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a2b97293ee483b5b1ab1a88c5f8b779957e3c8fc parent 5eb9667
7 files changed, +343 −51
  • .amadan/ci.d/30-minio-contract +6 −1
  • docs/superpowers/notes/media-conversion-copy-deck.md +5 −3
  • internal/mediaaws/buckets.go +41 −9
  • internal/mediaaws/engine.go +46 −26
  • internal/mediaaws/grants.go +31 −5
  • internal/mediaaws/mediaaws_test.go +208 −4
  • internal/mediaaws/minio_test.go +6 −3

CI failed — run details

diff --git a/.amadan/ci.d/30-minio-contract b/.amadan/ci.d/30-minio-contract
index 6f3876795..028e53d47 100755
--- a/.amadan/ci.d/30-minio-contract
+++ b/.amadan/ci.d/30-minio-contract
@@ -549,13 +549,17 @@ fi
# 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.
+# media-transfers-absent is never created: MinIO authorises a delete before
+# it looks for the bucket, so the user is allowed that one delete and the
+# test can see NoSuchBucket rather than a denial.
"$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/*"
- ]}
+ ]},
+ {"Effect": "Allow", "Action": ["s3:DeleteObject"], "Resource": ["arn:aws:s3:::media-transfers-absent/*"]}
]}
EOF
"$mc" --quiet admin policy create local media-transfers "$rundir/media-transfers.json"
@@ -570,6 +574,7 @@ CARLOS_MINIO_TEST=1 \
MEDIA_MINIO_SECRET=mediatransferssecret1 \
MEDIA_MINIO_BUCKET=media-transfers \
MEDIA_MINIO_RESULTS=media-transfer-results \
+ MEDIA_MINIO_ABSENT_BUCKET=media-transfers-absent \
go test ./internal/mediaaws/ -run 'TestMediaTransfersMinio' -count=1 -v >"$out_media" 2>&1
test_status=$?
set -e
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index dea4cb5dd..86ccc8e06 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -671,7 +671,7 @@ 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.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`, `store bucket`, `bucket settings`, `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) |
@@ -685,6 +685,8 @@ for whoever deploys the console and are not listed here.
| `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.cause.store_bucket` | `the bucket is not a bucket name`, `the bucket is outside this deployment's store prefix` (pending Luna pass; plan 3 Task 9 fix 1) |
+| `engine.aws.cause.no_account` | `no account to expect as the bucket's owner` (pending Luna pass; plan 3 Task 9 fix 1) |
+| `engine.aws.grant.request` | `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) |
+| `engine.aws.rejected` | The reason in `engine rejected the launch: %s`: an AWS error code, `HTTP 429`, 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/internal/mediaaws/buckets.go b/internal/mediaaws/buckets.go
index bd58212af..7098de931 100644
--- a/internal/mediaaws/buckets.go
+++ b/internal/mediaaws/buckets.go
@@ -26,11 +26,37 @@ type buckets struct {
api S3API
}
-// NewBuckets is the bucket settings adapter for buckets in accountID.
+// NewBuckets is the bucket settings adapter for buckets in accountID. With no
+// account there is no owner to expect, and S3 would skip the check, so every
+// call is refused and none reaches S3.
func NewBuckets(accountID string, api S3API) storecfg.Buckets {
+ if accountID == "" {
+ return noAccountBuckets{}
+ }
return &buckets{account: accountID, api: api}
}
+// noAccountBuckets refuses every call: see NewBuckets.
+type noAccountBuckets struct{}
+
+var errNoAccount = &adapterError{op: "bucket settings", what: "no account to expect as the bucket's owner"}
+
+func (noAccountBuckets) Inspect(context.Context, string) (storecfg.Facts, error) {
+ return storecfg.Facts{}, errNoAccount
+}
+
+func (noAccountBuckets) PutUploads(context.Context, string, []string) error { return errNoAccount }
+
+func (noAccountBuckets) DeleteUploads(context.Context, string) error { return errNoAccount }
+
+func (noAccountBuckets) BucketTags(context.Context, string) (map[string]string, error) {
+ return nil, errNoAccount
+}
+
+func (noAccountBuckets) PutBucketTags(context.Context, string, map[string]string) error {
+ return errNoAccount
+}
+
func (b *buckets) owner() *string { return aws.String(b.account) }
// Inspect reads what the bucket holds. A bucket of another account or in
@@ -222,18 +248,24 @@ func (b *buckets) cors(ctx context.Context, bucket string) ([]byte, error) {
}
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)),
- })
+ rules = append(rules, canonicalCORSRule(r))
}
return storecfg.CanonicalCORS(rules), nil
}
+// canonicalCORSRule is one CORS rule in storecfg's canonical form, which holds
+// every field S3 has (TestCORSCoversEverySDKField).
+func canonicalCORSRule(r s3types.CORSRule) storecfg.CORSRule {
+ return 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)),
+ }
+}
+
// 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 {
diff --git a/internal/mediaaws/engine.go b/internal/mediaaws/engine.go
index 4e155ab9b..c9914595d 100644
--- a/internal/mediaaws/engine.go
+++ b/internal/mediaaws/engine.go
@@ -3,6 +3,7 @@ package mediaaws
import (
"context"
"errors"
+ "net/http"
"slices"
"strconv"
"strings"
@@ -92,7 +93,7 @@ func (e *engine) Run(ctx context.Context, req media.RunRequest) (string, error)
if !ok {
return "", &media.Rejected{Reason: "no task definition for this class"}
}
- out, err := e.api.RunTask(ctx, runTaskInput(e.c, td, req))
+ out, err := e.api.RunTask(ctx, runTaskInput(e.c, td, req), singleAttempt)
if err != nil {
return "", runError(err)
}
@@ -104,6 +105,13 @@ func (e *engine) Run(ctx context.Context, req media.RunRequest) (string, error)
return "", rejectedByFailures(out.Failures)
}
+// singleAttempt turns off the SDK's retries for one RunTask. The answer to the
+// last attempt says nothing about the earlier ones: a first attempt that
+// created a task and lost its reply, then a throttled retry, would read as "no
+// task was created", and the job table would clear an execution whose task is
+// running. The job table owns retry and recovery.
+func singleAttempt(o *ecs.Options) { o.RetryMaxAttempts = 1 }
+
// 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 {
@@ -142,24 +150,42 @@ func safeReason(reason string) string {
return clean
}
+// retryableRefusals are API refusals that prove nothing ran and may clear by
+// themselves.
+var retryableRefusals = map[string]bool{
+ "ThrottlingException": true,
+ "TooManyRequestsException": true,
+ "ExpiredTokenException": true,
+}
+
// 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.
+// ECS models few of its errors. ThrottlingException and others 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. A 429 is a
+// refusal whatever its body holds. 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) {
+ if isCode(err, "ConflictException") {
return opError("ecs RunTask", err)
}
code := apiCode(err)
+ if httpStatus(err) == http.StatusTooManyRequests {
+ if code == "" {
+ code = "HTTP 429"
+ }
+ return &media.Rejected{Retryable: true, Reason: code}
+ }
+ var api smithy.APIError
+ if !errors.As(err, &api) || !clientFault(err, api) {
+ return opError("ecs RunTask", err)
+ }
if code == "" {
code = "the API refused the request"
}
- return &media.Rejected{Retryable: code == "ThrottlingException", Reason: code}
+ return &media.Rejected{Retryable: retryableRefusals[code], Reason: code}
}
// clientFault reports whether the API refused the request without acting on
@@ -167,9 +193,9 @@ func runError(err error) error {
// 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 status >= 400 && status < 500 && status != http.StatusRequestTimeout && status != http.StatusConflict
}
- return api.ErrorFault() == smithy.FaultClient || api.ErrorCode() == "ThrottlingException"
+ return api.ErrorFault() == smithy.FaultClient || retryableRefusals[api.ErrorCode()]
}
// Describe reads the tasks in batches. MISSING is an answer, the task's
@@ -224,8 +250,9 @@ func taskOf(t ecstypes.Task) media.Task {
// 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.
+// ListTasks accepts startedBy only as its one filter, and reading both desired
+// statuses needs that filter, so every task of the cluster is listed and each
+// 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
@@ -236,7 +263,6 @@ func (e *engine) ListByStartedBy(ctx context.Context, execution string) (media.T
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 {
@@ -366,9 +392,10 @@ func dropsAll(p *ecstypes.LinuxParameters) bool {
// 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.
+// container that one names in turn. Every volumesFrom entry also counts by
+// itself, as "volumes-from:<container>", even one naming c or an absent
+// container: the source may 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}
@@ -379,20 +406,13 @@ func reachableVolumes(c ecstypes.ContainerDefinition, byName map[string]ecstypes
}
for _, v := range from.VolumesFrom {
name := aws.ToString(v.SourceContainer)
+ reached["volumes-from:"+name] = true
source, ok := byName[name]
- if !ok {
- reached["volumes-from:"+name] = true
- continue
- }
- if visited[name] {
+ if !ok || visited[name] {
continue
}
visited[name] = true
- before := len(reached)
walk(source)
- if len(reached) == before {
- reached["volumes-from:"+name] = true
- }
}
}
walk(c)
diff --git a/internal/mediaaws/grants.go b/internal/mediaaws/grants.go
index e9d579e45..05f6f0875 100644
--- a/internal/mediaaws/grants.go
+++ b/internal/mediaaws/grants.go
@@ -213,13 +213,25 @@ func headPolicy(bucket string) (string, error) {
return marshalPolicy(policyStatement{Effect: "Allow", Action: "s3:GetObject", Resource: "arn:aws:s3:::" + bucket + "/*"})
}
+// checkStoreBucket refuses a bucket that is not one of this deployment's
+// stores, before any call or credential is made for it. The name is written
+// into IAM policies, where "*" and "?" are wildcards, so its shape is part of
+// the policy's meaning; the prefix keeps the console's own authority, and the
+// conversion role's, on store buckets. A config with no prefix admits nothing.
+func (g *grants) checkStoreBucket(bucket string) error {
+ if !bucketPattern.MatchString(bucket) {
+ return &adapterError{op: "store bucket", what: "the bucket is not a bucket name"}
+ }
+ if g.c.StorePrefix == "" || !strings.HasPrefix(bucket, g.c.StorePrefix) {
+ return &adapterError{op: "store bucket", what: "the bucket is outside this deployment's store prefix"}
+ }
+ return nil
+}
+
// 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.
+// The execution is written into an IAM policy, like the bucket.
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):
@@ -267,6 +279,9 @@ func validETag(s string) bool {
// 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 := g.checkStoreBucket(r.Bucket); err != nil {
+ return media.Transfers{}, time.Time{}, err
+ }
if err := checkGrantRequest(r); err != nil {
return media.Transfers{}, time.Time{}, &adapterError{op: "grant", what: err.Error()}
}
@@ -291,10 +306,15 @@ func (g *grants) Grant(ctx context.Context, r media.GrantRequest) (media.Transfe
}
// assumeSession assumes the role and refuses credentials with no expiry: the
-// grant's expiry is the session's, and the payload carries it.
+// grant's expiry is the session's, and the payload carries it. An error the
+// adapter already made safe keeps its API code; any other is sanitised here.
func (g *grants) assumeSession(ctx context.Context, name, policy string) (aws.Credentials, error) {
creds, err := g.assume(ctx, name, policy)
if err != nil {
+ var safe *adapterError
+ if errors.As(err, &safe) {
+ return aws.Credentials{}, safe
+ }
return aws.Credentials{}, opError("assume the conversion role", err)
}
if !creds.CanExpire || creds.Expires.IsZero() {
@@ -425,6 +445,9 @@ func signedHeaders(p *v4.PresignedHTTPRequest, req presignRequest, rawQuery stri
// 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) {
+ if err := g.checkStoreBucket(bucket); err != nil {
+ return media.ObjectHead{}, err
+ }
exists, err := g.listed(ctx, bucket, key)
if err != nil {
return media.ObjectHead{}, err
@@ -591,6 +614,9 @@ func (g *grants) DeleteResult(ctx context.Context, execution string) error {
// 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 {
+ if err := g.checkStoreBucket(bucket); err != nil {
+ return err
+ }
for _, key := range keys {
if !strings.HasPrefix(key, derivedPrefix) {
return &adapterError{op: "s3 DeleteObject", what: "refused a key outside derived/"}
diff --git a/internal/mediaaws/mediaaws_test.go b/internal/mediaaws/mediaaws_test.go
index f449eb14f..973a957cb 100644
--- a/internal/mediaaws/mediaaws_test.go
+++ b/internal/mediaaws/mediaaws_test.go
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io"
+ "net"
"net/http"
"net/http/httptest"
"net/url"
@@ -20,6 +21,7 @@ import (
"strings"
"sync"
"sync/atomic"
+ "syscall"
"testing"
"time"
@@ -110,6 +112,11 @@ func (s *stubECS) ListTasks(_ context.Context, in *ecs.ListTasksInput, _ ...func
s.mu.Lock()
s.lists = append(s.lists, in)
s.mu.Unlock()
+ // AWS: "When you specify startedBy as the filter, it must be the only
+ // filter that you use."
+ if in.StartedBy != nil && (in.DesiredStatus != "" || in.Family != nil || in.ServiceName != nil || in.ContainerInstance != nil || in.LaunchType != "") {
+ return nil, &ecstypes.InvalidParameterException{Message: aws.String("startedBy must be the only filter")}
+ }
return s.list(in)
}
@@ -464,6 +471,7 @@ func TestRunTaskOverrideFits(t *testing.T) {
c := testConfig()
c.Region = "ap-southeast-2"
c.ResultsBucket = "carlos-deployment-bucket-with-a-long-name-0123456789"
+ c.StorePrefix = "carlos-"
bucket := "carlos-" + strings.Repeat("b", 56)
token := strings.Repeat("IQoJb3JpZ2luX2VjE+/=", 70)
if len(token) != 1400 {
@@ -543,6 +551,9 @@ func TestRunErrorsClassified(t *testing.T) {
"token already used": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) {
return nil, &ecstypes.ConflictException{Message: aws.String("no")}
}, want{}},
+ "a throttle with no response": {func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) {
+ return nil, &smithy.GenericAPIError{Code: "ThrottlingException", Message: "no"}
+ }, want{true, true}},
"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{}},
}
@@ -582,6 +593,11 @@ func TestRunErrorsClassified(t *testing.T) {
"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{}},
+ "a 429 with a code": {429, `{"__type":"SomethingNew","message":"slow down"}`, want{true, true}},
+ "an unnamed 429": {429, `<html>slow down</html>`, want{true, true}},
+ "TooManyRequestsException": {400, `{"__type":"TooManyRequestsException","message":"slow down"}`, want{true, true}},
+ "ExpiredTokenException": {400, `{"__type":"ExpiredTokenException","message":"expired"}`, want{true, true}},
+ "a throttle answered 500": {500, `{"__type":"ThrottlingException","message":"odd"}`, want{}},
}
for name, tc := range wire {
t.Run("wire "+name, func(t *testing.T) {
@@ -619,6 +635,78 @@ func TestRunErrorsClassified(t *testing.T) {
})
}
+// TestRunMakesOneAttempt uses a client as production builds it, with the
+// SDK's default retries. A first attempt that may have created a task, then a
+// throttled retry, must never read as "no task was created".
+func TestRunMakesOneAttempt(t *testing.T) {
+ firsts := map[string]func(*http.Request) (*http.Response, error){
+ "a server fault": func(r *http.Request) (*http.Response, error) {
+ return answer(r, 500, map[string]string{"Content-Type": "application/x-amz-json-1.1"}, `{"__type":"ServerException","message":"oops"}`), nil
+ },
+ "a lost reply": func(*http.Request) (*http.Response, error) {
+ return nil, &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET}
+ },
+ }
+ for name, first := range firsts {
+ t.Run(name, func(t *testing.T) {
+ var attempts atomic.Int32
+ client := ecs.NewFromConfig(aws.Config{
+ Region: testRegion,
+ Credentials: credentials.NewStaticCredentialsProvider("AKIDEXAMPLE", "secret", ""),
+ HTTPClient: httpFunc(func(r *http.Request) (*http.Response, error) {
+ if attempts.Add(1) == 1 {
+ return first(r)
+ }
+ return answer(r, 400, map[string]string{"Content-Type": "application/x-amz-json-1.1"}, `{"__type":"ThrottlingException","message":"Rate exceeded"}`), nil
+ }),
+ })
+ _, err := NewEngine(testConfig(), client).Run(context.Background(), runRequest())
+ var rej *media.Rejected
+ if err == nil || errors.As(err, &rej) {
+ t.Fatalf("Run = %v: an ambiguous launch must not read as rejected", err)
+ }
+ if got := attempts.Load(); got != 1 {
+ t.Fatalf("%d HTTP attempts, want 1", got)
+ }
+ })
+ }
+}
+
+// TestFailureReasonsAreKeptSafe: a reason ECS gives reaches operators through
+// both Run and Describe, so both go through the same limits.
+func TestFailureReasonsAreKeptSafe(t *testing.T) {
+ leak := "https://bucket.s3.amazonaws.com/k?X-Amz-Signature=abc&X-Amz-Security-Token=" + testToken
+ tests := map[string]struct{ reason, want string }{
+ "a URL": {leak, "a reason that cannot be shown"},
+ "control bytes": {"RESOURCE:\x00CPU\n", "RESOURCE:CPU"},
+ "not ASCII": {"AGENT\u00e9", "AGENT"},
+ "too long": {strings.Repeat("x", 300), strings.Repeat("x", 200)},
+ "nothing at all": {"", "no reason reported"},
+ }
+ for name, tc := range tests {
+ t.Run(name, func(t *testing.T) {
+ run := &stubECS{run: func(*ecs.RunTaskInput) (*ecs.RunTaskOutput, error) {
+ return &ecs.RunTaskOutput{Failures: []ecstypes.Failure{{Reason: aws.String(tc.reason)}}}, nil
+ }}
+ _, err := NewEngine(testConfig(), run).Run(context.Background(), runRequest())
+ var rej *media.Rejected
+ if !errors.As(err, &rej) || rej.Reason != tc.want {
+ t.Fatalf("Run = %v, want the reason %q", err, tc.want)
+ }
+ assertClean(t, "Run", err)
+
+ describe := &stubECS{describe: func(*ecs.DescribeTasksInput) (*ecs.DescribeTasksOutput, error) {
+ return &ecs.DescribeTasksOutput{Failures: []ecstypes.Failure{{Arn: aws.String("arn:task/1"), Reason: aws.String(tc.reason)}}}, nil
+ }}
+ _, _, err = NewEngine(testConfig(), describe).Describe(context.Background(), []string{"arn:task/1"})
+ if err == nil || !strings.HasSuffix(err.Error(), "a task could not be read: "+tc.want) {
+ t.Fatalf("Describe = %v, want the reason %q", err, tc.want)
+ }
+ assertClean(t, "Describe", err)
+ })
+ }
+}
+
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{
@@ -708,7 +796,7 @@ func TestListByStartedByReadsBothLists(t *testing.T) {
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 {
+ if aws.ToString(in.Cluster) != testConfig().Cluster || in.StartedBy != nil {
t.Fatalf("list input: %+v", in)
}
}
@@ -927,6 +1015,9 @@ func TestCheckRevisionFill(t *testing.T) {
"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 borrows from itself": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) {
+ d.VolumesFrom = []ecstypes.VolumeFrom{{SourceContainer: aws.String(media.ContainerDeadline)}}
+ }, "shared_volume"},
"deadline restarts": {func(_ *ecstypes.TaskDefinition, d, _ *ecstypes.ContainerDefinition) {
d.RestartPolicy = &ecstypes.ContainerRestartPolicy{Enabled: aws.Bool(true)}
}, "restart_policy"},
@@ -960,7 +1051,8 @@ func TestCheckRevisionFill(t *testing.T) {
{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"}) {
+ want := []string{"vb", "vc", "volumes-from:a", "volumes-from:b", "volumes-from:c"}
+ if got := taskDefinition(td).Containers[0].Volumes; !slices.Equal(got, want) {
t.Fatalf("volumes = %v", got)
}
})
@@ -1108,7 +1200,7 @@ func TestGrantPathStyleOnlyForADottedBucket(t *testing.T) {
r := grantRequest()
r.Bucket = "carlos.store.abc"
c := testConfig()
- c.ResultsBucket = "results.with.dots"
+ c.ResultsBucket, c.StorePrefix = "results.with.dots", "carlos."
tr, _, err := NewGrants(c, staticAssume(time.Now().Add(time.Hour)), &stubS3{}).Grant(context.Background(), r)
if err != nil {
t.Fatal(err)
@@ -1122,6 +1214,7 @@ func TestGrantPathStyleOnlyForADottedBucket(t *testing.T) {
// Each bucket chooses for itself: the dotted store does not move an
// undotted results bucket onto a path.
c = testConfig()
+ c.StorePrefix = "carlos."
tr, _, err = NewGrants(c, staticAssume(time.Now().Add(time.Hour)), &stubS3{}).Grant(context.Background(), r)
if err != nil {
t.Fatal(err)
@@ -1427,7 +1520,9 @@ func TestHeadSessionPerBucketRenewedBeforeItExpires(t *testing.T) {
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 }))
+ c := testConfig()
+ c.StorePrefix = "bucket-"
+ g := NewGrants(c, 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 {
@@ -2068,6 +2163,115 @@ func TestBucketTags(t *testing.T) {
}
}
+// TestStoreBucketsOnly: Grant, Head and DeleteOutputs act on this deployment's
+// store buckets and nothing else, and refuse before any call is made.
+func TestStoreBucketsOnly(t *testing.T) {
+ refused := map[string]string{
+ "outside the prefix": "carlos-deployment-results",
+ "a wildcard": "carlos-store-*",
+ "a quote": `carlos-store-"x`,
+ "upper case": "carlos-store-ABC",
+ "empty": "",
+ }
+ check := func(t *testing.T, c Config, bucket string) {
+ t.Helper()
+ // Every collaborator is unset: a call to any of them panics.
+ assume := func(context.Context, string, string) (aws.Credentials, error) {
+ t.Fatal("the role was assumed for a bucket that is refused")
+ return aws.Credentials{}, nil
+ }
+ g := NewGrants(c, assume, &stubS3{})
+ r := grantRequest()
+ r.Bucket = bucket
+ if _, _, err := g.Grant(context.Background(), r); err == nil {
+ t.Error("Grant accepted the bucket")
+ }
+ _, err := g.Head(context.Background(), bucket, "uploads/x")
+ if err == nil || errors.Is(err, media.ErrNotFound) || errors.Is(err, media.ErrDenied) {
+ t.Errorf("Head = %v", err)
+ }
+ if err := g.DeleteOutputs(context.Background(), bucket, []string{"derived/x"}); err == nil {
+ t.Error("DeleteOutputs accepted the bucket")
+ }
+ }
+ for name, bucket := range refused {
+ t.Run(name, func(t *testing.T) { check(t, testConfig(), bucket) })
+ }
+ t.Run("a config with no prefix admits nothing", func(t *testing.T) {
+ c := testConfig()
+ c.StorePrefix = ""
+ check(t, c, testBucket)
+ })
+}
+
+// TestAssumeFailuresKeepTheirCode: an operator reading why a grant failed
+// sees STS's own code.
+func TestAssumeFailuresKeepTheirCode(t *testing.T) {
+ denied := &stubSTS{err: &smithy.GenericAPIError{Code: "AccessDenied", Message: "not authorized on " + testToken}}
+ console := &stubS3{listObjects: func(in *s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) {
+ return &s3.ListObjectsV2Output{Contents: []s3types.Object{{Key: in.Prefix}}}, nil
+ }}
+ g := NewGrants(testConfig(), assumeRole(denied, testConfig().ConversionRole), console)
+ _, _, grantErr := g.Grant(context.Background(), grantRequest())
+ _, headErr := g.Head(context.Background(), testBucket, "uploads/x")
+ for name, err := range map[string]error{"Grant": grantErr, "Head": headErr} {
+ if err == nil || !strings.Contains(err.Error(), "AccessDenied") {
+ t.Errorf("%s = %v, want STS's code", name, err)
+ }
+ if errors.Is(err, media.ErrDenied) {
+ t.Errorf("%s: STS refusing the role is not the object being denied", name)
+ }
+ assertClean(t, name, err)
+ }
+}
+
+func TestNewBucketsRefusesAnEmptyAccount(t *testing.T) {
+ // The stub has no operations set: reaching S3 panics.
+ b := NewBuckets("", &stubS3{})
+ _, inspect := b.Inspect(context.Background(), testBucket)
+ _, tags := b.BucketTags(context.Background(), testBucket)
+ for name, err := range map[string]error{
+ "Inspect": inspect,
+ "BucketTags": tags,
+ "PutUploads": b.PutUploads(context.Background(), testBucket, []string{"https://a.example.com"}),
+ "DeleteUploads": b.DeleteUploads(context.Background(), testBucket),
+ "PutBucketTags": b.PutBucketTags(context.Background(), testBucket, map[string]string{"a": "b"}),
+ } {
+ if err == nil {
+ t.Errorf("%s accepted an empty account", name)
+ }
+ }
+}
+
+// TestCORSCoversEverySDKField fails when an SDK upgrade adds a CORS setting the
+// canonical form does not carry: a rule differing only there would read as the
+// platform's own.
+func TestCORSCoversEverySDKField(t *testing.T) {
+ empty := storecfg.CanonicalCORS([]storecfg.CORSRule{canonicalCORSRule(s3types.CORSRule{})})
+ typ := reflect.TypeOf(s3types.CORSRule{})
+ for i := range typ.NumField() {
+ f := typ.Field(i)
+ if !f.IsExported() {
+ continue
+ }
+ var r s3types.CORSRule
+ v := reflect.ValueOf(&r).Elem().Field(i)
+ switch {
+ case f.Type == reflect.TypeOf((*string)(nil)):
+ v.Set(reflect.ValueOf(aws.String("set")))
+ case f.Type == reflect.TypeOf((*int32)(nil)):
+ v.Set(reflect.ValueOf(aws.Int32(7)))
+ case f.Type == reflect.TypeOf([]string(nil)):
+ v.Set(reflect.ValueOf([]string{"set"}))
+ default:
+ t.Fatalf("field %s has type %s, which this test does not set", f.Name, f.Type)
+ }
+ if got := storecfg.CanonicalCORS([]storecfg.CORSRule{canonicalCORSRule(r)}); bytes.Equal(got, empty) {
+ t.Errorf("field %s does not reach the canonical form", f.Name)
+ }
+ }
+}
+
// 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}
diff --git a/internal/mediaaws/minio_test.go b/internal/mediaaws/minio_test.go
index e2ad5751e..cd58892b0 100644
--- a/internal/mediaaws/minio_test.go
+++ b/internal/mediaaws/minio_test.go
@@ -57,7 +57,7 @@ func TestMediaTransfersMinio(t *testing.T) {
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"} {
+ for _, name := range []string{"MINIO_ENDPOINT", "MEDIA_MINIO_KEY", "MEDIA_MINIO_SECRET", "MEDIA_MINIO_BUCKET", "MEDIA_MINIO_RESULTS", "MEDIA_MINIO_ABSENT_BUCKET"} {
if env[name] = os.Getenv(name); env[name] == "" {
t.Fatalf("%s is not set (required when CARLOS_MINIO_TEST=1)", name)
}
@@ -69,7 +69,7 @@ func TestMediaTransfersMinio(t *testing.T) {
stsClient := sts.New(sts.Options{Region: minioRegion, BaseEndpoint: aws.String(endpoint), Credentials: user})
c := testConfig()
- c.Region, c.ResultsBucket = minioRegion, env["MEDIA_MINIO_RESULTS"]
+ c.Region, c.ResultsBucket, c.StorePrefix = minioRegion, env["MEDIA_MINIO_RESULTS"], bucket
g := NewGrants(c, assumeRole(stsClient, "arn:minio:iam:::role/media-conversion"), console, WithS3Endpoint(endpoint))
execution, err := media.NewExecutionID()
@@ -212,7 +212,10 @@ func TestMediaTransfersMinio(t *testing.T) {
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 {
+ // MinIO authorises before it looks for the bucket, so the user may delete
+ // in this one absent bucket: the answer is NoSuchBucket, and a denial
+ // stays fatal.
+ if err := g.DeleteOutputs(ctx, env["MEDIA_MINIO_ABSENT_BUCKET"], 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 {