console: refuse an engine beside a custom store, meter its S3 calls
Review rulings on the media wiring. An engine set together with CARLOS_STORE_ENDPOINT now stops the boot: its transfers would go to AWS S3 and not to that store. mediaaws.New takes options, and WithS3HTTP puts the console's own S3 client and the conversion role's sessions on the request meter, so a Head's listing and HEAD are both counted. A cloud that does not answer at boot still leaves media off until the next start. The log line is the deck's console.media.off_at_boot, pending a Luna pass, and the boot witness reads the real CLI's "engine not configured".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+176
−14
cmd/console/main.go+2 −1cmd/console/media.go+20 −6cmd/console/media_serve_test.go+39 −3cmd/console/media_test.go+85 −0docs/superpowers/notes/media-conversion-copy-deck.md+1 −0internal/mediaaws/config.go+17 −3internal/mediaaws/grants.go+12 −1
diff --git a/cmd/console/main.go b/cmd/console/main.go| index c03fa5eae..018587ce5 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -50,7 +50,8 @@ |
| // |
| // Media conversion is off unless CARLOS_MEDIA_ENGINE is set to the |
| // media-engine module's output, which needs CARLOS_STORE_CONVERSION=1 and a |
| -// store backend in the engine's region, account and bucket prefix. |
| +// store backend in the engine's region, account and bucket prefix, with no |
| +// CARLOS_STORE_ENDPOINT. |
| // CARLOS_STORE_CONVERSION=1 alone turns on browser uploads. CARLOS_MEDIA_LIMITS |
| // overrides the engine's limits. See media.go. |
| // |
diff --git a/cmd/console/media.go b/cmd/console/media.go| index 0c0c3e7f1..2461a8a8f 100644 |
| --- a/cmd/console/media.go |
| +++ b/cmd/console/media.go |
| @@ -26,6 +26,10 @@ import ( |
| // sts:GetCallerIdentity and loading the AWS configuration. |
| const mediaBootTimeout = 30 * time.Second |
| +// mediaOffAtBoot is the deck's console.media.off_at_boot, logged once when |
| +// the cloud does not answer at boot. |
| +const mediaOffAtBoot = "console: media conversion is off until the next start: %v" |
| + |
| // errMediaCloud marks a media wiring failure that is the cloud's and not the |
| // operator's: the settings are fine, but the account could not be read or a |
| // client could not be built. mediaConfig boots past it with media off. |
| @@ -49,9 +53,11 @@ type mediaClients struct { |
| newEngine func(ctx context.Context, c mediaaws.Config) (media.Engine, media.Grants, error) |
| } |
| -// realMediaClients builds the AWS adapters. Store settings calls are timed |
| -// and counted on rec like the console's other S3 calls. |
| -func realMediaClients(rec *perf.Recorder) mediaClients { |
| +// realMediaClients builds the AWS adapters. Every S3 request they send is |
| +// timed and counted on rec like the console's other S3 calls. engineOpts are |
| +// added to the engine's options: a test's stub endpoint, and nothing in |
| +// production. |
| +func realMediaClients(rec *perf.Recorder, engineOpts ...mediaaws.GrantsOption) mediaClients { |
| return mediaClients{ |
| identity: callerAccount, |
| newS3: func(ctx context.Context, region, endpoint string) (mediaaws.S3API, error) { |
| @@ -62,7 +68,10 @@ func realMediaClients(rec *perf.Recorder) mediaClients { |
| wrap := console.TimeS3HTTP(rec) |
| return awss3.New(client.Options(), func(o *awss3.Options) { o.HTTPClient = wrap(o.HTTPClient) }), nil |
| }, |
| - newEngine: mediaaws.New, |
| + newEngine: func(ctx context.Context, c mediaaws.Config) (media.Engine, media.Grants, error) { |
| + opts := append([]mediaaws.GrantsOption{mediaaws.WithS3HTTP(console.TimeS3HTTP(rec))}, engineOpts...) |
| + return mediaaws.New(ctx, c, opts...) |
| + }, |
| } |
| } |
| @@ -102,6 +111,10 @@ func mediaEngineConfig(getenv func(string) string, raw string, store storeEnv) ( |
| if err != nil { |
| return mediaaws.Config{}, media.Limits{}, fmt.Errorf("CARLOS_MEDIA_ENGINE: %w", err) |
| } |
| + // The value is not quoted: an endpoint URL can carry credentials. |
| + if store.Endpoint != "" { |
| + return mediaaws.Config{}, media.Limits{}, errors.New("CARLOS_MEDIA_ENGINE: CARLOS_STORE_ENDPOINT is also set, and the engine's transfers go to AWS S3, not to that store; unset one of them") |
| + } |
| if c.Region != store.Region { |
| return mediaaws.Config{}, media.Limits{}, fmt.Errorf("CARLOS_MEDIA_ENGINE: the engine is in region %s but CARLOS_STORE_REGION is %s; an engine converts only from stores in its own region", c.Region, store.Region) |
| } |
| @@ -187,7 +200,8 @@ func mediaFromEnv(ctx context.Context, getenv func(string) string, store storeEn |
| // storeBackend's do. A cloud that does not answer does not: as with |
| // mailBackends, one feature's dependency being briefly unreachable must not |
| // take down every other door, so the console boots with media off and says |
| -// so. The next start tries again. |
| +// so, and `carlos system media status` shows the engine as not configured. |
| +// The next start tries again. |
| func mediaConfig(store objstore.Deployment, rec *perf.Recorder) console.MediaConfig { |
| // Detached: serve has no context of its own this early in the boot. |
| ctx, cancel := context.WithTimeout(context.Background(), mediaBootTimeout) |
| @@ -199,7 +213,7 @@ func mediaConfig(store objstore.Deployment, rec *perf.Recorder) console.MediaCon |
| }, realMediaClients(rec)) |
| cancel() |
| if errors.Is(err, errMediaCloud) { |
| - log.Printf("console: media conversion is off until the next start: %v", err) |
| + log.Printf(mediaOffAtBoot, err) |
| return console.MediaConfig{} |
| } |
| if err != nil { |
diff --git a/cmd/console/media_serve_test.go b/cmd/console/media_serve_test.go| index acdbcc258..28dbe038a 100644 |
| --- a/cmd/console/media_serve_test.go |
| +++ b/cmd/console/media_serve_test.go |
| @@ -280,6 +280,34 @@ func (c *runningConsole) status(t *testing.T) mediaStatus { |
| return out |
| } |
| +// operatorStatus is what `carlos system media status` prints to the operator, |
| +// from the real CLI logged in to this console. |
| +func (c *runningConsole) operatorStatus(t *testing.T, carlos string) string { |
| + t.Helper() |
| + dir := t.TempDir() |
| + origin := "http://" + c.addr |
| + creds, err := json.Marshal(map[string]any{"version": 1, "credentials": []map[string]string{ |
| + {"console": origin, "address": mediaWitnessOperator, "token": c.token}, |
| + }}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + path := filepath.Join(dir, "credentials") |
| + if err := os.WriteFile(path, creds, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, carlos, "system", "media", "status", "--console", origin) |
| + cmd.Dir = dir |
| + cmd.Env = []string{"HOME=" + dir, "CARLOS_CREDENTIALS=" + path, "NO_PROXY=127.0.0.1"} |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("carlos system media status: %v\n%s", err, out) |
| + } |
| + return string(out) |
| +} |
| + |
| // refusal runs serve expecting it to stop at boot, and answers what it said. |
| func (w mediaWitness) refusal(t *testing.T, extra ...string) string { |
| t.Helper() |
| @@ -307,7 +335,11 @@ func TestServeMediaWiring(t *testing.T) { |
| // clients must never reach AWS. |
| t.Skip("the stub endpoint is scrubbed from a console running as root") |
| } |
| - bin, _ := buildConsole(t) |
| + bin, binDir := buildConsole(t) |
| + carlos := filepath.Join(binDir, "carlos") |
| + if out, err := exec.Command("go", "build", "-o", carlos, "../..").CombinedOutput(); err != nil { |
| + t.Fatalf("build carlos: %v\n%s", err, out) |
| + } |
| t.Run("an engine reaches the door and the checks", func(t *testing.T) { |
| w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)} |
| @@ -364,8 +396,11 @@ func TestServeMediaWiring(t *testing.T) { |
| if got := c.status(t); got.Configured || got.Region != "" { |
| t.Fatalf("status = %+v", got) |
| } |
| - if !strings.Contains(c.output(), "media conversion is off") { |
| - t.Fatalf("the boot log does not say media is off:\n%s", c.output()) |
| + if n := strings.Count(c.output(), strings.TrimSuffix(mediaOffAtBoot, "%v")); n != 1 { |
| + t.Fatalf("the boot log says media is off %d times, want once:\n%s", n, c.output()) |
| + } |
| + if got := c.operatorStatus(t, carlos); got != "engine not configured\n" { |
| + t.Fatalf("carlos system media status printed %q", got) |
| } |
| }) |
| @@ -388,6 +423,7 @@ func TestServeMediaWiring(t *testing.T) { |
| {"engine without conversion", []string{"CARLOS_MEDIA_ENGINE=" + testMediaEngine(t, nil)}, "CARLOS_STORE_CONVERSION=1"}, |
| {"another prefix", []string{"CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE=" + testMediaEngine(t, func(c *mediaaws.Config) { c.StorePrefix = "other-" })}, "CARLOS_STORE_BUCKET_PREFIX"}, |
| {"another account", []string{"CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE=" + testMediaEngine(t, foreign)}, "account"}, |
| + {"custom store endpoint", []string{"CARLOS_STORE_CONVERSION=1", "CARLOS_STORE_ENDPOINT=http://127.0.0.1:9", "CARLOS_MEDIA_ENGINE=" + testMediaEngine(t, nil)}, "CARLOS_STORE_ENDPOINT"}, |
| {"malformed limits", []string{"CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE=" + testMediaEngine(t, nil), "CARLOS_MEDIA_LIMITS=short=none"}, "CARLOS_MEDIA_LIMITS"}, |
| {"conversion misspelt", []string{"CARLOS_STORE_CONVERSION=yes"}, "CARLOS_STORE_CONVERSION"}, |
| } { |
diff --git a/cmd/console/media_test.go b/cmd/console/media_test.go| index 4fdc14540..f32d64f42 100644 |
| --- a/cmd/console/media_test.go |
| +++ b/cmd/console/media_test.go |
| @@ -4,7 +4,13 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| "strings" |
| + "sync" |
| "testing" |
| "time" |
| @@ -12,6 +18,7 @@ import ( |
| "github.com/carlosframework/platform/internal/media" |
| "github.com/carlosframework/platform/internal/media/mediatest" |
| "github.com/carlosframework/platform/internal/mediaaws" |
| + "github.com/carlosframework/platform/internal/perf" |
| ) |
| const ( |
| @@ -261,6 +268,12 @@ func TestMediaFromEnvRefusals(t *testing.T) { |
| })}, |
| want: "account", |
| }, |
| + { |
| + name: "engine with a custom store endpoint", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": engine(nil)}, |
| + store: func(s *storeEnv) { s.Endpoint = "http://" + secret + "@127.0.0.1:9000" }, |
| + want: "CARLOS_STORE_ENDPOINT", |
| + }, |
| { |
| name: "malformed limits", |
| env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": engine(nil), "CARLOS_MEDIA_LIMITS": "short=none"}, |
| @@ -340,3 +353,75 @@ func TestMediaFromEnvCloudFailures(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// The boot's one log line is the deck's row. |
| +func TestMediaOffAtBootIsTheDecksWording(t *testing.T) { |
| + deck, err := os.ReadFile("../../docs/superpowers/notes/media-conversion-copy-deck.md") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(string(deck), "| `console.media.off_at_boot` | `"+mediaOffAtBoot+"`") { |
| + t.Fatalf("the deck has no console.media.off_at_boot row reading %q", mediaOffAtBoot) |
| + } |
| +} |
| + |
| +// Every S3 request the engine's adapters send lands on the console's request |
| +// meter, through the clients production builds: the console's own listing and |
| +// the conversion role's HEAD. STS is not S3 and is not counted. |
| +func TestEngineS3RequestsAreCounted(t *testing.T) { |
| + if os.Geteuid() == 0 { |
| + t.Skip("the stub endpoint is scrubbed from a console running as root") |
| + } |
| + var mu sync.Mutex |
| + seen := map[string]int{} |
| + stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + mu.Lock() |
| + defer mu.Unlock() |
| + switch { |
| + case r.Method == http.MethodHead: |
| + seen["head"]++ |
| + w.Header().Set("ETag", `"0123456789abcdef0123456789abcdef"`) |
| + w.Header().Set("Content-Length", "5") |
| + case r.URL.Query().Get("list-type") == "2": |
| + seen["list"]++ |
| + w.Header().Set("Content-Type", "application/xml") |
| + fmt.Fprint(w, `<ListBucketResult><KeyCount>1</KeyCount><Contents><Key>uploads/clip.mov</Key></Contents></ListBucketResult>`) |
| + case strings.Contains(string(body), "Action=AssumeRole"): |
| + seen["assume"]++ |
| + w.Header().Set("Content-Type", "text/xml") |
| + fmt.Fprintf(w, `<AssumeRoleResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><AssumeRoleResult><Credentials><AccessKeyId>ASIASTUB</AccessKeyId><SecretAccessKey>stub</SecretAccessKey><SessionToken>stub</SessionToken><Expiration>%s</Expiration></Credentials></AssumeRoleResult></AssumeRoleResponse>`, |
| + time.Now().Add(time.Hour).UTC().Format(time.RFC3339)) |
| + default: |
| + seen["other"]++ |
| + w.WriteHeader(http.StatusNotFound) |
| + } |
| + })) |
| + defer stub.Close() |
| + t.Setenv("HOME", t.TempDir()) |
| + t.Setenv("AWS_ENDPOINT_URL", stub.URL) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "AKIASTUBSTUBSTUBSTUB") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "stub") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + |
| + rec := new(perf.Recorder) |
| + _, grants, err := realMediaClients(rec, mediaaws.WithS3Endpoint(stub.URL)).newEngine(context.Background(), testMediaConfig()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + head, err := grants.Head(context.Background(), testMediaPrefix+"shop", "uploads/clip.mov") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if head.Size != 5 { |
| + t.Fatalf("head = %+v", head) |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if seen["list"] != 1 || seen["head"] != 1 || seen["assume"] != 1 || seen["other"] != 0 { |
| + t.Fatalf("the stub saw %v", seen) |
| + } |
| + if got := rec.Background()["s3"]; got != 2 { |
| + t.Fatalf("the meter counted %d S3 requests, want the listing and the HEAD", got) |
| + } |
| +} |
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index 86ccc8e06..ad3ecdbdb 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -690,3 +690,4 @@ for whoever deploys the console and are not listed here. |
| | `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, `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) | |
| +| `console.media.off_at_boot` | `console: media conversion is off until the next start: %v`, logged once at boot when the cloud account cannot be read or a client cannot be built. `%v` starts `the cloud account could not be reached: ` and goes on to the failure (pending Luna pass; plan 3 Task 10 fix 1) | |
diff --git a/internal/mediaaws/config.go b/internal/mediaaws/config.go| index ab1013301..ad9fc635f 100644 |
| --- a/internal/mediaaws/config.go |
| +++ b/internal/mediaaws/config.go |
| @@ -181,14 +181,28 @@ type S3API interface { |
| } |
| // 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) { |
| +// default AWS configuration, in the config's region. WithS3Endpoint and |
| +// WithS3HTTP apply to the console's own S3 client as well as to the sessions. |
| +func New(ctx context.Context, c Config, opts ...GrantsOption) (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) |
| } |
| + var o grantsOptions |
| + for _, opt := range opts { |
| + opt(&o) |
| + } |
| + console := s3.NewFromConfig(cfg, func(s *s3.Options) { |
| + if o.endpoint != "" { |
| + s.BaseEndpoint = aws.String(o.endpoint) |
| + s.UsePathStyle = true |
| + } |
| + if o.wrapHTTP != nil { |
| + s.HTTPClient = o.wrapHTTP(s.HTTPClient) |
| + } |
| + }) |
| assume := assumeRole(sts.NewFromConfig(cfg), c.ConversionRole) |
| - return NewEngine(c, ecs.NewFromConfig(cfg)), NewGrants(c, assume, s3.NewFromConfig(cfg)), nil |
| + return NewEngine(c, ecs.NewFromConfig(cfg)), NewGrants(c, assume, console, opts...), nil |
| } |
| // sessionSeconds is the life of every assumed session: the longest a role |
diff --git a/internal/mediaaws/grants.go b/internal/mediaaws/grants.go| index 05f6f0875..30f1c3b57 100644 |
| --- a/internal/mediaaws/grants.go |
| +++ b/internal/mediaaws/grants.go |
| @@ -74,6 +74,7 @@ type GrantsOption func(*grantsOptions) |
| type grantsOptions struct { |
| endpoint string |
| + wrapHTTP func(s3.HTTPClient) s3.HTTPClient |
| presign presignFunc |
| sessionS3 func(aws.Credentials, string) S3API |
| now func() time.Time |
| @@ -86,6 +87,12 @@ func WithS3Endpoint(endpoint string) GrantsOption { |
| return func(o *grantsOptions) { o.endpoint = endpoint } |
| } |
| +// WithS3HTTP wraps the HTTP client of every S3 client that sends requests, so |
| +// the console can count them: S3 requests cost money. Presigning sends none. |
| +func WithS3HTTP(wrap func(s3.HTTPClient) s3.HTTPClient) GrantsOption { |
| + return func(o *grantsOptions) { o.wrapHTTP = wrap } |
| +} |
| + |
| func withPresigner(f presignFunc) GrantsOption { |
| return func(o *grantsOptions) { o.presign = f } |
| } |
| @@ -110,8 +117,12 @@ func NewGrants(c Config, assume func(ctx context.Context, sessionName, policy st |
| o.presign = realPresigner(c.Region, o.endpoint, client) |
| } |
| if o.sessionS3 == nil { |
| + var sessionHTTP aws.HTTPClient = client |
| + if o.wrapHTTP != nil { |
| + sessionHTTP = o.wrapHTTP(client) |
| + } |
| o.sessionS3 = func(creds aws.Credentials, bucket string) S3API { |
| - return s3.New(sessionOptions(c.Region, o.endpoint, client, creds, bucket)) |
| + return s3.New(sessionOptions(c.Region, o.endpoint, sessionHTTP, creds, bucket)) |
| } |
| } |
| if o.now == nil { |