media: drill state, ownership, secrets; evidence; non-dumpable
Plan 3 Task 7 fix round 1 (Astra P1 x3, P2 x4, ledger ruling). Endpoint drill script: every AWS change is preceded by a checksummed state line read back before the change, and a line that cannot be written stops the run; cleanup refuses a truncated, garbled or misshapen state whole. Intent is recorded apart from verified ownership (a random run tag, the user's ARN and UserId); cleanup deletes only what still carries them, records each deletion, and leaves a collision or a replaced resource as NOT CLEANED. The user's key reaches aws only through its environment; xtrace is refused; both profiles' accounts are checked, and must differ, before anything is made. fill-scratch and many-files pass only on evidence (ENOSPC/EDQUOT seen, the scratch full, the files counted), with cleanup errors kept apart. The selftest checks video and poster dimensions as encoded. An inotify canary proves an MP4's external reference is never opened, with a positive control. codec, selftest and the drills make the process non-dumpable first. Plan 1 Task 4 and plan 3 R2/R3 gain the drill's --subnets/--security-group and the deadline env (F25).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+1,431
−293
cmd/carlos-media/drill.go+7 −1cmd/carlos-media/drill_linux.go+43 −10cmd/carlos-media/drill_linux_test.go+156 −1cmd/carlos-media/harden_linux.go+17 −0cmd/carlos-media/harden_other.go+7 −0cmd/carlos-media/main.go+21 −0docs/superpowers/notes/media-conversion-copy-deck.md+7 −5docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md+1 −1docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md+6 −6internal/mediahandler/hostile_linux.go+64 −15internal/mediahandler/hostile_test.go+228 −9internal/mediahandler/selftest.go+24 −8internal/mediahandler/selftest_test.go+40 −0scripts/media-endpoint-drill.sh+482 −158scripts/media_endpoint_drill_test.py+328 −79
diff --git a/cmd/carlos-media/drill.go b/cmd/carlos-media/drill.go| index 9858e93d5..ce275921b 100644 |
| --- a/cmd/carlos-media/drill.go |
| +++ b/cmd/carlos-media/drill.go |
| @@ -104,8 +104,14 @@ func drillClient(dialer *net.Dialer) *http.Client { |
| // 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. |
| +// otherwise, 2 for a usage error. Every drill but the hostile child |
| +// first makes the process non-dumpable (hardened): endpoints holds the |
| +// foreign key, bad-outputs a payload, and fill-scratch and many-files |
| +// start children. |
| func drillCommand(args []string, stdout, stderr io.Writer) int { |
| + if (len(args) == 0 || args[0] != "child") && !hardened(stderr) { |
| + return 1 |
| + } |
| return runDrill(context.Background(), realDrillEnv(), args, stdout, stderr) |
| } |
diff --git a/cmd/carlos-media/drill_linux.go b/cmd/carlos-media/drill_linux.go| index 9196609be..630358427 100644 |
| --- a/cmd/carlos-media/drill_linux.go |
| +++ b/cmd/carlos-media/drill_linux.go |
| @@ -61,25 +61,58 @@ func linuxDrill(ctx context.Context, name string, rest []string, r *report, stde |
| } |
| // drillChildJob runs kind's hostile child under the handler's child |
| -// rules and reports the job code the handler gave it. |
| +// rules and reports what judgeChildJob makes of 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 { |
| + o, err := 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) |
| + if why := judgeChildJob(kind, o, err); why != "" { |
| + r.fail(kind, "%s (job %s, in %s)", why, codeOrNone(o.Code), took) |
| return |
| } |
| + r.pass(kind, "the job failed %s in %s; %s; no child left; outputs reset", o.Code, took, evidence(kind, o)) |
| +} |
| + |
| +// judgeChildJob answers why the drill fails, or "" when it passes. A |
| +// pass needs the evidence, not only a named code: fill-scratch, the |
| +// child's own report of a full file system (ENOSPC or EDQUOT), the |
| +// scratch reading full, and engine_failed (the task's storage, not the |
| +// source); many-files, the hundred thousand files there, and |
| +// unreadable. Either way no child may be left and the outputs must have |
| +// been reset. |
| +func judgeChildJob(kind string, o mediahandler.DrillOutcome, cleanupErr error) string { |
| + switch { |
| + case cleanupErr != nil: |
| + return cleanupErr.Error() |
| + case kind == mediahandler.HostileFillScratch && o.Exhausted == "": |
| + return "the child never met a full file system" |
| + case kind == mediahandler.HostileFillScratch && !o.ScratchFull: |
| + return "the scratch did not read full" |
| + case kind == mediahandler.HostileFillScratch && o.Code != media.CodeEngineFailed: |
| + return "the job did not end " + media.CodeEngineFailed |
| + case kind == mediahandler.HostileManyFiles && o.Files < 100_000: |
| + return "the child made " + strconv.Itoa(o.Files) + " files, not 100000" |
| + case kind == mediahandler.HostileManyFiles && o.Code != media.CodeUnreadable: |
| + return "the job did not end " + media.CodeUnreadable |
| + } |
| + return "" |
| +} |
| + |
| +// evidence is the PASS line's account of what was seen. |
| +func evidence(kind string, o mediahandler.DrillOutcome) string { |
| + if kind == mediahandler.HostileFillScratch { |
| + return "the child met " + o.Exhausted + " and the scratch read full" |
| + } |
| + return strconv.Itoa(o.Files) + " files were made" |
| +} |
| + |
| +func codeOrNone(code string) string { |
| if code == "" { |
| - code = "no error" |
| + return "no error" |
| } |
| - r.fail(kind, "the job ended %s in %s, want %s", code, took, want) |
| + return code |
| } |
| // drillBadOutputs runs mediahandler.DrillBadOutputs and reports each |
diff --git a/cmd/carlos-media/drill_linux_test.go b/cmd/carlos-media/drill_linux_test.go| index 17f6b8109..f48e48842 100644 |
| --- a/cmd/carlos-media/drill_linux_test.go |
| +++ b/cmd/carlos-media/drill_linux_test.go |
| @@ -5,7 +5,10 @@ package main |
| import ( |
| "bytes" |
| "context" |
| + "errors" |
| + "fmt" |
| "os" |
| + "os/exec" |
| "slices" |
| "strings" |
| "syscall" |
| @@ -22,9 +25,125 @@ 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)) |
| } |
| + switch os.Getenv(hardenTestEnv) { |
| + case "hardened", "plain": |
| + os.Exit(hardenParent(os.Getenv(hardenTestEnv) == "hardened")) |
| + case "child": |
| + os.Exit(readParentEnviron()) |
| + } |
| os.Exit(m.Run()) |
| } |
| +// hardenTestEnv names the role of a re-executed test binary in |
| +// TestHardenedProcessHidesItsEnviron. |
| +const hardenTestEnv = "CARLOS_MEDIA_TEST_HARDEN" |
| + |
| +// hardenSecret is in the parent's environment from its start, as the |
| +// payload is in the codec's. |
| +const hardenSecret = "CARLOS_MEDIA_TEST_SECRET=payload-in-the-environment" |
| + |
| +// hardenParent stands in for the handler: non-dumpable when asked, it |
| +// starts a child of its own and passes on what the child reports. |
| +func hardenParent(hardenIt bool) int { |
| + if hardenIt && notDumpable() != nil { |
| + return 2 |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + return 2 |
| + } |
| + cmd := exec.Command(self) |
| + cmd.Env = []string{hardenTestEnv + "=child"} |
| + cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr |
| + if cmd.Run() != nil { |
| + return 2 |
| + } |
| + return 0 |
| +} |
| + |
| +// readParentEnviron is the compromised child: it opens its parent's |
| +// /proc/<ppid>/environ and says what happened. |
| +func readParentEnviron() int { |
| + b, err := os.ReadFile(fmt.Sprintf("/proc/%d/environ", os.Getppid())) |
| + switch { |
| + case errors.Is(err, syscall.EACCES): |
| + fmt.Println("EACCES") |
| + case err != nil: |
| + fmt.Println("error:", err) |
| + case bytes.Contains(b, []byte(hardenSecret)): |
| + fmt.Println("read the secret") |
| + default: |
| + fmt.Println("read, no secret") |
| + } |
| + return 0 |
| +} |
| + |
| +// TestHardenedProcessHidesItsEnviron (ledger ruling, PR_SET_DUMPABLE): |
| +// a child of a non-dumpable process, running as the same user, gets |
| +// EACCES opening /proc/<ppid>/environ; the control, a dumpable parent, |
| +// lets the same child read the secret there. Root reads either way, so |
| +// as root this skips. |
| +func TestHardenedProcessHidesItsEnviron(t *testing.T) { |
| + if os.Geteuid() == 0 { |
| + t.Skip("root reads any process's environ") |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for mode, want := range map[string]string{"hardened": "EACCES\n", "plain": "read the secret\n"} { |
| + cmd := exec.Command(self) |
| + cmd.Env = []string{hardenTestEnv + "=" + mode, hardenSecret} |
| + out, err := cmd.CombinedOutput() |
| + if err != nil || string(out) != want { |
| + t.Errorf("%s parent: the child said %q (%v), want %q", mode, out, err, want) |
| + } |
| + } |
| +} |
| + |
| +// TestCommandsHardenFirst: codec, selftest and every drill but the |
| +// hostile child make the process non-dumpable before they read |
| +// anything; when that fails, each stops with exit 1 and reads nothing |
| +// (the payload stays where it was, nothing is printed on stdout). |
| +func TestCommandsHardenFirst(t *testing.T) { |
| + saved := harden |
| + defer func() { harden = saved }() |
| + calls := 0 |
| + payloadThen := []bool{} |
| + harden = func() error { |
| + calls++ |
| + _, ok := os.LookupEnv(media.PayloadEnv) |
| + payloadThen = append(payloadThen, ok) |
| + return nil |
| + } |
| + t.Setenv(mediahandler.ScratchEnv, t.TempDir()) |
| + t.Setenv(media.PayloadEnv, `{"v":2}`) |
| + var stdout, stderr bytes.Buffer |
| + dispatch([]string{media.CodecCommand}, &stdout, &stderr) |
| + if calls != 1 || !payloadThen[0] { |
| + t.Fatalf("codec: harden called %d times, payload still set then: %v", calls, payloadThen) |
| + } |
| + dispatch([]string{"drill", "child", "none", t.TempDir()}, &stdout, &stderr) |
| + if calls != 1 { |
| + t.Fatal("the hostile child was hardened") |
| + } |
| + |
| + harden = func() error { calls++; return errors.New("refused") } |
| + t.Setenv(media.PayloadEnv, `{"v":2}`) |
| + for _, args := range [][]string{{media.CodecCommand}, {"selftest", "audio"}, {"drill", "creds"}, {"drill", "bad-outputs"}} { |
| + stdout.Reset() |
| + stderr.Reset() |
| + before := calls |
| + if code := dispatch(args, &stdout, &stderr); code != 1 || calls != before+1 || stdout.Len() != 0 || |
| + stderr.String() != "carlos-media: cannot make the process non-dumpable: refused\n" { |
| + t.Errorf("%q: exit %d, %q %q", args, code, stdout.String(), stderr.String()) |
| + } |
| + if v, ok := os.LookupEnv(media.PayloadEnv); !ok || v != `{"v":2}` { |
| + t.Errorf("%q read the payload", args) |
| + } |
| + } |
| +} |
| + |
| // fakeTimerOS records what hostile-timer does. Nothing here signals a |
| // real process: the real kill(-1) would reach every process the user |
| // owns. |
| @@ -99,7 +218,8 @@ func TestDrillManyFiles(t *testing.T) { |
| 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 ") { |
| + if r.failed || !strings.HasPrefix(out.String(), "PASS many-files: the job failed unreadable in ") || |
| + !strings.Contains(out.String(), "; 100000 files were made; no child left; outputs reset\n") { |
| t.Fatalf("%s", out.String()) |
| } |
| if ents, err := os.ReadDir(scratch + "/out"); err != nil || len(ents) != 0 { |
| @@ -126,3 +246,38 @@ func TestDrillBadOutputsCommand(t *testing.T) { |
| t.Fatal("the payload variable is still set") |
| } |
| } |
| + |
| +// TestJudgeChildJob: fill-scratch and many-files pass only on their |
| +// evidence, with no child left and the outputs reset; each missing |
| +// piece is its own FAIL. |
| +func TestJudgeChildJob(t *testing.T) { |
| + fill, many := mediahandler.HostileFillScratch, mediahandler.HostileManyFiles |
| + full := mediahandler.DrillOutcome{Code: media.CodeEngineFailed, Exhausted: "ENOSPC", ScratchFull: true} |
| + files := mediahandler.DrillOutcome{Code: media.CodeUnreadable, Files: 100_000} |
| + with := func(o mediahandler.DrillOutcome, f func(*mediahandler.DrillOutcome)) mediahandler.DrillOutcome { |
| + f(&o) |
| + return o |
| + } |
| + for _, c := range []struct { |
| + name, kind string |
| + o mediahandler.DrillOutcome |
| + err error |
| + want string |
| + }{ |
| + {"fill passes", fill, full, nil, ""}, |
| + {"fill on EDQUOT passes", fill, with(full, func(o *mediahandler.DrillOutcome) { o.Exhausted = "EDQUOT" }), nil, ""}, |
| + {"no exhaustion seen", fill, with(full, func(o *mediahandler.DrillOutcome) { o.Exhausted = "" }), nil, "the child never met a full file system"}, |
| + {"scratch not full", fill, with(full, func(o *mediahandler.DrillOutcome) { o.ScratchFull = false }), nil, "the scratch did not read full"}, |
| + {"named but not engine_failed", fill, with(full, func(o *mediahandler.DrillOutcome) { o.Code = media.CodeUnreadable }), nil, "the job did not end engine_failed"}, |
| + {"a child left", fill, full, errors.New("a child outlived the cleanup"), "a child outlived the cleanup"}, |
| + {"not reset", fill, full, errors.New("the outputs were not reset: permission denied"), "the outputs were not reset: permission denied"}, |
| + {"many passes", many, files, nil, ""}, |
| + {"too few files", many, with(files, func(o *mediahandler.DrillOutcome) { o.Files = 12 }), nil, "the child made 12 files, not 100000"}, |
| + {"many not reset", many, files, errors.New("the outputs were not reset: x"), "the outputs were not reset: x"}, |
| + {"many wrong code", many, with(files, func(o *mediahandler.DrillOutcome) { o.Code = "" }), nil, "the job did not end unreadable"}, |
| + } { |
| + if got := judgeChildJob(c.kind, c.o, c.err); got != c.want { |
| + t.Errorf("%s: %q, want %q", c.name, got, c.want) |
| + } |
| + } |
| +} |
diff --git a/cmd/carlos-media/harden_linux.go b/cmd/carlos-media/harden_linux.go| new file mode 100644 |
| index 000000000..ae0cc2f3b |
| --- /dev/null |
| +++ b/cmd/carlos-media/harden_linux.go |
| @@ -0,0 +1,17 @@ |
| +//go:build linux |
| + |
| +package main |
| + |
| +import sysunix "golang.org/x/sys/unix" |
| + |
| +// notDumpable clears the process's dumpable flag (prctl |
| +// PR_SET_DUMPABLE 0; ledger ruling, plan 3 Task 7 fix 1). The kernel |
| +// then makes /proc/<pid>/environ, mem and the rest owned by root and |
| +// refuses ptrace by the same user, so a compromised ffmpeg running as |
| +// the codec's own user cannot read the payload (its presigned |
| +// transfers) from the handler's environment or memory. The flag is not |
| +// inherited across exec: the children the handler starts stay dumpable, |
| +// so the handler can still read their /proc entries and kill them. |
| +func notDumpable() error { |
| + return sysunix.Prctl(sysunix.PR_SET_DUMPABLE, 0, 0, 0, 0) |
| +} |
diff --git a/cmd/carlos-media/harden_other.go b/cmd/carlos-media/harden_other.go| new file mode 100644 |
| index 000000000..70b3b9677 |
| --- /dev/null |
| +++ b/cmd/carlos-media/harden_other.go |
| @@ -0,0 +1,7 @@ |
| +//go:build !linux |
| + |
| +package main |
| + |
| +// notDumpable has nothing to do where there is no /proc and no |
| +// conversion runs (the engine image is Linux). |
| +func notDumpable() error { return nil } |
diff --git a/cmd/carlos-media/main.go b/cmd/carlos-media/main.go| index c8cc842c6..240c76fac 100644 |
| --- a/cmd/carlos-media/main.go |
| +++ b/cmd/carlos-media/main.go |
| @@ -90,6 +90,9 @@ func codecCommand(rest []string, stderr io.Writer) int { |
| if len(rest) != 0 { |
| return media.ExitFailed |
| } |
| + if !hardened(stderr) { |
| + return media.ExitFailed |
| + } |
| payload := os.Getenv(media.PayloadEnv) |
| os.Unsetenv(media.PayloadEnv) |
| cfg := mediahandler.Config{Logf: func(format string, args ...any) { |
| @@ -115,6 +118,9 @@ func selftestCommand(rest []string, stdout, stderr io.Writer) int { |
| fmt.Fprintln(stderr, selftestUsage) |
| return exitUsage |
| } |
| + if !hardened(stderr) { |
| + return 1 |
| + } |
| cfg := mediahandler.Config{Logf: func(format string, args ...any) { |
| fmt.Fprintf(stderr, format+"\n", args...) |
| }} |
| @@ -125,6 +131,21 @@ func selftestCommand(rest []string, stdout, stderr io.Writer) int { |
| return 0 |
| } |
| +// harden is notDumpable; tests replace it to see it called. |
| +var harden = notDumpable |
| + |
| +// hardened makes the process non-dumpable before it reads a payload, |
| +// a drill input or anything a child could steal, and reports whether it |
| +// could. A process it could not harden stops: copy deck row |
| +// engine.harden.failed (pending Luna pass). |
| +func hardened(stderr io.Writer) bool { |
| + if err := harden(); err != nil { |
| + fmt.Fprintf(stderr, "carlos-media: cannot make the process non-dumpable: %v\n", err) |
| + return false |
| + } |
| + return true |
| +} |
| + |
| // 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/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index e483459d4..39f23cceb 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -609,7 +609,7 @@ or an output's name: never a credential, a URL or a header. `%s` and |
| | `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.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`; `poster.jpg is %dx%d, want %dx%d`; `video.mp4 does not probe: %s`; `video.mp4 is %s %dx%d (rotation %d, SAR %d:%d), want h264 %dx%d` (fix 1: as encoded, never scaled first); `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) | |
| @@ -619,11 +619,13 @@ or an output's name: never a credential, a URL or a header. `%s` and |
| | `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.child_job` | `PASS %s: the job failed %s in %s; %s; no child left; outputs reset` (the evidence: `the child met %s and the scratch read full`, ENOSPC or EDQUOT, or `%d files were made`); `FAIL %s: %s (job %s, in %s)`, the reason one of `the child never met a full file system`, `the scratch did not read full`, `the job did not end %s`, `the child made %d files, not 100000`, `a child outlived the cleanup`, `the outputs were not reset: %s`, `the scratch is unusable: %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, fix 1) | |
| +| `engine.harden.failed` | `carlos-media: cannot make the process non-dumpable: %s` (pending Luna pass; plan 3 Task 7 fix 1). The system's error; codec, selftest and the drills then exit 1 having read nothing | |
| | `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) | |
| +| `engine.drill.child` | `hostile child: exhausted: ENOSPC` or `EDQUOT` (on the child's stdout: the drill's evidence, fix 1), `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 | |
| +| `script.endpoint_drill.cleanup` | `cleaned %s`, `NOT CLEANED %s` (an obligation: `endpoint-policies`, `repository-policy`, `bucket`, `foreign-user`, `log-group`, `input`; and, fix 1, `NOT CLEANED state` when the state file is damaged) (pending Luna pass; plan 3 Task 7). On stdout | |
| +| `script.endpoint_drill.fix1` | `media-endpoint-drill: refusing to run with xtrace on: it would print the drill's secrets`; `media-endpoint-drill: refusing to run with BASH_XTRACEFD set: it would print the drill's secrets`; `media-endpoint-drill: the state file cannot be written; stopped before: %s` (the state line); `media-endpoint-drill: the state file cannot be written: %s`; `media-endpoint-drill: the state file in %s is damaged or incomplete; nothing was undone. Check the drill's resources by hand.`; `media-endpoint-drill: the bucket is there but this run cannot prove it made it; left as it is`, and the same for `the user` and `the log group`; `media-endpoint-drill: the repository policy is neither the saved one nor the drill's; left as it is`; and as `script.endpoint_drill.error`: `the dev profile does not answer`; `the dev profile is not the cluster's account`; `the foreign profile is the dev account: the drill needs an unrelated account`; `no run id`; `the bucket's run tag was not set`; `the bucket does not carry this run's tag`; `the log group does not carry this run's tag`; `the user's ARN or id is not the expected one`; `the user does not carry this run's tag`; `the repository policy is not the one set` (pending Luna pass; plan 3 Task 7 fix 1). On stderr | |
| +| `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 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/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md b/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md| index e77588706..3be430a28 100644 |
| --- a/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md |
| +++ b/docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md |
| @@ -65,7 +65,7 @@ Each step runs one or more tasks through `mediaspike run` and records the probe' |
| - [ ] **Step 1: Credentials.** `--command creds` on each class. Expected: none of the credential-bearing variables (`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`); `AWS_EXECUTION_ENV` and the region variables are recorded and allowed; `169.254.170.2` serves no credential; `169.254.169.254` unreachable; the v4 task metadata answers but holds no credential. |
| - [ ] **Step 2: Names and routes.** `dns` for the five allowed names and for `example.com`, `amazonaws.com`, `sts.eu-west-1.amazonaws.com`, `ecs.eu-west-1.amazonaws.com`; `net` to `1.1.1.1:443`, the dev console's private IP on 443 and another dev box's private IP on 22. Expected: only the allowed names resolve; every connection fails. An unsigned `GET` of a spike-bucket object: refused at the S3 endpoint. |
| -- [ ] **Step 3: The endpoint drill.** Run the endpoint drill exactly as plan 3 Task 7 defines it (registry token minted outside the VPC and passed in; the same four authenticated requests under the restrictive policies, AWS's full-access policy, and the restored policies) with the foreign user, on the video-short task definition. Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and the saved policies are back. Record the table, the policy swap's start and end times, and the cleanup lines; every one must read `cleaned`. If any reads `NOT CLEANED`, or the run was killed, run `cleanup <run dir>` until all are clean and tell Paul before Task 5. Causality comes from phase B, not from error text. |
| +- [ ] **Step 3: The endpoint drill.** Run the endpoint drill exactly as plan 3 Task 7 defines it (registry token minted outside the VPC and passed in; the same four authenticated requests under the restrictive policies, AWS's full-access policy, and the restored policies) with the foreign user, on the video-short task definition, passing `--subnets` and `--security-group` from the scratch root's outputs (the script's required flags since plan 3 Task 7: a Fargate `run-task` needs them, and the endpoints are found from the subnet's VPC). Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and the saved policies are back. Record the table, the policy swap's start and end times, and the cleanup lines; every one must read `cleaned`. If any reads `NOT CLEANED`, or the run was killed, run `cleanup <run dir>` until all are clean and tell Paul before Task 5. Causality comes from phase B, not from error text. |
| - [ ] **Step 4: Non-reuse and isolation.** Two tasks in sequence and two side by side with `--command marker` (writes its task ARN under `/scratch` and `/tmp`, reads for any other ARN, lists `/proc` for foreign PIDs). Expected: each sees only itself; distinct task ARNs and ENIs; and the codec, as `65534`, can create `/scratch/in`, `/scratch/out` and `/scratch/tmp` on the bind mount (record `stat /scratch`: owner, mode). |
| - [ ] **Step 5: Overrides, size, storage.** Twenty `grant` calls: record the longest token. A `run` with that token and a 512-byte key of 3-byte runes: record the override byte length and whether RunTask accepts it. `--storage 48`: accepted, and `df /scratch` in the task shows it. `--cpu 16384 --memory 32768` on the audio-short definition: accepted or refused (whether size can be set per run). A video-long run at 16 vCPU ARM64: placed, or the capacity error. |
| - [ ] **Step 6: Idempotency.** RunTask twice with one `clientToken` and the same body: the same task ARN. The same token with a different environment value: record the error code. |
diff --git a/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md b/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md| index 6105526ac..29905bf67 100644 |
| --- a/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md |
| +++ b/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md |
| @@ -166,8 +166,8 @@ Depends on plan 1 Task 3 Step 4: the muxer rules and the parser's accepted box s |
| **The endpoint drill (the one definition; plan 1 Task 4 Step 3 and rollout R3 both run it).** It proves that foreign credentials cannot use any of the four endpoints, by controls, never by error text. |
| - **The principal and its four requests.** A user in an unrelated account whose identity policy allows, and whose target resources admit: `s3:GetObject` on one object of a drill bucket; `ecr:GetAuthorizationToken`; the image pull actions on the engine's repository; `logs:CreateLogStream` and `logs:PutLogEvents` on the drill log group only (`arn:aws:logs:<region>:<foreign account>:log-group:<name>:*`), a group of its own account in the same region. The script provisions all of it (below). Then, outside the engine VPC (docs-t1, with that user's new key), it presigns the S3 GET (expiry 1 h), mints the user's ECR registry token with `GetAuthorizationToken`, creates the log stream, and writes the drill input `{"s3_get_url", "ecr_token", "ecr_manifest_url" (the engine image's manifest by digest on the `*.dkr.ecr` host), "region", "access_key_id", "secret_access_key", "log_group", "log_stream"}` to `<run dir>/input.json` (mode 0600), passed to the task in `CARLOS_MEDIA_DRILL` (never logged). |
| - **One pass** (`carlos-media drill endpoints`, inside a task on a media task definition with `command ["drill", "endpoints"]` on `codec`): the same four authenticated requests, each with a 20 s timeout: S3 gateway, `GET` of the presigned URL; ECR API, `GetAuthorizationToken` SigV4-signed in the task with the passed key; ECR Docker, `HEAD` of the manifest with `Authorization: Basic <ecr_token>`; Logs, `PutLogEvents` SigV4-signed with the passed key. It prints one line per endpoint, `<endpoint> ok` for a 2xx and `<endpoint> refused <status or "conn">` for anything else, and nothing else: no error text, no URL, no header. |
| -- **Provisioning, the three phases and cleanup are one script run.** `scripts/media-endpoint-drill.sh run --profile <dev profile> --foreign-profile <unrelated account's admin profile> --cluster <arn> --task-definition <arn> --repository <name> --bucket <drill bucket name>`, the operator's AWS CLI, every call through `${AWS:-aws}`. Its first act makes a run directory with `mktemp -d "$TMPDIR/media-endpoint-drill.XXXXXX"` and installs `trap cleanup EXIT INT TERM HUP`; only then does it create anything. Before each create it appends what it is about to create to `<run dir>/state` (names only, never a secret), so cleanup covers a create that half-happened. Steps: save the four endpoints' policies to the run directory; save the repository's existing policy (or note none); create the drill bucket, its one object and its bucket policy admitting the user; add the user's grant to the repository policy; in the foreign account create the log group, the user, its policy and its key; write `input.json`. Phase A, one pass under the saved policies: every endpoint must be `refused`. Replace all four with AWS's default full-access policy (`aws ec2 modify-vpc-endpoint --reset-policy`), then one pass every 60 s, at most 5: phase B passes when every endpoint is `ok`. Restore the saved policies, then one pass every 60 s, at most 5: phase C passes when every endpoint is `refused`. `carlos-media drill endpoints-verdict A B C` prints a table of endpoint by phase and exits 0 only when A and C are all `refused` and B all `ok`. A refusal is causal for an endpoint only because the identical request succeeded in phase B. |
| -- **`cleanup` runs on every exit** (success, a failed step, a failed verdict, a signal, an interrupted setup), each step idempotent, in this order: restore the four saved endpoint policies; put back the saved repository policy (or delete it if there was none); delete the bucket policy, the object and the bucket; in the foreign account delete the user's key, policy and user, then the log group; `rm -f <run dir>/input.json`. It then verifies, before returning: the four endpoint policies equal the saved ones byte for byte (`aws ec2 describe-vpc-endpoints`); the repository policy equals the saved one or is absent as it was; `aws s3api head-bucket` answers 404; `aws iam get-user` answers `NoSuchEntity`; `aws logs describe-log-groups --log-group-name-prefix <group>` lists nothing; `input.json` does not exist. It prints one line per obligation, `cleaned` or `NOT CLEANED <obligation>`, exits non-zero if any is not clean (whatever the drill's verdict), and removes the run directory only when all are clean. `scripts/media-endpoint-drill.sh cleanup <run dir>` runs the same cleanup from a kept `state` file, for the one exit a trap cannot catch (`SIGKILL`, a lost machine). |
| +- **Provisioning, the three phases and cleanup are one script run.** `scripts/media-endpoint-drill.sh run --profile <dev profile> --foreign-profile <unrelated account's admin profile> --cluster <arn> --task-definition <arn> --repository <name> --bucket <drill bucket name> --subnets <subnet,...> --security-group <tasks' security group>` (the subnets and group from the `carlos_media_engine` output: a Fargate `run-task` needs them, and the engine VPC, so its four endpoints, is found from the first subnet), the operator's AWS CLI, every call through `${AWS:-aws}`. It refuses to run with xtrace on. Before it makes anything it reads both profiles' identities: the dev profile must be the cluster's account and the foreign one another account. Its first act then makes a run directory with `mktemp -d "$TMPDIR/media-endpoint-drill.XXXXXX"` and installs the traps (EXIT runs cleanup; INT, TERM and HUP exit, which runs it); only then does it create anything. Before each AWS change it appends its intent to `<run dir>/state` (names only, never a secret; each line carries its own checksum and is read back before the change, and a line that cannot be written stops the run before the change); a create that succeeded and was verified to be this run's (a random run tag on the bucket, the log group and the user, and the user's ARN and UserId from the create's answer) is recorded as owned, and each deletion is recorded once made. Steps (fix round 1 order: a policy cannot name a user that does not exist yet): save the four endpoints' policies to the run directory; save the repository's existing policy (or note none); check the drill bucket does not exist, create it, tag it and put its one object; in the foreign account create the log group, the user, its policy and its key; then the bucket policy admitting the user and the user's grant in the repository policy; then, with the user's key alone (in aws's environment, never an argument), the presigned GET, the registry token and the log stream; write `input.json`. Phase A, one pass under the saved policies: every endpoint must be `refused`. Replace all four with AWS's default full-access policy (`aws ec2 modify-vpc-endpoint --reset-policy`), then one pass every 60 s, at most 5: phase B passes when every endpoint is `ok`. Restore the saved policies, then one pass every 60 s, at most 5: phase C passes when every endpoint is `refused`. `carlos-media drill endpoints-verdict A B C` prints a table of endpoint by phase and exits 0 only when A and C are all `refused` and B all `ok`. A refusal is causal for an endpoint only because the identical request succeeded in phase B. |
| +- **`cleanup` runs on every exit** (success, a failed step, a failed verdict, a signal, an interrupted setup), each step idempotent. It first reads the state file whole and refuses a truncated, garbled or misshapen one (`NOT CLEANED state`, nothing changed). It deletes a resource only while it still carries this run's tag (and, for the user, the UserId its create answered): a name collision, an untagged bucket or a resource replaced since is left alone and reported `NOT CLEANED` for the operator. In this order: restore the four saved endpoint policies; put back the saved repository policy (or delete it if there was none); delete the bucket policy, the object and the bucket; in the foreign account delete the user's key, policy and user, then the log group; `rm -f <run dir>/input.json`. It then verifies, before returning: the four endpoint policies equal the saved ones byte for byte (`aws ec2 describe-vpc-endpoints`); the repository policy equals the saved one or is absent as it was; `aws s3api head-bucket` answers 404; `aws iam get-user` answers `NoSuchEntity`; `aws logs describe-log-groups --log-group-name-prefix <group>` lists nothing; `input.json` does not exist. It prints one line per obligation, `cleaned` or `NOT CLEANED <obligation>`, exits non-zero if any is not clean (whatever the drill's verdict), and removes the run directory only when all are clean. `scripts/media-endpoint-drill.sh cleanup <run dir>` runs the same cleanup from a kept `state` file, for the one exit a trap cannot catch (`SIGKILL`, a lost machine). |
| - **Conversion stays off** until this drill passes: `CARLOS_MEDIA_ENGINE` is not set on a console of that deployment before then. |
| - [ ] **Step 1: Write the failing tests:** `TestCorpusEndsInNamedErrors` (each corpus file through `Run` with the fake ffprobe answering as the real one would for it: a named code from `HandlerCodes`, never a panic, never exit 0, and no request other than the source GET and the result PUT); `TestPlaylistStyleFileMakesNoRequest` (the `169.254.169.254` file: `unsupported_container`, ffmpeg never started, the test server saw one GET); `TestHostileChildrenFailOnlyTheirJob` (`fill-scratch`, `many-files`, `fork-setsid`, `ignore-term`: exit 1 with a named error within the test's 30 s, no stray process left); `TestBadOutputsUploadNothing`; `TestDrillCredsReportsAnEnvCredential` (a fake environment with `AWS_SECRET_ACCESS_KEY` set: `FAIL`; one with only `AWS_EXECUTION_ENV=AWS_ECS_FARGATE` and `AWS_REGION`: `PASS`); `TestDrillOutputHasNoSecrets`; `TestDrillEndpointsOnePass` (four `httptest` endpoints answering 403, 200, a closed port and 200: exactly the four lines `s3 refused 403`, `ecr-api ok`, `ecr-docker refused conn`, `logs ok`, and the ECR Docker request carried `Authorization: Basic <the passed token>` unchanged); `TestSigV4Vector` (AWS's published SigV4 test vector `get-vanilla`); `TestEndpointsVerdict` (A all refused, B all ok, C all refused: exit 0; any one cell otherwise: exit 1, naming the cell). `media_endpoint_drill_test.py` runs the script with `AWS` pointing at a fake `aws` (a Python script under the test's temporary directory that logs each call, keeps a fake state of endpoints, policies, bucket, user and log group, and fails on demand): `test_cleanup_after_each_failed_setup_step` (a failure injected at each create in turn: every obligation already begun is undone, the verification calls run, the script exits non-zero, `input.json` is gone and the endpoint policies equal the saved ones); `test_cleanup_after_failed_verdict` (phase B never `ok`: same obligations, non-zero exit); `test_cleanup_on_sigterm_mid_phase_b` (SIGTERM while the full-access policies are in place: they are restored and every resource deleted); `test_cleanup_reports_what_it_could_not_clean` (the fake refuses one delete: `NOT CLEANED` for that obligation, non-zero exit, the run directory and `state` kept); `test_cleanup_subcommand_from_state` (a `state` file from a killed run: `cleanup <run dir>` finishes the job). |
| @@ -310,16 +310,16 @@ Ask each time with the account, region, resources, cost, duration, traffic effec |
| ### R2: Dev infrastructure, with the door still off |
| - [ ] Ask Paul (profile `kass`, `eu-west-1`), including the endpoint drill's scope (Task 7), all of it created and removed by the drill script's one run in R3: in an unrelated account he names (with a profile of his allowed to create them), one IAM user and key whose policy allows `s3:GetObject` on the drill object, `ecr:GetAuthorizationToken`, the pull actions on the engine repository, and `logs:CreateLogStream` and `logs:PutLogEvents` on the drill log group only, plus that log group; in dev, a drill bucket with one object and a bucket policy admitting that user, and a grant in the engine repository's policy; and, for minutes, the four endpoint policies replaced by AWS's default full-access policy and then restored. In the dev root: `store_conversion = true` on the console's region-host; `media-engine` with `image_digest = ""`; apply. Push the image (`mediaimage push`), set `image_digest`, `image_built_at`, `image_ffmpeg`; apply. Do not set `CARLOS_MEDIA_ENGINE` yet. |
| -- [ ] Run `carlos-media selftest` once per class as a one-off task (`aws ecs run-task` with the class's task definition and `command ["selftest"]` on `codec`). Expected: every case `PASS`. |
| +- [ ] Run `carlos-media selftest` once per class as a one-off task (`aws ecs run-task` with the class's task definition, `command ["selftest", "video"]` on `codec` for a video-720p class or `["selftest", "audio"]` for an audio-aac one, and, on `deadline`, `CARLOS_MEDIA_DEADLINE_S=900` and `CARLOS_MEDIA_GRANT_EXPIRY=<now + 3600, Unix seconds>`: without both the deadline container exits 3 at once and stops the task, preflight F25). Expected: every case `PASS`. |
| ### R3: Dev activation gates (spec §5.5), before the door is on |
| -Each drill names its tool; record every result in `docs/superpowers/reviews/2026-11-16-media-conversion-dev-drills.md`. Every task here is started with `aws ecs run-task`; no console is involved. |
| +Each drill names its tool; record every result in `docs/superpowers/reviews/2026-11-16-media-conversion-dev-drills.md`. Every task here is started with `aws ecs run-task`; no console is involved. Every hand-run `run-task` here passes, on `deadline`, `CARLOS_MEDIA_DEADLINE_S` (900, or the value a step names) and `CARLOS_MEDIA_GRANT_EXPIRY` (now + 3600, Unix seconds), as R2's selftest does (preflight F25); the endpoint drill script passes both itself. |
| - [ ] `drill creds`, `drill dns`, `drill net <console private IP>` and `drill net <another box's private IP>`: all `PASS`. An unsigned S3 request from inside a task: refused at the endpoint. |
| -- [ ] The endpoint drill (Task 7's definition): `scripts/media-endpoint-drill.sh run --profile kass --foreign-profile <Paul's> --cluster <arn> --task-definition <video-720p/short revision> --repository <name> --bucket <drill bucket>`. Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and every cleanup line reads `cleaned`. Record the table and the cleanup lines. |
| +- [ ] The endpoint drill (Task 7's definition): `scripts/media-endpoint-drill.sh run --profile kass --foreign-profile <Paul's> --cluster <arn> --task-definition <video-720p/short revision> --repository <name> --bucket <drill bucket> --subnets <the output's subnets, comma-separated> --security-group <the output's security_group>`. Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and every cleanup line reads `cleaned`. Record the table and the cleanup lines. |
| - [ ] A revision with `deadline` made to start late (its image padded so its pull is slow): `codec` starts only after it. A revision whose `deadline` image digest does not exist: `codec` never runs. |
| -- [ ] A task running `drill hostile-timer` with `CARLOS_MEDIA_DEADLINE_S=180`: gone within 210 s, deadline exit 0, codec 137. |
| +- [ ] A task running `drill hostile-timer` with `CARLOS_MEDIA_DEADLINE_S=180` (and `CARLOS_MEDIA_GRANT_EXPIRY` now + 3600) on `deadline`: gone within 210 s, deadline exit 0, codec 137. |
| - [ ] If the drill's run printed any `NOT CLEANED` line or was killed, run `scripts/media-endpoint-drill.sh cleanup <run dir>` until every line reads `cleaned`, and tell Paul before going on. |
| - [ ] Only when every line above passed: set `CARLOS_STORE_CONVERSION=1` and `CARLOS_MEDIA_ENGINE=<output>` on the dev console through the roll restart. Check `carlos system media status`: configured, four gates `ok`, image age. A failure here stops the rollout and goes to Paul. |
diff --git a/internal/mediahandler/hostile_linux.go b/internal/mediahandler/hostile_linux.go| index 9d0bac040..43552965c 100644 |
| --- a/internal/mediahandler/hostile_linux.go |
| +++ b/internal/mediahandler/hostile_linux.go |
| @@ -13,6 +13,7 @@ import ( |
| "os" |
| "path/filepath" |
| "strconv" |
| + "strings" |
| "sync/atomic" |
| "syscall" |
| "time" |
| @@ -95,7 +96,9 @@ func fillScratch(dir string) int { |
| 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) { |
| + if errno := exhaustion(err); errno != "" { |
| + // The evidence, on stdout, which DrillEncode reads. |
| + fmt.Fprintln(os.Stdout, exhaustedPrefix+errno) |
| fmt.Fprintln(os.Stderr, "Error writing trailer: No space left on device") |
| return 1 |
| } |
| @@ -107,6 +110,22 @@ func fillScratch(dir string) int { |
| return hostileExitBroken |
| } |
| +// exhaustedPrefix begins the line HostileFillScratch prints on stdout |
| +// when a write meets a full file system, followed by the error's name. |
| +const exhaustedPrefix = "hostile child: exhausted: " |
| + |
| +// exhaustion names err when it is a full file system or quota: ENOSPC |
| +// or EDQUOT; "" otherwise. |
| +func exhaustion(err error) string { |
| + switch { |
| + case errors.Is(err, syscall.ENOSPC): |
| + return "ENOSPC" |
| + case errors.Is(err, syscall.EDQUOT): |
| + return "EDQUOT" |
| + } |
| + return "" |
| +} |
| + |
| // manyFiles makes manyFilesCount empty files in dir. |
| func manyFiles(dir string) int { |
| for i := range manyFilesCount { |
| @@ -123,29 +142,59 @@ func manyFiles(dir string) int { |
| return 1 |
| } |
| +// DrillOutcome is what DrillEncode saw, apart from its cleanup's |
| +// errors: the job code the handler names for the child's run ("" for a |
| +// clean exit); Exhausted, the error a fill-scratch child reported |
| +// meeting (ENOSPC or EDQUOT; "" when it reported none); ScratchFull, |
| +// whether the scratch read full after the child (diskIsFull's rule); |
| +// and Files, the entries left in <scratch>/out, counted before the |
| +// reset. |
| +type DrillOutcome struct { |
| + Code, Exhausted string |
| + ScratchFull bool |
| + Files int |
| +} |
| + |
| +// drillOutputBytes is how much of a drill child's stdout is kept. |
| +const drillOutputBytes = 4 << 10 |
| + |
| // 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 { |
| +// mapping, the scratch-full check included). It answers what it saw, |
| +// and separately its cleanup's errors: a child left alive |
| +// (childrenDead), or <scratch>/out and tmp not emptied again |
| +// (resetOutputs). `carlos-media drill fill-scratch|many-files` run the |
| +// binary itself as the child, on HostileChild; the drill decides from |
| +// both whether to pass. |
| +func DrillEncode(ctx context.Context, cfg Config, binary string, args func(outDir string) []string) (DrillOutcome, error) { |
| cfg = cfg.withDefaults() |
| - cfg.FFmpeg = binary |
| if err := prepareScratch(cfg.Scratch); err != nil { |
| - cfg.Logf("codec: scratch directory unusable: %v", err) |
| - return media.CodeEngineFailed |
| + return DrillOutcome{}, fmt.Errorf("the scratch is unusable: %s", sysReason(err)) |
| + } |
| + out := filepath.Join(cfg.Scratch, "out") |
| + stdout := &capBuffer{max: drillOutputBytes} |
| + tail, err := runChildTo(ctx, cfg, binary, args(out), filepath.Join(cfg.Scratch, "tmp"), stdout) |
| + err = ffmpegOutcome(ctx, cfg, "drill", err, tail, true) |
| + var o DrillOutcome |
| + o.Code = codeOfErr(err) |
| + for _, line := range strings.Split(stdout.buf.String(), "\n") { |
| + if errno, ok := strings.CutPrefix(line, exhaustedPrefix); ok && (errno == "ENOSPC" || errno == "EDQUOT") { |
| + o.Exhausted = errno |
| + } |
| + } |
| + o.ScratchFull = cfg.diskFull(cfg.Scratch) |
| + if ents, rerr := os.ReadDir(out); rerr == nil { |
| + o.Files = len(ents) |
| } |
| - err := encode(ctx, cfg, "drill", args(filepath.Join(cfg.Scratch, "out"))) |
| + var cleanupErr error |
| if derr := childrenDead(cfg); derr != nil { |
| - err = derr |
| + cleanupErr = errors.New("a child outlived the cleanup") |
| } |
| - if rerr := resetOutputs(cfg.Scratch); rerr != nil && err == nil { |
| - err = rerr |
| + if rerr := resetOutputs(cfg.Scratch); rerr != nil { |
| + cleanupErr = errors.Join(cleanupErr, fmt.Errorf("the outputs were not reset: %s", sysReason(rerr))) |
| } |
| - return codeOfErr(err) |
| + return o, cleanupErr |
| } |
| // codeOfErr is err's job code: "" for nil, the jobError's code, or |
diff --git a/internal/mediahandler/hostile_test.go b/internal/mediahandler/hostile_test.go| index 557d66007..0c6285f04 100644 |
| --- a/internal/mediahandler/hostile_test.go |
| +++ b/internal/mediahandler/hostile_test.go |
| @@ -17,6 +17,7 @@ import ( |
| "syscall" |
| "testing" |
| "time" |
| + "unsafe" |
| "golang.org/x/sys/unix" |
| @@ -287,15 +288,19 @@ func TestPlaylistStyleFileMakesNoRequest(t *testing.T) { |
| // 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) { |
| +// inNamespace reruns t's own test (name is t.Name(), a subtest's |
| +// included) 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 test skipped there. |
| +func inNamespace(t *testing.T) { |
| 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") |
| + var run []string |
| + for _, part := range strings.Split(t.Name(), "/") { |
| + run = append(run, "^"+part+"$") |
| + } |
| + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run="+strings.Join(run, "/"), "-test.count=1", "-test.v") |
| cmd.Env = append(os.Environ(), nsEnv+"=1") |
| cmd.SysProcAttr = &syscall.SysProcAttr{ |
| Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNS, |
| @@ -310,9 +315,9 @@ func inNamespace(t *testing.T, subtest string) { |
| } |
| err := cmd.Wait() |
| switch { |
| - case strings.Contains(out.String(), "--- SKIP: TestHostileChildrenFailOnlyTheirJob/"+subtest): |
| + case strings.Contains(out.String(), "--- SKIP: "+t.Name()): |
| t.Skipf("skipped in the namespace:\n%s", out.String()) |
| - case err != nil || !strings.Contains(out.String(), "--- PASS: TestHostileChildrenFailOnlyTheirJob/"+subtest): |
| + case err != nil || !strings.Contains(out.String(), "--- PASS: "+t.Name()): |
| t.Fatalf("in the namespace: %v\n%s", err, out.String()) |
| } |
| t.Logf("in the namespace:\n%s", out.String()) |
| @@ -389,7 +394,7 @@ func TestHostileChildrenFailOnlyTheirJob(t *testing.T) { |
| } { |
| t.Run(c.scenario, func(t *testing.T) { |
| if c.scenario == HostileFillScratch && os.Getenv(nsEnv) == "" { |
| - inNamespace(t, c.scenario) |
| + inNamespace(t) |
| return |
| } |
| h, p, cfg, record := runJobSetup(t, media.PresetVideo720p, c.scenario) |
| @@ -588,3 +593,217 @@ func readCorpusF(f *testing.F, name string) []byte { |
| } |
| return b |
| } |
| + |
| +func init() { |
| + // hostile-direct is the drill's own child: HostileChild with the |
| + // kind and directory it is given (DrillEncode's arguments). |
| + fakeScenarios["hostile-direct"] = func(args []string) int { return HostileChild(args[0], args[1]) } |
| + // unremovable leaves a directory in out that cannot be emptied (read |
| + // only), and exits 1. |
| + fakeScenarios["unremovable"] = func(args []string) int { |
| + d := filepath.Join(args[1], "locked") |
| + if os.Mkdir(d, 0o700) != nil || os.WriteFile(filepath.Join(d, "f"), []byte("x"), 0o600) != nil || os.Chmod(d, 0o500) != nil { |
| + return hostileExitBroken |
| + } |
| + return 1 |
| + } |
| +} |
| + |
| +// drillConfig is a Config whose child is the fake running scenario, |
| +// with an empty scratch for DrillEncode to prepare. |
| +func drillConfig(t *testing.T, scenario, scratch string) Config { |
| + t.Helper() |
| + cfg, _ := fakeConfig(t, scenario) |
| + cfg.Scratch = scratch |
| + return cfg |
| +} |
| + |
| +func drillArgs(kind string) func(string) []string { |
| + return func(out string) []string { return []string{kind, out} } |
| +} |
| + |
| +// TestDrillEncodeEvidence: DrillEncode answers what it saw apart from |
| +// its cleanup's errors. many-files: the hundred thousand files counted |
| +// and unreadable; a child that only fails: no exhaustion reported; a |
| +// child that leaves an undeletable directory: the reset's error, never |
| +// swallowed. |
| +func TestDrillEncodeEvidence(t *testing.T) { |
| + needChildren(t) |
| + ctx := context.Background() |
| + o, err := DrillEncode(ctx, drillConfig(t, "hostile-direct", t.TempDir()), fakeBinary(t), drillArgs(HostileManyFiles)) |
| + if err != nil || o.Code != media.CodeUnreadable || o.Files != manyFilesCount || o.Exhausted != "" { |
| + t.Fatalf("many-files: %+v, %v", o, err) |
| + } |
| + o, err = DrillEncode(ctx, drillConfig(t, "fail", t.TempDir()), fakeBinary(t), drillArgs(HostileFillScratch)) |
| + if err != nil || o.Exhausted != "" || o.ScratchFull || o.Code != media.CodeUnreadable { |
| + t.Fatalf("a failing child: %+v, %v", o, err) |
| + } |
| + scratch := t.TempDir() |
| + t.Cleanup(func() { _ = os.Chmod(filepath.Join(scratch, "out", "locked"), 0o700) }) |
| + o, err = DrillEncode(ctx, drillConfig(t, "unremovable", scratch), fakeBinary(t), drillArgs("x")) |
| + if err == nil || !strings.Contains(err.Error(), "the outputs were not reset") || o.Code != media.CodeUnreadable { |
| + t.Fatalf("an undeletable output: %+v, %v", o, err) |
| + } |
| +} |
| + |
| +// TestDrillEncodeFillsTheScratch: on a small tmpfs (in a user and mount |
| +// namespace; skipped where those are not allowed), the fill-scratch |
| +// child reports ENOSPC, the scratch reads full, the job is |
| +// engine_failed, and the reset empties it again. |
| +func TestDrillEncodeFillsTheScratch(t *testing.T) { |
| + needChildren(t) |
| + if os.Getenv(nsEnv) == "" { |
| + inNamespace(t) |
| + return |
| + } |
| + scratch := smallTmpfs(t) |
| + o, err := DrillEncode(context.Background(), drillConfig(t, "hostile-direct", scratch), fakeBinary(t), drillArgs(HostileFillScratch)) |
| + if err != nil || o.Exhausted != "ENOSPC" || !o.ScratchFull || o.Code != media.CodeEngineFailed { |
| + t.Fatalf("fill-scratch: %+v, %v", o, err) |
| + } |
| + if scratchFull(scratch) { |
| + t.Fatal("the reset left the scratch full") |
| + } |
| +} |
| + |
| +// aliasDref rewrites an MP4 whose moov is its last top-level box so that |
| +// every track's dref is one Mac alias entry whose absolute path is path: |
| +// what ffmpeg's mov demuxer opens as the track's data when external |
| +// references are on. The samples' offsets do not move. |
| +func aliasDref(t *testing.T, mp4 []byte, path string) []byte { |
| + t.Helper() |
| + p := []byte(path) |
| + if len(p)%2 == 1 { |
| + p = append(p, 0) |
| + } |
| + be16 := func(v int) []byte { return []byte{byte(v >> 8), byte(v)} } |
| + be32 := func(v int) []byte { return []byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)} } |
| + body := make([]byte, 0, 256) |
| + body = append(body, 0, 0, 0, 0) // version, flags |
| + body = append(body, make([]byte, 10)...) // record header |
| + body = append(body, 0) // volume name length |
| + body = append(body, make([]byte, 27)...) |
| + body = append(body, make([]byte, 12)...) |
| + body = append(body, 6) |
| + body = append(body, append([]byte("canary"), make([]byte, 57)...)...) |
| + body = append(body, make([]byte, 16)...) |
| + body = append(body, 0xff, 0xff, 0xff, 0xff) // nlvl_from, nlvl_to: -1 |
| + body = append(body, make([]byte, 16)...) |
| + body = append(body, be16(2)...) // type 2: absolute path |
| + body = append(body, be16(len(path))...) |
| + body = append(body, p...) |
| + body = append(body, 0xff, 0xff, 0, 0) // end |
| + entry := append(append(be32(8+len(body)), "alis"...), body...) |
| + containers := map[string]bool{"moov": true, "trak": true, "mdia": true, "minf": true, "dinf": true} |
| + var walk func(b []byte) []byte |
| + walk = func(b []byte) []byte { |
| + var out []byte |
| + for off := 0; off+8 <= len(b); { |
| + size := int(b[off])<<24 | int(b[off+1])<<16 | int(b[off+2])<<8 | int(b[off+3]) |
| + typ := string(b[off+4 : off+8]) |
| + if size < 8 || off+size > len(b) { |
| + t.Fatalf("box %q at %d has size %d", typ, off, size) |
| + } |
| + inner := b[off+8 : off+size] |
| + switch { |
| + case containers[typ]: |
| + inner = walk(inner) |
| + case typ == "dref": |
| + inner = append(append(append([]byte(nil), inner[:4]...), be32(1)...), entry...) |
| + } |
| + out = append(append(append(out, be32(8+len(inner))...), typ...), inner...) |
| + off += size |
| + } |
| + return out |
| + } |
| + for off := 0; off+8 <= len(mp4); { |
| + size := int(mp4[off])<<24 | int(mp4[off+1])<<16 | int(mp4[off+2])<<8 | int(mp4[off+3]) |
| + if string(mp4[off+4:off+8]) == "moov" { |
| + if off+size != len(mp4) { |
| + t.Fatal("moov is not the last box") |
| + } |
| + return append(append([]byte(nil), mp4[:off]...), walk(mp4[off:])...) |
| + } |
| + off += size |
| + } |
| + t.Fatal("no moov") |
| + return nil |
| +} |
| + |
| +// watchOpens watches path for any open or read, and answers a function |
| +// that reports how many happened since. |
| +func watchOpens(t *testing.T, path string) func() int { |
| + t.Helper() |
| + fd, err := unix.InotifyInit1(unix.IN_NONBLOCK | unix.IN_CLOEXEC) |
| + if err != nil { |
| + t.Skipf("no inotify: %v", err) |
| + } |
| + t.Cleanup(func() { unix.Close(fd) }) |
| + if _, err := unix.InotifyAddWatch(fd, path, unix.IN_OPEN|unix.IN_ACCESS); err != nil { |
| + t.Fatal(err) |
| + } |
| + return func() int { |
| + n := 0 |
| + buf := make([]byte, 64<<10) |
| + for { |
| + m, err := unix.Read(fd, buf) |
| + if m <= 0 || err != nil { |
| + return n |
| + } |
| + for off := 0; off+unix.SizeofInotifyEvent <= m; { |
| + ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off])) |
| + if ev.Mask&(unix.IN_OPEN|unix.IN_ACCESS) != 0 { |
| + n++ |
| + } |
| + off += unix.SizeofInotifyEvent + int(ev.Len) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestRealExternalReferenceIsNeverOpened: an MP4 whose tracks name a |
| +// canary file this test made, by absolute path, goes through Run under |
| +// both presets on the real ffprobe and ffmpeg (skipped without them): |
| +// it ends in a named error and the canary is never opened (inotify). |
| +// The positive control: the same file through the same ffprobe with |
| +// external references switched on opens the canary, so the watch sees |
| +// what it is looking for. |
| +func TestRealExternalReferenceIsNeverOpened(t *testing.T) { |
| + real := realConfig(t) |
| + canary := filepath.Join(t.TempDir(), "canary.bin") |
| + base := readCorpus(t, "dref-alis-etc-passwd.mp4") |
| + if err := os.WriteFile(canary, base, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + src := aliasDref(t, base, canary) |
| + if !bytes.Contains(src, []byte(canary)) || bytes.Contains(src, []byte("/etc/passwd")) { |
| + t.Fatal("the fixture does not name the canary alone") |
| + } |
| + opens := watchOpens(t, canary) |
| + for _, preset := range []string{media.PresetVideo720p, media.PresetAudioAAC} { |
| + h := newHarness(t) |
| + p := h.s.payload(t, preset, src, 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("%s: Run = %d, want 1; logs %q", preset, code, h.Logs()) |
| + } |
| + wantOnlyResult(t, h, preset, media.CodeUnreadable) |
| + if n := opens(); n != 0 { |
| + t.Fatalf("%s: the canary was opened or read %d times", preset, n) |
| + } |
| + } |
| + |
| + path := filepath.Join(t.TempDir(), "source.mp4") |
| + if err := os.WriteFile(path, src, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd := exec.Command(real.FFprobe, "-hide_banner", "-loglevel", "error", "-f", "mov", "-enable_drefs", "1", |
| + "-use_absolute_path", "1", "-show_entries", "stream=index", "-of", "csv", "-i", path) |
| + cmd.Env = append(os.Environ(), real.extraEnv...) |
| + out, _ := cmd.CombinedOutput() |
| + if n := opens(); n == 0 { |
| + t.Fatalf("the positive control: ffprobe with external references on did not open the canary:\n%s", out) |
| + } |
| +} |
diff --git a/internal/mediahandler/selftest.go b/internal/mediahandler/selftest.go| index 9c5092cec..908942263 100644 |
| --- a/internal/mediahandler/selftest.go |
| +++ b/internal/mediahandler/selftest.go |
| @@ -9,6 +9,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "image/jpeg" |
| "io" |
| "math" |
| "net" |
| @@ -280,9 +281,9 @@ func checkSelftestOutputs(store *selftestStore, exec string, r media.Result, dir |
| 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. |
| +// checkSelftestVideo: the result's dimensions for video.mp4 and the |
| +// poster, video.mp4 as ffprobe reads it, and the poster as its JPEG |
| +// header says, are all targetSize of the source (checkVideoGeometry). |
| 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 { |
| @@ -290,15 +291,30 @@ func checkSelftestVideo(ctx context.Context, cfg Config, store *selftestStore, e |
| 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 checkVideoGeometry(w, h, out, store.object(exec, "poster.jpg")) |
| +} |
| + |
| +// checkVideoGeometry holds the encoded outputs to w x h exactly, as |
| +// encoded: video.mp4 is h264 of that size with no rotation left to |
| +// apply and square pixels (nothing normalised first: a 1920x1080 output |
| +// is a FAIL, not "1280x720 once scaled"), and the poster is a JPEG whose |
| +// own header gives that size. |
| +func checkVideoGeometry(w, h int, out probeFacts, poster []byte) error { |
| + if out.VideoCodec != "h264" || out.Width != w || out.Height != h || out.Rotation != 0 || |
| + (out.SARNum != 0 && out.SARNum != out.SARDen) { |
| + return fmt.Errorf("video.mp4 is %s %dx%d (rotation %d, SAR %d:%d), want h264 %dx%d", out.VideoCodec, out.Width, out.Height, |
| + out.Rotation, out.SARNum, out.SARDen, w, h) |
| + } |
| + pc, err := jpeg.DecodeConfig(bytes.NewReader(poster)) |
| + if err != nil { |
| + return errors.New("poster.jpg is not a JPEG") |
| + } |
| + if pc.Width != w || pc.Height != h { |
| + return fmt.Errorf("poster.jpg is %dx%d, want %dx%d", pc.Width, pc.Height, w, h) |
| } |
| return nil |
| } |
diff --git a/internal/mediahandler/selftest_test.go b/internal/mediahandler/selftest_test.go| index a8c740ec5..f59046fa3 100644 |
| --- a/internal/mediahandler/selftest_test.go |
| +++ b/internal/mediahandler/selftest_test.go |
| @@ -5,6 +5,8 @@ package mediahandler |
| import ( |
| "bytes" |
| "context" |
| + "image" |
| + "image/jpeg" |
| "net/http" |
| "strings" |
| "testing" |
| @@ -122,3 +124,41 @@ func TestSelftestStoreHoldsThePresignedContract(t *testing.T) { |
| t.Fatalf("problems %q", s.problems()) |
| } |
| } |
| + |
| +// jpegOf is a w x h JPEG. |
| +func jpegOf(t *testing.T, w, h int) []byte { |
| + t.Helper() |
| + var b bytes.Buffer |
| + if err := jpeg.Encode(&b, image.NewGray(image.Rect(0, 0, w, h)), nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.Bytes() |
| +} |
| + |
| +// TestCheckVideoGeometry: the selftest holds the outputs to the target |
| +// size as encoded. An oversized 1920x1080 video, or poster, FAILs; so |
| +// do a rotation left to apply, non-square pixels, a codec other than |
| +// h264 and a poster that is not a JPEG. |
| +func TestCheckVideoGeometry(t *testing.T) { |
| + ok := probeFacts{VideoCodec: "h264", Width: 1280, Height: 720, SARNum: 1, SARDen: 1} |
| + good := jpegOf(t, 1280, 720) |
| + if err := checkVideoGeometry(1280, 720, ok, good); err != nil { |
| + t.Fatalf("the right size: %v", err) |
| + } |
| + with := func(f func(*probeFacts)) probeFacts { o := ok; f(&o); return o } |
| + for name, c := range map[string]struct { |
| + out probeFacts |
| + poster []byte |
| + }{ |
| + "an oversized 1920x1080 video": {with(func(o *probeFacts) { o.Width, o.Height = 1920, 1080 }), good}, |
| + "an oversized 1920x1080 poster": {ok, jpegOf(t, 1920, 1080)}, |
| + "a rotation left to apply": {with(func(o *probeFacts) { o.Width, o.Height, o.Rotation = 720, 1280, -90 }), good}, |
| + "non-square pixels": {with(func(o *probeFacts) { o.SARNum, o.SARDen = 4, 3 }), good}, |
| + "not h264": {with(func(o *probeFacts) { o.VideoCodec = "hevc" }), good}, |
| + "a poster that is no JPEG": {ok, []byte{0xff, 0xd8, 0xff, 0xe0, 0, 0}}, |
| + } { |
| + if err := checkVideoGeometry(1280, 720, c.out, c.poster); err == nil { |
| + t.Errorf("%s passed", name) |
| + } |
| + } |
| +} |
diff --git a/scripts/media-endpoint-drill.sh b/scripts/media-endpoint-drill.sh| index 1614895f2..6d9d6efef 100755 |
| --- a/scripts/media-endpoint-drill.sh |
| +++ b/scripts/media-endpoint-drill.sh |
| @@ -22,22 +22,57 @@ |
| # policies (phase C: every endpoint must refuse again). |
| # `carlos-media drill endpoints-verdict` prints the table and decides. |
| # |
| +# Before anything is made, both profiles' identities are read: the dev |
| +# profile must be the cluster's account and the foreign one another. |
| +# |
| +# The state file (<run dir>/state) is the recovery record. Each line is |
| +# "<key> <fields…> <cksum of the rest>", names only, never a secret. |
| +# Every AWS change is preceded by its intent ("creating bucket …"), and |
| +# the line is read back before the change is made: a state that cannot |
| +# be written stops the run before the change. A create that succeeded |
| +# and was verified to be this run's (a user's ARN and UserId from the |
| +# create's own answer and its run tag; the bucket's and log group's run |
| +# tag) is recorded as "own …"; every deletion is recorded after it is |
| +# made, and never made again. Cleanup deletes a resource only while it |
| +# is still verifiably this run's: it carries the run's random tag (which |
| +# only this run writes), and a user also the UserId its create |
| +# answered. An attempted create that cannot be proved this run's (a |
| +# name collision, an untagged bucket) and a resource replaced since are |
| +# left alone and reported NOT CLEANED for the operator. A state file whose lines are truncated, |
| +# garbled or out of shape is refused whole: cleanup changes nothing and |
| +# reports "NOT CLEANED state". |
| +# |
| # 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). |
| +# before anything is created, and on every exit (success, a failed |
| +# step, a failed verdict, a signal) cleanup restores the endpoint and |
| +# repository policies, deletes what this run owns, removes input.json, |
| +# verifies each obligation, and prints "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). |
| +# |
| +# Secrets (the user's key, the registry token, the presigned URL) never |
| +# reach an argument list: the key goes to aws through its environment, |
| +# exported inside a subshell, and the rest is written by builtins to |
| +# files of the run directory. The script refuses to run with xtrace. |
| # |
| # 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). |
| +# MEDIA_DRILL_LOG_WAIT shorten the waits; MEDIA_DRILL_FAIL_RECORD makes |
| +# the state line starting with it fail to be written (it can only stop a |
| +# run). CARLOS_MEDIA is the command that runs carlos-media (default: |
| +# carlos-media on PATH, else `go run` of cmd/carlos-media in this |
| +# checkout). |
| + |
| +# Tracing would print the secrets: refuse it before anything else. |
| +case "$-" in |
| + *x*) echo "media-endpoint-drill: refusing to run with xtrace on: it would print the drill's secrets" >&2; exit 2 ;; |
| +esac |
| +if [ -n "${BASH_XTRACEFD:-}" ]; then |
| + echo "media-endpoint-drill: refusing to run with BASH_XTRACEFD set: it would print the drill's secrets" >&2 |
| + exit 2 |
| +fi |
| +set +x |
| set -uo pipefail |
| umask 077 |
| @@ -52,6 +87,7 @@ endpoints=(s3 ecr-api ecr-docker logs) |
| object_key="drill-object" |
| user_policy="carlos-media-endpoint-drill" |
| log_stream="drill" |
| +run_tag="carlos-media-drill-run" |
| say() { printf 'media-endpoint-drill: %s\n' "$*" >&2; } |
| die() { say "$*"; exit 1; } |
| @@ -68,20 +104,129 @@ 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; } |
| +# The state, in memory: every line read back from the file, its sum |
| +# taken off. |
| +state_lines=() |
| + |
| +# line_sum is the cksum of a state line's content. |
| +line_sum() { |
| + local s |
| + s="$(printf '%s' "$1" | cksum)" || return 1 |
| + printf '%s' "${s%% *}" |
| +} |
| + |
| +# write_state appends one line to the state file and reads it back; |
| +# false if either fails, or the test hook names the line. |
| +write_state() { |
| + local line="$*" sum |
| + if [ -n "${MEDIA_DRILL_FAIL_RECORD:-}" ] && [[ "$line" == "$MEDIA_DRILL_FAIL_RECORD"* ]]; then |
| + return 1 |
| + fi |
| + sum="$(line_sum "$line")" || return 1 |
| + printf '%s %s\n' "$line" "$sum" >>"$rundir/state" 2>/dev/null || return 1 |
| + [ "$(tail -n 1 "$rundir/state" 2>/dev/null)" = "$line $sum" ] || return 1 |
| + state_lines+=("$line") |
| +} |
| + |
| +# record writes a state line before the change it announces, and stops |
| +# the run, before that change, when it cannot. |
| +record() { write_state "$@" || die "the state file cannot be written; stopped before: $*"; } |
| + |
| +# note records what cleanup did; a failure is reported, not fatal (the |
| +# verification still decides). |
| +note() { write_state "$@" || say "the state file cannot be written: $*"; } |
| + |
| +# recorded is true when the state has the line exactly. |
| +recorded() { |
| + local l |
| + for l in "${state_lines[@]}"; do |
| + [ "$l" = "$*" ] && return 0 |
| + done |
| + return 1 |
| +} |
| + |
| # state_value prints the value of the first "<key> <value>" line. |
| -state_value() { awk -v k="$1" '$1 == k { sub("^[^ ]+ ", ""); print; exit }' "$rundir/state"; } |
| +state_value() { |
| + local l |
| + for l in "${state_lines[@]}"; do |
| + if [ "${l%% *}" = "$1" ] && [ "$l" != "$1" ]; then |
| + printf '%s' "${l#* }" |
| + return 0 |
| + fi |
| + done |
| + return 1 |
| +} |
| + |
| +# state_keys prints the second field of every "<key> …" line. |
| +state_keys() { |
| + local l |
| + for l in "${state_lines[@]}"; do |
| + [ "${l%% *}" = "$1" ] && printf '%s\n' "${l#* }" |
| + done |
| +} |
| + |
| +# read_state_whole reads and checks the state file whole: every line |
| +# ends with a newline and its own sum, the first is the header, every |
| +# other has a known key and that key's shape, and the names cleanup acts |
| +# on are each there exactly once. False, with nothing to be trusted, |
| +# otherwise: cleanup then changes nothing. |
| +read_state_whole() { |
| + local f="$rundir/state" |
| + [ -s "$f" ] && [ -z "$(tail -c 1 "$f")" ] || return 1 |
| + state_lines=() |
| + local line content sum key n=0 |
| + while IFS= read -r line; do |
| + content="${line% *}" |
| + sum="${line##* }" |
| + [ "$content" != "$line" ] && [[ "$sum" =~ ^[0-9]+$ ]] || return 1 |
| + [ "$(line_sum "$content")" = "$sum" ] || return 1 |
| + key="${content%% *}" |
| + if [ "$n" = 0 ]; then |
| + [ "$content" = "drill-state 1" ] || return 1 |
| + else |
| + state_shape "$key" "$content" || return 1 |
| + fi |
| + state_lines+=("$content") |
| + n=$((n + 1)) |
| + done <"$f" |
| + for key in run profile foreign-profile region cluster repository bucket user log-group; do |
| + state_value "$key" >/dev/null || return 1 |
| + [ "$(state_keys "$key" | wc -l)" = 1 ] || return 1 |
| + done |
| + return 0 |
| +} |
| + |
| +# state_shape is true when content is a well-formed line for key. |
| +state_shape() { |
| + local key="$1" content="$2" |
| + case "$key" in |
| + run | profile | foreign-profile | region | cluster | repository | bucket | user | log-group | dev-account | foreign-account) |
| + [[ "$content" =~ ^[a-z-]+\ [A-Za-z0-9._:/@+=,-]+$ ]] ;; |
| + endpoint) [[ "$content" =~ ^endpoint\ (s3|ecr-api|ecr-docker|logs)\ vpce-[0-9a-z]+$ ]] ;; |
| + repo-policy) [[ "$content" =~ ^repo-policy\ (saved|none)$ ]] ;; |
| + creating | created | deleted) |
| + [[ "$content" =~ ^[a-z]+\ (bucket|object|bucket-policy|log-group|user|user-policy|log-stream|access-key(\ [A-Z0-9]+)?)$ ]] ;; |
| + own) [[ "$content" =~ ^own\ (bucket|log-group|repo-policy|user\ [A-Z0-9]+)$ ]] ;; |
| + changing | restored) [[ "$content" =~ ^[a-z]+\ (repo-policy|endpoints)$ ]] ;; |
| + opening) [ "$content" = "opening endpoints" ] ;; |
| + restoring) [ "$content" = "restoring endpoints" ] ;; |
| + running) [ "$content" = "running task" ] ;; |
| + task) [[ "$content" =~ ^task\ arn:aws:ecs:[a-z0-9-]+:[0-9]{12}:task/[A-Za-z0-9_/-]+$ ]] ;; |
| + *) return 1 ;; |
| + esac |
| +} |
| 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" "$@" |
| -} |
| +# as_user runs aws with the drill user's key alone, outside the VPC. The |
| +# key is exported inside this subshell, so it is in aws's environment and |
| +# never in an argument list. |
| +as_user() ( |
| + unset AWS_PROFILE AWS_DEFAULT_PROFILE AWS_SESSION_TOKEN AWS_SECURITY_TOKEN |
| + export AWS_ACCESS_KEY_ID="$user_key_id" |
| + export AWS_SECRET_ACCESS_KEY="$user_secret" |
| + exec "$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). |
| @@ -123,12 +268,28 @@ pause() { |
| # no backslash, no control character. |
| safe() { [[ -n "$1" && "$1" != *[\"\\]* && "$1" != *[[:cntrl:]]* ]]; } |
| +# Ownership: each is true only when the resource is there now and |
| +# carries this run's tag (and, for the user, the UserId its create |
| +# answered). |
| +bucket_tag() { dev s3api get-bucket-tagging --bucket "$bucket" --query "TagSet[?Key=='$run_tag'].Value | [0]" --output text 2>/dev/null; } |
| +bucket_is_ours() { [ "$(bucket_tag)" = "$run_id" ]; } |
| +log_group_is_ours() { |
| + [ "$(foreign logs list-tags-log-group --log-group-name "$log_group" --query "tags.\"$run_tag\"" --output text 2>/dev/null)" = "$run_id" ] |
| +} |
| +user_is_ours() { |
| + local want_id="$1" |
| + [ "$(foreign iam list-user-tags --user-name "$user" --query "Tags[?Key=='$run_tag'].Value | [0]" --output text 2>/dev/null)" = "$run_id" ] || return 1 |
| + [ -z "$want_id" ] || [ "$(foreign iam get-user --user-name "$user" --query User.UserId --output text 2>/dev/null)" = "$want_id" ] |
| +} |
| + |
| bg_pid="" |
| cleaning="" |
| +run_id="" |
| +made_rundir="" |
| -# 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 is the EXIT trap and the cleanup subcommand: read and check |
| +# the state, undo what this run owns, verify each obligation, report, |
| +# and set the exit. $1 is the status the script was leaving with. |
| cleanup() { |
| local status="${1:-0}" |
| [ -n "$cleaning" ] && return |
| @@ -138,10 +299,21 @@ cleanup() { |
| kill "$bg_pid" 2>/dev/null |
| wait "$bg_pid" 2>/dev/null |
| fi |
| - if [ -z "${rundir:-}" ] || [ ! -f "$rundir/state" ]; then |
| + if [ -z "${rundir:-}" ]; then |
| + exit "$status" |
| + fi |
| + if [ ! -e "$rundir/state" ] && [ -n "$made_rundir" ]; then |
| + rm -rf -- "$rundir" # this run made it, and made nothing else yet |
| + exit "$status" |
| + fi |
| + if ! read_state_whole; then |
| + say "the state file in $rundir is damaged or incomplete; nothing was undone. Check the drill's resources by hand." |
| + printf 'NOT CLEANED state\n' |
| + [ "$status" = 0 ] && status=3 |
| exit "$status" |
| fi |
| load_state |
| + rm -f -- "$rundir/input.json" "$rundir/overrides.json" |
| undo |
| if verify; then |
| rm -rf -- "$rundir" |
| @@ -153,6 +325,7 @@ cleanup() { |
| } |
| load_state() { |
| + run_id="$(state_value run)" |
| profile="$(state_value profile)" |
| foreign_profile="$(state_value foreign-profile)" |
| region="$(state_value region)" |
| @@ -164,62 +337,146 @@ load_state() { |
| } |
| # endpoint_ids prints "label id" for each endpoint whose policy was saved. |
| -endpoint_ids() { awk '$1 == "endpoint" { print $2, $3 }' "$rundir/state"; } |
| +endpoint_ids() { state_keys endpoint; } |
| + |
| +# The obligations' outcomes, set by undo and read by verify: "uncertain" |
| +# means a resource is there that this run cannot prove it made. |
| +declare -A uncertain=() |
| 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 |
| + while read -r arn; do |
| + [ -n "$arn" ] && dev ecs stop-task --cluster "$cluster" --task "$arn" --reason "carlos media endpoint drill cleanup" >/dev/null 2>&1 |
| + done < <(state_keys task) |
| + if recorded "opening endpoints"; then |
| + while read -r label id; do |
| + [ -n "$label" ] || continue |
| 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 |
| + done < <(endpoint_ids) |
| 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" |
| + undo_repo_policy |
| + undo_bucket |
| + undo_user |
| + undo_log_group |
| +} |
| + |
| +# undo_repo_policy puts the saved repository policy back (or deletes |
| +# the policy when there was none), but only while the policy is the one |
| +# this run set: anything else there now is someone else's change. |
| +undo_repo_policy() { |
| + recorded "changing repo-policy" || return 0 |
| + recorded "restored repo-policy" && return 0 |
| + local now |
| + if now="$(dev ecr get-repository-policy --repository-name "$repository" --query policyText --output text 2>"$rundir/err")"; then |
| + if [ "$now" = "$(cat "$rundir/repo-policy-drill.json")" ]; 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"; return; } |
| + else |
| + gone_ok 'RepositoryPolicyNotFoundException' dev ecr delete-repository-policy --repository-name "$repository" || |
| + { say "could not delete the repository policy"; return; } |
| + fi |
| + note "restored repo-policy" |
| + elif [ "$(state_value repo-policy)" = saved ] && [ "$now" = "$(cat "$rundir/repo-policy.json")" ]; then |
| + note "restored repo-policy" # the change never took |
| else |
| - gone_ok 'RepositoryPolicyNotFoundException' dev ecr delete-repository-policy --repository-name "$repository" || |
| - say "could not delete the repository policy" |
| + uncertain[repository-policy]=1 |
| + say "the repository policy is neither the saved one nor the drill's; left as it is" |
| fi |
| + elif grep -q RepositoryPolicyNotFoundException "$rundir/err" && [ "$(state_value repo-policy)" = none ]; then |
| + note "restored repo-policy" # none, as there was none |
| + else |
| + uncertain[repository-policy]=1 |
| fi |
| - if recorded "create bucket-policy"; then |
| - gone_ok 'NoSuchBucket' dev s3api delete-bucket-policy --bucket "$bucket" || say "could not delete the bucket policy" |
| +} |
| + |
| +# undo_bucket deletes the bucket policy, the object and the bucket, only |
| +# while the bucket carries this run's tag. A bucket there without it |
| +# (a create that collided, or a bucket made since) is left alone. |
| +undo_bucket() { |
| + recorded "creating bucket" || return 0 |
| + recorded "deleted bucket" && return 0 |
| + if fails_with '\(404\)|Not Found|NoSuchBucket' dev s3api head-bucket --bucket "$bucket"; then |
| + return 0 # never made, or already gone |
| 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" |
| + # The run tag is random and only this run writes it: a bucket that |
| + # carries it is this run's, even if the create's answer was lost. |
| + if ! bucket_is_ours; then |
| + uncertain[bucket]=1 |
| + say "the bucket is there but this run cannot prove it made it; left as it is" |
| + return 0 |
| fi |
| - if recorded "create bucket"; then |
| - gone_ok 'NoSuchBucket' dev s3api delete-bucket --bucket "$bucket" || say "could not delete the bucket" |
| + if recorded "creating bucket-policy" && ! recorded "deleted bucket-policy"; then |
| + gone_ok 'NoSuchBucket' dev s3api delete-bucket-policy --bucket "$bucket" && note "deleted bucket-policy" || |
| + say "could not delete the bucket policy" |
| 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 |
| + if recorded "creating object" && ! recorded "deleted object"; then |
| + gone_ok 'NoSuchBucket|NoSuchKey' dev s3api delete-object --bucket "$bucket" --key "$object_key" && note "deleted object" || |
| + say "could not delete the object" |
| 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" |
| + gone_ok 'NoSuchBucket' dev s3api delete-bucket --bucket "$bucket" && note "deleted bucket" || say "could not delete the bucket" |
| +} |
| + |
| +# undo_user deletes the user's keys, its policy and the user, only while |
| +# the user carries this run's tag and the UserId its create answered. |
| +undo_user() { |
| + recorded "creating user" || return 0 |
| + recorded "deleted user" && return 0 |
| + if fails_with 'NoSuchEntity' foreign iam get-user --user-name "$user"; then |
| + return 0 |
| fi |
| - if recorded "create user"; then |
| - gone_ok 'NoSuchEntity' foreign iam delete-user --user-name "$user" || say "could not delete the user" |
| + local own_id id |
| + own_id="$(state_keys own | awk '$1 == "user" { print $2; exit }')" |
| + # The run tag, set by the create itself, and the UserId the create |
| + # answered when the answer came back: a user made since has neither. |
| + if ! user_is_ours "$own_id"; then |
| + uncertain[foreign-user]=1 |
| + say "the user is there but this run cannot prove it made it; left as it is" |
| + return 0 |
| 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" |
| + 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" && note "deleted access-key $id" || |
| + say "could not delete a key" |
| + done |
| + if recorded "creating user-policy" && ! recorded "deleted user-policy"; then |
| + gone_ok 'NoSuchEntity' foreign iam delete-user-policy --user-name "$user" --policy-name "$user_policy" && note "deleted user-policy" || |
| + say "could not delete the user's policy" |
| fi |
| - rm -f -- "$rundir/input.json" "$rundir/overrides.json" |
| + gone_ok 'NoSuchEntity' foreign iam delete-user --user-name "$user" && note "deleted user" || say "could not delete the user" |
| +} |
| + |
| +# undo_log_group deletes the log group, only while it carries this run's |
| +# tag. |
| +undo_log_group() { |
| + recorded "creating log-group" || return 0 |
| + recorded "deleted log-group" && return 0 |
| + log_group_exists || return 0 |
| + if ! log_group_is_ours; then |
| + uncertain[log-group]=1 |
| + say "the log group is there but this run cannot prove it made it; left as it is" |
| + return 0 |
| + fi |
| + gone_ok 'ResourceNotFoundException' foreign logs delete-log-group --log-group-name "$log_group" && note "deleted log-group" || |
| + say "could not delete the log group" |
| +} |
| + |
| +# log_group_exists is true when a group of exactly that name is listed |
| +# (or the listing fails: then it may be). |
| +log_group_exists() { |
| + local groups |
| + groups="$(foreign logs describe-log-groups --log-group-name-prefix "$log_group" --query 'logGroups[].logGroupName' --output text 2>/dev/null)" || return 0 |
| + tr '\t' '\n' <<<"$groups" | grep -qxF -- "$log_group" |
| } |
| # verify checks each obligation and prints its line; false if any is not |
| -# clean. An obligation never begun is clean. |
| +# clean. An obligation never begun is clean; one whose resource this run |
| +# cannot prove it made is NOT CLEANED, for the operator to decide. |
| 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 |
| @@ -227,9 +484,9 @@ verify() { |
| >"$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 recorded "changing repo-policy"; then |
| + [ -z "${uncertain[repository-policy]:-}" ] || clean="" |
| 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="" |
| @@ -238,27 +495,24 @@ verify() { |
| 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="" |
| + if recorded "creating bucket"; then |
| + [ -z "${uncertain[bucket]:-}" ] || clean="" |
| + fails_with '\(404\)|Not Found|NoSuchBucket' 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 |
| + if recorded "creating user"; then |
| + [ -z "${uncertain[foreign-user]:-}" ] || clean="" |
| 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="" |
| + if recorded "creating log-group"; then |
| + [ -z "${uncertain[log-group]:-}" ] || clean="" |
| + log_group_exists && 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 |
| @@ -288,18 +542,22 @@ all_lines() { |
| # 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 |
| + local out="$1" arn task_id i input |
| : >"$out" |
| # The deadline container needs both values (preflight F25); the |
| - # codec container gets the drill's input. |
| + # codec container gets the drill's input. Builtins only: the input is |
| + # never an argument, and the overrides are never echoed. |
| + input="$(<"$rundir/input.json")" |
| 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" |
| + "$(($(date +%s) + 3600))" "${input//\"/\\\"}" >"$rundir/overrides.json" |
| + input="" |
| + record "running task" |
| 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; } |
| + [ "$rc" = 0 ] && [[ "$arn" =~ ^arn:aws:ecs:[a-z0-9-]+:[0-9]{12}:task/[A-Za-z0-9_/-]+$ ]] || { 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. |
| @@ -317,59 +575,24 @@ run_pass() { |
| 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" |
| +# identities reads both profiles' accounts before anything is made: the |
| +# dev profile must be the cluster's account, the foreign one another. |
| +identities() { |
| + local dev_seen |
| + dev_seen="$("$AWS" --profile "$profile" --region "$region" sts get-caller-identity --query Account --output text)" || |
| + die "the dev profile does not answer" |
| + [ "$dev_seen" = "$dev_account" ] || die "the dev profile is not the cluster's account" |
| + foreign_account="$("$AWS" --profile "$foreign_profile" --region "$region" 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" |
| + [ "$foreign_account" != "$dev_account" ] || die "the foreign profile is the dev account: the drill needs an unrelated account" |
| +} |
| + |
| +# discover finds the four endpoints and saves their policies, saves the |
| +# repository policy, and reads the codec's image and log stream. |
| +discover() { |
| + local vpc id line label policy image |
| 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" ;; |
| @@ -379,7 +602,7 @@ main_run() { |
| 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" |
| + [[ "${endpoint_id[$label]:-}" =~ ^vpce-[0-9a-z]+$ ]] || 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' \ |
| @@ -397,49 +620,74 @@ main_run() { |
| 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]}" |
| + manifest_url="https://${BASH_REMATCH[1]}/v2/${BASH_REMATCH[2]}/manifests/${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. |
| +# make_bucket creates the drill bucket, its run tag and its object. The |
| +# bucket must not exist before: cleanup deletes only what this run made. |
| +make_bucket() { |
| fails_with '\(404\)|Not Found' dev s3api head-bucket --bucket "$bucket" || die "the drill bucket already exists, or cannot be checked" |
| - record "create bucket" |
| + record "creating 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 |
| + record "created bucket" |
| + retry dev s3api put-bucket-tagging --bucket "$bucket" --tagging "TagSet=[{Key=$run_tag,Value=$run_id}]" || |
| + die "the bucket's run tag was not set" |
| + bucket_is_ours || die "the bucket does not carry this run's tag" |
| + record "own bucket" |
| printf 'carlos-media endpoint drill\n' >"$rundir/object.txt" |
| - record "create object" |
| + record "creating object" |
| dev s3api put-object --bucket "$bucket" --key "$object_key" --body "$rundir/object.txt" >/dev/null || die "the object was not created" |
| + record "created object" |
| +} |
| - # 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" |
| +# make_foreign creates, in the foreign account, the log group, the user, |
| +# its policy and its key, each verified as this run's before it is |
| +# recorded as owned. |
| +make_foreign() { |
| + record "creating log-group" |
| + foreign logs create-log-group --log-group-name "$log_group" --tags "$run_tag=$run_id" || die "the log group was not created" |
| + log_group_is_ours || die "the log group does not carry this run's tag" |
| + record "own log-group" |
| + record "creating user" |
| + local answer arn uid |
| + answer="$(foreign iam create-user --user-name "$user" --tags "Key=$run_tag,Value=$run_id" --query 'User.[Arn,UserId]' --output text)" || |
| + die "the user was not created" |
| + read -r arn uid <<<"$answer" |
| + [ "$arn" = "arn:aws:iam::$foreign_account:user/$user" ] && [[ "$uid" =~ ^AIDA[A-Z0-9]+$ ]] || die "the user's ARN or id is not the expected one" |
| + user_arn="$arn" |
| + user_is_ours "$uid" || die "the user does not carry this run's tag" |
| + record "own user $uid" |
| + record "creating 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" |
| + record "created user-policy" |
| + record "creating 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" |
| + keys="" |
| + [[ "${user_key_id:-}" =~ ^AKIA[A-Z0-9]+$ ]] && [ -n "${user_secret:-}" ] || die "the user's key was not created" |
| + record "created access-key $user_key_id" |
| +} |
| - # The drill bucket and the engine repository admit the user. |
| - record "create bucket-policy" |
| +# admit gives the user the bucket's object and the repository's pull. |
| +admit() { |
| + record "creating 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" |
| + record "created bucket-policy" |
| 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 |
| @@ -449,46 +697,56 @@ 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" |
| + printf '%s' "$repo_policy" >"$rundir/repo-policy-drill.json" |
| + record "changing repo-policy" |
| retry dev ecr set-repository-policy --repository-name "$repository" --policy-text "$repo_policy" >/dev/null || |
| die "the repository grant was not created" |
| + [ "$(dev ecr get-repository-policy --repository-name "$repository" --query policyText --output text)" = "$repo_policy" ] || |
| + die "the repository policy is not the one set" |
| + record "own repo-policy" |
| +} |
| - # Outside the VPC, with the user's key: the presigned GET, the |
| - # registry token and the log stream. |
| +# mint makes, outside the VPC and with the user's key alone, the |
| +# presigned GET, the registry token and the log stream, and writes |
| +# input.json. Nothing minted is ever an argument. |
| +mint() { |
| 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" |
| + record "creating log-stream" |
| retry as_user logs create-log-stream --log-group-name "$log_group" --log-stream-name "$log_stream" || die "the log stream was not created" |
| + record "created log-stream" |
| + local v |
| 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 |
| + "$s3_url" "$token" "$manifest_url" "$region" "$user_key_id" "$user_secret" "$log_group" "$log_stream" >"$rundir/input.json" |
| + s3_url="" token="" user_secret="" |
| +} |
| - # Phase A: the saved policies refuse every endpoint. |
| +# phases runs A, B and C and the verdict. |
| +phases() { |
| + local label n |
| 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" |
| + record "opening 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" |
| + record "restoring endpoints" |
| 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" |
| @@ -505,13 +763,79 @@ print(json.dumps(p))' "$rundir/repo-policy.json" "$grant")" || die "the reposito |
| carlos_media drill endpoints-verdict "$rundir/A.out" "$rundir/B.out" "$rundir/C.out" |
| } |
| +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 |
| + for v in "$profile_" "$foreign_" "$repo_" "$bucket_"; do |
| + [[ "$v" =~ ^[A-Za-z0-9._-]+$ ]] || { 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]}" |
| + dev_account="${BASH_REMATCH[2]}" |
| + profile="$profile_" foreign_profile="$foreign_" cluster="$cluster_" task_definition="$td_" |
| + repository="$repo_" bucket="$bucket_" subnets="$subnets_" security_group="$sg_" |
| + |
| + # Nothing is made before both identities are known to be right. |
| + identities |
| + |
| + # The run directory and the trap come next: nothing exists yet. |
| + rundir="$(mktemp -d "${TMPDIR:-/tmp}/media-endpoint-drill.XXXXXX")" || die "no run directory" |
| + made_rundir=1 |
| + trap 'cleanup $?' EXIT |
| + trap 'exit 130' INT |
| + trap 'exit 143' TERM |
| + trap 'exit 129' HUP |
| + |
| + run_id="$(od -An -N8 -tx1 /dev/urandom | tr -d ' \n')" |
| + [[ "$run_id" =~ ^[0-9a-f]{16}$ ]] || die "no run id" |
| + user="carlos-media-drill-$run_id" |
| + log_group="carlos-media-endpoint-drill-$run_id" |
| + record "drill-state 1" |
| + record "run $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" |
| + record "dev-account $dev_account" |
| + record "foreign-account $foreign_account" |
| + say "run directory $rundir" |
| + |
| + declare -gA endpoint_id=() |
| + discover |
| + make_bucket |
| + make_foreign |
| + admit |
| + mint |
| + phases |
| +} |
| + |
| case "${1:-}" in |
| run) |
| shift |
| main_run "$@" |
| ;; |
| cleanup) |
| - [ $# = 2 ] && [ -f "$2/state" ] || { echo "$usage" >&2; exit 2; } |
| + [ $# = 2 ] && [ -d "$2" ] && [ -e "$2/state" ] || { echo "$usage" >&2; exit 2; } |
| rundir="$(cd "$2" && pwd)" |
| cleanup 0 |
| ;; |
diff --git a/scripts/media_endpoint_drill_test.py b/scripts/media_endpoint_drill_test.py| index 51ad6c0a3..c30612d59 100644 |
| --- a/scripts/media_endpoint_drill_test.py |
| +++ b/scripts/media_endpoint_drill_test.py |
| @@ -1,15 +1,17 @@ |
| """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). |
| +script that logs each call (with its whole argv) 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. |
| +state line that cannot be written, a failed verdict, SIGTERM with the |
| +endpoints open, a delete AWS refuses, a SIGKILL), every resource this run |
| +can prove it made is removed, nothing it cannot prove it made is touched, |
| +and the run says which it could not clean. And the secrets never reach a |
| +child's argv or a trace. |
| Run from the repo root: python3 -m unittest scripts/media_endpoint_drill_test.py |
| (the Go test TestMediaEndpointDrillPythonGuards runs it in CI). |
| @@ -17,6 +19,7 @@ Run from the repo root: python3 -m unittest scripts/media_endpoint_drill_test.py |
| import json |
| import os |
| from pathlib import Path |
| +import shutil |
| import signal |
| import subprocess |
| import sys |
| @@ -36,13 +39,19 @@ REPO = 'carlos-media' |
| SECRET = 'fakeSECRETvalue/0123456789abcdefghijklmnopqrstuv' |
| TOKEN = 'QVdTOmZha2UtcmVnaXN0cnktcGFzc3dvcmQ=' |
| SIGNATURE = 'fakesignature0123456789abcdef' |
| +SECRETS = (SECRET, TOKEN, SIGNATURE) |
| DEFAULT_POLICY = '{"Statement":[{"Action":"*","Effect":"Allow","Principal":"*","Resource":"*"}]}' |
| +RUN_TAG = 'carlos-media-drill-run' |
| 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'), |
| } |
| +# The tools the script runs as programs: each is wrapped in the |
| +# argv test to log its arguments. |
| +TOOLS = ['sed', 'awk', 'grep', 'cat', 'tr', 'od', 'date', 'cmp', 'rm', 'mktemp', 'python3', 'sleep', 'cksum', |
| + 'tail', 'wc', 'dirname', 'go', 'carlos-media', 'env', 'printf', 'echo', 'test', '['] |
| def original_policy(label): |
| @@ -51,16 +60,16 @@ def original_policy(label): |
| FAKE_AWS = r''' |
| -import fcntl, json, os, sys, time |
| +import fcntl, glob, json, os, sys, time |
| world_path = os.environ['FAKE_AWS_WORLD'] |
| args = sys.argv[1:] |
| -glob, rest = {}, [] |
| +glob_opts, rest = {}, [] |
| i = 0 |
| while i < len(args): |
| a = args[i] |
| if a in ('--profile', '--region', '--query', '--output'): |
| - glob[a[2:]] = args[i + 1] |
| + glob_opts[a[2:]] = args[i + 1] |
| i += 2 |
| continue |
| rest.append(a) |
| @@ -80,12 +89,13 @@ while i < len(opargs): |
| opts.setdefault('_', []).append(a) |
| i += 1 |
| name = service + ' ' + op |
| +query = glob_opts.get('query', '') |
| 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}) |
| +world['calls'].append({'call': name, 'opts': opts, 'flags': sorted(flags), 'profile': glob_opts.get('profile'), |
| + 'env_key': 'AWS_ACCESS_KEY_ID' in os.environ, 'argv': sys.argv}) |
| def save(): |
| @@ -108,11 +118,15 @@ def err(code, msg='failed'): |
| sys.exit(254) |
| -if world.get('refuse') == name: |
| +if world.get('chmod_state_on') == name: |
| + for st in glob.glob(os.path.join(os.environ['TMPDIR'], 'media-endpoint-drill.*', 'state')): |
| + os.chmod(st, 0o400) |
| +if world.get('refuse') and name in world['refuse']: |
| err('AccessDenied', 'refused by the test') |
| if world.get('fail') == name: |
| err('InjectedFailure', 'injected by the test') |
| fail_after = world.get('fail_after') == name |
| +collide = world.get('collide') |
| def done(s=''): |
| @@ -121,15 +135,18 @@ def done(s=''): |
| out(s) |
| +def text(v): |
| + return 'None' if v is None else str(v) |
| + |
| + |
| 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): |
| +if user_cmd and (glob_opts.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'): |
| +if not user_cmd and not glob_opts.get('profile'): |
| err('NoProfile', 'an operator call named no profile') |
| -dev = glob.get('profile') == 'kass' |
| if name == 'sts get-caller-identity': |
| - out('210987654321') |
| + out(world['accounts'][glob_opts['profile']]) |
| if name == 'ec2 describe-subnets': |
| out('vpc-0drill') |
| if name == 'ec2 describe-vpc-endpoints': |
| @@ -153,7 +170,7 @@ if name == 'ecr delete-repository-policy': |
| world['repo_policy'] = None |
| done('{}') |
| if name == 'ecs describe-task-definition': |
| - if 'image' in glob.get('query', ''): |
| + if 'image' in query: |
| out('123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-media@sha256:' + 'ab' * 32) |
| out('media-engine\tmedia') |
| buckets = world['buckets'] |
| @@ -162,13 +179,26 @@ if name == 's3api head-bucket': |
| out() |
| err('404', 'Not Found') |
| if name == 's3api create-bucket': |
| + if collide == 'bucket': |
| + buckets[opts['bucket']] = {'objects': ['theirs'], 'policy': None, 'tags': {}, 'owner': 'foreign'} |
| + err('BucketAlreadyExists', 'The requested bucket name is not available') |
| if opts['bucket'] in buckets: |
| err('BucketAlreadyOwnedByYou') |
| - buckets[opts['bucket']] = {'objects': [], 'policy': None} |
| + buckets[opts['bucket']] = {'objects': [], 'policy': None, 'tags': {}, 'owner': 'drill'} |
| 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-bucket-tagging': |
| + t = opts['tagging'] # TagSet=[{Key=k,Value=v}] |
| + k = t.split('Key=')[1].split(',')[0] |
| + v = t.split('Value=')[1].split('}')[0] |
| + b['tags'][k] = v |
| + done() |
| +if name == 's3api get-bucket-tagging': |
| + if not b['tags']: |
| + err('NoSuchTagSet', 'The TagSet does not exist') |
| + out(text(b['tags'].get(world['run_tag']))) |
| if name == 's3api put-object': |
| b['objects'].append(opts['key']) |
| done('{}') |
| @@ -189,15 +219,24 @@ if name == 's3api delete-bucket': |
| done() |
| users = world['users'] |
| if name == 'iam create-user': |
| + if collide == 'user': |
| + users[opts['user-name']] = {'policies': ['theirs'], 'keys': ['AKIATHEIRS0000000001'], 'tags': {}, 'id': 'AIDATHEIRS0000000001'} |
| + err('EntityAlreadyExists', 'User with name already exists') |
| if opts['user-name'] in users: |
| err('EntityAlreadyExists') |
| - users[opts['user-name']] = {'policies': [], 'keys': []} |
| - done(f'arn:aws:iam::210987654321:user/{opts["user-name"]}') |
| + world['user_seq'] += 1 |
| + t = opts.get('tags', '') |
| + tags = {t.split('Key=')[1].split(',')[0]: t.split('Value=')[1]} if t else {} |
| + uid = f'AIDAFAKEDRILL{world["user_seq"]:07d}' |
| + users[opts['user-name']] = {'policies': [], 'keys': [], 'tags': tags, 'id': uid} |
| + done(f'arn:aws:iam::210987654321:user/{opts["user-name"]}\t{uid}') |
| 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('{}') |
| + out(u['id'] if 'UserId' in query else '{}') |
| +if name == 'iam list-user-tags': |
| + out(text(u['tags'].get(world['run_tag']))) |
| if name == 'iam put-user-policy': |
| world['user_policy_documents'].append(opts['policy-document']) |
| u['policies'].append(opts['policy-name']) |
| @@ -209,9 +248,13 @@ if name == 'iam create-access-key': |
| if name == 'iam list-access-keys': |
| out('\t'.join(u['keys'])) |
| if name == 'iam delete-access-key': |
| + if opts['access-key-id'] not in u['keys']: |
| + err('NoSuchEntity', 'The access key cannot be found') |
| u['keys'].remove(opts['access-key-id']) |
| done() |
| if name == 'iam delete-user-policy': |
| + if opts['policy-name'] not in u['policies']: |
| + err('NoSuchEntity', 'The user policy cannot be found') |
| u['policies'].remove(opts['policy-name']) |
| done() |
| if name == 'iam delete-user': |
| @@ -221,12 +264,22 @@ if name == 'iam delete-user': |
| done() |
| groups = world['log_groups'] |
| if name == 'logs create-log-group': |
| - groups.append(opts['log-group-name']) |
| + if collide == 'log-group': |
| + groups[opts['log-group-name']] = {} |
| + err('ResourceAlreadyExistsException', 'The specified log group already exists') |
| + if opts['log-group-name'] in groups: |
| + err('ResourceAlreadyExistsException') |
| + k, _, v = opts.get('tags', '').partition('=') |
| + groups[opts['log-group-name']] = {k: v} if k else {} |
| done() |
| +if name == 'logs list-tags-log-group': |
| + if opts['log-group-name'] not in groups: |
| + err('ResourceNotFoundException') |
| + out(text(groups[opts['log-group-name']].get(world['run_tag']))) |
| if name == 'logs delete-log-group': |
| if opts['log-group-name'] not in groups: |
| err('ResourceNotFoundException') |
| - groups.remove(opts['log-group-name']) |
| + del groups[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']))) |
| @@ -270,7 +323,7 @@ err('UnknownOperation', name) |
| ''' |
| FAKE_CARLOS_MEDIA = r''' |
| -import re, sys |
| +import sys |
| args = sys.argv[1:] |
| assert args[:2] == ['drill', 'endpoints-verdict'], args |
| def cells(path): |
| @@ -288,7 +341,23 @@ 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', |
| +# Each AWS change the run makes, after the state line that announces it: |
| +# (the line's start, the fake call that must then never happen). |
| +MUTATIONS = [ |
| + ('creating bucket', 's3api create-bucket'), |
| + ('created bucket', 's3api put-bucket-tagging'), |
| + ('creating object', 's3api put-object'), |
| + ('creating log-group', 'logs create-log-group'), |
| + ('creating user', 'iam create-user'), |
| + ('creating user-policy', 'iam put-user-policy'), |
| + ('creating access-key', 'iam create-access-key'), |
| + ('creating bucket-policy', 's3api put-bucket-policy'), |
| + ('changing repo-policy', 'ecr set-repository-policy'), |
| + ('creating log-stream', 'logs create-log-stream'), |
| + ('running task', 'ecs run-task'), |
| + ('opening endpoints', 'ec2 modify-vpc-endpoint'), |
| +] |
| +CREATES = ['s3api create-bucket', 's3api put-bucket-tagging', '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'] |
| @@ -298,15 +367,15 @@ class Drill: |
| def __init__(self, test, **world): |
| self.dir = Path(tempfile.mkdtemp(prefix='media-drill-test-')) |
| - test.addCleanup(subprocess.run, ['rm', '-rf', str(self.dir)]) |
| + test.addCleanup(shutil.rmtree, self.dir, True) |
| 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'), |
| + 'default_policy': DEFAULT_POLICY, 'repo_policy': None, 'buckets': {}, 'users': {}, 'log_groups': {}, |
| + 'tasks': {}, 'task_seq': 0, 'user_seq': 0, 'calls': [], 'overrides': [], 'phases': [], 'user_policy_documents': [], |
| + 'marker': str(self.dir / 'blocked'), 'run_tag': RUN_TAG, 'accounts': {'kass': DEV, 'foreign': FOREIGN}, |
| } |
| w.update(world) |
| self.world_path.write_text(json.dumps(w)) |
| @@ -324,16 +393,21 @@ class Drill: |
| 'AWS_PROFILE': 'should-not-reach-the-user-calls', |
| } |
| - def args(self): |
| - return ['bash', str(SCRIPT), 'run', '--profile', 'kass', '--foreign-profile', 'foreign', '--cluster', CLUSTER, |
| + def args(self, bash=('bash',)): |
| + 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) |
| + def run(self, *args, env=None): |
| + p = subprocess.run(list(args) or self.args(), env={**self.env, **(env or {})}, capture_output=True, text=True, timeout=120) |
| self.code, self.stdout, self.stderr = p.returncode, p.stdout, p.stderr |
| return self |
| + def cleanup(self): |
| + rundirs = self.rundirs() |
| + assert len(rundirs) == 1, rundirs |
| + return self.run('bash', str(SCRIPT), 'cleanup', str(rundirs[0])) |
| + |
| def start(self): |
| return subprocess.Popen(self.args(), env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| @@ -351,13 +425,29 @@ class Drill: |
| w.update(kv) |
| self.world_path.write_text(json.dumps(w)) |
| + def kill_in_phase_b(self, test): |
| + """Starts a run that blocks with the endpoints open and kills it |
| + with SIGKILL, leaving the run directory and everything made.""" |
| + p = self.start() |
| + marker = Path(self.world()['marker']) |
| + deadline = time.monotonic() + 60 |
| + while not marker.exists(): |
| + test.assertIsNone(p.poll(), 'the run ended before phase B') |
| + test.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) |
| + marker.unlink() |
| + self.set_world(block_when_open=False) |
| + |
| class MediaEndpointDrillTest(unittest.TestCase): |
| def assert_clean(self, d, kept=False): |
| w = d.world() |
| - self.assertEqual(w['buckets'], {}, d.stderr) |
| + self.assertEqual(w['buckets'], {}, d.stdout + d.stderr) |
| self.assertEqual(w['users'], {}, d.stderr) |
| - self.assertEqual(w['log_groups'], [], 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) |
| @@ -371,18 +461,23 @@ class MediaEndpointDrillTest(unittest.TestCase): |
| self.assertNotIn('NOT CLEANED', d.stdout) |
| def assert_no_secret_printed(self, d): |
| - for s in (SECRET, TOKEN, SIGNATURE, 'X-Amz', 'https://'): |
| + for s in (*SECRETS, 'X-Amz', 'https://'): |
| self.assertNotIn(s, d.stdout + d.stderr) |
| + def assert_no_secret_in_aws_argv(self, d): |
| + for c in d.world()['calls']: |
| + for s in SECRETS: |
| + self.assertNotIn(s, ' '.join(c['argv']), c['call']) |
| + |
| 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) |
| + self.assert_no_secret_in_aws_argv(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']) |
| @@ -395,40 +490,192 @@ class MediaEndpointDrillTest(unittest.TestCase): |
| '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. |
| + logs = actions['["logs:CreateLogStream", "logs:PutLogEvents"]'] |
| + self.assertTrue(logs.startswith(f'arn:aws:logs:{REGION}:{FOREIGN}:log-group:carlos-media-endpoint-drill-')) |
| + self.assertTrue(logs.endswith(':*')) |
| 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_no_secret_in_any_childs_argv(self): |
| + d = Drill(self) |
| + wrap = d.dir / 'wrap' |
| + wrap.mkdir() |
| + log = d.dir / 'argv.log' |
| + for tool in TOOLS: |
| + real = shutil.which(tool, path=d.env['PATH']) |
| + if real is None: |
| + continue |
| + w = wrap / tool |
| + w.write_text(f'#!/bin/sh\nprintf "%s\\037" "$0" "$@" >>"{log}"\nprintf "\\n" >>"{log}"\nexec "{real}" "$@"\n') |
| + w.chmod(0o755) |
| + d.env['PATH'] = f'{wrap}:{d.env["PATH"]}' |
| + d.set_world(repo_policy='{"Version":"2012-10-17","Statement":[]}') # so python3 runs too |
| + d.run() |
| + self.assertEqual(d.code, 0, d.stdout + d.stderr) |
| + argv = log.read_text() |
| + for tool in ('tail', 'cksum', 'python3', 'mktemp', 'cat'): |
| + self.assertIn(f'/{tool}\x1f', argv, f'{tool} was not seen; the wrapper did not run') |
| + for s in SECRETS: |
| + self.assertNotIn(s, argv) |
| + self.assert_no_secret_in_aws_argv(d) |
| + self.assertEqual(d.world()['repo_policy'], '{"Version":"2012-10-17","Statement":[]}') |
| + |
| + def test_refuses_xtrace(self): |
| + for how, run in ( |
| + ('bash -x', lambda d: d.run(*d.args(('bash', '-x')))), |
| + ('BASH_XTRACEFD', lambda d: d.run(env={'BASH_XTRACEFD': '2'})), |
| + ('SHELLOPTS', lambda d: d.run(env={'SHELLOPTS': 'xtrace'})), |
| + ): |
| + with self.subTest(how=how): |
| + d = run(Drill(self)) |
| + self.assertEqual(d.code, 2, d.stderr[-500:]) |
| + self.assertIn('refusing to run with', d.stderr) |
| + self.assertEqual(d.calls(), []) |
| + for s in SECRETS: |
| + self.assertNotIn(s, d.stderr) |
| + |
| + def test_identities_are_checked_first(self): |
| + for accounts, why in (({'kass': DEV, 'foreign': DEV}, 'the foreign profile is the dev account'), |
| + ({'kass': FOREIGN, 'foreign': '333333333333'}, "the dev profile is not the cluster's account")): |
| + with self.subTest(why=why): |
| + d = Drill(self, accounts=accounts).run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn(why, d.stderr) |
| + self.assertTrue(set(d.calls()) <= {'sts get-caller-identity'}, d.calls()) |
| + self.assertEqual(d.rundirs(), []) |
| + |
| + def test_failed_state_write_stops_each_mutation(self): |
| + for line, call in MUTATIONS: |
| + with self.subTest(line=line): |
| + d = Drill(self).run(env={'MEDIA_DRILL_FAIL_RECORD': line}) |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn('the state file cannot be written; stopped before: ' + line, d.stderr) |
| + if call == 'ec2 modify-vpc-endpoint': |
| + self.assertFalse(any('reset-policy' in c['flags'] for c in d.world()['calls'])) |
| + else: |
| + self.assertNotIn(call, d.calls()) |
| + if line == 'created bucket': |
| + # Stopped before its run tag: a bucket this run cannot |
| + # prove it made is left and reported. |
| + self.assertIn('NOT CLEANED bucket\n', d.stdout) |
| + self.assertEqual(list(d.world()['buckets']), [BUCKET]) |
| + continue |
| + self.assert_clean(d) |
| + |
| + def test_state_that_cannot_be_written_stops_the_run(self): |
| + # The fake makes the state file read-only as it answers put-object: |
| + # the next line cannot be written, so the run stops there, and |
| + # cleanup still undoes what the readable state shows. |
| + d = Drill(self, chmod_state_on='s3api put-object').run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn('stopped before: created object', d.stderr) |
| + self.assertNotIn('logs create-log-group', d.calls()) |
| + self.assert_clean(d) |
| + |
| + def test_damaged_state_is_refused(self): |
| + damages = { |
| + 'truncated': lambda b: b[:-7], |
| + 'garbled': lambda b: b.replace(b'creating user\x20', b'creatinG user\x20', 1), |
| + 'unknown key': lambda b: b + b'mystery thing 1\n', |
| + # Still the right shape, so only the line's sum catches it: |
| + # cleanup would otherwise act on someone else's bucket. |
| + 'changed value': lambda b: b.replace(b'\nbucket ' + BUCKET.encode(), b'\nbucket someone-elses-bucket', 1), |
| + 'missing name': lambda b: b'\n'.join(l for l in b.split(b'\n') if not l.startswith(b'bucket ')), |
| + } |
| + for what, damage in damages.items(): |
| + with self.subTest(damage=what): |
| + d = Drill(self, block_when_open=True) |
| + d.kill_in_phase_b(self) |
| + state = d.rundirs()[0] / 'state' |
| + good = state.read_bytes() |
| + state.write_bytes(damage(good)) |
| + before = d.world() |
| + n = len(before['calls']) |
| + d.cleanup() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn('NOT CLEANED state\n', d.stdout) |
| + self.assertEqual(d.world()['calls'][n:], [], 'cleanup acted on a damaged state') |
| + self.assertEqual(len(d.rundirs()), 1) |
| + # The same state, undamaged, cleans. |
| + state.write_bytes(good) |
| + d.cleanup() |
| + self.assertEqual(d.code, 0, d.stdout + d.stderr) |
| + self.assert_clean(d) |
| + |
| def test_cleanup_after_each_failed_setup_step(self): |
| + # An untagged bucket (its create's answer lost, or its tag never |
| + # set) cannot be proved this run's: it is left and reported. |
| + uncertain = {('s3api create-bucket', 'fail_after'): 'bucket', ('s3api put-bucket-tagging', 'fail'): 'bucket'} |
| 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.assertNotIn('ecs run-task', d.calls()) |
| + left = uncertain.get((create, mode)) |
| + if left is None: |
| + self.assert_clean(d) |
| + else: |
| + self.assertIn(f'NOT CLEANED {left}\n', d.stdout) |
| + self.assertNotIn('s3api delete-bucket', d.calls()) |
| + self.assertEqual(list(d.world()['buckets']), [BUCKET]) |
| + self.assertEqual(len(d.rundirs()), 1) |
| self.assert_no_secret_printed(d) |
| + def test_name_collision_leaves_the_foreign_resource(self): |
| + for what, line in (('bucket', 'bucket'), ('user', 'foreign-user'), ('log-group', 'log-group')): |
| + with self.subTest(collide=what): |
| + d = Drill(self, collide=what).run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn(f'NOT CLEANED {line}\n', d.stdout) |
| + w = d.world() |
| + calls = d.calls() |
| + if what == 'bucket': |
| + self.assertEqual(w['buckets'][BUCKET]['objects'], ['theirs']) |
| + for c in ('s3api delete-bucket', 's3api delete-object', 's3api delete-bucket-policy'): |
| + self.assertNotIn(c, calls) |
| + if what == 'user': |
| + (u,) = w['users'].values() |
| + self.assertEqual((u['id'], u['keys'], u['policies']), ('AIDATHEIRS0000000001', ['AKIATHEIRS0000000001'], ['theirs'])) |
| + for c in ('iam delete-user', 'iam delete-access-key', 'iam delete-user-policy'): |
| + self.assertNotIn(c, calls) |
| + if what == 'log-group': |
| + self.assertEqual(len(w['log_groups']), 1) |
| + self.assertNotIn('logs delete-log-group', calls) |
| + |
| + def test_replaced_between_failed_cleanup_and_retry_is_left(self): |
| + d = Drill(self, refuse=['iam delete-user', 's3api delete-bucket']).run() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn('NOT CLEANED foreign-user\n', d.stdout) |
| + self.assertIn('NOT CLEANED bucket\n', d.stdout) |
| + # Someone replaces both with their own before the retry. The user |
| + # even keeps the run tag (say, recreated from a copy of it): only |
| + # its new UserId tells it apart. |
| + w = d.world() |
| + (name,) = w['users'] |
| + tags = dict(w['users'][name]['tags']) |
| + self.assertIn(RUN_TAG, tags) |
| + w['users'][name] = {'policies': ['theirs'], 'keys': ['AKIATHEIRS0000000001'], 'tags': tags, 'id': 'AIDATHEIRS0000000002'} |
| + w['buckets'][BUCKET] = {'objects': ['theirs'], 'policy': 'theirs', 'tags': {'owner': 'them'}, 'owner': 'foreign'} |
| + w['refuse'] = [] |
| + d.world_path.write_text(json.dumps(w)) |
| + n = len(w['calls']) |
| + d.cleanup() |
| + self.assertNotEqual(d.code, 0) |
| + self.assertIn('NOT CLEANED foreign-user\n', d.stdout) |
| + self.assertIn('NOT CLEANED bucket\n', d.stdout) |
| + retry = [c['call'] for c in d.world()['calls'][n:]] |
| + for c in ('iam delete-user', 'iam delete-access-key', 'iam delete-user-policy', 's3api delete-bucket', |
| + 's3api delete-object', 's3api delete-bucket-policy'): |
| + self.assertNotIn(c, retry) |
| + w = d.world() |
| + self.assertEqual(w['users'][name]['id'], 'AIDATHEIRS0000000002') |
| + self.assertEqual(w['buckets'][BUCKET]['objects'], ['theirs']) |
| + |
| def test_cleanup_after_failed_verdict(self): |
| d = Drill(self, b_never_ok=True).run() |
| self.assertNotEqual(d.code, 0) |
| @@ -461,7 +708,7 @@ class MediaEndpointDrillTest(unittest.TestCase): |
| 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() |
| + 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: |
| @@ -470,41 +717,38 @@ class MediaEndpointDrillTest(unittest.TestCase): |
| 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.assertIn('\nown user AIDA', state) |
| + self.assertIn('\ndeleted access-key AKIA', state) |
| + for s in SECRETS: |
| 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])) |
| + # Once AWS allows it, cleanup <run dir> finishes the job, and does |
| + # not delete again what the state shows deleted. |
| + d.set_world(refuse=[]) |
| + n = len(d.world()['calls']) |
| + d.cleanup() |
| self.assertEqual(d.code, 0, d.stdout + d.stderr) |
| self.assert_clean(d) |
| + retry = [c['call'] for c in d.world()['calls'][n:]] |
| + for c in ('s3api delete-bucket', 'logs delete-log-group', 'iam delete-user-policy'): |
| + self.assertNotIn(c, retry) |
| 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) |
| + d.kill_in_phase_b(self) |
| 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.assertTrue((d.rundirs()[0] / 'input.json').exists()) |
| + d.cleanup() |
| 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() |
| + theirs = {'objects': ['theirs'], 'policy': None, 'tags': {}, 'owner': 'foreign'} |
| + d = Drill(self, buckets={BUCKET: theirs}).run() |
| self.assertNotEqual(d.code, 0) |
| - self.assertEqual(d.world()['buckets'], {BUCKET: {'objects': ['theirs'], 'policy': None}}) |
| + self.assertEqual(d.world()['buckets'], {BUCKET: theirs}) |
| for call in ('s3api create-bucket', 's3api delete-object', 's3api delete-bucket'): |
| self.assertNotIn(call, d.calls()) |
| self.assertIn('cleaned bucket\n', d.stdout) |
| @@ -516,6 +760,11 @@ class MediaEndpointDrillTest(unittest.TestCase): |
| self.assertEqual(d.rundirs(), []) |
| d.run('bash', str(SCRIPT), 'cleanup', str(d.tmp / 'absent')) |
| self.assertEqual(d.code, 2) |
| + empty = d.tmp / 'not-a-run' |
| + empty.mkdir() |
| + d.run('bash', str(SCRIPT), 'cleanup', str(empty)) |
| + self.assertEqual(d.code, 2) |
| + self.assertTrue(empty.exists(), 'cleanup removed a directory with no state') |
| self.assertEqual(d.calls(), []) |