media: hostile-input corpus, fuzzing, selftest and drills
Plan 3 Task 7. The hostile-input corpus (playlists naming the metadata address and a local file, a truncated MP4, an MP4 whose alias dref names /etc/passwd, empty, random, HTML, ZIP) ends in named errors on the fakes and on Debian's ffmpeg; Task 7's hostile children (fill-scratch on a namespaced tmpfs, many-files, fork-setsid, ignore-term, a compromised grandchild swapping outputs) fail only their own job; hostile outputs upload nothing. New fuzz targets for the payload, the meter, the drill input and the verdict. carlos-media selftest <video|audio> converts lavfi sources (1080p, rotated portrait, PQ 4K, a location-tagged MOV, a live WebM voice, a silent WAV, an MP3 with cover art) through Run against an in-process presigned-style store and checks sizes, fMP4 and playlist, dimensions, loudness, peaks and that no metadata reaches a log or an output. carlos-media drill creds|dns|net|endpoints|endpoints-verdict (portable) and hostile-timer|fill-scratch|many-files|bad-outputs (Linux, F23), with a stdlib SigV4 signer. scripts/media-endpoint-drill.sh runs the three-phase endpoint drill with unconditional, verified cleanup and a cleanup <run dir> mode; its Python tests run against a fake aws and in CI through TestMediaEndpointDrillPythonGuards (F31).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
29 files changed,
+4,491
−5
cmd/carlos-media/drill.go+605 −0cmd/carlos-media/drill_linux.go+173 −0cmd/carlos-media/drill_linux_test.go+128 −0cmd/carlos-media/drill_other.go+25 −0cmd/carlos-media/drill_test.go+527 −0cmd/carlos-media/main.go+31 −4cmd/carlos-media/sigv4.go+97 −0docs/superpowers/notes/census-claims-media-conversion.tsv+6 −0docs/superpowers/notes/media-conversion-copy-deck.md+33 −0internal/mediahandler/fakeffmpeg_test.go+5 −1internal/mediahandler/hostile_linux.go+338 −0internal/mediahandler/hostile_test.go+590 −0internal/mediahandler/probe_test.go+4 −0internal/mediahandler/selftest.go+652 −0internal/mediahandler/selftest_test.go+124 −0internal/mediahandler/testdata/corpus/archive.zipbinaryinternal/mediahandler/testdata/corpus/concat-list.ffconcat+3 −0internal/mediahandler/testdata/corpus/dref-alis-etc-passwd.mp4binaryinternal/mediahandler/testdata/corpus/empty.bin+0 −0internal/mediahandler/testdata/corpus/page.html+3 −0internal/mediahandler/testdata/corpus/playlist-local-file.m3u8+6 −0internal/mediahandler/testdata/corpus/playlist-metadata.m3u8+6 −0internal/mediahandler/testdata/corpus/provenance.txt+37 −0internal/mediahandler/testdata/corpus/random-4k.binbinaryinternal/mediahandler/testdata/corpus/truncated.mp4binaryinternal/mediahandler/testdata/probe/dref-alis.json+45 −0internal/mediahandler/testdata/probe/provenance.txt+8 −0scripts/media-endpoint-drill.sh+522 −0scripts/media_endpoint_drill_test.py+523 −0
diff --git a/cmd/carlos-media/drill.go b/cmd/carlos-media/drill.go| new file mode 100644 |
| index 000000000..9858e93d5 |
| --- /dev/null |
| +++ b/cmd/carlos-media/drill.go |
| @@ -0,0 +1,605 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "os" |
| + "regexp" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// The rollout drills (plan 3 Task 7; spec §5.5 and §9; rollout R3 and |
| +// R4). Each runs inside a media task started by the operator with |
| +// `aws ecs run-task` and command ["drill", "<name>", …] on codec, and |
| +// prints PASS/FAIL lines to stdout, the task's log. No drill ever |
| +// prints a credential, a URL or a header: a line names a check and an |
| +// outcome in fixed words, a status code, an environment variable's |
| +// name, a host name or an address the operator typed. |
| +// |
| +// drill.go holds the drills that work anywhere; drill_linux.go the ones |
| +// that need Linux (signals to every process, a child subreaper, a full |
| +// scratch), which drill_other.go refuses elsewhere (preflight F23). |
| + |
| +// drillUsage is copy deck row engine.drill.usage (pending Luna pass). |
| +const drillUsage = "usage: carlos-media drill <creds|dns|net <address>…|endpoints|endpoints-verdict <A> <B> <C>|hostile-timer|fill-scratch|many-files|bad-outputs>" |
| + |
| +// DrillEnv names the endpoint drill's input (the run directory's |
| +// input.json, scripts/media-endpoint-drill.sh). It holds the foreign |
| +// user's key and is never logged. |
| +const drillInputEnv = "CARLOS_MEDIA_DRILL" |
| + |
| +// drillEnv is what the drills read from the world; tests replace any |
| +// of it. |
| +type drillEnv struct { |
| + lookupEnv func(string) (string, bool) |
| + environ func() []string |
| + now func() time.Time |
| + resolve func(ctx context.Context, host string) ([]string, error) |
| + dial func(ctx context.Context, network, addr string) (net.Conn, error) |
| + // client makes the drills' HTTP requests: no proxy, no redirect, |
| + // no compression. |
| + client *http.Client |
| + |
| + // The metadata addresses the creds drill probes. |
| + credsURL, imdsURL string |
| + // ecrAPIURL and logsURL make each API's base URL from the region; |
| + // tests point them at local servers. |
| + ecrAPIURL, logsURL func(region string) string |
| + // timeout bounds each check (20 s for the endpoint drill's |
| + // requests, drillTimeout for the rest). |
| + endpointTimeout, checkTimeout time.Duration |
| +} |
| + |
| +// drillTimeout bounds each creds, dns and net check. |
| +const drillTimeout = 5 * time.Second |
| + |
| +// endpointTimeout bounds each of the endpoint drill's four requests. |
| +const endpointTimeout = 20 * time.Second |
| + |
| +// realDrillEnv is the binary's world. |
| +func realDrillEnv() drillEnv { |
| + dialer := &net.Dialer{Timeout: drillTimeout} |
| + return drillEnv{ |
| + lookupEnv: os.LookupEnv, |
| + environ: os.Environ, |
| + now: time.Now, |
| + resolve: net.DefaultResolver.LookupHost, |
| + dial: dialer.DialContext, |
| + client: drillClient(dialer), |
| + credsURL: "http://169.254.170.2/v2/credentials", |
| + imdsURL: "http://169.254.169.254/latest/meta-data/", |
| + ecrAPIURL: func(region string) string { return "https://api.ecr." + region + ".amazonaws.com/" }, |
| + logsURL: func(region string) string { return "https://logs." + region + ".amazonaws.com/" }, |
| + |
| + endpointTimeout: endpointTimeout, |
| + checkTimeout: drillTimeout, |
| + } |
| +} |
| + |
| +// drillClient is the drills' HTTP client: no proxy from the |
| +// environment, no redirect followed (a redirect is an answer, not a |
| +// success), no compression asked for. |
| +func drillClient(dialer *net.Dialer) *http.Client { |
| + return &http.Client{ |
| + Transport: &http.Transport{ |
| + Proxy: nil, |
| + DialContext: dialer.DialContext, |
| + TLSHandshakeTimeout: 10 * time.Second, |
| + ResponseHeaderTimeout: endpointTimeout, |
| + DisableCompression: true, |
| + DisableKeepAlives: true, |
| + }, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + } |
| +} |
| + |
| +// drillCommand runs `drill <name> [args]` and answers the exit: 0 when |
| +// every line it printed is PASS (or, for endpoints, when it ran), 1 |
| +// otherwise, 2 for a usage error. |
| +func drillCommand(args []string, stdout, stderr io.Writer) int { |
| + return runDrill(context.Background(), realDrillEnv(), args, stdout, stderr) |
| +} |
| + |
| +// runDrill is drillCommand on env. |
| +func runDrill(ctx context.Context, env drillEnv, args []string, stdout, stderr io.Writer) int { |
| + if len(args) == 0 { |
| + fmt.Fprintln(stderr, drillUsage) |
| + return exitUsage |
| + } |
| + name, rest := args[0], args[1:] |
| + r := &report{w: stdout} |
| + switch name { |
| + case "creds": |
| + if len(rest) != 0 { |
| + break |
| + } |
| + drillCreds(ctx, env, r) |
| + return r.exit() |
| + case "dns": |
| + if len(rest) != 0 { |
| + break |
| + } |
| + drillDNS(ctx, env, r) |
| + return r.exit() |
| + case "net": |
| + if len(rest) == 0 { |
| + break |
| + } |
| + drillNet(ctx, env, rest, r) |
| + return r.exit() |
| + case "endpoints": |
| + if len(rest) != 0 { |
| + break |
| + } |
| + return drillEndpoints(ctx, env, stdout, stderr) |
| + case "endpoints-verdict": |
| + if len(rest) != 3 { |
| + break |
| + } |
| + return endpointsVerdict(rest, stdout) |
| + default: |
| + if code, ok := linuxDrill(ctx, name, rest, r, stderr); ok { |
| + return code |
| + } |
| + } |
| + fmt.Fprintln(stderr, drillUsage) |
| + return exitUsage |
| +} |
| + |
| +// report collects a drill's PASS/FAIL lines. |
| +type report struct { |
| + w io.Writer |
| + failed bool |
| +} |
| + |
| +// pass prints "PASS <check>: <what>". |
| +func (r *report) pass(check, format string, args ...any) { |
| + fmt.Fprintf(r.w, "PASS %s: %s\n", check, fmt.Sprintf(format, args...)) |
| +} |
| + |
| +// fail prints "FAIL <check>: <what>" and marks the drill failed. |
| +func (r *report) fail(check, format string, args ...any) { |
| + r.failed = true |
| + fmt.Fprintf(r.w, "FAIL %s: %s\n", check, fmt.Sprintf(format, args...)) |
| +} |
| + |
| +func (r *report) exit() int { |
| + if r.failed { |
| + return 1 |
| + } |
| + return 0 |
| +} |
| + |
| +// credentialEnv are the variables that carry, or lead to, an AWS |
| +// credential. None may be set in a media task (it has no task role). |
| +var credentialEnv = []string{ |
| + "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_SECURITY_TOKEN", |
| + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", |
| + "AWS_CONTAINER_AUTHORIZATION_TOKEN", "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", |
| + "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", |
| +} |
| + |
| +// metadataEnv names the task metadata endpoint (v4) Fargate sets. |
| +const metadataEnv = "ECS_CONTAINER_METADATA_URI_V4" |
| + |
| +// drillCreds: no credential variable is set (ordinary metadata such as |
| +// AWS_EXECUTION_ENV and AWS_REGION is allowed and named); |
| +// 169.254.170.2/v2/credentials gives no credential; 169.254.169.254 is |
| +// unreachable; the v4 task metadata endpoint, and its /task, give no |
| +// credential. Values are never printed. |
| +func drillCreds(ctx context.Context, env drillEnv, r *report) { |
| + var set []string |
| + for _, name := range credentialEnv { |
| + if _, ok := env.lookupEnv(name); ok { |
| + set = append(set, name) |
| + } |
| + } |
| + for _, name := range set { |
| + r.fail("creds env", "%s is set", name) |
| + } |
| + if len(set) == 0 { |
| + var other []string |
| + for _, kv := range env.environ() { |
| + name, _, _ := strings.Cut(kv, "=") |
| + if strings.HasPrefix(name, "AWS_") { |
| + other = append(other, name) |
| + } |
| + } |
| + sort.Strings(other) |
| + r.pass("creds env", "no credential variable; AWS variables set: %s", namesOrNone(other)) |
| + } |
| + |
| + switch held, reached := credentialAt(ctx, env, env.credsURL); { |
| + case held: |
| + r.fail("creds 169.254.170.2", "answered with a credential") |
| + case reached: |
| + r.pass("creds 169.254.170.2", "answered with no credential") |
| + default: |
| + r.pass("creds 169.254.170.2", "unreachable") |
| + } |
| + |
| + if _, reached := credentialAt(ctx, env, env.imdsURL); reached { |
| + r.fail("creds 169.254.169.254", "reachable") |
| + } else { |
| + r.pass("creds 169.254.169.254", "unreachable") |
| + } |
| + |
| + base, ok := env.lookupEnv(metadataEnv) |
| + if !ok || base == "" { |
| + r.pass("creds task metadata", "%s is not set", metadataEnv) |
| + return |
| + } |
| + for _, u := range []string{base, strings.TrimSuffix(base, "/") + "/task"} { |
| + if held, _ := credentialAt(ctx, env, u); held { |
| + r.fail("creds task metadata", "an answer holds a credential") |
| + return |
| + } |
| + } |
| + r.pass("creds task metadata", "no answer holds a credential") |
| +} |
| + |
| +// namesOrNone joins names, or says none. |
| +func namesOrNone(names []string) string { |
| + if len(names) == 0 { |
| + return "none" |
| + } |
| + return strings.Join(names, " ") |
| +} |
| + |
| +// credentialMarkers are the JSON keys of AWS's credential answers. |
| +var credentialMarkers = []string{`"AccessKeyId"`, `"SecretAccessKey"`, `"Token"`, `"SessionToken"`} |
| + |
| +// credentialAt GETs u (a bounded body) and reports whether anything |
| +// answered (reached) and whether the answer holds a credential (held). |
| +func credentialAt(ctx context.Context, env drillEnv, u string) (held, reached bool) { |
| + ctx, cancel := context.WithTimeout(ctx, env.checkTimeout) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil) |
| + if err != nil { |
| + return false, false |
| + } |
| + resp, err := env.client.Do(req) |
| + if err != nil { |
| + return false, false |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) |
| + for _, m := range credentialMarkers { |
| + if bytes.Contains(body, []byte(m)) { |
| + return true, true |
| + } |
| + } |
| + return false, true |
| +} |
| + |
| +// drillRegion is the task's region, AWS_REGION or AWS_DEFAULT_REGION, |
| +// if it is a plain region name. |
| +func drillRegion(env drillEnv) (string, bool) { |
| + for _, name := range []string{"AWS_REGION", "AWS_DEFAULT_REGION"} { |
| + if v, ok := env.lookupEnv(name); ok && regionName.MatchString(v) { |
| + return v, true |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// regionName is an AWS region's shape, so it can be put in a host name. |
| +var regionName = regexp.MustCompile(`^[a-z]{2}(-[a-z]+)+-[0-9]$`) |
| + |
| +// drillDNS: the five allowed names (the DNS firewall's allow list, |
| +// infra/modules/media-engine) resolve; example.com, amazonaws.com, |
| +// sts.<region>.amazonaws.com and ecs.<region>.amazonaws.com do not. |
| +// The wildcard entries are tried with a fixed label. |
| +func drillDNS(ctx context.Context, env drillEnv, r *report) { |
| + region, ok := drillRegion(env) |
| + if !ok { |
| + r.fail("dns", "no region in AWS_REGION or AWS_DEFAULT_REGION") |
| + return |
| + } |
| + allowed := []string{ |
| + "s3." + region + ".amazonaws.com", |
| + "carlos-media-drill.s3." + region + ".amazonaws.com", |
| + "api.ecr." + region + ".amazonaws.com", |
| + "carlos-media-drill.dkr.ecr." + region + ".amazonaws.com", |
| + "logs." + region + ".amazonaws.com", |
| + } |
| + blocked := []string{"example.com", "amazonaws.com", "sts." + region + ".amazonaws.com", "ecs." + region + ".amazonaws.com"} |
| + resolves := func(name string) bool { |
| + ctx, cancel := context.WithTimeout(ctx, env.checkTimeout) |
| + defer cancel() |
| + addrs, err := env.resolve(ctx, name) |
| + return err == nil && len(addrs) > 0 |
| + } |
| + for _, name := range allowed { |
| + if resolves(name) { |
| + r.pass("dns "+name, "resolves") |
| + } else { |
| + r.fail("dns "+name, "does not resolve") |
| + } |
| + } |
| + for _, name := range blocked { |
| + if resolves(name) { |
| + r.fail("dns "+name, "resolves") |
| + } else { |
| + r.pass("dns "+name, "does not resolve") |
| + } |
| + } |
| +} |
| + |
| +// drillNet: TCP to 1.1.1.1:443 and to each address given (an IP, with |
| +// an optional port, 443 by default) does not connect. |
| +func drillNet(ctx context.Context, env drillEnv, addrs []string, r *report) { |
| + targets := []string{"1.1.1.1:443"} |
| + for _, a := range addrs { |
| + t, ok := netTarget(a) |
| + if !ok { |
| + r.fail("net", "an argument is not an IP address with an optional port") |
| + return |
| + } |
| + targets = append(targets, t) |
| + } |
| + for _, t := range targets { |
| + dctx, cancel := context.WithTimeout(ctx, env.checkTimeout) |
| + conn, err := env.dial(dctx, "tcp", t) |
| + cancel() |
| + if err == nil { |
| + conn.Close() |
| + r.fail("net "+t, "connected") |
| + continue |
| + } |
| + r.pass("net "+t, "no connection") |
| + } |
| +} |
| + |
| +// netTarget is a as host:port: an IP literal, with port 443 if it |
| +// names none. |
| +func netTarget(a string) (string, bool) { |
| + if ip := net.ParseIP(a); ip != nil { |
| + return net.JoinHostPort(ip.String(), "443"), true |
| + } |
| + host, port, err := net.SplitHostPort(a) |
| + if err != nil || net.ParseIP(host) == nil { |
| + return "", false |
| + } |
| + if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 { |
| + return "", false |
| + } |
| + return net.JoinHostPort(host, port), true |
| +} |
| + |
| +// endpointInput is the endpoint drill's input, minted outside the |
| +// engine VPC by scripts/media-endpoint-drill.sh: a presigned S3 GET of |
| +// the drill object, the foreign user's ECR registry token, the engine |
| +// image's manifest URL on the *.dkr.ecr host, the region, the user's |
| +// key, and the log group and stream it may write. |
| +type endpointInput struct { |
| + S3GetURL string `json:"s3_get_url"` |
| + ECRToken string `json:"ecr_token"` |
| + ECRManifestURL string `json:"ecr_manifest_url"` |
| + Region string `json:"region"` |
| + AccessKeyID string `json:"access_key_id"` |
| + SecretAccessKey string `json:"secret_access_key"` |
| + LogGroup string `json:"log_group"` |
| + LogStream string `json:"log_stream"` |
| +} |
| + |
| +// endpointNames are the four endpoints in the order a pass prints them. |
| +var endpointNames = []string{"s3", "ecr-api", "ecr-docker", "logs"} |
| + |
| +// drillEndpoints is one pass of the endpoint drill (plan 3 Task 7): |
| +// the four authenticated requests, each bounded by endpointTimeout, |
| +// each printed as "<endpoint> ok" (2xx) or "<endpoint> refused |
| +// <status|conn>", and nothing else on stdout. The input is read from |
| +// drillInputEnv and removed from the environment; a missing or |
| +// malformed input prints one fixed line to stderr and exits 1. |
| +func drillEndpoints(ctx context.Context, env drillEnv, stdout, stderr io.Writer) int { |
| + raw, _ := env.lookupEnv(drillInputEnv) |
| + os.Unsetenv(drillInputEnv) |
| + in, ok := parseEndpointInput(raw) |
| + if !ok { |
| + // engine.drill.endpoints.input (pending Luna pass). |
| + fmt.Fprintln(stderr, "drill endpoints: "+drillInputEnv+" does not hold the drill's input") |
| + return 1 |
| + } |
| + key := sigv4Key{AccessKeyID: in.AccessKeyID, SecretAccessKey: in.SecretAccessKey} |
| + requests := map[string]func(context.Context) (*http.Request, error){ |
| + "s3": func(ctx context.Context) (*http.Request, error) { |
| + return http.NewRequestWithContext(ctx, http.MethodGet, in.S3GetURL, nil) |
| + }, |
| + "ecr-api": func(ctx context.Context) (*http.Request, error) { |
| + return signedJSON(ctx, env, env.ecrAPIURL(in.Region), "ecr", "AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken", []byte("{}"), key, in.Region) |
| + }, |
| + "ecr-docker": func(ctx context.Context) (*http.Request, error) { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodHead, in.ECRManifestURL, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + req.Header.Set("Authorization", "Basic "+in.ECRToken) |
| + req.Header.Set("Accept", manifestAccept) |
| + return req, nil |
| + }, |
| + "logs": func(ctx context.Context) (*http.Request, error) { |
| + body, err := json.Marshal(map[string]any{ |
| + "logGroupName": in.LogGroup, |
| + "logStreamName": in.LogStream, |
| + "logEvents": []map[string]any{{"timestamp": env.now().UnixMilli(), "message": "carlos-media endpoint drill"}}, |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return signedJSON(ctx, env, env.logsURL(in.Region), "logs", "Logs_20140328.PutLogEvents", body, key, in.Region) |
| + }, |
| + } |
| + for _, name := range endpointNames { |
| + fmt.Fprintf(stdout, "%s %s\n", name, endpointOutcome(ctx, env, requests[name])) |
| + } |
| + return 0 |
| +} |
| + |
| +// manifestAccept asks the registry for any manifest the image may be. |
| +const manifestAccept = "application/vnd.oci.image.index.v1+json, application/vnd.oci.image.manifest.v1+json, " + |
| + "application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json" |
| + |
| +// parseEndpointInput decodes the input strictly: no unknown field, |
| +// nothing after the object, every field set, a plain region. |
| +func parseEndpointInput(raw string) (endpointInput, bool) { |
| + var in endpointInput |
| + if raw == "" || len(raw) > 64<<10 { |
| + return in, false |
| + } |
| + dec := json.NewDecoder(strings.NewReader(raw)) |
| + dec.DisallowUnknownFields() |
| + if dec.Decode(&in) != nil { |
| + return in, false |
| + } |
| + if _, err := dec.Token(); err != io.EOF { |
| + return in, false |
| + } |
| + for _, v := range []string{in.S3GetURL, in.ECRToken, in.ECRManifestURL, in.Region, in.AccessKeyID, in.SecretAccessKey, in.LogGroup, in.LogStream} { |
| + if v == "" { |
| + return in, false |
| + } |
| + } |
| + return in, regionName.MatchString(in.Region) |
| +} |
| + |
| +// signedJSON is an AWS JSON 1.1 API call: a POST of body to u with the |
| +// target header, SigV4-signed for service with key. |
| +func signedJSON(ctx context.Context, env drillEnv, u, service, target string, body []byte, key sigv4Key, region string) (*http.Request, error) { |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + req.Header.Set("Content-Type", "application/x-amz-json-1.1") |
| + req.Header.Set("X-Amz-Target", target) |
| + signV4(req, body, key, region, service, env.now()) |
| + return req, nil |
| +} |
| + |
| +// endpointOutcome makes one request and answers "ok" for a 2xx, |
| +// "refused <status>" for any other answer, "refused conn" when there |
| +// was none (or the request could not be built). Nothing of the |
| +// request, the answer or an error is passed on. |
| +func endpointOutcome(ctx context.Context, env drillEnv, build func(context.Context) (*http.Request, error)) string { |
| + ctx, cancel := context.WithTimeout(ctx, env.endpointTimeout) |
| + defer cancel() |
| + req, err := build(ctx) |
| + if err != nil { |
| + return "refused conn" |
| + } |
| + resp, err := env.client.Do(req) |
| + if err != nil { |
| + return "refused conn" |
| + } |
| + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20)) |
| + resp.Body.Close() |
| + if resp.StatusCode >= 200 && resp.StatusCode < 300 { |
| + return "ok" |
| + } |
| + return "refused " + strconv.Itoa(resp.StatusCode) |
| +} |
| + |
| +// passLine is one line of a pass: an endpoint and its outcome. |
| +var passLine = regexp.MustCompile(`^(s3|ecr-api|ecr-docker|logs) (ok|refused (?:conn|[1-5][0-9][0-9]))$`) |
| + |
| +// endpointsVerdict reads three passes' outputs (files A, B, C: phase A |
| +// under the saved policies, B under the full-access policy, C under the |
| +// restored ones), prints a table of endpoint by phase, then one FAIL |
| +// line per cell that is not what its phase needs, or one PASS line. A |
| +// and C must be refused at every endpoint, B ok at every endpoint: a |
| +// refusal is caused by the policy only because the same request |
| +// succeeded in phase B. Exit 0 only when every cell is right. |
| +// |
| +// A cell is "missing" when its phase has no line for the endpoint (or |
| +// no file), "malformed" when its phase has a line that is not a pass |
| +// line or names an endpoint twice. Only parsed words are printed, never |
| +// a line read from a file. |
| +func endpointsVerdict(files []string, stdout io.Writer) int { |
| + phases := []string{"A", "B", "C"} |
| + want := map[string]string{"A": "refused", "B": "ok", "C": "refused"} |
| + cells := map[string]map[string]string{} |
| + for i, p := range phases { |
| + cells[p] = readPass(files[i]) |
| + } |
| + // engine.drill.verdict.* (pending Luna pass). |
| + fmt.Fprintf(stdout, "%-12s %-14s %-14s %-14s\n", "endpoint", "A (saved)", "B (open)", "C (restored)") |
| + for _, e := range endpointNames { |
| + fmt.Fprintf(stdout, "%-12s %-14s %-14s %-14s\n", e, cells["A"][e], cells["B"][e], cells["C"][e]) |
| + } |
| + failed := false |
| + for _, p := range phases { |
| + for _, e := range endpointNames { |
| + got := cells[p][e] |
| + if want[p] == "ok" && got == "ok" || want[p] == "refused" && strings.HasPrefix(got, "refused ") { |
| + continue |
| + } |
| + failed = true |
| + fmt.Fprintf(stdout, "FAIL %s phase %s: %s, want %s\n", e, p, got, want[p]) |
| + } |
| + } |
| + if failed { |
| + return 1 |
| + } |
| + fmt.Fprintln(stdout, "PASS endpoints: refused under the saved and restored policies, ok under the open one, at all four endpoints") |
| + return 0 |
| +} |
| + |
| +// readPass parses one pass's output into a cell per endpoint. |
| +func readPass(path string) map[string]string { |
| + cells := map[string]string{} |
| + for _, e := range endpointNames { |
| + cells[e] = "missing" |
| + } |
| + b, err := readBounded(path, 64<<10) |
| + if err != nil { |
| + return cells |
| + } |
| + seen := map[string]bool{} |
| + malformed := false |
| + for _, line := range strings.Split(string(b), "\n") { |
| + line = strings.TrimRight(line, "\r") |
| + if strings.TrimSpace(line) == "" { |
| + continue |
| + } |
| + m := passLine.FindStringSubmatch(line) |
| + if m == nil || seen[m[1]] { |
| + malformed = true |
| + continue |
| + } |
| + seen[m[1]] = true |
| + cells[m[1]] = m[2] |
| + } |
| + if malformed { |
| + for _, e := range endpointNames { |
| + cells[e] = "malformed" |
| + } |
| + } |
| + return cells |
| +} |
| + |
| +// readBounded reads at most max bytes of path; a longer file is an |
| +// error. |
| +func readBounded(path string, max int64) ([]byte, error) { |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer f.Close() |
| + b, err := io.ReadAll(io.LimitReader(f, max+1)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if int64(len(b)) > max { |
| + return nil, errors.New("too long") |
| + } |
| + return b, nil |
| +} |
diff --git a/cmd/carlos-media/drill_linux.go b/cmd/carlos-media/drill_linux.go| new file mode 100644 |
| index 000000000..9196609be |
| --- /dev/null |
| +++ b/cmd/carlos-media/drill_linux.go |
| @@ -0,0 +1,173 @@ |
| +//go:build linux |
| + |
| +package main |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "os" |
| + "os/signal" |
| + "strconv" |
| + "syscall" |
| + "time" |
| + |
| + sysunix "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| + "github.com/carlosframework/platform/internal/mediahandler" |
| +) |
| + |
| +// linuxDrill runs the drills that need Linux. ok is false for a name |
| +// it does not know or the wrong arguments (a usage error). |
| +// |
| +// - hostile-timer: the codec container gone rogue (spec §9, astra |
| +// R5-1): it ignores SIGTERM and SIGINT, sends SIGKILL to every |
| +// process it can see and to -1, then keeps doing so until the |
| +// deadline container ends the task. Only as PID 1 of its own PID |
| +// namespace (a Fargate container's entrypoint): anywhere else -1 is |
| +// every process of the user, so it refuses. |
| +// - fill-scratch, many-files: the binary started as the codec starts |
| +// ffmpeg (mediahandler.DrillEncode), as a child that fills the |
| +// scratch or makes a hundred thousand files; PASS when the handler |
| +// names the failure (fill-scratch: engine_failed, the task's |
| +// storage) and no child is left. |
| +// - bad-outputs: mediahandler.DrillBadOutputs; PASS when every hostile |
| +// output is refused and no PUT was attempted. |
| +// - child <kind> <dir>: the child those two start |
| +// (mediahandler.HostileChild); not for the operator. |
| +func linuxDrill(ctx context.Context, name string, rest []string, r *report, stderr io.Writer) (int, bool) { |
| + logf := func(format string, args ...any) { fmt.Fprintf(stderr, format+"\n", args...) } |
| + switch { |
| + case name == "hostile-timer" && len(rest) == 0: |
| + return hostileTimer(realTimerOS(), r.w), true |
| + case (name == mediahandler.HostileFillScratch || name == mediahandler.HostileManyFiles) && len(rest) == 0: |
| + self, err := os.Executable() |
| + if err != nil { |
| + r.fail(name, "the binary's own path is unknown") |
| + return 1, true |
| + } |
| + drillChildJob(ctx, mediahandler.Config{Logf: logf}, self, name, r) |
| + return r.exit(), true |
| + case name == "bad-outputs" && len(rest) == 0: |
| + payload := os.Getenv(media.PayloadEnv) |
| + os.Unsetenv(media.PayloadEnv) |
| + drillBadOutputs(ctx, mediahandler.Config{Logf: logf}, payload, r) |
| + return r.exit(), true |
| + case name == "child" && len(rest) == 2: |
| + return mediahandler.HostileChild(rest[0], rest[1]), true |
| + } |
| + return 0, false |
| +} |
| + |
| +// drillChildJob runs kind's hostile child under the handler's child |
| +// rules and reports the job code the handler gave it. |
| +func drillChildJob(ctx context.Context, cfg mediahandler.Config, self, kind string, r *report) { |
| + start := time.Now() |
| + code := mediahandler.DrillEncode(ctx, cfg, self, func(out string) []string { |
| + return []string{"drill", "child", kind, out} |
| + }) |
| + took := time.Since(start).Round(time.Second) |
| + want := media.CodeUnreadable |
| + if kind == mediahandler.HostileFillScratch { |
| + want = media.CodeEngineFailed // the task's storage, not the source |
| + } |
| + if code == want { |
| + r.pass(kind, "the job failed %s in %s; no child left", code, took) |
| + return |
| + } |
| + if code == "" { |
| + code = "no error" |
| + } |
| + r.fail(kind, "the job ended %s in %s, want %s", code, took, want) |
| +} |
| + |
| +// drillBadOutputs runs mediahandler.DrillBadOutputs and reports each |
| +// round and the PUT count. |
| +func drillBadOutputs(ctx context.Context, cfg mediahandler.Config, payload string, r *report) { |
| + rounds, puts, err := mediahandler.DrillBadOutputs(ctx, cfg, payload) |
| + for _, b := range rounds { |
| + check := "bad-outputs " + b.Name + " " + b.Kind |
| + if b.Refused { |
| + r.pass(check, "refused (%s)", b.Reason) |
| + } else { |
| + r.fail(check, "not refused") |
| + } |
| + } |
| + if err != nil { |
| + r.fail("bad-outputs", "the drill could not run: %v", err) |
| + } |
| + if puts != 0 { |
| + r.fail("bad-outputs", "%d PUTs attempted, want 0", puts) |
| + return |
| + } |
| + r.pass("bad-outputs", "0 PUTs attempted") |
| +} |
| + |
| +// timerOS is what hostile-timer does to the system; tests replace all |
| +// of it, and must: the real kill(-1) is every process the user owns. |
| +type timerOS struct { |
| + getpid func() int |
| + ignore func(...os.Signal) |
| + pids func() []int |
| + kill func(pid int, sig syscall.Signal) error |
| + // rounds answers a channel that fires once per round of killing |
| + // after the first; the real one never closes. |
| + rounds func() <-chan time.Time |
| +} |
| + |
| +// hostileTimerEvery is how often hostile-timer kills again. |
| +const hostileTimerEvery = time.Second |
| + |
| +func realTimerOS() timerOS { |
| + return timerOS{ |
| + getpid: os.Getpid, |
| + ignore: signal.Ignore, |
| + pids: procPIDs, |
| + kill: sysunix.Kill, |
| + rounds: func() <-chan time.Time { return time.NewTicker(hostileTimerEvery).C }, |
| + } |
| +} |
| + |
| +// hostileTimer is the drill: see linuxDrill. It returns only if o's |
| +// rounds channel closes (tests), or it refuses. |
| +func hostileTimer(o timerOS, stdout io.Writer) int { |
| + if o.getpid() != 1 { |
| + // engine.drill.hostile_timer.refused (pending Luna pass). |
| + fmt.Fprintln(stdout, "FAIL hostile-timer: not PID 1 of its own PID namespace; refusing to signal every process") |
| + return 1 |
| + } |
| + o.ignore(syscall.SIGTERM, syscall.SIGINT) |
| + killAll := func() int { |
| + n := 0 |
| + for _, pid := range o.pids() { |
| + if pid != 1 && o.kill(pid, syscall.SIGKILL) == nil { |
| + n++ |
| + } |
| + } |
| + _ = o.kill(-1, syscall.SIGKILL) |
| + return n |
| + } |
| + n := killAll() |
| + // engine.drill.hostile_timer.running (pending Luna pass). |
| + fmt.Fprintf(stdout, "hostile-timer: ignoring SIGTERM and SIGINT; sent SIGKILL to %d other processes and to -1; repeating until the deadline ends the task\n", n) |
| + for range o.rounds() { |
| + killAll() |
| + } |
| + return 1 |
| +} |
| + |
| +// procPIDs are the PIDs in /proc. |
| +func procPIDs() []int { |
| + ents, err := os.ReadDir("/proc") |
| + if err != nil { |
| + return nil |
| + } |
| + var out []int |
| + for _, e := range ents { |
| + if pid, err := strconv.Atoi(e.Name()); err == nil { |
| + out = append(out, pid) |
| + } |
| + } |
| + return out |
| +} |
diff --git a/cmd/carlos-media/drill_linux_test.go b/cmd/carlos-media/drill_linux_test.go| new file mode 100644 |
| index 000000000..17f6b8109 |
| --- /dev/null |
| +++ b/cmd/carlos-media/drill_linux_test.go |
| @@ -0,0 +1,128 @@ |
| +//go:build linux |
| + |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "os" |
| + "slices" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| + "github.com/carlosframework/platform/internal/mediahandler" |
| +) |
| + |
| +// TestMain lets the test binary stand in for carlos-media as the |
| +// drills' child: `<test binary> drill child <kind> <dir>`. |
| +func TestMain(m *testing.M) { |
| + if len(os.Args) >= 3 && os.Args[1] == "drill" && os.Args[2] == "child" { |
| + os.Exit(dispatch(os.Args[1:], os.Stdout, os.Stderr)) |
| + } |
| + os.Exit(m.Run()) |
| +} |
| + |
| +// fakeTimerOS records what hostile-timer does. Nothing here signals a |
| +// real process: the real kill(-1) would reach every process the user |
| +// owns. |
| +type fakeTimerOS struct { |
| + pid int |
| + ignored []os.Signal |
| + kills []int |
| + rounds int |
| +} |
| + |
| +func (f *fakeTimerOS) os() timerOS { |
| + return timerOS{ |
| + getpid: func() int { return f.pid }, |
| + ignore: func(s ...os.Signal) { f.ignored = append(f.ignored, s...) }, |
| + pids: func() []int { return []int{1, 7, 9} }, |
| + kill: func(pid int, sig syscall.Signal) error { |
| + if sig != syscall.SIGKILL { |
| + panic("hostile-timer sent " + sig.String()) |
| + } |
| + f.kills = append(f.kills, pid) |
| + return nil |
| + }, |
| + rounds: func() <-chan time.Time { |
| + c := make(chan time.Time, f.rounds) |
| + for range f.rounds { |
| + c <- time.Time{} |
| + } |
| + close(c) |
| + return c |
| + }, |
| + } |
| +} |
| + |
| +// TestHostileTimerRefusesUnlessPID1: anywhere but PID 1 of its own |
| +// namespace hostile-timer signals nothing and ignores nothing. |
| +func TestHostileTimerRefusesUnlessPID1(t *testing.T) { |
| + f := &fakeTimerOS{pid: 4242} |
| + var out bytes.Buffer |
| + if code := hostileTimer(f.os(), &out); code != 1 || len(f.kills) != 0 || len(f.ignored) != 0 || |
| + out.String() != "FAIL hostile-timer: not PID 1 of its own PID namespace; refusing to signal every process\n" { |
| + t.Fatalf("exit %d, kills %v, ignored %v\n%s", code, f.kills, f.ignored, out.String()) |
| + } |
| +} |
| + |
| +// TestHostileTimerKillsEverythingItSees: as PID 1, hostile-timer |
| +// ignores SIGTERM and SIGINT, sends SIGKILL to every other PID it sees |
| +// and to -1, says so once, and does it again every round. |
| +func TestHostileTimerKillsEverythingItSees(t *testing.T) { |
| + f := &fakeTimerOS{pid: 1, rounds: 2} |
| + var out bytes.Buffer |
| + hostileTimer(f.os(), &out) |
| + if !slices.Equal(f.ignored, []os.Signal{syscall.SIGTERM, syscall.SIGINT}) { |
| + t.Fatalf("ignored %v", f.ignored) |
| + } |
| + if want := []int{7, 9, -1, 7, 9, -1, 7, 9, -1}; !slices.Equal(f.kills, want) { |
| + t.Fatalf("kills %v, want %v", f.kills, want) |
| + } |
| + if out.String() != "hostile-timer: ignoring SIGTERM and SIGINT; sent SIGKILL to 2 other processes and to -1; repeating until the deadline ends the task\n" { |
| + t.Fatalf("printed %q", out.String()) |
| + } |
| +} |
| + |
| +// TestDrillManyFiles: `drill many-files` runs the binary (here the test |
| +// binary, TestMain) as a child that makes 100,000 files and fails: the |
| +// handler names unreadable, and nothing is left in the scratch's out. |
| +func TestDrillManyFiles(t *testing.T) { |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + scratch := t.TempDir() |
| + var out bytes.Buffer |
| + r := &report{w: &out} |
| + drillChildJob(context.Background(), mediahandler.Config{Scratch: scratch, Logf: t.Logf}, self, mediahandler.HostileManyFiles, r) |
| + if r.failed || !strings.HasPrefix(out.String(), "PASS many-files: the job failed unreadable in ") { |
| + t.Fatalf("%s", out.String()) |
| + } |
| + if ents, err := os.ReadDir(scratch + "/out"); err != nil || len(ents) != 0 { |
| + t.Fatalf("out holds %d entries, %v", len(ents), err) |
| + } |
| +} |
| + |
| +// TestDrillBadOutputsCommand: `drill bad-outputs` with no payload (an |
| +// operator's run-task, preflight F24) refuses every hostile output and |
| +// reports 0 PUTs; the payload variable, when set, is removed. |
| +func TestDrillBadOutputsCommand(t *testing.T) { |
| + t.Setenv(mediahandler.ScratchEnv, t.TempDir()) |
| + t.Setenv(media.PayloadEnv, "") |
| + var stdout, stderr bytes.Buffer |
| + code := runDrill(context.Background(), realDrillEnv(), []string{"bad-outputs"}, &stdout, &stderr) |
| + lines := strings.Split(strings.TrimSpace(stdout.String()), "\n") |
| + if code != 0 || len(lines) != len(mediahandler.HostileOutputKinds)*3+1 || lines[len(lines)-1] != "PASS bad-outputs: 0 PUTs attempted" { |
| + t.Fatalf("exit %d\n%s", code, stdout.String()) |
| + } |
| + if !slices.Contains(lines, "PASS bad-outputs poster.jpg symlink: refused (output poster.jpg refused: a symlink)") { |
| + t.Fatalf("%s", stdout.String()) |
| + } |
| + if _, ok := os.LookupEnv(media.PayloadEnv); ok { |
| + t.Fatal("the payload variable is still set") |
| + } |
| +} |
diff --git a/cmd/carlos-media/drill_other.go b/cmd/carlos-media/drill_other.go| new file mode 100644 |
| index 000000000..aba68eb9d |
| --- /dev/null |
| +++ b/cmd/carlos-media/drill_other.go |
| @@ -0,0 +1,25 @@ |
| +//go:build !linux |
| + |
| +package main |
| + |
| +import ( |
| + "context" |
| + "io" |
| +) |
| + |
| +// linuxDrill: hostile-timer, fill-scratch, many-files and bad-outputs |
| +// need Linux (signals to every process, a child subreaper, the |
| +// handler's collect); the engine image is Linux. Elsewhere each fails |
| +// (preflight F23). |
| +func linuxDrill(_ context.Context, name string, rest []string, r *report, _ io.Writer) (int, bool) { |
| + switch name { |
| + case "hostile-timer", "fill-scratch", "many-files", "bad-outputs": |
| + if len(rest) != 0 { |
| + return 0, false |
| + } |
| + // engine.drill.unsupported (pending Luna pass). |
| + r.fail(name, "unsupported on this system") |
| + return r.exit(), true |
| + } |
| + return 0, false |
| +} |
diff --git a/cmd/carlos-media/drill_test.go b/cmd/carlos-media/drill_test.go| new file mode 100644 |
| index 000000000..dc3fed1a7 |
| --- /dev/null |
| +++ b/cmd/carlos-media/drill_test.go |
| @@ -0,0 +1,527 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// closedURL is an http URL on a port nothing listens on: a listener |
| +// opened and closed again. |
| +func closedURL(t *testing.T) string { |
| + t.Helper() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + addr := ln.Addr().String() |
| + ln.Close() |
| + return "http://" + addr + "/" |
| +} |
| + |
| +// testDrillEnv is a drill world with env as the whole environment, |
| +// the metadata addresses closed, and the endpoint APIs at the given |
| +// URLs. |
| +func testDrillEnv(t *testing.T, env map[string]string) drillEnv { |
| + t.Helper() |
| + dialer := &net.Dialer{Timeout: 2 * time.Second} |
| + return drillEnv{ |
| + lookupEnv: func(k string) (string, bool) { v, ok := env[k]; return v, ok }, |
| + environ: func() []string { |
| + var out []string |
| + for k, v := range env { |
| + out = append(out, k+"="+v) |
| + } |
| + return out |
| + }, |
| + now: func() time.Time { return time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) }, |
| + resolve: func(context.Context, string) ([]string, error) { return nil, errors.New("no") }, |
| + dial: dialer.DialContext, |
| + client: drillClient(dialer), |
| + credsURL: closedURL(t), |
| + imdsURL: closedURL(t), |
| + ecrAPIURL: func(string) string { return closedURL(t) }, |
| + logsURL: func(string) string { return closedURL(t) }, |
| + endpointTimeout: 5 * time.Second, |
| + checkTimeout: 2 * time.Second, |
| + } |
| +} |
| + |
| +func runTestDrill(t *testing.T, env drillEnv, args ...string) (int, string, string) { |
| + t.Helper() |
| + var stdout, stderr bytes.Buffer |
| + code := runDrill(context.Background(), env, args, &stdout, &stderr) |
| + return code, stdout.String(), stderr.String() |
| +} |
| + |
| +// TestDrillCredsReportsAnEnvCredential: a credential variable set is a |
| +// FAIL naming the variable, never its value; an environment with only |
| +// AWS_EXECUTION_ENV and AWS_REGION passes, naming both; a metadata |
| +// endpoint that answers with a credential fails; 169.254.169.254 |
| +// answering at all fails. |
| +func TestDrillCredsReportsAnEnvCredential(t *testing.T) { |
| + const secret = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYSECRETKEY" |
| + code, out, _ := runTestDrill(t, testDrillEnv(t, map[string]string{"AWS_SECRET_ACCESS_KEY": secret, "AWS_REGION": "eu-west-1"}), "creds") |
| + if code != 1 || !strings.Contains(out, "FAIL creds env: AWS_SECRET_ACCESS_KEY is set\n") || strings.Contains(out, secret) { |
| + t.Fatalf("a credential variable: exit %d\n%s", code, out) |
| + } |
| + for _, name := range credentialEnv { |
| + code, out, _ := runTestDrill(t, testDrillEnv(t, map[string]string{name: ""}), "creds") |
| + if code != 1 || !strings.Contains(out, "FAIL creds env: "+name+" is set\n") { |
| + t.Errorf("%s set and empty: exit %d\n%s", name, code, out) |
| + } |
| + } |
| + |
| + env := testDrillEnv(t, map[string]string{"AWS_EXECUTION_ENV": "AWS_ECS_FARGATE", "AWS_REGION": "eu-west-1"}) |
| + code, out, _ = runTestDrill(t, env, "creds") |
| + want := "PASS creds env: no credential variable; AWS variables set: AWS_EXECUTION_ENV AWS_REGION\n" + |
| + "PASS creds 169.254.170.2: unreachable\n" + |
| + "PASS creds 169.254.169.254: unreachable\n" + |
| + "PASS creds task metadata: ECS_CONTAINER_METADATA_URI_V4 is not set\n" |
| + if code != 0 || out != want { |
| + t.Fatalf("only metadata: exit %d\n%s\nwant\n%s", code, out, want) |
| + } |
| + |
| + cred := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + io.WriteString(w, `{"AccessKeyId":"ASIAEXAMPLE","SecretAccessKey":"`+secret+`","Token":"tok"}`) |
| + })) |
| + defer cred.Close() |
| + meta := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + io.WriteString(w, `{"TaskARN":"arn:aws:ecs:eu-west-1:111122223333:task/c/abc"}`) |
| + })) |
| + defer meta.Close() |
| + env = testDrillEnv(t, map[string]string{metadataEnv: meta.URL + "/v4/abc"}) |
| + env.credsURL, env.imdsURL = cred.URL, meta.URL |
| + code, out, _ = runTestDrill(t, env, "creds") |
| + if code != 1 || !strings.Contains(out, "FAIL creds 169.254.170.2: answered with a credential\n") || |
| + !strings.Contains(out, "FAIL creds 169.254.169.254: reachable\n") || |
| + !strings.Contains(out, "PASS creds task metadata: no answer holds a credential\n") || strings.Contains(out, secret) { |
| + t.Fatalf("credential endpoints: exit %d\n%s", code, out) |
| + } |
| + env = testDrillEnv(t, map[string]string{metadataEnv: cred.URL}) |
| + if code, out, _ = runTestDrill(t, env, "creds"); code != 1 || !strings.Contains(out, "FAIL creds task metadata: an answer holds a credential\n") { |
| + t.Fatalf("task metadata with a credential: exit %d\n%s", code, out) |
| + } |
| +} |
| + |
| +// TestDrillDNS: the five allowed names must resolve and the four others |
| +// must not; each wrong answer is a FAIL naming the name. |
| +func TestDrillDNS(t *testing.T) { |
| + allowed := map[string]bool{ |
| + "s3.eu-west-1.amazonaws.com": true, "carlos-media-drill.s3.eu-west-1.amazonaws.com": true, |
| + "api.ecr.eu-west-1.amazonaws.com": true, "carlos-media-drill.dkr.ecr.eu-west-1.amazonaws.com": true, |
| + "logs.eu-west-1.amazonaws.com": true, |
| + } |
| + env := testDrillEnv(t, map[string]string{"AWS_REGION": "eu-west-1"}) |
| + var asked []string |
| + env.resolve = func(_ context.Context, host string) ([]string, error) { |
| + asked = append(asked, host) |
| + if allowed[host] { |
| + return []string{"10.98.0.10"}, nil |
| + } |
| + return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true} |
| + } |
| + code, out, _ := runTestDrill(t, env, "dns") |
| + if code != 0 || strings.Count(out, "PASS ") != 9 { |
| + t.Fatalf("exit %d\n%s", code, out) |
| + } |
| + for _, blocked := range []string{"example.com", "amazonaws.com", "sts.eu-west-1.amazonaws.com", "ecs.eu-west-1.amazonaws.com"} { |
| + if !slices.Contains(asked, blocked) { |
| + t.Errorf("%s was not tried", blocked) |
| + } |
| + } |
| + allowed["sts.eu-west-1.amazonaws.com"] = true |
| + delete(allowed, "logs.eu-west-1.amazonaws.com") |
| + code, out, _ = runTestDrill(t, env, "dns") |
| + if code != 1 || !strings.Contains(out, "FAIL dns sts.eu-west-1.amazonaws.com: resolves\n") || |
| + !strings.Contains(out, "FAIL dns logs.eu-west-1.amazonaws.com: does not resolve\n") { |
| + t.Fatalf("exit %d\n%s", code, out) |
| + } |
| + if code, out, _ = runTestDrill(t, testDrillEnv(t, nil), "dns"); code != 1 || out != "FAIL dns: no region in AWS_REGION or AWS_DEFAULT_REGION\n" { |
| + t.Fatalf("no region: exit %d\n%s", code, out) |
| + } |
| +} |
| + |
| +// TestDrillNet: 1.1.1.1:443 and each address given are dialled; any |
| +// connection is a FAIL; an argument that is not an IP is refused. |
| +func TestDrillNet(t *testing.T) { |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + env := testDrillEnv(t, nil) |
| + var dialled []string |
| + env.dial = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + dialled = append(dialled, addr) |
| + if addr == ln.Addr().String() { |
| + return net.Dial(network, addr) |
| + } |
| + return nil, errors.New("refused") |
| + } |
| + code, out, _ := runTestDrill(t, env, "net", "10.0.3.7", ln.Addr().String()) |
| + if code != 1 || !slices.Equal(dialled, []string{"1.1.1.1:443", "10.0.3.7:443", ln.Addr().String()}) || |
| + out != "PASS net 1.1.1.1:443: no connection\nPASS net 10.0.3.7:443: no connection\nFAIL net "+ln.Addr().String()+": connected\n" { |
| + t.Fatalf("exit %d, dialled %q\n%s", code, dialled, out) |
| + } |
| + if code, out, _ := runTestDrill(t, env, "net", "console.internal"); code != 1 || !strings.HasPrefix(out, "FAIL net: ") { |
| + t.Fatalf("a host name: exit %d\n%s", code, out) |
| + } |
| + if code, _, errOut := runTestDrill(t, env, "net"); code != exitUsage || errOut != drillUsage+"\n" { |
| + t.Fatalf("no address: exit %d", code) |
| + } |
| +} |
| + |
| +// endpointServer records each request it gets and answers status. |
| +type endpointServer struct { |
| + *httptest.Server |
| + mu sync.Mutex |
| + reqs []recorded |
| +} |
| + |
| +type recorded struct { |
| + method, path string |
| + header http.Header |
| + body []byte |
| +} |
| + |
| +func newEndpoint(t *testing.T, status int) *endpointServer { |
| + t.Helper() |
| + e := &endpointServer{} |
| + e.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + e.mu.Lock() |
| + e.reqs = append(e.reqs, recorded{r.Method, r.URL.Path, r.Header.Clone(), body}) |
| + e.mu.Unlock() |
| + w.WriteHeader(status) |
| + })) |
| + t.Cleanup(e.Close) |
| + return e |
| +} |
| + |
| +func (e *endpointServer) requests() []recorded { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + return append([]recorded(nil), e.reqs...) |
| +} |
| + |
| +// drillInput is an endpoint drill input for the four servers. |
| +func drillInput(s3URL, manifestURL string) endpointInput { |
| + return endpointInput{ |
| + S3GetURL: s3URL + "/drill-object?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=deadbeefcafe", |
| + ECRToken: "QVdTOmRyaWxsLXJlZ2lzdHJ5LXBhc3N3b3Jk", |
| + ECRManifestURL: manifestURL + "/v2/engine/manifests/sha256:0123", |
| + Region: "eu-west-1", |
| + AccessKeyID: "AKIAFOREIGNDRILL0001", |
| + SecretAccessKey: "foreign/secret+key/value0000000000000000", |
| + LogGroup: "carlos-media-endpoint-drill", |
| + LogStream: "drill-stream", |
| + } |
| +} |
| + |
| +func endpointEnv(t *testing.T, in endpointInput, ecrAPI, logs string) drillEnv { |
| + t.Helper() |
| + b, err := json.Marshal(in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + env := testDrillEnv(t, map[string]string{drillInputEnv: string(b)}) |
| + env.ecrAPIURL = func(region string) string { |
| + if region != "eu-west-1" { |
| + t.Errorf("ecr api for region %q", region) |
| + } |
| + return ecrAPI + "/" |
| + } |
| + env.logsURL = func(string) string { return logs + "/" } |
| + return env |
| +} |
| + |
| +// TestDrillEndpointsOnePass: S3 answering 403, the ECR API 200, the |
| +// ECR registry on a closed port and Logs 200 print exactly four lines. |
| +// A second pass with the registry answering shows its request carried |
| +// Authorization: Basic <the passed token> unchanged; the two API calls |
| +// are SigV4-signed with the passed key for their services, the logs |
| +// call names the group and stream. |
| +func TestDrillEndpointsOnePass(t *testing.T) { |
| + s3 := newEndpoint(t, http.StatusForbidden) |
| + api := newEndpoint(t, http.StatusOK) |
| + logs := newEndpoint(t, http.StatusOK) |
| + in := drillInput(s3.URL, strings.TrimSuffix(closedURL(t), "/")) |
| + t.Setenv(drillInputEnv, "the drill's input") |
| + code, out, errOut := runTestDrill(t, endpointEnv(t, in, api.URL, logs.URL), "endpoints") |
| + if _, ok := os.LookupEnv(drillInputEnv); ok { |
| + t.Error("the drill left its input in the environment") |
| + } |
| + if code != 0 || errOut != "" || out != "s3 refused 403\necr-api ok\necr-docker refused conn\nlogs ok\n" { |
| + t.Fatalf("exit %d, stderr %q\n%s", code, errOut, out) |
| + } |
| + |
| + docker := newEndpoint(t, http.StatusOK) |
| + in = drillInput(s3.URL, docker.URL) |
| + if code, out, _ = runTestDrill(t, endpointEnv(t, in, api.URL, logs.URL), "endpoints"); code != 0 || out != "s3 refused 403\necr-api ok\necr-docker ok\nlogs ok\n" { |
| + t.Fatalf("second pass: exit %d\n%s", code, out) |
| + } |
| + d := docker.requests() |
| + if len(d) != 1 || d[0].method != http.MethodHead || d[0].path != "/v2/engine/manifests/sha256:0123" || |
| + d[0].header.Get("Authorization") != "Basic "+in.ECRToken || d[0].header.Values("Authorization")[0] != "Basic "+in.ECRToken { |
| + t.Fatalf("registry request %+v", d) |
| + } |
| + if g := s3.requests(); len(g) != 2 || g[0].method != http.MethodGet || g[0].header.Get("Authorization") != "" { |
| + t.Fatalf("s3 requests %+v", g) |
| + } |
| + for _, c := range []struct { |
| + e *endpointServer |
| + service, target string |
| + }{ |
| + {api, "ecr", "AmazonEC2ContainerRegistry_V20150921.GetAuthorizationToken"}, |
| + {logs, "logs", "Logs_20140328.PutLogEvents"}, |
| + } { |
| + r := c.e.requests()[0] |
| + auth := r.header.Get("Authorization") |
| + if r.method != http.MethodPost || r.header.Get("X-Amz-Target") != c.target || |
| + !strings.HasPrefix(auth, "AWS4-HMAC-SHA256 Credential="+in.AccessKeyID+"/20261118/eu-west-1/"+c.service+"/aws4_request, SignedHeaders=") { |
| + t.Fatalf("%s request: %s %q", c.service, r.method, auth) |
| + } |
| + if !strings.Contains(auth, "x-amz-target") || !strings.Contains(auth, "x-amz-date") { |
| + t.Errorf("%s signs %q", c.service, auth) |
| + } |
| + } |
| + var put struct { |
| + LogGroupName, LogStreamName string |
| + LogEvents []struct{ Timestamp int64 } |
| + } |
| + if err := json.Unmarshal(logs.requests()[0].body, &put); err != nil || put.LogGroupName != in.LogGroup || |
| + put.LogStreamName != in.LogStream || len(put.LogEvents) != 1 || put.LogEvents[0].Timestamp != 1795003200000 { |
| + t.Fatalf("logs body %s, %v", logs.requests()[0].body, err) |
| + } |
| + |
| + // No input, or an input with a field missing: one fixed line, exit 1. |
| + for _, raw := range []string{"", `{"s3_get_url":"x"}`, `not json`} { |
| + env := testDrillEnv(t, map[string]string{drillInputEnv: raw}) |
| + code, out, errOut := runTestDrill(t, env, "endpoints") |
| + if code != 1 || out != "" || errOut != "drill endpoints: CARLOS_MEDIA_DRILL does not hold the drill's input\n" { |
| + t.Fatalf("input %q: exit %d %q %q", raw, code, out, errOut) |
| + } |
| + } |
| +} |
| + |
| +// TestSigV4Vector: AWS's published SigV4 test vector get-vanilla. |
| +func TestSigV4Vector(t *testing.T) { |
| + req, err := http.NewRequest(http.MethodGet, "https://example.amazonaws.com/", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Date(2015, 8, 30, 12, 36, 0, 0, time.UTC) |
| + signV4(req, nil, sigv4Key{AccessKeyID: "AKIDEXAMPLE", SecretAccessKey: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"}, "us-east-1", "service", now) |
| + canonical, signed := canonicalRequest(req, nil) |
| + wantCanonical := "GET\n/\n\nhost:example.amazonaws.com\nx-amz-date:20150830T123600Z\n\nhost;x-amz-date\n" + |
| + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" |
| + if canonical != wantCanonical || signed != "host;x-amz-date" || hexSHA256([]byte(canonical)) != "bb579772317eb040ac9ed261061d46c1f17a8133879d6129b6e1c25292927e63" { |
| + t.Fatalf("canonical request\n%s", canonical) |
| + } |
| + want := "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-date, " + |
| + "Signature=5fa00fa31553b73ebf1942676e86291e8372ff2a2260956d9b8aae1d763fbf31" |
| + if got := req.Header.Get("Authorization"); got != want { |
| + t.Fatalf("Authorization\n got %s\nwant %s", got, want) |
| + } |
| +} |
| + |
| +// writePass writes one pass's output to a file and answers its path. |
| +func writePass(t *testing.T, dir, name, out string) string { |
| + t.Helper() |
| + p := filepath.Join(dir, name) |
| + if err := os.WriteFile(p, []byte(out), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return p |
| +} |
| + |
| +const ( |
| + allRefused = "s3 refused 403\necr-api refused 403\necr-docker refused 403\nlogs refused 400\n" |
| + allOK = "s3 ok\necr-api ok\necr-docker ok\nlogs ok\n" |
| +) |
| + |
| +// TestEndpointsVerdict: A all refused, B all ok, C all refused exits 0 |
| +// with the table; any one cell otherwise, a missing phase, a missing |
| +// line or a stray line exits 1 naming the cell. Nothing read from a |
| +// file is echoed. |
| +func TestEndpointsVerdict(t *testing.T) { |
| + dir := t.TempDir() |
| + run := func(a, b, c string) (int, string) { |
| + var out bytes.Buffer |
| + code := endpointsVerdict([]string{writePass(t, dir, "A", a), writePass(t, dir, "B", b), writePass(t, dir, "C", c)}, &out) |
| + return code, out.String() |
| + } |
| + code, out := run(allRefused, allOK, "s3 refused 403\necr-api refused conn\necr-docker refused 403\nlogs refused 400\n") |
| + if code != 0 || !strings.HasPrefix(out, "endpoint A (saved) B (open) C (restored) \ns3 refused 403 ok refused 403 \n") || |
| + !strings.HasSuffix(out, "PASS endpoints: refused under the saved and restored policies, ok under the open one, at all four endpoints\n") { |
| + t.Fatalf("exit %d\n%s", code, out) |
| + } |
| + for _, c := range []struct { |
| + a, b, c, fail string |
| + }{ |
| + {strings.Replace(allRefused, "s3 refused 403", "s3 ok", 1), allOK, allRefused, "FAIL s3 phase A: ok, want refused\n"}, |
| + {allRefused, strings.Replace(allOK, "ecr-docker ok", "ecr-docker refused 403", 1), allRefused, "FAIL ecr-docker phase B: refused 403, want ok\n"}, |
| + {allRefused, allOK, strings.Replace(allRefused, "logs refused 400", "logs ok", 1), "FAIL logs phase C: ok, want refused\n"}, |
| + {allRefused, strings.Replace(allOK, "ecr-api ok\n", "", 1), allRefused, "FAIL ecr-api phase B: missing, want ok\n"}, |
| + {allRefused, "", allRefused, "FAIL s3 phase B: missing, want ok\n"}, |
| + {allRefused, allOK + "https://secret.example/?X-Amz-Signature=1\n", allRefused, "FAIL logs phase B: malformed, want ok\n"}, |
| + {allRefused, allOK + "s3 ok\n", allRefused, "FAIL s3 phase B: malformed, want ok\n"}, |
| + } { |
| + code, out := run(c.a, c.b, c.c) |
| + if code != 1 || !strings.Contains(out, c.fail) || strings.Count(out, "FAIL ") < 1 || strings.Contains(out, "PASS") || strings.Contains(out, "secret") { |
| + t.Errorf("want %q: exit %d\n%s", c.fail, code, out) |
| + } |
| + } |
| + var out2 bytes.Buffer |
| + if code := endpointsVerdict([]string{filepath.Join(dir, "none"), filepath.Join(dir, "B"), filepath.Join(dir, "C")}, &out2); code != 1 || !strings.Contains(out2.String(), "FAIL s3 phase A: missing, want refused\n") { |
| + t.Fatalf("no A file: exit %d\n%s", code, out2.String()) |
| + } |
| +} |
| + |
| +// TestDrillOutputHasNoSecrets: whatever the drills are given (a |
| +// credential in the environment and at the metadata endpoints, the |
| +// endpoint input's key, token and presigned URL, a pass file holding a |
| +// URL), nothing they print to stdout or stderr carries a secret, a URL |
| +// or a header. |
| +func TestDrillOutputHasNoSecrets(t *testing.T) { |
| + s3 := newEndpoint(t, http.StatusForbidden) |
| + api := newEndpoint(t, http.StatusBadRequest) |
| + logs := newEndpoint(t, http.StatusOK) |
| + docker := newEndpoint(t, http.StatusUnauthorized) |
| + in := drillInput(s3.URL, docker.URL) |
| + cred := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + io.WriteString(w, `{"AccessKeyId":"`+in.AccessKeyID+`","SecretAccessKey":"`+in.SecretAccessKey+`","Token":"`+in.ECRToken+`"}`) |
| + })) |
| + defer cred.Close() |
| + |
| + var all bytes.Buffer |
| + env := endpointEnv(t, in, api.URL, logs.URL) |
| + for _, args := range [][]string{{"endpoints"}, {"creds"}} { |
| + env2 := env |
| + if args[0] == "creds" { |
| + b, _ := json.Marshal(in) |
| + env2 = testDrillEnv(t, map[string]string{"AWS_SECRET_ACCESS_KEY": in.SecretAccessKey, "AWS_SESSION_TOKEN": in.ECRToken, |
| + metadataEnv: cred.URL, drillInputEnv: string(b)}) |
| + env2.credsURL, env2.imdsURL = cred.URL, cred.URL |
| + } |
| + _, out, errOut := runTestDrill(t, env2, args...) |
| + all.WriteString(out + errOut) |
| + } |
| + dir := t.TempDir() |
| + var vout bytes.Buffer |
| + endpointsVerdict([]string{writePass(t, dir, "A", in.S3GetURL+"\n"+allRefused), writePass(t, dir, "B", "Authorization: Basic "+in.ECRToken), writePass(t, dir, "C", allRefused)}, &vout) |
| + all.Write(vout.Bytes()) |
| + if all.Len() == 0 { |
| + t.Fatal("no output") |
| + } |
| + for _, s := range []string{in.AccessKeyID, in.SecretAccessKey, in.ECRToken, in.S3GetURL, "X-Amz", "Signature", "http://", "https://", |
| + "Authorization", "Basic", s3.URL, strings.TrimPrefix(s3.URL, "http://"), in.LogStream, "deadbeef"} { |
| + if strings.Contains(all.String(), s) { |
| + t.Errorf("the drills printed %q:\n%s", s, all.String()) |
| + } |
| + } |
| +} |
| + |
| +// TestDrillUsage: no drill, an unknown one, or extra arguments are a |
| +// usage error, exit 2, with the usage line on stderr. |
| +func TestDrillUsage(t *testing.T) { |
| + for _, args := range [][]string{nil, {"nope"}, {"creds", "x"}, {"dns", "x"}, {"endpoints", "x"}, {"endpoints-verdict", "a", "b"}, |
| + {"hostile-timer", "x"}, {"fill-scratch", "x"}, {"bad-outputs", "x"}} { |
| + var stdout, stderr bytes.Buffer |
| + if code := dispatch(append([]string{"drill"}, args...), &stdout, &stderr); code != exitUsage || stdout.Len() != 0 || stderr.String() != drillUsage+"\n" { |
| + t.Errorf("drill %q: exit %d, %q %q", args, code, stdout.String(), stderr.String()) |
| + } |
| + } |
| + for _, args := range [][]string{nil, {"both"}, {"video", "audio"}} { |
| + var stdout, stderr bytes.Buffer |
| + if code := dispatch(append([]string{"selftest"}, args...), &stdout, &stderr); code != exitUsage || stderr.String() != selftestUsage+"\n" { |
| + t.Errorf("selftest %q: exit %d, %q", args, code, stderr.String()) |
| + } |
| + } |
| +} |
| + |
| +// TestMediaEndpointDrillPythonGuards runs scripts/media_endpoint_drill_test.py |
| +// (the drill script's cleanup on every exit, against a fake aws), so CI |
| +// runs it (preflight F31). It skips locally without python3 or bash; |
| +// in CI it fails without them. |
| +func TestMediaEndpointDrillPythonGuards(t *testing.T) { |
| + python := ciBinary(t, "python3") |
| + ciBinary(t, "bash") |
| + cmd := exec.Command(python, "-B", "-m", "unittest", "-v", "scripts.media_endpoint_drill_test") |
| + cmd.Dir = "../.." |
| + output, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("media endpoint drill Python tests: %v\n%s", err, output) |
| + } |
| + t.Logf("%s", output) |
| +} |
| + |
| +// ciBinary is name on PATH, or a skip locally and a failure in CI. |
| +func ciBinary(t *testing.T, name string) string { |
| + t.Helper() |
| + binary, err := exec.LookPath(name) |
| + if err == nil { |
| + return binary |
| + } |
| + if os.Getenv("CI") != "" || os.Getenv("AMADAN_CI") != "" { |
| + t.Fatalf("%s is required in CI: %v", name, err) |
| + } |
| + t.Skipf("%s is not installed: %v", name, err) |
| + return "" |
| +} |
| + |
| +// FuzzParseEndpointInput: whatever CARLOS_MEDIA_DRILL holds, the parse |
| +// never panics, and an input it accepts has every field and a plain |
| +// region. |
| +func FuzzParseEndpointInput(f *testing.F) { |
| + b, _ := json.Marshal(drillInput("http://127.0.0.1:1", "http://127.0.0.1:2")) |
| + f.Add(string(b)) |
| + f.Add(`{"s3_get_url":"x"}`) |
| + f.Add(``) |
| + f.Fuzz(func(t *testing.T, raw string) { |
| + in, ok := parseEndpointInput(raw) |
| + if !ok { |
| + return |
| + } |
| + if in.S3GetURL == "" || in.ECRToken == "" || in.LogStream == "" || !regionName.MatchString(in.Region) { |
| + t.Fatalf("accepted %+v", in) |
| + } |
| + }) |
| +} |
| + |
| +// FuzzReadPass: whatever a pass's output file holds (it comes from the |
| +// task's log), every cell is one of the verdict's own words, never |
| +// text from the file. |
| +func FuzzReadPass(f *testing.F) { |
| + f.Add([]byte(allRefused)) |
| + f.Add([]byte(allOK + "s3 ok\n")) |
| + f.Add([]byte("https://example.com/?X-Amz-Signature=1\n")) |
| + cell := regexp.MustCompile(`^(ok|refused (conn|[1-5][0-9][0-9])|missing|malformed)$`) |
| + dir := f.TempDir() |
| + f.Fuzz(func(t *testing.T, b []byte) { |
| + p := filepath.Join(dir, "pass") |
| + if err := os.WriteFile(p, b, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + for e, c := range readPass(p) { |
| + if !slices.Contains(endpointNames, e) || !cell.MatchString(c) { |
| + t.Fatalf("cell %q = %q", e, c) |
| + } |
| + } |
| + }) |
| +} |
diff --git a/cmd/carlos-media/main.go b/cmd/carlos-media/main.go| index 519212e34..c8cc842c6 100644 |
| --- a/cmd/carlos-media/main.go |
| +++ b/cmd/carlos-media/main.go |
| @@ -7,7 +7,8 @@ |
| // takes no argument. |
| // - codec: the conversion handler (internal/mediahandler), reading |
| // media.PayloadEnv and taking no argument. |
| -// - selftest, drill: rollout checks (plan 3 Task 7). |
| +// - selftest <video|audio>, drill <name>: rollout checks (plan 3 |
| +// Task 7; selftest.go in internal/mediahandler, drill.go here). |
| // - version: prints the build. |
| // |
| // The refusal gate requires each container's entry point and command to |
| @@ -51,9 +52,10 @@ func dispatch(args []string, stdout, stderr io.Writer) int { |
| return deadlineCommand(args[1:]) |
| case media.CodecCommand: |
| return codecCommand(args[1:], stderr) |
| - case "selftest", "drill": |
| - // Filled by plan 3 Task 7. Until then each fails. |
| - return media.ExitFailed |
| + case "selftest": |
| + return selftestCommand(args[1:], stdout, stderr) |
| + case "drill": |
| + return drillCommand(args[1:], stdout, stderr) |
| case "version": |
| fmt.Fprintln(stdout, version.Build) |
| return 0 |
| @@ -98,6 +100,31 @@ func codecCommand(rest []string, stderr io.Writer) int { |
| return mediahandler.Run(context.Background(), cfg, payload) |
| } |
| +// selftestUsage is copy deck row engine.selftest.usage (pending Luna |
| +// pass). |
| +const selftestUsage = "usage: carlos-media selftest <video|audio>" |
| + |
| +// selftestCommand is `selftest video|audio` (plan 3 Task 7, preflight |
| +// F25): mediahandler.Selftest's cases for one preset, run on the |
| +// image's own ffmpeg, as a one-off task of that preset's class. One |
| +// PASS or FAIL line per case on stdout; the handler's log lines on |
| +// stderr. Exit 0 when every case passed, 1 otherwise, 2 for a usage |
| +// error. |
| +func selftestCommand(rest []string, stdout, stderr io.Writer) int { |
| + if len(rest) != 1 || (rest[0] != mediahandler.SelftestVideo && rest[0] != mediahandler.SelftestAudio) { |
| + fmt.Fprintln(stderr, selftestUsage) |
| + return exitUsage |
| + } |
| + cfg := mediahandler.Config{Logf: func(format string, args ...any) { |
| + fmt.Fprintf(stderr, format+"\n", args...) |
| + }} |
| + // Background: as codec, the task's end bounds the run. |
| + if err := mediahandler.Selftest(context.Background(), cfg, rest[0], stdout); err != nil { |
| + return 1 |
| + } |
| + return 0 |
| +} |
| + |
| // signalsReady runs once SIGTERM is caught. It does nothing in the |
| // binary; TestDeadlineSIGTERMProcess's child sets it to tell the parent |
| // when a SIGTERM will reach runDeadline rather than kill the process. |
diff --git a/cmd/carlos-media/sigv4.go b/cmd/carlos-media/sigv4.go| new file mode 100644 |
| index 000000000..06008e13b |
| --- /dev/null |
| +++ b/cmd/carlos-media/sigv4.go |
| @@ -0,0 +1,97 @@ |
| +package main |
| + |
| +import ( |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "net/http" |
| + "sort" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// A stdlib AWS Signature Version 4 signer, for the endpoint drill's two |
| +// signed API calls (ECR GetAuthorizationToken and CloudWatch Logs |
| +// PutLogEvents) made with the foreign user's key. The provider boundary |
| +// keeps the AWS SDK out of cmd/carlos-media (plan 3 Task 13), so this |
| +// is the whole of what the drill needs and no more: a request with an |
| +// empty query, a body known in full, and the headers it sets itself. |
| + |
| +// sigv4Algorithm is the only algorithm signed here. |
| +const sigv4Algorithm = "AWS4-HMAC-SHA256" |
| + |
| +// sigv4Key is one access key: no session token (the drill's foreign |
| +// user has a long-term key). |
| +type sigv4Key struct { |
| + AccessKeyID, SecretAccessKey string |
| +} |
| + |
| +// signV4 signs req, whose body is body (already set on req), for |
| +// service in region at now: it sets X-Amz-Date and Authorization, |
| +// signing the host and every header req carries. req's URL must have |
| +// an empty query and a path that needs no escaping beyond what it has. |
| +func signV4(req *http.Request, body []byte, key sigv4Key, region, service string, now time.Time) { |
| + amzDate := now.UTC().Format("20060102T150405Z") |
| + req.Header.Set("X-Amz-Date", amzDate) |
| + scope := amzDate[:8] + "/" + region + "/" + service + "/aws4_request" |
| + canonical, signed := canonicalRequest(req, body) |
| + toSign := sigv4Algorithm + "\n" + amzDate + "\n" + scope + "\n" + hexSHA256([]byte(canonical)) |
| + k := hmacSHA256([]byte("AWS4"+key.SecretAccessKey), amzDate[:8]) |
| + k = hmacSHA256(k, region) |
| + k = hmacSHA256(k, service) |
| + k = hmacSHA256(k, "aws4_request") |
| + sig := hex.EncodeToString(hmacSHA256(k, toSign)) |
| + req.Header.Set("Authorization", sigv4Algorithm+" Credential="+key.AccessKeyID+"/"+scope+ |
| + ", SignedHeaders="+signed+", Signature="+sig) |
| +} |
| + |
| +// canonicalRequest is SigV4's canonical request for req and body, and |
| +// its signed header list: the method, the path ("/" when empty), an |
| +// empty query, every header of req plus host, lower-cased, sorted, each |
| +// value trimmed with inner runs of spaces folded, and the body's |
| +// SHA-256. |
| +func canonicalRequest(req *http.Request, body []byte) (canonical, signed string) { |
| + headers := map[string]string{"host": req.Host} |
| + if headers["host"] == "" { |
| + headers["host"] = req.URL.Host |
| + } |
| + for name, values := range req.Header { |
| + lower := strings.ToLower(name) |
| + if lower == "authorization" { |
| + continue |
| + } |
| + folded := make([]string, len(values)) |
| + for i, v := range values { |
| + folded[i] = strings.Join(strings.Fields(v), " ") |
| + } |
| + headers[lower] = strings.Join(folded, ",") |
| + } |
| + names := make([]string, 0, len(headers)) |
| + for n := range headers { |
| + names = append(names, n) |
| + } |
| + sort.Strings(names) |
| + var b strings.Builder |
| + path := req.URL.EscapedPath() |
| + if path == "" { |
| + path = "/" |
| + } |
| + b.WriteString(req.Method + "\n" + path + "\n" + req.URL.RawQuery + "\n") |
| + for _, n := range names { |
| + b.WriteString(n + ":" + headers[n] + "\n") |
| + } |
| + signed = strings.Join(names, ";") |
| + b.WriteString("\n" + signed + "\n" + hexSHA256(body)) |
| + return b.String(), signed |
| +} |
| + |
| +func hexSHA256(b []byte) string { |
| + sum := sha256.Sum256(b) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +func hmacSHA256(key []byte, data string) []byte { |
| + m := hmac.New(sha256.New, key) |
| + m.Write([]byte(data)) |
| + return m.Sum(nil) |
| +} |
diff --git a/docs/superpowers/notes/census-claims-media-conversion.tsv b/docs/superpowers/notes/census-claims-media-conversion.tsv| index a99a5f179..d8619fb73 100644 |
| --- a/docs/superpowers/notes/census-claims-media-conversion.tsv |
| +++ b/docs/superpowers/notes/census-claims-media-conversion.tsv |
| @@ -47,3 +47,9 @@ |
| # internal/clireg: DispatchErr (Dispatch returning an unhandled leaf error instead of panicking; Dispatch is |
| # DispatchErr plus the same panic), Node.FallbackErr (a fallback whose error is routed like a leaf's), and |
| # Validate's matching check. The walk and matching are unchanged. No I/O. |
| +# |
| +# Plan 3 Task 7 (preflight F28): scripts/media-endpoint-drill.sh is new. F28 expected every .sh to be a census unit, |
| +# but the census does not scan scripts/ (census_scope_fixture_test.go pins scripts/tool.sh:external as not scanned, |
| +# AGENTS.md "What is in scope": scripts/ is out), and `make census-card` with this file stays clean after the script |
| +# is added, so it takes no claim line (one would be "not a change the census sees"). For the reviewer: it is an |
| +# operator drill script run from docs-t1 with the operator's own AWS profiles; root never runs, installs or reads it. |
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index dc54068a9..e483459d4 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -594,3 +594,36 @@ prints nothing. |
| | `engine.codec.result_unwritten` | `codec: converted, but the result could not be written` (pending Luna pass; plan 3 Task 6) | |
| | `engine.codec.error_unwritten` | `codec: the result naming %s could not be written` (pending Luna pass; plan 3 Task 6). `%s` is the job error code | |
| | `engine.codec.unexpected` | `codec: an unexpected %T ends the job` (pending Luna pass; plan 3 Task 6). `%T` is a Go error type, never its text | |
| + |
| +### Rollout checks: `selftest`, `drill` and the endpoint drill script (plan 3 Task 7) |
| + |
| +Operator-facing text the rollout reads (R2-R4): one-off tasks' logs and |
| +the drill script's terminal. Every line is fixed words, numbers, an |
| +environment variable's name, a host name, an address the operator typed |
| +or an output's name: never a credential, a URL or a header. `%s` and |
| +`%d` are what each row says. All rows are pending a Luna pass. |
| + |
| +| Key | Text | |
| +|---|---| |
| +| `engine.selftest.usage` | `usage: carlos-media selftest <video\|audio>` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.selftest.pass` | `PASS %s` (pending Luna pass; plan 3 Task 7). `%s` is a case: `video-1080p`, `video-portrait-rotated`, `video-pq-4k`, `video-location-tag`, `audio-voice-webm-live`, `audio-silent-wav`, `audio-mp3-cover-art` | |
| +| `engine.selftest.fail` | `FAIL %s: %s` (pending Luna pass; plan 3 Task 7). A case and one of `engine.selftest.reason.*` | |
| +| `engine.selftest.no_scratch` | `FAIL selftest: no directory in the scratch: %s`, `FAIL selftest: no local store: %s` (pending Luna pass; plan 3 Task 7). The system's error number's text | |
| +| `engine.selftest.reason.*` | `no case directory: %s`; `ffmpeg could not make the source: %s`; `the source cannot be read: %s`; `the source does not sniff: %s`; `the source does not probe: %s`; `no payload: %s`; `the conversion exited %d`; `the handler broke the presigned contract: %s` (`a request the store did not sign` or `a signed header missing or changed`); `the result is not a success result`; `converted %d ms of a %d ms source`; `%s: stored %d bytes, the result says %d`; `%s does not read as a fragmented MP4: %s`; `%s: no playlist: %s`; `%s is not the playlist of %s`; `the result gives %s as %dx%d, want %dx%d`; `poster.jpg is not a JPEG`; `video.mp4 does not probe: %s`; `video.mp4 is %s %dx%d, want h264 %dx%d`; `peaks.json does not hold %d peaks`; `peaks.json has a peak outside 0 to 255`; `a silent source has a peak of %d`; `every peak is 0`; `the source does not measure: %s`; `audio.mp4 does not measure: %s`; `audio.mp4's true peak is %.1f dBTP, over %.1f`; `audio.mp4 is %.1f LUFS, louder than %.0f LUFS`; `audio.mp4's loudness range is %.1f LU, the source's %.1f`; `a log line carries the source's metadata`; `%s carries the source's metadata` (pending Luna pass; plan 3 Task 7). Each `%s` after a colon is a job code, a system error number's text or one of the meter's fixed reasons | |
| +| `engine.selftest.measured` | `%s: source %.1f LUFS, %.1f dBTP, LRA %.1f LU; audio.mp4 %.1f LUFS, %.1f dBTP, LRA %.1f LU` (pending Luna pass; plan 3 Task 7). On stderr, the voice case only | |
| +| `engine.loudness.reason.lra` | `the ebur128 summary's LRA is not a number`, `the ebur128 summary has no LRA` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.usage` | `usage: carlos-media drill <creds\|dns\|net <address>…\|endpoints\|endpoints-verdict <A> <B> <C>\|hostile-timer\|fill-scratch\|many-files\|bad-outputs>` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.creds` | `PASS creds env: no credential variable; AWS variables set: %s` (names, or `none`); `FAIL creds env: %s is set` (a variable's name); `PASS creds 169.254.170.2: unreachable`, `PASS creds 169.254.170.2: answered with no credential`, `FAIL creds 169.254.170.2: answered with a credential`; `PASS creds 169.254.169.254: unreachable`, `FAIL creds 169.254.169.254: reachable`; `PASS creds task metadata: %s is not set`, `PASS creds task metadata: no answer holds a credential`, `FAIL creds task metadata: an answer holds a credential` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.dns` | `PASS dns %s: resolves`, `FAIL dns %s: does not resolve` (an allowed name); `PASS dns %s: does not resolve`, `FAIL dns %s: resolves` (a blocked one); `FAIL dns: no region in AWS_REGION or AWS_DEFAULT_REGION` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.net` | `PASS net %s: no connection`, `FAIL net %s: connected` (an address and port); `FAIL net: an argument is not an IP address with an optional port` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.endpoints` | `%s ok`, `%s refused %s` (an endpoint: `s3`, `ecr-api`, `ecr-docker`, `logs`; a status code or `conn`), the only stdout of a pass; `drill endpoints: CARLOS_MEDIA_DRILL does not hold the drill's input` on stderr (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.verdict` | the table head `endpoint A (saved) B (open) C (restored)`, then one row per endpoint of cells (`ok`, `refused %s`, `missing`, `malformed`); `FAIL %s phase %s: %s, want %s` (an endpoint, A/B/C, a cell, `refused` or `ok`); `PASS endpoints: refused under the saved and restored policies, ok under the open one, at all four endpoints` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.hostile_timer` | `FAIL hostile-timer: not PID 1 of its own PID namespace; refusing to signal every process`; `hostile-timer: ignoring SIGTERM and SIGINT; sent SIGKILL to %d other processes and to -1; repeating until the deadline ends the task` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.child_job` | `PASS %s: the job failed %s in %s; no child left`, `FAIL %s: the job ended %s in %s, want %s`, `FAIL %s: the binary's own path is unknown` (`fill-scratch` or `many-files`, a job code or `no error`, a duration) (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.bad_outputs` | `PASS bad-outputs %s %s: refused (%s)` (an output's name, a kind: `symlink`, `hardlink`, `fifo`, `directory`, `empty`, `oversize`; `engine.collect.refused`'s text), `FAIL bad-outputs %s %s: not refused`, `FAIL bad-outputs: the drill could not run: %s`, `FAIL bad-outputs: %d PUTs attempted, want 0`, `PASS bad-outputs: 0 PUTs attempted` (pending Luna pass; plan 3 Task 7) | |
| +| `engine.drill.unsupported` | `FAIL %s: unsupported on this system` (pending Luna pass; plan 3 Task 7). Off Linux only | |
| +| `engine.drill.child` | `hostile child: unknown kind`, `hostile child: no file system status: %s`, `hostile child: refusing to fill a %d-byte file system`, `hostile child: %s` (on the hostile child's stderr; it reaches the task's log only as `engine.encode.failed`'s tail) (pending Luna pass; plan 3 Task 7) | |
| +| `script.endpoint_drill.usage` | `usage: media-endpoint-drill.sh run --profile <p> --foreign-profile <p> --cluster <arn> --task-definition <arn> --repository <name> --bucket <name> --subnets <id,...> --security-group <id> \| cleanup <run dir>` (pending Luna pass; plan 3 Task 7) | |
| +| `script.endpoint_drill.progress` | `media-endpoint-drill: run directory %s`; `media-endpoint-drill: phase A: the saved endpoint policies`; `media-endpoint-drill: phase B: the endpoints opened to full access`; `media-endpoint-drill: phase C: the saved endpoint policies restored`; `media-endpoint-drill: phase A was not refused at every endpoint; the endpoints are not opened`; `media-endpoint-drill: kept %s; finish with: %s cleanup %s` (pending Luna pass; plan 3 Task 7). On stderr | |
| +| `script.endpoint_drill.cleanup` | `cleaned %s`, `NOT CLEANED %s` (an obligation: `endpoint-policies`, `repository-policy`, `bucket`, `foreign-user`, `log-group`, `input`) (pending Luna pass; plan 3 Task 7). On stdout | |
| +| `script.endpoint_drill.error` | `media-endpoint-drill: ` then one of: `--cluster is not a cluster ARN`; `no run directory`; `the foreign profile does not answer`; `the foreign profile has no account`; `the subnet is unknown`; `the engine VPC has no %s endpoint`; `the %s endpoint's policy cannot be read`; `the repository policy cannot be read`; `the task definition cannot be read`; `the codec image is not pinned by digest`; `the codec container has no awslogs group and prefix`; `the drill bucket already exists, or cannot be checked`; `the bucket was not created`; `the object was not created`; `the log group was not created`; `the user was not created`; `the user's ARN is not the expected one`; `the user's policy was not created`; `the user's key was not created`; `the bucket policy was not created`; `the repository grant cannot be written`; `the repository grant was not created`; `the GET was not presigned`; `the registry token was not minted`; `the log stream was not created`; `a minted value cannot be written as JSON`; `the %s endpoint's policy was not reset`; `the %s endpoint's policy was not restored`; `a drill task did not start`; `the drill task did not stop in time`; `the drill task's output is incomplete`; `could not restore the %s endpoint's policy`; `could not put back the repository policy`; `could not delete the repository policy`; `could not delete the bucket policy`; `could not delete the object`; `could not delete the bucket`; `could not delete a key`; `could not delete the user's policy`; `could not delete the user`; `could not delete the log group` (pending Luna pass; plan 3 Task 7). On stderr | |
diff --git a/internal/mediahandler/fakeffmpeg_test.go b/internal/mediahandler/fakeffmpeg_test.go| index 6116aab12..3dd4e485f 100644 |
| --- a/internal/mediahandler/fakeffmpeg_test.go |
| +++ b/internal/mediahandler/fakeffmpeg_test.go |
| @@ -15,7 +15,11 @@ import ( |
| // The fake ffmpeg and ffprobe: the test binary re-executed as either, |
| // with fakeEnv naming a scenario. TestMain runs the scenario instead of |
| // the tests, so the fake takes ffmpeg's own arguments, never the test |
| -// flags. Tasks 4 to 7 add their scenarios to fakeScenarios. |
| +// flags. Tasks 4 to 7 add their scenarios to fakeScenarios: Task 7's |
| +// hostile ones (fill-scratch, many-files, symlink-out, hardlink-out, |
| +// fifo-out, oversize-out, fork-setsid, ignore-term, compromised and |
| +// dref-alis) are registered by hostile_test.go, since each needs Linux; |
| +// fail is here. |
| // |
| // A test points Config.FFprobe (or FFmpeg) at fakeBinary(t) and passes |
| // the scenario through Config.extraEnv, since runChild gives every |
diff --git a/internal/mediahandler/hostile_linux.go b/internal/mediahandler/hostile_linux.go| new file mode 100644 |
| index 000000000..9d0bac040 |
| --- /dev/null |
| +++ b/internal/mediahandler/hostile_linux.go |
| @@ -0,0 +1,338 @@ |
| +//go:build linux |
| + |
| +package mediahandler |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "sync/atomic" |
| + "syscall" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// The hostile child processes and outputs of spec §9's drills (plan 3 |
| +// Task 7), shared by the tests' fake ffmpeg and by `carlos-media drill`, |
| +// so the drills in a task exercise exactly what the tests do. |
| + |
| +// Hostile children (HostileChild's kinds). |
| +const ( |
| + // HostileFillScratch writes into its directory until the file |
| + // system is full (ENOSPC), then exits 1 as ffmpeg does. |
| + HostileFillScratch = "fill-scratch" |
| + // HostileManyFiles makes manyFilesCount empty files in its |
| + // directory, then exits 1. |
| + HostileManyFiles = "many-files" |
| +) |
| + |
| +// manyFilesCount is how many files HostileManyFiles makes (spec §9: a |
| +// hundred thousand small files). |
| +const manyFilesCount = 100_000 |
| + |
| +// fillScratchMaxBytes is the largest file system HostileFillScratch |
| +// will fill: Fargate's largest ephemeral storage is 200 GiB, so a file |
| +// system bigger than this is not a task's scratch (a developer's disk, |
| +// say), and the child refuses it without writing a byte. |
| +const fillScratchMaxBytes = 256 << 30 |
| + |
| +// fillChunk is one write of HostileFillScratch. |
| +const fillChunk = 1 << 20 |
| + |
| +// Exits of HostileChild other than the hostile one's 1. |
| +const ( |
| + hostileExitRefused = 3 // the file system is too big to fill |
| + hostileExitBroken = 4 // the act could not be done as asked |
| +) |
| + |
| +// statfs is unix.Statfs; tests replace it. |
| +var statfs = unix.Statfs |
| + |
| +// HostileChild does kind's hostile act in dir, the output directory a |
| +// conversion's ffmpeg writes to, and answers the process's exit (1, as |
| +// a failing ffmpeg's): HostileFillScratch, HostileManyFiles. An |
| +// unknown kind, or a fill-scratch on a file system over |
| +// fillScratchMaxBytes, does nothing and exits non-zero. |
| +func HostileChild(kind, dir string) int { |
| + switch kind { |
| + case HostileFillScratch: |
| + return fillScratch(dir) |
| + case HostileManyFiles: |
| + return manyFiles(dir) |
| + } |
| + fmt.Fprintln(os.Stderr, "hostile child: unknown kind") |
| + return hostileExitBroken |
| +} |
| + |
| +// fillScratch writes zeros to dir/fill until the file system is full. |
| +func fillScratch(dir string) int { |
| + var st unix.Statfs_t |
| + if err := statfs(dir, &st); err != nil { |
| + fmt.Fprintln(os.Stderr, "hostile child: no file system status:", err) |
| + return hostileExitBroken |
| + } |
| + total := st.Blocks * uint64(st.Bsize) |
| + if total > fillScratchMaxBytes { |
| + fmt.Fprintf(os.Stderr, "hostile child: refusing to fill a %d-byte file system\n", total) |
| + return hostileExitRefused |
| + } |
| + f, err := os.OpenFile(filepath.Join(dir, "fill"), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "hostile child:", err) |
| + return hostileExitBroken |
| + } |
| + defer f.Close() |
| + buf := make([]byte, fillChunk) |
| + for written := uint64(0); written <= total; written += fillChunk { |
| + if _, err := f.Write(buf); err != nil { |
| + if errors.Is(err, syscall.ENOSPC) { |
| + fmt.Fprintln(os.Stderr, "Error writing trailer: No space left on device") |
| + return 1 |
| + } |
| + fmt.Fprintln(os.Stderr, "hostile child:", err) |
| + return hostileExitBroken |
| + } |
| + } |
| + // The file system took more than its size: it is not full. |
| + return hostileExitBroken |
| +} |
| + |
| +// manyFiles makes manyFilesCount empty files in dir. |
| +func manyFiles(dir string) int { |
| + for i := range manyFilesCount { |
| + f, err := os.OpenFile(filepath.Join(dir, "f"+strconv.Itoa(i)), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "hostile child:", err) |
| + return hostileExitBroken |
| + } |
| + if err := f.Close(); err != nil { |
| + return hostileExitBroken |
| + } |
| + } |
| + fmt.Fprintln(os.Stderr, "Conversion failed!") |
| + return 1 |
| +} |
| + |
| +// DrillEncode prepares the scratch and runs binary with args(<scratch>/out) |
| +// as an encode runs ffmpeg (runChild: a subreaper, the child's own |
| +// process group, every descendant killed and reaped; ffmpegOutcome's |
| +// mapping, the scratch-full check included), then checks that no child |
| +// is left (childrenDead) and empties <scratch>/out and tmp again. It |
| +// answers the job code the handler would name, "" for a clean exit. |
| +// `carlos-media drill fill-scratch|many-files` run the binary itself as |
| +// the child, on HostileChild. |
| +func DrillEncode(ctx context.Context, cfg Config, binary string, args func(outDir string) []string) string { |
| + cfg = cfg.withDefaults() |
| + cfg.FFmpeg = binary |
| + if err := prepareScratch(cfg.Scratch); err != nil { |
| + cfg.Logf("codec: scratch directory unusable: %v", err) |
| + return media.CodeEngineFailed |
| + } |
| + err := encode(ctx, cfg, "drill", args(filepath.Join(cfg.Scratch, "out"))) |
| + if derr := childrenDead(cfg); derr != nil { |
| + err = derr |
| + } |
| + if rerr := resetOutputs(cfg.Scratch); rerr != nil && err == nil { |
| + err = rerr |
| + } |
| + return codeOfErr(err) |
| +} |
| + |
| +// codeOfErr is err's job code: "" for nil, the jobError's code, or |
| +// engine_failed for anything else. |
| +func codeOfErr(err error) string { |
| + var je jobError |
| + switch { |
| + case err == nil: |
| + return "" |
| + case errors.As(err, &je): |
| + return je.code |
| + } |
| + return media.CodeEngineFailed |
| +} |
| + |
| +// Hostile outputs (makeHostileOutput's kinds), Task 6's refusals. |
| +const ( |
| + HostileSymlink = "symlink" |
| + HostileHardlink = "hardlink" |
| + HostileFIFO = "fifo" |
| + HostileDirectory = "directory" |
| + HostileEmpty = "empty" |
| + HostileOversize = "oversize" |
| +) |
| + |
| +// HostileOutputKinds are every kind of hostile output, in drill order. |
| +var HostileOutputKinds = []string{HostileSymlink, HostileHardlink, HostileFIFO, HostileDirectory, HostileEmpty, HostileOversize} |
| + |
| +// makeHostileOutput leaves kind's hostile file at dir/name: a symlink |
| +// to /etc/passwd; a regular file with a second link at |
| +// dir/../tmp/<name>.link; a FIFO; a directory; an empty file; a sparse |
| +// file one byte over bound. |
| +func makeHostileOutput(dir, name, kind string, bound int64) error { |
| + path := filepath.Join(dir, name) |
| + switch kind { |
| + case HostileSymlink: |
| + return os.Symlink("/etc/passwd", path) |
| + case HostileHardlink: |
| + if err := os.WriteFile(path, []byte("linked"), 0o600); err != nil { |
| + return err |
| + } |
| + return os.Link(path, filepath.Join(filepath.Dir(dir), "tmp", name+".link")) |
| + case HostileFIFO: |
| + return unix.Mkfifo(path, 0o600) |
| + case HostileDirectory: |
| + return os.Mkdir(path, 0o700) |
| + case HostileEmpty: |
| + return os.WriteFile(path, nil, 0o600) |
| + case HostileOversize: |
| + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + return err |
| + } |
| + return errors.Join(f.Truncate(bound+1), f.Close()) |
| + } |
| + return errors.New("unknown hostile output") |
| +} |
| + |
| +// hostileOutputMaker is makeHostileOutput; a test replaces it to show |
| +// the drill's PUT count counts. |
| +var hostileOutputMaker = makeHostileOutput |
| + |
| +// BadOutput is one round of DrillBadOutputs: the output name made |
| +// hostile, the kind, and whether collect refused it (with its reason). |
| +type BadOutput struct { |
| + Name, Kind, Reason string |
| + Refused bool |
| +} |
| + |
| +// DrillBadOutputs is `carlos-media drill bad-outputs` (spec §9: a |
| +// child that leaves a symlink, a hard link, a FIFO and an oversized |
| +// file under the output names uploads nothing). For each hostile kind |
| +// and each of the preset's output names, it empties <scratch>/out, |
| +// writes the preset's outputs as small regular files with that one |
| +// name made hostile, and delivers them as Run does (deliver: collect, |
| +// then upload in order). It answers every round and how many PUTs the |
| +// transport was asked to make, which must be 0. |
| +// |
| +// payload is media.PayloadEnv's value; empty, a synthetic payload whose |
| +// transfers all point at 127.0.0.1:1 is used (preflight F24: an |
| +// operator's run-task has no grant, and none is needed to show that |
| +// nothing is sent). |
| +func DrillBadOutputs(ctx context.Context, cfg Config, payload string) ([]BadOutput, int64, error) { |
| + cfg = cfg.withDefaults() |
| + var p media.Payload |
| + var err error |
| + if payload == "" { |
| + p, err = syntheticPayload(cfg.Now()) |
| + } else { |
| + p, err = parsePayload(payload) |
| + } |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + if err := prepareScratch(cfg.Scratch); err != nil { |
| + return nil, 0, err |
| + } |
| + var puts atomic.Int64 |
| + base := cfg.HTTP.Transport |
| + if base == nil { |
| + base = http.DefaultTransport |
| + } |
| + client := *cfg.HTTP |
| + client.Transport = countingTransport{base: base, n: &puts} |
| + cfg.HTTP = &client |
| + |
| + out := filepath.Join(cfg.Scratch, "out") |
| + names := media.OutputNames(p.Preset) |
| + bounds := outputBounds(p) |
| + var rounds []BadOutput |
| + for _, kind := range HostileOutputKinds { |
| + for _, hostile := range names { |
| + if err := resetOutputs(cfg.Scratch); err != nil { |
| + return rounds, puts.Load(), err |
| + } |
| + for _, n := range names { |
| + if n == hostile { |
| + err = hostileOutputMaker(out, n, kind, bounds[n]) |
| + } else { |
| + err = os.WriteFile(filepath.Join(out, n), []byte("regular output"), 0o600) |
| + } |
| + if err != nil { |
| + return rounds, puts.Load(), err |
| + } |
| + } |
| + _, derr := deliver(ctx, cfg, p, probeFacts{}) |
| + var refused outputRefused |
| + r := BadOutput{Name: hostile, Kind: kind} |
| + if errors.As(derr, &refused) { |
| + r.Refused, r.Reason = true, refused.Error() |
| + } |
| + rounds = append(rounds, r) |
| + } |
| + } |
| + return rounds, puts.Load(), resetOutputs(cfg.Scratch) |
| +} |
| + |
| +// resetOutputs empties <scratch>/out and <scratch>/tmp. |
| +func resetOutputs(scratch string) error { |
| + for _, d := range []string{"out", "tmp"} { |
| + if err := os.RemoveAll(filepath.Join(scratch, d)); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + return err |
| + } |
| + } |
| + return prepareScratch(scratch) |
| +} |
| + |
| +// countingTransport counts every request it is asked to make. |
| +type countingTransport struct { |
| + base http.RoundTripper |
| + n *atomic.Int64 |
| +} |
| + |
| +func (c countingTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| + c.n.Add(1) |
| + return c.base.RoundTrip(r) |
| +} |
| + |
| +// syntheticPayload is a video-720p payload whose five transfers point |
| +// at 127.0.0.1:1, where nothing listens, with the shape Validate wants. |
| +func syntheticPayload(now time.Time) (media.Payload, error) { |
| + id := make([]byte, 16) |
| + if _, err := rand.Read(id); err != nil { |
| + return media.Payload{}, err |
| + } |
| + const base = "http://127.0.0.1:1/drill/" |
| + shared := "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=DRILL%2F20000101%2Fus-east-1%2Fs3%2Faws4_request" + |
| + "&X-Amz-Expires=3600&X-Amz-Security-Token=drill" |
| + put := func(name string) media.Transfer { |
| + return media.Transfer{Name: name, Method: http.MethodPut, Query: "X-Amz-SignedHeaders=host&X-Amz-Signature=00", |
| + Header: map[string]string{"Content-Type": media.ContentType(name), "If-None-Match": "*"}} |
| + } |
| + tr := media.Transfers{ |
| + Shared: shared, |
| + Source: media.Transfer{URL: base + "source", Method: http.MethodGet, Query: "X-Amz-SignedHeaders=host%3Bif-match&X-Amz-Signature=00", |
| + Header: map[string]string{"If-Match": `"0"`}}, |
| + OutPrefix: base + "out/", |
| + Result: media.Transfer{URL: base + "result.json", Method: http.MethodPut, Query: "X-Amz-SignedHeaders=host&X-Amz-Signature=00"}, |
| + } |
| + for _, n := range media.OutputNames(media.PresetVideo720p) { |
| + tr.Outputs = append(tr.Outputs, put(n)) |
| + } |
| + p := media.Payload{ |
| + V: media.PayloadVersion, Execution: hex.EncodeToString(id), Preset: media.PresetVideo720p, |
| + Limits: media.JobLimits{SourceBytes: 1, GrantedMS: 1000, GrantedBy: grantedByClass, MaxMS: 1000, MaxHiMS: 1000, OutputBytes: 1 << 20}, |
| + Expiry: now.Add(time.Hour).Unix(), |
| + Transfers: tr, |
| + } |
| + return p, p.Validate() |
| +} |
diff --git a/internal/mediahandler/hostile_test.go b/internal/mediahandler/hostile_test.go| new file mode 100644 |
| index 000000000..557d66007 |
| --- /dev/null |
| +++ b/internal/mediahandler/hostile_test.go |
| @@ -0,0 +1,590 @@ |
| +//go:build linux |
| + |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// Plan 3 Task 7: the hostile-input corpus (testdata/corpus), the |
| +// hostile children of spec §9 and the outputs they leave, and the |
| +// fuzz targets for what the handler parses from outside. None of these |
| +// tests runs in parallel: runChild makes the test process a child |
| +// subreaper and kills every child it has, so another test's child |
| +// process alongside would be killed. |
| + |
| +// The scenarios of plan 3 Task 7 (fakeffmpeg_test.go's list; they live |
| +// here because each needs Linux): |
| +// |
| +// - fill-scratch, many-files: probe ok-av; the video encode is |
| +// HostileChild's act in the output directory (exit 1); |
| +// - symlink-out, hardlink-out, fifo-out, oversize-out: probe ok-av, |
| +// encodes as ok-video, but the poster is left as that hostile file |
| +// (makeHostileOutput), exit 0; |
| +// - fork-setsid: the probe starts a grandchild in its own session |
| +// (the block scenario, which ignores SIGTERM, SIGINT and SIGHUP), |
| +// writes its pid to fakePIDFileEnv's file, and exits 1; |
| +// - ignore-term: the probe writes its pid, ignores SIGTERM, SIGINT |
| +// and SIGHUP, and blocks until SIGKILL; |
| +// - compromised: the video encode writes the video, starts a |
| +// grandchild in its own session that keeps replacing the outputs |
| +// with links to /etc/passwd, waits for its first swap, and exits 0; |
| +// - dref-alis: answers as the real ffprobe and ffmpeg do for |
| +// testdata/corpus/dref-alis-etc-passwd.mp4 (the probe lists the |
| +// streams; decoding finds no packet, exit 183). |
| +func init() { |
| + for _, kind := range []string{HostileFillScratch, HostileManyFiles} { |
| + fakeScenarios[kind] = func(args []string) int { |
| + return fakeOK("ok-av", args, func(name string) (int, bool) { |
| + if name != "video.mp4" { |
| + return 0, false |
| + } |
| + return HostileChild(kind, filepath.Dir(args[len(args)-1])), true |
| + }) |
| + } |
| + } |
| + for scenario, kind := range map[string]string{ |
| + "symlink-out": HostileSymlink, "hardlink-out": HostileHardlink, "fifo-out": HostileFIFO, "oversize-out": HostileOversize, |
| + } { |
| + fakeScenarios[scenario] = func(args []string) int { |
| + return fakeOK("ok-av", args, func(name string) (int, bool) { |
| + if name != "poster.jpg" { |
| + return 0, false |
| + } |
| + if err := makeHostileOutput(filepath.Dir(args[len(args)-1]), name, kind, posterBound); err != nil { |
| + fmt.Fprintln(os.Stderr, "fake:", err) |
| + return 1, true |
| + } |
| + return 0, true |
| + }) |
| + } |
| + } |
| + fakeScenarios["fork-setsid"] = func([]string) int { |
| + cmd := exec.Command(os.Args[0]) |
| + cmd.Env = []string{fakeEnv + "=block"} |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| + if err := cmd.Start(); err != nil { |
| + return 1 |
| + } |
| + if err := os.WriteFile(os.Getenv(fakePIDFileEnv), []byte(strconv.Itoa(cmd.Process.Pid)), 0o600); err != nil { |
| + return 1 |
| + } |
| + fmt.Fprintln(os.Stderr, "fake: Invalid data found when processing input") |
| + return 1 |
| + } |
| + fakeScenarios["ignore-term"] = func([]string) int { |
| + signal.Ignore(hostileSignals...) |
| + if err := os.WriteFile(os.Getenv(fakePIDFileEnv), []byte(strconv.Itoa(os.Getpid())), 0o600); err != nil { |
| + return 1 |
| + } |
| + return blockForever() |
| + } |
| + fakeScenarios["compromised"] = func(args []string) int { |
| + return fakeOK("ok-av", args, func(name string) (int, bool) { |
| + if name != "poster.jpg" { |
| + return 0, false |
| + } |
| + out := filepath.Dir(args[len(args)-1]) |
| + cmd := exec.Command(os.Args[0]) |
| + cmd.Env = []string{fakeEnv + "=swap-loop", "MEDIA_FAKE_OUT=" + out, fakePIDFileEnv + "=" + os.Getenv(fakePIDFileEnv)} |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| + if err := cmd.Start(); err != nil { |
| + return 1, true |
| + } |
| + // Exit only once the grandchild has made its first swap. |
| + for range 2000 { |
| + if fi, err := os.Lstat(filepath.Join(out, "poster.jpg")); err == nil && fi.Mode()&os.ModeSymlink != 0 { |
| + return 0, true |
| + } |
| + <-time.After(5 * time.Millisecond) |
| + } |
| + return 1, true |
| + }) |
| + } |
| + // swap-loop is compromised's grandchild: it writes its pid, then |
| + // keeps replacing every output with a link to /etc/passwd. |
| + fakeScenarios["swap-loop"] = func([]string) int { |
| + signal.Ignore(hostileSignals...) |
| + if err := os.WriteFile(os.Getenv(fakePIDFileEnv), []byte(strconv.Itoa(os.Getpid())), 0o600); err != nil { |
| + return 1 |
| + } |
| + out := os.Getenv("MEDIA_FAKE_OUT") |
| + for { |
| + for _, n := range videoNames { |
| + tmp := filepath.Join(out, "."+n+".swap") |
| + _ = os.Symlink("/etc/passwd", tmp) |
| + _ = os.Rename(tmp, filepath.Join(out, n)) |
| + } |
| + <-time.After(time.Millisecond) |
| + } |
| + } |
| + fakeScenarios["dref-alis"] = func(args []string) int { |
| + if slices.Contains(args, "-of") { |
| + return fakeProbe("dref-alis", args) |
| + } |
| + fmt.Fprintln(os.Stderr, "Cannot determine format of input 0:0 after EOF") |
| + return 183 |
| + } |
| +} |
| + |
| +// corpusCase is one corpus file's expected end under a preset. |
| +type corpusCase struct { |
| + file, scenario string |
| + want map[string]string // preset → code |
| + probes bool // ffprobe runs (sniff accepts it) |
| +} |
| + |
| +// corpusCases are testdata/corpus, each with the fake that answers as |
| +// the real ffprobe and ffmpeg do for it (provenance.txt), and the code |
| +// it must end in. |
| +var corpusCases = []corpusCase{ |
| + {"playlist-metadata.m3u8", "fail", bothPresets(media.CodeUnsupportedContainer), false}, |
| + {"playlist-local-file.m3u8", "fail", bothPresets(media.CodeUnsupportedContainer), false}, |
| + {"concat-list.ffconcat", "fail", bothPresets(media.CodeUnsupportedContainer), false}, |
| + {"empty.bin", "fail", bothPresets(media.CodeUnsupportedContainer), false}, |
| + {"random-4k.bin", "fail", bothPresets(media.CodeUnsupportedContainer), false}, |
| + {"page.html", "fail", bothPresets(media.CodeUnsupportedContainer), false}, |
| + {"archive.zip", "fail", bothPresets(media.CodeUnsupportedContainer), false}, |
| + {"truncated.mp4", "fail", bothPresets(media.CodeUnreadable), true}, |
| + {"dref-alis-etc-passwd.mp4", "dref-alis", bothPresets(media.CodeUnreadable), true}, |
| +} |
| + |
| +func bothPresets(code string) map[string]string { |
| + return map[string]string{media.PresetVideo720p: code, media.PresetAudioAAC: code} |
| +} |
| + |
| +// readCorpus reads testdata/corpus/name. |
| +func readCorpus(t *testing.T, name string) []byte { |
| + t.Helper() |
| + b, err := os.ReadFile(filepath.Join("testdata", "corpus", name)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| +} |
| + |
| +// corpusSetup is runJobSetup with data as the source. |
| +func corpusSetup(t *testing.T, preset, scenario string, data []byte) (*harness, media.Payload, Config, string) { |
| + t.Helper() |
| + h, _, cfg, record := runJobSetup(t, preset, scenario) |
| + p := h.s.payload(t, preset, data, 8*mib) |
| + p.Limits.GrantedMS = 9000 |
| + return h, p, cfg, record |
| +} |
| + |
| +// TestCorpusEndsInNamedErrors: every corpus file, under each preset, |
| +// with the fake answering as the real binaries do for it, ends in its |
| +// named code from media.HandlerCodes: Run exits 1 (never 0), the result |
| +// names the code, and the store saw the source's GET and the result's |
| +// PUT and nothing else. The two probe fixtures of a lying duration and |
| +// a decompression bomb end the same way. |
| +func TestCorpusEndsInNamedErrors(t *testing.T) { |
| + needChildren(t) |
| + type run struct { |
| + name, preset, scenario, want string |
| + data []byte |
| + probes bool |
| + } |
| + var runs []run |
| + for _, c := range corpusCases { |
| + for preset, want := range c.want { |
| + runs = append(runs, run{c.file, preset, c.scenario, want, readCorpus(t, c.file), c.probes}) |
| + } |
| + } |
| + src := readFixture(t, "video.mp4") |
| + runs = append(runs, |
| + run{"lying-10h", media.PresetVideo720p, "probe-lying-10h", media.CodeSourceTooLong, src, true}, |
| + run{"bomb-30000", media.PresetVideo720p, "probe-bomb-30000", media.CodeSourceDimensions, src, true}) |
| + for _, r := range runs { |
| + t.Run(r.name+"/"+r.preset, func(t *testing.T) { |
| + if !media.HandlerCodes[r.want] { |
| + t.Fatalf("%s is not a handler code", r.want) |
| + } |
| + h, p, cfg, record := corpusSetup(t, r.preset, r.scenario, r.data) |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1; logs %q", code, h.Logs()) |
| + } |
| + wantOnlyResult(t, h, r.preset, r.want) |
| + if ran := fakeRuns(t, record); r.probes != (len(ran) > 0) { |
| + t.Fatalf("fake runs %q; ffprobe should run: %t", passKinds(ran), r.probes) |
| + } |
| + h.s.CheckClean(t) |
| + }) |
| + } |
| +} |
| + |
| +// TestRealCorpusEndsInNamedErrors is TestCorpusEndsInNamedErrors on |
| +// the real ffprobe and ffmpeg (skipped without them, realConfig). |
| +func TestRealCorpusEndsInNamedErrors(t *testing.T) { |
| + real := realConfig(t) |
| + for _, c := range corpusCases { |
| + for preset, want := range c.want { |
| + t.Run(c.file+"/"+preset, func(t *testing.T) { |
| + h := newHarness(t) |
| + p := h.s.payload(t, preset, readCorpus(t, c.file), 8*mib) |
| + cfg := h.cfg |
| + cfg.Scratch = t.TempDir() |
| + cfg.FFmpeg, cfg.FFprobe, cfg.extraEnv = real.FFmpeg, real.FFprobe, real.extraEnv |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1; logs %q", code, h.Logs()) |
| + } |
| + wantOnlyResult(t, h, preset, want) |
| + t.Logf("logs %q", h.Logs()) |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// TestPlaylistStyleFileMakesNoRequest: the playlist naming |
| +// http://169.254.169.254/ is unsupported_container under both presets: |
| +// ffmpeg and ffprobe never start, and the store saw one GET (the |
| +// source's) and the result's PUT. |
| +func TestPlaylistStyleFileMakesNoRequest(t *testing.T) { |
| + needChildren(t) |
| + data := readCorpus(t, "playlist-metadata.m3u8") |
| + if !bytes.Contains(data, []byte("http://169.254.169.254/")) { |
| + t.Fatal("the corpus playlist does not name the metadata address") |
| + } |
| + for _, preset := range []string{media.PresetVideo720p, media.PresetAudioAAC} { |
| + h, p, cfg, record := corpusSetup(t, preset, "fail", data) |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("%s: Run = %d, want 1", preset, code) |
| + } |
| + wantOnlyResult(t, h, preset, media.CodeUnsupportedContainer) |
| + gets := 0 |
| + for _, r := range h.s.Requests() { |
| + if r.Method == http.MethodGet { |
| + gets++ |
| + } |
| + } |
| + if gets != 1 { |
| + t.Fatalf("%s: %d GETs, want 1", preset, gets) |
| + } |
| + if _, err := os.Stat(record); !os.IsNotExist(err) { |
| + t.Fatalf("%s: ffmpeg or ffprobe started: %q", preset, passKinds(fakeRuns(t, record))) |
| + } |
| + } |
| +} |
| + |
| +// nsEnv tells a re-executed test binary it runs in its own user and |
| +// mount namespace, where it may mount a small tmpfs. |
| +const nsEnv = "MEDIA_TEST_IN_NAMESPACE" |
| + |
| +// inNamespace reruns the named subtest of TestHostileChildrenFailOnlyTheirJob |
| +// in a new user and mount namespace (so it can mount a tmpfs without |
| +// root), and reports whether it passed there; it skips t when such |
| +// namespaces are not allowed here, or the subtest skipped there. |
| +func inNamespace(t *testing.T, subtest string) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestHostileChildrenFailOnlyTheirJob$/^"+subtest+"$", "-test.count=1", "-test.v") |
| + cmd.Env = append(os.Environ(), nsEnv+"=1") |
| + cmd.SysProcAttr = &syscall.SysProcAttr{ |
| + Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNS, |
| + UidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getuid(), Size: 1}}, |
| + GidMappings: []syscall.SysProcIDMap{{ContainerID: 0, HostID: os.Getgid(), Size: 1}}, |
| + GidMappingsEnableSetgroups: false, |
| + } |
| + var out bytes.Buffer |
| + cmd.Stdout, cmd.Stderr = &out, &out |
| + if err := cmd.Start(); err != nil { |
| + t.Skipf("no user and mount namespace here: %v", err) |
| + } |
| + err := cmd.Wait() |
| + switch { |
| + case strings.Contains(out.String(), "--- SKIP: TestHostileChildrenFailOnlyTheirJob/"+subtest): |
| + t.Skipf("skipped in the namespace:\n%s", out.String()) |
| + case err != nil || !strings.Contains(out.String(), "--- PASS: TestHostileChildrenFailOnlyTheirJob/"+subtest): |
| + t.Fatalf("in the namespace: %v\n%s", err, out.String()) |
| + } |
| + t.Logf("in the namespace:\n%s", out.String()) |
| +} |
| + |
| +// tmpfsMagic is statfs's f_type for tmpfs. |
| +const tmpfsMagic = 0x01021994 |
| + |
| +// smallTmpfs mounts a 48 MiB tmpfs on a new directory and answers it; |
| +// only inside inNamespace. 48 MiB is over scratchFullBytes, so the |
| +// scratch is not full until the child fills it. |
| +func smallTmpfs(t *testing.T) string { |
| + t.Helper() |
| + dir := t.TempDir() |
| + if err := unix.Mount("", "/", "", unix.MS_REC|unix.MS_PRIVATE, ""); err != nil { |
| + t.Skipf("mounts cannot be made private: %v", err) |
| + } |
| + if err := unix.Mount("tmpfs", dir, "tmpfs", 0, "size=48m,mode=0700"); err != nil { |
| + t.Skipf("no tmpfs: %v", err) |
| + } |
| + t.Cleanup(func() { _ = unix.Unmount(dir, unix.MNT_DETACH) }) |
| + var st unix.Statfs_t |
| + if err := unix.Statfs(dir, &st); err != nil || st.Type != tmpfsMagic || st.Blocks*uint64(st.Bsize) > 64<<20 { |
| + t.Fatalf("the scratch is not the small tmpfs: %v, type %#x, %d bytes", err, st.Type, st.Blocks*uint64(st.Bsize)) |
| + } |
| + return dir |
| +} |
| + |
| +// childrenOf are the processes whose parent is pid. |
| +func childrenOf(pid int) []int { |
| + var out []int |
| + for _, p := range procPIDsForTest() { |
| + if b, err := os.ReadFile("/proc/" + strconv.Itoa(p) + "/stat"); err == nil && parentFromStat(b) == pid { |
| + out = append(out, p) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func procPIDsForTest() []int { |
| + ents, _ := os.ReadDir("/proc") |
| + var out []int |
| + for _, e := range ents { |
| + if pid, err := strconv.Atoi(e.Name()); err == nil { |
| + out = append(out, pid) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// TestHostileChildrenFailOnlyTheirJob: a child that fills the scratch |
| +// (on a small tmpfs: Linux, in a user namespace, skipped where that is |
| +// not allowed), makes a hundred thousand files, leaves a grandchild in |
| +// its own session, or ignores SIGTERM, fails its job with a named |
| +// error within 30 s: Run exits 1, the result names the code, nothing |
| +// is uploaded, no process it started is left, and the next job on the |
| +// same handler converts. compromised (a grandchild that keeps swapping |
| +// the outputs for links to /etc/passwd) is the same, and the child |
| +// never saw the payload or a credential in its environment. |
| +func TestHostileChildrenFailOnlyTheirJob(t *testing.T) { |
| + needChildren(t) |
| + t.Setenv(media.PayloadEnv, `{"v":1,"x":"in the handler's environment only"}`) |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "handler-environment-secret") |
| + for _, c := range []struct { |
| + scenario, want string |
| + pidFile bool |
| + probeTimeout time.Duration |
| + }{ |
| + {HostileFillScratch, media.CodeEngineFailed, false, 0}, |
| + {HostileManyFiles, media.CodeUnreadable, false, 0}, |
| + {"fork-setsid", media.CodeUnreadable, true, 0}, |
| + {"ignore-term", media.CodeUnreadable, true, 500 * time.Millisecond}, |
| + {"compromised", media.CodeEngineFailed, true, 0}, |
| + } { |
| + t.Run(c.scenario, func(t *testing.T) { |
| + if c.scenario == HostileFillScratch && os.Getenv(nsEnv) == "" { |
| + inNamespace(t, c.scenario) |
| + return |
| + } |
| + h, p, cfg, record := runJobSetup(t, media.PresetVideo720p, c.scenario) |
| + if c.scenario == HostileFillScratch { |
| + cfg.Scratch = smallTmpfs(t) |
| + } |
| + cfg.probeTimeout = c.probeTimeout |
| + pidFile := filepath.Join(t.TempDir(), "pid") |
| + cfg.extraEnv = append(append([]string(nil), cfg.extraEnv...), fakePIDFileEnv+"="+pidFile) |
| + start := time.Now() |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1; logs %q", code, h.Logs()) |
| + } |
| + if took := time.Since(start); took > 30*time.Second { |
| + t.Fatalf("the job took %s", took) |
| + } |
| + wantOnlyResult(t, h, media.PresetVideo720p, c.want) |
| + if c.pidFile { |
| + b, err := os.ReadFile(pidFile) |
| + if err != nil { |
| + t.Fatalf("the fake left no pid: %v", err) |
| + } |
| + pid, _ := strconv.Atoi(string(b)) |
| + wantGone(t, pid) |
| + } |
| + if kids := childrenOf(os.Getpid()); len(kids) != 0 { |
| + t.Fatalf("processes left: %v", kids) |
| + } |
| + for _, r := range fakeRuns(t, record) { |
| + for _, kv := range r.Env { |
| + if strings.HasPrefix(kv, media.PayloadEnv+"=") || strings.HasPrefix(kv, "AWS_") { |
| + t.Fatalf("a child saw %q", kv) |
| + } |
| + } |
| + } |
| + for _, name := range videoNames { |
| + if held, ok := h.s.Object(outPrefix + name); ok { |
| + t.Fatalf("%s was uploaded (%d bytes)", name, len(held)) |
| + } |
| + } |
| + switch c.scenario { |
| + case HostileFillScratch: |
| + if !scratchFull(cfg.Scratch) || !slices.Contains(h.Logs(), "codec: ffmpeg (video) failed with the scratch disk full") { |
| + t.Fatalf("the scratch was not filled; logs %q", h.Logs()) |
| + } |
| + case HostileManyFiles: |
| + if ents, err := os.ReadDir(filepath.Join(cfg.Scratch, "out")); err != nil || len(ents) < manyFilesCount { |
| + t.Fatalf("the child made %d files, %v", len(ents), err) |
| + } |
| + } |
| + // The next job on this handler converts. |
| + h2, p2, cfg2, _ := runJobSetup(t, media.PresetVideo720p, "ok-video") |
| + if code := runFor(t, cfg2, p2); code != media.ExitDone { |
| + t.Fatalf("the next job: Run = %d; logs %q", code, h2.Logs()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestBadOutputsUploadNothing: a child that leaves the poster as a |
| +// symlink to /etc/passwd, a hard link, a FIFO or a file one byte over |
| +// its bound: Run exits 1, engine_failed, and none of the three outputs |
| +// is PUT. Then the bad-outputs drill (DrillBadOutputs), with the |
| +// harness's payload and with none (its synthetic one): every hostile |
| +// kind under every output name is refused, and no PUT is attempted. |
| +func TestBadOutputsUploadNothing(t *testing.T) { |
| + needChildren(t) |
| + for _, scenario := range []string{"symlink-out", "hardlink-out", "fifo-out", "oversize-out"} { |
| + t.Run(scenario, func(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, scenario) |
| + if code := runFor(t, cfg, p); code != media.ExitFailed { |
| + t.Fatalf("Run = %d, want 1; logs %q", code, h.Logs()) |
| + } |
| + wantOnlyResult(t, h, media.PresetVideo720p, media.CodeEngineFailed) |
| + }) |
| + } |
| + for _, withPayload := range []bool{true, false} { |
| + t.Run(fmt.Sprintf("drill payload %t", withPayload), func(t *testing.T) { |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video") |
| + payload := "" |
| + if withPayload { |
| + payload = marshal(t, p) |
| + } |
| + rounds, puts, err := DrillBadOutputs(context.Background(), cfg, payload) |
| + if err != nil || puts != 0 || len(rounds) != len(HostileOutputKinds)*len(videoNames) { |
| + t.Fatalf("DrillBadOutputs: %d rounds, %d PUTs, %v", len(rounds), puts, err) |
| + } |
| + for _, r := range rounds { |
| + if !r.Refused || !strings.Contains(r.Reason, "output "+r.Name+" refused: ") { |
| + t.Errorf("%s as %s: %+v", r.Name, r.Kind, r) |
| + } |
| + } |
| + if len(h.s.Requests()) != 0 { |
| + t.Fatalf("the store saw %q", requestLines(h.s.Requests())) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestDrillBadOutputsCountsPUTs: the drill's PUT count is real: with |
| +// every hostile file made a regular one (collect then accepts the |
| +// outputs), the drill counts as many PUTs as the store saw, at least |
| +// the first round's three, and reports those rounds not refused. |
| +func TestDrillBadOutputsCountsPUTs(t *testing.T) { |
| + needChildren(t) |
| + h, p, cfg, _ := runJobSetup(t, media.PresetVideo720p, "ok-video") |
| + saved := hostileOutputMaker |
| + hostileOutputMaker = func(dir, name, _ string, _ int64) error { |
| + return os.WriteFile(filepath.Join(dir, name), []byte("regular output"), 0o600) |
| + } |
| + defer func() { hostileOutputMaker = saved }() |
| + rounds, n, err := DrillBadOutputs(context.Background(), cfg, marshal(t, p)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if seen := int64(len(puts(h.s.Requests()))); n < 3 || n != seen { |
| + t.Fatalf("%d PUTs counted, the store saw %d", n, seen) |
| + } |
| + if len(rounds) == 0 || rounds[0].Refused { |
| + t.Fatalf("rounds %+v", rounds) |
| + } |
| +} |
| + |
| +// TestFillScratchRefusesABigFileSystem: the fill-scratch child does |
| +// nothing on a file system over fillScratchMaxBytes (a developer's |
| +// disk, not a task's scratch): no file, exit hostileExitRefused. |
| +func TestFillScratchRefusesABigFileSystem(t *testing.T) { |
| + saved := statfs |
| + defer func() { statfs = saved }() |
| + statfs = func(path string, st *unix.Statfs_t) error { |
| + *st = unix.Statfs_t{Bsize: 4096, Blocks: (fillScratchMaxBytes / 4096) + 1, Bavail: 1 << 40} |
| + return nil |
| + } |
| + // Read-only, so that without the guard the child fails at its open |
| + // (exit hostileExitBroken) rather than write to this disk. |
| + dir := t.TempDir() |
| + if err := os.Chmod(dir, 0o500); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer os.Chmod(dir, 0o700) |
| + if code := HostileChild(HostileFillScratch, dir); code != hostileExitRefused { |
| + t.Fatalf("HostileChild = %d, want %d", code, hostileExitRefused) |
| + } |
| + if ents, _ := os.ReadDir(dir); len(ents) != 0 { |
| + t.Fatalf("it wrote %v", ents) |
| + } |
| +} |
| + |
| +// FuzzParsePayload: whatever the payload variable holds, parsePayload |
| +// never panics, and a payload it accepts validates and has a positive |
| +// cap and expiry; its errors never quote the input. |
| +func FuzzParsePayload(f *testing.F) { |
| + f.Add(`{"v":1}`) |
| + f.Add(`{"v":2}`) |
| + f.Add(``) |
| + f.Add(string(readCorpusF(f, "page.html"))) |
| + f.Add(`{"v":1,"x":"0123456789abcdef0123456789abcdef","p":"video-720p","l":{"b":1,"g":1,"gb":"class","d":1,"dh":1,"o":1},"e":1,` + |
| + `"tr":{"s":"a","src":{"u":"http://x/s","m":"GET","q":"q"},"op":"http://x/o/","out":[{"n":"video.mp4","m":"PUT","q":""},` + |
| + `{"n":"video.m3u8","m":"PUT","q":""},{"n":"poster.jpg","m":"PUT","q":""}],"res":{"u":"http://x/r","m":"PUT","q":""}}}`) |
| + f.Fuzz(func(t *testing.T, s string) { |
| + p, err := parsePayload(s) |
| + if err != nil { |
| + if len(s) > 8 && strings.Contains(err.Error(), s) { |
| + t.Fatalf("the error quotes the input: %v", err) |
| + } |
| + return |
| + } |
| + if p.Validate() != nil || p.Limits.SourceBytes <= 0 || p.Expiry <= 0 { |
| + t.Fatalf("accepted %+v", p) |
| + } |
| + }) |
| +} |
| + |
| +// FuzzParseMeter: whatever an info-level ffmpeg run prints (the |
| +// source's tags among it), parseMeter and parseLRA never panic and |
| +// never answer NaN. |
| +func FuzzParseMeter(f *testing.F) { |
| + f.Add([]byte(summary("-16.0", "-1.6"))) |
| + f.Add([]byte("\n[Parsed_ebur128_0 @ 0x1] Summary:\n LRA: 5.0 LU\n I: nan LUFS\n")) |
| + f.Add(readCorpusF(f, "page.html")) |
| + f.Fuzz(func(t *testing.T, b []byte) { |
| + i, tp, _, err := parseMeter(b) |
| + if err == nil && (i != i || tp != tp) { |
| + t.Fatalf("NaN: %v %v", i, tp) |
| + } |
| + if lra, err := parseLRA(b); err == nil && lra != lra { |
| + t.Fatal("NaN LRA") |
| + } |
| + }) |
| +} |
| + |
| +func readCorpusF(f *testing.F, name string) []byte { |
| + b, err := os.ReadFile(filepath.Join("testdata", "corpus", name)) |
| + if err != nil { |
| + f.Fatal(err) |
| + } |
| + return b |
| +} |
diff --git a/internal/mediahandler/probe_test.go b/internal/mediahandler/probe_test.go| index bcd9a5f3e..6b20eb4d9 100644 |
| --- a/internal/mediahandler/probe_test.go |
| +++ b/internal/mediahandler/probe_test.go |
| @@ -55,6 +55,10 @@ func TestParseProbeFixtures(t *testing.T) { |
| // Hand-written for Run's ok-video and ok-audio (plan 3 Task 6). |
| "ok-av": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 160, Height: 90, SARNum: 1, SARDen: 1, FPS: 30, VideoCodec: "h264", AudioCodec: "aac", Channels: 2, DurationMS: 9000}}, |
| "ok-audio": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 2, DurationMS: 9000}}, |
| + // The real ffprobe's answer for the corpus's alias-dref MP4 |
| + // (plan 3 Task 7): both tracks listed, though their data is |
| + // skipped with -enable_drefs 0. |
| + "dref-alis": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 160, Height: 90, SARNum: 1, SARDen: 1, FPS: 10, VideoCodec: "h264", AudioCodec: "aac", Channels: 1, DurationMS: 2000}}, |
| } |
| entries, err := probeFixtures.ReadDir("testdata/probe") |
| if err != nil { |
diff --git a/internal/mediahandler/selftest.go b/internal/mediahandler/selftest.go| new file mode 100644 |
| index 000000000..9c5092cec |
| --- /dev/null |
| +++ b/internal/mediahandler/selftest.go |
| @@ -0,0 +1,652 @@ |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/md5" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "math" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// `carlos-media selftest <video|audio>` (plan 3 Task 7, preflight F25): |
| +// the image's own ffmpeg makes each case's source from lavfi's test |
| +// patterns, an in-process store on 127.0.0.1 serves it the way S3 |
| +// serves a presigned GET, Run converts it as a real job, and the |
| +// outputs it stored are checked. R2 runs it once per class, before any |
| +// tenant's file is converted. |
| + |
| +// The two selftests: each preset's cases, run on its own classes |
| +// (audio-short has 1 vCPU and does not run the 4K case). |
| +const ( |
| + SelftestVideo = "video" |
| + SelftestAudio = "audio" |
| +) |
| + |
| +// selftestCase is one source and what to check of its conversion. |
| +type selftestCase struct { |
| + name, preset string |
| + // steps are ffmpeg's arguments after -hide_banner -nostdin |
| + // -loglevel error, one run each; "OUT" is the source's path, "TMP" |
| + // a scratch file, "COVER" a JPEG made by an earlier step. |
| + steps [][]string |
| + durationMS int64 |
| + // voice checks the output's loudness against the source's; silent |
| + // requires every peak 0; secrets must appear in no log line and no |
| + // stored object (preflight F19). |
| + voice, silent bool |
| + secrets []string |
| +} |
| + |
| +// lavfiAV is a 1080p-style testsrc2 picture of size for seconds with a |
| +// 440 Hz stereo tone. |
| +func lavfiAV(size, seconds string) []string { |
| + return []string{"-f", "lavfi", "-i", "testsrc2=size=" + size + ":rate=30:duration=" + seconds, |
| + "-f", "lavfi", "-i", "sine=frequency=440:duration=" + seconds + ":sample_rate=48000", "-ac", "2", |
| + "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k"} |
| +} |
| + |
| +// selftestCases are each selftest's cases, in order. |
| +var selftestCases = map[string][]selftestCase{ |
| + SelftestVideo: { |
| + {name: "video-1080p", preset: media.PresetVideo720p, durationMS: 10000, |
| + steps: [][]string{append(lavfiAV("1920x1080", "10"), "-f", "mp4", "OUT")}}, |
| + {name: "video-portrait-rotated", preset: media.PresetVideo720p, durationMS: 10000, |
| + steps: [][]string{ |
| + append(lavfiAV("1080x1920", "10"), "-f", "mp4", "TMP"), |
| + {"-display_rotation:v:0", "90", "-i", "TMP", "-c", "copy", "-f", "mp4", "OUT"}, |
| + }}, |
| + {name: "video-pq-4k", preset: media.PresetVideo720p, durationMS: 5000, |
| + steps: [][]string{{"-f", "lavfi", "-i", "testsrc2=size=3840x2160:rate=30:duration=5", |
| + "-c:v", "libx265", "-preset", "ultrafast", |
| + "-x265-params", "log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc", |
| + "-pix_fmt", "yuv420p10le", "-color_primaries", "bt2020", "-color_trc", "smpte2084", "-colorspace", "bt2020nc", |
| + "-tag:v", "hvc1", "-f", "mp4", "OUT"}}}, |
| + {name: "video-location-tag", preset: media.PresetVideo720p, durationMS: 3000, |
| + secrets: []string{"+48.8584", "002.2945", "selftest-title-7c1", "selftest-comment-7c1"}, |
| + steps: [][]string{append(lavfiAV("640x360", "3"), |
| + "-metadata", "location=+48.8584+002.2945/", "-metadata", "title=selftest-title-7c1", |
| + "-metadata", "comment=selftest-comment-7c1", "-f", "mov", "OUT")}}, |
| + }, |
| + SelftestAudio: { |
| + // A voice with a quiet stretch (a loudness range near 15 LU), |
| + // as Chrome's MediaRecorder writes it: Opus in WebM with no |
| + // duration or cues (-live 1). |
| + {name: "audio-voice-webm-live", preset: media.PresetAudioAAC, durationMS: 10000, voice: true, |
| + steps: [][]string{{"-f", "lavfi", "-i", |
| + "sine=frequency=220:duration=10:sample_rate=48000,volume=volume='if(between(t,3.5,7),0.08,0.9)':eval=frame", |
| + "-ac", "1", "-c:a", "libopus", "-b:a", "48k", "-live", "1", "-f", "webm", "OUT"}}}, |
| + {name: "audio-silent-wav", preset: media.PresetAudioAAC, durationMS: 5000, silent: true, |
| + steps: [][]string{{"-f", "lavfi", "-i", "anullsrc=channel_layout=mono:sample_rate=48000", "-t", "5", |
| + "-c:a", "pcm_s16le", "-f", "wav", "OUT"}}}, |
| + {name: "audio-mp3-cover-art", preset: media.PresetAudioAAC, durationMS: 5000, |
| + steps: [][]string{ |
| + {"-f", "lavfi", "-i", "testsrc2=size=64x64:rate=1", "-frames:v", "1", "-f", "image2", "COVER"}, |
| + {"-f", "lavfi", "-i", "sine=frequency=440:duration=5:sample_rate=44100", "-i", "COVER", |
| + "-map", "0:a", "-map", "1:v", "-c:a", "libmp3lame", "-b:a", "128k", "-c:v", "copy", |
| + "-disposition:v", "attached_pic", "-id3v2_version", "3", "-f", "mp3", "OUT"}, |
| + }}, |
| + }, |
| +} |
| + |
| +// selftestDurationSlackMS is how far the converted duration may be |
| +// from the source's: a frame or an AAC frame and the encoder's |
| +// priming. |
| +const selftestDurationSlackMS = 250 |
| + |
| +// Selftest runs kind's cases (SelftestVideo, SelftestAudio) in a |
| +// directory of cfg's scratch, printing "PASS <case>" or "FAIL <case>: |
| +// <reason>" for each to w. Run's own log lines go to cfg.Logf. It |
| +// answers an error when any case failed (or kind is unknown). Reasons |
| +// are fixed words and numbers: no URL, header or credential, and |
| +// nothing of a source's metadata. |
| +func Selftest(ctx context.Context, cfg Config, kind string, w io.Writer) error { |
| + cases, ok := selftestCases[kind] |
| + if !ok { |
| + return errors.New("selftest: unknown kind") |
| + } |
| + cfg = cfg.withDefaults() |
| + dir, err := os.MkdirTemp(cfg.Scratch, "selftest-") |
| + if err != nil { |
| + // engine.selftest.no_scratch (pending Luna pass). |
| + fmt.Fprintf(w, "FAIL selftest: no directory in the scratch: %s\n", sysReason(err)) |
| + return err |
| + } |
| + defer os.RemoveAll(dir) |
| + store, err := newSelftestStore() |
| + if err != nil { |
| + fmt.Fprintf(w, "FAIL selftest: no local store: %s\n", sysReason(err)) |
| + return err |
| + } |
| + defer store.Close() |
| + failed := 0 |
| + for _, c := range cases { |
| + caseDir := filepath.Join(dir, c.name) |
| + err := runSelftestCase(ctx, cfg, store, caseDir, c) |
| + _ = os.RemoveAll(caseDir) |
| + if err != nil { |
| + failed++ |
| + // engine.selftest.fail (pending Luna pass). |
| + fmt.Fprintf(w, "FAIL %s: %v\n", c.name, err) |
| + continue |
| + } |
| + // engine.selftest.pass (pending Luna pass). |
| + fmt.Fprintf(w, "PASS %s\n", c.name) |
| + } |
| + if failed > 0 { |
| + return fmt.Errorf("selftest: %d of %d cases failed", failed, len(cases)) |
| + } |
| + return nil |
| +} |
| + |
| +// runSelftestCase makes c's source, converts it with Run and checks |
| +// what was stored. Its errors are the case's FAIL reason. |
| +func runSelftestCase(ctx context.Context, cfg Config, store *selftestStore, dir string, c selftestCase) error { |
| + probeCfg := cfg |
| + probeCfg.Scratch = filepath.Join(dir, "probe") |
| + runCfg := cfg |
| + runCfg.Scratch = filepath.Join(dir, "run") |
| + for _, d := range []string{dir, probeCfg.Scratch, runCfg.Scratch} { |
| + if err := os.Mkdir(d, 0o700); err != nil { |
| + return fmt.Errorf("no case directory: %s", sysReason(err)) |
| + } |
| + } |
| + if err := prepareScratch(probeCfg.Scratch); err != nil { |
| + return fmt.Errorf("no case directory: %s", sysReason(err)) |
| + } |
| + if err := makeSelftestSource(ctx, probeCfg, c); err != nil { |
| + return err |
| + } |
| + data, err := os.ReadFile(sourcePath(probeCfg)) |
| + if err != nil { |
| + return fmt.Errorf("the source cannot be read: %s", sysReason(err)) |
| + } |
| + head, _ := readHead(sourcePath(probeCfg)) |
| + demuxer, err := sniff(head, c.preset) |
| + if err != nil { |
| + return fmt.Errorf("the source does not sniff: %v", err) |
| + } |
| + src, err := probe(ctx, probeCfg, demuxer, c.preset) |
| + if err != nil { |
| + return fmt.Errorf("the source does not probe: %v", err) |
| + } |
| + |
| + var mu sync.Mutex |
| + var logs []string |
| + runCfg.Logf = func(format string, args ...any) { |
| + line := fmt.Sprintf(format, args...) |
| + mu.Lock() |
| + logs = append(logs, line) |
| + mu.Unlock() |
| + cfg.Logf("%s: %s", c.name, line) |
| + } |
| + exec, p, err := store.job(c.preset, data, cfg.Now()) |
| + if err != nil { |
| + return fmt.Errorf("no payload: %v", err) |
| + } |
| + payload, err := json.Marshal(p) |
| + if err != nil { |
| + return fmt.Errorf("no payload: %v", err) |
| + } |
| + if code := Run(ctx, runCfg, string(payload)); code != media.ExitDone { |
| + return fmt.Errorf("the conversion exited %d", code) |
| + } |
| + if bad := store.problems(); len(bad) > 0 { |
| + return fmt.Errorf("the handler broke the presigned contract: %s", bad[0]) |
| + } |
| + r, err := media.ParseResult(store.object(exec, "result"), exec, c.preset) |
| + if err != nil || r.Error != "" || r.Source == nil { |
| + return errors.New("the result is not a success result") |
| + } |
| + if d := r.Source.DurationMS - c.durationMS; d < -selftestDurationSlackMS || d > selftestDurationSlackMS { |
| + return fmt.Errorf("converted %d ms of a %d ms source", r.Source.DurationMS, c.durationMS) |
| + } |
| + check := filepath.Join(dir, "check") |
| + if err := os.Mkdir(check, 0o700); err != nil { |
| + return fmt.Errorf("no case directory: %s", sysReason(err)) |
| + } |
| + if err := checkSelftestOutputs(store, exec, r, check); err != nil { |
| + return err |
| + } |
| + switch c.preset { |
| + case media.PresetVideo720p: |
| + err = checkSelftestVideo(ctx, cfg, store, exec, r, src, check) |
| + case media.PresetAudioAAC: |
| + err = checkSelftestAudio(ctx, cfg, store, exec, c, check) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return checkSelftestSecrets(c, logs, store, exec) |
| +} |
| + |
| +// makeSelftestSource runs c's steps with the image's ffmpeg, as the |
| +// handler runs it (runChild), leaving the source at <scratch>/in/source. |
| +func makeSelftestSource(ctx context.Context, cfg Config, c selftestCase) error { |
| + gen := filepath.Join(cfg.Scratch, "tmp") |
| + repl := strings.NewReplacer("OUT", sourcePath(cfg), "TMP", filepath.Join(gen, "step.tmp"), "COVER", filepath.Join(gen, "cover.jpg")) |
| + for _, step := range c.steps { |
| + args := []string{"-hide_banner", "-nostdin", "-loglevel", "error"} |
| + for _, a := range step { |
| + args = append(args, repl.Replace(a)) |
| + } |
| + if _, err := runChild(ctx, cfg, cfg.FFmpeg, args, gen); err != nil { |
| + return fmt.Errorf("ffmpeg could not make the source: %v", err) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// checkSelftestOutputs: every output the result names is stored with |
| +// the size and MD5 the result reports; the media file reads as a |
| +// fragmented MP4 and the playlist stored is the one its fragments |
| +// make. |
| +func checkSelftestOutputs(store *selftestStore, exec string, r media.Result, dir string) error { |
| + for _, o := range r.Outputs { |
| + b := store.object(exec, o.Name) |
| + sum := md5.Sum(b) |
| + if o.Bytes < 1 || int64(len(b)) != o.Bytes || hex.EncodeToString(sum[:]) != o.ETag { |
| + return fmt.Errorf("%s: stored %d bytes, the result says %d", o.Name, len(b), o.Bytes) |
| + } |
| + } |
| + names := []string{r.Outputs[0].Name, r.Outputs[1].Name} |
| + mediaFile := store.object(exec, names[0]) |
| + initLen, frags, _, err := readFMP4(bytes.NewReader(mediaFile), int64(len(mediaFile))) |
| + if err != nil { |
| + return fmt.Errorf("%s does not read as a fragmented MP4: %v", names[0], err) |
| + } |
| + var want bytes.Buffer |
| + if err := writePlaylist(&want, names[0], initLen, frags); err != nil { |
| + return fmt.Errorf("%s: no playlist: %v", names[0], err) |
| + } |
| + if !bytes.Equal(store.object(exec, names[1]), want.Bytes()) { |
| + return fmt.Errorf("%s is not the playlist of %s", names[1], names[0]) |
| + } |
| + return os.WriteFile(filepath.Join(dir, names[0]), mediaFile, 0o600) |
| +} |
| + |
| +// checkSelftestVideo: video.mp4, as ffprobe reads it, and the result's |
| +// dimensions for it and the poster, are targetSize of the source; the |
| +// poster is a JPEG. |
| +func checkSelftestVideo(ctx context.Context, cfg Config, store *selftestStore, exec string, r media.Result, src probeFacts, dir string) error { |
| + w, h := targetSize(src.Width, src.Height, src.Rotation) |
| + for _, o := range r.Outputs { |
| + if (o.Name == "video.mp4" || o.Name == "poster.jpg") && (o.Width != w || o.Height != h) { |
| + return fmt.Errorf("the result gives %s as %dx%d, want %dx%d", o.Name, o.Width, o.Height, w, h) |
| + } |
| + } |
| + if !bytes.HasPrefix(store.object(exec, "poster.jpg"), []byte{0xff, 0xd8, 0xff}) { |
| + return errors.New("poster.jpg is not a JPEG") |
| + } |
| + out, err := probeStored(ctx, cfg, filepath.Join(dir, "video.mp4"), media.PresetVideo720p, dir) |
| + if err != nil { |
| + return fmt.Errorf("video.mp4 does not probe: %v", err) |
| + } |
| + if ow, oh := targetSize(out.Width, out.Height, out.Rotation); ow != w || oh != h || out.VideoCodec != "h264" { |
| + return fmt.Errorf("video.mp4 is %s %dx%d, want h264 %dx%d", out.VideoCodec, ow, oh, w, h) |
| + } |
| + return nil |
| +} |
| + |
| +// checkSelftestAudio: peaks.json holds 1,000 peaks over the converted |
| +// duration, all 0 for a silent source and not all 0 otherwise; for a |
| +// voice, audio.mp4 measures -16 LUFS within 1 LU or is quieter (the |
| +// ceiling won), its true peak is never over -1.5 dBTP, and its loudness |
| +// range is at least the source's less 0.5 LU (spec §9, astra R6-5). |
| +func checkSelftestAudio(ctx context.Context, cfg Config, store *selftestStore, exec string, c selftestCase, dir string) error { |
| + var pk struct { |
| + Version int `json:"version"` |
| + DurationMS int64 `json:"duration_ms"` |
| + Peaks []int64 `json:"peaks"` |
| + } |
| + if err := json.Unmarshal(store.object(exec, "peaks.json"), &pk); err != nil || pk.Version != 1 || len(pk.Peaks) != peakCount { |
| + return fmt.Errorf("peaks.json does not hold %d peaks", peakCount) |
| + } |
| + loudest := int64(0) |
| + for _, v := range pk.Peaks { |
| + if v < 0 || v > 255 { |
| + return errors.New("peaks.json has a peak outside 0 to 255") |
| + } |
| + loudest = max(loudest, v) |
| + } |
| + switch { |
| + case c.silent && loudest != 0: |
| + return fmt.Errorf("a silent source has a peak of %d", loudest) |
| + case !c.silent && loudest == 0: |
| + return errors.New("every peak is 0") |
| + } |
| + if !c.voice { |
| + return nil |
| + } |
| + // runSelftestCase keeps the source in the probe scratch beside dir. |
| + srcPath := filepath.Join(filepath.Dir(dir), "probe", "in", "source") |
| + srcI, srcTP, srcLRA, err := selftestMeter(ctx, cfg, srcPath, dir) |
| + if err != nil { |
| + return fmt.Errorf("the source does not measure: %v", err) |
| + } |
| + outI, outTP, outLRA, err := selftestMeter(ctx, cfg, filepath.Join(dir, "audio.mp4"), dir) |
| + if err != nil { |
| + return fmt.Errorf("audio.mp4 does not measure: %v", err) |
| + } |
| + cfg.Logf("%s: source %.1f LUFS, %.1f dBTP, LRA %.1f LU; audio.mp4 %.1f LUFS, %.1f dBTP, LRA %.1f LU", |
| + c.name, srcI, srcTP, srcLRA, outI, outTP, outLRA) |
| + switch { |
| + case outTP > ceilingDBTP: |
| + return fmt.Errorf("audio.mp4's true peak is %.1f dBTP, over %.1f", outTP, ceilingDBTP) |
| + case outI > targetLUFS+1: |
| + return fmt.Errorf("audio.mp4 is %.1f LUFS, louder than %.0f LUFS", outI, targetLUFS) |
| + case outLRA < srcLRA-0.5: |
| + return fmt.Errorf("audio.mp4's loudness range is %.1f LU, the source's %.1f", outLRA, srcLRA) |
| + } |
| + return nil |
| +} |
| + |
| +// probeStored probes a file the selftest holds (an output) with the |
| +// handler's own probe, under preset. |
| +func probeStored(ctx context.Context, cfg Config, path, preset, dir string) (probeFacts, error) { |
| + pc := cfg |
| + pc.Scratch = filepath.Join(dir, "probe-out") |
| + if err := os.Mkdir(pc.Scratch, 0o700); err != nil { |
| + return probeFacts{}, err |
| + } |
| + if err := prepareScratch(pc.Scratch); err != nil { |
| + return probeFacts{}, err |
| + } |
| + if err := os.Rename(path, sourcePath(pc)); err != nil { |
| + return probeFacts{}, err |
| + } |
| + return probe(ctx, pc, "mov", preset) |
| +} |
| + |
| +// selftestMeter measures path's first audio stream with the loudness |
| +// meter: integrated loudness, true peak and loudness range. Only the |
| +// selftest's own files are measured, so the run is plain. |
| +func selftestMeter(ctx context.Context, cfg Config, path, dir string) (i, tp, lra float64, err error) { |
| + args := []string{"-hide_banner", "-nostats", "-loglevel", "info", "-nostdin", "-i", path, |
| + "-map", "0:a:0", "-vn", "-af", meterFilter, "-f", "null", "-"} |
| + tail, err := runChild(ctx, cfg, cfg.FFmpeg, args, dir) |
| + if err != nil { |
| + return 0, 0, 0, err |
| + } |
| + if i, tp, _, err = parseMeter(tail); err != nil { |
| + return 0, 0, 0, err |
| + } |
| + lra, err = parseLRA(tail) |
| + return i, tp, lra, err |
| +} |
| + |
| +// parseLRA reads "LRA: <n> LU" from ebur128's last summary. |
| +func parseLRA(stderr []byte) (float64, error) { |
| + at := bytes.LastIndex(stderr, append([]byte{'\n'}, meterPrefix...)) |
| + if at < 0 { |
| + return 0, errors.New("no ebur128 summary") |
| + } |
| + for _, line := range strings.Split(string(stderr[at+1:]), "\n")[1:] { |
| + if line != "" && line[0] != ' ' { |
| + break |
| + } |
| + if f := strings.Fields(line); len(f) == 3 && f[0] == "LRA:" && f[2] == "LU" { |
| + v, err := strconv.ParseFloat(f[1], 64) |
| + if err != nil || math.IsNaN(v) { |
| + return 0, errors.New("the ebur128 summary's LRA is not a number") |
| + } |
| + return v, nil |
| + } |
| + } |
| + return 0, errors.New("the ebur128 summary has no LRA") |
| +} |
| + |
| +// checkSelftestSecrets: none of c's secrets (a location, a title, a |
| +// comment the source carries) is in a log line of the run or in any |
| +// object it stored (preflight F19; spec §5.1 strips them from outputs). |
| +func checkSelftestSecrets(c selftestCase, logs []string, store *selftestStore, exec string) error { |
| + for _, s := range c.secrets { |
| + for _, line := range logs { |
| + if strings.Contains(line, s) { |
| + return errors.New("a log line carries the source's metadata") |
| + } |
| + } |
| + for _, name := range append(media.OutputNames(c.preset), "result") { |
| + if bytes.Contains(store.object(exec, name), []byte(s)) { |
| + return fmt.Errorf("%s carries the source's metadata", name) |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// selftestStore is an in-process store on 127.0.0.1 for the selftest: |
| +// it serves presigned-style transfers the way S3 does for the handler. |
| +// Each request must be one it issued: the same method, exactly the |
| +// query parameters it signed (in any order), and every signed header |
| +// with its signed value |
| +// (else 403, recorded as a problem). GET honours If-Match and a |
| +// "bytes=N-" Range; PUT honours If-None-Match: * and answers the |
| +// body's MD5 as the ETag. |
| +type selftestStore struct { |
| + srv *http.Server |
| + base string |
| + |
| + mu sync.Mutex |
| + objects map[string][]byte |
| + issued map[string]selftestTransfer |
| + problem []string |
| + putLimit int64 |
| +} |
| + |
| +// selftestTransfer is what the store signed for one path. |
| +type selftestTransfer struct { |
| + method, query string |
| + headers map[string]string |
| +} |
| + |
| +func newSelftestStore() (*selftestStore, error) { |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + return nil, err |
| + } |
| + s := &selftestStore{base: "http://" + ln.Addr().String(), objects: map[string][]byte{}, |
| + issued: map[string]selftestTransfer{}, putLimit: 1 << 30} |
| + s.srv = &http.Server{Handler: s, ReadHeaderTimeout: 30 * time.Second, IdleTimeout: time.Minute} |
| + go func() { _ = s.srv.Serve(ln) }() |
| + return s, nil |
| +} |
| + |
| +// Close stops the store. |
| +func (s *selftestStore) Close() error { return s.srv.Close() } |
| + |
| +func (s *selftestStore) problems() []string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return append([]string(nil), s.problem...) |
| +} |
| + |
| +// object is execution exec's stored object name ("result" for the |
| +// result object); nil when absent. |
| +func (s *selftestStore) object(exec, name string) []byte { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.objects[s.path(exec, name)] |
| +} |
| + |
| +func (s *selftestStore) path(exec, name string) string { |
| + switch name { |
| + case "source": |
| + return "/src/" + exec + "/source" |
| + case "result": |
| + return "/results/" + exec + ".json" |
| + } |
| + return "/out/" + exec + "/" + name |
| +} |
| + |
| +// job stores data as a new source and presigns its five transfers. |
| +func (s *selftestStore) job(preset string, data []byte, now time.Time) (string, media.Payload, error) { |
| + id := make([]byte, 24) |
| + if _, err := rand.Read(id); err != nil { |
| + return "", media.Payload{}, err |
| + } |
| + exec := hex.EncodeToString(id[:16]) |
| + token := hex.EncodeToString(id[16:]) |
| + sum := md5.Sum(data) |
| + etag := `"` + hex.EncodeToString(sum[:]) + `"` |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.objects[s.path(exec, "source")] = data |
| + tr := media.Transfers{OutPrefix: s.base + "/out/" + exec + "/"} |
| + presign := func(method, path string, headers map[string]string) (string, string, error) { |
| + sig := make([]byte, 32) |
| + if _, err := rand.Read(sig); err != nil { |
| + return "", "", err |
| + } |
| + date := now.UTC().Format("20060102T150405Z") |
| + signed := "host" |
| + for _, k := range []string{"content-type", "if-match", "if-none-match"} { |
| + if _, ok := headers[k]; ok { |
| + signed += "%3B" + k |
| + } |
| + } |
| + q := "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=SELFTEST%2F" + date[:8] + "%2Fus-east-1%2Fs3%2Faws4_request" + |
| + "&X-Amz-Date=" + date + "&X-Amz-Expires=3600&X-Amz-Security-Token=" + token + |
| + "&X-Amz-SignedHeaders=" + signed + "&X-Amz-Signature=" + hex.EncodeToString(sig) |
| + base, shared, rest, err := media.SplitPresigned(s.base + path + "?" + q) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + tr.Shared = shared // one grant: the same for every transfer |
| + s.issued[path] = selftestTransfer{method: method, query: q, headers: headers} |
| + return base, rest, nil |
| + } |
| + base, rest, err := presign(http.MethodGet, s.path(exec, "source"), map[string]string{"if-match": etag}) |
| + if err != nil { |
| + return "", media.Payload{}, err |
| + } |
| + tr.Source = media.Transfer{URL: base, Method: http.MethodGet, Query: rest, Header: map[string]string{"If-Match": etag}} |
| + for _, name := range media.OutputNames(preset) { |
| + h := map[string]string{"content-type": media.ContentType(name), "if-none-match": "*"} |
| + _, rest, err := presign(http.MethodPut, s.path(exec, name), h) |
| + if err != nil { |
| + return "", media.Payload{}, err |
| + } |
| + tr.Outputs = append(tr.Outputs, media.Transfer{Name: name, Method: http.MethodPut, Query: rest, |
| + Header: map[string]string{"Content-Type": h["content-type"], "If-None-Match": "*"}}) |
| + } |
| + h := map[string]string{"content-type": "application/json", "if-none-match": "*"} |
| + base, rest, err = presign(http.MethodPut, s.path(exec, "result"), h) |
| + if err != nil { |
| + return "", media.Payload{}, err |
| + } |
| + tr.Result = media.Transfer{URL: base, Method: http.MethodPut, Query: rest, |
| + Header: map[string]string{"Content-Type": "application/json", "If-None-Match": "*"}} |
| + p := media.Payload{ |
| + V: media.PayloadVersion, Execution: exec, Preset: preset, |
| + Limits: media.JobLimits{SourceBytes: int64(len(data)), GrantedMS: 600_000, GrantedBy: grantedByClass, |
| + MaxMS: 3_600_000, MaxHiMS: 1_200_000, OutputBytes: 1 << 30}, |
| + Expiry: now.Add(time.Hour).Unix(), |
| + Transfers: tr, |
| + } |
| + return exec, p, p.Validate() |
| +} |
| + |
| +func (s *selftestStore) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + s.mu.Lock() |
| + t, ok := s.issued[r.URL.Path] |
| + s.mu.Unlock() |
| + if !ok || r.Method != t.method || !sameRawQuery(r.URL.RawQuery, t.query) { |
| + s.refuse(w, "a request the store did not sign") |
| + return |
| + } |
| + for k, v := range t.headers { |
| + if r.Header.Get(k) != v { |
| + s.refuse(w, "a signed header missing or changed") |
| + return |
| + } |
| + } |
| + switch r.Method { |
| + case http.MethodGet: |
| + s.get(w, r) |
| + case http.MethodPut: |
| + s.put(w, r) |
| + } |
| +} |
| + |
| +// sameRawQuery reports whether two raw queries hold the same parameters, |
| +// each byte for byte, in any order (Transfers.URL puts the shared ones |
| +// last). |
| +func sameRawQuery(a, b string) bool { |
| + pa, pb := strings.Split(a, "&"), strings.Split(b, "&") |
| + slices.Sort(pa) |
| + slices.Sort(pb) |
| + return slices.Equal(pa, pb) |
| +} |
| + |
| +func (s *selftestStore) refuse(w http.ResponseWriter, why string) { |
| + s.mu.Lock() |
| + s.problem = append(s.problem, why) |
| + s.mu.Unlock() |
| + w.WriteHeader(http.StatusForbidden) |
| +} |
| + |
| +func (s *selftestStore) get(w http.ResponseWriter, r *http.Request) { |
| + s.mu.Lock() |
| + data, ok := s.objects[r.URL.Path] |
| + s.mu.Unlock() |
| + if !ok { |
| + w.WriteHeader(http.StatusNotFound) |
| + return |
| + } |
| + sum := md5.Sum(data) |
| + etag := `"` + hex.EncodeToString(sum[:]) + `"` |
| + if r.Header.Get("If-Match") != etag { |
| + w.WriteHeader(http.StatusPreconditionFailed) |
| + return |
| + } |
| + w.Header().Set("ETag", etag) |
| + start := int64(0) |
| + if rng := r.Header.Get("Range"); rng != "" { |
| + n, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimPrefix(rng, "bytes="), "-"), 10, 64) |
| + if err != nil || n < 0 || n >= int64(len(data)) { |
| + w.WriteHeader(http.StatusRequestedRangeNotSatisfiable) |
| + return |
| + } |
| + start = n |
| + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", n, len(data)-1, len(data))) |
| + w.Header().Set("Content-Length", strconv.Itoa(len(data)-int(n))) |
| + w.WriteHeader(http.StatusPartialContent) |
| + } else { |
| + w.Header().Set("Content-Length", strconv.Itoa(len(data))) |
| + } |
| + _, _ = w.Write(data[start:]) |
| +} |
| + |
| +func (s *selftestStore) put(w http.ResponseWriter, r *http.Request) { |
| + body, err := io.ReadAll(io.LimitReader(r.Body, s.putLimit+1)) |
| + if err != nil || int64(len(body)) > s.putLimit || int64(len(body)) != r.ContentLength { |
| + w.WriteHeader(http.StatusBadRequest) |
| + return |
| + } |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if _, exists := s.objects[r.URL.Path]; exists { |
| + w.WriteHeader(http.StatusPreconditionFailed) |
| + return |
| + } |
| + s.objects[r.URL.Path] = body |
| + sum := md5.Sum(body) |
| + w.Header().Set("ETag", `"`+hex.EncodeToString(sum[:])+`"`) |
| + w.WriteHeader(http.StatusOK) |
| +} |
diff --git a/internal/mediahandler/selftest_test.go b/internal/mediahandler/selftest_test.go| new file mode 100644 |
| index 000000000..a8c740ec5 |
| --- /dev/null |
| +++ b/internal/mediahandler/selftest_test.go |
| @@ -0,0 +1,124 @@ |
| +//go:build linux |
| + |
| +package mediahandler |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// TestSelftestReal runs both selftests on the real ffmpeg (skipped |
| +// without it, realConfig): every case PASS. |
| +func TestSelftestReal(t *testing.T) { |
| + real := realConfig(t) |
| + for _, kind := range []string{SelftestVideo, SelftestAudio} { |
| + t.Run(kind, func(t *testing.T) { |
| + cfg := real |
| + cfg.Scratch = t.TempDir() |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) |
| + defer cancel() |
| + var out bytes.Buffer |
| + err := Selftest(ctx, cfg, kind, &out) |
| + t.Logf("%s", out.String()) |
| + if err != nil || strings.Count(out.String(), "PASS ") != len(selftestCases[kind]) { |
| + t.Fatalf("Selftest(%s): %v\n%s", kind, err, out.String()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestSelftestFailsEachCase: with an ffmpeg that fails, every case is |
| +// one FAIL line naming it, and Selftest answers an error; an unknown |
| +// kind is an error with nothing printed. |
| +func TestSelftestFailsEachCase(t *testing.T) { |
| + needChildren(t) |
| + cfg, _ := fakeConfig(t, "fail") |
| + var out bytes.Buffer |
| + if err := Selftest(context.Background(), cfg, SelftestAudio, &out); err == nil { |
| + t.Fatal("Selftest passed on a failing ffmpeg") |
| + } |
| + lines := strings.Split(strings.TrimSpace(out.String()), "\n") |
| + if len(lines) != len(selftestCases[SelftestAudio]) { |
| + t.Fatalf("%d lines\n%s", len(lines), out.String()) |
| + } |
| + for i, c := range selftestCases[SelftestAudio] { |
| + if lines[i] != "FAIL "+c.name+": ffmpeg could not make the source: unreadable" { |
| + t.Errorf("line %q", lines[i]) |
| + } |
| + } |
| + out.Reset() |
| + if err := Selftest(context.Background(), cfg, "both", &out); err == nil || out.Len() != 0 { |
| + t.Fatalf("an unknown kind: %v %q", err, out.String()) |
| + } |
| +} |
| + |
| +// TestSelftestStoreHoldsThePresignedContract: the selftest's store |
| +// answers only what it signed: another query, a missing or changed |
| +// signed header, another method: 403, recorded; a second PUT to a key: |
| +// 412; the source's GET with its If-Match: 200 and the bytes. |
| +func TestSelftestStoreHoldsThePresignedContract(t *testing.T) { |
| + s, err := newSelftestStore() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + exec, p, err := s.job(media.PresetVideo720p, []byte("source bytes"), time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + do := func(method string, tr media.Transfer, header map[string]string, body string) int { |
| + req, err := http.NewRequest(method, p.Transfers.URL(tr), strings.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for k, v := range header { |
| + req.Header.Set(k, v) |
| + } |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + return resp.StatusCode |
| + } |
| + src := p.Transfers.Source |
| + if got := do(http.MethodGet, src, src.Header, ""); got != http.StatusOK { |
| + t.Fatalf("signed GET = %d", got) |
| + } |
| + out := p.Transfers.Outputs[0] |
| + if got := do(http.MethodPut, out, out.Header, "video"); got != http.StatusOK { |
| + t.Fatalf("signed PUT = %d", got) |
| + } |
| + if got := do(http.MethodPut, out, out.Header, "again"); got != http.StatusPreconditionFailed { |
| + t.Fatalf("second PUT = %d", got) |
| + } |
| + if string(s.object(exec, "video.mp4")) != "video" { |
| + t.Fatal("the PUT was not stored") |
| + } |
| + tampered := src |
| + tampered.Query += "&extra=1" |
| + for _, c := range []struct { |
| + method string |
| + tr media.Transfer |
| + header map[string]string |
| + }{ |
| + {http.MethodGet, tampered, src.Header}, |
| + {http.MethodGet, src, nil}, |
| + {http.MethodGet, src, map[string]string{"If-Match": `"other"`}}, |
| + {http.MethodPut, src, src.Header}, |
| + {http.MethodPut, p.Transfers.Outputs[1], map[string]string{"Content-Type": "text/plain", "If-None-Match": "*"}}, |
| + } { |
| + if got := do(c.method, c.tr, c.header, ""); got != http.StatusForbidden { |
| + t.Errorf("%s %+v: %d, want 403", c.method, c.header, got) |
| + } |
| + } |
| + if len(s.problems()) != 5 { |
| + t.Fatalf("problems %q", s.problems()) |
| + } |
| +} |
diff --git a/internal/mediahandler/testdata/corpus/archive.zip b/internal/mediahandler/testdata/corpus/archive.zip| new file mode 100644 |
| index 000000000..420a63a9d |
| Binary files /dev/null and b/internal/mediahandler/testdata/corpus/archive.zip differ |
diff --git a/internal/mediahandler/testdata/corpus/concat-list.ffconcat b/internal/mediahandler/testdata/corpus/concat-list.ffconcat| new file mode 100644 |
| index 000000000..9305853f6 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/corpus/concat-list.ffconcat |
| @@ -0,0 +1,3 @@ |
| +ffconcat version 1.0 |
| +file http://169.254.169.254/latest/meta-data/ |
| +file /etc/passwd |
diff --git a/internal/mediahandler/testdata/corpus/dref-alis-etc-passwd.mp4 b/internal/mediahandler/testdata/corpus/dref-alis-etc-passwd.mp4| new file mode 100644 |
| index 000000000..4eb941caf |
| Binary files /dev/null and b/internal/mediahandler/testdata/corpus/dref-alis-etc-passwd.mp4 differ |
diff --git a/internal/mediahandler/testdata/corpus/empty.bin b/internal/mediahandler/testdata/corpus/empty.bin| new file mode 100644 |
| index 000000000..e69de29bb |
diff --git a/internal/mediahandler/testdata/corpus/page.html b/internal/mediahandler/testdata/corpus/page.html| new file mode 100644 |
| index 000000000..02f0987c6 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/corpus/page.html |
| @@ -0,0 +1,3 @@ |
| +<!DOCTYPE html> |
| +<html><head><title>not media</title></head> |
| +<body><video src="http://169.254.169.254/latest/meta-data/"></video><img src="file:///etc/passwd"></body></html> |
diff --git a/internal/mediahandler/testdata/corpus/playlist-local-file.m3u8 b/internal/mediahandler/testdata/corpus/playlist-local-file.m3u8| new file mode 100644 |
| index 000000000..da0ebd833 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/corpus/playlist-local-file.m3u8 |
| @@ -0,0 +1,6 @@ |
| +#EXTM3U |
| +#EXT-X-VERSION:3 |
| +#EXT-X-TARGETDURATION:10 |
| +#EXTINF:10.0, |
| +file:///etc/passwd |
| +#EXT-X-ENDLIST |
diff --git a/internal/mediahandler/testdata/corpus/playlist-metadata.m3u8 b/internal/mediahandler/testdata/corpus/playlist-metadata.m3u8| new file mode 100644 |
| index 000000000..aed908c07 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/corpus/playlist-metadata.m3u8 |
| @@ -0,0 +1,6 @@ |
| +#EXTM3U |
| +#EXT-X-VERSION:3 |
| +#EXT-X-TARGETDURATION:10 |
| +#EXTINF:10.0, |
| +http://169.254.169.254/latest/meta-data/iam/security-credentials/ |
| +#EXT-X-ENDLIST |
diff --git a/internal/mediahandler/testdata/corpus/provenance.txt b/internal/mediahandler/testdata/corpus/provenance.txt| new file mode 100644 |
| index 000000000..33c6cd697 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/corpus/provenance.txt |
| @@ -0,0 +1,37 @@ |
| +The hostile-input corpus (plan 3 Task 7; spec §9). Each file goes |
| +through Run in TestCorpusEndsInNamedErrors (a fake answering as the real |
| +ffprobe and ffmpeg do) and TestRealCorpusEndsInNamedErrors (Debian 13's |
| +ffmpeg 7.1.5, skipped without it), under both presets, and must end in a |
| +named error with no request but the source's GET and the result's PUT. |
| + |
| +playlist-metadata.m3u8 an HLS playlist naming http://169.254.169.254/ |
| +playlist-local-file.m3u8 an HLS playlist naming file:///etc/passwd |
| +concat-list.ffconcat an ffconcat list naming both |
| +empty.bin 0 bytes |
| +random-4k.bin 4,096 bytes from Python's random.Random(20261118), |
| + drawn again until no sniffed magic is at its start |
| +page.html an HTML page whose tags name both addresses |
| +archive.zip a ZIP (Python zipfile) holding a file named clip.mp4 |
| + All of the above: unsupported_container, from sniff; ffprobe and |
| + ffmpeg never start. |
| + |
| +truncated.mp4 the first 12,000 bytes of a 26,716-byte MP4 |
| + (ffmpeg -f lavfi testsrc=size=160x90:rate=10:d=2 |
| + and sine=d=2, libx264 ultrafast, aac 32k), whose |
| + moov comes after the mdat, so it is cut off. |
| + ffprobe: "moov atom not found", exit 1 (the fake "fail"): unreadable. |
| + |
| +dref-alis-etc-passwd.mp4 that whole MP4 with each track's dref rewritten |
| + to one Mac alias ('alis') entry whose absolute |
| + path (type 2) is /etc/passwd: what ffmpeg's mov |
| + demuxer would open as the track's data with |
| + enable_drefs on. A 'url ' entry with a location |
| + is not enough: ffmpeg ignores those and reads |
| + the samples from the file itself. |
| + With -enable_drefs 0 ffprobe skips the external tracks and still |
| + lists both streams (testdata/probe/dref-alis.json, its answer to |
| + probe's arguments); video-720p's encode then finds no packet ("Cannot |
| + determine format of input 0:0 after EOF", exit 183, the fake |
| + "dref-alis"): unreadable. Under audio-aac the real loudness pass |
| + measures nothing (-70 LUFS), the encode writes no sample, and the job |
| + is unreadable too; the fake fails that pass instead, with the same end. |
diff --git a/internal/mediahandler/testdata/corpus/random-4k.bin b/internal/mediahandler/testdata/corpus/random-4k.bin| new file mode 100644 |
| index 000000000..a9da3119c |
| Binary files /dev/null and b/internal/mediahandler/testdata/corpus/random-4k.bin differ |
diff --git a/internal/mediahandler/testdata/corpus/truncated.mp4 b/internal/mediahandler/testdata/corpus/truncated.mp4| new file mode 100644 |
| index 000000000..ea0722019 |
| Binary files /dev/null and b/internal/mediahandler/testdata/corpus/truncated.mp4 differ |
diff --git a/internal/mediahandler/testdata/probe/dref-alis.json b/internal/mediahandler/testdata/probe/dref-alis.json| new file mode 100644 |
| index 000000000..af43728f9 |
| --- /dev/null |
| +++ b/internal/mediahandler/testdata/probe/dref-alis.json |
| @@ -0,0 +1,45 @@ |
| +{ |
| + "programs": [ |
| + |
| + ], |
| + "stream_groups": [ |
| + |
| + ], |
| + "streams": [ |
| + { |
| + "index": 0, |
| + "codec_name": "h264", |
| + "codec_type": "video", |
| + "width": 160, |
| + "height": 90, |
| + "sample_aspect_ratio": "1:1", |
| + "r_frame_rate": "10/1", |
| + "avg_frame_rate": "10/1", |
| + "duration": "2.000000", |
| + "disposition": { |
| + "attached_pic": 0 |
| + }, |
| + "tags": { |
| + |
| + } |
| + }, |
| + { |
| + "index": 1, |
| + "codec_name": "aac", |
| + "codec_type": "audio", |
| + "channels": 1, |
| + "r_frame_rate": "0/0", |
| + "avg_frame_rate": "0/0", |
| + "duration": "2.000000", |
| + "disposition": { |
| + "attached_pic": 0 |
| + }, |
| + "tags": { |
| + |
| + } |
| + } |
| + ], |
| + "format": { |
| + "duration": "2.000000" |
| + } |
| +} |
diff --git a/internal/mediahandler/testdata/probe/provenance.txt b/internal/mediahandler/testdata/probe/provenance.txt| index 910cc5a68..5f1e070e0 100644 |
| --- a/internal/mediahandler/testdata/probe/provenance.txt |
| +++ b/internal/mediahandler/testdata/probe/provenance.txt |
| @@ -42,3 +42,11 @@ handler's clamp to the grant (spec A2, preflight F15) is tested with: |
| ok-av.json H.264 160x90 + AAC stereo, 9.000 s |
| ok-audio.json AAC stereo, 9.000 s |
| + |
| +Recorded for the hostile-input corpus (plan 3 Task 7): the real |
| +ffprobe 7.1.5's answer, with probe's own arguments, for |
| +testdata/corpus/dref-alis-etc-passwd.mp4 (see the corpus's |
| +provenance.txt); its tags objects are empty: |
| + |
| +dref-alis.json H.264 160x90 + AAC mono, both tracks |
| + naming /etc/passwd as their data |
diff --git a/scripts/media-endpoint-drill.sh b/scripts/media-endpoint-drill.sh| new file mode 100755 |
| index 000000000..1614895f2 |
| --- /dev/null |
| +++ b/scripts/media-endpoint-drill.sh |
| @@ -0,0 +1,522 @@ |
| +#!/usr/bin/env bash |
| +# scripts/media-endpoint-drill.sh: the media engine's endpoint drill |
| +# (plan 3 Task 7, the one definition; plan 1 Task 4 Step 3 and rollout R3 |
| +# run it). An operator script: root never runs it. |
| +# |
| +# media-endpoint-drill.sh run --profile <dev profile> --foreign-profile <profile> |
| +# --cluster <cluster arn> --task-definition <arn> --repository <name> |
| +# --bucket <drill bucket name> --subnets <subnet,...> --security-group <sg> |
| +# media-endpoint-drill.sh cleanup <run dir> |
| +# |
| +# It proves that credentials of an unrelated account cannot use any of |
| +# the engine VPC's four endpoints (S3 gateway, ECR API, ECR Docker, |
| +# Logs), by controls, never by error text. It provisions a user in the |
| +# foreign account whose own policy, and whose target resources, admit |
| +# one S3 GET, an ECR token and an image pull, and log writes to a drill |
| +# log group; mints the presigned GET, the registry token and the log |
| +# stream outside the VPC (here); then runs `carlos-media drill endpoints` |
| +# in a media task three times: under the endpoints' saved policies |
| +# (phase A: every endpoint must refuse), under AWS's default full-access |
| +# policy (phase B: every endpoint must answer ok, which is what makes a |
| +# refusal in A and C the policy's doing), and under the restored |
| +# policies (phase C: every endpoint must refuse again). |
| +# `carlos-media drill endpoints-verdict` prints the table and decides. |
| +# |
| +# Cleanup is unconditional: the run directory and the EXIT trap exist |
| +# before anything is created, every create is written to <run dir>/state |
| +# (names only, never a secret) before it is made, and on every exit |
| +# (success, a failed step, a failed verdict, a signal) cleanup restores |
| +# the endpoint and repository policies, deletes the bucket, the user, its |
| +# key and the log group, removes input.json, then verifies each and |
| +# prints one line per obligation: "cleaned <obligation>" or "NOT CLEANED |
| +# <obligation>". Any NOT CLEANED makes the exit non-zero and keeps the run |
| +# directory; `cleanup <run dir>` repeats the job from its state file (for |
| +# a SIGKILL or a lost machine). |
| +# |
| +# Every AWS call goes through ${AWS:-aws}. Tests: AWS names a fake, and |
| +# MEDIA_DRILL_INTERVAL, MEDIA_DRILL_PASSES, MEDIA_DRILL_IAM_WAIT and |
| +# MEDIA_DRILL_LOG_WAIT shorten the waits. CARLOS_MEDIA is the command that |
| +# runs carlos-media (default: carlos-media on PATH, else `go run` of |
| +# cmd/carlos-media in this checkout). |
| +set -uo pipefail |
| +umask 077 |
| + |
| +AWS="${AWS:-aws}" |
| +interval="${MEDIA_DRILL_INTERVAL:-60}" |
| +passes="${MEDIA_DRILL_PASSES:-5}" |
| +iam_wait="${MEDIA_DRILL_IAM_WAIT:-10}" |
| +log_wait="${MEDIA_DRILL_LOG_WAIT:-5}" |
| +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" |
| +usage="usage: media-endpoint-drill.sh run --profile <p> --foreign-profile <p> --cluster <arn> --task-definition <arn> --repository <name> --bucket <name> --subnets <id,...> --security-group <id> | cleanup <run dir>" |
| +endpoints=(s3 ecr-api ecr-docker logs) |
| +object_key="drill-object" |
| +user_policy="carlos-media-endpoint-drill" |
| +log_stream="drill" |
| + |
| +say() { printf 'media-endpoint-drill: %s\n' "$*" >&2; } |
| +die() { say "$*"; exit 1; } |
| + |
| +# carlos_media runs carlos-media with its arguments. |
| +carlos_media() { |
| + if [ -n "${CARLOS_MEDIA:-}" ]; then |
| + # shellcheck disable=SC2086 # CARLOS_MEDIA may be a command with arguments |
| + $CARLOS_MEDIA "$@" |
| + elif command -v carlos-media >/dev/null 2>&1; then |
| + carlos-media "$@" |
| + else |
| + (cd "$here/.." && go run ./cmd/carlos-media "$@") |
| + fi |
| +} |
| + |
| +# record appends one line to the state file. |
| +record() { printf '%s\n' "$*" >>"$rundir/state"; } |
| +# recorded is true when the state file has the line exactly. |
| +recorded() { grep -qxF -- "$*" "$rundir/state" 2>/dev/null; } |
| +# state_value prints the value of the first "<key> <value>" line. |
| +state_value() { awk -v k="$1" '$1 == k { sub("^[^ ]+ ", ""); print; exit }' "$rundir/state"; } |
| + |
| +dev() { "$AWS" --profile "$profile" --region "$region" "$@"; } |
| +foreign() { "$AWS" --profile "$foreign_profile" --region "$region" "$@"; } |
| +# as_user runs aws with the drill user's key alone, outside the VPC. |
| +as_user() { |
| + env -u AWS_PROFILE -u AWS_DEFAULT_PROFILE -u AWS_SESSION_TOKEN -u AWS_SECURITY_TOKEN \ |
| + AWS_ACCESS_KEY_ID="$user_key_id" AWS_SECRET_ACCESS_KEY="$user_secret" "$AWS" --region "$region" "$@" |
| +} |
| + |
| +# gone_ok runs a command and succeeds if it did, or if its error names |
| +# one of the codes in $1 (the thing is already gone). |
| +gone_ok() { |
| + local codes="$1" err |
| + shift |
| + err="$("$@" 2>&1 >/dev/null)" && return 0 |
| + grep -Eq "$codes" <<<"$err" |
| +} |
| + |
| +# fails_with succeeds only when the command fails naming one of $1. |
| +fails_with() { |
| + local codes="$1" err |
| + shift |
| + err="$("$@" 2>&1 >/dev/null)" && return 1 |
| + grep -Eq "$codes" <<<"$err" |
| +} |
| + |
| +# retry runs a command up to 6 times, iam_wait seconds apart (IAM's new |
| +# users and keys take a few seconds to be usable everywhere). |
| +retry() { |
| + local i |
| + for i in 1 2 3 4 5 6; do |
| + "$@" && return 0 |
| + [ "$i" = 6 ] || pause "$iam_wait" |
| + done |
| + return 1 |
| +} |
| + |
| +# pause sleeps in the background, so a signal is handled at once. |
| +pause() { |
| + sleep "$1" & |
| + bg_pid=$! |
| + wait "$bg_pid" |
| + bg_pid="" |
| +} |
| + |
| +# safe is true when $1 can go inside a JSON string as it is: no quote, |
| +# no backslash, no control character. |
| +safe() { [[ -n "$1" && "$1" != *[\"\\]* && "$1" != *[[:cntrl:]]* ]]; } |
| + |
| +bg_pid="" |
| +cleaning="" |
| + |
| +# cleanup is the EXIT trap and the cleanup subcommand: undo every |
| +# obligation the state file shows begun, verify each, report, and set the |
| +# exit. $1 is the status the script was leaving with. |
| +cleanup() { |
| + local status="${1:-0}" |
| + [ -n "$cleaning" ] && return |
| + cleaning=1 |
| + trap '' INT TERM HUP |
| + if [ -n "$bg_pid" ]; then |
| + kill "$bg_pid" 2>/dev/null |
| + wait "$bg_pid" 2>/dev/null |
| + fi |
| + if [ -z "${rundir:-}" ] || [ ! -f "$rundir/state" ]; then |
| + exit "$status" |
| + fi |
| + load_state |
| + undo |
| + if verify; then |
| + rm -rf -- "$rundir" |
| + exit "$status" |
| + fi |
| + say "kept $rundir; finish with: $0 cleanup $rundir" |
| + [ "$status" = 0 ] && status=3 |
| + exit "$status" |
| +} |
| + |
| +load_state() { |
| + profile="$(state_value profile)" |
| + foreign_profile="$(state_value foreign-profile)" |
| + region="$(state_value region)" |
| + cluster="$(state_value cluster)" |
| + repository="$(state_value repository)" |
| + bucket="$(state_value bucket)" |
| + user="$(state_value user)" |
| + log_group="$(state_value log-group)" |
| +} |
| + |
| +# endpoint_ids prints "label id" for each endpoint whose policy was saved. |
| +endpoint_ids() { awk '$1 == "endpoint" { print $2, $3 }' "$rundir/state"; } |
| + |
| +undo() { |
| + local label id arn |
| + # Tasks still running hold the drill input: stop them. |
| + awk '$1 == "task" { print $2 }' "$rundir/state" | while read -r arn; do |
| + dev ecs stop-task --cluster "$cluster" --task "$arn" --reason "carlos media endpoint drill cleanup" >/dev/null 2>&1 |
| + done |
| + if recorded "open endpoints"; then |
| + endpoint_ids | while read -r label id; do |
| + dev ec2 modify-vpc-endpoint --vpc-endpoint-id "$id" --policy-document "$(cat "$rundir/policy-$label.json")" >/dev/null 2>&1 || |
| + say "could not restore the $label endpoint's policy" |
| + done |
| + fi |
| + if recorded "create repo-grant"; then |
| + if [ "$(state_value repo-policy)" = saved ]; then |
| + dev ecr set-repository-policy --repository-name "$repository" --policy-text "$(cat "$rundir/repo-policy.json")" >/dev/null 2>&1 || |
| + say "could not put back the repository policy" |
| + else |
| + gone_ok 'RepositoryPolicyNotFoundException' dev ecr delete-repository-policy --repository-name "$repository" || |
| + say "could not delete the repository policy" |
| + fi |
| + fi |
| + if recorded "create bucket-policy"; then |
| + gone_ok 'NoSuchBucket' dev s3api delete-bucket-policy --bucket "$bucket" || say "could not delete the bucket policy" |
| + fi |
| + if recorded "create object"; then |
| + gone_ok 'NoSuchBucket|NoSuchKey' dev s3api delete-object --bucket "$bucket" --key "$object_key" || say "could not delete the object" |
| + fi |
| + if recorded "create bucket"; then |
| + gone_ok 'NoSuchBucket' dev s3api delete-bucket --bucket "$bucket" || say "could not delete the bucket" |
| + fi |
| + if recorded "create access-key"; then |
| + foreign iam list-access-keys --user-name "$user" --query 'AccessKeyMetadata[].AccessKeyId' --output text 2>/dev/null | |
| + tr '\t' '\n' | while read -r id; do |
| + [ -n "$id" ] && [ "$id" != None ] || continue |
| + gone_ok 'NoSuchEntity' foreign iam delete-access-key --user-name "$user" --access-key-id "$id" || say "could not delete a key" |
| + done |
| + fi |
| + if recorded "create user-policy"; then |
| + gone_ok 'NoSuchEntity' foreign iam delete-user-policy --user-name "$user" --policy-name "$user_policy" || say "could not delete the user's policy" |
| + fi |
| + if recorded "create user"; then |
| + gone_ok 'NoSuchEntity' foreign iam delete-user --user-name "$user" || say "could not delete the user" |
| + fi |
| + if recorded "create log-group"; then |
| + gone_ok 'ResourceNotFoundException' foreign logs delete-log-group --log-group-name "$log_group" || say "could not delete the log group" |
| + fi |
| + rm -f -- "$rundir/input.json" "$rundir/overrides.json" |
| +} |
| + |
| +# verify checks each obligation and prints its line; false if any is not |
| +# clean. An obligation never begun is clean. |
| +verify() { |
| + local ok=0 label id clean |
| + # endpoint-policies: each saved policy is what the endpoint has now. |
| + clean=1 |
| + while read -r label id; do |
| + [ -n "$label" ] || continue |
| + dev ec2 describe-vpc-endpoints --vpc-endpoint-ids "$id" --query 'VpcEndpoints[0].PolicyDocument' --output text \ |
| + >"$rundir/now-$label.json" 2>/dev/null && cmp -s "$rundir/now-$label.json" "$rundir/policy-$label.json" || clean="" |
| + done < <(endpoint_ids) |
| + report_line "$clean" endpoint-policies || ok=1 |
| + # repository-policy: the saved one, or none as there was none. |
| + clean=1 |
| + if recorded "create repo-grant"; then |
| + if [ "$(state_value repo-policy)" = saved ]; then |
| + dev ecr get-repository-policy --repository-name "$repository" --query policyText --output text \ |
| + >"$rundir/now-repo-policy.json" 2>/dev/null && cmp -s "$rundir/now-repo-policy.json" "$rundir/repo-policy.json" || clean="" |
| + else |
| + fails_with 'RepositoryPolicyNotFoundException' dev ecr get-repository-policy --repository-name "$repository" || clean="" |
| + fi |
| + fi |
| + report_line "$clean" repository-policy || ok=1 |
| + # bucket: HeadBucket answers 404. |
| + clean=1 |
| + if recorded "create bucket"; then |
| + fails_with '\(404\)|Not Found' dev s3api head-bucket --bucket "$bucket" || clean="" |
| + fi |
| + report_line "$clean" bucket || ok=1 |
| + # foreign-user: GetUser answers NoSuchEntity. |
| + clean=1 |
| + if recorded "create user"; then |
| + fails_with 'NoSuchEntity' foreign iam get-user --user-name "$user" || clean="" |
| + fi |
| + report_line "$clean" foreign-user || ok=1 |
| + # log-group: no group of that name. |
| + clean=1 |
| + if recorded "create log-group"; then |
| + local groups |
| + groups="$(foreign logs describe-log-groups --log-group-name-prefix "$log_group" --query 'logGroups[].logGroupName' --output text 2>/dev/null)" || clean="" |
| + tr '\t' '\n' <<<"$groups" | grep -qxF -- "$log_group" && clean="" |
| + fi |
| + report_line "$clean" log-group || ok=1 |
| + # input: neither the input nor the overrides holding it is left. |
| + clean=1 |
| + [ -e "$rundir/input.json" ] || [ -e "$rundir/overrides.json" ] && clean="" |
| + report_line "$clean" input || ok=1 |
| + return "$ok" |
| +} |
| + |
| +# report_line prints "cleaned <obligation>" or "NOT CLEANED <obligation>". |
| +report_line() { |
| + if [ -n "$1" ]; then |
| + printf 'cleaned %s\n' "$2" |
| + return 0 |
| + fi |
| + printf 'NOT CLEANED %s\n' "$2" |
| + return 1 |
| +} |
| + |
| +# all_lines is true when file $1 holds exactly one line per endpoint, |
| +# each matching "<endpoint> $2". |
| +all_lines() { |
| + local file="$1" want="$2" e |
| + [ "$(grep -c . "$file")" = 4 ] || return 1 |
| + for e in "${endpoints[@]}"; do |
| + grep -Eqx "$e $want" "$file" || return 1 |
| + done |
| +} |
| + |
| +# run_pass runs one pass of `carlos-media drill endpoints` in a media |
| +# task and writes its output lines to $1. |
| +run_pass() { |
| + local out="$1" arn task_id i |
| + : >"$out" |
| + # The deadline container needs both values (preflight F25); the |
| + # codec container gets the drill's input. |
| + printf '{"containerOverrides":[{"name":"deadline","environment":[{"name":"CARLOS_MEDIA_DEADLINE_S","value":"300"},{"name":"CARLOS_MEDIA_GRANT_EXPIRY","value":"%s"}]},{"name":"codec","command":["drill","endpoints"],"environment":[{"name":"CARLOS_MEDIA_DRILL","value":"%s"}]}]}\n' \ |
| + "$(($(date +%s) + 3600))" "$(sed 's/"/\\"/g' "$rundir/input.json")" >"$rundir/overrides.json" |
| + arn="$(dev ecs run-task --cluster "$cluster" --task-definition "$task_definition" --launch-type FARGATE --count 1 \ |
| + --network-configuration "awsvpcConfiguration={subnets=[$subnets],securityGroups=[$security_group],assignPublicIp=DISABLED}" \ |
| + --overrides "file://$rundir/overrides.json" --query 'tasks[0].taskArn' --output text)" |
| + local rc=$? |
| + rm -f -- "$rundir/overrides.json" |
| + [ "$rc" = 0 ] && [[ "$arn" == arn:aws:ecs:* ]] || { say "a drill task did not start"; return 1; } |
| + record "task $arn" |
| + # In the background, and not through a function (that would be a |
| + # subshell), so a signal is handled at once and cleanup can stop it. |
| + "$AWS" --profile "$profile" --region "$region" ecs wait tasks-stopped --cluster "$cluster" --tasks "$arn" & |
| + bg_pid=$! |
| + wait "$bg_pid" || say "the drill task did not stop in time" |
| + bg_pid="" |
| + task_id="${arn##*/}" |
| + for i in 1 2 3 4 5; do |
| + dev logs get-log-events --log-group-name "$engine_log_group" --log-stream-name "$engine_log_prefix/codec/$task_id" \ |
| + --start-from-head --query 'events[].[message]' --output text >"$out" 2>/dev/null || : >"$out" |
| + [ "$(grep -c . "$out")" -ge 4 ] && return 0 |
| + pause "$log_wait" |
| + done |
| + say "the drill task's output is incomplete" |
| +} |
| + |
| +main_run() { |
| + local profile_="" foreign_="" cluster_="" td_="" repo_="" bucket_="" subnets_="" sg_="" |
| + while [ $# -gt 0 ]; do |
| + case "$1" in |
| + --profile) profile_="${2:-}" ;; |
| + --foreign-profile) foreign_="${2:-}" ;; |
| + --cluster) cluster_="${2:-}" ;; |
| + --task-definition) td_="${2:-}" ;; |
| + --repository) repo_="${2:-}" ;; |
| + --bucket) bucket_="${2:-}" ;; |
| + --subnets) subnets_="${2:-}" ;; |
| + --security-group) sg_="${2:-}" ;; |
| + *) echo "$usage" >&2; exit 2 ;; |
| + esac |
| + shift 2 || { echo "$usage" >&2; exit 2; } |
| + done |
| + for v in "$profile_" "$foreign_" "$cluster_" "$td_" "$repo_" "$bucket_" "$subnets_" "$sg_"; do |
| + [ -n "$v" ] || { echo "$usage" >&2; exit 2; } |
| + done |
| + [[ "$cluster_" =~ ^arn:aws:ecs:([a-z0-9-]+):([0-9]{12}):cluster/[A-Za-z0-9_-]+$ ]] || die "--cluster is not a cluster ARN" |
| + region="${BASH_REMATCH[1]}" |
| + local dev_account="${BASH_REMATCH[2]}" |
| + |
| + # The run directory and the trap come first: nothing exists yet. |
| + rundir="$(mktemp -d "${TMPDIR:-/tmp}/media-endpoint-drill.XXXXXX")" || die "no run directory" |
| + trap 'cleanup $?' EXIT |
| + trap 'exit 130' INT |
| + trap 'exit 143' TERM |
| + trap 'exit 129' HUP |
| + |
| + profile="$profile_" foreign_profile="$foreign_" cluster="$cluster_" task_definition="$td_" |
| + repository="$repo_" bucket="$bucket_" subnets="$subnets_" security_group="$sg_" |
| + local id |
| + id="$(od -An -N4 -tx1 /dev/urandom | tr -d ' \n')" |
| + user="carlos-media-drill-$id" |
| + log_group="carlos-media-endpoint-drill-$id" |
| + record "run $id" |
| + record "profile $profile" |
| + record "foreign-profile $foreign_profile" |
| + record "region $region" |
| + record "cluster $cluster" |
| + record "repository $repository" |
| + record "bucket $bucket" |
| + record "user $user" |
| + record "log-group $log_group" |
| + say "run directory $rundir" |
| + |
| + # The engine's network, its four endpoints and the codec's log stream. |
| + local foreign_account vpc image registry digest repo_path line label policy |
| + foreign_account="$(foreign sts get-caller-identity --query Account --output text)" || die "the foreign profile does not answer" |
| + [[ "$foreign_account" =~ ^[0-9]{12}$ ]] || die "the foreign profile has no account" |
| + vpc="$(dev ec2 describe-subnets --subnet-ids "${subnets%%,*}" --query 'Subnets[0].VpcId' --output text)" || die "the subnet is unknown" |
| + local -A endpoint_id=() |
| + while read -r id line; do |
| + case "$line" in |
| + *.s3) endpoint_id[s3]="$id" ;; |
| + *.ecr.api) endpoint_id[ecr-api]="$id" ;; |
| + *.ecr.dkr) endpoint_id[ecr-docker]="$id" ;; |
| + *.logs) endpoint_id[logs]="$id" ;; |
| + esac |
| + done < <(dev ec2 describe-vpc-endpoints --filters "Name=vpc-id,Values=$vpc" --query 'VpcEndpoints[].[VpcEndpointId,ServiceName]' --output text) |
| + for label in "${endpoints[@]}"; do |
| + [ -n "${endpoint_id[$label]:-}" ] || die "the engine VPC has no $label endpoint" |
| + done |
| + for label in "${endpoints[@]}"; do |
| + dev ec2 describe-vpc-endpoints --vpc-endpoint-ids "${endpoint_id[$label]}" --query 'VpcEndpoints[0].PolicyDocument' \ |
| + --output text >"$rundir/policy-$label.json" || die "the $label endpoint's policy cannot be read" |
| + record "endpoint $label ${endpoint_id[$label]}" |
| + done |
| + if policy="$(dev ecr get-repository-policy --repository-name "$repository" --query policyText --output text 2>"$rundir/err")"; then |
| + printf '%s\n' "$policy" >"$rundir/repo-policy.json" |
| + record "repo-policy saved" |
| + elif grep -q RepositoryPolicyNotFoundException "$rundir/err"; then |
| + record "repo-policy none" |
| + else |
| + die "the repository policy cannot be read" |
| + fi |
| + image="$(dev ecs describe-task-definition --task-definition "$task_definition" \ |
| + --query "taskDefinition.containerDefinitions[?name=='codec'].image | [0]" --output text)" || die "the task definition cannot be read" |
| + [[ "$image" =~ ^([a-z0-9.-]+)/([a-z0-9._/-]+)@(sha256:[0-9a-f]{64})$ ]] || die "the codec image is not pinned by digest" |
| + registry="${BASH_REMATCH[1]}" repo_path="${BASH_REMATCH[2]}" digest="${BASH_REMATCH[3]}" |
| + read -r engine_log_group engine_log_prefix < <(dev ecs describe-task-definition --task-definition "$task_definition" \ |
| + --query "taskDefinition.containerDefinitions[?name=='codec'].logConfiguration.options | [0].[\"awslogs-group\",\"awslogs-stream-prefix\"]" --output text) |
| + [ -n "${engine_log_group:-}" ] && [ -n "${engine_log_prefix:-}" ] && [ "$engine_log_group" != None ] || |
| + die "the codec container has no awslogs group and prefix" |
| + |
| + # The drill bucket must not exist: cleanup deletes only what this run made. |
| + fails_with '\(404\)|Not Found' dev s3api head-bucket --bucket "$bucket" || die "the drill bucket already exists, or cannot be checked" |
| + record "create bucket" |
| + if [ "$region" = us-east-1 ]; then |
| + dev s3api create-bucket --bucket "$bucket" >/dev/null || die "the bucket was not created" |
| + else |
| + dev s3api create-bucket --bucket "$bucket" --create-bucket-configuration "LocationConstraint=$region" >/dev/null || |
| + die "the bucket was not created" |
| + fi |
| + printf 'carlos-media endpoint drill\n' >"$rundir/object.txt" |
| + record "create object" |
| + dev s3api put-object --bucket "$bucket" --key "$object_key" --body "$rundir/object.txt" >/dev/null || die "the object was not created" |
| + |
| + # The foreign account: the log group, the user, its policy and its key. |
| + record "create log-group" |
| + foreign logs create-log-group --log-group-name "$log_group" || die "the log group was not created" |
| + record "create user" |
| + local user_arn |
| + user_arn="$(foreign iam create-user --user-name "$user" --query User.Arn --output text)" || die "the user was not created" |
| + [[ "$user_arn" == "arn:aws:iam::$foreign_account:user/$user" ]] || die "the user's ARN is not the expected one" |
| + record "create user-policy" |
| + foreign iam put-user-policy --user-name "$user" --policy-name "$user_policy" --policy-document \ |
| + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::$bucket/$object_key\"},{\"Effect\":\"Allow\",\"Action\":\"ecr:GetAuthorizationToken\",\"Resource\":\"*\"},{\"Effect\":\"Allow\",\"Action\":[\"ecr:BatchGetImage\",\"ecr:GetDownloadUrlForLayer\",\"ecr:BatchCheckLayerAvailability\"],\"Resource\":\"arn:aws:ecr:$region:$dev_account:repository/$repository\"},{\"Effect\":\"Allow\",\"Action\":[\"logs:CreateLogStream\",\"logs:PutLogEvents\"],\"Resource\":\"arn:aws:logs:$region:$foreign_account:log-group:$log_group:*\"}]}" || |
| + die "the user's policy was not created" |
| + record "create access-key" |
| + local keys |
| + keys="$(foreign iam create-access-key --user-name "$user" --query 'AccessKey.[AccessKeyId,SecretAccessKey]' --output text)" || |
| + die "the user's key was not created" |
| + read -r user_key_id user_secret <<<"$keys" |
| + unset keys |
| + [ -n "${user_key_id:-}" ] && [ -n "${user_secret:-}" ] || die "the user's key was not created" |
| + |
| + # The drill bucket and the engine repository admit the user. |
| + record "create bucket-policy" |
| + retry dev s3api put-bucket-policy --bucket "$bucket" --policy \ |
| + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"CarlosMediaEndpointDrill\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"$user_arn\"},\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::$bucket/$object_key\"}]}" || |
| + die "the bucket policy was not created" |
| + local grant="{\"Sid\":\"CarlosMediaEndpointDrill\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"$user_arn\"},\"Action\":[\"ecr:BatchGetImage\",\"ecr:GetDownloadUrlForLayer\",\"ecr:BatchCheckLayerAvailability\"]}" |
| + local repo_policy="{\"Version\":\"2012-10-17\",\"Statement\":[$grant]}" |
| + if [ "$(state_value repo-policy)" = saved ]; then |
| + repo_policy="$(python3 -I -c 'import json,sys |
| +p = json.load(open(sys.argv[1])) |
| +s = p.get("Statement", []) |
| +p["Statement"] = (s if isinstance(s, list) else [s]) + [json.loads(sys.argv[2])] |
| +print(json.dumps(p))' "$rundir/repo-policy.json" "$grant")" || die "the repository grant cannot be written" |
| + fi |
| + record "create repo-grant" |
| + retry dev ecr set-repository-policy --repository-name "$repository" --policy-text "$repo_policy" >/dev/null || |
| + die "the repository grant was not created" |
| + |
| + # Outside the VPC, with the user's key: the presigned GET, the |
| + # registry token and the log stream. |
| + local s3_url token |
| + s3_url="$(retry as_user s3 presign "s3://$bucket/$object_key" --expires-in 3600)" || die "the GET was not presigned" |
| + token="$(retry as_user ecr get-authorization-token --query 'authorizationData[0].authorizationToken' --output text)" || |
| + die "the registry token was not minted" |
| + retry as_user logs create-log-stream --log-group-name "$log_group" --log-stream-name "$log_stream" || die "the log stream was not created" |
| + for v in "$s3_url" "$token" "$user_key_id" "$user_secret"; do |
| + safe "$v" || die "a minted value cannot be written as JSON" |
| + done |
| + printf '{"s3_get_url":"%s","ecr_token":"%s","ecr_manifest_url":"%s","region":"%s","access_key_id":"%s","secret_access_key":"%s","log_group":"%s","log_stream":"%s"}\n' \ |
| + "$s3_url" "$token" "https://$registry/v2/$repo_path/manifests/$digest" "$region" "$user_key_id" "$user_secret" "$log_group" "$log_stream" \ |
| + >"$rundir/input.json" |
| + unset s3_url token user_secret |
| + |
| + # Phase A: the saved policies refuse every endpoint. |
| + say "phase A: the saved endpoint policies" |
| + run_pass "$rundir/A.out" |
| + : >"$rundir/B.out" |
| + : >"$rundir/C.out" |
| + if all_lines "$rundir/A.out" 'refused (conn|[0-9]{3})'; then |
| + # Phase B: AWS's default full-access policy on all four. |
| + say "phase B: the endpoints opened to full access" |
| + record "open endpoints" |
| + for label in "${endpoints[@]}"; do |
| + dev ec2 modify-vpc-endpoint --vpc-endpoint-id "${endpoint_id[$label]}" --reset-policy >/dev/null || |
| + die "the $label endpoint's policy was not reset" |
| + done |
| + local n |
| + for ((n = 1; n <= passes; n++)); do |
| + pause "$interval" |
| + run_pass "$rundir/B.out" |
| + all_lines "$rundir/B.out" ok && break |
| + done |
| + # Phase C: the saved policies back. |
| + say "phase C: the saved endpoint policies restored" |
| + for label in "${endpoints[@]}"; do |
| + dev ec2 modify-vpc-endpoint --vpc-endpoint-id "${endpoint_id[$label]}" --policy-document "$(cat "$rundir/policy-$label.json")" >/dev/null || |
| + die "the $label endpoint's policy was not restored" |
| + done |
| + record "restored endpoints" |
| + for ((n = 1; n <= passes; n++)); do |
| + pause "$interval" |
| + run_pass "$rundir/C.out" |
| + all_lines "$rundir/C.out" 'refused (conn|[0-9]{3})' && break |
| + done |
| + else |
| + say "phase A was not refused at every endpoint; the endpoints are not opened" |
| + fi |
| + carlos_media drill endpoints-verdict "$rundir/A.out" "$rundir/B.out" "$rundir/C.out" |
| +} |
| + |
| +case "${1:-}" in |
| + run) |
| + shift |
| + main_run "$@" |
| + ;; |
| + cleanup) |
| + [ $# = 2 ] && [ -f "$2/state" ] || { echo "$usage" >&2; exit 2; } |
| + rundir="$(cd "$2" && pwd)" |
| + cleanup 0 |
| + ;; |
| + *) |
| + echo "$usage" >&2 |
| + exit 2 |
| + ;; |
| +esac |
diff --git a/scripts/media_endpoint_drill_test.py b/scripts/media_endpoint_drill_test.py| new file mode 100644 |
| index 000000000..51ad6c0a3 |
| --- /dev/null |
| +++ b/scripts/media_endpoint_drill_test.py |
| @@ -0,0 +1,523 @@ |
| +"""Tests for scripts/media-endpoint-drill.sh, the media engine's endpoint |
| +drill (plan 3 Task 7), with no AWS call: `aws` is a fake on AWS, a Python |
| +script that logs each call and keeps a fake world (the four endpoint |
| +policies, the repository policy, the bucket, the foreign user and the log |
| +group) in a JSON file, and fails on demand. `carlos-media` is a fake too, |
| +for `drill endpoints-verdict` (cmd/carlos-media's own tests hold the real |
| +one). |
| + |
| +The cleanup is the subject: whatever ends the run (a failed create, a |
| +failed verdict, SIGTERM with the endpoints open, a delete AWS refuses, a |
| +SIGKILL), every obligation already begun is undone and verified, and the |
| +run says which it could not clean. |
| + |
| +Run from the repo root: python3 -m unittest scripts/media_endpoint_drill_test.py |
| +(the Go test TestMediaEndpointDrillPythonGuards runs it in CI). |
| +""" |
| +import json |
| +import os |
| +from pathlib import Path |
| +import signal |
| +import subprocess |
| +import sys |
| +import tempfile |
| +import time |
| +import unittest |
| + |
| +SCRIPT = Path(__file__).with_name('media-endpoint-drill.sh') |
| + |
| +REGION = 'eu-west-1' |
| +DEV = '123456789012' |
| +FOREIGN = '210987654321' |
| +CLUSTER = f'arn:aws:ecs:{REGION}:{DEV}:cluster/media' |
| +TASKDEF = f'arn:aws:ecs:{REGION}:{DEV}:task-definition/media-video-720p-short:3' |
| +BUCKET = 'carlos-media-endpoint-drill-bucket' |
| +REPO = 'carlos-media' |
| +SECRET = 'fakeSECRETvalue/0123456789abcdefghijklmnopqrstuv' |
| +TOKEN = 'QVdTOmZha2UtcmVnaXN0cnktcGFzc3dvcmQ=' |
| +SIGNATURE = 'fakesignature0123456789abcdef' |
| +DEFAULT_POLICY = '{"Statement":[{"Action":"*","Effect":"Allow","Principal":"*","Resource":"*"}]}' |
| +ENDPOINTS = { |
| + 'vpce-0s3': ('s3', f'com.amazonaws.{REGION}.s3'), |
| + 'vpce-0api': ('ecr-api', f'com.amazonaws.{REGION}.ecr.api'), |
| + 'vpce-0dkr': ('ecr-docker', f'com.amazonaws.{REGION}.ecr.dkr'), |
| + 'vpce-0logs': ('logs', f'com.amazonaws.{REGION}.logs'), |
| +} |
| + |
| + |
| +def original_policy(label): |
| + return ('{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"*","Resource":"*",' |
| + f'"Condition":{{"StringEquals":{{"aws:PrincipalArn":"arn:aws:iam::{DEV}:role/media-{label}"}}}}}}]}}') |
| + |
| + |
| +FAKE_AWS = r''' |
| +import fcntl, json, os, sys, time |
| + |
| +world_path = os.environ['FAKE_AWS_WORLD'] |
| +args = sys.argv[1:] |
| +glob, rest = {}, [] |
| +i = 0 |
| +while i < len(args): |
| + a = args[i] |
| + if a in ('--profile', '--region', '--query', '--output'): |
| + glob[a[2:]] = args[i + 1] |
| + i += 2 |
| + continue |
| + rest.append(a) |
| + i += 1 |
| +service, op, opargs = rest[0], rest[1], rest[2:] |
| +opts, flags = {}, set() |
| +i = 0 |
| +while i < len(opargs): |
| + a = opargs[i] |
| + if a in ('--reset-policy', '--start-from-head'): |
| + flags.add(a[2:]) |
| + i += 1 |
| + elif a.startswith('--'): |
| + opts[a[2:]] = opargs[i + 1] if i + 1 < len(opargs) else '' |
| + i += 2 |
| + else: |
| + opts.setdefault('_', []).append(a) |
| + i += 1 |
| +name = service + ' ' + op |
| + |
| +lock = open(world_path + '.lock', 'w') |
| +fcntl.flock(lock, fcntl.LOCK_EX) |
| +world = json.load(open(world_path)) |
| +world['calls'].append({'call': name, 'opts': opts, 'flags': sorted(flags), 'profile': glob.get('profile'), |
| + 'env_key': 'AWS_ACCESS_KEY_ID' in os.environ}) |
| + |
| + |
| +def save(): |
| + tmp = world_path + '.tmp' |
| + with open(tmp, 'w') as f: |
| + json.dump(world, f) |
| + os.replace(tmp, world_path) |
| + |
| + |
| +def out(s=''): |
| + save() |
| + if s: |
| + print(s) |
| + sys.exit(0) |
| + |
| + |
| +def err(code, msg='failed'): |
| + save() |
| + print(f'An error occurred ({code}) when calling the {op} operation: {msg}', file=sys.stderr) |
| + sys.exit(254) |
| + |
| + |
| +if world.get('refuse') == name: |
| + err('AccessDenied', 'refused by the test') |
| +if world.get('fail') == name: |
| + err('InjectedFailure', 'injected by the test') |
| +fail_after = world.get('fail_after') == name |
| + |
| + |
| +def done(s=''): |
| + if fail_after: |
| + err('InjectedFailure', 'injected after the change') |
| + out(s) |
| + |
| + |
| +eps = world['endpoints'] |
| +user_cmd = name in ('s3 presign', 'ecr get-authorization-token', 'logs create-log-stream') |
| +if user_cmd and (glob.get('profile') or 'AWS_ACCESS_KEY_ID' not in os.environ): |
| + err('NoCredentials', 'the drill user key was not used') |
| +if not user_cmd and not glob.get('profile'): |
| + err('NoProfile', 'an operator call named no profile') |
| +dev = glob.get('profile') == 'kass' |
| +if name == 'sts get-caller-identity': |
| + out('210987654321') |
| +if name == 'ec2 describe-subnets': |
| + out('vpc-0drill') |
| +if name == 'ec2 describe-vpc-endpoints': |
| + if 'vpc-endpoint-ids' in opts: |
| + out(eps[opts['vpc-endpoint-ids']]['policy']) |
| + out('\n'.join(f'{k}\t{v["service"]}' for k, v in eps.items())) |
| +if name == 'ec2 modify-vpc-endpoint': |
| + ep = eps[opts['vpc-endpoint-id']] |
| + ep['policy'] = world['default_policy'] if 'reset-policy' in flags else opts['policy-document'] |
| + done('{"Return": true}') |
| +if name == 'ecr get-repository-policy': |
| + if world['repo_policy'] is None: |
| + err('RepositoryPolicyNotFoundException', 'Repository policy does not exist') |
| + out(world['repo_policy']) |
| +if name == 'ecr set-repository-policy': |
| + world['repo_policy'] = opts['policy-text'] |
| + done('{}') |
| +if name == 'ecr delete-repository-policy': |
| + if world['repo_policy'] is None: |
| + err('RepositoryPolicyNotFoundException', 'Repository policy does not exist') |
| + world['repo_policy'] = None |
| + done('{}') |
| +if name == 'ecs describe-task-definition': |
| + if 'image' in glob.get('query', ''): |
| + out('123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-media@sha256:' + 'ab' * 32) |
| + out('media-engine\tmedia') |
| +buckets = world['buckets'] |
| +if name == 's3api head-bucket': |
| + if opts['bucket'] in buckets: |
| + out() |
| + err('404', 'Not Found') |
| +if name == 's3api create-bucket': |
| + if opts['bucket'] in buckets: |
| + err('BucketAlreadyOwnedByYou') |
| + buckets[opts['bucket']] = {'objects': [], 'policy': None} |
| + done('{}') |
| +if name.startswith('s3api ') and opts.get('bucket') not in buckets: |
| + err('NoSuchBucket', 'The specified bucket does not exist') |
| +b = buckets.get(opts.get('bucket')) |
| +if name == 's3api put-object': |
| + b['objects'].append(opts['key']) |
| + done('{}') |
| +if name == 's3api put-bucket-policy': |
| + b['policy'] = opts['policy'] |
| + done() |
| +if name == 's3api delete-bucket-policy': |
| + b['policy'] = None |
| + done() |
| +if name == 's3api delete-object': |
| + if opts['key'] in b['objects']: |
| + b['objects'].remove(opts['key']) |
| + done() |
| +if name == 's3api delete-bucket': |
| + if b['objects']: |
| + err('BucketNotEmpty') |
| + del buckets[opts['bucket']] |
| + done() |
| +users = world['users'] |
| +if name == 'iam create-user': |
| + if opts['user-name'] in users: |
| + err('EntityAlreadyExists') |
| + users[opts['user-name']] = {'policies': [], 'keys': []} |
| + done(f'arn:aws:iam::210987654321:user/{opts["user-name"]}') |
| +if name.startswith('iam ') and opts.get('user-name') not in users: |
| + err('NoSuchEntity', 'The user cannot be found') |
| +u = users.get(opts.get('user-name')) |
| +if name == 'iam get-user': |
| + out('{}') |
| +if name == 'iam put-user-policy': |
| + world['user_policy_documents'].append(opts['policy-document']) |
| + u['policies'].append(opts['policy-name']) |
| + done() |
| +if name == 'iam create-access-key': |
| + key = f'AKIAFAKEDRILL{len(u["keys"]):07d}' |
| + u['keys'].append(key) |
| + done(key + '\t' + os.environ['FAKE_SECRET']) |
| +if name == 'iam list-access-keys': |
| + out('\t'.join(u['keys'])) |
| +if name == 'iam delete-access-key': |
| + u['keys'].remove(opts['access-key-id']) |
| + done() |
| +if name == 'iam delete-user-policy': |
| + u['policies'].remove(opts['policy-name']) |
| + done() |
| +if name == 'iam delete-user': |
| + if u['policies'] or u['keys']: |
| + err('DeleteConflict') |
| + del users[opts['user-name']] |
| + done() |
| +groups = world['log_groups'] |
| +if name == 'logs create-log-group': |
| + groups.append(opts['log-group-name']) |
| + done() |
| +if name == 'logs delete-log-group': |
| + if opts['log-group-name'] not in groups: |
| + err('ResourceNotFoundException') |
| + groups.remove(opts['log-group-name']) |
| + done() |
| +if name == 'logs describe-log-groups': |
| + out('\t'.join(g for g in groups if g.startswith(opts['log-group-name-prefix']))) |
| +if name == 'logs create-log-stream': |
| + if opts['log-group-name'] not in groups: |
| + err('ResourceNotFoundException') |
| + done() |
| +if name == 's3 presign': |
| + out(f'https://{opts["_"][0][5:].split("/")[0]}.s3.eu-west-1.amazonaws.com/drill-object?X-Amz-Algorithm=AWS4-HMAC-SHA256' |
| + f'&X-Amz-Credential=AKIAFAKEDRILL%2F20261118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature={os.environ["FAKE_SIGNATURE"]}') |
| +if name == 'ecr get-authorization-token': |
| + out(os.environ['FAKE_TOKEN']) |
| +opened = all(e['policy'] == world['default_policy'] for e in eps.values()) |
| +if name == 'ecs run-task': |
| + path = opts['overrides'][len('file://'):] |
| + world['overrides'].append(json.load(open(path))) |
| + world['task_seq'] += 1 |
| + arn = f'arn:aws:ecs:eu-west-1:123456789012:task/media/{world["task_seq"]:032x}' |
| + ok = opened and not world.get('b_never_ok') |
| + world['tasks'][arn] = [f'{e} ok' if ok else f'{e} refused 403' for e in ('s3', 'ecr-api', 'ecr-docker', 'logs')] |
| + world['phases'].append('open' if opened else 'saved') |
| + done(arn) |
| +if name == 'ecs wait': |
| + if world.get('block_when_open') and opened: |
| + save() |
| + lock.close() |
| + open(world['marker'] + '.tmp', 'w').write(str(os.getpid())) |
| + os.replace(world['marker'] + '.tmp', world['marker']) |
| + time.sleep(60) |
| + sys.exit(0) # its world is stale by now: never written back |
| + out() |
| +if name == 'ecs stop-task': |
| + out('{}') |
| +if name == 'logs get-log-events': |
| + task_id = opts['log-stream-name'].rsplit('/', 1)[1] |
| + for arn, lines in world['tasks'].items(): |
| + if arn.endswith('/' + task_id): |
| + out('\n'.join(lines)) |
| + err('ResourceNotFoundException') |
| +err('UnknownOperation', name) |
| +''' |
| + |
| +FAKE_CARLOS_MEDIA = r''' |
| +import re, sys |
| +args = sys.argv[1:] |
| +assert args[:2] == ['drill', 'endpoints-verdict'], args |
| +def cells(path): |
| + lines = [l for l in open(path).read().splitlines() if l.strip()] |
| + return {l.split(' ', 1)[0]: l.split(' ', 1)[1] for l in lines} if len(lines) == 4 else {} |
| +want = {'A': 'refused', 'B': 'ok', 'C': 'refused'} |
| +ok = True |
| +for phase, path in zip('ABC', args[2:]): |
| + c = cells(path) |
| + for e in ('s3', 'ecr-api', 'ecr-docker', 'logs'): |
| + if not c.get(e, '').startswith(want[phase]): |
| + ok = False |
| + print(f'FAIL {e} phase {phase}') |
| +print('PASS endpoints' if ok else 'verdict: FAIL') |
| +sys.exit(0 if ok else 1) |
| +''' |
| + |
| +CREATES = ['s3api create-bucket', 's3api put-object', 'logs create-log-group', 'iam create-user', |
| + 'iam put-user-policy', 'iam create-access-key', 's3api put-bucket-policy', 'ecr set-repository-policy'] |
| +OBLIGATIONS = ['endpoint-policies', 'repository-policy', 'bucket', 'foreign-user', 'log-group', 'input'] |
| + |
| + |
| +class Drill: |
| + """One run directory's worth of fakes and the script's outcome.""" |
| + |
| + def __init__(self, test, **world): |
| + self.dir = Path(tempfile.mkdtemp(prefix='media-drill-test-')) |
| + test.addCleanup(subprocess.run, ['rm', '-rf', str(self.dir)]) |
| + self.tmp = self.dir / 'tmp' |
| + self.tmp.mkdir() |
| + self.world_path = self.dir / 'world.json' |
| + w = { |
| + 'endpoints': {k: {'label': v[0], 'service': v[1], 'policy': original_policy(v[0])} for k, v in ENDPOINTS.items()}, |
| + 'default_policy': DEFAULT_POLICY, 'repo_policy': None, 'buckets': {}, 'users': {}, 'log_groups': [], |
| + 'tasks': {}, 'task_seq': 0, 'calls': [], 'overrides': [], 'phases': [], 'user_policy_documents': [], |
| + 'marker': str(self.dir / 'blocked'), |
| + } |
| + w.update(world) |
| + self.world_path.write_text(json.dumps(w)) |
| + self.aws = self.dir / 'aws' |
| + self.aws.write_text(f'#!{sys.executable} -I\n' + FAKE_AWS) |
| + self.aws.chmod(0o755) |
| + cm = self.dir / 'carlos-media' |
| + cm.write_text(f'#!{sys.executable} -I\n' + FAKE_CARLOS_MEDIA) |
| + cm.chmod(0o755) |
| + self.env = { |
| + 'PATH': os.environ.get('PATH', '/usr/bin:/bin'), 'HOME': str(self.dir), 'TMPDIR': str(self.tmp), |
| + 'AWS': str(self.aws), 'CARLOS_MEDIA': str(cm), 'FAKE_AWS_WORLD': str(self.world_path), |
| + 'FAKE_SECRET': SECRET, 'FAKE_TOKEN': TOKEN, 'FAKE_SIGNATURE': SIGNATURE, |
| + 'MEDIA_DRILL_INTERVAL': '0', 'MEDIA_DRILL_IAM_WAIT': '0', 'MEDIA_DRILL_LOG_WAIT': '0', 'MEDIA_DRILL_PASSES': '2', |
| + 'AWS_PROFILE': 'should-not-reach-the-user-calls', |
| + } |
| + |
| + def args(self): |
| + return ['bash', str(SCRIPT), 'run', '--profile', 'kass', '--foreign-profile', 'foreign', '--cluster', CLUSTER, |
| + '--task-definition', TASKDEF, '--repository', REPO, '--bucket', BUCKET, |
| + '--subnets', 'subnet-0a,subnet-0b', '--security-group', 'sg-0tasks'] |
| + |
| + def run(self, *args): |
| + p = subprocess.run(list(args) or self.args(), env=self.env, capture_output=True, text=True, timeout=120) |
| + self.code, self.stdout, self.stderr = p.returncode, p.stdout, p.stderr |
| + return self |
| + |
| + def start(self): |
| + return subprocess.Popen(self.args(), env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| + |
| + def world(self): |
| + return json.loads(self.world_path.read_text()) |
| + |
| + def rundirs(self): |
| + return sorted(self.tmp.glob('media-endpoint-drill.*')) |
| + |
| + def calls(self): |
| + return [c['call'] for c in self.world()['calls']] |
| + |
| + def set_world(self, **kv): |
| + w = self.world() |
| + w.update(kv) |
| + self.world_path.write_text(json.dumps(w)) |
| + |
| + |
| +class MediaEndpointDrillTest(unittest.TestCase): |
| + def assert_clean(self, d, kept=False): |
| + w = d.world() |
| + self.assertEqual(w['buckets'], {}, d.stderr) |
| + self.assertEqual(w['users'], {}, d.stderr) |
| + self.assertEqual(w['log_groups'], [], d.stderr) |
| + self.assertIsNone(w['repo_policy']) |
| + for k, v in w['endpoints'].items(): |
| + self.assertEqual(v['policy'], original_policy(ENDPOINTS[k][0]), k) |
| + for rd in d.rundirs(): |
| + self.assertFalse((rd / 'input.json').exists()) |
| + self.assertFalse((rd / 'overrides.json').exists()) |
| + if not kept: |
| + self.assertEqual(d.rundirs(), [], 'the run directory was kept') |
| + for o in OBLIGATIONS: |
| + self.assertIn(f'cleaned {o}\n', d.stdout) |
| + self.assertNotIn('NOT CLEANED', d.stdout) |
| + |
| + def assert_no_secret_printed(self, d): |
| + for s in (SECRET, TOKEN, SIGNATURE, 'X-Amz', 'https://'): |
| + self.assertNotIn(s, d.stdout + d.stderr) |
| + |
| + def test_run_passes_and_cleans(self): |
| + d = Drill(self).run() |
| + self.assertEqual(d.code, 0, d.stdout + d.stderr) |
| + self.assertIn('PASS endpoints', d.stdout) |
| + self.assert_clean(d) |
| + self.assert_no_secret_printed(d) |
| + w = d.world() |
| + self.assertEqual(w['phases'], ['saved', 'open', 'saved']) |
| + # Every pass ran the drill with its input on codec and both deadline values (F25). |
| + for o in w['overrides']: |
| + by = {c['name']: c for c in o['containerOverrides']} |
| + self.assertEqual(by['codec']['command'], ['drill', 'endpoints']) |
| + env = {e['name']: e['value'] for e in by['codec']['environment']} |
| + drill = json.loads(env['CARLOS_MEDIA_DRILL']) |
| + self.assertEqual(sorted(drill), sorted(['s3_get_url', 'ecr_token', 'ecr_manifest_url', 'region', 'access_key_id', |
| + 'secret_access_key', 'log_group', 'log_stream'])) |
| + self.assertEqual((drill['secret_access_key'], drill['ecr_token'], drill['region']), (SECRET, TOKEN, REGION)) |
| + self.assertEqual(drill['ecr_manifest_url'], |
| + 'https://123456789012.dkr.ecr.eu-west-1.amazonaws.com/v2/carlos-media/manifests/sha256:' + 'ab' * 32) |
| + denv = {e['name'] for e in by['deadline']['environment']} |
| + self.assertEqual(denv, {'CARLOS_MEDIA_DEADLINE_S', 'CARLOS_MEDIA_GRANT_EXPIRY'}) |
| + # The user's policy: the four grants, the logs ones on the drill group only. |
| + doc = json.loads(w['user_policy_documents'][0]) |
| + actions = {json.dumps(s['Action']): s['Resource'] for s in doc['Statement']} |
| + self.assertTrue(actions['["logs:CreateLogStream", "logs:PutLogEvents"]'].startswith( |
| + f'arn:aws:logs:{REGION}:{FOREIGN}:log-group:carlos-media-endpoint-drill-')) |
| + self.assertTrue(actions['["logs:CreateLogStream", "logs:PutLogEvents"]'].endswith(':*')) |
| + # The minted values came from the user's key alone, never a profile. |
| + for c in w['calls']: |
| + if c['call'] in ('s3 presign', 'ecr get-authorization-token', 'logs create-log-stream'): |
| + self.assertTrue(c['env_key']) |
| + self.assertIsNone(c['profile']) |
| + |
| + def test_cleanup_after_each_failed_setup_step(self): |
| + for create in CREATES: |
| + for mode in ('fail', 'fail_after'): |
| + with self.subTest(create=create, mode=mode): |
| + d = Drill(self, **{mode: create}).run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assert_clean(d) |
| + calls = d.calls() |
| + self.assertNotIn('ecs run-task', calls) |
| + i = calls.index(create) |
| + begun = calls[:i + 1] |
| + after = calls[i + 1:] |
| + if 's3api create-bucket' in begun: |
| + self.assertIn('s3api head-bucket', after) |
| + if 'iam create-user' in begun: |
| + self.assertIn('iam get-user', after) |
| + if 'logs create-log-group' in begun: |
| + self.assertIn('logs describe-log-groups', after) |
| + if 'ecr set-repository-policy' in begun: |
| + self.assertIn('ecr get-repository-policy', after) |
| + self.assert_no_secret_printed(d) |
| + |
| + def test_cleanup_after_failed_verdict(self): |
| + d = Drill(self, b_never_ok=True).run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn('FAIL s3 phase B', d.stdout) |
| + self.assert_clean(d) |
| + self.assertEqual(d.world()['phases'], ['saved', 'open', 'open', 'saved']) |
| + |
| + def test_phase_a_open_never_opens_the_endpoints(self): |
| + policies = {k: {'label': v[0], 'service': v[1], 'policy': DEFAULT_POLICY} for k, v in ENDPOINTS.items()} |
| + d = Drill(self, endpoints=policies).run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertNotIn('ec2 modify-vpc-endpoint', d.calls()) |
| + self.assertEqual(d.world()['phases'], ['open']) |
| + |
| + def test_cleanup_on_sigterm_mid_phase_b(self): |
| + d = Drill(self, block_when_open=True) |
| + p = d.start() |
| + marker = Path(d.world()['marker']) |
| + deadline = time.monotonic() + 60 |
| + while not marker.exists(): |
| + self.assertIsNone(p.poll(), 'the run ended before phase B') |
| + self.assertLess(time.monotonic(), deadline) |
| + time.sleep(0.05) |
| + self.assertTrue(all(e['policy'] == DEFAULT_POLICY for e in d.world()['endpoints'].values())) |
| + p.send_signal(signal.SIGTERM) |
| + d.stdout, d.stderr = p.communicate(timeout=60) |
| + d.code = p.returncode |
| + self.assertEqual(d.code, 143, d.stderr) |
| + self.assert_clean(d) |
| + self.assertIn('ecs stop-task', d.calls()) |
| + |
| + def test_cleanup_reports_what_it_could_not_clean(self): |
| + d = Drill(self, refuse='iam delete-user').run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn('NOT CLEANED foreign-user\n', d.stdout) |
| + for o in OBLIGATIONS: |
| + if o != 'foreign-user': |
| + self.assertIn(f'cleaned {o}\n', d.stdout) |
| + rundirs = d.rundirs() |
| + self.assertEqual(len(rundirs), 1) |
| + state = (rundirs[0] / 'state').read_text() |
| + self.assertIn('create user\n', state) |
| + for s in (SECRET, TOKEN, SIGNATURE): |
| + self.assertNotIn(s, state) |
| + self.assertFalse((rundirs[0] / 'input.json').exists()) |
| + # Once AWS allows it, cleanup <run dir> finishes the job. |
| + d.set_world(refuse=None) |
| + d.run('bash', str(SCRIPT), 'cleanup', str(rundirs[0])) |
| + self.assertEqual(d.code, 0, d.stdout + d.stderr) |
| + self.assert_clean(d) |
| + |
| + def test_cleanup_subcommand_from_state(self): |
| + d = Drill(self, block_when_open=True) |
| + p = d.start() |
| + marker = Path(d.world()['marker']) |
| + deadline = time.monotonic() + 60 |
| + while not marker.exists(): |
| + self.assertLess(time.monotonic(), deadline) |
| + time.sleep(0.05) |
| + p.kill() # SIGKILL: no trap runs |
| + os.kill(int(marker.read_text()), signal.SIGKILL) # the fake aws the script left waiting |
| + p.communicate(timeout=60) |
| + w = d.world() |
| + self.assertEqual(len(w['buckets']), 1) |
| + self.assertTrue(all(e['policy'] == DEFAULT_POLICY for e in w['endpoints'].values())) |
| + rundirs = d.rundirs() |
| + self.assertEqual(len(rundirs), 1) |
| + self.assertTrue((rundirs[0] / 'input.json').exists()) |
| + d.run('bash', str(SCRIPT), 'cleanup', str(rundirs[0])) |
| + self.assertEqual(d.code, 0, d.stdout + d.stderr) |
| + self.assert_clean(d) |
| + |
| + def test_existing_bucket_is_refused_and_kept(self): |
| + d = Drill(self, buckets={BUCKET: {'objects': ['theirs'], 'policy': None}}).run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertEqual(d.world()['buckets'], {BUCKET: {'objects': ['theirs'], 'policy': None}}) |
| + for call in ('s3api create-bucket', 's3api delete-object', 's3api delete-bucket'): |
| + self.assertNotIn(call, d.calls()) |
| + self.assertIn('cleaned bucket\n', d.stdout) |
| + self.assertEqual(d.rundirs(), []) |
| + |
| + def test_usage(self): |
| + d = Drill(self).run('bash', str(SCRIPT), 'run', '--profile', 'kass') |
| + self.assertEqual(d.code, 2) |
| + self.assertEqual(d.rundirs(), []) |
| + d.run('bash', str(SCRIPT), 'cleanup', str(d.tmp / 'absent')) |
| + self.assertEqual(d.code, 2) |
| + self.assertEqual(d.calls(), []) |
| + |
| + |
| +if __name__ == '__main__': |
| + unittest.main() |