carlos / platform Public

media: drill restore refuses orphans and a live normal input

Plan 3 Task 7 fix round 3 (Astra round 3).

A fixture whose first apply began and never exited 0 may hold a
resource tofu did not save: restore destroys what the state knows,
prints the names to look for, and stays NOT CLEANED.

Preflight and restore now read the engine root's normal drill input
with no override file (TF_VAR_media_engine_drill unset, tofu console
answering true to the null check) and plan without one, so a root
whose own tfvars set the drill cannot pass and reopen later.

run and restore share one validator for each recorded value, so a
profile restore could not read is refused before anything is made.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1f41eabe1cc2a8a8e5f00b2cf5ecd2898caef0a2 parent 00e4300
4 files changed, +190 −36
  • docs/superpowers/notes/media-conversion-copy-deck.md +2 −2
  • docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md +2 −2
  • scripts/media-endpoint-drill.sh +82 −25
  • scripts/media_endpoint_drill_test.py +104 −7

CI passed — run details

diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 52dbc5199..feb4987e4 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -627,5 +627,5 @@ or an output's name: never a credential, a URL or a header. `%s` and
| `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 |
+| `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.`; `media-endpoint-drill: the engine root's normal media_engine_drill input is not null: its next ordinary apply would reopen the drill`; `media-endpoint-drill: the fixture's first apply did not finish, so a resource may exist that tofu never saved.`; `media-endpoint-drill: look for the user carlos-media-drill-%s and the log group carlos-media-endpoint-drill-%s in the foreign account, and the bucket %s in dev`; `media-endpoint-drill: delete what you find, then remove %s` (pending Luna pass; plan 3 Task 7 fixes 2 and 3). 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`; `TF_VAR_media_engine_drill is set; unset it first`; `the engine root's normal media_engine_drill input is not null; set it back first`; `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-3-engine.md b/docs/superpowers/plans/2026-11-16-media-conversion-plan-3-engine.md
index d32ae4085..7e83c8694 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
@@ -167,8 +167,8 @@ Depends on plan 1 Task 3 Step 4: the muxer rules and the parser's accepted box s
- **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.
- **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.
+- **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`; `--profile` and `--foreign-profile` are names `restore` can read back (one validator for both paths: letters, digits, `.`, `_` and `-`); the engine root declares `media_engine_drill`; its normal input, with no override file, is null (`TF_VAR_media_engine_drill` is unset, and `tofu console` answers `true` to `var.media_engine_drill == null`), because otherwise its next ordinary apply would reopen the drill; and a normal `tofu plan -detailed-exitcode`, with no override file, shows nothing pending on the five policy resources. 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 requires the root's normal input to be null (as in the preflight) and a normal `tofu plan -detailed-exitcode`, with no override file, to have nothing left; and destroys the fixture, whichever way the engine went, then asks `tofu state list` whether anything is left. A fixture whose first apply began and has no marker of exiting 0 may hold a resource tofu never saved: the restore still destroys what the state knows, prints the names to look for (the run-unique user and log group, and the bucket), and reports `NOT CLEANED fixture` however often it is repeated; the operator checks by hand and removes the run directory. 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 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).
diff --git a/scripts/media-endpoint-drill.sh b/scripts/media-endpoint-drill.sh
index 3b79d48f3..614d334fa 100755
--- a/scripts/media-endpoint-drill.sh
+++ b/scripts/media-endpoint-drill.sh
@@ -41,6 +41,14 @@
# answers; any NOT CLEANED makes the exit non-zero and keeps the run
# directory.
#
+# Two things tofu cannot answer from a forced value are checked apart. The
+# engine root's normal input (its tfvars and TF_VAR_media_engine_drill, with
+# no override) must be null before the run and after the restore, or its
+# next ordinary apply would reopen the drill. And a fixture whose first apply
+# began but never exited 0 may have made a resource tofu did not save: the
+# restore destroys what the state knows, names what to look for, and stays
+# NOT CLEANED, because tofu cannot say that nothing was left.
+#
# Secrets (the user's key, the registry token, the presigned URL) never
# 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
@@ -159,6 +167,12 @@ pause() {
bg_pid=""
}
+# The one definition of each value run accepts and restore reads back.
+valid_profile() { [[ "$1" =~ ^[A-Za-z0-9._-]+$ ]]; }
+valid_engine_root() { [[ "$1" =~ ^/[A-Za-z0-9._/+-]+$ ]]; }
+valid_run_id() { [[ "$1" =~ ^[0-9a-f]{16}$ ]]; }
+valid_bucket() { [[ "$1" =~ ^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$ ]]; }
+
# safe is true when $1 can go inside a JSON string as it is: no quote,
# no backslash, no control character.
safe() { [[ -n "$1" && "$1" != *[\"\\]* && "$1" != *[[:cntrl:]]* ]]; }
@@ -173,19 +187,40 @@ report_line() {
return 1
}
-# restore_engine applies the engine root with the drill off, and asks tofu
-# whether anything is left to change.
+# normal_input_is_off is true when the engine root's normal drill input,
+# with no override file, is null: nothing in its tfvars and no
+# TF_VAR_media_engine_drill. Its next ordinary apply then keeps the drill off.
+normal_input_is_off() {
+ [ -z "${TF_VAR_media_engine_drill+set}" ] || return 1
+ local answer
+ answer="$(printf 'var.media_engine_drill == null\n' |
+ AWS_PROFILE="$profile" "$TOFU" "-chdir=$engine_root" console -input=false 2>>"$rundir/tofu.log")" || return 1
+ [ "$answer" = true ]
+}
+
+# normal_plan_is_clean is true when an ordinary plan of the five policy
+# resources, with no override file, has nothing to change.
+normal_plan_is_clean() {
+ engine_tf plan -input=false -detailed-exitcode "${engine_targets[@]}"
+}
+
+# restore_engine applies the engine root with the drill off, then asks tofu
+# what the root's normal input is and whether a normal plan has anything
+# 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[@]}"
+ if ! normal_input_is_off; then
+ say "the engine root's normal media_engine_drill input is not null: its next ordinary apply would reopen the drill"
+ return 1
+ fi
+ normal_plan_is_clean
}
-# 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
+# destroy_fixture destroys the fixture and asks tofu whether its state
+# still holds anything.
+destroy_fixture() {
fixture_tf init -input=false || return 1
fixture_tf destroy -input=false -auto-approve || return 1
local left
@@ -193,6 +228,23 @@ restore_fixture() {
[ -z "$left" ]
}
+# restore_fixture destroys what the state knows. A run that never began
+# the first apply has nothing else. One that began it and has no record of
+# it exiting 0 may have made a resource tofu never saved, so it cannot be
+# called clean: the operator is told what to look for.
+restore_fixture() {
+ [ -f "$rundir/fixture/terraform.tfvars.json" ] || return 0
+ local rc=0
+ destroy_fixture || rc=1
+ if [ -e "$rundir/fixture-apply.started" ] && [ ! -e "$rundir/fixture-apply.finished" ]; then
+ say "the fixture's first apply did not finish, so a resource may exist that tofu never saved."
+ say "look for the user carlos-media-drill-$run_id and the log group carlos-media-endpoint-drill-$run_id in the foreign account, and the bucket $bucket in dev"
+ say "delete what you find, then remove $rundir"
+ return 1
+ fi
+ return "$rc"
+}
+
# 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
@@ -240,26 +292,28 @@ finish() {
exit "$status"
}
-# write_conf records the two values restore needs and reads them back.
+# write_conf records the 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"
+ local want="profile=$profile"$'\n'"engine_root=$engine_root"$'\n'"run_id=$run_id"$'\n'"bucket=$bucket"
printf '%s\n' "$want" >"$rundir/drill.conf" || return 1
[ "$(<"$rundir/drill.conf")" = "$want" ]
}
-# read_conf reads drill.conf strictly: both values there, each of its shape.
+# read_conf reads drill.conf strictly: every value there, each of its shape.
read_conf() {
local key value
- profile="" engine_root=""
+ profile="" engine_root="" run_id="" bucket=""
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" ;;
+ profile) valid_profile "$value" || return 1; profile="$value" ;;
+ engine_root) valid_engine_root "$value" || return 1; engine_root="$value" ;;
+ run_id) valid_run_id "$value" || return 1; run_id="$value" ;;
+ bucket) valid_bucket "$value" || return 1; bucket="$value" ;;
*) return 1 ;;
esac
done <"$rundir/drill.conf"
- [ -n "$profile" ] && [ -n "$engine_root" ]
+ [ -n "$profile" ] && [ -n "$engine_root" ] && [ -n "$run_id" ] && [ -n "$bucket" ]
}
# all_lines is true when file $1 holds exactly one line per endpoint,
@@ -333,14 +387,15 @@ read_task_definition() {
die "the codec container has no awslogs group and prefix"
}
-# 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 refuses a root without the drill's variable, one whose
+# normal input is not null (its next ordinary apply would reopen the drill),
+# 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"
+ [ -z "${TF_VAR_media_engine_drill+set}" ] || die "TF_VAR_media_engine_drill is set; unset it first"
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"
+ normal_input_is_off || die "the engine root's normal media_engine_drill input is not null; set it back first"
+ normal_plan_is_clean || die "the engine root's policies have changes pending; apply or revert them first"
}
# prepare_fixture copies the fixture into the run directory and writes
@@ -353,11 +408,14 @@ prepare_fixture() {
"arn:aws:ecr:$region:$dev_account:repository/$repository" >"$rundir/fixture/terraform.tfvars.json" || die "the fixture's variables cannot be written"
}
-# apply_fixture applies the fixture and checks the user it made.
+# apply_fixture applies the fixture and checks the user it made. The two
+# markers tell restore whether the first apply began and whether it exited 0.
apply_fixture() {
say "applying the fixture"
fixture_tf init -input=false || die "the fixture does not initialise"
+ : >"$rundir/fixture-apply.started" || die "the run directory cannot be written"
fixture_tf apply -input=false -auto-approve || die "the fixture was not applied"
+ : >"$rundir/fixture-apply.finished" || die "the run directory cannot be written"
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"
}
@@ -444,13 +502,12 @@ main_run() {
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; }
- done
+ valid_profile "$profile_" && valid_profile "$foreign_" && valid_bucket "$bucket_" || { echo "$usage" >&2; exit 2; }
+ [[ "$repo_" =~ ^[A-Za-z0-9._/-]+$ ]] || { echo "$usage" >&2; exit 2; }
[[ "$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"
+ valid_engine_root "$engine_root" || 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]}"
@@ -469,7 +526,7 @@ main_run() {
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"
+ valid_run_id "$run_id" || die "no run id"
user="carlos-media-drill-$run_id"
log_group="carlos-media-endpoint-drill-$run_id"
diff --git a/scripts/media_endpoint_drill_test.py b/scripts/media_endpoint_drill_test.py
index e84a1b193..e3f35e5d4 100644
--- a/scripts/media_endpoint_drill_test.py
+++ b/scripts/media_endpoint_drill_test.py
@@ -126,6 +126,8 @@ def tofu():
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'
+ if sub == 'console':
+ sys.stdin.read()
tfvars = ''
if kind == 'fixture' and os.path.exists(chdir + '/terraform.tfvars.json'):
with open(chdir + '/terraform.tfvars.json') as f:
@@ -141,7 +143,8 @@ def tofu():
w['engine'] = drill
w['engine_history'].append(drill)
if kind == 'engine' and sub == 'plan':
- pending = w.get('pending_plan', False) or w['engine'] != drill
+ wanted = w['normal_drill'] if drill == 'absent' else drill
+ pending = w.get('pending_plan', False) or w['engine'] != wanted
plan_exit = 2 if pending else 0
if kind == 'fixture' and sub == 'apply':
v = json.loads(tfvars)
@@ -155,9 +158,13 @@ def tofu():
if kind == 'fixture' and sub == 'destroy' and not w.get('destroy_lies'):
w['fixture'] = []
w['keys'] = []
- listing, user = list(w['fixture']), w.get('user')
+ listing, user, normal = list(w['fixture']), w.get('user'), w['normal_drill']
if interrupted:
sys.exit(1)
+ if sub == 'console':
+ # As real tofu: the environment's value wins, and "null" parses as null.
+ from_env = os.environ.get('TF_VAR_media_engine_drill')
+ print('true' if (from_env == 'null' if from_env is not None else normal is None) else 'false')
if sub == 'plan':
sys.exit(plan_exit)
if sub == 'state':
@@ -256,7 +263,7 @@ class Drill:
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 = {'engine': None, 'engine_history': [], 'fixture': [], 'keys': [], 'calls': [], 'seen': {}, 'fail': {}, 'block': None,
+ w = {'engine': None, 'normal_drill': 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)
@@ -420,7 +427,7 @@ class MediaEndpointDrillTest(unittest.TestCase):
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',
+ for step in ('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)
@@ -449,7 +456,7 @@ class MediaEndpointDrillTest(unittest.TestCase):
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),
+ for step, times in (('fixture init', 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()
@@ -479,8 +486,9 @@ class MediaEndpointDrillTest(unittest.TestCase):
def test_clean_is_what_tofu_reports(self):
d = Drill(self, pending_plan=False)
+ self.assertIn("w['engine'] != wanted", (d.bin / 'tofu').read_text())
(d.bin / 'tofu').write_text((d.bin / 'tofu').read_text().replace(
- "pending = w.get('pending_plan', False) or w['engine'] != drill",
+ "pending = w.get('pending_plan', False) or w['engine'] != wanted",
"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)
@@ -489,6 +497,36 @@ class MediaEndpointDrillTest(unittest.TestCase):
self.assertEqual(d.code, 3, d.stdout + d.stderr)
self.assertIn('NOT CLEANED fixture\n', d.stdout)
+ def assert_orphan_reported(self, d, code=3):
+ self.assertEqual(d.code, code, d.stdout + d.stderr)
+ self.assertIn('NOT CLEANED fixture\n', d.stdout)
+ self.assertNotIn('cleaned fixture\n', d.stdout.replace('NOT CLEANED', ''))
+ self.assertEqual(len(d.rundirs()), 1, 'the run directory must be kept')
+ run_id = (d.rundirs()[0] / 'drill.conf').read_text().split('run_id=')[1].split('\n')[0]
+ for name in (f'carlos-media-drill-{run_id}', f'carlos-media-endpoint-drill-{run_id}', BUCKET):
+ self.assertIn(name, d.stderr)
+
+ def test_resource_missing_from_state_is_never_called_clean(self):
+ # SIGKILL during the first apply: a user exists that tofu never saved.
+ d = Drill(self).kill_at(self, 'fixture apply')
+ d.set_world(orphans=['aws_iam_user.drill'])
+ self.assertEqual(d.world()['fixture'], [], 'the state must know nothing')
+ d.restore()
+ self.assert_orphan_reported(d)
+ self.assertIn('fixture destroy', d.steps(), 'what the state knows is still destroyed')
+ self.assertIn('cleaned engine-policies\n', d.stdout)
+ # Repeating it cannot turn the doubt into a clean answer.
+ d.restore()
+ self.assert_orphan_reported(d)
+ self.assertEqual(d.world()['orphans'], ['aws_iam_user.drill'])
+
+ def test_first_apply_that_did_not_exit_0_is_not_clean(self):
+ d = Drill(self, fail={'fixture apply': 1}).run()
+ self.assert_orphan_reported(d, 1)
+ d = Drill(self).interrupt_at(self, 'fixture apply')
+ self.assert_orphan_reported(d, 143)
+ self.assertEqual(d.world()['fixture'], [], 'what the state knows is destroyed')
+
def test_restore_after_sigkill_and_repeated(self):
d = Drill(self).kill_at(self, 'engine apply open')
w = d.world()
@@ -503,7 +541,9 @@ class MediaEndpointDrillTest(unittest.TestCase):
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'):
+ good = f'engine_root=/x\nrun_id={"a" * 16}\nbucket={BUCKET}\n'
+ for text in ('', 'profile=kass\n', 'profile=kass\nengine_root=relative/path\n', 'profile=$(id)\n' + good, 'profile=team/dev\n' + good,
+ 'other=1\n', 'profile=kass\nengine_root=/x\n', 'profile=kass\n' + good.replace('a' * 16, 'zz')):
with self.subTest(text=text):
d = Drill(self).kill_at(self, 'engine apply open')
(d.rundirs()[0] / 'drill.conf').write_text(text)
@@ -533,6 +573,63 @@ class MediaEndpointDrillTest(unittest.TestCase):
self.assertIn('declares no media_engine_drill variable', d.stderr)
self.assertFalse([s for s in d.steps() if ' apply' in s])
+ def test_normal_input_must_be_off_before_the_run(self):
+ closed = {'endpoints_open': False, 'foreign_principal_arn': f'arn:aws:iam::{FOREIGN}:user/carlos-media-drill-{"a" * 16}'}
+ # The policies are closed and the root's own tfvars say closed: a plan
+ # of the root's normal input has nothing to change.
+ d = Drill(self, engine=closed, normal_drill=closed).run()
+ self.assertEqual(d.code, 1, d.stdout + d.stderr)
+ self.assertIn("normal media_engine_drill input is not null", d.stderr)
+ self.assertFalse([s for s in d.steps() if ' apply' in s or 'destroy' in s])
+ self.assertEqual(d.rundirs(), [])
+ d = Drill(self).run(env={'TF_VAR_media_engine_drill': 'null'})
+ self.assertEqual(d.code, 1, d.stdout + d.stderr)
+ self.assertIn('TF_VAR_media_engine_drill is set', d.stderr)
+ self.assertFalse([s for s in d.steps() if ' apply' in s or 'destroy' in s])
+
+ def test_normal_input_must_be_off_after_the_restore(self):
+ closed = {'endpoints_open': False, 'foreign_principal_arn': f'arn:aws:iam::{FOREIGN}:user/carlos-media-drill-{"a" * 16}'}
+ d = Drill(self).kill_at(self, 'engine apply open')
+ d.set_world(normal_drill=closed) # someone set it in the root's tfvars meanwhile
+ d.restore()
+ self.assertEqual(d.code, 3, d.stdout + d.stderr)
+ self.assertIn('NOT CLEANED engine-policies\n', d.stdout)
+ self.assertIn('its next ordinary apply would reopen the drill', d.stderr)
+ self.assertIsNone(d.world()['engine'], 'the override still closes it for now')
+ self.assertIn('cleaned fixture\n', d.stdout)
+ self.assertEqual(len(d.rundirs()), 1)
+ # The same from the environment of the shell that restores.
+ d.set_world(normal_drill=None)
+ d.run('bash', str(SCRIPT), 'restore', str(d.rundirs()[0]), env={'TF_VAR_media_engine_drill': 'null'})
+ self.assertEqual(d.code, 3, d.stdout + d.stderr)
+ self.assertIn('NOT CLEANED engine-policies\n', d.stdout)
+ # Set back, the restore converges.
+ d.restore()
+ self.assertEqual(d.code, 0, d.stdout + d.stderr)
+ self.assert_restored(d)
+
+ def test_normal_plan_is_asked_without_the_override(self):
+ d = Drill(self).run()
+ self.assertEqual(d.code, 0, d.stdout + d.stderr)
+ calls = d.world()['calls']
+ plans = [c for c in calls if c['step'] == 'engine plan']
+ self.assertEqual(len(plans), 2, 'before the run and after the restore')
+ for c in plans:
+ self.assertEqual([a for a in c['argv'] if a.startswith('-var-file')], [])
+ self.assertEqual(sum(c['step'] == 'engine console' for c in calls), 2)
+
+ def test_profile_restore_cannot_read_is_refused_first(self):
+ for flag in ('--profile', '--foreign-profile'):
+ with self.subTest(flag=flag):
+ d = Drill(self)
+ args = d.args()
+ args[args.index(flag) + 1] = 'team/dev'
+ d.run(*args)
+ self.assertEqual(d.code, 2, d.stdout + d.stderr)
+ self.assertIn('usage:', d.stderr)
+ self.assertEqual(d.steps(), [])
+ self.assertEqual(d.rundirs(), [])
+
def test_refuses_xtrace(self):
for how, run in (
('bash -x', lambda d: d.run(*d.args(('bash', '-x')))),