console: wire media conversion from the environment
serve reads CARLOS_STORE_CONVERSION, CARLOS_MEDIA_ENGINE and CARLOS_MEDIA_LIMITS through mediaConfig (media.go) and connects the mediaaws adapters to the door, the pass and the store checks. With the settings unset nothing is read and no cloud call is made. A wrong setting stops the boot and names the variable without quoting the engine value: an engine in another region, store prefix or account is refused. A cloud that does not answer boots with media off, as mailBackends does, so one dependency cannot take down every other door. TestServeMediaWiring drives the built console through serve with every AWS client pointed at a local stub. The PDF settings move to pdf.go to pay for the new lines in serve, whose record drops to 367.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+1,003
−19
.amadan/code-health.tsv+1 −1cmd/console/main.go+11 −18cmd/console/media.go+209 −0cmd/console/media_serve_test.go+406 −0cmd/console/media_test.go+342 −0cmd/console/pdf.go+34 −0
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 836bf624a..984e3f3d6 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -2182,7 +2182,7 @@ host-context internal/host withEffectiveMovesFloorLock context.Background 2 |
| func-lines . TestFleetAppServesThroughTheHub - 408 |
| func-lines . runDeploy - 329 |
| func-lines . runRoute - 519 |
| -func-lines cmd/console serve - 369 |
| +func-lines cmd/console serve - 367 |
| func-lines internal/activator (*Service).doWakeOnce - 567 |
| func-lines internal/analytics Prune - 343 |
| func-lines internal/appconfig SyncExecWithCallbacks - 320 |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 6700d3d90..c03fa5eae 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -48,6 +48,12 @@ |
| // member's own verb and destroy is the account owner's browser ceremony; |
| // it is read whether or not a backend is configured. |
| // |
| +// 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. |
| +// CARLOS_STORE_CONVERSION=1 alone turns on browser uploads. CARLOS_MEDIA_LIMITS |
| +// overrides the engine's limits. See media.go. |
| +// |
| // CARLOS_TEMPORARY_APPS=1 turns on temporary apps (carlos deploy |
| // --temporary); off by default, see the temporary static sites rollout. |
| // |
| @@ -147,7 +153,6 @@ import ( |
| "log" |
| "math/rand/v2" |
| "net" |
| - "net/url" |
| "os" |
| "os/signal" |
| "path/filepath" |
| @@ -408,14 +413,13 @@ func serve() { |
| rec := new(perf.Recorder) |
| storeProvisioner, storeDeployment := storeBackend(rec) |
| storeScanner, seedAntivirus := storeScannerFor(storeDeployment) |
| - pdfLimits, err := console.ParsePDFLimits(os.Getenv("CARLOS_PDF_LIMITS")) |
| - if err != nil { |
| - log.Fatalf("console: %v", err) |
| - } |
| - pdfAddr, err := pdfEngine(os.Getenv) |
| + pdfLimits, pdfAddr, err := pdfSettings(os.Getenv) |
| if err != nil { |
| log.Fatalf("console: %v", err) |
| } |
| + // Media conversion (media.go): off with its settings unset, and a wrong |
| + // setting stops the boot here. |
| + mediaCfg := mediaConfig(storeDeployment, rec) |
| catalog, err := planCatalog() |
| if err != nil { |
| // A broken catalog must never quietly mean "no limits". |
| @@ -618,6 +622,7 @@ func serve() { |
| StoreScanner: storeScanner, |
| PDFEngine: pdfAddr, |
| PDFLimits: pdfLimits, |
| + MediaConfig: mediaCfg, |
| ScanSeedFromDeprecatedEnv: seedAntivirus, |
| ScanBudget: envDuration("CARLOS_STORE_SCAN_BUDGET", time.Minute), |
| ScanInterval: envDuration("CARLOS_STORE_SCAN_INTERVAL", 24*time.Hour), |
| @@ -2222,18 +2227,6 @@ func regionIngress(getenv func(string) string) ([]string, error) { |
| return console.ParseRegionIngress(getenv("CONSOLE_REGION_INGRESS")) |
| } |
| -func pdfEngine(getenv func(string) string) (string, error) { |
| - addr := strings.TrimSpace(getenv("CARLOS_PDF_ADDR")) |
| - if addr == "" { |
| - return "", nil |
| - } |
| - u, err := url.Parse(addr) |
| - if err != nil || u.Scheme != "http" || u.Hostname() == "" { |
| - return "", fmt.Errorf("CARLOS_PDF_ADDR must be an http:// URL with a host") |
| - } |
| - return addr, nil |
| -} |
| - |
| // startHACapacity keeps observation independent of claim-worker activation. |
| func startHACapacity(ctx context.Context, srv *console.Server, cfg console.Config) <-chan struct{} { |
| if len(cfg.HARegions) > 0 || strings.TrimSpace(os.Getenv("CARLOS_REGION_METRICS")) == "cloudwatch" { |
diff --git a/cmd/console/media.go b/cmd/console/media.go| new file mode 100644 |
| index 000000000..0c0c3e7f1 |
| --- /dev/null |
| +++ b/cmd/console/media.go |
| @@ -0,0 +1,209 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "strings" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/media" |
| + "github.com/carlosframework/platform/internal/mediaaws" |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/perf" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +// mediaBootTimeout bounds the cloud calls media wiring makes at boot: one |
| +// sts:GetCallerIdentity and loading the AWS configuration. |
| +const mediaBootTimeout = 30 * time.Second |
| + |
| +// 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. |
| +var errMediaCloud = errors.New("the cloud account could not be reached") |
| + |
| +// storeEnv is the part of CARLOS_STORE_* media wiring compares the engine |
| +// with: storeBackend's checked values, Backend "" on a deployment with no |
| +// object storage. |
| +type storeEnv struct { |
| + Backend, Region, Prefix, Endpoint string |
| +} |
| + |
| +// mediaClients are the cloud half of mediaFromEnv, so a test reaches every |
| +// branch with no network and no credential. realMediaClients is production's. |
| +type mediaClients struct { |
| + // identity answers the account the console's own credentials are in. |
| + identity func(ctx context.Context, region string) (string, error) |
| + // newS3 builds the client that reads and writes store bucket settings. |
| + newS3 func(ctx context.Context, region, endpoint string) (mediaaws.S3API, error) |
| + // newEngine builds the engine and the grants. |
| + 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 { |
| + return mediaClients{ |
| + identity: callerAccount, |
| + newS3: func(ctx context.Context, region, endpoint string) (mediaaws.S3API, error) { |
| + client, err := objstore.S3ClientFor(ctx, region, endpoint) |
| + if err != nil { |
| + return nil, err |
| + } |
| + wrap := console.TimeS3HTTP(rec) |
| + return awss3.New(client.Options(), func(o *awss3.Options) { o.HTTPClient = wrap(o.HTTPClient) }), nil |
| + }, |
| + newEngine: mediaaws.New, |
| + } |
| +} |
| + |
| +// callerAccount is sts:GetCallerIdentity's account. |
| +func callerAccount(ctx context.Context, region string) (string, error) { |
| + cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(region)) |
| + if err != nil { |
| + return "", fmt.Errorf("load AWS configuration: %w", err) |
| + } |
| + out, err := sts.NewFromConfig(cfg).GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) |
| + if err != nil { |
| + return "", fmt.Errorf("sts GetCallerIdentity: %w", err) |
| + } |
| + return aws.ToString(out.Account), nil |
| +} |
| + |
| +// storeConversionOn reads CARLOS_STORE_CONVERSION. A value that is neither on |
| +// nor off is refused: read as off, a typo would leave uploads and conversion |
| +// refusing on a deployment whose operator turned them on. |
| +func storeConversionOn(getenv func(string) string) (bool, error) { |
| + switch v := strings.TrimSpace(getenv("CARLOS_STORE_CONVERSION")); v { |
| + case "", "0": |
| + return false, nil |
| + case "1": |
| + return true, nil |
| + default: |
| + return false, fmt.Errorf("CARLOS_STORE_CONVERSION %q is not a value this build knows: set 1 to turn it on, or leave it unset", v) |
| + } |
| +} |
| + |
| +// mediaEngineConfig parses CARLOS_MEDIA_ENGINE and CARLOS_MEDIA_LIMITS and |
| +// holds the engine to the deployment's stores. Its errors never quote the |
| +// engine setting: mediaaws.ParseConfig's name the field at fault, not its |
| +// value. |
| +func mediaEngineConfig(getenv func(string) string, raw string, store storeEnv) (mediaaws.Config, media.Limits, error) { |
| + c, err := mediaaws.ParseConfig(raw) |
| + if err != nil { |
| + return mediaaws.Config{}, media.Limits{}, fmt.Errorf("CARLOS_MEDIA_ENGINE: %w", err) |
| + } |
| + 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) |
| + } |
| + if c.StorePrefix != store.Prefix { |
| + return mediaaws.Config{}, media.Limits{}, fmt.Errorf("CARLOS_MEDIA_ENGINE: the engine's store_prefix is %q but CARLOS_STORE_BUCKET_PREFIX is %q; the conversion role can reach only buckets under its own prefix", c.StorePrefix, store.Prefix) |
| + } |
| + limits, err := media.ParseLimits(getenv("CARLOS_MEDIA_LIMITS")) |
| + if err != nil { |
| + return mediaaws.Config{}, media.Limits{}, fmt.Errorf("CARLOS_MEDIA_LIMITS: %w", err) |
| + } |
| + return c, limits, nil |
| +} |
| + |
| +// mediaFromEnv is the media half of the console's config, from |
| +// CARLOS_STORE_CONVERSION, CARLOS_MEDIA_ENGINE and CARLOS_MEDIA_LIMITS. With |
| +// the first two unset it reads nothing else and calls nothing: the console |
| +// has no engine and its doors answer not_configured. |
| +// |
| +// CARLOS_STORE_CONVERSION=1 alone is browser uploads, which need the store |
| +// bucket settings and no engine. CARLOS_MEDIA_LIMITS is read only with an |
| +// engine, the one thing it limits. |
| +// |
| +// A setting that is wrong is an error, decided before any cloud call where it |
| +// can be. A cloud that does not answer is errMediaCloud. Either way nothing is |
| +// half configured. A host-claim console is not refused here: both doors and |
| +// the pass already refuse there (spec A1). |
| +func mediaFromEnv(ctx context.Context, getenv func(string) string, store storeEnv, clients mediaClients) (console.MediaConfig, error) { |
| + conversion, err := storeConversionOn(getenv) |
| + if err != nil { |
| + return console.MediaConfig{}, err |
| + } |
| + rawEngine := strings.TrimSpace(getenv("CARLOS_MEDIA_ENGINE")) |
| + if !conversion && rawEngine == "" { |
| + return console.MediaConfig{}, nil |
| + } |
| + if !conversion { |
| + return console.MediaConfig{}, errors.New("CARLOS_MEDIA_ENGINE is set: also set CARLOS_STORE_CONVERSION=1 (conversion reads and sets store bucket settings)") |
| + } |
| + if store.Backend == "" { |
| + return console.MediaConfig{}, errors.New("CARLOS_STORE_CONVERSION=1 is set: also set CARLOS_STORE_BACKEND (there are no object stores on this deployment)") |
| + } |
| + var engine mediaaws.Config |
| + var limits media.Limits |
| + if rawEngine != "" { |
| + if engine, limits, err = mediaEngineConfig(getenv, rawEngine, store); err != nil { |
| + return console.MediaConfig{}, err |
| + } |
| + } |
| + |
| + account, err := clients.identity(ctx, store.Region) |
| + if err != nil { |
| + return console.MediaConfig{}, fmt.Errorf("%w: %v", errMediaCloud, err) |
| + } |
| + if account == "" { |
| + return console.MediaConfig{}, fmt.Errorf("%w: sts GetCallerIdentity answered no account", errMediaCloud) |
| + } |
| + if rawEngine != "" && engine.AccountID != account { |
| + return console.MediaConfig{}, fmt.Errorf("CARLOS_MEDIA_ENGINE: the engine is in account %s but this console's credentials are in account %s", engine.AccountID, account) |
| + } |
| + s3Client, err := clients.newS3(ctx, store.Region, store.Endpoint) |
| + if err != nil { |
| + return console.MediaConfig{}, fmt.Errorf("%w: %v", errMediaCloud, err) |
| + } |
| + cfg := console.MediaConfig{ |
| + StoreConversion: true, |
| + StoreBuckets: mediaaws.NewBuckets(account, s3Client), |
| + StoreAccountID: account, |
| + } |
| + if rawEngine == "" { |
| + return cfg, nil |
| + } |
| + cfg.MediaEngine, cfg.MediaGrants, err = clients.newEngine(ctx, engine) |
| + if err != nil { |
| + return console.MediaConfig{}, fmt.Errorf("%w: %v", errMediaCloud, err) |
| + } |
| + cfg.MediaLimits = limits |
| + cfg.MediaRegion = engine.Region |
| + cfg.MediaImage = engine.Image |
| + return cfg, nil |
| +} |
| + |
| +// mediaConfig is serve's media wiring. A wrong setting stops the boot, as |
| +// 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. |
| +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) |
| + cfg, err := mediaFromEnv(ctx, os.Getenv, storeEnv{ |
| + Backend: store.Backend, |
| + Region: store.Region, |
| + Prefix: store.BucketPrefix, |
| + Endpoint: store.Endpoint, |
| + }, realMediaClients(rec)) |
| + cancel() |
| + if errors.Is(err, errMediaCloud) { |
| + log.Printf("console: media conversion is off until the next start: %v", err) |
| + return console.MediaConfig{} |
| + } |
| + if err != nil { |
| + log.Fatalf("console: %v", err) |
| + } |
| + return cfg |
| +} |
diff --git a/cmd/console/media_serve_test.go b/cmd/console/media_serve_test.go| new file mode 100644 |
| index 000000000..acdbcc258 |
| --- /dev/null |
| +++ b/cmd/console/media_serve_test.go |
| @@ -0,0 +1,406 @@ |
| +//go:build !windows |
| + |
| +package main |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/mediaaws" |
| +) |
| + |
| +const mediaWitnessOperator = "operator@example.com" |
| + |
| +// mediaCloudStub stands in for AWS: the built console's every AWS client is |
| +// pointed here by AWS_ENDPOINT_URL. It answers sts:GetCallerIdentity and |
| +// records what reaches it. |
| +type mediaCloudStub struct { |
| + srv *httptest.Server |
| + |
| + mu sync.Mutex |
| + account string |
| + denyIdent bool |
| + identities int |
| + revisions map[string]int |
| +} |
| + |
| +func newMediaCloudStub(t *testing.T) *mediaCloudStub { |
| + t.Helper() |
| + s := &mediaCloudStub{account: testMediaAccount, revisions: map[string]int{}} |
| + s.srv = httptest.NewServer(http.HandlerFunc(s.serve)) |
| + t.Cleanup(s.srv.Close) |
| + return s |
| +} |
| + |
| +func (s *mediaCloudStub) serve(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if strings.HasSuffix(r.Header.Get("X-Amz-Target"), ".DescribeTaskDefinition") { |
| + var in struct { |
| + TaskDefinition string `json:"taskDefinition"` |
| + } |
| + _ = json.Unmarshal(body, &in) |
| + s.revisions[in.TaskDefinition]++ |
| + w.Header().Set("Content-Type", "application/x-amz-json-1.1") |
| + w.WriteHeader(http.StatusBadRequest) |
| + fmt.Fprint(w, `{"__type":"ClientException","message":"stub"}`) |
| + return |
| + } |
| + form, _ := url.ParseQuery(string(body)) |
| + // The infrastructure inventory (internal/awsinv) is the console's other |
| + // caller of GetCallerIdentity, from a background worker. Denied here as |
| + // on a deployment with no inventory grant, it stops before that call, so |
| + // every identity counted below is media wiring's. |
| + if form.Get("Action") == "DescribeRegions" { |
| + w.Header().Set("Content-Type", "text/xml") |
| + w.WriteHeader(http.StatusForbidden) |
| + fmt.Fprint(w, `<Response><Errors><Error><Code>UnauthorizedOperation</Code><Message>stub</Message></Error></Errors><RequestID>stub</RequestID></Response>`) |
| + return |
| + } |
| + if form.Get("Action") == "GetCallerIdentity" { |
| + s.identities++ |
| + w.Header().Set("Content-Type", "text/xml") |
| + if s.denyIdent { |
| + w.WriteHeader(http.StatusForbidden) |
| + fmt.Fprint(w, `<ErrorResponse><Error><Type>Sender</Type><Code>InvalidClientTokenId</Code><Message>stub</Message></Error></ErrorResponse>`) |
| + return |
| + } |
| + fmt.Fprintf(w, `<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><GetCallerIdentityResult><Arn>arn:aws:iam::%[1]s:role/console</Arn><UserId>stub</UserId><Account>%[1]s</Account></GetCallerIdentityResult><ResponseMetadata><RequestId>stub</RequestId></ResponseMetadata></GetCallerIdentityResponse>`, s.account) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNotFound) |
| +} |
| + |
| +// denyIdentity makes GetCallerIdentity answer as AWS does a bad credential. |
| +func (s *mediaCloudStub) denyIdentity() { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.denyIdent = true |
| +} |
| + |
| +func (s *mediaCloudStub) identityCalls() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.identities |
| +} |
| + |
| +func (s *mediaCloudStub) revisionCalls() map[string]int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + out := map[string]int{} |
| + for k, v := range s.revisions { |
| + out[k] = v |
| + } |
| + return out |
| +} |
| + |
| +// mediaWitness runs the real console binary through serve. |
| +type mediaWitness struct { |
| + bin string |
| + stub *mediaCloudStub |
| +} |
| + |
| +// env is what a console with a store backend boots on, every AWS client held |
| +// to the stub. Built from nothing rather than os.Environ, so no credential, |
| +// profile or proxy of the machine running the test can reach a client. |
| +func (w mediaWitness) env(dir, addr string, extra ...string) []string { |
| + return append([]string{ |
| + "HOME=" + dir, |
| + "CONSOLE_ORIGIN=http://" + addr, |
| + "CONSOLE_ADDR=" + addr, |
| + "CONSOLE_DB=" + filepath.Join(dir, "console.db"), |
| + "CARLOS_DEPLOYMENT_DIR=" + filepath.Join(dir, "bucket"), |
| + "CARLOS_REGISTRY=" + filepath.Join(dir, "registry.db"), |
| + // 32 zero bytes: a well-formed Ed25519 public key. |
| + "CARLOS_RELEASE_PUBKEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", |
| + "CARLOS_SYSTEM_OPERATORS=" + mediaWitnessOperator, |
| + "CARLOS_STORE_BACKEND=aws", |
| + "CARLOS_STORE_REGION=" + testMediaRegion, |
| + "CARLOS_STORE_BUCKET_PREFIX=" + testMediaPrefix, |
| + "CARLOS_STORE_USER_BOUNDARY=arn:aws:iam::" + testMediaAccount + ":policy/store-boundary", |
| + "AWS_ENDPOINT_URL=" + w.stub.srv.URL, |
| + "AWS_REGION=" + testMediaRegion, |
| + "AWS_ACCESS_KEY_ID=AKIASTUBSTUBSTUBSTUB", |
| + "AWS_SECRET_ACCESS_KEY=stub", |
| + "AWS_EC2_METADATA_DISABLED=true", |
| + "NO_PROXY=127.0.0.1", |
| + }, extra...) |
| +} |
| + |
| +func freeLoopbackAddr(t *testing.T) string { |
| + t.Helper() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + return ln.Addr().String() |
| +} |
| + |
| +// mintMediaToken makes the operator's CLI token in the database the console |
| +// is about to open, through the same store calls `carlos auth login` drives. |
| +func mintMediaToken(t *testing.T, db string) string { |
| + t.Helper() |
| + st, err := console.Open(db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer st.Close() |
| + now := time.Now() |
| + user, device, err := st.NewCLIAuth("media witness", "127.0.0.1", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.ApproveCLIAuth(user, mediaWitnessOperator, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, token, _, err := st.PollCLIAuth(device, now) |
| + if err != nil || token == "" { |
| + t.Fatalf("mint token: %q, %v", token, err) |
| + } |
| + return token |
| +} |
| + |
| +// runningConsole is a serve process that reached its listener. |
| +type runningConsole struct { |
| + addr, token string |
| + |
| + mu sync.Mutex |
| + log strings.Builder |
| +} |
| + |
| +func (c *runningConsole) output() string { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.log.String() |
| +} |
| + |
| +// boot starts serve and returns once it logs its listener, which it does with |
| +// the socket already open. The console is stopped when the test ends. |
| +func (w mediaWitness) boot(t *testing.T, extra ...string) *runningConsole { |
| + t.Helper() |
| + dir := t.TempDir() |
| + addr := freeLoopbackAddr(t) |
| + c := &runningConsole{addr: addr, token: mintMediaToken(t, filepath.Join(dir, "console.db"))} |
| + cmd := exec.Command(w.bin, "serve") |
| + cmd.Dir = dir |
| + cmd.Env = w.env(dir, addr, extra...) |
| + stderr, err := cmd.StderrPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + listening := make(chan struct{}) |
| + drained := make(chan struct{}) |
| + go func() { |
| + defer close(drained) |
| + var once sync.Once |
| + sc := bufio.NewScanner(stderr) |
| + sc.Buffer(make([]byte, 64*1024), 1024*1024) |
| + for sc.Scan() { |
| + c.mu.Lock() |
| + c.log.WriteString(sc.Text() + "\n") |
| + c.mu.Unlock() |
| + if strings.Contains(sc.Text(), "listening on") { |
| + once.Do(func() { close(listening) }) |
| + } |
| + } |
| + }() |
| + t.Cleanup(func() { |
| + _ = cmd.Process.Signal(syscall.SIGTERM) |
| + select { |
| + case <-drained: |
| + case <-time.After(30 * time.Second): |
| + _ = cmd.Process.Kill() |
| + <-drained |
| + } |
| + _ = cmd.Wait() |
| + }) |
| + select { |
| + case <-listening: |
| + case <-drained: |
| + t.Fatalf("serve exited before listening:\n%s", c.output()) |
| + case <-time.After(90 * time.Second): |
| + t.Fatalf("serve did not reach its listener:\n%s", c.output()) |
| + } |
| + return c |
| +} |
| + |
| +// mediaStatus is the part of GET /api/cli/system/media the wiring decides. |
| +type mediaStatus struct { |
| + Configured bool `json:"configured"` |
| + Region string `json:"region"` |
| + Checks map[string]string `json:"checks"` |
| + Image struct { |
| + Digest string `json:"digest"` |
| + } `json:"image"` |
| +} |
| + |
| +// status reads system media status as the CLI does. |
| +func (c *runningConsole) status(t *testing.T) mediaStatus { |
| + t.Helper() |
| + req, err := http.NewRequest(http.MethodGet, "http://"+c.addr+"/api/cli/system/media", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer "+c.token) |
| + client := &http.Client{Timeout: 60 * time.Second, Transport: &http.Transport{}} |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + t.Fatalf("system media status: %v\n%s", err, c.output()) |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(resp.Body) |
| + if resp.StatusCode != http.StatusOK { |
| + t.Fatalf("system media status: %d %s\n%s", resp.StatusCode, body, c.output()) |
| + } |
| + var out mediaStatus |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + t.Fatalf("system media status: %v: %s", err, body) |
| + } |
| + return 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() |
| + dir := t.TempDir() |
| + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, w.bin, "serve") |
| + cmd.Dir = dir |
| + cmd.Env = w.env(dir, freeLoopbackAddr(t), extra...) |
| + out, err := cmd.CombinedOutput() |
| + if ctx.Err() != nil { |
| + t.Fatalf("serve did not stop:\n%s", out) |
| + } |
| + if err == nil { |
| + t.Fatalf("serve exited 0:\n%s", out) |
| + } |
| + return string(out) |
| +} |
| + |
| +// TestServeMediaWiring is the production-wired witness: the built console, |
| +// through serve, with only the cloud's HTTP endpoint replaced. |
| +func TestServeMediaWiring(t *testing.T) { |
| + if os.Geteuid() == 0 { |
| + // rootaws.ScrubEnvironment drops AWS_ENDPOINT_URL for root, and these |
| + // clients must never reach AWS. |
| + t.Skip("the stub endpoint is scrubbed from a console running as root") |
| + } |
| + bin, _ := buildConsole(t) |
| + |
| + t.Run("an engine reaches the door and the checks", func(t *testing.T) { |
| + w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)} |
| + c := w.boot(t, "CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE="+testMediaEngine(t, nil)) |
| + got := c.status(t) |
| + if !got.Configured || got.Region != testMediaRegion || got.Image.Digest != testMediaDigest { |
| + t.Fatalf("status = %+v\n%s", got, c.output()) |
| + } |
| + // Each class's check went through the real ECS adapter to the stub. |
| + revisions := w.stub.revisionCalls() |
| + for class, arn := range testMediaConfig().TaskDefinitions { |
| + if _, ok := got.Checks[class]; !ok { |
| + t.Errorf("no check for class %s in %v", class, got.Checks) |
| + } |
| + if revisions[arn] == 0 { |
| + t.Errorf("revision %s never reached the ECS client", arn) |
| + } |
| + } |
| + if n := w.stub.identityCalls(); n != 1 { |
| + t.Errorf("GetCallerIdentity called %d times, want once", n) |
| + } |
| + }) |
| + |
| + t.Run("no media settings is a console with no engine", func(t *testing.T) { |
| + w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)} |
| + c := w.boot(t) |
| + got := c.status(t) |
| + if got.Configured || got.Region != "" || got.Image.Digest != "" || len(got.Checks) != 0 { |
| + t.Fatalf("status = %+v", got) |
| + } |
| + if n := w.stub.identityCalls(); n != 0 { |
| + t.Errorf("GetCallerIdentity called %d times with nothing configured", n) |
| + } |
| + if n := len(w.stub.revisionCalls()); n != 0 { |
| + t.Errorf("%d revisions read with nothing configured", n) |
| + } |
| + }) |
| + |
| + t.Run("conversion alone wires no engine", func(t *testing.T) { |
| + w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)} |
| + c := w.boot(t, "CARLOS_STORE_CONVERSION=1") |
| + if got := c.status(t); got.Configured || got.Region != "" { |
| + t.Fatalf("status = %+v", got) |
| + } |
| + if n := w.stub.identityCalls(); n != 1 { |
| + t.Errorf("GetCallerIdentity called %d times, want once", n) |
| + } |
| + }) |
| + |
| + t.Run("a cloud that refuses leaves the console up with media off", func(t *testing.T) { |
| + w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)} |
| + w.stub.denyIdentity() |
| + c := w.boot(t, "CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE="+testMediaEngine(t, nil)) |
| + 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()) |
| + } |
| + }) |
| + |
| + t.Run("bad settings stop the boot", func(t *testing.T) { |
| + const secret = "hunter2-do-not-print" |
| + foreign := func(c *mediaaws.Config) { |
| + c.AccountID = "210987654321" |
| + c.ConversionRole = "arn:aws:iam::210987654321:role/media-conversion" |
| + for k, v := range c.TaskDefinitions { |
| + c.TaskDefinitions[k] = strings.Replace(v, testMediaAccount, "210987654321", 1) |
| + } |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + env []string |
| + want string |
| + }{ |
| + {"malformed engine", []string{"CARLOS_STORE_CONVERSION=1", `CARLOS_MEDIA_ENGINE={"token":"` + secret + `"}`}, "CARLOS_MEDIA_ENGINE"}, |
| + {"engine that is not JSON", []string{"CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE=" + secret}, "CARLOS_MEDIA_ENGINE"}, |
| + {"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"}, |
| + {"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"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)} |
| + out := w.refusal(t, tc.env...) |
| + if !strings.Contains(out, tc.want) { |
| + t.Fatalf("the refusal does not name %s:\n%s", tc.want, out) |
| + } |
| + if strings.Contains(out, secret) { |
| + t.Fatalf("the refusal prints the setting's value:\n%s", out) |
| + } |
| + }) |
| + } |
| + }) |
| +} |
diff --git a/cmd/console/media_test.go b/cmd/console/media_test.go| new file mode 100644 |
| index 000000000..4fdc14540 |
| --- /dev/null |
| +++ b/cmd/console/media_test.go |
| @@ -0,0 +1,342 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/media" |
| + "github.com/carlosframework/platform/internal/media/mediatest" |
| + "github.com/carlosframework/platform/internal/mediaaws" |
| +) |
| + |
| +const ( |
| + testMediaAccount = "123456789012" |
| + testMediaRegion = "eu-west-1" |
| + testMediaPrefix = "carlos-test-" |
| + testMediaDigest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" |
| +) |
| + |
| +// testMediaConfig is a CARLOS_MEDIA_ENGINE every check accepts. |
| +func testMediaConfig() mediaaws.Config { |
| + defs := map[string]string{} |
| + for _, preset := range []string{media.PresetVideo720p, media.PresetAudioAAC} { |
| + for _, class := range []string{media.ClassShort, media.ClassLong} { |
| + key := media.ClassKey{Preset: preset, Class: class} |
| + defs[key.String()] = "arn:aws:ecs:" + testMediaRegion + ":" + testMediaAccount + |
| + ":task-definition/media-" + preset + "-" + class + ":3" |
| + } |
| + } |
| + return mediaaws.Config{ |
| + V: 1, |
| + Region: testMediaRegion, |
| + Cluster: "media", |
| + TaskDefinitions: defs, |
| + Subnets: []string{"subnet-1"}, |
| + SecurityGroup: "sg-1", |
| + ConversionRole: "arn:aws:iam::" + testMediaAccount + ":role/media-conversion", |
| + ResultsBucket: "carlos-media-results", |
| + StorePrefix: testMediaPrefix, |
| + AccountID: testMediaAccount, |
| + Image: media.ImageInfo{Digest: testMediaDigest, BuiltAt: "2026-11-01T00:00:00Z", FFmpeg: "7.1.5"}, |
| + } |
| +} |
| + |
| +// testMediaEngine is testMediaConfig as the variable holds it, after edit. |
| +func testMediaEngine(t *testing.T, edit func(*mediaaws.Config)) string { |
| + t.Helper() |
| + c := testMediaConfig() |
| + if edit != nil { |
| + edit(&c) |
| + } |
| + b, err := json.Marshal(c) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| +} |
| + |
| +// fakeMediaClients counts what mediaFromEnv asks of the cloud. |
| +type fakeMediaClients struct { |
| + account string |
| + identityErr error |
| + s3Err error |
| + engineErr error |
| + |
| + identities, s3s, engines int |
| + s3Region, s3Endpoint string |
| + identityRegion string |
| + engineConfig mediaaws.Config |
| + engine media.Engine |
| + grants media.Grants |
| +} |
| + |
| +func (f *fakeMediaClients) clients() mediaClients { |
| + return mediaClients{ |
| + identity: func(_ context.Context, region string) (string, error) { |
| + f.identities++ |
| + f.identityRegion = region |
| + return f.account, f.identityErr |
| + }, |
| + newS3: func(_ context.Context, region, endpoint string) (mediaaws.S3API, error) { |
| + f.s3s++ |
| + f.s3Region, f.s3Endpoint = region, endpoint |
| + return nil, f.s3Err |
| + }, |
| + newEngine: func(_ context.Context, c mediaaws.Config) (media.Engine, media.Grants, error) { |
| + f.engines++ |
| + f.engineConfig = c |
| + if f.engineErr != nil { |
| + return nil, nil, f.engineErr |
| + } |
| + return f.engine, f.grants, nil |
| + }, |
| + } |
| +} |
| + |
| +func newFakeMediaClients() *fakeMediaClients { |
| + return &fakeMediaClients{ |
| + account: testMediaAccount, |
| + engine: mediatest.NewFakeEngine(time.Now), |
| + grants: mediatest.NewFakeGrants(time.Now), |
| + } |
| +} |
| + |
| +func testStoreEnv() storeEnv { |
| + return storeEnv{Backend: "aws", Region: testMediaRegion, Prefix: testMediaPrefix} |
| +} |
| + |
| +func mediaEnv(m map[string]string) func(string) string { |
| + return func(k string) string { return m[k] } |
| +} |
| + |
| +func TestMediaFromEnvUnset(t *testing.T) { |
| + for name, env := range map[string]map[string]string{ |
| + "nothing set": nil, |
| + "blank": {"CARLOS_MEDIA_ENGINE": " ", "CARLOS_STORE_CONVERSION": " "}, |
| + "conversion off": {"CARLOS_STORE_CONVERSION": "0"}, |
| + "limits alone are unread": {"CARLOS_MEDIA_LIMITS": "not a limit"}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + f := newFakeMediaClients() |
| + got, err := mediaFromEnv(context.Background(), mediaEnv(env), testStoreEnv(), f.clients()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got != (console.MediaConfig{}) { |
| + t.Fatalf("configured %+v, want nothing", got) |
| + } |
| + if f.identities+f.s3s+f.engines != 0 { |
| + t.Fatalf("cloud clients used: identity %d, s3 %d, engine %d", f.identities, f.s3s, f.engines) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// CARLOS_STORE_CONVERSION=1 alone is browser uploads with no engine: the |
| +// bucket settings and the account, and nothing that converts. |
| +func TestMediaFromEnvConversionOnly(t *testing.T) { |
| + f := newFakeMediaClients() |
| + store := testStoreEnv() |
| + store.Endpoint = "http://127.0.0.1:9000" |
| + got, err := mediaFromEnv(context.Background(), mediaEnv(map[string]string{ |
| + "CARLOS_STORE_CONVERSION": "1", |
| + "CARLOS_MEDIA_LIMITS": "not a limit", |
| + }), store, f.clients()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !got.StoreConversion || got.StoreBuckets == nil || got.StoreAccountID != testMediaAccount { |
| + t.Fatalf("conversion = %v, buckets = %v, account = %q", got.StoreConversion, got.StoreBuckets, got.StoreAccountID) |
| + } |
| + if got.MediaEngine != nil || got.MediaGrants != nil || got.MediaRegion != "" || got.MediaImage != (media.ImageInfo{}) { |
| + t.Fatalf("an engine is configured: %+v", got) |
| + } |
| + if f.identities != 1 || f.identityRegion != testMediaRegion { |
| + t.Fatalf("identity called %d times in %q, want once in %s", f.identities, f.identityRegion, testMediaRegion) |
| + } |
| + if f.s3s != 1 || f.s3Region != testMediaRegion || f.s3Endpoint != store.Endpoint { |
| + t.Fatalf("s3 client %d times for %q at %q", f.s3s, f.s3Region, f.s3Endpoint) |
| + } |
| + if f.engines != 0 { |
| + t.Fatalf("engine built %d times", f.engines) |
| + } |
| +} |
| + |
| +func TestMediaFromEnvEngine(t *testing.T) { |
| + f := newFakeMediaClients() |
| + got, err := mediaFromEnv(context.Background(), mediaEnv(map[string]string{ |
| + "CARLOS_STORE_CONVERSION": "1", |
| + "CARLOS_MEDIA_ENGINE": testMediaEngine(t, nil), |
| + "CARLOS_MEDIA_LIMITS": "short=3", |
| + }), testStoreEnv(), f.clients()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := media.DefaultLimits() |
| + want.Short = 3 |
| + if got.MediaLimits != want { |
| + t.Fatalf("limits = %+v, want %+v", got.MediaLimits, want) |
| + } |
| + if got.MediaEngine != f.engine || got.MediaGrants != f.grants { |
| + t.Fatalf("engine %v grants %v are not the adapters built", got.MediaEngine, got.MediaGrants) |
| + } |
| + if got.MediaRegion != testMediaRegion || got.MediaImage != testMediaConfig().Image { |
| + t.Fatalf("region %q image %+v", got.MediaRegion, got.MediaImage) |
| + } |
| + if !got.StoreConversion || got.StoreBuckets == nil || got.StoreAccountID != testMediaAccount { |
| + t.Fatalf("conversion = %v, buckets = %v, account = %q", got.StoreConversion, got.StoreBuckets, got.StoreAccountID) |
| + } |
| + if f.identities != 1 || f.engines != 1 || f.engineConfig.Cluster != "media" { |
| + t.Fatalf("identity %d, engine %d, config %+v", f.identities, f.engines, f.engineConfig) |
| + } |
| +} |
| + |
| +// Every refusal stops the boot, names the variable to fix, and is decided |
| +// before an engine is built. |
| +func TestMediaFromEnvRefusals(t *testing.T) { |
| + const secret = "hunter2-do-not-print" |
| + engine := func(edit func(*mediaaws.Config)) string { return testMediaEngine(t, edit) } |
| + for _, tc := range []struct { |
| + name string |
| + env map[string]string |
| + store func(*storeEnv) |
| + want string |
| + }{ |
| + { |
| + name: "conversion is neither on nor off", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "true"}, |
| + want: "CARLOS_STORE_CONVERSION", |
| + }, |
| + { |
| + name: "conversion without a store backend", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1"}, |
| + store: func(s *storeEnv) { *s = storeEnv{} }, |
| + want: "CARLOS_STORE_BACKEND", |
| + }, |
| + { |
| + name: "engine without conversion", |
| + env: map[string]string{"CARLOS_MEDIA_ENGINE": engine(nil)}, |
| + want: "CARLOS_STORE_CONVERSION=1", |
| + }, |
| + { |
| + name: "malformed engine", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": `{"v":1,"token":"` + secret + `"}`}, |
| + want: "CARLOS_MEDIA_ENGINE", |
| + }, |
| + { |
| + name: "engine that is not JSON", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": secret}, |
| + want: "CARLOS_MEDIA_ENGINE", |
| + }, |
| + { |
| + name: "engine in another region", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": engine(func(c *mediaaws.Config) { |
| + c.Region = "us-east-1" |
| + for k, v := range c.TaskDefinitions { |
| + c.TaskDefinitions[k] = strings.Replace(v, testMediaRegion, "us-east-1", 1) |
| + } |
| + })}, |
| + want: "CARLOS_STORE_REGION", |
| + }, |
| + { |
| + name: "engine for another store prefix", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": engine(func(c *mediaaws.Config) { |
| + c.StorePrefix = "other-" |
| + })}, |
| + want: "CARLOS_STORE_BUCKET_PREFIX", |
| + }, |
| + { |
| + name: "engine in another account", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": engine(func(c *mediaaws.Config) { |
| + c.AccountID = "210987654321" |
| + c.ConversionRole = "arn:aws:iam::210987654321:role/media-conversion" |
| + for k, v := range c.TaskDefinitions { |
| + c.TaskDefinitions[k] = strings.Replace(v, testMediaAccount, "210987654321", 1) |
| + } |
| + })}, |
| + want: "account", |
| + }, |
| + { |
| + name: "malformed limits", |
| + env: map[string]string{"CARLOS_STORE_CONVERSION": "1", "CARLOS_MEDIA_ENGINE": engine(nil), "CARLOS_MEDIA_LIMITS": "short=none"}, |
| + want: "CARLOS_MEDIA_LIMITS", |
| + }, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + f := newFakeMediaClients() |
| + store := testStoreEnv() |
| + if tc.store != nil { |
| + tc.store(&store) |
| + } |
| + got, err := mediaFromEnv(context.Background(), mediaEnv(tc.env), store, f.clients()) |
| + if err == nil { |
| + t.Fatalf("accepted: %+v", got) |
| + } |
| + if errors.Is(err, errMediaCloud) { |
| + t.Fatalf("a bad setting reads as a cloud failure, so the console would boot past it: %v", err) |
| + } |
| + if !strings.Contains(err.Error(), tc.want) { |
| + t.Fatalf("error %q does not name %q", err, tc.want) |
| + } |
| + if strings.Contains(err.Error(), secret) { |
| + t.Fatalf("error prints the setting's value: %q", err) |
| + } |
| + if f.engines != 0 { |
| + t.Fatal("an engine was built for a refused setting") |
| + } |
| + if got != (console.MediaConfig{}) { |
| + t.Fatalf("a refusal also configured %+v", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A bad setting is reported whether or not the cloud answers: only the |
| +// account comparison needs STS. |
| +func TestMediaFromEnvChecksSettingsBeforeTheCloud(t *testing.T) { |
| + f := newFakeMediaClients() |
| + _, err := mediaFromEnv(context.Background(), mediaEnv(map[string]string{ |
| + "CARLOS_STORE_CONVERSION": "1", |
| + "CARLOS_MEDIA_ENGINE": "{", |
| + }), testStoreEnv(), f.clients()) |
| + if err == nil { |
| + t.Fatal("accepted") |
| + } |
| + if f.identities != 0 { |
| + t.Fatalf("STS called %d times before the setting was checked", f.identities) |
| + } |
| +} |
| + |
| +// A cloud that does not answer is not a bad setting: errMediaCloud is how |
| +// mediaConfig tells the two apart, and nothing is half configured. |
| +func TestMediaFromEnvCloudFailures(t *testing.T) { |
| + boom := errors.New("boom") |
| + for name, breakIt := range map[string]func(*fakeMediaClients){ |
| + "identity": func(f *fakeMediaClients) { f.identityErr = boom }, |
| + "no account in the answer": func(f *fakeMediaClients) { |
| + f.account = "" |
| + }, |
| + "s3 client": func(f *fakeMediaClients) { f.s3Err = boom }, |
| + "engine": func(f *fakeMediaClients) { f.engineErr = boom }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + f := newFakeMediaClients() |
| + breakIt(f) |
| + got, err := mediaFromEnv(context.Background(), mediaEnv(map[string]string{ |
| + "CARLOS_STORE_CONVERSION": "1", |
| + "CARLOS_MEDIA_ENGINE": testMediaEngine(t, nil), |
| + }), testStoreEnv(), f.clients()) |
| + if !errors.Is(err, errMediaCloud) { |
| + t.Fatalf("err = %v, want errMediaCloud", err) |
| + } |
| + if got != (console.MediaConfig{}) { |
| + t.Fatalf("half configured: %+v", got) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/cmd/console/pdf.go b/cmd/console/pdf.go| new file mode 100644 |
| index 000000000..3fb655e76 |
| --- /dev/null |
| +++ b/cmd/console/pdf.go |
| @@ -0,0 +1,34 @@ |
| +package main |
| + |
| +import ( |
| + "fmt" |
| + "net/url" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| +) |
| + |
| +// pdfSettings reads CARLOS_PDF_LIMITS and CARLOS_PDF_ADDR. |
| +func pdfSettings(getenv func(string) string) (console.PDFLimits, string, error) { |
| + limits, err := console.ParsePDFLimits(getenv("CARLOS_PDF_LIMITS")) |
| + if err != nil { |
| + return console.PDFLimits{}, "", err |
| + } |
| + addr, err := pdfEngine(getenv) |
| + if err != nil { |
| + return console.PDFLimits{}, "", err |
| + } |
| + return limits, addr, nil |
| +} |
| + |
| +func pdfEngine(getenv func(string) string) (string, error) { |
| + addr := strings.TrimSpace(getenv("CARLOS_PDF_ADDR")) |
| + if addr == "" { |
| + return "", nil |
| + } |
| + u, err := url.Parse(addr) |
| + if err != nil || u.Scheme != "http" || u.Hostname() == "" { |
| + return "", fmt.Errorf("CARLOS_PDF_ADDR must be an http:// URL with a host") |
| + } |
| + return addr, nil |
| +} |