carlos / platform Public

media: endpoint drill setup moves to OpenTofu

Plan 3 Task 7 fix round 2 (Paul's ruling, 2026-11-18). The script's
journal, ownership proofs, policy comparison and hand-written undo
paths are gone.

A fixture root in scripts/media-endpoint-drill/ owns the foreign user,
its log group and the drill bucket. The engine root owns the endpoint
and repository policies through media_engine_drill, whose contract is
now in plan 3 Task 11. The script only orchestrates, and a trap restores
on every exit: the engine root applied with the drill off, the fixture
destroyed, each item reported from what tofu answers. restore <run dir>
can be repeated.

The access key is minted with the CLI, so no secret reaches tofu. The
user stays admitted to the repository in phases A and C, so that only
the endpoint policies differ between the phases.

Plan 1 Tasks 1, 4 and 8 and plan 3 Tasks 7 and 11, R2 and R3 describe
the new flow.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 00e4300ead51a91073ea19b482d5b216ace5e661 parent 5bea2c6
9 files changed, +938 −1,237
  • cmd/carlos-media/drill_test.go +10 −3
  • docs/superpowers/notes/census-claims-media-conversion.tsv +1 −0
  • docs/superpowers/notes/media-conversion-copy-deck.md +5 −5
  • docs/superpowers/plans/2026-11-16-media-conversion-plan-1-spike.md +5 −5
  • docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md +16 −9
  • scripts/media-endpoint-drill.sh +238 −576
  • scripts/media-endpoint-drill/main.tf +115 −0
  • scripts/media-endpoint-drill/variables.tf +43 −0
  • scripts/media_endpoint_drill_test.py +505 −639
diff --git a/cmd/carlos-media/drill_test.go b/cmd/carlos-media/drill_test.go
index dc3fed1a7..ea6fa10c7 100644
--- a/cmd/carlos-media/drill_test.go
+++ b/cmd/carlos-media/drill_test.go
@@ -456,14 +456,21 @@ func TestDrillUsage(t *testing.T) {
}
// TestMediaEndpointDrillPythonGuards runs scripts/media_endpoint_drill_test.py
-// (the drill script's cleanup on every exit, against a fake aws), so CI
-// runs it (preflight F31). It skips locally without python3 or bash;
-// in CI it fails without them.
+// (the drill script's orchestration and restore, against fake tofu and
+// aws), so CI runs it (preflight F31), with this package's real
+// `drill endpoints-verdict` built for the three-phase cases. It skips
+// locally without python3 or bash; in CI it fails without them.
func TestMediaEndpointDrillPythonGuards(t *testing.T) {
python := ciBinary(t, "python3")
ciBinary(t, "bash")
+ binary := filepath.Join(t.TempDir(), "carlos-media")
+ build := exec.Command("go", "build", "-o", binary, ".")
+ if output, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("building carlos-media: %v\n%s", err, output)
+ }
cmd := exec.Command(python, "-B", "-m", "unittest", "-v", "scripts.media_endpoint_drill_test")
cmd.Dir = "../.."
+ cmd.Env = append(os.Environ(), "MEDIA_DRILL_CARLOS_MEDIA="+binary)
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("media endpoint drill Python tests: %v\n%s", err, output)
diff --git a/docs/superpowers/notes/census-claims-media-conversion.tsv b/docs/superpowers/notes/census-claims-media-conversion.tsv
index d8619fb73..32e26da7a 100644
--- a/docs/superpowers/notes/census-claims-media-conversion.tsv
+++ b/docs/superpowers/notes/census-claims-media-conversion.tsv
@@ -53,3 +53,4 @@
# AGENTS.md "What is in scope": scripts/ is out), and `make census-card` with this file stays clean after the script
# is added, so it takes no claim line (one would be "not a change the census sees"). For the reviewer: it is an
# operator drill script run from docs-t1 with the operator's own AWS profiles; root never runs, installs or reads it.
+# Its fixture root scripts/media-endpoint-drill/*.tf is outside infra/ for the same reason (fix round 2).
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 39f23cceb..52dbc5199 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -624,8 +624,8 @@ or an output's name: never a credential, a URL or a header. `%s` and
| `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: 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`; 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 |
+| `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> --engine-root <dir> \| restore <run dir>` (pending Luna pass; plan 3 Task 7 fix 2) |
+| `script.endpoint_drill.progress` | `media-endpoint-drill: run directory %s`; `media-endpoint-drill: applying the fixture`; `media-endpoint-drill: phase A: the endpoints' real policies`; `media-endpoint-drill: phase B: the endpoints opened to full access`; `media-endpoint-drill: phase C: the endpoints' real policies again`; `media-endpoint-drill: phase A was not refused at every endpoint; the endpoints are not opened`; `media-endpoint-drill: kept %s; finish with: %s restore %s` (pending Luna pass; plan 3 Task 7 fix 2). On stderr |
+| `script.endpoint_drill.restore` | `cleaned %s`, `NOT CLEANED %s` (an item: `engine-policies`, `fixture`, `input`) (pending Luna pass; plan 3 Task 7 fix 2). On stdout |
+| `script.endpoint_drill.refused` | `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: %s/drill.conf is damaged; nothing was changed. Restore the engine root and destroy the fixture by hand.` (pending Luna pass; plan 3 Task 7 fix 2). On stderr |
+| `script.endpoint_drill.error` | `media-endpoint-drill: ` then one of: `--engine-root is not a directory`; `--engine-root has characters the drill cannot record`; `--cluster is not a cluster ARN`; `the dev profile does not answer`; `the dev profile is not the cluster's account`; `the foreign profile does not answer`; `the foreign profile has no account`; `the foreign profile is the dev account: the drill needs an unrelated account`; `the task definition cannot be read`; `the codec image is not pinned by digest`; `the codec image is not from --repository`; `the codec container has no awslogs group and prefix`; `no run directory`; `no run id`; `the run directory cannot be written`; `the engine root declares no media_engine_drill variable`; `the engine root does not initialise`; `the engine root's policies have changes pending; apply or revert them first`; `the engine root's variables cannot be written`; `the engine root was not applied`; `the fixture cannot be copied`; `the fixture's variables cannot be written`; `the fixture does not initialise`; `the fixture was not applied`; `the fixture has no user`; `the fixture's user is not the expected one`; `the user's key 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 drill's input cannot be written`; `a drill task did not start`; `the drill task did not stop in time`; `the drill task's output is incomplete` (pending Luna pass; plan 3 Task 7 fix 2). 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 3be430a28..3fc6bcac9 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
@@ -35,10 +35,10 @@
**Interfaces (scratch):** `mediaspike` subcommands. Driver: `grant --bucket <b> --key <k> --etag <e> --session <minutes>` (AssumeRole of the spike conversion role with plan 3 Task 9's session policy, prints the five transfers in plan 2 Task 1's `media.Transfers` JSON, its struct copied into the scratch module since plan 2 is not built yet, and the token length); `run --class <preset/class> [--command …] [--env K=V]… [--storage <GiB>] [--cpu <units> --memory <MiB>] [--token <t>]` (RunTask as plan 3 Task 9 builds it; prints the ARN and the override byte length); `watch <arn>` (DescribeTasks every 5 s; prints created, pull start/stop, started, each container's start from the codec's metadata log, stopped, stop code, exits); `retention <arn>…` (DescribeTasks every 5 min until `MISSING`). Probe (in the task): `creds`, `dns <name>…`, `net <host:port>…`, `endpoints` (and the driver's `endpoints-verdict`), built to plan 3 Task 7's definition of the endpoint drill and nothing else, `marker`, `hostile-timer`, `deadline` (plan 2's `media.DeadlineSleep` rule, copied), `clock`, `encode --preset <x264> --profile video|audio|poster|hdr` (downloads the transfer's source with resume, runs the plan 3 arguments, reads `memory.peak` of its cgroup, uploads, prints wall times per phase), `playlist <mp4>` (a scratch copy of plan 3's `readFMP4` and `writePlaylist`), `reconnect --cut-at <bytes> --pause-until <unix>`.
-- [ ] **Step 1:** Write `mediaspike`, and a scratch copy of `scripts/media-endpoint-drill.sh` to plan 3 Task 7's definition (the drill is defined only there; plan 3 builds the committed version), including its unconditional cleanup: the trap installed before the first create, the `state` file, the restore, delete and verify steps, and the `cleanup <run dir>` subcommand; run plan 3's `media_endpoint_drill_test.py` failure-path cases against the scratch copy with the fake `aws` before Task 2 (no AWS call); `go vet` and `CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build`. Expected: clean.
-- [ ] **Step 2:** Write the tofu root (plan 3 Task 11's resources, `name = "mediaspike"`, the bucket `<dev store prefix>mediaspike-<6 hex>` with SSE-S3, versioning off, public access blocked; drill task definitions `late-deadline` (the deadline container on a separate image tag padded with a 2 GB layer), `no-deadline` (the deadline container on a digest that does not exist), `no-start-dep` and `stop-20`). `tofu init -backend=false && tofu validate`. Expected: valid. Read the dev store prefix from the dev root (read-only).
+- [ ] **Step 1:** Write `mediaspike`. The endpoint drill is not copied: use the branch's `scripts/media-endpoint-drill.sh` and its fixture root `scripts/media-endpoint-drill/` (plan 3 Task 7, the one definition), and run `scripts/media_endpoint_drill_test.py` with its fake `tofu` and `aws` before Task 2 (no AWS call); `go vet` and `CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build`. Expected: clean.
+- [ ] **Step 2:** Write the tofu root (plan 3 Task 11's resources, as a local module called `module "media_engine"` with Task 11's `drill` input and the root's `variable "media_engine_drill"`, default `null`, so the drill script's five `-target` addresses hold, `name = "mediaspike"`, the bucket `<dev store prefix>mediaspike-<6 hex>` with SSE-S3, versioning off, public access blocked; drill task definitions `late-deadline` (the deadline container on a separate image tag padded with a 2 GB layer), `no-deadline` (the deadline container on a digest that does not exist), `no-start-dep` and `stop-20`). `tofu init -backend=false && tofu validate`. Expected: valid. Read the dev store prefix from the dev root (read-only).
- [ ] **Step 3:** Write the Containerfile: `FROM docker.io/library/debian:13-slim@sha256:<digest>`, `apt-get install --no-install-recommends ffmpeg`, `COPY mediaspike /usr/local/bin/`, `RUN mkdir /scratch && chown 65534:65534 /scratch && chmod 0700 /scratch`, `VOLUME ["/scratch"]` (plan 3's image does the same), `USER 65534:65534`, `ENTRYPOINT ["/usr/local/bin/mediaspike"]`. Record the digest.
-- [ ] **Step 4:** Write `scope.md`, the approval request, with: account and region; every resource of Step 2 by type and name, plus one throwaway `t4g.medium` Debian 13 arm64 builder (SSM only, no inbound, 40 GB gp3; or the existing dev root runner if one is up), one dev app `mediaspike` for the playback page; for the foreign-credential gate, in an unrelated account Paul names, one IAM user and access key whose identity policy allows `s3:GetObject` on one object of the spike bucket, `ecr:GetAuthorizationToken` and the pull actions on the spike repository, and `logs:CreateLogStream`/`logs:PutLogEvents` on one log group in that account, plus that log group, named `mediaspike-endpoint-drill` in `eu-west-1`, all of it created and removed by the drill script's one run in Task 4 Step 3 (Paul gives a profile in that account allowed to create them); a spike-bucket policy and a spike-repository policy admitting that user; and, for minutes inside Task 4 Step 3, each of the four endpoint policies replaced by AWS's default full-access policy as a positive control and then restored; what each permits (the conversion role trusts only the operator's `kass` principal); traffic effects (none on tenants or the dev console); cost at most 100 US dollars (endpoints about 1 dollar a day, Fargate runs, the builder, about 150 GB of S3 for a week); duration at most 7 days; Task 8's cleanup and its verification. List the files needed from Paul (spec decision 1): 4K60 HDR in Dolby Vision or HLG, a portrait clip with rotation, a variable-frame-rate clip, an ordinary 1080p clip, an hour or more of video, a browser voice recording; and the Safari checks on his iPhone or the tito-studio Mac.
+- [ ] **Step 4:** Write `scope.md`, the approval request, with: account and region; every resource of Step 2 by type and name, plus one throwaway `t4g.medium` Debian 13 arm64 builder (SSM only, no inbound, 40 GB gp3; or the existing dev root runner if one is up), one dev app `mediaspike` for the playback page; for the foreign-credential gate, all of it made and removed by the drill script's one run in Task 4 Step 3: the fixture root `scripts/media-endpoint-drill/`, with local state in the run directory, makes, in an unrelated account Paul names (he gives a profile there allowed to create them), one IAM user whose identity policy allows `s3:GetObject` on the drill object, `ecr:GetAuthorizationToken` and the pull actions on the spike repository, and `logs:CreateLogStream`/`logs:PutLogEvents` on one log group in that account, plus that log group, named `carlos-media-endpoint-drill-<run id>` in `eu-west-1`, and in dev a drill bucket with one object and a bucket policy admitting that user; the script mints one access key for that user; and the scratch root, through `media_engine_drill`, holds a spike-repository policy admitting that user for the length of the run and, for minutes inside Task 4 Step 3, each of the four endpoint policies under AWS's default full-access policy as a positive control, then `null` again; what each permits (the conversion role trusts only the operator's `kass` principal); traffic effects (none on tenants or the dev console); cost at most 100 US dollars (endpoints about 1 dollar a day, Fargate runs, the builder, about 150 GB of S3 for a week); duration at most 7 days; Task 8's cleanup and its verification. List the files needed from Paul (spec decision 1): 4K60 HDR in Dolby Vision or HLG, a portrait clip with rotation, a variable-frame-rate clip, an ordinary 1080p clip, an hour or more of video, a browser voice recording; and the Safari checks on his iPhone or the tito-studio Mac.
---
@@ -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, 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 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 and `--engine-root` naming the scratch root (a Fargate `run-task` needs the first two; the script applies the third with the drill closed, open, closed and finally off). Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and tofu reports the drill off and the fixture destroyed. Record the table, the policy swap's start and end times, and the restore lines; every one must read `cleaned`. If any reads `NOT CLEANED`, or the run was killed, run `restore <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.
@@ -112,7 +112,7 @@ Each step runs one or more tasks through `mediaspike run` and records the probe'
- [ ] **Step 1: Also establish the image route.** Whether amadan CI runs on a schedule (amadan CLI help and `.amadan/README.md`); whether `snapshot.debian.org` is reachable from docs-t1 (`curl -sI`, with that host declared). Record which weekly refresh plan 3 Task 8 uses: an amadan schedule, or a Paseo schedule on docs-t1.
- [ ] **Step 2: Write the report:** Paul's approval; environment and image; Paul's files' facts (tags removed); every Task 4 to 7 result as a table; then **Values for plans 2 and 3**, one row each with provisional and measured: `media.EngineRecordRetention` (1 h), `media.MaxOverrideBytes` (8,192) and the worst token length (1,400 in plan 2's test), `video_max` (2 h), `video_max_hi` (30 min), `video_bytes` (40 GiB), `audio_max` (8 h), `audio_bytes` (10 GiB), the four class rows' CPU and memory and whether 16 vCPU ARM64 places, the short classes' granted durations (10 min, 2 h), `x264Preset` (`veryfast`), `x264CRF` (23), the HDR chain and `refuseDolbyVision5` (false), the muxer flags and the top-level box sequence of the fixtures (plan 3 expects `ftyp`, `moov`, then `moof`/`mdat` pairs with `skip_trailer`), whether `/scratch` is writable by 65534, `codecHeadroomDB` (0.5), whether `ephemeralStorage` and task size are accepted per run, platform version (1.4.0), clock skew, the playback matrix and the acceptance time, the weekly image refresh, and the cost table. Then **Spec amendments**: one per failed proof, with the evidence; or "none".
- [ ] **Step 3:** Commit the report and fixtures on the design branch: `docs: media conversion spike report and fixtures`. Paul confirms the report before plan 3 Task 4 starts.
-- [ ] **Step 4: Clean up**, then verify each: `tofu destroy` (bucket emptied first) and an `aws resourcegroupstaggingapi get-resources` for the spike's tag showing nothing; the builder terminated (or the root runner's `/var/tmp/mediaspike` removed); the drill's foreign user, key and log group `mediaspike-endpoint-drill` and its bucket and repository grants, already removed and verified by the drill script's own cleanup (re-run `cleanup <run dir>` if its directory remains), checked absent once more in that account (`aws iam get-user` answers `NoSuchEntity`; `aws logs describe-log-groups --log-group-name-prefix mediaspike-endpoint-drill` lists nothing), by Paul or with his credentials; dev app `mediaspike` deleted; `~/.cache/mediaspike/` and `$TMPDIR/mediaspike/` removed by exact path. Tell Paul it is done, with the report's path.
+- [ ] **Step 4: Clean up**, then verify each: `tofu destroy` (bucket emptied first) and an `aws resourcegroupstaggingapi get-resources` for the spike's tag showing nothing; the builder terminated (or the root runner's `/var/tmp/mediaspike` removed); the drill's foreign user, key and log group and its bucket, already destroyed by the drill script's own restore (re-run `restore <run dir>` if its directory remains), checked absent once more in that account (`aws iam get-user` answers `NoSuchEntity`; `aws logs describe-log-groups --log-group-name-prefix carlos-media-endpoint-drill-` lists nothing), by Paul or with his credentials; dev app `mediaspike` deleted; `~/.cache/mediaspike/` and `$TMPDIR/mediaspike/` removed by exact path. Tell Paul it is done, with the report's path.
---
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 29905bf67..d32ae4085 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
@@ -158,19 +158,20 @@ Depends on plan 1 Task 3 Step 4: the muxer rules and the parser's accepted box s
**Files:**
- Modify: `internal/mediahandler/fakeffmpeg_test.go` (Task 3's helper; the scenarios below)
-- Create: `cmd/carlos-media/sigv4.go` (a stdlib SigV4 signer for the drill's two signed API calls; the provider boundary keeps the SDK out), `scripts/media-endpoint-drill.sh`, `scripts/media_endpoint_drill_test.py` (stdlib `unittest`, the shape of `scripts/*_test.py`), `internal/mediahandler/hostile_test.go`, `internal/mediahandler/selftest.go`, `cmd/carlos-media/drill.go`, `cmd/carlos-media/drill_test.go`, `internal/mediahandler/testdata/corpus/*` (playlist-style files naming `http://169.254.169.254/` and `file:///etc/passwd`, a truncated MP4, an MP4 whose `dref` names `/etc/passwd`, a 0-byte file, 4 KiB of random bytes, an HTML file, a ZIP)
+- Create: `cmd/carlos-media/sigv4.go` (a stdlib SigV4 signer for the drill's two signed API calls; the provider boundary keeps the SDK out), `scripts/media-endpoint-drill.sh`, `scripts/media-endpoint-drill/{main.tf,variables.tf}` (the drill's fixture root, outside `infra/`), `scripts/media_endpoint_drill_test.py` (stdlib `unittest`, the shape of `scripts/*_test.py`), `internal/mediahandler/hostile_test.go`, `internal/mediahandler/selftest.go`, `cmd/carlos-media/drill.go`, `cmd/carlos-media/drill_test.go`, `internal/mediahandler/testdata/corpus/*` (playlist-style files naming `http://169.254.169.254/` and `file:///etc/passwd`, a truncated MP4, an MP4 whose `dref` names `/etc/passwd`, a 0-byte file, 4 KiB of random bytes, an HTML file, a ZIP)
**Interfaces:**
- Produces: fake-ffmpeg scenarios `fail`, `fill-scratch` (writes until `ENOSPC` on a small tmpfs, Linux only, skipped elsewhere), `many-files` (100,000 empty files in the output directory), `symlink-out`, `hardlink-out`, `fifo-out`, `oversize-out`, `fork-setsid`, `ignore-term`; `func Selftest(ctx context.Context, cfg Config) error` (generates inputs with the image's real ffmpeg via `lavfi` (`testsrc2` 1080p 10 s with a 440 Hz tone; the same at 1080x1920 with `-display_rotation 90`; a PQ-tagged 10-bit 4K 5 s; a `-live 1` WebM Opus voice clip; a silent mono WAV; an MP3 with an attached picture), serves them from an in-process presigned-style server, runs `Run` for each, and checks: exit 0, output sizes, `readFMP4` and the playlist, the video output size from `targetSize`, the voice clip's output loudness within 1 LU of -16 or its true peak at most -1.5 dBTP and never above, its loudness range at least the source's less 0.5 LU, 1,000 peaks, the silent file's peaks all 0); `carlos-media selftest` prints one `PASS`/`FAIL <case>: <reason>` line per case and exits 0 or 1; `carlos-media drill <name>` with `creds` (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` is set; ordinary metadata such as `AWS_EXECUTION_ENV`, `AWS_REGION` and `AWS_DEFAULT_REGION` is allowed; `169.254.170.2/v2/credentials` and `169.254.169.254` unreachable; the v4 task metadata endpoint yields no credential), `dns` (only the allowed names resolve; `example.com`, `amazonaws.com`, `sts.eu-west-1.amazonaws.com` do not), `net` (TCP to 1.1.1.1:443 and to a private address given as an argument fails), `endpoints` (one pass of the endpoint drill defined below), `hostile-timer` (ignores SIGTERM and SIGINT, sends `SIGKILL` to every PID it can see and to `-1`, then loops), `fill-scratch`, `many-files`, `bad-outputs` (creates the hostile files of Task 6 under the output names, then calls `collect` and `upload` with the payload from `CARLOS_MEDIA_JOB`; prints how many PUTs were attempted, expected 0); each prints `PASS`/`FAIL` lines and never prints a credential, a URL or a header.
**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).
+- **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 fixture root and the engine root provide all of it (below). Then, outside the engine VPC (docs-t1, with that user's new key, minted by the script with the AWS CLI so that it never reaches tofu's state), the script 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> --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).
+- **One owner per policy (Paul, 2026-11-18).** OpenTofu owns everything the drill changes, and the script keeps no record of its own. The engine root owns the four endpoint policies and the repository policy, through its `media_engine_drill` variable (Task 11 defines the contract). The fixture root `scripts/media-endpoint-drill/` owns the foreign IAM user (`force_destroy = true`, which also removes the key the script mints), its inline policy, the foreign log group, and the drill bucket with its object and bucket policy, through two AWS providers (dev and foreign, each pinned with `allowed_account_ids`). The script copies the fixture into the run directory, so its local state lives there (mode 0600, directory 0700). No secret is in either root's variables or state.
+- **The three phases 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> --engine-root <the deployment root that calls media-engine>`, every call through `${AWS:-aws}` and `${TOFU:-tofu}`. It refuses to run with xtrace on. Before it changes anything it checks: the dev profile is the cluster's account and the foreign profile another account; the codec image is pinned by digest and comes from `--repository`; the engine root declares `media_engine_drill`; and `tofu plan -detailed-exitcode` shows nothing pending on the five policy resources with the drill off. Then: make the run directory (`mktemp -d "$TMPDIR/media-endpoint-drill.XXXXXX"`) and install the traps; apply the fixture; mint the user's key, the presigned GET, the registry token and the log stream, and write `input.json`; apply the engine root with `{endpoints_open = false, foreign_principal_arn = <user>}`; phase A, one pass: every endpoint must be `refused`; apply with `endpoints_open = true`, then one pass every 60 s, at most 5: phase B passes when every endpoint is `ok`; apply with `endpoints_open = false`, then one pass every 60 s, at most 5: phase C passes when every endpoint is `refused`. If phase A is not refused everywhere the endpoints are never opened. `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`. The user stays admitted to the repository through all three phases, so that only the endpoint policies differ between them: a refusal is causal for an endpoint only because the identical request succeeded in phase B.
+- **`restore` runs on every exit** (success, a failed step, a failed verdict, a signal) from a trap that first stops any running tofu and waits for it. It removes `input.json`; applies the engine root with `media_engine_drill = null`, then asks `tofu plan -detailed-exitcode` whether anything is left; and destroys the fixture, whichever way the engine went, then asks `tofu state list` whether anything is left. It prints `cleaned <item>` or `NOT CLEANED <item>` for `engine-policies`, `fixture` and `input` from what tofu answers, 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 restore <run dir>` does the same again and can be repeated, for the one exit a trap cannot catch (`SIGKILL`, a lost machine) or a failed restore.
- **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).
+- [ ] **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 fake `tofu` and `aws` on `PATH` (one Python script under the test's temporary directory that logs each call and keeps a fake world of the drill variable, the fixture and the key, and fails or blocks on demand): `test_interrupt_at_each_step_restores` (a signal at each step: the drill ends off and the fixture destroyed); `test_failed_restore_reports_and_rerun_converges` (`NOT CLEANED <item>`, non-zero exit, the run directory kept, then `restore <run dir>` finishes the job); `test_restore_after_sigkill_and_repeated`; `test_verdict_needs_all_three_phases`; `test_no_secret_reaches_argv_tofu_or_output` (no secret in any child's argv, tofu's environment or variables, or a file of the run directory); `test_refuses_xtrace`; `test_fixture_validates` (`tofu validate` when tofu is installed, else skipped with a message).
- [ ] **Step 2:** Run `go test ./internal/mediahandler/ ./cmd/carlos-media/ -run 'TestCorpus|TestPlaylistStyle|TestHostileChildren|TestBadOutputs|TestDrill|TestSigV4|TestEndpointsVerdict' -count=1` and `python3 -I -m unittest discover -s scripts -p 'media_endpoint_drill_test.py'`. Expected: FAIL.
- [ ] **Step 3:** Implement.
- [ ] **Step 4:** Rerun. Expected: PASS. Then each fuzz target for 60 s. Expected: no crashers; add any found input to `testdata/fuzz/`.
@@ -247,7 +248,13 @@ Depends on plan 1 Task 3 Step 4: the muxer rules and the parser's accepted box s
- Endpoint policies: S3 gateway: Allow `s3:GetObject`, `s3:PutObject` on the store prefix and `media-results/*` for principal `*` with `StringEquals aws:PrincipalArn` = the conversion role ARN; Allow `s3:GetObject` on `arn:aws:s3:::prod-<region>-starport-layer-bucket/*` for `*`. ECR API and Docker: Allow `ecr:BatchGetImage`, `ecr:GetDownloadUrlForLayer`, `ecr:BatchCheckLayerAvailability` on the repository and `ecr:GetAuthorizationToken` on `*`, each with `aws:PrincipalArn` = the execution role. Logs: Allow `logs:CreateLogStream`, `logs:PutLogEvents` on the log group with `aws:PrincipalArn` = the execution role.
- `reaper.py`: `handler(event, context)` lists `RUNNING` tasks (paginated), describes them in batches of 100, and stops each whose `createdAt` is older than `MAX_AGE_MINUTES` with reason `carlos media reaper: older than <n> minutes`; it reads no other input.
-- [ ] **Step 1: Write the failing tests.** `media_engine.tftest.hcl` with `mock_provider "aws" {}`, runs: `region_must_be_store_region` (`expect_failures`); `no_digest_creates_only_the_repository` (no task definitions, `carlos_media_engine == ""`); `task_definitions_pass_the_gate` (for each of four: `task_role_arn == null`, `pid_mode == null`, ARM64, and on `jsondecode(container_definitions)`: names, essential, `dependsOn` `deadline`/`START`, `stopTimeout` 30 both, read-only root, user, caps drop `ALL`, images equal `<repo>@<digest>`, `scratch` mounted in `codec` only, CPU and memory per class); `endpoint_policies_name_their_principals` (every statement of the three interface policies has the execution-role condition; the S3 policy's two statements exactly); `tasks_sg_has_no_ingress_and_only_https_egress`; `no_default_route`; `dns_firewall_allows_three_services_and_blocks_the_rest`; `conversion_role_policy_exact` (three Allows, two Denies, trust only the console role); `console_policy_exact`; `reaper_role_is_cluster_scoped`; `output_parses` (the output's JSON has `v` 1, the region, four task definitions and the image). `reaper_test.py` (stdlib `unittest`, a stub client): an old task is stopped, a young one is not, pagination across two pages, a describe failure stops nothing.
+- **The drill input: the contract with Task 7's script (Paul, 2026-11-18).** The module takes `drill`, `object({ endpoints_open = bool, foreign_principal_arn = string })`, default `null`. A deployment root that runs the endpoint drill calls this module as `module "media_engine"`, declares `variable "media_engine_drill"` of that type with default `null`, and passes it as `drill`; it needs no other `-var` to apply. The script runs `tofu -chdir=<root> apply -input=false -auto-approve -var-file=<file> -target=…` under `AWS_PROFILE=<dev profile>`, the file holding only `{"media_engine_drill": …}`, and targets exactly these five addresses, which therefore must exist under these names: `module.media_engine.aws_vpc_endpoint_policy.s3`, `.ecr_api`, `.ecr_dkr`, `.logs` (the endpoints themselves set no inline `policy`) and `module.media_engine.aws_ecr_repository_policy.engine`. The three values:
+ - `null` (off, the default): the endpoint policies below; no repository policy (`count = 0`), so no foreign principal.
+ - `{ endpoints_open = false, foreign_principal_arn = <user> }`: the same endpoint policies; the repository policy holds one statement, Sid `CarlosMediaEndpointDrill`, allowing that principal `ecr:BatchGetImage`, `ecr:GetDownloadUrlForLayer` and `ecr:BatchCheckLayerAvailability`.
+ - `{ endpoints_open = true, foreign_principal_arn = <user> }`: that repository policy, and each of the four endpoints under AWS's default full-access policy, written out as `{"Version":"2008-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"*","Resource":"*"}]}`.
+
+ A non-null `foreign_principal_arn` must match `^arn:aws:iam::[0-9]{12}:user/carlos-media-drill-[0-9a-f]{16}$` and must not be in the module's own account. Nothing but these five resources may depend on `drill`.
+- [ ] **Step 1: Write the failing tests.** Besides the runs below: `drill_off_by_default` (no repository policy, the locked endpoint policies), `drill_closed_admits_only_the_user` (the endpoint policies unchanged, one repository statement), `drill_open_opens_only_the_endpoints`, `drill_refuses_another_principal` (`expect_failures`, a role ARN and an ARN in the module's account), and a Go test that no deployment root in this repository sets `media_engine_drill` to anything but `null` outside dev. `media_engine.tftest.hcl` with `mock_provider "aws" {}`, runs: `region_must_be_store_region` (`expect_failures`); `no_digest_creates_only_the_repository` (no task definitions, `carlos_media_engine == ""`); `task_definitions_pass_the_gate` (for each of four: `task_role_arn == null`, `pid_mode == null`, ARM64, and on `jsondecode(container_definitions)`: names, essential, `dependsOn` `deadline`/`START`, `stopTimeout` 30 both, read-only root, user, caps drop `ALL`, images equal `<repo>@<digest>`, `scratch` mounted in `codec` only, CPU and memory per class); `endpoint_policies_name_their_principals` (every statement of the three interface policies has the execution-role condition; the S3 policy's two statements exactly); `tasks_sg_has_no_ingress_and_only_https_egress`; `no_default_route`; `dns_firewall_allows_three_services_and_blocks_the_rest`; `conversion_role_policy_exact` (three Allows, two Denies, trust only the console role); `console_policy_exact`; `reaper_role_is_cluster_scoped`; `output_parses` (the output's JSON has `v` 1, the region, four task definitions and the image). `reaper_test.py` (stdlib `unittest`, a stub client): an old task is stopped, a young one is not, pagination across two pages, a describe failure stops nothing.
- [ ] **Step 2:** Run `cd infra/modules/media-engine && tofu init -backend=false && tofu test` and `python3 -I -m unittest discover -s infra/modules/media-engine/reaper`. Expected: FAIL.
- [ ] **Step 3:** Implement. `tofu fmt -check` and `tofu validate` clean. Write the README in `pdf-host`'s shape (what it is, the two-phase apply: repository first, then the digest; wiring `carlos_media_engine` → `CARLOS_MEDIA_ENGINE`; the region rule; the activation gates of spec §5.5; rollback by digest); copy-review it.
- [ ] **Step 4:** Rerun Step 2's commands. Expected: PASS.
@@ -309,7 +316,7 @@ 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.
+- [ ] Ask Paul (profile `kass`, `eu-west-1`), including the endpoint drill's scope (Task 7), all of it made and removed by the drill script's one run in R3. The fixture root `scripts/media-endpoint-drill/`, with local state in the run directory: in an unrelated account he names (with a profile of his allowed to create them), one IAM user 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, and one access key the script mints for that user; in dev, a drill bucket with one object and a bucket policy admitting that user. The dev root, through `media_engine_drill`, targeted at its five policy resources: for the length of the run a repository policy admitting that user, and, for minutes, the four endpoint policies under AWS's default full-access policy; `null` again at the end. In the dev root: `store_conversion = true` on the console's region-host; `media-engine` as `module "media_engine"` with `image_digest = ""` and `drill = var.media_engine_drill` (default `null`); 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, `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
@@ -317,10 +324,10 @@ Ask each time with the account, region, resources, cost, duration, traffic effec
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> --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.
+- [ ] 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> --engine-root <the dev root's directory>`. Expected: `endpoints-verdict` exits 0 (A refused, B ok, C refused at all four endpoints) and every restore line reads `cleaned`. Record the table and the restore 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` (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.
+- [ ] If the drill's run printed any `NOT CLEANED` line or was killed, run `scripts/media-endpoint-drill.sh restore <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.
### R4: Dev drills with the door on (spec §9)
diff --git a/scripts/media-endpoint-drill.sh b/scripts/media-endpoint-drill.sh
index 6d9d6efef..3b79d48f3 100755
--- a/scripts/media-endpoint-drill.sh
+++ b/scripts/media-endpoint-drill.sh
@@ -6,63 +6,51 @@
# media-endpoint-drill.sh run --profile <dev profile> --foreign-profile <profile>
# --cluster <cluster arn> --task-definition <arn> --repository <name>
# --bucket <drill bucket name> --subnets <subnet,...> --security-group <sg>
-# media-endpoint-drill.sh cleanup <run dir>
+# --engine-root <the deployment root that calls media-engine>
+# media-endpoint-drill.sh restore <run dir>
#
# It proves that credentials of an unrelated account cannot use any of
# the engine VPC's four endpoints (S3 gateway, ECR API, ECR Docker,
-# Logs), by controls, never by error text. It provisions a user in the
-# foreign account whose own policy, and whose target resources, admit
-# one S3 GET, an ECR token and an image pull, and log writes to a drill
-# log group; mints the presigned GET, the registry token and the log
-# stream outside the VPC (here); then runs `carlos-media drill endpoints`
-# in a media task three times: under the endpoints' saved policies
-# (phase A: every endpoint must refuse), under AWS's default full-access
-# policy (phase B: every endpoint must answer ok, which is what makes a
-# refusal in A and C the policy's doing), and under the restored
-# policies (phase C: every endpoint must refuse again).
-# `carlos-media drill endpoints-verdict` prints the table and decides.
+# Logs), by controls, never by error text: the same four requests from
+# inside a media task are refused under the endpoints' real policies
+# (phase A), succeed under AWS's full-access policy (phase B, which is
+# what makes a refusal the policy's doing), and are refused again once
+# the real policies are back (phase C).
#
-# Before anything is made, both profiles' identities are read: the dev
-# profile must be the cluster's account and the foreign one another.
+# OpenTofu owns everything the drill changes, so this script keeps no
+# record of its own:
#
-# 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".
+# - scripts/media-endpoint-drill/ is the fixture: the foreign user, its
+# log group, and the drill bucket with its object and policy. It is
+# copied into the run directory and applied with local state there.
+# - The engine root owns the endpoint and repository policies. Its
+# variable media_engine_drill (plan 3 Task 11) is null when the drill
+# is off; {endpoints_open = false, foreign_principal_arn = <user>}
+# keeps the real endpoint policies and admits the user to the
+# repository, so that only the endpoints differ between the phases;
+# endpoints_open = true opens them. Only the five policy resources are
+# targeted, so nothing else pending in that root is applied.
#
-# Cleanup is unconditional: the run directory and the EXIT trap exist
-# 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).
+# The flow: apply the fixture; mint the user's key, the registry token and
+# the presigned GET; pass A with the endpoints closed; open them; pass B;
+# close them; pass C; print the verdict. A trap restores on every exit:
+# the engine root is applied with the drill off and the fixture destroyed,
+# which also deletes the key (force_destroy). `restore <run dir>` does the
+# same again, for a SIGKILL or a lost machine, and can be repeated. Each
+# item is reported "cleaned <item>" or "NOT CLEANED <item>" from what tofu
+# answers; any NOT CLEANED makes the exit non-zero and keeps the run
+# directory.
#
# 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.
+# reach tofu, its state or 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; 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).
+# Every call goes through ${AWS:-aws} and ${TOFU:-tofu}. MEDIA_DRILL_INTERVAL,
+# MEDIA_DRILL_PASSES, MEDIA_DRILL_IAM_WAIT and MEDIA_DRILL_LOG_WAIT shorten
+# the waits for tests. CARLOS_MEDIA is the command that runs carlos-media
+# (default: carlos-media on PATH, else `go run` of cmd/carlos-media here).
# Tracing would print the secrets: refuse it before anything else.
case "$-" in
@@ -77,17 +65,30 @@ set -uo pipefail
umask 077
AWS="${AWS:-aws}"
+TOFU="${TOFU:-tofu}"
interval="${MEDIA_DRILL_INTERVAL:-60}"
passes="${MEDIA_DRILL_PASSES:-5}"
iam_wait="${MEDIA_DRILL_IAM_WAIT:-10}"
log_wait="${MEDIA_DRILL_LOG_WAIT:-5}"
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-usage="usage: media-endpoint-drill.sh run --profile <p> --foreign-profile <p> --cluster <arn> --task-definition <arn> --repository <name> --bucket <name> --subnets <id,...> --security-group <id> | cleanup <run dir>"
+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> --engine-root <dir> | restore <run dir>"
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"
+# The five resources the engine root's drill input changes (plan 3 Task 11).
+engine_targets=(
+ -target=module.media_engine.aws_vpc_endpoint_policy.s3
+ -target=module.media_engine.aws_vpc_endpoint_policy.ecr_api
+ -target=module.media_engine.aws_vpc_endpoint_policy.ecr_dkr
+ -target=module.media_engine.aws_vpc_endpoint_policy.logs
+ -target=module.media_engine.aws_ecr_repository_policy.engine
+)
+
+bg_pid=""
+current_task=""
+restoring=""
+changed=""
+rundir=""
say() { printf 'media-endpoint-drill: %s\n' "$*" >&2; }
die() { say "$*"; exit 1; }
@@ -104,118 +105,6 @@ carlos_media() {
fi
}
-# 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() {
- 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. The
@@ -228,22 +117,28 @@ as_user() (
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).
-gone_ok() {
- local codes="$1" err
+# tf runs tofu in directory $1, its output to the run directory's log. In
+# the background, so a signal is handled at once; the trap then stops it
+# and waits for it before restoring.
+tf() {
+ local dir="$1" rc
shift
- err="$("$@" 2>&1 >/dev/null)" && return 0
- grep -Eq "$codes" <<<"$err"
+ "$TOFU" "-chdir=$dir" "$@" -no-color >>"$rundir/tofu.log" 2>&1 &
+ bg_pid=$!
+ wait "$bg_pid"
+ rc=$?
+ bg_pid=""
+ return "$rc"
}
-# fails_with succeeds only when the command fails naming one of $1.
-fails_with() {
- local codes="$1" err
- shift
- err="$("$@" 2>&1 >/dev/null)" && return 1
- grep -Eq "$codes" <<<"$err"
-}
+# engine_tf is tf in the engine root, under the dev profile.
+engine_tf() { AWS_PROFILE="$profile" tf "$engine_root" "$@"; }
+
+# fixture_tf is tf in the run directory's copy of the fixture.
+fixture_tf() { tf "$rundir/fixture" "$@"; }
+
+# write_off writes the variable file that turns the drill off.
+write_off() { printf '{"media_engine_drill":null}\n' >"$rundir/engine-off.tfvars.json"; }
# retry runs a command up to 6 times, iam_wait seconds apart (IAM's new
# users and keys take a few seconds to be usable everywhere).
@@ -268,265 +163,103 @@ 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" ]
+# report_line prints "cleaned <item>" or "NOT CLEANED <item>".
+report_line() {
+ if [ "$1" = 0 ]; then
+ printf 'cleaned %s\n' "$2"
+ return 0
+ fi
+ printf 'NOT CLEANED %s\n' "$2"
+ return 1
}
-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" ]
+
+# restore_engine applies the engine root with the drill off, and asks tofu
+# whether anything is left to change.
+restore_engine() {
+ write_off || return 1
+ engine_tf init -input=false || return 1
+ engine_tf apply -input=false -auto-approve "-var-file=$rundir/engine-off.tfvars.json" "${engine_targets[@]}" || return 1
+ engine_tf plan -input=false -detailed-exitcode "-var-file=$rundir/engine-off.tfvars.json" "${engine_targets[@]}"
+}
+
+# restore_fixture destroys the fixture and asks tofu whether its state
+# still holds anything. A run that never wrote the fixture has none.
+restore_fixture() {
+ [ -f "$rundir/fixture/terraform.tfvars.json" ] || return 0
+ fixture_tf init -input=false || return 1
+ fixture_tf destroy -input=false -auto-approve || return 1
+ local left
+ left="$("$TOFU" "-chdir=$rundir/fixture" state list 2>>"$rundir/tofu.log")" || return 1
+ [ -z "$left" ]
+}
+
+# restore puts everything back and reports each item: the engine's
+# policies first (the fixture's user is named in them), then the fixture,
+# whichever way the first went, so the foreign key never outlives a failed
+# apply. False when any item is not clean.
+restore() {
+ local ok=0 rc
+ rm -f -- "$rundir/input.json" "$rundir/overrides.json"
+ restore_engine
+ rc=$?
+ report_line "$rc" engine-policies || ok=1
+ restore_fixture
+ rc=$?
+ report_line "$rc" fixture || ok=1
+ rc=0
+ [ ! -e "$rundir/input.json" ] && [ ! -e "$rundir/overrides.json" ] || rc=1
+ report_line "$rc" input || ok=1
+ return "$ok"
}
-bg_pid=""
-cleaning=""
-run_id=""
-made_rundir=""
-
-# 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() {
+# finish is the EXIT trap and the restore subcommand's end: stop what is
+# in flight, restore, and set the exit. $1 is the status being left with.
+finish() {
local status="${1:-0}"
- [ -n "$cleaning" ] && return
- cleaning=1
+ [ -z "$restoring" ] || return
+ restoring=1
trap '' INT TERM HUP
if [ -n "$bg_pid" ]; then
- kill "$bg_pid" 2>/dev/null
+ kill -TERM "$bg_pid" 2>/dev/null
wait "$bg_pid" 2>/dev/null
+ bg_pid=""
fi
- 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"
+ if [ -n "$current_task" ]; then
+ dev ecs stop-task --cluster "$cluster" --task "$current_task" --reason "carlos media endpoint drill restore" >/dev/null 2>&1
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
+ if [ -z "$changed" ]; then
+ [ -z "$rundir" ] || rm -rf -- "$rundir"
exit "$status"
fi
- load_state
- rm -f -- "$rundir/input.json" "$rundir/overrides.json"
- undo
- if verify; then
+ if restore; then
rm -rf -- "$rundir"
exit "$status"
fi
- say "kept $rundir; finish with: $0 cleanup $rundir"
- [ "$status" = 0 ] && status=3
+ say "kept $rundir; finish with: $0 restore $rundir"
+ [ "$status" != 0 ] || status=3
exit "$status"
}
-load_state() {
- run_id="$(state_value run)"
- profile="$(state_value profile)"
- foreign_profile="$(state_value foreign-profile)"
- region="$(state_value region)"
- cluster="$(state_value cluster)"
- repository="$(state_value repository)"
- bucket="$(state_value bucket)"
- user="$(state_value user)"
- log_group="$(state_value log-group)"
-}
-
-# endpoint_ids prints "label id" for each endpoint whose policy was saved.
-endpoint_ids() { 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.
- 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 < <(endpoint_ids)
- fi
- 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
- 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
-}
-
-# 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
- # 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 "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 "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
- 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
- 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
- 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
- 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"
+# write_conf records the two values restore needs and reads them back.
+# It is written once, before the first change.
+write_conf() {
+ local want="profile=$profile"$'\n'"engine_root=$engine_root"
+ printf '%s\n' "$want" >"$rundir/drill.conf" || return 1
+ [ "$(<"$rundir/drill.conf")" = "$want" ]
}
-# verify checks each obligation and prints its line; false if any is not
-# 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
- clean=1
- while read -r label id; do
- [ -n "$label" ] || continue
- dev ec2 describe-vpc-endpoints --vpc-endpoint-ids "$id" --query 'VpcEndpoints[0].PolicyDocument' --output text \
- >"$rundir/now-$label.json" 2>/dev/null && cmp -s "$rundir/now-$label.json" "$rundir/policy-$label.json" || clean=""
- done < <(endpoint_ids)
- report_line "$clean" endpoint-policies || ok=1
- clean=1
- 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=""
- else
- fails_with 'RepositoryPolicyNotFoundException' dev ecr get-repository-policy --repository-name "$repository" || clean=""
- fi
- fi
- report_line "$clean" repository-policy || ok=1
- clean=1
- 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
- clean=1
- 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
- clean=1
- if recorded "creating log-group"; then
- [ -z "${uncertain[log-group]:-}" ] || clean=""
- log_group_exists && clean=""
- fi
- report_line "$clean" log-group || ok=1
- clean=1
- [ -e "$rundir/input.json" ] || [ -e "$rundir/overrides.json" ] && clean=""
- report_line "$clean" input || ok=1
- return "$ok"
-}
-
-# report_line prints "cleaned <obligation>" or "NOT CLEANED <obligation>".
-report_line() {
- if [ -n "$1" ]; then
- printf 'cleaned %s\n' "$2"
- return 0
- fi
- printf 'NOT CLEANED %s\n' "$2"
- return 1
+# read_conf reads drill.conf strictly: both values there, each of its shape.
+read_conf() {
+ local key value
+ profile="" engine_root=""
+ while IFS='=' read -r key value; do
+ case "$key" in
+ profile) [[ "$value" =~ ^[A-Za-z0-9._-]+$ ]] || return 1; profile="$value" ;;
+ engine_root) [[ "$value" =~ ^/[A-Za-z0-9._/+-]+$ ]] || return 1; engine_root="$value" ;;
+ *) return 1 ;;
+ esac
+ done <"$rundir/drill.conf"
+ [ -n "$profile" ] && [ -n "$engine_root" ]
}
# all_lines is true when file $1 holds exactly one line per endpoint,
@@ -542,7 +275,7 @@ 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 input
+ local out="$1" arn task_id i input rc
: >"$out"
# The deadline container needs both values (preflight F25); the
# codec container gets the drill's input. Builtins only: the input is
@@ -551,20 +284,20 @@ run_pass() {
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))" "${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=$?
+ rc=$?
rm -f -- "$rundir/overrides.json"
[ "$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"
+ current_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.
+ # subshell), so a signal is handled at once and the trap can stop it.
"$AWS" --profile "$profile" --region "$region" ecs wait tasks-stopped --cluster "$cluster" --tasks "$arn" &
bg_pid=$!
wait "$bg_pid" || say "the drill task did not stop in time"
bg_pid=""
+ current_task=""
task_id="${arn##*/}"
for i in 1 2 3 4 5; do
dev logs get-log-events --log-group-name "$engine_log_group" --log-stream-name "$engine_log_prefix/codec/$task_id" \
@@ -579,179 +312,107 @@ run_pass() {
# 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 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="$(foreign sts get-caller-identity --query Account --output text)" || die "the foreign profile does not answer"
[[ "$foreign_account" =~ ^[0-9]{12}$ ]] || die "the foreign profile has no account"
[ "$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"
- while read -r id line; do
- case "$line" in
- *.s3) endpoint_id[s3]="$id" ;;
- *.ecr.api) endpoint_id[ecr-api]="$id" ;;
- *.ecr.dkr) endpoint_id[ecr-docker]="$id" ;;
- *.logs) endpoint_id[logs]="$id" ;;
- esac
- done < <(dev ec2 describe-vpc-endpoints --filters "Name=vpc-id,Values=$vpc" --query 'VpcEndpoints[].[VpcEndpointId,ServiceName]' --output text)
- for label in "${endpoints[@]}"; do
- [[ "${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' \
- --output text >"$rundir/policy-$label.json" || die "the $label endpoint's policy cannot be read"
- record "endpoint $label ${endpoint_id[$label]}"
- done
- if policy="$(dev ecr get-repository-policy --repository-name "$repository" --query policyText --output text 2>"$rundir/err")"; then
- printf '%s\n' "$policy" >"$rundir/repo-policy.json"
- record "repo-policy saved"
- elif grep -q RepositoryPolicyNotFoundException "$rundir/err"; then
- record "repo-policy none"
- else
- die "the repository policy cannot be read"
- fi
+# read_task_definition reads the codec's image and log stream.
+read_task_definition() {
+ local image
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"
manifest_url="https://${BASH_REMATCH[1]}/v2/${BASH_REMATCH[2]}/manifests/${BASH_REMATCH[3]}"
+ [ "${BASH_REMATCH[2]}" = "$repository" ] || die "the codec image is not from --repository"
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"
}
-# 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 "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 "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"
+# check_engine_root refuses a root without the drill's variable, and one
+# whose policies have changes pending: restore would apply those too.
+check_engine_root() {
+ grep -qs 'variable "media_engine_drill"' "$engine_root"/*.tf || die "the engine root declares no media_engine_drill variable"
+ write_off || die "the run directory cannot be written"
+ engine_tf init -input=false || die "the engine root does not initialise"
+ engine_tf plan -input=false -detailed-exitcode "-var-file=$rundir/engine-off.tfvars.json" "${engine_targets[@]}" ||
+ die "the engine root's policies have changes pending; apply or revert them first"
}
-# 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 "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"
- 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"
+# prepare_fixture copies the fixture into the run directory and writes
+# its variables: names and account ids only.
+prepare_fixture() {
+ mkdir "$rundir/fixture" || die "the run directory cannot be written"
+ cp "$here/media-endpoint-drill/main.tf" "$here/media-endpoint-drill/variables.tf" "$rundir/fixture/" || die "the fixture cannot be copied"
+ printf '{"run_id":"%s","region":"%s","dev_profile":"%s","foreign_profile":"%s","dev_account_id":"%s","foreign_account_id":"%s","bucket":"%s","repository_arn":"%s"}\n' \
+ "$run_id" "$region" "$profile" "$foreign_profile" "$dev_account" "$foreign_account" "$bucket" \
+ "arn:aws:ecr:$region:$dev_account:repository/$repository" >"$rundir/fixture/terraform.tfvars.json" || die "the fixture's variables cannot be written"
}
-# 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
- repo_policy="$(python3 -I -c 'import json,sys
-p = json.load(open(sys.argv[1]))
-s = p.get("Statement", [])
-p["Statement"] = (s if isinstance(s, list) else [s]) + [json.loads(sys.argv[2])]
-print(json.dumps(p))' "$rundir/repo-policy.json" "$grant")" || die "the repository grant cannot be written"
- fi
- 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"
+# apply_fixture applies the fixture and checks the user it made.
+apply_fixture() {
+ say "applying the fixture"
+ fixture_tf init -input=false || die "the fixture does not initialise"
+ fixture_tf apply -input=false -auto-approve || die "the fixture was not applied"
+ user_arn="$("$TOFU" "-chdir=$rundir/fixture" output -raw user_arn 2>>"$rundir/tofu.log")" || die "the fixture has no user"
+ [ "$user_arn" = "arn:aws:iam::$foreign_account:user/$user" ] || die "the fixture's user is not the expected one"
}
-# 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 makes, outside the VPC, the user's key (with the CLI, so it never
+# reaches tofu's state) and, with that key alone, the presigned GET, the
+# registry token and the log stream, and writes input.json.
mint() {
- local s3_url token
+ local keys s3_url token v
+ keys="$(retry 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"
+ keys=""
+ [[ "${user_key_id:-}" =~ ^AKIA[A-Z0-9]+$ ]] && [ -n "${user_secret:-}" ] || die "the user's key was not created"
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" "$manifest_url" "$region" "$user_key_id" "$user_secret" "$log_group" "$log_stream" >"$rundir/input.json"
+ "$s3_url" "$token" "$manifest_url" "$region" "$user_key_id" "$user_secret" "$log_group" "$log_stream" >"$rundir/input.json" ||
+ die "the drill's input cannot be written"
s3_url="" token="" user_secret=""
}
+# set_endpoints applies the engine root with the user admitted to the
+# repository and the endpoints open ($1 true) or under their real
+# policies ($1 false).
+set_endpoints() {
+ printf '{"media_engine_drill":{"endpoints_open":%s,"foreign_principal_arn":"%s"}}\n' "$1" "$user_arn" >"$rundir/engine-drill.tfvars.json" ||
+ die "the engine root's variables cannot be written"
+ engine_tf apply -input=false -auto-approve "-var-file=$rundir/engine-drill.tfvars.json" "${engine_targets[@]}" ||
+ die "the engine root was not applied"
+}
+
# phases runs A, B and C and the verdict.
phases() {
- local label n
- say "phase A: the saved endpoint policies"
+ local n
+ say "phase A: the endpoints' real policies"
+ set_endpoints false
run_pass "$rundir/A.out"
: >"$rundir/B.out"
: >"$rundir/C.out"
if all_lines "$rundir/A.out" 'refused (conn|[0-9]{3})'; then
say "phase B: the endpoints opened to full access"
- 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
+ set_endpoints true
for ((n = 1; n <= passes; n++)); do
pause "$interval"
run_pass "$rundir/B.out"
all_lines "$rundir/B.out" ok && break
done
- 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"
- done
- record "restored endpoints"
+ say "phase C: the endpoints' real policies again"
+ set_endpoints false
for ((n = 1; n <= passes; n++)); do
pause "$interval"
run_pass "$rundir/C.out"
@@ -764,7 +425,7 @@ phases() {
}
main_run() {
- local profile_="" foreign_="" cluster_="" td_="" repo_="" bucket_="" subnets_="" sg_=""
+ local profile_="" foreign_="" cluster_="" td_="" repo_="" bucket_="" subnets_="" sg_="" root_="" v
while [ $# -gt 0 ]; do
case "$1" in
--profile) profile_="${2:-}" ;;
@@ -775,16 +436,21 @@ main_run() {
--bucket) bucket_="${2:-}" ;;
--subnets) subnets_="${2:-}" ;;
--security-group) sg_="${2:-}" ;;
+ --engine-root) root_="${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
+ for v in "$profile_" "$foreign_" "$cluster_" "$td_" "$repo_" "$bucket_" "$subnets_" "$sg_" "$root_"; 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; }
+ [[ "$v" =~ ^[A-Za-z0-9._/-]+$ ]] || { echo "$usage" >&2; exit 2; }
done
+ [[ "$subnets_" =~ ^subnet-[0-9a-z]+(,subnet-[0-9a-z]+)*$ ]] && [[ "$sg_" =~ ^sg-[0-9a-z]+$ ]] || { echo "$usage" >&2; exit 2; }
+ [ -d "$root_" ] || die "--engine-root is not a directory"
+ engine_root="$(cd "$root_" && pwd)"
+ [[ "$engine_root" =~ ^/[A-Za-z0-9._/+-]+$ ]] || die "--engine-root has characters the drill cannot record"
[[ "$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]}"
@@ -793,38 +459,27 @@ main_run() {
# Nothing is made before both identities are known to be right.
identities
+ read_task_definition
- # 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 'finish $?' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
+ say "run directory $rundir"
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
+ check_engine_root
+ prepare_fixture
+ write_conf || die "the run directory cannot be written"
+
+ # From here on, every exit restores.
+ changed=1
+ apply_fixture
mint
phases
}
@@ -834,10 +489,17 @@ case "${1:-}" in
shift
main_run "$@"
;;
- cleanup)
- [ $# = 2 ] && [ -d "$2" ] && [ -e "$2/state" ] || { echo "$usage" >&2; exit 2; }
+ restore)
+ [ $# = 2 ] && [ -d "$2" ] && [ -e "$2/drill.conf" ] || { echo "$usage" >&2; exit 2; }
rundir="$(cd "$2" && pwd)"
- cleanup 0
+ if ! read_conf; then
+ say "$rundir/drill.conf is damaged; nothing was changed. Restore the engine root and destroy the fixture by hand."
+ report_line 1 engine-policies
+ report_line 1 fixture
+ exit 3
+ fi
+ changed=1
+ finish 0
;;
*)
echo "$usage" >&2
diff --git a/scripts/media-endpoint-drill/main.tf b/scripts/media-endpoint-drill/main.tf
new file mode 100644
index 000000000..2a41dc305
--- /dev/null
+++ b/scripts/media-endpoint-drill/main.tf
@@ -0,0 +1,115 @@
+# The endpoint drill's fixture (plan 3 Task 7): what the foreign user is
+# and what it is admitted to. scripts/media-endpoint-drill.sh copies this
+# root into its run directory, applies it with local state there, and
+# destroys it on every exit.
+#
+# It holds no secret. The user's access key is minted by the script with
+# the AWS CLI after the apply, so it never reaches this state, and
+# force_destroy on the user removes that key with it. The endpoint and
+# repository policies are not here: the media-engine root owns them,
+# through its `drill` input.
+
+terraform {
+ required_version = ">= 1.10"
+ required_providers {
+ aws = {
+ source = "hashicorp/aws"
+ version = ">= 6.0"
+ }
+ }
+}
+
+provider "aws" {
+ alias = "dev"
+ region = var.region
+ profile = var.dev_profile
+ allowed_account_ids = [var.dev_account_id]
+}
+
+provider "aws" {
+ alias = "foreign"
+ region = var.region
+ profile = var.foreign_profile
+ allowed_account_ids = [var.foreign_account_id]
+}
+
+locals {
+ object_key = "drill-object"
+ user_name = "carlos-media-drill-${var.run_id}"
+ log_group_name = "carlos-media-endpoint-drill-${var.run_id}"
+ object_arn = "${aws_s3_bucket.drill.arn}/${local.object_key}"
+}
+
+resource "aws_s3_bucket" "drill" {
+ provider = aws.dev
+ bucket = var.bucket
+ force_destroy = true
+
+ lifecycle {
+ precondition {
+ condition = var.dev_account_id != var.foreign_account_id
+ error_message = "The foreign account must not be the dev account."
+ }
+ }
+}
+
+resource "aws_s3_object" "drill" {
+ provider = aws.dev
+ bucket = aws_s3_bucket.drill.id
+ key = local.object_key
+ content = "carlos-media endpoint drill\n"
+}
+
+resource "aws_cloudwatch_log_group" "drill" {
+ provider = aws.foreign
+ name = local.log_group_name
+ retention_in_days = 1
+}
+
+resource "aws_iam_user" "drill" {
+ provider = aws.foreign
+ name = local.user_name
+ force_destroy = true
+}
+
+resource "aws_iam_user_policy" "drill" {
+ provider = aws.foreign
+ name = "carlos-media-endpoint-drill"
+ user = aws_iam_user.drill.name
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [
+ { Effect = "Allow", Action = "s3:GetObject", Resource = local.object_arn },
+ { Effect = "Allow", Action = "ecr:GetAuthorizationToken", Resource = "*" },
+ {
+ Effect = "Allow"
+ Action = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"]
+ Resource = var.repository_arn
+ },
+ {
+ Effect = "Allow"
+ Action = ["logs:CreateLogStream", "logs:PutLogEvents"]
+ Resource = "${aws_cloudwatch_log_group.drill.arn}:*"
+ },
+ ]
+ })
+}
+
+resource "aws_s3_bucket_policy" "drill" {
+ provider = aws.dev
+ bucket = aws_s3_bucket.drill.id
+ policy = jsonencode({
+ Version = "2012-10-17"
+ Statement = [{
+ Sid = "CarlosMediaEndpointDrill"
+ Effect = "Allow"
+ Principal = { AWS = aws_iam_user.drill.arn }
+ Action = "s3:GetObject"
+ Resource = local.object_arn
+ }]
+ })
+}
+
+output "user_arn" {
+ value = aws_iam_user.drill.arn
+}
diff --git a/scripts/media-endpoint-drill/variables.tf b/scripts/media-endpoint-drill/variables.tf
new file mode 100644
index 000000000..db405fd97
--- /dev/null
+++ b/scripts/media-endpoint-drill/variables.tf
@@ -0,0 +1,43 @@
+variable "run_id" {
+ description = "The drill run's id, 16 hex characters: names the user and the log group."
+ type = string
+ validation {
+ condition = can(regex("^[0-9a-f]{16}$", var.run_id))
+ error_message = "run_id must be 16 lower-case hex characters."
+ }
+}
+
+variable "region" {
+ description = "The engine's region. The bucket and the log group are made there."
+ type = string
+}
+
+variable "dev_profile" {
+ description = "The AWS profile of the account the engine runs in."
+ type = string
+}
+
+variable "foreign_profile" {
+ description = "The AWS profile of the unrelated account."
+ type = string
+}
+
+variable "dev_account_id" {
+ description = "The dev profile must be this account."
+ type = string
+}
+
+variable "foreign_account_id" {
+ description = "The foreign profile must be this account."
+ type = string
+}
+
+variable "bucket" {
+ description = "The drill bucket's name, in the dev account."
+ type = string
+}
+
+variable "repository_arn" {
+ description = "The engine's image repository, which the user may pull from."
+ type = string
+}
diff --git a/scripts/media_endpoint_drill_test.py b/scripts/media_endpoint_drill_test.py
index c30612d59..e84a1b193 100644
--- a/scripts/media_endpoint_drill_test.py
+++ b/scripts/media_endpoint_drill_test.py
@@ -1,26 +1,27 @@
"""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 (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
-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.
+drill (plan 3 Task 7), with no AWS call: `tofu` and `aws` are fakes on PATH,
+one Python script that logs each call (its argv and environment) and keeps
+a fake world in a JSON file: the engine root's drill variable, the fixture's
+resources and the foreign user's keys. It fails, or blocks until signalled,
+on demand.
+
+OpenTofu owns what the drill changes, so the subject is the orchestration:
+whatever ends a run, the drill ends off and the fixture destroyed, or the run
+says what it could not clean; `restore` converges when repeated; the verdict
+needs all three phases; and no secret reaches an argument list, a trace or
+tofu's variables.
+
+`carlos-media` is the real binary when MEDIA_DRILL_CARLOS_MEDIA names one (the
+Go test TestMediaEndpointDrillPythonGuards builds it), else a small fake.
Run from the repo root: python3 -m unittest scripts/media_endpoint_drill_test.py
-(the Go test TestMediaEndpointDrillPythonGuards runs it in CI).
"""
import json
import os
from pathlib import Path
import shutil
import signal
+import stat
import subprocess
import sys
import tempfile
@@ -28,6 +29,7 @@ import time
import unittest
SCRIPT = Path(__file__).with_name('media-endpoint-drill.sh')
+FIXTURE = Path(__file__).with_name('media-endpoint-drill')
REGION = 'eu-west-1'
DEV = '123456789012'
@@ -40,489 +42,496 @@ 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', '[']
-
+TARGETS = ['aws_vpc_endpoint_policy.s3', 'aws_vpc_endpoint_policy.ecr_api', 'aws_vpc_endpoint_policy.ecr_dkr',
+ 'aws_vpc_endpoint_policy.logs', 'aws_ecr_repository_policy.engine']
+ITEMS = ['engine-policies', 'fixture', 'input']
+# The programs the script runs: each is wrapped in the argv test.
+TOOLS = ['grep', 'cat', 'tr', 'od', 'date', 'rm', 'mktemp', 'sleep', 'cp', 'mkdir', 'dirname', 'env', 'printf', 'echo']
+
+# One fake, installed as both `aws` and `tofu`. A step is named
+# "aws <service> <op>" or "<fixture|engine> <subcommand>", and an engine
+# apply also by the drill it sets: "engine apply off|closed|open". "#n" on a
+# step means its nth occurrence.
+FAKE = r'''
+import fcntl, json, os, signal, sys, time
+
+world_path = os.environ['FAKE_WORLD']
+tool = os.path.basename(sys.argv[0])
+args = sys.argv[1:]
-def original_policy(label):
- return ('{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"*","Resource":"*",'
- f'"Condition":{{"StringEquals":{{"aws:PrincipalArn":"arn:aws:iam::{DEV}:role/media-{label}"}}}}}}]}}')
+class World:
+ def __enter__(self):
+ self.lock = open(world_path + '.lock', 'w')
+ fcntl.flock(self.lock, fcntl.LOCK_EX)
+ with open(world_path) as f:
+ self.w = json.load(f)
+ return self.w
+
+ def __exit__(self, *exc):
+ tmp = world_path + '.tmp'
+ with open(tmp, 'w') as f:
+ json.dump(self.w, f)
+ os.replace(tmp, world_path)
+ self.lock.close()
+
+
+def block_until_signalled(marker):
+ stop = []
+ signal.signal(signal.SIGTERM, lambda *a: stop.append(1))
+ with open(marker + '.tmp', 'w') as f:
+ f.write(str(os.getpid()))
+ os.replace(marker + '.tmp', marker)
+ deadline = time.monotonic() + 60
+ while not stop and time.monotonic() < deadline:
+ time.sleep(0.01)
+
+
+def gate(step, record):
+ """Records the call; answers (failed, interrupted)."""
+ with World() as w:
+ w['calls'].append({**record, 'step': step})
+ w['seen'][step] = n = w['seen'].get(step, 0) + 1
+ names = (step, f'{step}#{n}')
+ blocked = w.get('block') in names
+ marker = w['marker']
+ if blocked:
+ w['block'] = None
+ left = 0
+ for name in names:
+ if name in w['fail'] and w['fail'][name] != 0:
+ left = w['fail'][name]
+ w['fail'][name] = left - 1 if left > 0 else left
+ if blocked:
+ block_until_signalled(marker)
+ return left != 0, blocked
+
+
+def flag(name):
+ for a in args:
+ if a.startswith(name + '='):
+ return a[len(name) + 1:]
+ return None
+
+
+def tofu():
+ chdir = args[0][len('-chdir='):]
+ sub = args[1]
+ kind = 'fixture' if chdir.endswith('/fixture') else 'engine'
+ step = f'{kind} {sub}'
+ var_file, drill = flag('-var-file'), 'absent'
+ if var_file:
+ with open(var_file) as f:
+ content = f.read()
+ drill = json.loads(content)['media_engine_drill']
+ if kind == 'engine' and sub == 'apply':
+ step += ' off' if drill is None else ' open' if drill['endpoints_open'] else ' closed'
+ tfvars = ''
+ if kind == 'fixture' and os.path.exists(chdir + '/terraform.tfvars.json'):
+ with open(chdir + '/terraform.tfvars.json') as f:
+ tfvars = f.read()
+ failed, interrupted = gate(step, {'tool': 'tofu', 'argv': sys.argv, 'env': dict(os.environ), 'chdir': chdir,
+ 'var_file': open(var_file).read() if var_file else '', 'tfvars': tfvars})
+ if failed:
+ print('Error: injected', file=sys.stderr)
+ sys.exit(1)
+ plan_exit = 0
+ with World() as w:
+ if kind == 'engine' and sub == 'apply':
+ w['engine'] = drill
+ w['engine_history'].append(drill)
+ if kind == 'engine' and sub == 'plan':
+ pending = w.get('pending_plan', False) or w['engine'] != drill
+ plan_exit = 2 if pending else 0
+ if kind == 'fixture' and sub == 'apply':
+ v = json.loads(tfvars)
+ w['fixture'] = ['aws_s3_bucket.drill', 'aws_s3_object.drill', 'aws_s3_bucket_policy.drill',
+ 'aws_iam_user.drill', 'aws_iam_user_policy.drill', 'aws_cloudwatch_log_group.drill']
+ w['user'] = f'carlos-media-drill-{v["run_id"]}'
+ fd = os.open(chdir + '/terraform.tfstate', os.O_WRONLY | os.O_CREAT, 0o666)
+ os.close(fd)
+ w['state_mode'] = os.stat(chdir + '/terraform.tfstate').st_mode & 0o777
+ w['dir_mode'] = os.stat(os.path.dirname(chdir)).st_mode & 0o777
+ if kind == 'fixture' and sub == 'destroy' and not w.get('destroy_lies'):
+ w['fixture'] = []
+ w['keys'] = []
+ listing, user = list(w['fixture']), w.get('user')
+ if interrupted:
+ sys.exit(1)
+ if sub == 'plan':
+ sys.exit(plan_exit)
+ if sub == 'state':
+ print('\n'.join(listing))
+ if sub == 'output':
+ print(f'arn:aws:iam::{FOREIGN}:user/{user}', end='')
+
+
+def aws():
+ a, opts = list(args), {}
+ pos = []
+ while a:
+ x = a.pop(0)
+ if x.startswith('--'):
+ opts[x[2:]] = a.pop(0) if a and not a[0].startswith('--') else ''
+ else:
+ pos.append(x)
+ name = f'{pos[0]} {pos[1]}'
+ failed, interrupted = gate('aws ' + name, {'tool': 'aws', 'argv': sys.argv, 'env_key': 'AWS_ACCESS_KEY_ID' in os.environ,
+ 'profile': opts.get('profile'), 'opts': opts})
+ if failed or interrupted:
+ print('An error occurred (Injected) when calling the operation', file=sys.stderr)
+ sys.exit(254)
+ user_call = name in ('s3 presign', 'ecr get-authorization-token', 'logs create-log-stream')
+ if user_call and (opts.get('profile') or 'AWS_ACCESS_KEY_ID' not in os.environ):
+ sys.exit(253)
+ if not user_call and not opts.get('profile'):
+ sys.exit(252)
+ q = opts.get('query', '')
+ with World() as w:
+ if name == 'sts get-caller-identity':
+ print(w['accounts'][opts['profile']])
+ elif name == 'ecs describe-task-definition':
+ print('123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-media@sha256:' + 'ab' * 32 if 'image' in q else 'media-engine\tmedia')
+ elif name == 'iam create-access-key':
+ if opts['user-name'] != w.get('user') or not w['fixture']:
+ sys.exit(254)
+ w['keys'].append('AKIAFAKEDRILL0000000')
+ print('AKIAFAKEDRILL0000000\t' + os.environ['FAKE_SECRET'])
+ elif name == 's3 presign':
+ print(f'https://{BUCKET}.s3.eu-west-1.amazonaws.com/drill-object?X-Amz-Algorithm=AWS4-HMAC-SHA256'
+ f'&X-Amz-Signature={os.environ["FAKE_SIGNATURE"]}')
+ elif name == 'ecr get-authorization-token':
+ print(os.environ['FAKE_TOKEN'])
+ elif name == 'ecs run-task':
+ with open(opts['overrides'][len('file://'):]) as f:
+ w['overrides'].append(json.load(f))
+ w['task_seq'] += 1
+ arn = f'arn:aws:ecs:eu-west-1:123456789012:task/media/{w["task_seq"]:032x}'
+ d = w['engine']
+ state = 'off' if d is None else 'open' if d['endpoints_open'] else 'closed'
+ w['passes'].append(state)
+ ok = w['answers'].get(state, state == 'open')
+ w['tasks'][arn[-32:]] = [f'{e} ok' if ok else f'{e} refused 403' for e in ('s3', 'ecr-api', 'ecr-docker', 'logs')]
+ print(arn)
+ elif name == 'logs get-log-events':
+ print('\n'.join(w['tasks'][opts['log-stream-name'][-32:]]))
-FAKE_AWS = r'''
-import fcntl, glob, json, os, sys, time
-world_path = os.environ['FAKE_AWS_WORLD']
-args = sys.argv[1:]
-glob_opts, rest = {}, []
-i = 0
-while i < len(args):
- a = args[i]
- if a in ('--profile', '--region', '--query', '--output'):
- glob_opts[a[2:]] = args[i + 1]
- i += 2
- continue
- rest.append(a)
- i += 1
-service, op, opargs = rest[0], rest[1], rest[2:]
-opts, flags = {}, set()
-i = 0
-while i < len(opargs):
- a = opargs[i]
- if a in ('--reset-policy', '--start-from-head'):
- flags.add(a[2:])
- i += 1
- elif a.startswith('--'):
- opts[a[2:]] = opargs[i + 1] if i + 1 < len(opargs) else ''
- i += 2
- else:
- opts.setdefault('_', []).append(a)
- i += 1
-name = service + ' ' + op
-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_opts.get('profile'),
- 'env_key': 'AWS_ACCESS_KEY_ID' in os.environ, 'argv': sys.argv})
-
-
-def save():
- tmp = world_path + '.tmp'
- with open(tmp, 'w') as f:
- json.dump(world, f)
- os.replace(tmp, world_path)
-
-
-def out(s=''):
- save()
- if s:
- print(s)
- sys.exit(0)
-
-
-def err(code, msg='failed'):
- save()
- print(f'An error occurred ({code}) when calling the {op} operation: {msg}', file=sys.stderr)
- sys.exit(254)
-
-
-if world.get('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=''):
- if fail_after:
- err('InjectedFailure', 'injected after the change')
- 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_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_opts.get('profile'):
- err('NoProfile', 'an operator call named no profile')
-if name == 'sts get-caller-identity':
- out(world['accounts'][glob_opts['profile']])
-if name == 'ec2 describe-subnets':
- out('vpc-0drill')
-if name == 'ec2 describe-vpc-endpoints':
- if 'vpc-endpoint-ids' in opts:
- out(eps[opts['vpc-endpoint-ids']]['policy'])
- out('\n'.join(f'{k}\t{v["service"]}' for k, v in eps.items()))
-if name == 'ec2 modify-vpc-endpoint':
- ep = eps[opts['vpc-endpoint-id']]
- ep['policy'] = world['default_policy'] if 'reset-policy' in flags else opts['policy-document']
- done('{"Return": true}')
-if name == 'ecr get-repository-policy':
- if world['repo_policy'] is None:
- err('RepositoryPolicyNotFoundException', 'Repository policy does not exist')
- out(world['repo_policy'])
-if name == 'ecr set-repository-policy':
- world['repo_policy'] = opts['policy-text']
- done('{}')
-if name == 'ecr delete-repository-policy':
- if world['repo_policy'] is None:
- err('RepositoryPolicyNotFoundException', 'Repository policy does not exist')
- world['repo_policy'] = None
- done('{}')
-if name == 'ecs describe-task-definition':
- if 'image' in query:
- out('123456789012.dkr.ecr.eu-west-1.amazonaws.com/carlos-media@sha256:' + 'ab' * 32)
- out('media-engine\tmedia')
-buckets = world['buckets']
-if name == 's3api head-bucket':
- if opts['bucket'] in buckets:
- out()
- err('404', 'Not Found')
-if name == 's3api create-bucket':
- if 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, '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('{}')
-if name == 's3api put-bucket-policy':
- b['policy'] = opts['policy']
- done()
-if name == 's3api delete-bucket-policy':
- b['policy'] = None
- done()
-if name == 's3api delete-object':
- if opts['key'] in b['objects']:
- b['objects'].remove(opts['key'])
- done()
-if name == 's3api delete-bucket':
- if b['objects']:
- err('BucketNotEmpty')
- del buckets[opts['bucket']]
- done()
-users = world['users']
-if name == 'iam create-user':
- if 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')
- 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(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'])
- done()
-if name == 'iam create-access-key':
- key = f'AKIAFAKEDRILL{len(u["keys"]):07d}'
- u['keys'].append(key)
- done(key + '\t' + os.environ['FAKE_SECRET'])
-if name == 'iam list-access-keys':
- out('\t'.join(u['keys']))
-if name == 'iam delete-access-key':
- 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':
- if u['policies'] or u['keys']:
- err('DeleteConflict')
- del users[opts['user-name']]
- done()
-groups = world['log_groups']
-if name == 'logs create-log-group':
- 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')
- 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'])))
-if name == 'logs create-log-stream':
- if opts['log-group-name'] not in groups:
- err('ResourceNotFoundException')
- done()
-if name == 's3 presign':
- out(f'https://{opts["_"][0][5:].split("/")[0]}.s3.eu-west-1.amazonaws.com/drill-object?X-Amz-Algorithm=AWS4-HMAC-SHA256'
- f'&X-Amz-Credential=AKIAFAKEDRILL%2F20261118%2Feu-west-1%2Fs3%2Faws4_request&X-Amz-Signature={os.environ["FAKE_SIGNATURE"]}')
-if name == 'ecr get-authorization-token':
- out(os.environ['FAKE_TOKEN'])
-opened = all(e['policy'] == world['default_policy'] for e in eps.values())
-if name == 'ecs run-task':
- path = opts['overrides'][len('file://'):]
- world['overrides'].append(json.load(open(path)))
- world['task_seq'] += 1
- arn = f'arn:aws:ecs:eu-west-1:123456789012:task/media/{world["task_seq"]:032x}'
- ok = opened and not world.get('b_never_ok')
- world['tasks'][arn] = [f'{e} ok' if ok else f'{e} refused 403' for e in ('s3', 'ecr-api', 'ecr-docker', 'logs')]
- world['phases'].append('open' if opened else 'saved')
- done(arn)
-if name == 'ecs wait':
- if world.get('block_when_open') and opened:
- save()
- lock.close()
- open(world['marker'] + '.tmp', 'w').write(str(os.getpid()))
- os.replace(world['marker'] + '.tmp', world['marker'])
- time.sleep(60)
- sys.exit(0) # its world is stale by now: never written back
- out()
-if name == 'ecs stop-task':
- out('{}')
-if name == 'logs get-log-events':
- task_id = opts['log-stream-name'].rsplit('/', 1)[1]
- for arn, lines in world['tasks'].items():
- if arn.endswith('/' + task_id):
- out('\n'.join(lines))
- err('ResourceNotFoundException')
-err('UnknownOperation', name)
+FOREIGN = '210987654321'
+BUCKET = 'carlos-media-endpoint-drill-bucket'
+tofu() if tool == 'tofu' else aws()
'''
FAKE_CARLOS_MEDIA = r'''
import sys
args = sys.argv[1:]
assert args[:2] == ['drill', 'endpoints-verdict'], args
-def cells(path):
- lines = [l for l in open(path).read().splitlines() if l.strip()]
- return {l.split(' ', 1)[0]: l.split(' ', 1)[1] for l in lines} if len(lines) == 4 else {}
want = {'A': 'refused', 'B': 'ok', 'C': 'refused'}
ok = True
for phase, path in zip('ABC', args[2:]):
- c = cells(path)
+ lines = [l for l in open(path).read().splitlines() if l.strip()]
+ cells = {l.split(' ', 1)[0]: l.split(' ', 1)[1] for l in lines}
for e in ('s3', 'ecr-api', 'ecr-docker', 'logs'):
- if not c.get(e, '').startswith(want[phase]):
+ got = cells.get(e, 'missing')
+ if not got.startswith(want[phase]):
ok = False
- print(f'FAIL {e} phase {phase}')
-print('PASS endpoints' if ok else 'verdict: FAIL')
+ print(f'FAIL {e} phase {phase}: {got}, want {want[phase]}')
+if ok:
+ print('PASS endpoints')
sys.exit(0 if ok else 1)
'''
-# 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']
-
class Drill:
- """One run directory's worth of fakes and the script's outcome."""
+ """A run's fakes, its world and its outcome."""
def __init__(self, test, **world):
self.dir = Path(tempfile.mkdtemp(prefix='media-drill-test-'))
test.addCleanup(shutil.rmtree, self.dir, True)
self.tmp = self.dir / 'tmp'
self.tmp.mkdir()
+ self.bin = self.dir / 'bin'
+ self.bin.mkdir()
+ self.root = self.dir / 'engine-root'
+ self.root.mkdir()
+ (self.root / 'variables.tf').write_text('variable "media_engine_drill" {\n default = null\n}\n')
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, 'user_seq': 0, 'calls': [], 'overrides': [], 'phases': [], 'user_policy_documents': [],
- 'marker': str(self.dir / 'blocked'), 'run_tag': RUN_TAG, 'accounts': {'kass': DEV, 'foreign': FOREIGN},
- }
+ w = {'engine': None, 'engine_history': [], 'fixture': [], 'keys': [], 'calls': [], 'seen': {}, 'fail': {}, 'block': None,
+ 'overrides': [], 'passes': [], 'answers': {}, 'tasks': {}, 'task_seq': 0, 'marker': str(self.dir / 'blocked'),
+ 'accounts': {'kass': DEV, 'foreign': FOREIGN}}
w.update(world)
self.world_path.write_text(json.dumps(w))
- self.aws = self.dir / 'aws'
- self.aws.write_text(f'#!{sys.executable} -I\n' + FAKE_AWS)
- self.aws.chmod(0o755)
- cm = self.dir / 'carlos-media'
- cm.write_text(f'#!{sys.executable} -I\n' + FAKE_CARLOS_MEDIA)
- cm.chmod(0o755)
+ for name in ('aws', 'tofu'):
+ (self.bin / name).write_text(f'#!{sys.executable} -I\n' + FAKE)
+ (self.bin / name).chmod(0o755)
+ cm = os.environ.get('MEDIA_DRILL_CARLOS_MEDIA')
+ if not cm:
+ cm = str(self.dir / 'carlos-media')
+ Path(cm).write_text(f'#!{sys.executable} -I\n' + FAKE_CARLOS_MEDIA)
+ Path(cm).chmod(0o755)
self.env = {
- 'PATH': os.environ.get('PATH', '/usr/bin:/bin'), 'HOME': str(self.dir), 'TMPDIR': str(self.tmp),
- 'AWS': str(self.aws), 'CARLOS_MEDIA': str(cm), 'FAKE_AWS_WORLD': str(self.world_path),
+ 'PATH': f'{self.bin}:{os.environ.get("PATH", "/usr/bin:/bin")}', 'HOME': str(self.dir), 'TMPDIR': str(self.tmp),
+ 'CARLOS_MEDIA': cm, 'FAKE_WORLD': str(self.world_path),
'FAKE_SECRET': SECRET, 'FAKE_TOKEN': TOKEN, 'FAKE_SIGNATURE': SIGNATURE,
'MEDIA_DRILL_INTERVAL': '0', 'MEDIA_DRILL_IAM_WAIT': '0', 'MEDIA_DRILL_LOG_WAIT': '0', 'MEDIA_DRILL_PASSES': '2',
- 'AWS_PROFILE': 'should-not-reach-the-user-calls',
}
def args(self, 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']
+ '--task-definition', TASKDEF, '--repository', REPO, '--bucket', BUCKET, '--subnets', 'subnet-0a,subnet-0b',
+ '--security-group', 'sg-0tasks', '--engine-root', str(self.root)]
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):
+ def restore(self):
rundirs = self.rundirs()
assert len(rundirs) == 1, rundirs
- return self.run('bash', str(SCRIPT), 'cleanup', str(rundirs[0]))
+ return self.run('bash', str(SCRIPT), 'restore', str(rundirs[0]))
def start(self):
- return subprocess.Popen(self.args(), env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ return subprocess.Popen(self.args(), env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ start_new_session=True)
def world(self):
return json.loads(self.world_path.read_text())
- def rundirs(self):
- return sorted(self.tmp.glob('media-endpoint-drill.*'))
-
- def calls(self):
- return [c['call'] for c in self.world()['calls']]
-
def set_world(self, **kv):
w = self.world()
w.update(kv)
self.world_path.write_text(json.dumps(w))
- 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()
+ def rundirs(self):
+ return sorted(self.tmp.glob('media-endpoint-drill.*'))
+
+ def steps(self):
+ return [c['step'] for c in self.world()['calls']]
+
+ def wait_blocked(self, test, p):
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
+ test.assertIsNone(p.poll(), 'the run ended before the step: ' + p.stderr.read() if p.poll() is not None else '')
+ test.assertLess(time.monotonic(), deadline, 'the step was never reached')
+ time.sleep(0.01)
+ return int(marker.read_text())
+
+ def interrupt_at(self, test, step, sig=signal.SIGTERM):
+ self.set_world(block=step)
+ p = self.start()
+ self.wait_blocked(test, p)
+ os.killpg(p.pid, sig)
+ self.stdout, self.stderr = p.communicate(timeout=90)
+ self.code = p.returncode
+ return self
+
+ def kill_at(self, test, step):
+ """SIGKILL at a step: no trap runs."""
+ self.set_world(block=step)
+ p = self.start()
+ pid = self.wait_blocked(test, p)
+ p.kill()
+ os.kill(pid, signal.SIGKILL)
p.communicate(timeout=60)
- marker.unlink()
- self.set_world(block_when_open=False)
+ Path(self.world()['marker']).unlink()
+ return self
class MediaEndpointDrillTest(unittest.TestCase):
- def assert_clean(self, d, kept=False):
+ def assert_restored(self, d):
w = d.world()
- self.assertEqual(w['buckets'], {}, d.stdout + d.stderr)
- self.assertEqual(w['users'], {}, d.stderr)
- self.assertEqual(w['log_groups'], {}, d.stderr)
- self.assertIsNone(w['repo_policy'])
- for k, v in w['endpoints'].items():
- self.assertEqual(v['policy'], original_policy(ENDPOINTS[k][0]), k)
- for rd in d.rundirs():
- self.assertFalse((rd / 'input.json').exists())
- self.assertFalse((rd / 'overrides.json').exists())
- if not kept:
- self.assertEqual(d.rundirs(), [], 'the run directory was kept')
- for o in OBLIGATIONS:
- self.assertIn(f'cleaned {o}\n', d.stdout)
+ self.assertIsNone(w['engine'], d.stdout + d.stderr)
+ self.assertEqual(w['fixture'], [], d.stdout + d.stderr)
+ self.assertEqual(w['keys'], [])
+ self.assertEqual(d.rundirs(), [], 'the run directory was kept')
+ for item in ITEMS:
+ self.assertIn(f'cleaned {item}\n', d.stdout)
self.assertNotIn('NOT CLEANED', d.stdout)
- def assert_no_secret_printed(self, d):
- 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 assert_no_secret(self, text, where=''):
+ for s in SECRETS:
+ self.assertNotIn(s, text, where)
- def test_run_passes_and_cleans(self):
+ def test_run_passes_in_order_and_restores(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)
+ self.assert_restored(d)
+ steps = [s for s in d.steps() if s in ('fixture apply', 'engine apply closed', 'engine apply open', 'engine apply off',
+ 'aws ecs run-task', 'fixture destroy', 'aws iam create-access-key')]
+ self.assertEqual(steps, ['fixture apply', 'aws iam create-access-key', 'engine apply closed', 'aws ecs run-task',
+ 'engine apply open', 'aws ecs run-task', 'engine apply closed', 'aws ecs run-task',
+ 'engine apply off', 'fixture destroy'])
w = d.world()
- self.assertEqual(w['phases'], ['saved', 'open', 'saved'])
+ self.assertEqual(w['passes'], ['closed', 'open', 'closed'])
+ self.assertLess(d.stdout.index('PASS endpoints'), d.stdout.index('cleaned engine-policies'))
for o in w['overrides']:
by = {c['name']: c for c in o['containerOverrides']}
self.assertEqual(by['codec']['command'], ['drill', 'endpoints'])
- env = {e['name']: e['value'] for e in by['codec']['environment']}
- drill = json.loads(env['CARLOS_MEDIA_DRILL'])
+ drill = json.loads({e['name']: e['value'] for e in by['codec']['environment']}['CARLOS_MEDIA_DRILL'])
self.assertEqual(sorted(drill), sorted(['s3_get_url', 'ecr_token', 'ecr_manifest_url', 'region', 'access_key_id',
'secret_access_key', 'log_group', 'log_stream']))
self.assertEqual((drill['secret_access_key'], drill['ecr_token'], drill['region']), (SECRET, TOKEN, REGION))
- self.assertEqual(drill['ecr_manifest_url'],
- 'https://123456789012.dkr.ecr.eu-west-1.amazonaws.com/v2/carlos-media/manifests/sha256:' + 'ab' * 32)
- denv = {e['name'] for e in by['deadline']['environment']}
- self.assertEqual(denv, {'CARLOS_MEDIA_DEADLINE_S', 'CARLOS_MEDIA_GRANT_EXPIRY'})
- doc = json.loads(w['user_policy_documents'][0])
- actions = {json.dumps(s['Action']): s['Resource'] for s in doc['Statement']}
- 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'])
+ self.assertEqual({e['name'] for e in by['deadline']['environment']}, {'CARLOS_MEDIA_DEADLINE_S', 'CARLOS_MEDIA_GRANT_EXPIRY'})
- def test_no_secret_in_any_childs_argv(self):
+ def test_engine_root_contract(self):
+ d = Drill(self).run()
+ self.assertEqual(d.code, 0, d.stderr)
+ w = d.world()
+ user = f'arn:aws:iam::{FOREIGN}:user/{w["user"]}'
+ self.assertEqual(w['engine_history'], [
+ {'endpoints_open': False, 'foreign_principal_arn': user},
+ {'endpoints_open': True, 'foreign_principal_arn': user},
+ {'endpoints_open': False, 'foreign_principal_arn': user},
+ None])
+ for c in w['calls']:
+ if c['tool'] == 'tofu' and c['chdir'] == str(d.root) and c['step'].split()[1] in ('apply', 'plan'):
+ self.assertEqual(sorted(a for a in c['argv'] if a.startswith('-target=')),
+ sorted('-target=module.media_engine.' + t for t in TARGETS), c['step'])
+ self.assertEqual(c['env'].get('AWS_PROFILE'), 'kass')
+ if c['step'].endswith(' apply') or ' apply ' in c['step']:
+ self.assertIn('-auto-approve', c['argv'])
+ self.assertIn('-input=false', c['argv'])
+
+ def test_verdict_needs_all_three_phases(self):
+ for name, answers, passes, cell in (
+ ('A not refused', {'closed': True}, ['closed'], 'phase A'),
+ ('B never ok', {'open': False}, ['closed', 'open', 'open', 'closed'], 'phase B: refused 403, want ok'),
+ ):
+ with self.subTest(name):
+ d = Drill(self, answers=answers).run()
+ self.assertEqual(d.code, 1, d.stdout + d.stderr)
+ self.assertIn('FAIL s3 ' + cell, d.stdout)
+ self.assertEqual(d.world()['passes'], passes)
+ self.assert_restored(d)
+ # C still open: the second closed apply took no effect at the endpoints.
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
+ real = (d.bin / 'aws').read_text().replace("ok = w['answers'].get(state, state == 'open')",
+ "ok = state == 'open' or len(w['passes']) >= 3")
+ (d.bin / 'aws').write_text(real)
+ d.run()
+ self.assertEqual(d.code, 1, d.stdout + d.stderr)
+ self.assertIn('FAIL s3 phase C: ok, want refused', d.stdout)
+ self.assert_restored(d)
+
+ def test_phase_a_not_refused_never_opens_the_endpoints(self):
+ d = Drill(self, answers={'closed': True}).run()
+ self.assertNotIn('engine apply open', d.steps())
+
+ def test_interrupt_at_each_step_restores(self):
+ for step in ('fixture apply', 'aws iam create-access-key', 'aws ecr get-authorization-token', 'engine apply closed',
+ 'aws ecs wait', 'engine apply open', 'aws ecs wait#2', 'engine apply closed#2', 'aws ecs wait#3'):
+ with self.subTest(step=step):
+ d = Drill(self).interrupt_at(self, step)
+ self.assertEqual(d.code, 143, d.stdout + d.stderr)
+ self.assert_restored(d)
+ self.assertEqual(d.world()['engine_history'][-1], None)
+
+ def test_each_signal_restores(self):
+ for sig, code in ((signal.SIGINT, 130), (signal.SIGHUP, 129), (signal.SIGTERM, 143)):
+ with self.subTest(sig=sig):
+ d = Drill(self).interrupt_at(self, 'engine apply open', sig)
+ self.assertEqual(d.code, code, d.stdout + d.stderr)
+ self.assert_restored(d)
+
+ def test_signal_to_the_script_alone_stops_tofu_before_restoring(self):
+ d = Drill(self)
+ d.set_world(block='engine apply open')
+ p = d.start()
+ d.wait_blocked(self, p)
+ start = time.monotonic()
+ p.send_signal(signal.SIGTERM) # the script only: the running tofu must be stopped by the script
+ d.stdout, d.stderr = p.communicate(timeout=90)
+ d.code = p.returncode
+ self.assertLess(time.monotonic() - start, 30, 'the restore waited out the running tofu')
+ self.assertEqual(d.code, 143, d.stdout + d.stderr)
+ self.assert_restored(d)
+
+ def test_failed_step_restores(self):
+ for step, times in (('fixture init', 1), ('fixture apply', 1), ('aws iam create-access-key', 6), ('engine apply closed', 1),
+ ('engine apply open', 1), ('engine apply closed#2', 1)):
+ with self.subTest(step=step):
+ d = Drill(self, fail={step: times}).run()
+ self.assertNotEqual(d.code, 0, d.stdout)
+ self.assert_restored(d)
+
+ def test_failed_restore_reports_and_rerun_converges(self):
+ for step, item in (('engine apply off', 'engine-policies'), ('engine init#2', 'engine-policies'),
+ ('fixture destroy', 'fixture'), ('fixture init#2', 'fixture')):
+ with self.subTest(step=step):
+ d = Drill(self, fail={step: -1}).run()
+ self.assertEqual(d.code, 3, d.stdout + d.stderr)
+ self.assertIn(f'NOT CLEANED {item}\n', d.stdout)
+ for other in set(ITEMS) - {item}:
+ self.assertIn(f'cleaned {other}\n', d.stdout)
+ self.assertEqual(len(d.rundirs()), 1)
+ self.assertFalse((d.rundirs()[0] / 'input.json').exists())
+ # Still failing: the same answer, and nothing gets worse.
+ if step in ('engine apply off', 'fixture destroy'):
+ d.restore()
+ self.assertEqual(d.code, 3)
+ self.assertIn(f'NOT CLEANED {item}\n', d.stdout)
+ d.set_world(fail={})
+ d.restore()
+ self.assertEqual(d.code, 0, d.stdout + d.stderr)
+ self.assert_restored(d)
+
+ def test_clean_is_what_tofu_reports(self):
+ d = Drill(self, pending_plan=False)
+ (d.bin / 'tofu').write_text((d.bin / 'tofu').read_text().replace(
+ "pending = w.get('pending_plan', False) or w['engine'] != drill",
+ "pending = len([c for c in w['calls'] if c['step'] == 'engine plan']) > 1"))
d.run()
+ self.assertEqual(d.code, 3, d.stdout + d.stderr)
+ self.assertIn('NOT CLEANED engine-policies\n', d.stdout)
+ d = Drill(self, destroy_lies=True).run()
+ self.assertEqual(d.code, 3, d.stdout + d.stderr)
+ self.assertIn('NOT CLEANED fixture\n', d.stdout)
+
+ def test_restore_after_sigkill_and_repeated(self):
+ d = Drill(self).kill_at(self, 'engine apply open')
+ w = d.world()
+ self.assertTrue(w['fixture'])
+ self.assertEqual(len(d.rundirs()), 1)
+ d.set_world(fail={'fixture destroy': 1})
+ d.restore()
+ self.assertEqual(d.code, 3, d.stdout + d.stderr)
+ self.assertIn('cleaned engine-policies\n', d.stdout)
+ d.restore()
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":[]}')
+ self.assert_restored(d)
+
+ def test_damaged_conf_changes_nothing(self):
+ for text in ('', 'profile=kass\n', 'profile=kass\nengine_root=relative/path\n', 'profile=$(id)\nengine_root=/x\n', 'other=1\n'):
+ with self.subTest(text=text):
+ d = Drill(self).kill_at(self, 'engine apply open')
+ (d.rundirs()[0] / 'drill.conf').write_text(text)
+ n = len(d.world()['calls'])
+ d.restore()
+ self.assertEqual(d.code, 3)
+ self.assertIn('NOT CLEANED engine-policies\nNOT CLEANED fixture\n', d.stdout)
+ self.assertEqual(len(d.world()['calls']), n)
+
+ def test_preflight_changes_nothing(self):
+ for name, setup, why in (
+ ('same account', {'accounts': {'kass': DEV, 'foreign': DEV}}, 'the foreign profile is the dev account'),
+ ('wrong dev account', {'accounts': {'kass': FOREIGN, 'foreign': '333333333333'}}, "the dev profile is not the cluster's account"),
+ ('pending changes', {'pending_plan': True}, 'changes pending'),
+ ):
+ with self.subTest(name):
+ d = Drill(self, **setup).run()
+ self.assertEqual(d.code, 1, d.stdout + d.stderr)
+ self.assertIn(why, d.stderr)
+ for s in d.steps():
+ self.assertFalse(' apply' in s or 'destroy' in s or 'create-access-key' in s, s)
+ self.assertEqual(d.rundirs(), [])
+ d = Drill(self)
+ (d.root / 'variables.tf').write_text('# no drill variable here\n')
+ d.run()
+ self.assertEqual(d.code, 1)
+ self.assertIn('declares no media_engine_drill variable', d.stderr)
+ self.assertFalse([s for s in d.steps() if ' apply' in s])
def test_refuses_xtrace(self):
for how, run in (
@@ -532,240 +541,97 @@ class MediaEndpointDrillTest(unittest.TestCase):
):
with self.subTest(how=how):
d = run(Drill(self))
- self.assertEqual(d.code, 2, d.stderr[-500:])
+ self.assertEqual(d.code, 2, d.stderr[-400:])
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(), [])
+ self.assertEqual(d.steps(), [])
+ self.assert_no_secret(d.stderr)
- 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.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)
+ def test_no_secret_reaches_argv_tofu_or_output(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:
+ (wrap / tool).write_text(f'#!/bin/sh\nprintf "%s\\037" "$0" "$@" >>"{log}"\nprintf "\\n" >>"{log}"\nexec "{real}" "$@"\n')
+ (wrap / tool).chmod(0o755)
+ d.env['PATH'] = f'{wrap}:{d.env["PATH"]}'
+ # A failed restore keeps the run directory, so its files can be read.
+ d.set_world(fail={'fixture destroy': -1})
+ d.run()
+ self.assertEqual(d.code, 3, d.stdout + d.stderr)
+ argv = log.read_text()
+ for tool in ('mktemp', 'cp', 'od'):
+ self.assertIn(f'/{tool}\x1f', argv, f'{tool} was not seen: the wrapper did not run')
+ self.assert_no_secret(argv, 'a child argv')
+ self.assert_no_secret(d.stdout + d.stderr, 'the output')
+ self.assertNotIn('X-Amz', d.stdout + d.stderr)
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)
- self.assertIn('FAIL s3 phase B', d.stdout)
- self.assert_clean(d)
- self.assertEqual(d.world()['phases'], ['saved', 'open', 'open', 'saved'])
-
- def test_phase_a_open_never_opens_the_endpoints(self):
- policies = {k: {'label': v[0], 'service': v[1], 'policy': DEFAULT_POLICY} for k, v in ENDPOINTS.items()}
- d = Drill(self, endpoints=policies).run()
- self.assertNotEqual(d.code, 0)
- self.assertNotIn('ec2 modify-vpc-endpoint', d.calls())
- self.assertEqual(d.world()['phases'], ['open'])
-
- def test_cleanup_on_sigterm_mid_phase_b(self):
- d = Drill(self, block_when_open=True)
- p = d.start()
- marker = Path(d.world()['marker'])
- deadline = time.monotonic() + 60
- while not marker.exists():
- self.assertIsNone(p.poll(), 'the run ended before phase B')
- self.assertLess(time.monotonic(), deadline)
- time.sleep(0.05)
- self.assertTrue(all(e['policy'] == DEFAULT_POLICY for e in d.world()['endpoints'].values()))
- p.send_signal(signal.SIGTERM)
- d.stdout, d.stderr = p.communicate(timeout=60)
- d.code = p.returncode
- self.assertEqual(d.code, 143, d.stderr)
- self.assert_clean(d)
- self.assertIn('ecs stop-task', d.calls())
-
- def test_cleanup_reports_what_it_could_not_clean(self):
- d = Drill(self, refuse=['iam delete-user']).run()
- self.assertNotEqual(d.code, 0)
- self.assertIn('NOT CLEANED foreign-user\n', d.stdout)
- for o in OBLIGATIONS:
- if o != 'foreign-user':
- self.assertIn(f'cleaned {o}\n', d.stdout)
- rundirs = d.rundirs()
- self.assertEqual(len(rundirs), 1)
- state = (rundirs[0] / 'state').read_text()
- self.assertIn('\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, 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)
- d.kill_in_phase_b(self)
+ for c in w['calls']:
+ self.assert_no_secret(' '.join(c['argv']), c['step'])
+ if c['tool'] == 'tofu':
+ env = {k: v for k, v in c['env'].items() if not k.startswith('FAKE_')} # the fakes' own inputs
+ self.assert_no_secret(json.dumps(env), c['step'] + ' environment')
+ self.assert_no_secret(c['var_file'] + c['tfvars'], c['step'] + ' variables')
+ self.assertFalse([k for k in c['env'] if k.startswith('TF_VAR_') or k.startswith('AWS_ACCESS') or k.startswith('AWS_SECRET')])
+ if c['step'] in ('aws s3 presign', 'aws ecr get-authorization-token', 'aws logs create-log-stream'):
+ self.assertTrue(c['env_key'])
+ self.assertIsNone(c['profile'])
+ rundir = d.rundirs()[0]
+ for path in rundir.rglob('*'):
+ if path.is_file():
+ self.assert_no_secret(path.read_text(errors='replace'), str(path))
+
+ def test_state_is_private(self):
+ d = Drill(self).run()
+ self.assertEqual(d.code, 0, d.stderr)
w = d.world()
- self.assertEqual(len(w['buckets']), 1)
- self.assertTrue(all(e['policy'] == DEFAULT_POLICY for e in w['endpoints'].values()))
- 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):
- 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: 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)
- self.assertEqual(d.rundirs(), [])
+ self.assertEqual((w['state_mode'], w['dir_mode']), (0o600, 0o700))
+
+ def test_fixture_holds_no_secret_and_owns_its_resources(self):
+ tf = (FIXTURE / 'main.tf').read_text()
+ self.assertNotIn('aws_iam_access_key', tf)
+ for resource in ('aws_iam_user', 'aws_iam_user_policy', 'aws_cloudwatch_log_group', 'aws_s3_bucket', 'aws_s3_object', 'aws_s3_bucket_policy'):
+ self.assertIn(f'resource "{resource}" "drill"', tf)
+ self.assertEqual(tf.count('force_destroy = true'), 2, 'the user and the bucket')
+ for alias in ('dev', 'foreign'):
+ self.assertIn(f'alias = "{alias}"', tf)
+ for forbidden in ('aws_vpc_endpoint', 'aws_ecr_repository_policy'):
+ self.assertNotIn(forbidden, tf, 'the engine root owns these')
+ self.assertEqual(stat.S_IMODE(SCRIPT.stat().st_mode) & 0o100, 0o100)
+
+ def test_fixture_validates(self):
+ tofu = shutil.which('tofu')
+ if tofu is None:
+ self.skipTest('tofu is not installed: the fixture root was not validated')
+ with tempfile.TemporaryDirectory(prefix='media-drill-validate-') as tmp:
+ for f in FIXTURE.glob('*.tf'):
+ shutil.copy(f, tmp)
+ env = {k: v for k, v in os.environ.items() if not k.startswith('AWS_')}
+ env.update({'TF_DATA_DIR': tmp + '/.data', 'AWS_CONFIG_FILE': '/dev/null', 'AWS_SHARED_CREDENTIALS_FILE': '/dev/null'})
+ init = subprocess.run([tofu, '-chdir=' + tmp, 'init', '-backend=false', '-input=false', '-no-color'],
+ env=env, capture_output=True, text=True, timeout=300)
+ if init.returncode != 0:
+ self.skipTest('tofu init could not fetch the provider here: the fixture root was not validated')
+ v = subprocess.run([tofu, '-chdir=' + tmp, 'validate', '-no-color'], env=env, capture_output=True, text=True, timeout=300)
+ if 'failed to instantiate provider' in v.stdout + v.stderr:
+ self.skipTest('the provider cannot start here (a sandbox): the fixture root was not validated')
+ self.assertEqual(v.returncode, 0, v.stdout + v.stderr)
def test_usage(self):
d = Drill(self).run('bash', str(SCRIPT), 'run', '--profile', 'kass')
self.assertEqual(d.code, 2)
- self.assertEqual(d.rundirs(), [])
- d.run('bash', str(SCRIPT), 'cleanup', str(d.tmp / 'absent'))
+ d.run('bash', str(SCRIPT), 'restore', str(d.tmp / 'absent'))
self.assertEqual(d.code, 2)
empty = d.tmp / 'not-a-run'
empty.mkdir()
+ d.run('bash', str(SCRIPT), 'restore', str(empty))
+ self.assertEqual(d.code, 2)
+ self.assertTrue(empty.exists(), 'restore removed a directory that is no run')
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(), [])
+ self.assertEqual(d.steps(), [])
if __name__ == '__main__':