oficina / equipo Public

hostedops: Task 33 review 1, Astra F1 to F18

Fix round 1 of the run kit (t33-r1.md, rulings in task-33-fix1.md), red
first: a wait-human watchdog unit and unit wait both run safe-stop; safe
stop under its own bounded context, sparing its own unit; creation
identity on every intent and paginated identity lookups; verify-gone
refuses what it cannot read unless a declared parent covers it; fence by
identity, host stop despite a failed attach, fence again after
reconcile; the first guard's caller bound for the run; trust policies
evaluated; connector identity before create; services_route_table_id
exported; the AMI from the release (HostAMI) and litestream-install;
--cert-key-id required; ledger resolution apart from dedup; launch
intents bound to their image; unresolved hosts stop admission; import
block adoption; S.1 unresolved without notes; GetObject's deadline held
through the read; decoded trail records; usage errors, vms scan --max,
unit probe, and SDK request-shape tests. The account plan (rev 4.1) and
Task 34's text follow. Mutations R1 to R36 are in the progress file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev bd37c0bbedc81eb4c29deaea3c859552d1c5a02a parent 9b28fef
35 files changed, +2,521 −236
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md +32 −11
  • docs/superpowers/plans/2026-11-30-hosted-runners-slice-2.md +1 −1
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +93 −0
  • go.mod +2 −1
  • go.sum +4 −2
  • infra/hosted/envs/dev/network/main.tf +4 −0
  • infra/hosted/envs/prod/network/main.tf +4 −0
  • infra/hosted/release-pins.json +3 −0
  • internal/hostedops/assert.go +31 −1
  • internal/hostedops/buckets.go +11 −12
  • internal/hostedops/cloud.go +4 −0
  • internal/hostedops/connector.go +20 −18
  • internal/hostedops/controller.go +1 −1
  • internal/hostedops/estimate.go +10 −1
  • internal/hostedops/fake_test.go +72 −9
  • internal/hostedops/fix1_test.go +692 −0
  • internal/hostedops/ledger.go +99 −15
  • internal/hostedops/ledgercmd.go +50 −19
  • internal/hostedops/ops.go +32 −5
  • internal/hostedops/ops_test.go +4 −3
  • internal/hostedops/report.go +138 −10
  • internal/hostedops/singleton.go +166 −35
  • internal/hostedops/stop.go +70 −10
  • internal/hostedops/tf.go +130 −8
  • internal/hostedops/tfvars.go +31 −8
  • internal/hostedops/units.go +133 −35
  • internal/hostedops/vms.go +18 −7
  • internal/isolatedjob/awsjob/opsaws/clients.go +14 −1
  • internal/isolatedjob/awsjob/opsaws/cloud.go +4 −0
  • internal/isolatedjob/awsjob/opsaws/fix1_test.go +441 −0
  • internal/isolatedjob/awsjob/opsaws/lookup.go +197 −19
  • internal/isolatedjob/awsjob/opsaws/opsaws.go +1 −1
  • internal/isolatedjob/awsjob/opsaws/opsaws_test.go +2 −1
  • scripts/release-hosted.sh +6 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 18365a22..b71cf956 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -88,4 +88,4 @@ perf GET /native/preview/exchange skip Rejects GET with 404; only a same-origin,
# and the same bounded cardView as the snapshot; no list scan or new route.
perf GET /api/v1/tasks/{id}/changes/diff skip Device-only bounded display patch JSON: indexed step/attempt lookup, 64 KiB patch and 128 KiB response, no Git or network work at read time; not an HTML screen.
size internal/hostedctl 6079 10017 Hosted controller core plus its lifecycle simulation; split planned for slice 1b; measured 5313/8516 source/test lines after the Task 17 pre-flight review rounds (R36, R38 ref checks); slice 2 Task 2 wires the egress manifest snapshot and LaunchRequest.Validate into Launch (logic in ctlegress), and maps ErrServiceUnset to 503 service_unset; measured 5341/8729; slice 2 Task 3 replaces Config.Images with the certificate set (logic in hostedcert and ctlcert), keeps the certificate digest and launch-by time on each intent, enforces launch-by before saving and before every provider call (it gates the dispatch path, so it stays here), and adds the admission record and route; measured 5444/9119; Task 3 review round 1 returns ErrLaunchExpired to a Launch whose own intent expired during dispatch (binding certificates to provider image versions is in ctlcert); measured 5462/9279; round 2 reports the launch-by time whichever abandonment reason is given; measured 5465/9325; slice 2 Task 4 wires the proxy client CA and feed (logic in ctlproxy): the three proxy routes and their transaction (proxy.go), the proxy role, Config.ProxyCA, the BootstrapV2 launch payload with its proxy code minted at intent save, revocation on stop, proof and resume, the code window opened by the first running sighting, the silent-proxy check in the reaper pass and its metric; measured 5662/9340. Task 4 review round 1: the proxy code is derived (HMAC key in Config, stripped from the saved bootstrap, derived again at each provider call; a changed key abandons the intent), and silence alerts are delivered from the store; measured 5689/9355. Slice 2 Task 5 wires the operator routes (ops.go: certification launch, certificate list, reload, restart, alert test, status; candidates, reload and the certification attempt are in ctlops): Launch and CertLaunch share one launch path, a certification intent is gated at dispatch by its image still being a candidate, the restart hook answers 202, and the reaper keeps its last clean pass for the status; operator_test.go is the brief's; measured 5939/9749. Task 5 review round 1: the reload fetches through an injected Deps.Fetcher first (ctlops.FetchAndReload; the S3 fetcher is in the command), the status reads the audit under one lock, and operator_test.go gains a fake config bucket and the fetch, failure and snapshot tests; measured 5954/9907. Slice 2 Task 13 wires certification reports (logic in ctlcert/report.go and hostedcert): the cert-report proxy route, its transaction and the controller's own stop of the reported VM (proxy.go), the operator evidence route, the proxy header check and two error codes (http.go), the Handler's signing key kept for evidence (controller.go), the stop reason, and schema version 5; measured 6022/9907. Task 13 review round 1: the report's stop is recorded in the transaction that keeps its evidence (recordStop, split out of requestStop so both share it) and driven on a context the request's end does not cancel; measured 6037/9907. Round 2: the stop rule moves to schema version 6 (the migration list line wraps) with TestUpgradeFromVersion5 upgrading a database made at bec02feb; measured 6038/9990. Round 3: the upgrade test also starts from a116d330's version 5; measured 6038/9996. Task 21 ruling: Get and Admission answer a signed 404 absent for an attempt with no record at all (ErrAbsent), keeping the 403 for another key's attempt, and the tests that pin it; measured 6049/10016. Task 22 review 2: Admission answers the job's current deadline (DeadlineInMS, counted from the answer) so the instance caps hosted credentials by a deadline moved earlier after launch, and its assertion; measured 6050/10017. Task 29: healthz.go, the metrics listener's GET /healthz (Controller.Healthz, a store read; the command mounts it beside /metrics and the API has no such route); wiring only, the CloudWatch publisher and Litestream lag live in the command; measured 6079/10017.
-size internal/hostedops 5499 - Hosted slice 2 Task 33: equipo-hosted-ops, the dev drill's and production bring-up's run kit; every subcommand the account plan uses (ledger, guard, estimate, VM settlement, connector, buckets, singletons, units, block and safe stop, tf and its reconcile, tfvars, named assertions, report and bundle) shares one journal and one Ops, so it is one package; measured 5499.
+size internal/hostedops 6258 - Hosted slice 2 Task 33: equipo-hosted-ops, the dev drill's and production bring-up's run kit; every subcommand the account plan uses (ledger, guard, estimate, VM settlement, connector, buckets, singletons, units, block and safe stop, tf and its reconcile, tfvars, named assertions, report and bundle) shares one journal and one Ops, so it is one package; measured 5499. Task 33 fix round 1 (Astra t33-r1 F1 to F18): the wait-human watchdog unit, unit wait into safe-stop, safe-stop's own context and unit, creation identity on intents, verify-gone's declared parents, fence by identity, MFA policy evaluation, connector identity, the release AMI, litestream-install, import-block adoption, decoded trail records, usage errors and the unit probe; 6258.
diff --git a/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md b/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md
index 0c5714ed..c6d2068e 100644
--- a/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md
+++ b/docs/superpowers/plans/2026-11-30-hosted-prod-account-plan.md
@@ -1,6 +1,8 @@
# Hosted runners: production account bring-up (149757027610, `equipo-hosted`)
-**Revision:** 4 (2026-11-30). Astra round 3 (`acct-r3.md`, the last) found two blocking items, both fixed
+**Revision:** 4.1 (2026-12-01): slice 2 Task 33 fix round 1 brought the `ops` steps into line with
+the tool (0.2's unit probe, the AMI from the release, 3.5's certification key ID, 4.1's Litestream
+install, 7.1's instance notes, the wait-human watchdog, unit wait and safe-stop rules). Revision 4 (2026-11-30). Astra round 3 (`acct-r3.md`, the last) found two blocking items, both fixed
here (rollback ordering; hand-over failure fences launches); its non-blocking items are carried into slice 2
Task 33 and the dev drill. Revision 4 is unreviewed by Astra (house limit of three rounds). Revision 3 came
after Astra rounds 1 and 2 (`acct-r1.md`, `acct-r2.md` in
@@ -137,7 +139,13 @@ Sections R (rollback), T (full teardown) and S (safe stop) run only when called.
and `cert`. Long blocks (3.4, 4.3, 5.2, 6.2) run as transient
systemd user units through `ops unit start|wait|stop` (Task 17b's R44 and R45 rules, ported: units
`hprod-<RUN>-<block>`, journalled before start, stopped by journalled name only, environment
- allowlisted).
+ allowlisted; 0.2 runs `ops unit probe` once first). `ops unit wait <block> --max <bound>` blocks until
+ the unit ends or its bound passes; a failure or an expired bound runs `ops safe-stop` and exits 99.
+ `ops wait-human <name> --max <bound> --background` starts a journalled watchdog unit
+ (`hprod-<RUN>-wait-<name>`) that runs `ops safe-stop` at the deadline with no further command;
+ `ops wait-human <name> --done`, run when Paul confirms, records it and stops the watchdog. `ops
+ safe-stop` runs under its own 30-minute bound, whatever interrupted its caller, and never stops the
+ unit it runs in.
- **Ledger.** Every create, in OpenTofu or not, has a durable intent before it. `ops tf` journals an
intent for each planned create address before `apply`; after a failed or interrupted apply,
`ops tf reconcile ROOT` runs `tofu plan -refresh-only` and lists this run's tagged resources through
@@ -270,6 +278,7 @@ img() ( eval "\$(aws configure export-credentials --profile equipo-hosted --form
cert() { "$P/bin/equipo-hosted-certify" "\$@"; }
EOF
"$P/bin/equipo-hosted-ops" -dir "$P" -run "$RUN" ledger init
+"$P/bin/equipo-hosted-ops" -dir "$P" -run "$RUN" unit probe # the systemd user unit mechanism, before any long block
echo "P=$P RUN=$RUN"
```
@@ -332,7 +341,9 @@ ops tfvars --out "$P/prod.tfvars" --instance-host '<INSTANCE_HOST>' --alert-emai
ops ledger note controller-pub "$(cat "$K/controller.pub")" # its fingerprint is posted on discussion 46 for 6.4
```
-`ops tfvars` writes only public halves, hostnames, fixed addresses and numbers.
+`ops tfvars` writes only public halves, hostnames, fixed addresses and numbers. It takes the hosts'
+AMI from the release manifest's `HostAMI` (pinned in `infra/hosted/release-pins.json`) and fails if
+the release pins none.
## 2. Account baseline
@@ -360,8 +371,8 @@ limit is $150.
### 2.3 Paul confirms the email subscription (HUMAN, by hand-over)
-`ops wait-human sns-confirmed --max 24h --background` starts the clock here; 9.1 checks it. Later
-steps do not wait for it.
+`ops wait-human sns-confirmed --max 24h --background` starts the clock and its watchdog here; when Paul
+confirms, `ops wait-human sns-confirmed --done`. 9.1 checks it. Later steps do not wait for it.
## 3. Network, config stack, connector, keys into place
@@ -411,7 +422,7 @@ hard stop.
### 3.5 Private keys into the config bucket
-`ops keys upload --bucket <config bucket> --expected-owner 149757027610 --keys "$P/keys"` uploads
+`ops keys upload --bucket <config bucket> --expected-owner 149757027610 --keys "$P/keys" --cert-key-id paul-cert-1` uploads
with SSE, each to its own key: `controller/controller.key`, `controller/client-ca.key`,
`controller/operators.json` (the operator public key), `controller/cert-keys.json` (Paul's certification public key, `<CERT_PUB>`), `proxy/a/proxy.key`, `proxy/a/intercept.key`,
`proxy/b/proxy.key`, `proxy/b/intercept.key`. Each is confirmed by a `HeadObject`. Keys are in place before any host exists. Each proxy's
@@ -428,7 +439,10 @@ for it. `image-source.tar` holds the exact manifest the release built the image
template and every input, each pinned in that manifest. Then run
`img build -bundle "$P/image-source.tar" -gitleaks-config "$REPO/.gitleaks.toml" -out "$P/image.zip"`
and `ops assert` that its digest equals `IMAGE_DIGEST` in the same release manifest, the image the dev
-drill certified. A difference is a hard stop.
+drill certified. A difference is a hard stop. Download the release's Litestream for docs-t1 too
+(`litestream-0.5.18-linux-x86_64.tar.gz`, the `linux/amd64` asset) and run
+`ops litestream-install --file "$P/litestream-0.5.18-linux-x86_64.tar.gz"`, which checks its SHA-256
+against the release manifest and installs `$P/bin/litestream` for 5.4.
### 4.2 Upload
@@ -484,7 +498,7 @@ reaper pass in the last 2 minutes; and the pin unchanged on a second read 60 s l
### 5.4 Restore check (fatal)
`ops litestream-check --bucket <litestream bucket>` restores the latest generation into `$P` with the
-pinned Litestream binary and checks that it opens and holds the `provider_bound` row. A failure is a hard stop: launches stay off until the database is durable. Litestream's version is
+pinned Litestream binary (`$P/bin/litestream`, installed in 4.1) and checks that it opens and holds the `provider_bound` row. A failure is a hard stop: launches stay off until the database is durable. Litestream's version is
pinned in the release manifest; the controller publishes `LitestreamLag`, and an alarm fires above
300 s. The drill that starts a restored controller against outstanding launches runs in the dev drill
(slice 2 Task 34), not here.
@@ -531,6 +545,9 @@ snapshot it derives from the evidence. The agent runs `cert verify -cert certifi
### 7.1 The Equipo instance's settings
+First `ops ledger note instance-app <INSTANCE_APP>` and `ops ledger note instance-account
+<INSTANCE_ACCOUNT>`, so the safe stop can turn the flag off (S.1); with a controller recorded and no
+notes, S.1 is unresolved and the safe stop exits 99. Then
`carlos env set --app <INSTANCE_APP> --account <INSTANCE_ACCOUNT> EQUIPO_HOSTED_CONTROLLER=https://<controller EIP>
EQUIPO_HOSTED_CONTROLLER_TLS_PIN=<pin> EQUIPO_HOSTED_CONTROLLER_PUB=<controller public key> EQUIPO_HOSTED_KEY_ID=instance
EQUIPO_HOSTED_IMAGE=<IMAGE_DIGEST> EQUIPO_HOSTED_ACCOUNT=<the instance's account name the controller records>` (the names slice 2 Task 21 reads);
@@ -563,7 +580,8 @@ step ends, `ops vms settle --image <image ARN> --max
### 8.3 Alert path
`cert alert-test --controller https://<controller EIP> --pin <pin> --operator-key "$P/keys/operator.key"`;
-then `ops wait-human alert-received --max 24h` (Paul confirms the email arrived). 9.1 requires it.
+then `ops wait-human alert-received --max 24h --background`, and `ops wait-human alert-received --done`
+when Paul confirms the email arrived. 9.1 requires it.
## 9. Hand-over
@@ -636,8 +654,11 @@ stay on.
## S. Safe stop
`ops safe-stop` runs these in order and never checks spend: S.0 `ops unit stop --all` (local, no
-AWS). S.1 `carlos env unset` of `EQUIPO_HOSTED_RUNNERS` if 7.1 ran. S.2 R.2's fence, if the
-controller host exists. S.3 R.3's VM identification. S.4 R.4's settlement, with its repeat after 10 minutes, then the other
+AWS; never the unit safe-stop itself runs in). S.1 `carlos env unset` of `EQUIPO_HOSTED_RUNNERS` from
+7.1's notes; with a controller and no notes this is unresolved (99). S.2 R.2's fence: every recorded
+controller host, and any open controller intent's host found by its creation identity; the host stop
+is attempted even if the policy attach fails, and if S.4's reconciliation finds more, the fence and
+settlement run again. S.3 R.3's VM identification. S.4 R.4's settlement, with its repeat after 10 minutes, then the other
intents' reconciliation, with `ops tf reconcile` for any root whose apply did not finish. S.5 `ops bundle` and
`ops report --stopped`: what exists and what it costs a day (about $1.10 with the controller host
stopped); the run waits for Paul. If a cloud step's own credential check fails, S does the local steps,
diff --git a/docs/superpowers/plans/2026-11-30-hosted-runners-slice-2.md b/docs/superpowers/plans/2026-11-30-hosted-runners-slice-2.md
index c9c64d6c..11671641 100644
--- a/docs/superpowers/plans/2026-11-30-hosted-runners-slice-2.md
+++ b/docs/superpowers/plans/2026-11-30-hosted-runners-slice-2.md
@@ -617,7 +617,7 @@ The account plan's Astra round 1 showed that live-run machinery adapted by hand
### Task 34: Dev live drill in `kass` (HUMAN GO)
-- [ ] Write `docs/superpowers/plans/2026-MM-DD-hosted-2-dev-live-plan.md` in the shape of Task 17b (safety-only hard stops, FINDING lines, ledger, systemd user units, teardown verified by type and tag): `tofu apply` of `envs/dev/*` in `kass` / `eu-west-1`, image build and publish, a certification launch, **HUMAN:** Paul signs offline, then hosted checks from the staging Equipo instance end to end, the Task 30 drills against real VMs, the egress matrix from inside a real VM, the connector interface cleanup (still unexercised), then `tofu destroy` and verification. Run every AWS step through `equipo-hosted-ops` (Task 33) with `-account 640012953448 -profile kass`, so the production tool is exercised first. Record `Task 34 PASSED` in the progress file only if every safety check passed. Astra reviews the plan, three rounds at most.
+- [ ] Write `docs/superpowers/plans/2026-MM-DD-hosted-2-dev-live-plan.md` in the shape of Task 17b (safety-only hard stops, FINDING lines, ledger, systemd user units, teardown verified by type and tag): `tofu apply` of `envs/dev/*` in `kass` / `eu-west-1`, image build and publish, a certification launch, **HUMAN:** Paul signs offline, then hosted checks from the staging Equipo instance end to end, the Task 30 drills against real VMs, the egress matrix from inside a real VM, the connector interface cleanup (still unexercised), then `tofu destroy` and verification. Run every AWS step through `equipo-hosted-ops` (Task 33) with `-account 640012953448 -profile kass`, so the production tool is exercised first. The `kass` profile names no `role_arn`, so the drill passes `-role` (its expected caller) to every `ops` call; the first `guard` binds that caller for the run. The dev release must pin `HostAMI` for `eu-west-1` (tfvars refuses a release without one), and the drill installs Litestream with `ops litestream-install` as the account plan's 4.1 does. Record `Task 34 PASSED` in the progress file only if every safety check passed. Astra reviews the plan, three rounds at most.
- [ ] **HUMAN:** Paul's one GO. The agent runs it, records spend, tears down.
### Task 35: Production bring-up (HUMAN GO)
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 815103b5..afc81047 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -2890,3 +2890,96 @@ Mutation checks (each applied alone, `CGO_ENABLED=0 go test ./<pkg> -run '^<Test
- M28 tf reconcile ignores a direct-read match. `TestTfReconcileFindsUntrackedResource`: exit 1 | ops_test.go:335: ops tf reconcile network = 99, want 0: | restored
- M29 an unreadable intent counts as absent. `TestReconcileUnresolvedWithoutNativeMatch`: exit 1 | ledger_test.go:120: ops ledger reconcile = 0, want 99: | restored
- M30 the bundle's secret scan off. `TestBundleReopenRoundTrip`: exit 1 | ledger_test.go:177: ops bundle --out $T/bundle.json = 0, want 99: | restored
+
+### Task 33 fix round 1
+
+Findings: `t33-r1.md` (Astra, changes requested); rulings: `task-33-fix1.md`. This round was red-first: every regression test below was written first and seen failing on its assertion against the round-1 code (`5c6d7afd`, rebased on `9b28fefb`), then the fix made it pass.
+
+The only API change made before the red run was a compile skeleton: `Deps.Self`, the identity fields on `LookupKey` (`NameTag`, `Parent`, `Token`) and the `networkCheckOutputs` list. One red came out wrong on the first try: `TestLookupMatchesIdentity` first panicked on a type assertion (the old code called DescribeTags). It was rewritten to fail on its assertion and run again. That second run is the red recorded below.
+
+RED (`CGO_ENABLED=0 go test ./internal/hostedops ./internal/isolatedjob/awsjob/opsaws -count=1 -run '<the new tests>'`). Line numbers are those of the red run; later test edits moved some, and the mutation lines below give the committed ones:
+- TestWaitHumanWatchdogStopsAtDeadline: fix1_test.go:54: no watchdog unit started and journalled: []
+- TestWaitHumanDoneCancelsWatchdog: fix1_test.go:74: --done did not stop the watchdog: []
+- TestUnitWaitFailureRunsSafeStop: fix1_test.go:89: ops unit wait 4.3 --max 50m = 1, want 99:
+- TestSafeStopSurvivesCancellation: fix1_test.go:113: safe-stop did not finish settling after the cancellation:
+- TestSafeStopSparesItsOwnUnit: fix1_test.go:125: stopped [hprod-r1-wait-sns.service hprod-r1-4.3.service]; want the other unit and never its own
+- TestTfIntentCarriesIdentity: fix1_test.go:140: the intent carries no identity: [...]
+- TestVerifyGoneUnsupportedStops: fix1_test.go:172: ops verify-gone = 0, want 99:
+- TestFenceFindsUnrecordedController: fix1_test.go:197: the unrecorded controller was not fenced: []
+- TestSafeStopFencesAgainAfterReconcile: fix1_test.go:227: safe-stop did not fence the host reconciliation found: [HeadBucket equipo-hosted-tfstate-149757027610 149757027610 TaggedARNs]
+- TestMFACheckParsesTrust: fix1_test.go:255: ops mfa-check = 0, want 99:
+- TestConnectorIdentityBeforeCreate: fix1_test.go:268: the connector intent lacks its subnet, group or role: [...]
+- TestOutputsMatchRoots: fix1_test.go:292: envs/prod/network has no output "services_route_table_id", which ops reads
+- TestTfvarsAMIFromRelease: fix1_test.go:317: ops tfvars --release hosted-0.1.0 = 0, want 1:
+- TestLitestreamInstall: fix1_test.go:349: ops litestream-install --file $T = 1, want 0:
+- TestCertKeyIDRequiredAndVerifies: fix1_test.go:374: ops keys upload --bucket equipo-hosted-config-149757027610 --expected-owner 149757027610 --keys $T = 0, want 1:
+- TestRepeatedOperationsResolve: fix1_test.go:408: a repeated fence left 1 intents open
+- TestRepeatedObjectPutResolves: fix1_test.go:425: a repeated upload left 1 intents open: equipo-hosted-config-149757027610/proxy/a/controller.json
+- TestSettleResolvesOnlyItsImage: fix1_test.go:442: open launch intents [], want image B's and the unmapped one
+- TestEstimateStopsOnUnresolvedHost: fix1_test.go:450: ops estimate = 0, want 99:
+- TestAdoptedResourceTornDown: fix1_test.go:483: no import block written: open $T no such file or directory
+- TestSafeStopInstanceFlagUnresolved: fix1_test.go:503: ops safe-stop = 0, want 99:
+- TestTrailEventSameRecord: fix1_test.go:539: trail-event seen true, want false
+- TestVMsScanMax: fix1_test.go:554: ops vms scan --image arn:aws:lambda:eu-west-1:149757027610:microvm-image:equipo-hosted-prod-r1 --max 1m = 1, want 0:
+- TestUnitProbe: fix1_test.go:563: ops unit probe = 1, want 0:
+- TestPlanInvocationsParseFlags: fix1_test.go:596: a malformed invocation is not a usage error: vms settle --image ARN [--terminate] --max D
+- TestLookupMatchesIdentity: fix1_test.go:72: the lookup called DescribeTags, not DescribeVpcs
+- TestLookupFiltersByParent: fix1_test.go:124: the lookup called DescribeTags, not DescribeSubnets
+- TestLookupLogGroup: fix1_test.go:155: log group lookup = {IDs:[] Definitive:false}, <nil>
+- TestGuardBindsFirstRole: fix1_test.go:173: a guard under another role = 0: guard: account 149757027610, arn:aws:sts::149757027610:assumed-role/Admin/equipo-hosted-bringup, region eu-west-1
+- TestGetObjectReadsWithinDeadline: fix1_test.go:203: GetObject = "", context canceled; want the whole body
+
+Not red-first, and recorded as such:
+- `TestSDKRequestShapes` (opsaws) is coverage. It records the request shape and pagination of the SDK calls round 1 never exercised: Network, Trail, Inventory, Quotas, alarms, SNS, the connector, IAM and the MicroVMs listing. It passed against the existing code when first run.
+- `TestEveryStackTypeVerifiable` is a structural check. It was written with F4's declared-parent map, to show that every type phases.json lists has a direct read or a declared parent.
+
+Two round-1 tests were changed to the rulings:
+- `TestRequiredStepFailureStops` now expects 99 through safe-stop from `unit wait` and `wait-human` (F1).
+- `TestFenceBeforeSettle` now records 7.1's instance notes, because a controller with no notes is unresolved (F16).
+
+The new test `TestAdoptedResourceTornDown` first compared the import against the reconcile's refresh plan, not the destroy plan, and was corrected. The journal's fsync is now skipped in tests only (`Deps.noSync`): on a box at load 89, the hostedops package fell from 26 s to 2 to 3 s.
+
+GREEN:
+- `CGO_ENABLED=0 go test ./internal/hostedops/... ./internal/isolatedjob/... ./cmd/equipo-hosted-ops ./internal/hostedclient -count=1`: all ok.
+- `make build vet govulncheck budget lanes-check fmt-check` ok; the budget record is now `size internal/hostedops 6258`, with its reason.
+- staticcheck v0.7.0 is clean on the new packages; the darwin and windows builds of the command succeed.
+- `python3 -I infra/hosted/scripts/plan_check_test.py`: 101 tests ok.
+- `tofu fmt -check -recursive infra/hosted` ok; `tofu validate` and `tofu test` (mocked provider) of `envs/prod/network` and `envs/dev/network`: valid, 2 passed each.
+
+Mutation checks (each applied alone, `CGO_ENABLED=0 go test ./<pkg> -run '^<Test>$' -count=1`, restored byte for byte and checked by the script). The first tries of R16, R35 and R36 did not compile; they were rewritten and run again, with the results below.
+- R1 F1 no watchdog unit. `TestWaitHumanWatchdogStopsAtDeadline`: exit 1 | fix1_test.go:54: no watchdog unit started and journalled: [] | restored
+- R2 F1 the expired wait skips safe-stop. `TestWaitHumanWatchdogStopsAtDeadline`: exit 1 | fix1_test.go:61: the watchdog did not run safe-stop at the deadline | restored
+- R3 F1 --done leaves the watchdog running. `TestWaitHumanDoneCancelsWatchdog`: exit 1 | fix1_test.go:74: --done did not stop the watchdog: [] | restored
+- R4 F1 a failed unit skips safe-stop. `TestUnitWaitFailureRunsSafeStop`: exit 1 | fix1_test.go:91: a failed required unit did not reach safe-stop | restored
+- R5 F2 safe-stop under the caller's context. `TestSafeStopSurvivesCancellation`: exit 1 | fix1_test.go:113: safe-stop did not finish settling after the cancellation: | restored
+- R6 F2 safe-stop stops its own unit. `TestSafeStopSparesItsOwnUnit`: exit 1 | fix1_test.go:125: stopped [hprod-r1-wait-sns.service hprod-r1-4.3.service]; want the other unit and never its own | restored
+- R7 F3 intents without identity. `TestTfIntentCarriesIdentity`: exit 1 | fix1_test.go:140: the intent carries no identity: [...] | restored
+- R8 F3 two matches taken as one. `TestTfIntentCarriesIdentity`: exit 1 | fix1_test.go:158: ops tf reconcile network = 0, want 99: | restored
+- R9 F3 the Name tag filter dropped. `TestLookupMatchesIdentity`: exit 1 | fix1_test.go:100: lookup of the VM VPC = {IDs:[] Definitive:true}, <nil>; want only vpc-0vm (on a later page) | restored
+- R10 F3 one page only. `TestLookupMatchesIdentity`: exit 1 | fix1_test.go:100: lookup of the VM VPC = {IDs:[] Definitive:true}, <nil>; want only vpc-0vm (on a later page) | restored
+- R11 F3 the parent filter dropped. `TestLookupFiltersByParent`: exit 1 | fix1_test.go:132: subnet lookup {IDs:[subnet-0vm] Definitive:true} <nil> with filters map[tag:Name:equipo-hosted-vm tag:run:r1] | restored
+- R12 F4 an unreadable type passes. `TestVerifyGoneUnsupportedStops`: exit 1 | fix1_test.go:175: ops verify-gone = 0, want 99: | restored
+- R13 F4 no log group read. `TestLookupLogGroup`: exit 1 | fix1_test.go:155: log group lookup = {IDs:[] Definitive:false}, <nil> | restored
+- R14 F5 open controller intents ignored. `TestFenceFindsUnrecordedController`: exit 1 | fix1_test.go:200: the unrecorded controller was not fenced: [AttachRolePolicy equipo-hosted-controller arn:aws:iam::149757027610:policy/equipo-hosted-deny-launches RolePolicyAttached equipo-hosted-controller] | restored
+- R15 F5 a failed attach skips the host stop. `TestFenceFindsUnrecordedController`: exit 1 | fix1_test.go:206: a failed attach skipped the host stop | restored
+- R16 F5 no second fence. `TestSafeStopFencesAgainAfterReconcile`: exit 1 | fix1_test.go:230: safe-stop did not fence the host reconciliation found: [Lookup aws_instance HeadBucket equipo-hosted-tfstate-149757027610 149757027610 TaggedARNs] | restored
+- R17 F6 no role binding. `TestGuardBindsFirstRole`: exit 1 | fix1_test.go:173: a guard under another role = 0: guard: account 149757027610, arn:aws:sts::149757027610:assumed-role/Admin/equipo-hosted-bringup, region eu-west-1 | restored
+- R18 F7 any MFA condition counts. `TestMFACheckParsesTrust`: exit 1 | fix1_test.go:258: ops mfa-check = 0, want 99: | restored
+- R19 F8 the intent without subnet, group and role. `TestConnectorIdentityBeforeCreate`: exit 1 | fix1_test.go:271: the connector intent lacks its subnet, group or role: [...] | restored
+- R20 F8 delete without a subnet. `TestConnectorIdentityBeforeCreate`: exit 1 | fix1_test.go:276: ops connector delete = 0, want 99: | restored
+- R21 F9 the output dropped again. `TestOutputsMatchRoots`: exit 1 | fix1_test.go:295: envs/prod/network has no output "services_route_table_id", which ops reads | restored
+- R22 F10 no AMI accepted. `TestTfvarsAMIFromRelease`: exit 1 | fix1_test.go:320: ops tfvars --release hosted-0.1.0 = 0, want 1: | restored
+- R23 F10 the Litestream digest unchecked. `TestLitestreamInstall`: exit 1 | fix1_test.go:358: ops litestream-install --file $T = 0, want 99: | restored
+- R24 F11 a default key ID. `TestCertKeyIDRequiredAndVerifies`: exit 1 | fix1_test.go:377: ops keys upload --bucket equipo-hosted-config-149757027610 --expected-owner 149757027610 --keys $T = 0, want 1: | restored
+- R25 F12 a repeated record resolves nothing. `TestRepeatedObjectPutResolves`: exit 1 | fix1_test.go:428: a repeated upload left 1 intents open: equipo-hosted-config-149757027610/proxy/a/controller.json | restored
+- R26 F12 no host repair. `TestRepeatedOperationsResolve`: exit 1 | fix1_test.go:416: the host record was not repaired: &{ID:i-0ctl Type: Address:services/module.controller.aws_instance.controller At:2026-12-01 09:59:58 +0000 UTC Gone:0001-01-01 00:00:00 +0000 UTC} | restored
+- R27 F13 any settlement resolves every launch. `TestSettleResolvesOnlyItsImage`: exit 1 | fix1_test.go:445: open launch intents [], want image B's and the unmapped one | restored
+- R28 F14 unresolved hosts admitted. `TestEstimateStopsOnUnresolvedHost`: exit 1 | fix1_test.go:453: ops estimate = 0, want 99: | restored
+- R29 F14 hosts charged from their record. `TestEstimateStopsOnUnresolvedHost`: exit 1 | fix1_test.go:465: the host is charged 1 hours, want at least the 5 since its intent | restored
+- R30 F15 adoptions never imported. `TestAdoptedResourceTornDown`: exit 1 | fix1_test.go:493: the adoption was not imported before the destroy plan: | restored
+- R31 F16 a missing note skipped. `TestSafeStopInstanceFlagUnresolved`: exit 1 | fix1_test.go:506: ops safe-stop = 0, want 99: | restored
+- R32 F17 the deadline ends with the call. `TestGetObjectReadsWithinDeadline`: exit 1 | fix1_test.go:203: GetObject = "", context canceled; want the whole body | restored
+- R33 F18 the run's time not checked. `TestTrailEventSameRecord`: exit 1 | fix1_test.go:542: trail-event seen true, want false | restored
+- R34 X1 a malformed invocation an ordinary failure. `TestPlanInvocationsParseFlags`: exit 1 | fix1_test.go:599: a malformed invocation is not a usage error: vms settle --image ARN [--terminate] --max D | restored
+- R35 X2 no retry within --max. `TestVMsScanMax`: exit 1 | fix1_test.go:557: ops vms scan --image arn:aws:lambda:eu-west-1:149757027610:microvm-image:equipo-hosted-prod-r1 --max 1m = 99, want 0: | restored
+- R36 X4 the probe accepts a credential. `TestUnitProbe`: exit 1 | fix1_test.go:574: ops unit probe = 0, want 99: | restored
diff --git a/go.mod b/go.mod
index eacf06c7..b5f28b36 100644
--- a/go.mod
+++ b/go.mod
@@ -26,6 +26,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/budgets v1.53.12
github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.15
github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
+ github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.92.5
github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0
github.com/aws/aws-sdk-go-v2/service/iam v1.68.3
github.com/aws/aws-sdk-go-v2/service/lambdacore v1.14.0
@@ -55,7 +56,7 @@ require (
github.com/Masterminds/sprig/v3 v3.3.0 // indirect
github.com/STARRY-S/zip v0.2.1 // indirect
github.com/andybalholm/brotli v1.2.7 // indirect
- github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 // indirect
+ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.21.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.9 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect
diff --git a/go.sum b/go.sum
index cefb6d71..a1652bfd 100644
--- a/go.sum
+++ b/go.sum
@@ -49,8 +49,8 @@ github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLj
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/aws/aws-sdk-go-v2 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU=
github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14 h1:3IZY0XAJquT3aHzbkHfPzy4ACPcEjVG0x87KOwtpqGY=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14/go.mod h1:zwM6veDkhGgQFqkBy+uT28AAYpLu+uFMlPl+rCg/73E=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29 h1:LfdRwpJ0Dfh+vpqHevmmnFnMoc3/lfB4pdHOfWpLfH4=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.29/go.mod h1:r6fijnrGRQ4OnSGyHYuFcC7G6wdwB4Ld8WhiIaGZHx0=
github.com/aws/aws-sdk-go-v2/config v1.33.21 h1:NY1d3yXmplUSYnUAue0sR88svD+SJiaI+YJGp8TxSNg=
github.com/aws/aws-sdk-go-v2/config v1.33.21/go.mod h1:pVJNXUXaCLu9a/4/liTklg9zR3yO0xm/XBEQhgg5nzc=
github.com/aws/aws-sdk-go-v2/credentials v1.21.3 h1:bh+9VoJ4eDzJVEY6jfdNTBa0Dx7tdr+lWSPNovU1vXc=
@@ -69,6 +69,8 @@ github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.15 h1:u9OIto7TbRP+w+uBTBHC
github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.15/go.mod h1:vHBVnRBszUt0AgzerqZmoIKjZLOwWNprVfko9XZMxwI=
github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0 h1:RdWMeCVaJfu4hCPyRNVQMKMP/Y5J04zB5LF45DmHhRg=
github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0/go.mod h1:HfsU8PQ6mHewSJNS77IPAFMZZgFaYSHjAhSOAFXdu9M=
+github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.92.5 h1:qkMh4i7JbfPDsJi81Jq9RkhSUIQ1r4WTi9ekp4hGKL8=
+github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs v1.92.5/go.mod h1:8aHzHS5El4/VWE+nUHqPWj5MRUigXyHIBKX6W/rRA8Q=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0 h1:EjAV+HmAnHedN+iYZF+b4SQYtMGlMdjURLbZc3q32fs=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0/go.mod h1:uMJiOkxaT3pV+LAeAvEaXToZ2x3nEnN53HnPdj+pcNo=
github.com/aws/aws-sdk-go-v2/service/iam v1.68.3 h1:neRSWQTKii7iv0SaHoYQjI0lvWTBoQXmT47U088GRe0=
diff --git a/infra/hosted/envs/dev/network/main.tf b/infra/hosted/envs/dev/network/main.tf
index fbd97a0d..1977f4fa 100644
--- a/infra/hosted/envs/dev/network/main.tf
+++ b/infra/hosted/envs/dev/network/main.tf
@@ -131,6 +131,10 @@ output "peering_id" {
value = module.network.peering_id
}
+output "services_route_table_id" {
+ value = module.network.services_route_table_id
+}
+
output "connector_operator_role_arn" {
value = module.network.connector_operator_role_arn
}
diff --git a/infra/hosted/envs/prod/network/main.tf b/infra/hosted/envs/prod/network/main.tf
index f1a9bc8b..127e16de 100644
--- a/infra/hosted/envs/prod/network/main.tf
+++ b/infra/hosted/envs/prod/network/main.tf
@@ -131,6 +131,10 @@ output "peering_id" {
value = module.network.peering_id
}
+output "services_route_table_id" {
+ value = module.network.services_route_table_id
+}
+
output "connector_operator_role_arn" {
value = module.network.connector_operator_role_arn
}
diff --git a/infra/hosted/release-pins.json b/infra/hosted/release-pins.json
index 21c72680..83257e8e 100644
--- a/infra/hosted/release-pins.json
+++ b/infra/hosted/release-pins.json
@@ -1,5 +1,8 @@
{
"BaseImageVersion": "",
+ "HostAMI": {
+ "eu-west-1": ""
+ },
"Litestream": {
"Version": "0.5.18",
"Source": "https://github.com/benbjohnson/litestream/releases/download/v0.5.18",
diff --git a/internal/hostedops/assert.go b/internal/hostedops/assert.go
index 2cd95341..5e873342 100644
--- a/internal/hostedops/assert.go
+++ b/internal/hostedops/assert.go
@@ -328,6 +328,7 @@ func checkTrailEvent(o *Ops, args []string) ([]string, error) {
if image == "" {
return nil, failf("no image recorded")
}
+ start := l.Entries[0].At // the run's first journal line
bucket := o.namePrefix() + "-trail-" + o.Account
if err := o.checkOwner(bucket, ""); err != nil {
return nil, err
@@ -349,7 +350,7 @@ func checkTrailEvent(o *Ops, args []string) ([]string, error) {
body = b
}
}
- if bytes.Contains(body, []byte(`"eventCategory":"Data"`)) && bytes.Contains(body, []byte(image)) {
+ if dataEventFor(body, image, start, o.Clock.Now()) {
found = true
}
}
@@ -360,6 +361,35 @@ func checkTrailEvent(o *Ops, args []string) ([]string, error) {
return nil, o.jw("NOTE", "trail-event seen %s", image)
}
+// dataEventFor decodes one trail log object (F18) and reports whether a
+// single record is a Data event, between from and to, whose resources name
+// image (or one of its versions).
+func dataEventFor(body []byte, image string, from, to time.Time) bool {
+ var log struct {
+ Records []struct {
+ EventCategory string `json:"eventCategory"`
+ EventTime time.Time `json:"eventTime"`
+ Resources []struct {
+ ARN string `json:"ARN"`
+ } `json:"resources"`
+ } `json:"Records"`
+ }
+ if json.Unmarshal(body, &log) != nil {
+ return false
+ }
+ for _, r := range log.Records {
+ if r.EventCategory != "Data" || r.EventTime.Before(from) || r.EventTime.After(to) {
+ continue
+ }
+ for _, res := range r.Resources {
+ if res.ARN == image || strings.HasPrefix(res.ARN, image+":") {
+ return true
+ }
+ }
+ }
+ return false
+}
+
// checkPrerequisites is 9.1: the SNS subscription confirmed (2.3's wait,
// within its bound), Paul's alert email (8.3), the alarms that must be OK,
// and the trail's MicroVM data event (6.4's fact).
diff --git a/internal/hostedops/buckets.go b/internal/hostedops/buckets.go
index 9a20a8c4..ed0f702b 100644
--- a/internal/hostedops/buckets.go
+++ b/internal/hostedops/buckets.go
@@ -56,7 +56,7 @@ func cmdBucketCreate(o *Ops, args []string) error {
sse := fs.String("sse", "", "AES256")
block := fs.Bool("block-public", false, "block all public access")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *b.name == "" {
- return failf("bucket create --name N [--versioning] [--sse AES256] [--block-public] --expected-owner A")
+ return usagef("bucket create --name N [--versioning] [--sse AES256] [--block-public] --expected-owner A")
}
if *sse != "" && *sse != "AES256" {
return failf("--sse must be AES256")
@@ -212,7 +212,7 @@ func cmdBucketEmpty(o *Ops, args []string) error {
fs := flag.NewFlagSet("bucket empty", flag.ContinueOnError)
b := bucketFlags(fs)
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *b.name == "" {
- return failf("bucket empty --name N [--expected-owner A]")
+ return usagef("bucket empty --name N [--expected-owner A]")
}
if ok, err := o.haveBucket(*b.name); !ok || err != nil {
return err
@@ -232,7 +232,7 @@ func cmdBucketDelete(o *Ops, args []string) error {
fs := flag.NewFlagSet("bucket delete", flag.ContinueOnError)
b := bucketFlags(fs)
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *b.name == "" {
- return failf("bucket delete --name N [--expected-owner A]")
+ return usagef("bucket delete --name N [--expected-owner A]")
}
if ok, err := o.haveBucket(*b.name); !ok || err != nil {
return err
@@ -287,7 +287,7 @@ func cmdObjectPut(o *Ops, args []string) error {
file := fs.String("file", "", "the file to upload")
owner := fs.String("expected-owner", "", "the account that must own the bucket (default -account)")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *bucket == "" || *key == "" || *file == "" {
- return failf("object put --bucket B --key K --file F [--expected-owner A]")
+ return usagef("object put --bucket B --key K --file F [--expected-owner A]")
}
abs, _ := filepath.Abs(*file)
keysDir, _ := filepath.Abs(o.path("keys"))
@@ -321,18 +321,17 @@ var keyUploads = [][2]string{
{"proxy/b/intercept.key", "intercept-ca.key"},
}
-// CertKeyID is the ID Paul's certification key gets in
-// controller/cert-keys.json; equipo-hosted-certify sign -key-id must match.
-const CertKeyID = "paul"
-
func cmdKeysUpload(o *Ops, args []string) error {
fs := flag.NewFlagSet("keys upload", flag.ContinueOnError)
bucket := fs.String("bucket", "", "the config bucket")
owner := fs.String("expected-owner", "", "the account that must own it")
dir := fs.String("keys", "", "the keys directory (1.2)")
- certID := fs.String("cert-key-id", CertKeyID, "the certification key's ID")
- if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *bucket == "" || *dir == "" {
- return failf("keys upload --bucket B --expected-owner A --keys DIR")
+ certID := fs.String("cert-key-id", "", "the certification key's ID (paul-cert-1 in the account plan); cert sign -key-id must match")
+ if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *bucket == "" || *dir == "" || *certID == "" {
+ return usagef("keys upload --bucket B --expected-owner A --keys DIR --cert-key-id ID")
+ }
+ if !kindPattern.MatchString(*certID) {
+ return usagef("--cert-key-id %q is not an ID", *certID)
}
l, err := o.ledger()
if err != nil {
@@ -390,7 +389,7 @@ func cmdWaitObject(o *Ops, args []string) error {
maxD := fs.Duration("max", 15*time.Minute, "the bound")
every := fs.Duration("every", 15*time.Second, "how often to look")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *bucket == "" || *key == "" {
- return failf("wait object --bucket B --key K --max D")
+ return usagef("wait object --bucket B --key K --max D")
}
if err := o.checkOwner(*bucket, ""); err != nil {
return err
diff --git a/internal/hostedops/cloud.go b/internal/hostedops/cloud.go
index 7b5d939f..fc970f81 100644
--- a/internal/hostedops/cloud.go
+++ b/internal/hostedops/cloud.go
@@ -159,6 +159,10 @@ type Inventory struct {
// token it was created under.
type LookupKey struct {
Type, ID, Name, Run string
+ // NameTag, Parent and Token are the creation identity journalled with
+ // the intent: the resource's Name tag, its parent's ID (a VPC for a
+ // subnet), and the client token where the API takes one.
+ NameTag, Parent, Token string
}
// LookupResult is a direct read's answer. Definitive is false when the read
diff --git a/internal/hostedops/connector.go b/internal/hostedops/connector.go
index e0a6a5e9..74b75c0b 100644
--- a/internal/hostedops/connector.go
+++ b/internal/hostedops/connector.go
@@ -27,7 +27,7 @@ func cmdConnectorCreate(o *Ops, args []string) error {
role := fs.String("role", "", "the connector_operator role ARN")
maxD := fs.Duration("max", 20*time.Minute, "the bound for ACTIVE")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *subnet == "" || *sg == "" || *role == "" {
- return failf("connector create --subnet S --security-group G --role ARN [--max D]")
+ return usagef("connector create --subnet S --security-group G --role ARN [--max D]")
}
l, err := o.ledger()
if err != nil {
@@ -44,7 +44,9 @@ func cmdConnectorCreate(o *Ops, args []string) error {
return stopf("connector %s has an unresolved intent; ledger reconcile first", name)
}
token := name + "-" + fmt.Sprint(len(l.Intents)+1)
- if err := o.jw("INTENT", "connector %s %s", name, token); err != nil {
+ // The subnet, group and role go in the intent, before the create (F8):
+ // a delete after any failure still knows which interfaces to prove gone.
+ if err := o.jw("INTENT", "connector %s %s subnet=%s sg=%s role=%s", name, token, *subnet, *sg, *role); err != nil {
return err
}
c := o.cloud
@@ -118,7 +120,7 @@ func cmdConnectorCreate(o *Ops, args []string) error {
// hand: each recorded one must be read gone.
func cmdConnectorDelete(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("connector delete takes no arguments")
+ return usagef("connector delete takes no arguments")
}
l, err := o.ledger()
if err != nil {
@@ -135,6 +137,14 @@ func cmdConnectorDelete(o *Ops, args []string) error {
}
arn := l.RecValue("connector", name)
subnet := l.Notes["connector-subnet"]
+ for _, in := range l.Intents {
+ if in.Kind == "connector" && in.Name == name && in.Attr("subnet") != "" {
+ subnet = in.Attr("subnet")
+ }
+ }
+ if subnet == "" {
+ return stopf("connector %s: no subnet is recorded, so its interfaces cannot be proved gone; nothing deleted", name)
+ }
c := o.cloud
budgetEnd := o.Clock.Now().Add(ConnectorBudget)
bound := func(d time.Duration) (time.Duration, error) {
@@ -144,15 +154,13 @@ func cmdConnectorDelete(o *Ops, args []string) error {
}
return min(d, left), nil
}
- var enis []string
- if subnet != "" {
- if enis, err = c.SubnetInterfaces(o.ctx, subnet); err != nil {
- return stopf("the interface list before the connector delete failed: %v", err)
- }
- for _, e := range enis {
- if err := o.jw("SERVICE-ENI", "%s", e); err != nil {
- return err
- }
+ enis, err := c.SubnetInterfaces(o.ctx, subnet)
+ if err != nil {
+ return stopf("the interface list before the connector delete failed: %v", err)
+ }
+ for _, e := range enis {
+ if err := o.jw("SERVICE-ENI", "%s", e); err != nil {
+ return err
}
}
attempt := func() (string, error) {
@@ -185,9 +193,6 @@ func cmdConnectorDelete(o *Ops, args []string) error {
}
}
interfacesGone := func() (bool, error) {
- if subnet == "" {
- return true, nil
- }
d, err := bound(ConnectorGoneBound)
if err != nil {
return false, err
@@ -230,9 +235,6 @@ func cmdConnectorDelete(o *Ops, args []string) error {
if err := o.finding("connector teardown needs the pre-approved fallback (%s, or interfaces left)", res); err != nil {
return err
}
- if subnet == "" {
- return stopf("no connector subnet recorded; the fallback policy cannot be written")
- }
role := o.namePrefix() + "-connector-operator"
a := "arn:aws:ec2:" + o.Region + ":" + o.Account
doc := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Sid":"DeleteEniInThisSubnet","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"%s:network-interface/*","Condition":{"ArnEquals":{"ec2:Subnet":"%s:subnet/%s"}}}]}`, a, a, subnet)
diff --git a/internal/hostedops/controller.go b/internal/hostedops/controller.go
index 5dbc4e24..d7a19c21 100644
--- a/internal/hostedops/controller.go
+++ b/internal/hostedops/controller.go
@@ -83,7 +83,7 @@ func cmdStatus(o *Ops, args []string) error {
fs := flag.NewFlagSet("status", flag.ContinueOnError)
ca := controllerFlags(fs)
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("status [--controller URL --pin HEX --operator-key FILE]")
+ return usagef("status [--controller URL --pin HEX --operator-key FILE]")
}
cl, err := o.controller(ca)
if err != nil {
diff --git a/internal/hostedops/estimate.go b/internal/hostedops/estimate.go
index a5eb7dea..89360e83 100644
--- a/internal/hostedops/estimate.go
+++ b/internal/hostedops/estimate.go
@@ -32,6 +32,10 @@ const (
DefaultStop = 25.0
)
+// chargeable are the resource types an estimate cannot leave out: a host
+// (with its address and volume) whose creation is unresolved stops it.
+var chargeable = map[string]bool{"aws_instance": true, "aws_eip": true}
+
// HostHourly are eu-west-1 on-demand rates for the types the stacks use.
var HostHourly = map[string]float64{"t4g.small": 0.0184, "t4g.micro": 0.0092}
@@ -141,6 +145,11 @@ func (o *Ops) estimate() (Estimate, error) {
if open := l.Open("microvm-image"); len(open) > 0 {
return Estimate{}, stopf("estimate: image %s is unresolved, so its VMs cannot be scanned", open[0].Name)
}
+ for _, in := range l.Open("tf") { // F14: a host that may exist but is not recorded cannot be charged
+ if chargeable[in.Attr("type")] {
+ return Estimate{}, stopf("estimate: %s may exist but is unresolved; tf reconcile its root first", in.Name)
+ }
+ }
for _, r := range l.Recorded("microvm-image") {
if l.Deleted["microvm-image "+r.Value] {
continue
@@ -163,7 +172,7 @@ func cmdEstimate(o *Ops, args []string) error {
fs := flag.NewFlagSet("estimate", flag.ContinueOnError)
stop := fs.Float64("stop", 0, "exit 99 when the estimate reaches USD")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("estimate [--stop USD]")
+ return usagef("estimate [--stop USD]")
}
e, err := o.estimate()
if err != nil {
diff --git a/internal/hostedops/fake_test.go b/internal/hostedops/fake_test.go
index b5769cc4..401fff53 100644
--- a/internal/hostedops/fake_test.go
+++ b/internal/hostedops/fake_test.go
@@ -3,10 +3,13 @@ package hostedops
import (
"bytes"
"context"
+ "crypto/sha256"
+ "encoding/base64"
"errors"
"fmt"
"os"
"path/filepath"
+ "sort"
"strings"
"sync"
"testing"
@@ -28,7 +31,10 @@ type fakeClock struct {
}
func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now }
-func (c *fakeClock) Sleep(_ context.Context, d time.Duration) error {
+func (c *fakeClock) Sleep(ctx context.Context, d time.Duration) error {
+ if ctx != nil && ctx.Err() != nil {
+ return ctx.Err()
+ }
c.mu.Lock()
c.now = c.now.Add(d)
c.mu.Unlock()
@@ -58,6 +64,9 @@ type fakeCloud struct {
instState string
reverify error
keys Keys
+ trust string
+ attachErr error
+ objects map[string][]byte // bucket/key
}
func newCloud(clock *fakeClock) *fakeCloud {
@@ -159,11 +168,14 @@ func (f *fakeCloud) PutRolePolicy(_ context.Context, role, name, doc string) err
}
func (f *fakeCloud) RoleTrustPolicy(_ context.Context, role string) (string, error) {
f.rec("RoleTrustPolicy %s", role)
- return `{"Statement":[{"Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}]}`, nil
+ if f.trust != "" {
+ return f.trust, nil
+ }
+ return `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"sts:AssumeRole","Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}}}]}`, nil
}
func (f *fakeCloud) AttachRolePolicy(_ context.Context, role, p string) error {
f.rec("AttachRolePolicy %s %s", role, p)
- return nil
+ return f.attachErr
}
func (f *fakeCloud) RolePolicyAttached(_ context.Context, role, p string) (bool, error) {
f.rec("RolePolicyAttached %s", role)
@@ -209,15 +221,45 @@ func (f *fakeCloud) DeleteBucket(_ context.Context, b, o string) error {
}
func (f *fakeCloud) PutObject(_ context.Context, b, o, k string, body []byte) error {
f.rec("PutObject %s/%s", b, k)
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.objects == nil {
+ f.objects = map[string][]byte{}
+ }
+ f.objects[b+"/"+k] = append([]byte(nil), body...)
return nil
}
func (f *fakeCloud) HeadObject(_ context.Context, b, o, k string) (string, error) {
- return "", ErrNotFound
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ body, ok := f.objects[b+"/"+k]
+ if !ok {
+ return "", ErrNotFound
+ }
+ s := sha256.Sum256(body)
+ return base64.StdEncoding.EncodeToString(s[:]), nil
}
func (f *fakeCloud) GetObject(_ context.Context, b, o, k string) ([]byte, error) {
- return nil, ErrNotFound
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ body, ok := f.objects[b+"/"+k]
+ if !ok {
+ return nil, ErrNotFound
+ }
+ return body, nil
+}
+func (f *fakeCloud) ListKeys(_ context.Context, b, o, p string) ([]string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []string
+ for k := range f.objects {
+ if strings.HasPrefix(k, b+"/"+p) {
+ out = append(out, strings.TrimPrefix(k, b+"/"))
+ }
+ }
+ sort.Strings(out)
+ return out, nil
}
-func (f *fakeCloud) ListKeys(_ context.Context, b, o, p string) ([]string, error) { return nil, nil }
func (f *fakeCloud) AccountPublicAccessBlock(context.Context) (PublicAccessBlock, error) {
f.rec("AccountPublicAccessBlock")
return f.pab, nil
@@ -283,6 +325,8 @@ type fakeSystemd struct {
states map[string]string
started []string
stopped []string
+ argv map[string][]string
+ status map[string]string // unit -> its status file
}
func (s *fakeSystemd) Start(unit, wd, out, status, ep string, argv []string) error {
@@ -290,6 +334,21 @@ func (s *fakeSystemd) Start(unit, wd, out, status, ep string, argv []string) err
defer s.mu.Unlock()
s.started = append(s.started, unit)
s.states[unit] = "running"
+ if s.argv == nil {
+ s.argv, s.status = map[string][]string{}, map[string]string{}
+ }
+ s.argv[unit], s.status[unit] = argv, status
+ // A probe unit writes its environment (its env -i pairs) to the file
+ // its shell command names, as the real one does.
+ if n := len(argv); n >= 2 && strings.Contains(argv[n-2], "env > ") {
+ var env []string
+ for _, a := range argv[2:] {
+ if strings.Contains(a, "=") && !strings.HasPrefix(a, "/") {
+ env = append(env, a)
+ }
+ }
+ os.WriteFile(argv[n-1], []byte(strings.Join(env, "\n")+"\n"), 0o600)
+ }
return nil
}
func (s *fakeSystemd) State(u string) string {
@@ -305,6 +364,9 @@ func (s *fakeSystemd) Stop(u string) error {
defer s.mu.Unlock()
s.stopped = append(s.stopped, u)
s.states[u] = "done"
+ if st := s.status[u]; st != "" {
+ os.WriteFile(st, []byte("signal:TERM\n"), 0o600)
+ }
return nil
}
func (s *fakeSystemd) List(prefix string) ([]string, error) {
@@ -329,15 +391,16 @@ type rig struct {
systemd *fakeSystemd
deps Deps
out bytes.Buffer
+ ctx context.Context
}
func newRig(t *testing.T, lines ...string) *rig {
t.Helper()
- r := &rig{t: t, dir: t.TempDir(), clock: &fakeClock{now: t0}}
+ r := &rig{t: t, dir: t.TempDir(), clock: &fakeClock{now: t0}, ctx: context.Background()}
r.cloud = newCloud(r.clock)
r.opener = &fakeOpener{cloud: r.cloud}
r.systemd = &fakeSystemd{states: map[string]string{}}
- r.deps = Deps{Opener: r.opener, Clock: r.clock, Systemd: r.systemd, Stdout: &r.out, Stderr: &r.out,
+ r.deps = Deps{Opener: r.opener, Clock: r.clock, Systemd: r.systemd, Stdout: &r.out, Stderr: &r.out, noSync: true,
Controller: func(ControllerArgs) (ControllerClient, error) {
t.Error("the controller was dialled")
return nil, errors.New("no controller in this test")
@@ -362,7 +425,7 @@ func (r *rig) journal(lines ...string) {
// ops runs one invocation with the global flags.
func (r *rig) ops(args ...string) int {
r.out.Reset()
- return Main(context.Background(), append([]string{"-dir", r.dir, "-run", "r1", "-profile", "p", "-account", ProdAccount, "-region", testRegion}, args...), r.deps)
+ return Main(r.ctx, append([]string{"-dir", r.dir, "-run", "r1", "-profile", "p", "-account", ProdAccount, "-region", testRegion}, args...), r.deps)
}
func (r *rig) ledger() *Ledger {
diff --git a/internal/hostedops/fix1_test.go b/internal/hostedops/fix1_test.go
new file mode 100644
index 00000000..a60dfba7
--- /dev/null
+++ b/internal/hostedops/fix1_test.go
@@ -0,0 +1,692 @@
+package hostedops
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/ed25519"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedcert"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+)
+
+// Fix round 1 (t33-r1.md, task-33-fix1.md): one regression test or more per
+// finding, each written and seen failing before its fix.
+
+// runUnit runs a unit the fake systemd was asked to start, as systemd
+// would: its argv after the binary, with its unit name in the environment.
+func (r *rig) runUnit(unit string) int {
+ r.t.Helper()
+ argv := r.systemd.argv[unit]
+ i := slices.Index(argv, "OPS")
+ if i < 0 {
+ r.t.Fatalf("unit %s does not run ops: %v", unit, argv)
+ }
+ r.t.Setenv("EQUIPO_HOSTED_OPS_UNIT", unit)
+ defer os.Unsetenv("EQUIPO_HOSTED_OPS_UNIT")
+ r.out.Reset()
+ return Main(r.ctx, argv[i+1:], r.deps)
+}
+
+// F1: a background wait starts a journalled watchdog unit; at the deadline
+// it runs safe-stop with no further operator command.
+func TestWaitHumanWatchdogStopsAtDeadline(t *testing.T) {
+ r := newRig(t)
+ r.deps.Self = "OPS"
+ r.want(0, "wait-human", "sns-confirmed", "--max", "24h", "--background")
+ unit := "hprod-r1-wait-sns-confirmed.service"
+ if !slices.Contains(r.systemd.started, unit) || !r.has("UNIT", unit) {
+ t.Fatalf("no watchdog unit started and journalled: %v", r.systemd.started)
+ }
+ r.clock.Sleep(context.Background(), 25*time.Hour)
+ if code := r.runUnit(unit); code != ExitStop {
+ t.Fatalf("the watchdog past its deadline exited %d, want 99:\n%s", code, r.out.String())
+ }
+ if !r.has("SAFE-STOP", "start") || !r.has("WAIT-EXPIRED", "sns-confirmed") {
+ t.Fatal("the watchdog did not run safe-stop at the deadline")
+ }
+}
+
+// F1: --done cancels the watchdog: its unit is stopped by name, and a
+// watchdog that runs anyway finds the wait done and stops nothing.
+func TestWaitHumanDoneCancelsWatchdog(t *testing.T) {
+ r := newRig(t)
+ r.deps.Self = "OPS"
+ r.want(0, "wait-human", "alert-received", "--max", "1h", "--background")
+ r.want(0, "wait-human", "alert-received", "--done")
+ unit := "hprod-r1-wait-alert-received.service"
+ if !slices.Contains(r.systemd.stopped, unit) {
+ t.Fatalf("--done did not stop the watchdog: %v", r.systemd.stopped)
+ }
+ r.clock.Sleep(context.Background(), 2*time.Hour)
+ if code := r.runUnit(unit); code != 0 || r.has("SAFE-STOP", "start") {
+ t.Fatalf("a watchdog after --done exited %d and safe-stop ran %t", code, r.has("SAFE-STOP", "start"))
+ }
+}
+
+// F1: unit wait routes a failed unit and an expired bound into safe-stop
+// (99), and waits through to the bound rather than returning early.
+func TestUnitWaitFailureRunsSafeStop(t *testing.T) {
+ r := newRig(t, "UNIT hprod-r1-4.3.service")
+ os.MkdirAll(filepath.Join(r.dir, "units"), 0o700)
+ os.WriteFile(filepath.Join(r.dir, "units", "4.3.start"), []byte(fmt.Sprint(t0.Unix())+"\n"), 0o600)
+ os.WriteFile(filepath.Join(r.dir, "units", "4.3.status"), []byte("1\n"), 0o600)
+ r.want(ExitStop, "unit", "wait", "4.3", "--max", "50m")
+ if !r.has("SAFE-STOP", "start") {
+ t.Fatal("a failed required unit did not reach safe-stop")
+ }
+ r = newRig(t, "UNIT hprod-r1-5.2.service")
+ os.MkdirAll(filepath.Join(r.dir, "units"), 0o700)
+ os.WriteFile(filepath.Join(r.dir, "units", "5.2.start"), []byte(fmt.Sprint(t0.Unix())+"\n"), 0o600)
+ r.systemd.states["hprod-r1-5.2.service"] = "running"
+ r.want(ExitStop, "unit", "wait", "5.2", "--max", "20m")
+ if !slices.Contains(r.systemd.stopped, "hprod-r1-5.2.service") || !r.has("SAFE-STOP", "start") || r.clock.Now().Before(t0.Add(20*time.Minute)) {
+ t.Fatal("an expired unit was not waited for, stopped and followed by safe-stop")
+ }
+}
+
+// F2: a cancelled invocation still completes its safe stop, under its own
+// context.
+func TestSafeStopSurvivesCancellation(t *testing.T) {
+ r := settleRig(t, nil, "VM microvm-a source=controller")
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ r.ctx = ctx
+ r.deps.Exec = func(ctxT, []string, []string, wT, wT) int { return 99 }
+ r.want(ExitStop, "block", "6.2", "--", "x")
+ if !r.has("SETTLED", "repeat=done") {
+ t.Fatalf("safe-stop did not finish settling after the cancellation:\n%s", r.out.String())
+ }
+}
+
+// F2: safe-stop never stops the unit it runs in; it stops the others.
+func TestSafeStopSparesItsOwnUnit(t *testing.T) {
+ r := newRig(t, "UNIT hprod-r1-wait-sns.service", "UNIT hprod-r1-4.3.service")
+ r.systemd.states["hprod-r1-wait-sns.service"] = "running"
+ r.systemd.states["hprod-r1-4.3.service"] = "running"
+ t.Setenv("EQUIPO_HOSTED_OPS_UNIT", "hprod-r1-wait-sns.service")
+ r.want(0, "safe-stop")
+ if slices.Contains(r.systemd.stopped, "hprod-r1-wait-sns.service") || !slices.Contains(r.systemd.stopped, "hprod-r1-4.3.service") {
+ t.Fatalf("stopped %v; want the other unit and never its own", r.systemd.stopped)
+ }
+}
+
+// F3: each tf intent carries the creation identity (Name tag, run, parent),
+// and reconciliation looks resources up by it.
+func TestTfIntentCarriesIdentity(t *testing.T) {
+ r, fake := tfRig(t)
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"resource_changes":[
+{"address":"module.network.aws_subnet.vm","type":"aws_subnet","change":{"actions":["create"],"after":{"vpc_id":"vpc-0parent","tags":{"Name":"equipo-hosted-vm"}}}}]}`), 0o600)
+ os.WriteFile(filepath.Join(fake, "fail-apply"), nil, 0o600)
+ r.want(ExitStop, "tf", "network", "network")
+ l := r.ledger()
+ in := l.Open("tf")
+ if len(in) != 1 || in[0].Attr("nametag") != "equipo-hosted-vm" || in[0].Attr("parent") != "vpc-0parent" || in[0].Attr("run") != "r1" {
+ t.Fatalf("the intent carries no identity: %+v", in)
+ }
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
+ var keys []LookupKey
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ keys = append(keys, k)
+ return LookupResult{Definitive: true}, nil
+ }
+ r.want(0, "tf", "reconcile", "network")
+ if len(keys) != 1 || keys[0].NameTag != "equipo-hosted-vm" || keys[0].Parent != "vpc-0parent" || keys[0].Run != "r1" {
+ t.Fatalf("the lookup did not use the identity: %+v", keys)
+ }
+ // Two matches by identity cannot be told apart: unresolved.
+ r, _ = tfRig(t, "INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc nametag=equipo-hosted-vm run=r1")
+ os.WriteFile(filepath.Join(os.Getenv("FAKE_TOFU"), "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
+ r.cloud.lookup = func(LookupKey) (LookupResult, error) {
+ return LookupResult{IDs: []string{"vpc-1", "vpc-2"}, Definitive: true}, nil
+ }
+ r.want(ExitStop, "tf", "reconcile", "network")
+}
+
+// F4: verify-gone cannot pass a recorded resource it cannot read, unless a
+// declared parent's verified deletion covers it.
+func TestVerifyGoneUnsupportedStops(t *testing.T) {
+ r := newRig(t, "REC tf config/module.config.aws_cloudwatch_log_group.image_build id=/aws/lambda-microvms/equipo-hosted-image-build type=aws_cloudwatch_log_group source=state",
+ "REC tf config/module.config.aws_widget.x id=w-1 type=aws_widget source=state")
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_cloudwatch_log_group" {
+ return LookupResult{IDs: []string{k.ID}, Definitive: true}, nil
+ }
+ return LookupResult{}, nil // no direct read for this type
+ }
+ r.want(ExitStop, "verify-gone")
+ r = newRig(t, "REC tf config/module.config.aws_widget.x id=w-1 type=aws_widget source=state")
+ r.cloud.lookup = func(LookupKey) (LookupResult, error) { return LookupResult{}, nil }
+ r.want(ExitStop, "verify-gone")
+ r = newRig(t, "REC tf config/module.config.aws_iam_role.image_build id=arn:aws:iam::149757027610:role/equipo-hosted-image-build type=aws_iam_role source=state",
+ "REC tf config/module.config.aws_iam_role_policy.image_build id=equipo-hosted-image-build:image-build type=aws_iam_role_policy source=state parent=equipo-hosted-image-build")
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_iam_role" {
+ return LookupResult{Definitive: true}, nil
+ }
+ return LookupResult{}, nil
+ }
+ r.want(0, "verify-gone") // the role's verified deletion covers its inline policy
+}
+
+// F5: a controller only in an open intent is found by identity and fenced;
+// a failed attach does not skip the host stop.
+func TestFenceFindsUnrecordedController(t *testing.T) {
+ r := newRig(t, "INTENT tf services/module.controller.aws_iam_policy.deny_launches - type=aws_iam_policy name=equipo-hosted-deny-launches run=r1",
+ "INTENT tf services/module.controller.aws_instance.controller - type=aws_instance nametag=equipo-hosted-controller run=r1")
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_instance" && k.NameTag == "equipo-hosted-controller" {
+ return LookupResult{IDs: []string{"i-0found"}, Definitive: true}, nil
+ }
+ return LookupResult{Definitive: true}, nil
+ }
+ r.want(0, "fence")
+ if r.cloud.index("AttachRolePolicy equipo-hosted-controller") < 0 || r.cloud.index("StopInstance i-0found") < 0 {
+ t.Fatalf("the unrecorded controller was not fenced: %v", r.cloud.log())
+ }
+ r = newRig(t, ctlPol, ctlVM)
+ r.cloud.attachErr = errors.New("AccessDenied")
+ r.want(ExitStop, "fence")
+ if r.cloud.index("StopInstance i-0ctl") < 0 {
+ t.Fatal("a failed attach skipped the host stop")
+ }
+}
+
+// F5: when safe-stop's reconciliation finds a host it did not know at
+// fence time, it fences again.
+func TestSafeStopFencesAgainAfterReconcile(t *testing.T) {
+ r, fake := tfRig(t, "INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc nametag=equipo-hosted-vm run=r1", "TF-APPLY network start network")
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{"child_modules":[{"resources":[
+{"address":"module.network.aws_vpc.vm","type":"aws_vpc","values":{"id":"vpc-0vm"}}]}]}}}`), 0o600)
+ r.journal("INTENT tf services/module.controller.aws_instance.controller - type=aws_instance nametag=equipo-hosted-controller run=r1")
+ looked := 0
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_instance" {
+ looked++
+ if looked > 1 { // not there at the first fence; there after reconciliation
+ return LookupResult{IDs: []string{"i-0late"}, Definitive: true}, nil
+ }
+ return LookupResult{}, nil
+ }
+ return LookupResult{Definitive: true}, nil
+ }
+ r.ops("safe-stop")
+ if r.cloud.index("StopInstance i-0late") < 0 {
+ t.Fatalf("safe-stop did not fence the host reconciliation found: %v", r.cloud.log())
+ }
+}
+
+// F7: MFA enforcement is read from the trust policy's statements.
+func TestMFACheckParsesTrust(t *testing.T) {
+ allow := func(cond string) string {
+ c := ""
+ if cond != "" {
+ c = `,"Condition":` + cond
+ }
+ return `{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"sts:AssumeRole"` + c + `}`
+ }
+ for _, c := range []struct {
+ name, doc string
+ code int
+ }{
+ {"enforced", `{"Statement":[` + allow(`{"Bool":{"aws:MultiFactorAuthPresent":"true"}}`) + `]}`, 0},
+ {"enforced, list value", `{"Statement":` + allow(`{"Bool":{"aws:MultiFactorAuthPresent":["true"]}}`) + `}`, 0},
+ {"false", `{"Statement":[` + allow(`{"Bool":{"aws:MultiFactorAuthPresent":"false"}}`) + `]}`, ExitStop},
+ {"one unconditional allow beside", `{"Statement":[` + allow(`{"Bool":{"aws:MultiFactorAuthPresent":"true"}}`) + `,` + allow("") + `]}`, ExitStop},
+ {"if exists", `{"Statement":[` + allow(`{"BoolIfExists":{"aws:MultiFactorAuthPresent":"true"}}`) + `]}`, ExitStop},
+ {"not json", `aws:MultiFactorAuthPresent`, ExitStop},
+ {"no allow", `{"Statement":[]}`, ExitStop},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newRig(t)
+ r.cloud.trust = c.doc
+ r.want(c.code, "mfa-check")
+ })
+ }
+}
+
+// F8: the connector's subnet, security group and role are journalled before
+// the create; delete never claims success without interface proof.
+func TestConnectorIdentityBeforeCreate(t *testing.T) {
+ r := newRig(t)
+ r.cloud.getConn = func(int, string) (Connector, error) { return Connector{}, errors.New("timeout") }
+ r.ops("connector", "create", "--subnet", "subnet-0vm", "--security-group", "sg-0vm", "--role", "arn:aws:iam::149757027610:role/equipo-hosted-connector-operator", "--max", "1m")
+ in := r.ledger().Intents
+ if len(in) != 1 || in[0].Attr("subnet") != "subnet-0vm" || in[0].Attr("sg") != "sg-0vm" || !strings.HasSuffix(in[0].Attr("role"), "connector-operator") {
+ t.Fatalf("the connector intent lacks its subnet, group or role: %+v", in)
+ }
+ const arn = "arn:aws:lambda:eu-west-1:149757027610:network-connector:nc-1"
+ r = newRig(t, "INTENT connector equipo-hosted-prod-r1-egress t1", "REC connector "+arn+" name=equipo-hosted-prod-r1-egress")
+ r.cloud.getConn = func(int, string) (Connector, error) { return Connector{}, ErrNotFound }
+ r.want(ExitStop, "connector", "delete")
+ if r.has("DELETED", "connector") {
+ t.Fatal("a delete without interface proof was recorded as done")
+ }
+}
+
+// F9: the outputs ops reads are the ones the network roots declare.
+func TestOutputsMatchRoots(t *testing.T) {
+ for _, env := range []string{"prod", "dev"} {
+ b, err := os.ReadFile(filepath.Join("..", "..", "infra", "hosted", "envs", env, "network", "main.tf"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ declared := map[string]bool{}
+ for _, m := range regexp.MustCompile(`(?m)^output "([a-z_]+)"`).FindAllStringSubmatch(string(b), -1) {
+ declared[m[1]] = true
+ }
+ for _, name := range append(append([]string{}, networkOutputs...), networkCheckOutputs...) {
+ if !declared[name] {
+ t.Errorf("envs/%s/network has no output %q, which ops reads", env, name)
+ }
+ }
+ }
+}
+
+// release writes a release manifest at REPO/release/<tag>.json.
+func release(t *testing.T, r *rig, extra map[string]any) {
+ m := map[string]any{"URL": "https://example.invalid/hosted-0.1.0", "IMAGE_DIGEST": "sha256:" + strings.Repeat("a", 64),
+ "Artifacts": []map[string]any{{"Name": "equipo-hosted-controller-linux-arm64", "SHA256": strings.Repeat("1", 64)},
+ {"Name": "equipo-hosted-proxy-linux-arm64", "SHA256": strings.Repeat("2", 64)}},
+ "Litestream": map[string]any{"Assets": map[string]any{"linux/arm64": map[string]any{"Name": "litestream-arm64.tar.gz", "SHA256": strings.Repeat("3", 64)}}}}
+ for k, v := range extra {
+ m[k] = v
+ }
+ b, _ := json.Marshal(m)
+ os.MkdirAll(filepath.Join(r.dir, "repo", "release"), 0o700)
+ os.WriteFile(filepath.Join(r.dir, "repo", "release", "hosted-0.1.0.json"), b, 0o600)
+}
+
+// F10: tfvars takes the hosts' AMI from the release manifest and fails
+// without it.
+func TestTfvarsAMIFromRelease(t *testing.T) {
+ r := newRig(t)
+ release(t, r, nil)
+ r.want(ExitFail, "tfvars", "--release", "hosted-0.1.0")
+ r = newRig(t)
+ release(t, r, map[string]any{"HostAMI": map[string]string{"eu-west-1": "ami-0123456789abcdef0"}})
+ r.want(0, "tfvars", "--release", "hosted-0.1.0")
+ b, _ := os.ReadFile(filepath.Join(r.dir, "prod.tfvars"))
+ if !strings.Contains(string(b), `ami_id = "ami-0123456789abcdef0"`) {
+ t.Fatalf("no ami_id:\n%s", b)
+ }
+}
+
+func litestreamTarball(t *testing.T, dir, name string) (string, string) {
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ body := []byte("#!/bin/sh\necho litestream\n")
+ tw.WriteHeader(&tar.Header{Name: "litestream", Mode: 0o755, Size: int64(len(body))})
+ tw.Write(body)
+ tw.Close()
+ gz.Close()
+ p := filepath.Join(dir, name)
+ os.WriteFile(p, buf.Bytes(), 0o600)
+ s := sha256.Sum256(buf.Bytes())
+ return p, hex.EncodeToString(s[:])
+}
+
+// F10: litestream-install takes the release's pinned tarball, checks its
+// digest against the release manifest and installs the binary.
+func TestLitestreamInstall(t *testing.T) {
+ r := newRig(t, "NOTE release hosted-0.1.0")
+ plat := "linux/" + runtime.GOARCH
+ tb, sum := litestreamTarball(t, t.TempDir(), "litestream-0.5.18-linux.tar.gz")
+ release(t, r, map[string]any{"Litestream": map[string]any{"Assets": map[string]any{plat: map[string]any{"Name": filepath.Base(tb), "SHA256": sum}}}})
+ r.want(0, "litestream-install", "--file", tb)
+ if st, err := os.Stat(filepath.Join(r.dir, "bin", "litestream")); err != nil || st.Mode().Perm()&0o100 == 0 {
+ t.Fatalf("no executable litestream installed: %v", err)
+ }
+ r = newRig(t, "NOTE release hosted-0.1.0")
+ release(t, r, map[string]any{"Litestream": map[string]any{"Assets": map[string]any{plat: map[string]any{"Name": filepath.Base(tb), "SHA256": strings.Repeat("0", 64)}}}})
+ r.want(ExitStop, "litestream-install", "--file", tb)
+}
+
+// F11: keys upload needs the certification key's ID, and a certificate
+// signed under that ID verifies against the uploaded cert-keys.json.
+func TestCertKeyIDRequiredAndVerifies(t *testing.T) {
+ pub, priv, _ := ed25519.GenerateKey(nil)
+ setup := func() *rig {
+ r := newRig(t, "NOTE cert-pub "+base64.StdEncoding.EncodeToString(pub))
+ keys := filepath.Join(r.dir, "keys")
+ os.MkdirAll(keys, 0o700)
+ opPub, _, _ := ed25519.GenerateKey(nil)
+ os.WriteFile(filepath.Join(keys, "operator.pub"), []byte(base64.StdEncoding.EncodeToString(opPub)), 0o644)
+ for _, u := range keyUploads {
+ os.WriteFile(filepath.Join(keys, u[1]), []byte("secret"), 0o600)
+ }
+ return r
+ }
+ r := setup()
+ r.want(ExitFail, "keys", "upload", "--bucket", "equipo-hosted-config-149757027610", "--expected-owner", ProdAccount, "--keys", filepath.Join(r.dir, "keys"))
+ if r.cloud.count("PutObject") != 0 {
+ t.Fatal("keys upload ran without a certification key ID")
+ }
+ r = setup()
+ r.want(0, "keys", "upload", "--bucket", "equipo-hosted-config-149757027610", "--expected-owner", ProdAccount, "--keys", filepath.Join(r.dir, "keys"), "--cert-key-id", "paul-cert-1")
+ var kf struct {
+ Keys []struct{ ID, PublicKey string } `json:"keys"`
+ }
+ raw := r.cloud.objects["equipo-hosted-config-149757027610/controller/cert-keys.json"]
+ if err := json.Unmarshal(bytes.ReplaceAll(raw, []byte("public_key"), []byte("PublicKey")), &kf); err != nil {
+ t.Fatal(err)
+ }
+ trusted := map[string]ed25519.PublicKey{}
+ for _, k := range kf.Keys {
+ b, _ := base64.StdEncoding.DecodeString(k.PublicKey)
+ trusted[k.ID] = b
+ }
+ s := hostedcert.Snapshot{Purpose: hostedcert.Purpose, Version: hostedcert.Version, Image: isolatedjob.ImageDigest("sha256:" + strings.Repeat("a", 64)),
+ ImageVersion: "arn:aws:lambda:eu-west-1:149757027610:microvm-image:img:1", Runner: strings.Repeat("1", 64), VMInit: strings.Repeat("2", 64),
+ SandboxPolicy: strings.Repeat("3", 64), ProxyPolicy: 1, Deps: hostedcert.DepsPrimaryBundleV1, Deployment: []string{"equipo.example.com"},
+ Profile: hostedcert.ProfileVMBoundaryChecks, EvidenceID: "ev-1"}
+ if _, err := hostedcert.Verify(hostedcert.Sign(s, "paul-cert-1", priv, t0), trusted); err != nil {
+ t.Fatalf("a certificate signed as paul-cert-1 does not verify against the uploaded keys: %v", err)
+ }
+}
+
+// F12: a repeated operation resolves its own intent, and a later record
+// repairs a host's metadata.
+func TestRepeatedOperationsResolve(t *testing.T) {
+ r := newRig(t, ctlPol, ctlVM)
+ r.want(0, "fence")
+ r.want(0, "fence")
+ if open := r.ledger().Open(); len(open) != 0 {
+ t.Fatalf("a repeated fence left %d intents open", len(open))
+ }
+ r = newRig(t, "REC tf services/module.controller.aws_instance.controller id=i-0ctl type=aws_instance source=outside-state",
+ ctlVM)
+ if h := r.ledger().Hosts["i-0ctl"]; h == nil || h.Type != "t4g.small" {
+ t.Fatalf("the host record was not repaired: %+v", h)
+ }
+}
+
+func TestRepeatedObjectPutResolves(t *testing.T) {
+ r := newRig(t, "OWNER equipo-hosted-config-149757027610 149757027610")
+ f := filepath.Join(t.TempDir(), "c.json")
+ os.WriteFile(f, []byte(`{"url":"https://203.0.113.7"}`), 0o600)
+ for i := 0; i < 2; i++ {
+ r.want(0, "object", "put", "--bucket", "equipo-hosted-config-149757027610", "--key", "proxy/a/controller.json", "--file", f)
+ }
+ if open := r.ledger().Open(); len(open) != 0 {
+ t.Fatalf("a repeated upload left %d intents open: %s", len(open), open[0].Name)
+ }
+}
+
+// F13: settling one image resolves only the launch intents of that image.
+func TestSettleResolvesOnlyItsImage(t *testing.T) {
+ imageB := strings.Replace(image1, "prod-r1", "prod-r1-b", 1)
+ dA, dB := "sha256:"+strings.Repeat("a", 64), "sha256:"+strings.Repeat("b", 64)
+ r := newRig(t, "REC microvm-image "+image1, "REC microvm-image "+imageB, "IMAGE-DIGEST "+dA+" "+image1, "IMAGE-DIGEST "+dB+" "+imageB,
+ "INTENT cert-launch "+dA+" large 1 att-a", "INTENT cert-launch "+dB+" large 1 att-b", "INTENT cert-launch sha256:"+strings.Repeat("c", 64)+" large 1 att-c",
+ "SETTLED "+image1+" repeat=done")
+ open := r.ledger().Open("cert-launch")
+ var tokens []string
+ for _, in := range open {
+ tokens = append(tokens, in.Token)
+ }
+ if !slices.Equal(tokens, []string{"att-b", "att-c"}) {
+ t.Fatalf("open launch intents %v, want image B's and the unmapped one", tokens)
+ }
+}
+
+// F14: a host whose creation is unresolved stops admission, and a host is
+// charged from its intent.
+func TestEstimateStopsOnUnresolvedHost(t *testing.T) {
+ r := newRig(t, "INTENT tf services/module.controller.aws_instance.controller - type=aws_instance nametag=equipo-hosted-controller run=r1")
+ r.want(ExitStop, "estimate")
+ r = newRig(t)
+ f, _ := os.OpenFile(filepath.Join(r.dir, JournalFile), os.O_APPEND|os.O_WRONLY, 0o600)
+ fmt.Fprintf(f, "%s\tINTENT tf services/module.controller.aws_instance.controller - type=aws_instance\n", t0.Add(-5*time.Hour).Format(stamp))
+ fmt.Fprintf(f, "%s\t%s\n", t0.Format(stamp), ctlVM)
+ f.Close()
+ e, err := Compute(r.ledger(), t0.Add(time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, l := range e.Lines {
+ if strings.HasPrefix(l.What, "host i-0ctl") && l.Count < 5 {
+ t.Fatalf("the host is charged %v hours, want at least the 5 since its intent", l.Count)
+ }
+ }
+}
+
+// F15: a resource reconciliation found outside state is adopted by an
+// import block and removed by the normal destroy path, then verified gone.
+func TestAdoptedResourceTornDown(t *testing.T) {
+ r, fake := tfRig(t, "INTENT tf network/module.network.aws_vpc.vm - type=aws_vpc nametag=equipo-hosted-vm run=r1", "TF-APPLY network start network")
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600)
+ gone := false
+ r.cloud.lookup = func(k LookupKey) (LookupResult, error) {
+ if k.Type == "aws_vpc" && !gone {
+ return LookupResult{IDs: []string{"vpc-0orphan"}, Definitive: true}, nil
+ }
+ return LookupResult{Definitive: true}, nil
+ }
+ r.want(0, "tf", "reconcile", "network")
+ imports := filepath.Join(r.dir, "repo", "infra", "hosted", "envs", "prod", "network", "ops_imports_r1.tf")
+ b, err := os.ReadFile(imports)
+ if err != nil || !strings.Contains(string(b), `to = module.network.aws_vpc.vm`) || !strings.Contains(string(b), `id = "vpc-0orphan"`) {
+ t.Fatalf("no import block written: %v\n%s", err, b)
+ }
+ os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"resource_changes":[{"address":"module.network.aws_vpc.vm","type":"aws_vpc","change":{"actions":["delete"],"before":{"id":"vpc-0orphan"}}}]}`), 0o600)
+ os.WriteFile(filepath.Join(fake, "state.json"), []byte(`{"values":{"root_module":{}}}`), 0o600)
+ r.want(0, "tf", "network", "destroy-network")
+ log := calls(t, fake)
+ if i, j := strings.Index(log, " import "), strings.Index(log, " -destroy"); i < 0 || j < i || !strings.Contains(log, "module.network.aws_vpc.vm vpc-0orphan") {
+ t.Fatalf("the adoption was not imported before the destroy plan:\n%s", log)
+ }
+ if _, err := os.Stat(imports); err == nil {
+ t.Fatal("the import block stayed in the root after the import")
+ }
+ gone = true
+ r.want(0, "verify-gone")
+}
+
+// F16: with a controller recorded and no instance notes, safe-stop cannot
+// prove the instance flag is off: unresolved, 99.
+func TestSafeStopInstanceFlagUnresolved(t *testing.T) {
+ r := newRig(t, ctlVM)
+ r.want(ExitStop, "safe-stop")
+ if !r.has("SAFE-STOP", "S.1") || r.has("SKIP", "7.1 did not run") {
+ t.Fatal("missing shutdown information was not an unresolved condition")
+ }
+ r = newRig(t, ctlVM, "NOTE instance-app equipo", "NOTE instance-account acme")
+ carlos := filepath.Join(t.TempDir(), "carlos")
+ os.WriteFile(carlos, []byte("#!/bin/sh\necho \"$@\" > \"$0.args\"\n"), 0o755)
+ r.deps.Carlos = carlos
+ r.want(0, "safe-stop")
+ if b, _ := os.ReadFile(carlos + ".args"); !strings.Contains(string(b), "env unset --app equipo --account acme EQUIPO_HOSTED_RUNNERS") {
+ t.Fatalf("carlos was not asked to unset the flag: %q", b)
+ }
+}
+
+// F18: the trail evidence is one Data event naming the image, in the run's
+// time.
+func TestTrailEventSameRecord(t *testing.T) {
+ key := func(n int) string {
+ return fmt.Sprintf("equipo-hosted-trail-149757027610/AWSLogs/149757027610/CloudTrail/eu-west-1/%s/log%d.json", t0.Format("2006/01/02"), n)
+ }
+ at := t0.Add(30 * time.Minute).Format(time.RFC3339)
+ for _, c := range []struct {
+ name, body string
+ seen bool
+ }{
+ {"mixed records", `{"Records":[{"eventCategory":"Data","eventTime":"` + at + `","resources":[{"ARN":"arn:aws:s3:::other"}]},` +
+ `{"eventCategory":"Management","eventTime":"` + at + `","resources":[{"ARN":"` + image1 + `"}]}]}`, false},
+ {"spaced JSON", `{ "Records" : [ { "eventCategory" : "Data" , "eventTime" : "` + at + `" , "resources" : [ { "ARN" : "` + image1 + `:3" } ] } ] }`, true},
+ {"before the run", `{"Records":[{"eventCategory":"Data","eventTime":"2026-11-01T00:00:00Z","resources":[{"ARN":"` + image1 + `"}]}]}`, false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newRig(t, "REC microvm-image "+image1)
+ r.cloud.objects = map[string][]byte{key(1): []byte(c.body)}
+ r.clock.Sleep(context.Background(), time.Hour)
+ r.want(0, "fact", "trail-event")
+ if seen := strings.HasPrefix(r.ledger().Notes["trail-event"], "seen"); seen != c.seen {
+ t.Fatalf("trail-event seen %t, want %t", seen, c.seen)
+ }
+ })
+ }
+}
+
+// Extra: vms scan takes --max, and retries an incomplete scan within it.
+func TestVMsScanMax(t *testing.T) {
+ r := newRig(t, "REC microvm-image "+image1)
+ r.cloud.listVMs = func(n int, _ string) ([]VM, error) {
+ if n == 1 {
+ return nil, errors.New("throttled")
+ }
+ return nil, nil
+ }
+ r.want(0, "vms", "scan", "--image", image1, "--max", "1m")
+ r = newRig(t, "REC microvm-image "+image1)
+ r.cloud.listVMs = func(int, string) ([]VM, error) { return nil, errors.New("throttled") }
+ r.want(ExitStop, "vms", "scan", "--image", image1, "--max", "1m")
+}
+
+// Extra: the probe unit (Task 17b's unit_probe, ported).
+func TestUnitProbe(t *testing.T) {
+ r := newRig(t)
+ r.want(0, "unit", "probe")
+ if !slices.Contains(r.systemd.started, "hprod-r1-probe.service") || !slices.Contains(r.systemd.stopped, "hprod-r1-probe.service") {
+ t.Fatalf("the probe unit was not started and stopped: %v %v", r.systemd.started, r.systemd.stopped)
+ }
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "leak")
+ UnitEnv = append(UnitEnv, "AWS_SECRET_ACCESS_KEY")
+ defer func() { UnitEnv = UnitEnv[:len(UnitEnv)-1] }()
+ r = newRig(t)
+ r.want(ExitStop, "unit", "probe")
+}
+
+// Extra: every ops invocation in the account plan passes the real flag
+// parsers; a malformed one is reported as a usage error.
+func TestPlanInvocationsParseFlags(t *testing.T) {
+ b, err := os.ReadFile(filepath.Join("..", "..", "docs", "superpowers", "plans", "2026-11-30-hosted-prod-account-plan.md"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Chdir(t.TempDir()) // the plan writes some files by relative path (9.4's bundle)
+ invs := planInvocations(string(b))
+ if len(invs) < 40 {
+ t.Fatalf("only %d invocations found", len(invs))
+ }
+ for _, inv := range invs {
+ r := newRig(t, "REC microvm-image "+image1)
+ r.deps.Exec = func(ctxT, []string, []string, wT, wT) int { return 0 }
+ r.ops(inv...)
+ if strings.Contains(r.out.String(), "usage:") {
+ t.Errorf("ops %s: %s", strings.Join(inv, " "), r.out.String())
+ }
+ }
+ r := newRig(t, "REC microvm-image "+image1)
+ r.ops("vms", "settle", "--image", image1, "--bogus")
+ if !strings.Contains(r.out.String(), "usage:") {
+ t.Fatalf("a malformed invocation is not a usage error: %s", r.out.String())
+ }
+}
+
+// planInvocations extracts every ops invocation from the plan's code and
+// inline spans, with placeholders filled.
+func planInvocations(plan string) [][]string {
+ fill := strings.NewReplacer("$P", "p", "$IMAGE_DIGEST", "sha256:"+strings.Repeat("a", 64), "$RUN", "r1", "$K", "p/keys")
+ var out [][]string
+ add := func(s string) {
+ s = regexp.MustCompile(`--max <[^>]*>`).ReplaceAllString(s, "--max 1m")
+ s = regexp.MustCompile(`\$\([^)]*\)`).ReplaceAllString(s, "x")
+ s = regexp.MustCompile(`<[^>]*>`).ReplaceAllString(s, "x")
+ f := shellWords(fill.Replace(s))
+ if len(f) > 1 && f[0] == "ops" {
+ out = append(out, f[1:])
+ }
+ }
+ for _, m := range regexp.MustCompile("`(ops [^`]+)`").FindAllStringSubmatch(plan, -1) {
+ s := m[1]
+ if strings.ContainsAny(s, "|") || regexp.MustCompile(`\b(ROOT|PHASE|ID|NAME|CMD)\b`).MatchString(s) {
+ continue // a pattern, not an invocation
+ }
+ bare := len(strings.Fields(s)) <= 3 && !strings.Contains(s, "<")
+ for _, f := range strings.Fields(s) {
+ bare = bare && !strings.HasPrefix(f, "-")
+ }
+ if bare {
+ continue // a command named in prose
+ }
+ add(s)
+ }
+ for _, block := range regexp.MustCompile("(?s)```sh\n(.*?)```").FindAllStringSubmatch(plan, -1) {
+ for _, line := range strings.Split(strings.ReplaceAll(block[1], "\\\n", " "), "\n") {
+ if i := strings.Index(line, "ops "); i >= 0 && (i == 0 || line[i-1] == ' ' || line[i-1] == ';') && !strings.Contains(line, "ops()") {
+ add(strings.SplitN(line[i:], "#", 2)[0])
+ }
+ }
+ }
+ return out
+}
+
+// shellWords splits like sh for the plan's simple quoting.
+func shellWords(s string) []string {
+ var out []string
+ var cur strings.Builder
+ in, q := false, byte(0)
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ switch {
+ case q != 0 && c == q:
+ q = 0
+ case q != 0:
+ cur.WriteByte(c)
+ case c == '\'' || c == '"':
+ q, in = c, true
+ case c == ' ' || c == '\t' || c == '\n':
+ if in {
+ out = append(out, cur.String())
+ cur.Reset()
+ in = false
+ }
+ default:
+ cur.WriteByte(c)
+ in = true
+ }
+ }
+ if in {
+ out = append(out, cur.String())
+ }
+ return out
+}
+
+// F4: every type the stacks create is read directly or covered by a
+// declared parent.
+func TestEveryStackTypeVerifiable(t *testing.T) {
+ b, err := os.ReadFile(filepath.Join("..", "..", "infra", "hosted", "scripts", "phases.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ types := map[string]bool{}
+ for _, m := range regexp.MustCompile(`"(?:module\.[a-z_]+\.)?(aws_[a-z0-9_]+)\.[a-z0-9_]+"`).FindAllStringSubmatch(string(b), -1) {
+ types[m[1]] = true
+ }
+ if len(types) < 20 {
+ t.Fatalf("only %d types read from phases.json", len(types))
+ }
+ for typ := range types {
+ if !slices.Contains(DirectReadTypes, typ) && coveredBy[typ] == "" {
+ t.Errorf("%s has neither a direct read nor a declared parent", typ)
+ }
+ }
+}
diff --git a/internal/hostedops/ledger.go b/internal/hostedops/ledger.go
index 9aec3be7..54dc52a6 100644
--- a/internal/hostedops/ledger.go
+++ b/internal/hostedops/ledger.go
@@ -65,6 +65,8 @@ func (e Entry) Attr(key string) string {
type Journal struct {
Path string
Now func() time.Time
+ // noSync skips the fsync after each line: tests only (Deps.noSync).
+ noSync bool
}
const stamp = "2006-01-02T15:04:05.000Z"
@@ -82,7 +84,7 @@ func (j *Journal) Write(verb, text string) error {
line += " " + text
}
_, err = f.WriteString(line + "\n")
- if err == nil {
+ if err == nil && !j.noSync {
err = f.Sync()
}
if cerr := f.Close(); err == nil {
@@ -168,7 +170,8 @@ type Ledger struct {
Waits map[string]Wait
Settled map[string]time.Time // image ARN -> last settlement with its repeat
Targets []string
- TFApplying map[string]bool // roots whose last apply did not finish
+ TFApplying map[string]bool // roots whose last apply did not finish
+ ImageOf map[string]string // image digest -> image ARN (IMAGE-DIGEST)
}
// Wait is a wait-human clock.
@@ -186,7 +189,7 @@ func LoadLedger(j *Journal) (*Ledger, error) {
}
l := &Ledger{Entries: es, Deleted: map[string]bool{}, Notes: map[string]string{}, VMs: map[string]*VMSeen{},
Hosts: map[string]*Host{}, Owned: map[string]bool{}, Waits: map[string]Wait{}, Settled: map[string]time.Time{},
- TFApplying: map[string]bool{}}
+ TFApplying: map[string]bool{}, ImageOf: map[string]string{}}
for _, e := range es {
l.apply(e)
}
@@ -211,18 +214,46 @@ func (l *Ledger) apply(e Entry) {
l.Intents = append(l.Intents, in)
case "REC":
r := Rec{Entry: e, Kind: e.Field(0), Value: e.Field(1), Name: e.Attr("name")}
- if l.hasRec(r.Kind, r.Value) {
- return // the same record twice (img publish, then ops ledger rec) is one
+ // Three things, kept apart (fix round 1, F12): the operation's own
+ // intent is resolved; the resource is listed once; a later record of
+ // the same resource updates its metadata. A repeated record resolves
+ // only an intent that names it, never the oldest of its kind (img
+ // publish's REC then ops ledger rec of the same ARN is one record).
+ i := l.recIndex(r.Kind, r.Value)
+ in := l.resolve(r.Kind, r.Name, r.Value, "confirmed", i < 0)
+ if i >= 0 {
+ l.Recs[i] = mergeRec(l.Recs[i], r)
+ r = l.Recs[i]
+ } else {
+ l.Recs = append(l.Recs, r)
}
- l.Recs = append(l.Recs, r)
- l.resolve(r.Kind, r.Name, r.Value, "confirmed")
- if r.Kind == "tf" {
- if t := e.Attr("type"); t == "aws_instance" {
- l.Hosts[e.Attr("id")] = &Host{ID: e.Attr("id"), Type: e.Attr("instance_type"), Address: r.Value, At: e.At}
+ if r.Kind == "tf" && r.Attr("type") == "aws_instance" && r.Attr("id") != "" {
+ // A host is charged from its intent (or its first record) on.
+ at := e.At
+ if in != nil && in.At.Before(at) {
+ at = in.At
+ }
+ for _, o := range l.Intents {
+ if o.Kind == "tf" && o.Name == r.Value && o.At.Before(at) {
+ at = o.At
+ }
+ }
+ h := l.Hosts[r.Attr("id")]
+ if h == nil {
+ h = &Host{ID: r.Attr("id"), Address: r.Value, At: at}
+ l.Hosts[h.ID] = h
+ }
+ if t := r.Attr("instance_type"); t != "" {
+ h.Type = t
+ }
+ if at.Before(h.At) {
+ h.At = at
}
}
case "NOTCREATED":
- l.resolve(e.Field(0), e.Field(1), "", "absent")
+ l.resolve(e.Field(0), e.Field(1), "", "absent", true)
+ case "IMAGE-DIGEST":
+ l.ImageOf[e.Field(0)] = e.Field(1)
case "DELETED":
l.Deleted[e.Field(0)+" "+e.Field(1)] = true
if e.Field(0) == "host" {
@@ -260,8 +291,11 @@ func (l *Ledger) apply(e Entry) {
case "SETTLED":
l.Settled[e.Field(0)] = e.At
if e.Attr("repeat") == "done" {
- for _, in := range l.Intents { // no VM of the image can be live: the run's launches are settled
- if isVMIntent(in.Kind) && in.State == "open" && in.At.Before(e.At) {
+ // No VM of this image can be live, so this image's launches
+ // are settled; a launch bound to another image, or to none
+ // the ledger can name, stays open (F13).
+ for _, in := range l.Intents {
+ if isVMIntent(in.Kind) && in.State == "open" && in.At.Before(e.At) && l.intentImage(in) == e.Field(0) {
in.State, in.Value = "absent", "settled"
}
}
@@ -307,7 +341,7 @@ func (l *Ledger) hasRec(kind, value string) bool {
// resolve settles the open intent a REC or NOTCREATED answers: the one of
// that kind named name or value, else (a REC without a name) the oldest
// open one of that kind.
-func (l *Ledger) resolve(kind, name, value, state string) {
+func (l *Ledger) resolve(kind, name, value, state string, oldestToo bool) *Intent {
var pick, oldest *Intent
for _, in := range l.Intents {
if in.Kind != kind || in.State != "open" {
@@ -321,12 +355,62 @@ func (l *Ledger) resolve(kind, name, value, state string) {
oldest = in
}
}
- if pick == nil && name == "" {
+ if pick == nil && name == "" && oldestToo {
pick = oldest
}
if pick != nil {
pick.State, pick.Value = state, value
}
+ return pick
+}
+
+// intentImage is the image ARN a VM launch intent is bound to: a
+// cert-launch names its image digest (IMAGE-DIGEST maps it), a vm-launch
+// its image=ARN; "" when the ledger cannot name it.
+func (l *Ledger) intentImage(in *Intent) string {
+ if a := in.Attr("image"); strings.HasPrefix(a, "arn:") {
+ return a
+ }
+ if in.Kind == "cert-launch" {
+ return l.ImageOf[in.Name]
+ }
+ return ""
+}
+
+func (l *Ledger) recIndex(kind, value string) int {
+ for i, r := range l.Recs {
+ if r.Kind == kind && r.Value == value {
+ return i
+ }
+ }
+ return -1
+}
+
+// mergeRec is old with newer's key=value attributes laid over its own; it
+// keeps old's time (the first record).
+func mergeRec(old, newer Rec) Rec {
+ attrs := map[string]string{}
+ var keys []string
+ for _, f := range append(append([]string{}, old.Fields[2:]...), newer.Fields[2:]...) {
+ if k, v, ok := strings.Cut(f, "="); ok {
+ if _, seen := attrs[k]; !seen {
+ keys = append(keys, k)
+ }
+ if v != "" {
+ attrs[k] = v
+ }
+ }
+ }
+ fields := []string{old.Kind, old.Value}
+ for _, k := range keys {
+ fields = append(fields, k+"="+attrs[k])
+ }
+ m := old
+ m.Fields, m.Text = fields, strings.Join(fields, " ")
+ if newer.Name != "" {
+ m.Name = newer.Name
+ }
+ return m
}
// Recorded returns the REC lines of kind, oldest first.
diff --git a/internal/hostedops/ledgercmd.go b/internal/hostedops/ledgercmd.go
index 80b3781c..5e299765 100644
--- a/internal/hostedops/ledgercmd.go
+++ b/internal/hostedops/ledgercmd.go
@@ -5,6 +5,7 @@ import (
"flag"
"os"
"regexp"
+ "slices"
"strconv"
"strings"
"time"
@@ -17,7 +18,7 @@ var (
func cmdLedgerInit(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("ledger init takes no arguments")
+ return usagef("ledger init takes no arguments")
}
if err := os.MkdirAll(o.Dir, 0o700); err != nil {
return failf("ledger init: %v", err)
@@ -39,7 +40,7 @@ func cmdLedgerInit(o *Ops, args []string) error {
func cmdLedgerIntent(o *Ops, args []string) error {
if len(args) < 2 || len(args) > 3 || !kindPattern.MatchString(args[0]) {
- return failf("ledger intent KIND NAME [TOKEN]")
+ return usagef("ledger intent KIND NAME [TOKEN]")
}
for _, a := range args[1:] {
if !wordPattern.MatchString(a) {
@@ -79,7 +80,7 @@ func (o *Ops) rec(kind, value string, attrs ...string) error {
func cmdLedgerRec(o *Ops, args []string) error {
if len(args) < 2 {
- return failf("ledger rec KIND VALUE [key=value...]")
+ return usagef("ledger rec KIND VALUE [key=value...]")
}
for _, a := range args[2:] {
if !strings.Contains(a, "=") || !wordPattern.MatchString(a) {
@@ -95,14 +96,14 @@ func cmdLedgerRec(o *Ops, args []string) error {
func cmdLedgerDeleted(o *Ops, args []string) error {
if len(args) < 2 || !kindPattern.MatchString(args[0]) {
- return failf("ledger deleted KIND VALUE [HOW]")
+ return usagef("ledger deleted KIND VALUE [HOW]")
}
return o.jw("DELETED", "%s", strings.Join(args, " "))
}
func cmdLedgerNote(o *Ops, args []string) error {
if len(args) < 2 || !kindPattern.MatchString(args[0]) {
- return failf("ledger note KEY VALUE...")
+ return usagef("ledger note KEY VALUE...")
}
v := strings.Join(args[1:], " ")
if looksSecret(v) {
@@ -155,7 +156,7 @@ func cmdAssert(o *Ops, args []string) error {
}
}
if len(args) != 3 {
- return failf("assert WHAT GOT WANT, or a named check: %s", checkNames())
+ return usagef("assert WHAT GOT WANT, or a named check: %s", checkNames())
}
if args[1] != args[2] {
_ = o.jw("ABORT", "assert %s: got [%s], want [%s]", args[0], args[1], args[2])
@@ -170,7 +171,7 @@ func cmdAssert(o *Ops, args []string) error {
// a FACT line. It never stops the run.
func cmdFact(o *Ops, args []string) error {
if len(args) == 0 {
- return failf("fact WHAT GOT WANT | fact TEXT... | fact NAMED-CHECK")
+ return usagef("fact WHAT GOT WANT | fact TEXT... | fact NAMED-CHECK")
}
if chk, ok := namedChecks[args[0]]; ok {
if chk.aws {
@@ -211,15 +212,23 @@ func cmdFact(o *Ops, args []string) error {
// ---- wait-human -------------------------------------------------------
-// cmdWaitHuman bounds a step only Paul can take. The first call starts the
-// clock (WAIT-HUMAN NAME deadline=...); --background returns at once;
-// otherwise it waits for "wait-human NAME --done" (the agent records Paul's
-// word) and exits 1 when the bound passes, which a block turns into a hard
-// stop. A later call never moves the deadline.
+// cmdWaitHuman bounds a step only Paul can take (fix round 1, F1). The
+// first call starts the clock (WAIT-HUMAN NAME deadline=...).
+// - --background starts a watchdog: a journalled user unit,
+// h<env>-<RUN>-wait-NAME, running "wait-human NAME --watch", which runs
+// safe-stop at the deadline unless the wait was done first; then it
+// returns.
+// - --done records Paul's word and stops the watchdog by its journalled
+// name.
+// - --watch (the watchdog) and the foreground form wait; at the deadline
+// they run safe-stop and exit 99, with no further operator command.
+//
+// A later call never moves the deadline.
func cmdWaitHuman(o *Ops, args []string) error {
fs := flag.NewFlagSet("wait-human", flag.ContinueOnError)
maxD := fs.Duration("max", 0, "the bound")
- bg := fs.Bool("background", false, "start the clock and return")
+ bg := fs.Bool("background", false, "start the clock and its watchdog, and return")
+ watch := fs.Bool("watch", false, "the watchdog itself")
done := fs.Bool("done", false, "record that the person did it")
every := fs.Duration("every", 30*time.Second, "how often to look")
pos, err := parseFlags(fs, args)
@@ -227,9 +236,10 @@ func cmdWaitHuman(o *Ops, args []string) error {
return err
}
if len(pos) != 1 || !kindPattern.MatchString(pos[0]) {
- return failf("wait-human NAME --max D [--background] | NAME --done")
+ return usagef("wait-human NAME --max D [--background] | NAME --done")
}
name := pos[0]
+ unit := o.unitName("wait-" + name)
l, err := o.ledger()
if err != nil {
return err
@@ -239,11 +249,23 @@ func cmdWaitHuman(o *Ops, args []string) error {
if !started {
return failf("wait-human %s was never started", name)
}
- return o.jw("HUMAN-DONE", "%s", name)
+ if err := o.jw("HUMAN-DONE", "%s", name); err != nil {
+ return err
+ }
+ if slices.Contains(l.Units, unit) && unit != os.Getenv("EQUIPO_HOSTED_OPS_UNIT") {
+ if err := o.Systemd.Stop(unit); err != nil {
+ return failf("the watchdog %s was not proved stopped: %v", unit, err)
+ }
+ return o.jw("UNIT-STOPPED", "%s", unit)
+ }
+ return nil
}
if !started {
+ if *watch {
+ return failf("wait-human %s was never started", name)
+ }
if *maxD <= 0 || *maxD > 72*time.Hour {
- return failf("wait-human needs --max between 0 and 72h")
+ return usagef("wait-human needs --max between 0 and 72h")
}
w = Wait{Deadline: o.Clock.Now().Add(*maxD)}
if err := o.jw("WAIT-HUMAN", "%s deadline=%d max=%s", name, w.Deadline.Unix(), *maxD); err != nil {
@@ -251,7 +273,12 @@ func cmdWaitHuman(o *Ops, args []string) error {
}
}
if *bg {
- o.out("wait-human %s: the clock runs until %s", name, w.Deadline.UTC().Format(time.RFC3339))
+ if !slices.Contains(l.Units, unit) {
+ if err := o.startUnit("wait-"+name, o.selfArgv("wait-human", name, "--watch")); err != nil {
+ return err
+ }
+ }
+ o.out("wait-human %s: the clock runs until %s; watchdog %s", name, w.Deadline.UTC().Format(time.RFC3339), unit)
return nil
}
for {
@@ -265,10 +292,14 @@ func cmdWaitHuman(o *Ops, args []string) error {
}
if !o.Clock.Now().Before(w.Deadline) {
_ = o.jw("WAIT-EXPIRED", "%s", name)
- return failf("wait-human %s: not done by %s", name, w.Deadline.UTC().Format(time.RFC3339))
+ o.out("ABORT: wait-human %s: not done by %s; running safe-stop", name, w.Deadline.UTC().Format(time.RFC3339))
+ if err := o.safeStop(); err != nil {
+ o.out("safe-stop: %v", err)
+ }
+ return stopf("wait-human %s: not done by %s", name, w.Deadline.UTC().Format(time.RFC3339))
}
if err := o.Clock.Sleep(o.ctx, *every); err != nil {
- return failf("wait-human: %v", err)
+ return stopf("wait-human %s: interrupted: %v", name, err)
}
}
}
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go
index 66286778..ef98a9b9 100644
--- a/internal/hostedops/ops.go
+++ b/internal/hostedops/ops.go
@@ -61,6 +61,14 @@ func (e *exitError) Error() string { return e.msg }
func failf(format string, a ...any) error { return fmt.Errorf(format, a...) }
+// usageError is an invocation the command's own parser refuses: exit 1,
+// printed as "usage: ..." (TestPlanInvocationsParseFlags looks for it).
+type usageError struct{ msg string }
+
+func (e *usageError) Error() string { return "usage: " + e.msg }
+
+func usagef(format string, a ...any) error { return &usageError{msg: fmt.Sprintf(format, a...)} }
+
// Clock is time for waits; tests use a fake one.
type Clock interface {
Now() time.Time
@@ -91,8 +99,12 @@ type Deps struct {
PlanCheck []string // python3 -I <repo>/infra/hosted/scripts/plan-check.py
Litestream string // <dir>/bin/litestream
Carlos string // "carlos"
+ Self string // this binary, for the units ops starts; os.Executable()
Stdout io.Writer
Stderr io.Writer
+ // noSync: tests skip the journal's fsync (it is the only reason they
+ // are slow); production always syncs.
+ noSync bool
// Exec runs a block's command; nil runs it as a child process.
Exec func(ctx context.Context, argv []string, env []string, stdout, stderr io.Writer) int
}
@@ -193,10 +205,14 @@ func (o *Ops) open() (Cloud, error) {
if err != nil {
return nil, err
}
+ bound := "" // the caller the run's first guard verified (F6)
for _, e := range l.Entries {
if e.Verb == "GUARD" && (e.Attr("account") != o.Account || e.Attr("region") != o.Region) {
return nil, stopf("this run was opened for account %s in %s; refusing %s in %s", e.Attr("account"), e.Attr("region"), o.Account, o.Region)
}
+ if e.Verb == "GUARD" && bound == "" {
+ bound = e.Attr("arn")
+ }
}
c, err := o.Opener.Open(o.ctx, Target{Profile: o.Profile, Account: o.Account, Region: o.Region, Role: o.Role})
if err != nil {
@@ -209,6 +225,10 @@ func (o *Ops) open() (Cloud, error) {
if id.Account != o.Account || id.Region != o.Region { // the opener's own answer, checked again here
return nil, stopf("the opener returned account %s in %s, not %s in %s", id.Account, id.Region, o.Account, o.Region)
}
+ if bound != "" && id.ARN != bound {
+ _ = o.jw("ABORT", "guard: the caller is %s; this run is bound to %s", id.ARN, bound)
+ return nil, stopf("the caller is %s, but this run was bound at its first guard to %s; a profile changed since is refused", id.ARN, bound)
+ }
if err := o.jw("GUARD", "account=%s region=%s arn=%s", id.Account, id.Region, id.ARN); err != nil {
return nil, err
}
@@ -254,6 +274,8 @@ func init() {
"unit start": {false, cmdUnitStart, "BLOCK -- CMD..."},
"unit wait": {false, cmdUnitWait, "BLOCK --max D"},
"unit stop": {false, cmdUnitStop, "BLOCK | --all"},
+ "unit probe": {false, cmdUnitProbe, ""},
+ "litestream-install": {false, cmdLitestreamInstall, "--file TARBALL"},
"status": {false, cmdStatus, "[controller flags]"},
"singleton ensure": {true, cmdSingletonEnsure, "NAME"},
"singleton get": {true, cmdSingletonGet, "NAME"},
@@ -317,6 +339,11 @@ func Main(ctx context.Context, args []string, d Deps) int {
if o.Carlos == "" {
o.Carlos = "carlos"
}
+ if o.Self == "" {
+ if exe, err := os.Executable(); err == nil {
+ o.Self = exe
+ }
+ }
return o.main(args)
}
@@ -331,7 +358,7 @@ func (o *Ops) main(args []string) int {
fs.StringVar(&o.Role, "role", "", "the expected role, ROLE or ROLE/SESSION (default: the profile's)")
fs.StringVar(&o.Repo, "repo", "", "the release worktree (default DIR/repo)")
if err := fs.Parse(args); err != nil {
- return o.report(failf("%v", err))
+ return o.report(usagef("%v", err))
}
switch {
case o.Dir == "":
@@ -350,10 +377,10 @@ func (o *Ops) main(args []string) int {
if len(o.PlanCheck) == 0 {
o.PlanCheck = []string{"python3", "-I", filepath.Join(o.Repo, "infra", "hosted", "scripts", "plan-check.py")}
}
- o.j = &Journal{Path: o.path(JournalFile), Now: o.Clock.Now}
+ o.j = &Journal{Path: o.path(JournalFile), Now: o.Clock.Now, noSync: o.noSync}
name, c, rest, ok := lookup(fs.Args())
if !ok {
- return o.report(failf("unknown command %q; commands: %s", strings.Join(fs.Args(), " "), commandNames()))
+ return o.report(usagef("unknown command %q; commands: %s", strings.Join(fs.Args(), " "), commandNames()))
}
if name != "ledger init" && name != "reopen" {
if _, err := o.ledger(); err != nil {
@@ -401,7 +428,7 @@ func parseFlags(fs *flag.FlagSet, args []string) ([]string, error) {
var pos []string
for {
if err := fs.Parse(args); err != nil {
- return nil, failf("%s: %v", fs.Name(), err)
+ return nil, usagef("%s: %v", fs.Name(), err)
}
rest := fs.Args()
if len(rest) == 0 {
@@ -417,7 +444,7 @@ func parseFlags(fs *flag.FlagSet, args []string) ([]string, error) {
func cmdGuard(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("guard takes no arguments")
+ return usagef("guard takes no arguments")
}
id := o.cloud.Identity()
o.out("guard: account %s, %s, region %s", id.Account, id.ARN, id.Region)
diff --git a/internal/hostedops/ops_test.go b/internal/hostedops/ops_test.go
index 85a2a221..4d6c8143 100644
--- a/internal/hostedops/ops_test.go
+++ b/internal/hostedops/ops_test.go
@@ -117,8 +117,8 @@ func TestRequiredStepFailureStops(t *testing.T) {
r.want(0, "wait-human", "sns-confirmed", "--max", "1h", "--background")
r.clock.Sleep(context.Background(), 2*time.Hour)
waitCode := r.ops("wait-human", "sns-confirmed", "--max", "1h")
- if unitCode != 1 || waitCode != 1 {
- t.Fatalf("a failed unit exits %d and an expired wait %d; want 1 each", unitCode, waitCode)
+ if unitCode != ExitStop || waitCode != ExitStop || !r.has("SAFE-STOP", "start") {
+ t.Fatalf("a failed unit exits %d and an expired wait %d; want 99 each, through safe-stop (fix round 1, F1)", unitCode, waitCode)
}
for name, code := range map[string]int{"exit 1": 1, "failed unit": unitCode, "expired wait": waitCode} {
r := newRig(t)
@@ -161,7 +161,8 @@ func TestSafeStopSkipsSpendCheck(t *testing.T) {
// TestFenceBeforeSettle: safe-stop attaches the deny policy and stops the
// controller host before it touches any VM.
func TestFenceBeforeSettle(t *testing.T) {
- r := settleRig(t, nil, ctlPol, ctlVM, "VM microvm-a source=controller")
+ r := settleRig(t, nil, ctlPol, ctlVM, "VM microvm-a source=controller", "NOTE instance-app equipo", "NOTE instance-account acme")
+ r.deps.Carlos = "/bin/true"
r.want(0, "safe-stop")
attach, stop := r.cloud.index("AttachRolePolicy equipo-hosted-controller arn:aws:iam::149757027610:policy/equipo-hosted-deny-launches"), r.cloud.index("StopInstance i-0ctl")
first := min(r.cloud.index("ListVMs"), r.cloud.index("TerminateVM"))
diff --git a/internal/hostedops/report.go b/internal/hostedops/report.go
index bcd0f5ff..1d5e0726 100644
--- a/internal/hostedops/report.go
+++ b/internal/hostedops/report.go
@@ -1,16 +1,23 @@
package hostedops
import (
+ "archive/tar"
"bytes"
+ "compress/gzip"
"context"
+ "crypto/sha256"
"database/sql"
+ "encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
+ "io"
"os"
"os/exec"
+ "path"
"path/filepath"
+ "runtime"
"strconv"
"strings"
"time"
@@ -28,7 +35,7 @@ func cmdReport(o *Ops, args []string) error {
stopped := fs.Bool("stopped", false, "S.5: what exists and what it costs a day while stopped")
out := fs.String("out", "", "where to write it (default DIR/report.md)")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("report [--stopped] [--out F]")
+ return usagef("report [--stopped] [--out F]")
}
path := *out
if path == "" {
@@ -210,7 +217,7 @@ func cmdBundle(o *Ops, args []string) error {
fs := flag.NewFlagSet("bundle", flag.ContinueOnError)
out := fs.String("out", "", "where to write the bundle")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *out == "" {
- return failf("bundle --out F")
+ return usagef("bundle --out F")
}
return o.writeBundle(*out)
}
@@ -222,7 +229,7 @@ func cmdReopen(o *Ops, args []string) error {
fs := flag.NewFlagSet("reopen", flag.ContinueOnError)
in := fs.String("bundle", "", "the bundle")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *in == "" {
- return failf("reopen --bundle F")
+ return usagef("reopen --bundle F")
}
raw, err := os.ReadFile(*in)
if err != nil {
@@ -271,6 +278,36 @@ func isBundleFile(n string) bool {
// their parents.
var resourceKinds = []string{"s3-bucket", "s3-object", "connector", "microvm-image", "tf"}
+// coveredBy declares, for each type the stacks create that has no direct
+// read, the parent type whose verified deletion proves it gone (F4). Every
+// other recorded type needs a direct read (TestEveryStackTypeVerifiable).
+var coveredBy = map[string]string{
+ "aws_iam_role_policy": "aws_iam_role", "aws_iam_role_policy_attachment": "aws_iam_role",
+ "aws_s3_bucket_versioning": "aws_s3_bucket", "aws_s3_bucket_server_side_encryption_configuration": "aws_s3_bucket",
+ "aws_s3_bucket_public_access_block": "aws_s3_bucket", "aws_s3_bucket_policy": "aws_s3_bucket", "aws_s3_bucket_lifecycle_configuration": "aws_s3_bucket",
+ "aws_route": "aws_route_table", "aws_route_table_association": "aws_route_table",
+ "aws_vpc_security_group_egress_rule": "aws_security_group", "aws_vpc_security_group_ingress_rule": "aws_security_group",
+ "aws_network_acl_rule": "aws_network_acl",
+ "aws_default_security_group": "aws_vpc", "aws_default_route_table": "aws_vpc", "aws_default_network_acl": "aws_vpc",
+ "aws_sns_topic_policy": "aws_sns_topic", "aws_sns_topic_subscription": "aws_sns_topic",
+}
+
+// DirectReadTypes are the tf types opsaws reads directly (Lookup).
+var DirectReadTypes = []string{"aws_s3_bucket", "aws_iam_role", "aws_iam_policy", "aws_iam_instance_profile", "aws_sns_topic",
+ "aws_cloudtrail", "aws_cloudwatch_metric_alarm", "aws_cloudwatch_log_group", "aws_budgets_budget", "aws_budgets_budget_action",
+ "aws_vpc", "aws_subnet", "aws_security_group", "aws_route_table", "aws_internet_gateway", "aws_vpc_peering_connection",
+ "aws_instance", "aws_eip", "aws_network_acl"}
+
+// parentMatches reports whether p is the parent a child names by ID, name
+// or ARN.
+func parentMatches(p Rec, ref string) bool {
+ if ref == "" {
+ return false
+ }
+ id := p.Attr("id")
+ return id == ref || p.Attr("rname") == ref || strings.HasSuffix(id, "/"+ref) || strings.HasSuffix(ref, "/"+id) || strings.HasSuffix(ref, ":"+p.Attr("rname"))
+}
+
// kept reports whether R leaves r on purpose (section 2 and the state
// bucket); --all (T) checks those too.
func (o *Ops) kept(r Rec) bool {
@@ -283,7 +320,7 @@ func cmdVerifyGone(o *Ops, args []string) error {
fs := flag.NewFlagSet("verify-gone", flag.ContinueOnError)
all := fs.Bool("all", false, "also section 2 and the state bucket (T)")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("verify-gone [--all]")
+ return usagef("verify-gone [--all]")
}
l, err := o.ledger()
if err != nil {
@@ -293,13 +330,19 @@ func cmdVerifyGone(o *Ops, args []string) error {
return stopf("verify-gone: %d intents are unresolved (%s %s first)", len(open), open[0].Kind, open[0].Name)
}
var present []string
- for _, r := range l.Recs {
+ gone := map[int]bool{} // index into l.Recs: read gone in this pass
+ var covered []int
+ for i, r := range l.Recs {
if !contains(resourceKinds, r.Kind) || (!*all && o.kept(r)) {
continue
}
key := LookupKey{Type: r.Kind, ID: r.Value, Name: r.Name, Run: o.Run}
if r.Kind == "tf" {
key = LookupKey{Type: r.Attr("type"), ID: r.Attr("id"), Name: r.Attr("rname"), Run: o.Run}
+ if coveredBy[key.Type] != "" {
+ covered = append(covered, i)
+ continue
+ }
}
if r.Kind == "s3-bucket" {
key.ID = r.Name
@@ -311,11 +354,35 @@ func cmdVerifyGone(o *Ops, args []string) error {
case len(res.IDs) > 0:
present = append(present, r.Kind+" "+r.Value)
case !res.Definitive:
- if err := o.jw("UNCHECKED", "%s %s %s: no direct read for this type; its parent's read covers it", r.Kind, r.Value, key.Type); err != nil {
- return err
+ // No direct read and no declared parent: not proof (F4).
+ present = append(present, r.Kind+" "+r.Value+" (no direct read for "+key.Type+")")
+ default:
+ gone[i] = true
+ if !l.Deleted[r.Kind+" "+r.Value] {
+ if err := o.jw("DELETED", "%s %s read-gone", r.Kind, r.Value); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ // A covered type passes only when its declared parent was itself read
+ // gone in this pass.
+ for _, i := range covered {
+ r := l.Recs[i]
+ parent, ok := "", false
+ for j, p := range l.Recs {
+ if p.Kind == "tf" && p.Attr("type") == coveredBy[r.Attr("type")] && parentMatches(p, r.Attr("parent")) {
+ parent, ok = p.Value, gone[j]
+ break
}
- case !l.Deleted[r.Kind+" "+r.Value]:
- if err := o.jw("DELETED", "%s %s read-gone", r.Kind, r.Value); err != nil {
+ }
+ switch {
+ case parent == "":
+ present = append(present, "tf "+r.Value+" (no recorded parent "+coveredBy[r.Attr("type")]+" covers it)")
+ case !ok:
+ present = append(present, "tf "+r.Value+" (its parent "+parent+" was not read gone)")
+ case !l.Deleted["tf "+r.Value]:
+ if err := o.jw("DELETED", "tf %s covered-by %s", r.Value, parent); err != nil {
return err
}
}
@@ -351,7 +418,7 @@ func cmdLitestreamCheck(o *Ops, args []string) error {
fs := flag.NewFlagSet("litestream-check", flag.ContinueOnError)
bucket := fs.String("bucket", "", "the Litestream bucket")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *bucket == "" {
- return failf("litestream-check --bucket B")
+ return usagef("litestream-check --bucket B")
}
if err := o.checkOwner(*bucket, ""); err != nil {
return err
@@ -389,3 +456,64 @@ func cmdLitestreamCheck(o *Ops, args []string) error {
o.out("litestream-check: restored and opened; provider_binding %s", ns)
return o.jw("LITESTREAM-OK", "%s", ns)
}
+
+// cmdLitestreamInstall installs the release's pinned Litestream (F10): the
+// tarball for this machine's platform, fetched with the release (account
+// plan 4.1), must have the name and SHA-256 the release manifest records;
+// its litestream binary goes to DIR/bin/litestream, where litestream-check
+// runs it.
+func cmdLitestreamInstall(o *Ops, args []string) error {
+ fs := flag.NewFlagSet("litestream-install", flag.ContinueOnError)
+ file := fs.String("file", "", "the release's litestream-*.tar.gz for this platform")
+ if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *file == "" {
+ return usagef("litestream-install --file TARBALL")
+ }
+ m, err := o.releaseManifest()
+ if err != nil {
+ return err
+ }
+ plat := "linux/" + runtime.GOARCH
+ ls, _ := m["Litestream"].(map[string]any)
+ assets, _ := ls["Assets"].(map[string]any)
+ a, _ := assets[plat].(map[string]any)
+ name, _ := a["Name"].(string)
+ want, _ := a["SHA256"].(string)
+ if name == "" || want == "" {
+ return failf("the release manifest pins no Litestream for %s", plat)
+ }
+ if filepath.Base(*file) != name {
+ return stopf("%s is not the release's Litestream for %s (%s)", filepath.Base(*file), plat, name)
+ }
+ raw, err := os.ReadFile(*file)
+ if err != nil {
+ return failf("%v", err)
+ }
+ sum := sha256.Sum256(raw)
+ if got := hex.EncodeToString(sum[:]); got != want {
+ _ = o.jw("ABORT", "litestream-install: %s has SHA-256 %s, the release records %s", name, got, want)
+ return stopf("%s has SHA-256 %s, not the release's %s", name, got, want)
+ }
+ gz, err := gzip.NewReader(bytes.NewReader(raw))
+ if err != nil {
+ return stopf("%s is not a gzip tarball: %v", name, err)
+ }
+ tr := tar.NewReader(gz)
+ for {
+ h, err := tr.Next()
+ if err != nil {
+ return stopf("%s holds no litestream binary (%v)", name, err)
+ }
+ if path.Base(h.Name) != "litestream" || h.Typeflag != tar.TypeReg {
+ continue
+ }
+ bin, err := io.ReadAll(io.LimitReader(tr, 256<<20))
+ if err != nil {
+ return failf("%v", err)
+ }
+ if err := writeFileAtomic(o.Litestream, bin, 0o755); err != nil {
+ return failf("%v", err)
+ }
+ o.out("installed %s from %s (SHA-256 %s)", o.Litestream, name, want)
+ return o.jw("LITESTREAM-INSTALLED", "%s sha256=%s", name, want)
+ }
+}
diff --git a/internal/hostedops/singleton.go b/internal/hostedops/singleton.go
index 856ff69f..485324fc 100644
--- a/internal/hostedops/singleton.go
+++ b/internal/hostedops/singleton.go
@@ -6,6 +6,7 @@ import (
"flag"
"fmt"
"net/url"
+ "slices"
"strings"
"time"
)
@@ -37,7 +38,7 @@ func (o *Ops) readSingleton(name string) (on bool, shown string, err error) {
func cmdSingletonGet(o *Ops, args []string) error {
if len(args) != 1 {
- return failf("singleton get NAME")
+ return usagef("singleton get NAME")
}
on, shown, err := o.readSingleton(args[0])
if err != nil {
@@ -49,7 +50,7 @@ func cmdSingletonGet(o *Ops, args []string) error {
func cmdSingletonEnsure(o *Ops, args []string) error {
if len(args) != 1 {
- return failf("singleton ensure NAME")
+ return usagef("singleton ensure NAME")
}
name := args[0]
on, prior, err := o.readSingleton(name)
@@ -87,7 +88,7 @@ func cmdMFACheck(o *Ops, args []string) error {
fs := flag.NewFlagSet("mfa-check", flag.ContinueOnError)
role := fs.String("role-name", "", "the access role (default: the expected role's name)")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("mfa-check [--role-name R]")
+ return usagef("mfa-check [--role-name R]")
}
name := *role
if name == "" {
@@ -105,7 +106,10 @@ func cmdMFACheck(o *Ops, args []string) error {
if d, err := url.QueryUnescape(doc); err == nil {
doc = d
}
- enforced := strings.Contains(doc, "aws:MultiFactorAuthPresent")
+ enforced, why := TrustRequiresMFA(doc)
+ if !enforced {
+ o.out("MFA: %s", why)
+ }
if err := o.jw("NOTE", "mfa-enforced %t role=%s", enforced, name); err != nil {
return err
}
@@ -125,9 +129,99 @@ func cmdMFACheck(o *Ops, args []string) error {
return stopf("MFA is not enforced by the trust policy of %s and the GO did not waive it (decision 3)", name)
}
-// fence is R.2: attach the deny-launches policy to the controller role
-// directly, confirm it, then stop the controller host and confirm it
-// stopped. It acts only on what the services stack recorded.
+// TrustRequiresMFA evaluates a role trust policy (fix round 1, F7): MFA is
+// enforced only when the document parses, has at least one Allow statement
+// granting an assume-role action, and every such statement carries
+// Condition.Bool "aws:MultiFactorAuthPresent" equal to true (a string, a
+// bool, or a list holding only true). A NotAction, NotPrincipal,
+// BoolIfExists, or any other shape is not enforcement.
+func TrustRequiresMFA(doc string) (bool, string) {
+ var p struct {
+ Statement json.RawMessage
+ }
+ if err := json.Unmarshal([]byte(doc), &p); err != nil || len(p.Statement) == 0 {
+ return false, "the trust policy does not parse"
+ }
+ var stmts []map[string]json.RawMessage
+ if err := json.Unmarshal(p.Statement, &stmts); err != nil {
+ var one map[string]json.RawMessage
+ if err := json.Unmarshal(p.Statement, &one); err != nil {
+ return false, "the trust policy's statements do not parse"
+ }
+ stmts = []map[string]json.RawMessage{one}
+ }
+ allows := 0
+ for i, st := range stmts {
+ var effect string
+ if json.Unmarshal(st["Effect"], &effect) != nil {
+ return false, fmt.Sprintf("statement %d has no Effect", i)
+ }
+ if effect != "Allow" {
+ continue
+ }
+ if _, bad := st["NotAction"]; bad {
+ return false, fmt.Sprintf("statement %d uses NotAction", i)
+ }
+ if _, bad := st["NotPrincipal"]; bad {
+ return false, fmt.Sprintf("statement %d uses NotPrincipal", i)
+ }
+ var actions []string
+ if json.Unmarshal(st["Action"], &actions) != nil {
+ var a string
+ if json.Unmarshal(st["Action"], &a) != nil {
+ return false, fmt.Sprintf("statement %d has no readable Action", i)
+ }
+ actions = []string{a}
+ }
+ assume := false
+ for _, a := range actions {
+ if a == "*" || a == "sts:*" || strings.HasPrefix(a, "sts:AssumeRole") {
+ assume = true
+ }
+ }
+ if !assume {
+ continue
+ }
+ allows++
+ var cond map[string]map[string]json.RawMessage
+ if json.Unmarshal(st["Condition"], &cond) != nil || !mfaTrue(cond["Bool"]["aws:MultiFactorAuthPresent"]) {
+ return false, fmt.Sprintf("statement %d allows the role without requiring aws:MultiFactorAuthPresent true", i)
+ }
+ }
+ if allows == 0 {
+ return false, "the trust policy allows no assume-role action"
+ }
+ return true, ""
+}
+
+func mfaTrue(v json.RawMessage) bool {
+ var s string
+ if json.Unmarshal(v, &s) == nil {
+ return s == "true"
+ }
+ var b bool
+ if json.Unmarshal(v, &b) == nil {
+ return b
+ }
+ var l []json.RawMessage
+ if json.Unmarshal(v, &l) != nil || len(l) == 0 {
+ return false
+ }
+ for _, x := range l {
+ if !mfaTrue(x) {
+ return false
+ }
+ }
+ return true
+}
+
+// fence is R.2 (fix round 1, F5): attach the deny-launches policy to the
+// controller role directly, then stop every controller host and confirm
+// each stopped. The policy is attached when the services stack recorded it
+// or has an open intent for it; the hosts are the recorded controller and
+// any open controller intent's instance, found by its creation identity. A
+// failed attach does not skip the host stop; every problem is reported at
+// the end, and a controller whose existence cannot be settled is one.
func (o *Ops) fence() error {
l, err := o.ledger()
if err != nil {
@@ -135,14 +229,20 @@ func (o *Ops) fence() error {
}
role := o.namePrefix() + "-controller"
policy := "arn:aws:iam::" + o.Account + ":policy/" + o.namePrefix() + "-deny-launches"
- hasPolicy := false
+ var problems []string
+ policyKnown := false
for _, r := range l.Recorded("tf") {
if r.Attr("type") == "aws_iam_policy" && strings.HasSuffix(r.Value, ".deny_launches") && !l.Deleted["tf "+r.Value] {
- hasPolicy = true
+ policyKnown = true
}
}
- if !hasPolicy {
- if err := o.jw("SKIP", "fence policy: the services stack recorded no deny_launches policy"); err != nil {
+ for _, in := range l.Open("tf") {
+ if strings.HasSuffix(in.Name, ".deny_launches") {
+ policyKnown = true
+ }
+ }
+ if !policyKnown {
+ if err := o.jw("SKIP", "fence policy: the services stack has no deny_launches policy"); err != nil {
return err
}
} else {
@@ -150,49 +250,80 @@ func (o *Ops) fence() error {
return err
}
if err := o.cloud.AttachRolePolicy(o.ctx, role, policy); err != nil {
- return stopf("fence: attaching %s to %s failed: %v", policy, role, err)
- }
- ok, err := o.cloud.RolePolicyAttached(o.ctx, role, policy)
- if err != nil || !ok {
- return stopf("fence: %s is not read back attached to %s (%v)", policy, role, err)
- }
- if err := o.rec("fence-attach", policy, "name="+role); err != nil {
+ problems = append(problems, fmt.Sprintf("attaching %s to %s failed: %v", policy, role, err))
+ _ = o.jw("NOTCREATED", "fence-attach %s attach-failed", role)
+ } else if ok, err := o.cloud.RolePolicyAttached(o.ctx, role, policy); err != nil || !ok {
+ problems = append(problems, fmt.Sprintf("%s is not read back attached to %s (%v)", policy, role, err))
+ _ = o.jw("NOTCREATED", "fence-attach %s not-read-back", role)
+ } else if err := o.rec("fence-attach", policy, "name="+role); err != nil {
return err
}
}
- var ctl *Host
+ var ids []string
for _, h := range l.Hosts {
if strings.HasSuffix(h.Address, "aws_instance.controller") && h.Gone.IsZero() {
- ctl = h
+ ids = append(ids, h.ID)
+ }
+ }
+ for _, in := range l.Open("tf") {
+ if !strings.HasSuffix(in.Name, "aws_instance.controller") {
+ continue
+ }
+ res, err := o.cloud.Lookup(o.ctx, LookupKey{Type: "aws_instance", NameTag: in.Attr("nametag"), Run: o.Run, Parent: in.Attr("parent")})
+ switch {
+ case err != nil:
+ problems = append(problems, fmt.Sprintf("the controller intent %s could not be looked up: %v", in.Name, err))
+ case len(res.IDs) > 0:
+ for _, id := range res.IDs {
+ if !slices.Contains(ids, id) {
+ ids = append(ids, id)
+ _ = o.finding("fence: controller %s exists only as an open intent (%s); stopping it", id, in.Name)
+ }
+ }
+ case !res.Definitive:
+ problems = append(problems, fmt.Sprintf("the controller intent %s is unresolved: no direct read can rule it out", in.Name))
}
}
- if ctl == nil {
- o.out("fence: no controller host recorded")
- return o.jw("SKIP", "fence host: no controller host recorded")
+ slices.Sort(ids)
+ for _, id := range ids {
+ if err := o.stopHost(id); err != nil {
+ problems = append(problems, err.Error())
+ }
}
- if err := o.cloud.StopInstance(o.ctx, ctl.ID); err != nil && !errors.Is(err, ErrNotFound) {
- return stopf("fence: stopping %s failed: %v", ctl.ID, err)
+ if len(ids) == 0 {
+ _ = o.jw("SKIP", "fence host: no controller host recorded or found")
+ }
+ if len(problems) > 0 {
+ _ = o.jw("ABORT", "fence: %s", strings.Join(problems, "; "))
+ return stopf("fence incomplete: %s", strings.Join(problems, "; "))
+ }
+ o.out("fenced: %s on %s; controller hosts stopped: %v", policy, role, ids)
+ return o.jw("FENCED", "%s %s %s", role, policy, strings.Join(ids, ","))
+}
+
+// stopHost stops one EC2 host and waits up to 10 minutes for stopped.
+func (o *Ops) stopHost(id string) error {
+ if err := o.cloud.StopInstance(o.ctx, id); err != nil && !errors.Is(err, ErrNotFound) {
+ return fmt.Errorf("stopping %s failed: %v", id, err)
}
end := o.Clock.Now().Add(10 * time.Minute)
for {
- st, err := o.cloud.InstanceState(o.ctx, ctl.ID)
+ st, err := o.cloud.InstanceState(o.ctx, id)
if errors.Is(err, ErrNotFound) || st == "stopped" || st == "terminated" {
- break
+ return o.jw("HOST-STOPPED", "%s %s", id, st)
}
if !o.Clock.Now().Add(15 * time.Second).Before(end) {
- return stopf("fence: the controller host %s is not stopped (%s, %v)", ctl.ID, st, err)
+ return fmt.Errorf("the controller host %s is not stopped (%s, %v)", id, st, err)
}
if err := o.Clock.Sleep(o.ctx, 15*time.Second); err != nil {
- return stopf("interrupted: %v", err)
+ return fmt.Errorf("interrupted: %v", err)
}
}
- o.out("fenced: %s attached to %s; controller %s stopped", policy, role, ctl.ID)
- return o.jw("FENCED", "%s %s %s stopped", role, policy, ctl.ID)
}
func cmdFence(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("fence takes no arguments")
+ return usagef("fence takes no arguments")
}
return o.fence()
}
@@ -200,7 +331,7 @@ func cmdFence(o *Ops, args []string) error {
// cmdTrailStop is T's first step: stop the run's trail and confirm.
func cmdTrailStop(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("cloudtrail stop-logging takes no arguments")
+ return usagef("cloudtrail stop-logging takes no arguments")
}
l, err := o.ledger()
if err != nil {
@@ -250,7 +381,7 @@ func tfState(l *Ledger, root, typ string) string {
// inventory.json. Anything else non-zero is a FINDING, never touched.
func cmdInventory(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("inventory takes no arguments")
+ return usagef("inventory takes no arguments")
}
inv, err := o.cloud.Inventory(o.ctx)
if err != nil {
@@ -308,7 +439,7 @@ func ownName(l *Ledger, n string) bool {
// under 64 GB of VM memory, is a FINDING.
func cmdQuota(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("quota takes no arguments")
+ return usagef("quota takes no arguments")
}
qs, err := o.cloud.Quotas(o.ctx)
if err != nil {
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go
index 37b025ae..e9f025ad 100644
--- a/internal/hostedops/stop.go
+++ b/internal/hostedops/stop.go
@@ -7,6 +7,7 @@ import (
"io"
"os"
"os/exec"
+ "slices"
"strings"
"time"
)
@@ -22,7 +23,7 @@ func cmdBlock(o *Ops, args []string) error {
optional := fs.Bool("optional", false, "a non-zero exit other than 99 is not a hard stop")
pos, err := parseFlags(fs, args)
if err != nil || len(pos) < 2 || !blockPattern.MatchString(pos[0]) {
- return failf("block ID [--stop USD] [--optional] -- CMD...")
+ return usagef("block ID [--stop USD] [--optional] -- CMD...")
}
id, argv := pos[0], pos[1:]
if err := o.jw("BLOCK", "%s start", id); err != nil {
@@ -87,9 +88,12 @@ func runChild(ctx context.Context, argv, env []string, stdout, stderr io.Writer)
return ExitFail
}
+// SafeStopBound bounds one safe stop, whatever the invocation's context.
+const SafeStopBound = 30 * time.Minute
+
func cmdSafeStop(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("safe-stop takes no arguments")
+ return usagef("safe-stop takes no arguments")
}
return o.safeStop()
}
@@ -99,6 +103,12 @@ func cmdSafeStop(o *Ops, args []string) error {
// fails safe-stop records it, does the remaining local step (S.5) and
// returns 99: the run waits for Paul. Nothing but VMs is deleted.
func (o *Ops) safeStop() error {
+ // Its own context (F2): an interrupted invocation still stops safely,
+ // for at most SafeStopBound.
+ outer := o.ctx
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(outer), SafeStopBound)
+ o.ctx = ctx
+ defer func() { cancel(); o.ctx = outer }()
_ = o.jw("SAFE-STOP", "start")
var problems []string
note := func(step string, err error) {
@@ -117,24 +127,39 @@ func (o *Ops) safeStop() error {
note("credentials", err)
}
if cloudOK {
- note("S.2 fence", o.fence())
+ fenceErr := o.fence()
+ note("S.2 fence", fenceErr)
+ before := o.knownResources()
note("S.3 vms reconcile", cmdVMsReconcile(o, nil))
- l, err := o.ledger()
- if err == nil {
+ settled := map[string]bool{}
+ settleAll := func() {
+ l, err := o.ledger()
+ if err != nil {
+ note("S.4", err)
+ return
+ }
for _, r := range l.Recorded("microvm-image") {
- if l.Deleted["microvm-image "+r.Value] {
+ if l.Deleted["microvm-image "+r.Value] || settled[r.Value] {
continue
}
+ settled[r.Value] = true
note("S.4 settle "+r.Value, o.settleImage(r.Value, true, defaultSettle))
}
- note("S.4 ledger reconcile", o.reconcileLedger())
+ }
+ settleAll()
+ note("S.4 ledger reconcile", o.reconcileLedger())
+ if l, err := o.ledger(); err == nil {
for root, applying := range l.TFApplying {
if applying {
note("S.4 tf reconcile "+root, o.tfReconcile(root))
}
}
- } else {
- note("S.4", err)
+ }
+ // Reconciliation may find what the first fence could not: fence
+ // and settle again (F5).
+ if fenceErr != nil || o.knownResources() != before {
+ note("S.4 fence again", o.fence())
+ settleAll()
}
}
note("S.5 bundle", o.writeBundle(o.path("bundle.json")))
@@ -148,6 +173,27 @@ func (o *Ops) safeStop() error {
return nil
}
+// knownResources summarises the hosts, images and open intents the ledger
+// holds, to see whether reconciliation found more.
+func (o *Ops) knownResources() string {
+ l, err := o.ledger()
+ if err != nil {
+ return ""
+ }
+ var parts []string
+ for id := range l.Hosts {
+ parts = append(parts, id)
+ }
+ for _, r := range l.Recorded("microvm-image") {
+ parts = append(parts, r.Value)
+ }
+ for _, in := range l.Open() {
+ parts = append(parts, in.Kind+":"+in.Name)
+ }
+ slices.Sort(parts)
+ return strings.Join(parts, " ")
+}
+
// unsetInstanceFlag is S.1: if 7.1 ran (ledger notes instance-app and
// instance-account), carlos env unset EQUIPO_HOSTED_RUNNERS.
func (o *Ops) unsetInstanceFlag() error {
@@ -157,7 +203,21 @@ func (o *Ops) unsetInstanceFlag() error {
}
app, acct := l.Notes["instance-app"], l.Notes["instance-account"]
if app == "" || acct == "" {
- return o.jw("SKIP", "S.1: 7.1 did not run (no instance-app and instance-account notes)")
+ // The flag can be on only once a controller exists (7.1 needs its
+ // address). Without one, there is nothing to turn off; with one and
+ // no notes, the flag's state is unknown: unresolved (F16).
+ controller := false
+ for _, h := range l.Hosts {
+ controller = controller || strings.HasSuffix(h.Address, "aws_instance.controller")
+ }
+ for _, in := range l.Open("tf") {
+ controller = controller || strings.HasSuffix(in.Name, "aws_instance.controller")
+ }
+ if !controller {
+ return o.jw("SKIP", "S.1: no controller exists, so the instance cannot have been wired to one")
+ }
+ _ = o.jw("UNRESOLVED", "S.1: a controller exists and the ledger has no instance-app and instance-account notes; the instance flag's state is unknown")
+ return stopf("S.1: cannot prove EQUIPO_HOSTED_RUNNERS is off: record ledger note instance-app and instance-account (7.1) and run safe-stop again")
}
ctx, cancel := context.WithTimeout(o.ctx, 2*time.Minute)
defer cancel()
diff --git a/internal/hostedops/tf.go b/internal/hostedops/tf.go
index 366d13b1..1f6de866 100644
--- a/internal/hostedops/tf.go
+++ b/internal/hostedops/tf.go
@@ -164,6 +164,43 @@ type planChange struct {
} `json:"change"`
}
+// identity is a planned resource's creation identity (F3): its API name,
+// its Name tag and its parent's ID, as far as the plan knows them.
+func identity(after map[string]any) []string {
+ var out []string
+ if n := nameOf(after); n != "" && !strings.ContainsAny(n, " \t") {
+ out = append(out, "name="+n)
+ }
+ for _, k := range []string{"tags", "tags_all"} {
+ if t, ok := after[k].(map[string]any); ok {
+ if n, ok := t["Name"].(string); ok && n != "" && !strings.ContainsAny(n, " \t") {
+ out = append(out, "nametag="+n)
+ break
+ }
+ }
+ }
+ for _, k := range []string{"vpc_id", "subnet_id"} {
+ if p, ok := after[k].(string); ok && p != "" {
+ out = append(out, "parent="+p)
+ break
+ }
+ }
+ return out
+}
+
+// parentKey names, per covered type, the attribute holding its parent
+// (verify-gone, F4).
+var parentKey = map[string]string{
+ "aws_iam_role_policy": "role", "aws_iam_role_policy_attachment": "role",
+ "aws_s3_bucket_versioning": "bucket", "aws_s3_bucket_server_side_encryption_configuration": "bucket",
+ "aws_s3_bucket_public_access_block": "bucket", "aws_s3_bucket_policy": "bucket", "aws_s3_bucket_lifecycle_configuration": "bucket",
+ "aws_route": "route_table_id", "aws_route_table_association": "route_table_id",
+ "aws_vpc_security_group_egress_rule": "security_group_id", "aws_vpc_security_group_ingress_rule": "security_group_id",
+ "aws_network_acl_rule": "network_acl_id",
+ "aws_default_security_group": "vpc_id", "aws_default_route_table": "vpc_id", "aws_default_network_acl": "vpc_id",
+ "aws_sns_topic_policy": "arn", "aws_sns_topic_subscription": "topic_arn",
+}
+
func nameOf(v map[string]any) string {
for _, k := range []string{"name", "bucket", "alarm_name", "role", "trail_name"} {
if s, ok := v[k].(string); ok && s != "" {
@@ -187,7 +224,7 @@ func cmdTf(o *Ops, args []string) error {
return o.tfReconcile(args[1])
}
if len(args) != 2 {
- return failf("tf ROOT PHASE | tf reconcile ROOT")
+ return usagef("tf ROOT PHASE | tf reconcile ROOT")
}
root, phase := args[0], args[1]
destroy, err := o.phaseFor(root, phase)
@@ -212,6 +249,9 @@ func cmdTf(o *Ops, args []string) error {
if err := o.tofuInit(root, dir); err != nil {
return err
}
+ if err := o.importAdopted(root, dir, vars); err != nil {
+ return err
+ }
td := o.path("tf")
if err := os.MkdirAll(td, 0o700); err != nil {
return failf("%v", err)
@@ -257,10 +297,9 @@ func cmdTf(o *Ops, args []string) error {
for _, ch := range plan.Changes {
switch {
case slices.Contains(ch.Change.Actions, "create"):
- n := nameOf(ch.Change.After)
- text := fmt.Sprintf("tf %s/%s - type=%s", root, ch.Address, ch.Type)
- if n != "" {
- text += " name=" + n
+ text := fmt.Sprintf("tf %s/%s - type=%s run=%s", root, ch.Address, ch.Type, o.Run)
+ for _, kv := range identity(ch.Change.After) {
+ text += " " + kv
}
if err := o.jw("INTENT", "%s", text); err != nil {
return err
@@ -419,6 +458,11 @@ func (o *Ops) recTF(root string, r stateResource, source string) error {
if n := nameOf(r.Values); n != "" && !strings.ContainsAny(n, " \t") {
attrs = append(attrs, "rname="+n)
}
+ if k := parentKey[r.Type]; k != "" {
+ if p, ok := r.Values[k].(string); ok && p != "" && !strings.ContainsAny(p, " \t") {
+ attrs = append(attrs, "parent="+p)
+ }
+ }
return o.rec("tf", root+"/"+r.Address, attrs...)
}
@@ -497,7 +541,8 @@ func (o *Ops) tfReconcile(root string) error {
}
continue
}
- res, err := o.cloud.Lookup(o.ctx, LookupKey{Type: in.Attr("type"), Name: in.Attr("name"), Run: o.Run})
+ res, err := o.cloud.Lookup(o.ctx, LookupKey{Type: in.Attr("type"), Name: in.Attr("name"), Run: o.Run,
+ NameTag: in.Attr("nametag"), Parent: in.Attr("parent"), Token: in.Token})
switch {
case err != nil:
left = append(left, in.Name)
@@ -507,7 +552,7 @@ func (o *Ops) tfReconcile(root string) error {
if err := o.rec("tf", in.Name, "id="+id, "type="+in.Attr("type"), "source=outside-state"); err != nil {
return err
}
- if err := o.finding("tf reconcile: %s exists as %s outside state; ops deletes it, or Paul adopts it", in.Name, id); err != nil {
+ if err := o.adopt(root, in.Name, id); err != nil {
return err
}
case len(res.IDs) > 1:
@@ -622,7 +667,84 @@ func (o *Ops) reconcileLedger() error {
func cmdLedgerReconcile(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("ledger reconcile takes no arguments")
+ return usagef("ledger reconcile takes no arguments")
}
return o.reconcileLedger()
}
+
+// importsFile is a root's run-local import blocks (F15): the run's own
+// worktree of the release, never the repository's tree.
+func (o *Ops) importsFile(dir string) string { return filepath.Join(dir, "ops_imports_"+o.Run+".tf") }
+
+// adopt records a resource tf reconcile found outside state (ADOPT) and
+// writes the root's import blocks, so the next tf ROOT PHASE imports it and
+// the normal plan, plan-check and apply (or destroy) path handles it.
+func (o *Ops) adopt(root, name, id string) error {
+ if err := o.jw("ADOPT", "%s %s", name, id); err != nil {
+ return err
+ }
+ if err := o.finding("tf reconcile: %s exists as %s outside state; adopted by an import block, removed by the next destroy", name, id); err != nil {
+ return err
+ }
+ return o.writeImports(root)
+}
+
+// pendingImports are root's adoptions not yet imported, address to ID.
+func (o *Ops) pendingImports(root string) ([][2]string, error) {
+ l, err := o.ledger()
+ if err != nil {
+ return nil, err
+ }
+ done := map[string]bool{}
+ var out [][2]string
+ for i := len(l.Entries) - 1; i >= 0; i-- {
+ e := l.Entries[i]
+ addr, ok := strings.CutPrefix(e.Field(0), root+"/")
+ if !ok || done[addr] {
+ continue
+ }
+ switch e.Verb {
+ case "IMPORTED":
+ done[addr] = true
+ case "ADOPT":
+ done[addr] = true
+ out = append(out, [2]string{addr, e.Field(1)})
+ }
+ }
+ return out, nil
+}
+
+func (o *Ops) writeImports(root string) error {
+ pend, err := o.pendingImports(root)
+ if err != nil {
+ return err
+ }
+ var b strings.Builder
+ b.WriteString("# Written by equipo-hosted-ops tf reconcile: resources this run created outside\n# OpenTofu's state, adopted here and imported by the next ops tf.\n")
+ for _, p := range pend {
+ fmt.Fprintf(&b, "\nimport {\n to = %s\n id = %q\n}\n", p[0], p[1])
+ }
+ return writeFileAtomic(o.importsFile(o.rootDir(root)), []byte(b.String()), 0o600)
+}
+
+// importAdopted imports each pending adoption into state with tofu import
+// (state only; no resource changes), then removes the import file before
+// the plan, so plan-check reads the release's root unchanged.
+func (o *Ops) importAdopted(root, dir, vars string) error {
+ pend, err := o.pendingImports(root)
+ if err != nil {
+ return err
+ }
+ for _, p := range pend {
+ if _, err := o.tofu("-chdir="+dir, "import", "-input=false", "-no-color", "-var-file="+vars, "-var=run="+o.Run, p[0], p[1]); err != nil {
+ return stopf("importing the adopted %s (%s) failed: %v", p[0], p[1], err)
+ }
+ if err := o.jw("IMPORTED", "%s/%s %s", root, p[0], p[1]); err != nil {
+ return err
+ }
+ }
+ if err := os.Remove(o.importsFile(dir)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return failf("%v", err)
+ }
+ return nil
+}
diff --git a/internal/hostedops/tfvars.go b/internal/hostedops/tfvars.go
index 3248cfb7..a8449428 100644
--- a/internal/hostedops/tfvars.go
+++ b/internal/hostedops/tfvars.go
@@ -38,6 +38,9 @@ var (
tagPattern = regexp.MustCompile(`^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$`)
)
+// networkCheckOutputs are the network root's outputs the 3.3 checks read.
+var networkCheckOutputs = []string{"vm_vpc_id", "vm_subnet_id", "vm_security_group_id", "services_route_table_id", "peering_id"}
+
// networkOutputs are the network root's outputs the services root takes.
var networkOutputs = []string{"services_vpc_id", "services_subnet_a_id", "services_subnet_b_id", "vm_vpc_id",
"vm_subnet_id", "vm_security_group_id", "peering_id", "services_route_table_id"}
@@ -56,9 +59,8 @@ func cmdTfvars(o *Ops, args []string) error {
certPub := fs.String("cert-pub", "", "Paul's certification public key (standard base64)")
addImage := fs.String("add-image", "", "img publish's -out file: adds the image map")
addConn := fs.Bool("add-connector", false, "add the connector's :1 ARN from the ledger")
- ami := fs.String("ami", "", "the hosts' AMI ID (not in the account plan; see the run kit report)")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("tfvars --out F --instance-host H --alert-email E --budget N --budget-action N --release TAG --keys DIR --cert-pub KEY | tfvars --add-image FILE --add-connector")
+ return usagef("tfvars --out F --instance-host H --alert-email E --budget N --budget-action N --release TAG --keys DIR --cert-pub KEY | tfvars --add-image FILE --add-connector")
}
if o.Account == "" || o.Region == "" {
return failf("tfvars needs -account and -region")
@@ -98,6 +100,11 @@ func cmdTfvars(o *Ops, args []string) error {
return err
}
vars["release"] = rel
+ ami, err := o.releaseAMI(*release)
+ if err != nil {
+ return err
+ }
+ vars["ami_id"] = ami
if err := o.jw("NOTE", "release %s", *release); err != nil {
return err
}
@@ -117,12 +124,6 @@ func cmdTfvars(o *Ops, args []string) error {
return err
}
}
- if *ami != "" {
- if !amiPattern.MatchString(*ami) {
- return failf("--ami %q is not an AMI ID", *ami)
- }
- vars["ami_id"] = *ami
- }
for _, k := range networkOutputs {
if v := o.output("network", k); v != "" {
if err := CheckValue(v, o.Account, o.Region, l.Owned); err != nil {
@@ -149,6 +150,9 @@ func cmdTfvars(o *Ops, args []string) error {
}
images[d] = im
vars["images"] = images
+ if err := o.jw("IMAGE-DIGEST", "%s %s", d, im["image_arn"]); err != nil {
+ return err
+ }
}
if _, ok := vars["images"]; !ok {
vars["images"] = map[string]any{}
@@ -244,6 +248,25 @@ func (o *Ops) releaseVars(tag string) (map[string]any, error) {
return r, nil
}
+// releaseAMI is the hosts' AMI the release manifest pins for the region
+// (HostAMI, from infra/hosted/release-pins.json): fix round 1, F10. A
+// release without one cannot be deployed.
+func (o *Ops) releaseAMI(tag string) (string, error) {
+ b, err := os.ReadFile(filepath.Join(o.Repo, "release", tag+".json"))
+ if err != nil {
+ return "", failf("the release manifest: %v", err)
+ }
+ var m struct{ HostAMI map[string]string }
+ if err := json.Unmarshal(b, &m); err != nil {
+ return "", failf("the release manifest does not read: %v", err)
+ }
+ ami := m.HostAMI[o.Region]
+ if !amiPattern.MatchString(ami) {
+ return "", failf("the release %s pins no host AMI for %s (HostAMI in infra/hosted/release-pins.json)", tag, o.Region)
+ }
+ return ami, nil
+}
+
// keyVars reads only *.pub files (1.2's keygen output).
func keyVars(dir string, vars map[string]any) error {
pub := func(name string) (string, error) {
diff --git a/internal/hostedops/units.go b/internal/hostedops/units.go
index f2b70a35..60ae62ad 100644
--- a/internal/hostedops/units.go
+++ b/internal/hostedops/units.go
@@ -56,12 +56,12 @@ esac > "$1"
func (o *Ops) unitName(block string) string { return o.unitPrefix() + block + ".service" }
-// busy lists the run's journalled units (other than except) that are not
-// done.
+// busy lists the run's journalled block units (other than except) that
+// are not done. A wait-human watchdog is not a block.
func (o *Ops) busy(l *Ledger, except string) []string {
var b []string
for _, u := range l.Units {
- if u == except {
+ if u == except || strings.HasPrefix(u, o.unitPrefix()+"wait-") || u == o.unitName("probe") {
continue
}
if s := o.Systemd.State(u); s != "done" {
@@ -73,9 +73,26 @@ func (o *Ops) busy(l *Ledger, except string) []string {
func cmdUnitStart(o *Ops, args []string) error {
if len(args) < 3 || args[1] != "--" || !blockPattern.MatchString(args[0]) {
- return failf("unit start BLOCK -- CMD...")
+ return usagef("unit start BLOCK -- CMD...")
}
- block, argv := args[0], args[2:]
+ l, err := o.ledger()
+ if err != nil {
+ return err
+ }
+ if b := o.busy(l, ""); len(b) > 0 {
+ return failf("REFUSED: a block is not finished: %s", strings.Join(b, ", "))
+ }
+ if err := o.startUnit(args[0], args[2:]); err != nil {
+ return err
+ }
+ o.out("block %s started as unit %s", args[0], o.unitName(args[0]))
+ return nil
+}
+
+// startUnit journals the unit's name, then runs argv as the transient user
+// unit for block, under /usr/bin/env -i with the allowlist and the unit's
+// own name (EQUIPO_HOSTED_OPS_UNIT, so a safe-stop inside it can spare it).
+func (o *Ops) startUnit(block string, argv []string) error {
if strings.ContainsAny(o.Dir, " \t\n\"'\\$") {
return failf("the run directory has characters a systemd command line could misread")
}
@@ -87,15 +104,11 @@ func cmdUnitStart(o *Ops, args []string) error {
if slices.Contains(l.Units, u) {
return failf("block %s was already started as %s", block, u)
}
- if b := o.busy(l, ""); len(b) > 0 {
- return failf("REFUSED: a block is not finished: %s", strings.Join(b, ", "))
- }
ep := o.path("bin", "exitpost.sh")
if err := writeFileAtomic(ep, []byte(exitPost), 0o755); err != nil {
return failf("%v", err)
}
- ud := o.path("units")
- if err := os.MkdirAll(ud, 0o700); err != nil {
+ if err := os.MkdirAll(o.path("units"), 0o700); err != nil {
return failf("%v", err)
}
full := []string{"/usr/bin/env", "-i"}
@@ -104,7 +117,7 @@ func cmdUnitStart(o *Ops, args []string) error {
full = append(full, v+"="+val)
}
}
- full = append(full, "EQUIPO_HOSTED_OPS_BLOCK="+block)
+ full = append(full, "EQUIPO_HOSTED_OPS_BLOCK="+block, "EQUIPO_HOSTED_OPS_UNIT="+u)
full = append(full, argv...)
if err := o.jw("UNIT", "%s", u); err != nil { // journalled before systemd-run (R45)
return err
@@ -115,21 +128,35 @@ func cmdUnitStart(o *Ops, args []string) error {
if err := o.Systemd.Start(u, o.Dir, o.path("units", block+".out"), o.path("units", block+".status"), ep, full); err != nil {
return failf("systemd-run could not start %s: %v", u, err)
}
- o.out("block %s started as unit %s", block, u)
return nil
}
-// cmdUnitWait waits for a unit within one call's limit (--call-max, 540 s,
-// under the agent's 10-minute tool limit). Finished with status 0: exit 0.
-// Finished otherwise, or stopped at --max (killed): exit 1. Its state
-// unresolved: 99. Still running inside its bound: exit 3, call again.
+// selfArgv is this binary with the invocation's global flags, for a unit
+// that runs ops itself (the wait-human watchdog).
+func (o *Ops) selfArgv(args ...string) []string {
+ argv := []string{o.Self, "-dir", o.Dir, "-run", o.Run}
+ for _, f := range [][2]string{{"-profile", o.Profile}, {"-account", o.Account}, {"-region", o.Region}, {"-role", o.Role}, {"-repo", o.Repo}} {
+ if f[1] != "" {
+ argv = append(argv, f[0], f[1])
+ }
+ }
+ return append(argv, args...)
+}
+
+// cmdUnitWait waits for a required unit until it is done or its bound
+// passes (fix round 1, F1: no early return). Finished with status 0: exit
+// 0. Finished otherwise, or past --max (the unit is stopped): safe-stop
+// runs and the exit is 99, as for any required step. A state that cannot
+// be established is 99 likewise.
func cmdUnitWait(o *Ops, args []string) error {
fs := flag.NewFlagSet("unit wait", flag.ContinueOnError)
maxD := fs.Duration("max", 0, "the block's bound from its start")
- callMax := fs.Duration("call-max", 540*time.Second, "how long this call may wait")
pos, err := parseFlags(fs, args)
- if err != nil || len(pos) != 1 || *maxD <= 0 {
- return failf("unit wait BLOCK --max D")
+ if err != nil {
+ return err
+ }
+ if len(pos) != 1 || *maxD <= 0 {
+ return usagef("unit wait BLOCK --max D")
}
block := pos[0]
l, err := o.ledger()
@@ -146,39 +173,39 @@ func cmdUnitWait(o *Ops, args []string) error {
}
sec, _ := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64)
start := time.Unix(sec, 0)
- callEnd := o.Clock.Now().Add(*callMax)
- over := func() bool { return !o.Clock.Now().Before(start.Add(*maxD)) }
+ hard := func(why string) error {
+ _ = o.jw("ABORT", "unit %s: %s", u, why)
+ o.out("ABORT: block %s: %s; running safe-stop", block, why)
+ if err := o.safeStop(); err != nil {
+ o.out("safe-stop: %v", err)
+ }
+ return stopf("block %s: %s", block, why)
+ }
for {
- s := o.Systemd.State(u)
- switch s {
+ switch o.Systemd.State(u) {
case "done":
st, _ := os.ReadFile(o.path("units", block+".status"))
status := strings.TrimSpace(string(st))
_ = o.jw("UNIT-DONE", "%s status=%s", u, status)
o.out("block %s finished: exit status %s", block, status)
if status != "0" {
- return failf("block %s failed: exit status %s", block, status)
+ return hard("exit status " + status)
}
return nil
case "unresolved":
- _ = o.jw("ABORT", "unit %s unresolved", u)
- return stopf("the state of unit %s cannot be established; run safe-stop", u)
+ return hard("its state cannot be established")
}
- if over() {
+ if !o.Clock.Now().Before(start.Add(*maxD)) {
if err := o.Systemd.Stop(u); err != nil {
_ = writeFileAtomic(o.path("units", block+".status"), []byte("unresolved\n"), 0o600)
- return stopf("block %s ran past its %s bound and unit %s was not proved stopped", block, *maxD, u)
+ return hard(fmt.Sprintf("past its %s bound and not proved stopped", *maxD))
}
_ = writeFileAtomic(o.path("units", block+".status"), []byte("killed\n"), 0o600)
_ = o.jw("UNIT-KILLED", "%s past %s", u, *maxD)
- return failf("block %s ran past its %s bound; unit %s stopped", block, *maxD, u)
- }
- if !o.Clock.Now().Add(5 * time.Second).Before(callEnd) {
- o.out("block %s still running after %s; call again", block, o.Clock.Now().Sub(start).Round(time.Second))
- return &exitError{code: ExitRunning, msg: "RUNNING: call unit wait again"}
+ return hard(fmt.Sprintf("past its %s bound; stopped", *maxD))
}
if err := o.Clock.Sleep(o.ctx, 5*time.Second); err != nil {
- return failf("interrupted: %v", err)
+ return hard("the wait was interrupted")
}
}
}
@@ -192,10 +219,17 @@ func (o *Ops) stopUnits(only string) error {
return err
}
var failed []string
+ own := os.Getenv("EQUIPO_HOSTED_OPS_UNIT")
for _, u := range l.Units {
if only != "" && u != only {
continue
}
+ if u == own { // never the unit this process runs in (F2); it ends when this does
+ if err := o.jw("UNIT-SPARED", "%s: this process runs in it", u); err != nil {
+ return err
+ }
+ continue
+ }
if o.Systemd.State(u) == "done" {
continue
}
@@ -233,7 +267,7 @@ func cmdUnitStop(o *Ops, args []string) error {
case len(args) == 1 && blockPattern.MatchString(args[0]):
return o.stopUnits(o.unitName(args[0]))
}
- return failf("unit stop BLOCK | --all")
+ return usagef("unit stop BLOCK | --all")
}
// ---- the real user manager --------------------------------------------
@@ -339,3 +373,67 @@ func (realSystemd) List(prefix string) ([]string, error) {
}
return out, nil
}
+
+// cmdUnitProbe is Task 17b's unit_probe, ported: start the run's probe unit
+// (it writes its environment to a file, then sleeps), see it running,
+// check that its environment holds only allowlisted names and no
+// credential, stop it, and see it end by TERM. Run it once before the
+// first long block (account plan 0.2).
+func cmdUnitProbe(o *Ops, args []string) error {
+ if len(args) != 0 {
+ return usagef("unit probe takes no arguments")
+ }
+ l, err := o.ledger()
+ if err != nil {
+ return err
+ }
+ block := "probe"
+ for n := 2; slices.Contains(l.Units, o.unitName(block)); n++ {
+ block = fmt.Sprintf("probe-%d", n)
+ }
+ u := o.unitName(block)
+ envFile := o.path("units", block+".env")
+ _ = os.Remove(envFile)
+ if err := o.startUnit(block, []string{"/bin/sh", "-c", `env > "$0"; exec sleep 60`, envFile}); err != nil {
+ return err
+ }
+ fail := func(why string) error {
+ _ = o.Systemd.Stop(u)
+ _ = o.jw("ABORT", "unit probe: %s", why)
+ return stopf("the unit probe failed: %s", why)
+ }
+ var env []byte
+ for i := 0; i < 20; i++ {
+ if o.Systemd.State(u) == "running" {
+ if env, err = os.ReadFile(envFile); err == nil && len(env) > 0 {
+ break
+ }
+ }
+ if err := o.Clock.Sleep(o.ctx, 250*time.Millisecond); err != nil {
+ return fail("interrupted")
+ }
+ }
+ if len(env) == 0 {
+ return fail("the probe unit did not run and record its environment")
+ }
+ allowed := append(append([]string{}, UnitEnv...), "PWD", "SHLVL", "_", "EQUIPO_HOSTED_OPS_BLOCK", "EQUIPO_HOSTED_OPS_UNIT")
+ for _, line := range strings.Split(strings.TrimSpace(string(env)), "\n") {
+ n, _, _ := strings.Cut(line, "=")
+ up := strings.ToUpper(n)
+ if strings.HasPrefix(up, "AWS_") || strings.Contains(up, "SECRET") || strings.Contains(up, "TOKEN") || strings.Contains(up, "PASSWORD") {
+ return fail(n + " reached the unit")
+ }
+ if !slices.Contains(allowed, n) {
+ return fail(n + " is not on the allowlist")
+ }
+ }
+ if err := o.stopUnits(u); err != nil {
+ return fail("not proved stopped: " + err.Error())
+ }
+ st, _ := os.ReadFile(o.path("units", block+".status"))
+ if strings.TrimSpace(string(st)) != "signal:TERM" {
+ return fail("its exit status is " + strings.TrimSpace(string(st)) + ", not signal:TERM")
+ }
+ o.out("unit probe: %s ran with only allowlisted names and stopped by TERM", u)
+ return o.jw("UNIT-PROBE", "ok %s", u)
+}
diff --git a/internal/hostedops/vms.go b/internal/hostedops/vms.go
index e22aac96..92bb779c 100644
--- a/internal/hostedops/vms.go
+++ b/internal/hostedops/vms.go
@@ -55,8 +55,9 @@ func (o *Ops) runImage(l *Ledger, image string) error {
func cmdVMsScan(o *Ops, args []string) error {
fs := flag.NewFlagSet("vms scan", flag.ContinueOnError)
image := imageFlag(fs)
- if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("vms scan --image ARN")
+ maxD := fs.Duration("max", 0, "how long an incomplete scan may be retried (0: one attempt)")
+ if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 || *maxD < 0 || *maxD > MaxSettle {
+ return usagef("vms scan --image ARN [--max D]")
}
l, err := o.ledger()
if err != nil {
@@ -65,9 +66,19 @@ func cmdVMsScan(o *Ops, args []string) error {
if err := o.runImage(l, *image); err != nil {
return err
}
+ end := o.Clock.Now().Add(*maxD)
vms, err := o.cloud.ListVMs(o.ctx, *image)
- if err != nil {
- return stopf("the VM scan is incomplete: %v", err)
+ for err != nil {
+ if !o.Clock.Now().Add(15 * time.Second).Before(end) {
+ return stopf("the VM scan is incomplete: %v", err)
+ }
+ if ferr := o.finding("vms scan: incomplete (%v); scanning again", err); ferr != nil {
+ return ferr
+ }
+ if serr := o.Clock.Sleep(o.ctx, 15*time.Second); serr != nil {
+ return stopf("the VM scan is incomplete: interrupted")
+ }
+ vms, err = o.cloud.ListVMs(o.ctx, *image)
}
if err := o.recordVMs(l, vms, "scan"); err != nil {
return err
@@ -213,7 +224,7 @@ func cmdVMsSettle(o *Ops, args []string) error {
terminate := fs.Bool("terminate", false, "terminate every target and live VM first")
maxD := fs.Duration("max", defaultSettle, "the bound")
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("vms settle --image ARN [--terminate] --max D")
+ return usagef("vms settle --image ARN [--terminate] --max D")
}
if *maxD <= 0 || *maxD > MaxSettle {
return failf("--max must be positive and at most %s", MaxSettle)
@@ -261,7 +272,7 @@ func (o *Ops) settleImage(image string, terminate bool, maxD time.Duration) erro
// repeat done); that is what resolves it.
func cmdVMsReconcile(o *Ops, args []string) error {
if len(args) != 0 {
- return failf("vms reconcile takes no arguments")
+ return usagef("vms reconcile takes no arguments")
}
l, err := o.ledger()
if err != nil {
@@ -306,7 +317,7 @@ func cmdVMsAdopt(o *Ops, args []string) error {
fs := flag.NewFlagSet("vms adopt", flag.ContinueOnError)
ca := controllerFlags(fs)
if pos, err := parseFlags(fs, args); err != nil || len(pos) != 0 {
- return failf("vms adopt [controller flags]")
+ return usagef("vms adopt [controller flags]")
}
cl, err := o.controller(ca)
if err != nil {
diff --git a/internal/isolatedjob/awsjob/opsaws/clients.go b/internal/isolatedjob/awsjob/opsaws/clients.go
index f6334cc6..a1e6a09e 100644
--- a/internal/isolatedjob/awsjob/opsaws/clients.go
+++ b/internal/isolatedjob/awsjob/opsaws/clients.go
@@ -8,6 +8,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/budgets"
"github.com/aws/aws-sdk-go-v2/service/cloudtrail"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/aws/aws-sdk-go-v2/service/lambdacore"
@@ -33,6 +34,7 @@ type clients struct {
budgets *budgets.Client
sns *sns.Client
cw *cloudwatch.Client
+ logs *cloudwatchlogs.Client
quotas *servicequotas.Client
tags *tagging.Client
}
@@ -99,6 +101,11 @@ func newClients(cfg aws.Config, region string, timeout time.Duration) clients {
o.EndpointResolverV2, o.Retryer, o.RetryMaxAttempts = cloudwatch.NewDefaultEndpointResolverV2(), aws.NopRetryer{}, 1
o.APIOptions = append(o.APIOptions, d)
}),
+ logs: cloudwatchlogs.NewFromConfig(cfg, func(o *cloudwatchlogs.Options) {
+ o.Region, o.BaseEndpoint, o.EndpointOptions = region, nil, cloudwatchlogs.EndpointResolverOptions{}
+ o.EndpointResolverV2, o.Retryer, o.RetryMaxAttempts = cloudwatchlogs.NewDefaultEndpointResolverV2(), aws.NopRetryer{}, 1
+ o.APIOptions = append(o.APIOptions, d)
+ }),
quotas: servicequotas.NewFromConfig(cfg, func(o *servicequotas.Options) {
o.Region, o.BaseEndpoint, o.EndpointOptions = region, nil, servicequotas.EndpointResolverOptions{}
o.EndpointResolverV2, o.Retryer, o.RetryMaxAttempts = servicequotas.NewDefaultEndpointResolverV2(), aws.NopRetryer{}, 1
@@ -112,11 +119,17 @@ func newClients(cfg aws.Config, region string, timeout time.Duration) clients {
}
}
-// deadlineEach bounds each whole call, first in the stack.
+// deadlineEach bounds each whole call, first in the stack. A call whose
+// answer is a stream (GetObject) is bounded by its caller instead, through
+// the body's read and close (F17): cancelling here, as the call returns,
+// would cut the body off unread.
func deadlineEach(timeout time.Duration) func(*middleware.Stack) error {
return func(s *middleware.Stack) error {
return s.Initialize.Add(middleware.InitializeMiddlewareFunc("OpsawsCallDeadline",
func(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (middleware.InitializeOutput, middleware.Metadata, error) {
+ if _, streamed := in.Parameters.(*s3.GetObjectInput); streamed {
+ return next.HandleInitialize(ctx, in)
+ }
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return next.HandleInitialize(ctx, in)
diff --git a/internal/isolatedjob/awsjob/opsaws/cloud.go b/internal/isolatedjob/awsjob/opsaws/cloud.go
index 60c7e0e2..3f0ff36a 100644
--- a/internal/isolatedjob/awsjob/opsaws/cloud.go
+++ b/internal/isolatedjob/awsjob/opsaws/cloud.go
@@ -43,6 +43,8 @@ type cloud struct {
id hostedops.Identity
keys hostedops.Keys
now func() time.Time
+ // timeout bounds each call; GetObject applies it through the read.
+ timeout time.Duration
}
var notFoundCodes = []string{"ResourceNotFoundException", "NotFound", "NoSuchBucket", "NoSuchKey", "NoSuchEntity",
@@ -399,6 +401,8 @@ func (c *cloud) HeadObject(ctx context.Context, bucket, owner, key string) (stri
}
func (c *cloud) GetObject(ctx context.Context, bucket, owner, key string) ([]byte, error) {
+ ctx, cancel := context.WithTimeout(ctx, c.timeout) // through the body's read and close (F17)
+ defer cancel()
r, err := c.cl.s3.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), ExpectedBucketOwner: aws.String(owner)})
if err != nil {
return nil, wrap("GetObject", err)
diff --git a/internal/isolatedjob/awsjob/opsaws/fix1_test.go b/internal/isolatedjob/awsjob/opsaws/fix1_test.go
new file mode 100644
index 00000000..b9cee497
--- /dev/null
+++ b/internal/isolatedjob/awsjob/opsaws/fix1_test.go
@@ -0,0 +1,441 @@
+package opsaws
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "slices"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/hostedops"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/budgets"
+ budgettypes "github.com/aws/aws-sdk-go-v2/service/budgets/types"
+ "github.com/aws/aws-sdk-go-v2/service/cloudtrail"
+ trailtypes "github.com/aws/aws-sdk-go-v2/service/cloudtrail/types"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch"
+ cwtypes "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
+ logtypes "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
+ "github.com/aws/aws-sdk-go-v2/service/ec2"
+ ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/aws/aws-sdk-go-v2/service/iam"
+ iamtypes "github.com/aws/aws-sdk-go-v2/service/iam/types"
+ "github.com/aws/aws-sdk-go-v2/service/lambdacore"
+ coretypes "github.com/aws/aws-sdk-go-v2/service/lambdacore/types"
+ vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ vmtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/aws/aws-sdk-go-v2/service/servicequotas"
+ sqtypes "github.com/aws/aws-sdk-go-v2/service/servicequotas/types"
+ "github.com/aws/aws-sdk-go-v2/service/sns"
+ snstypes "github.com/aws/aws-sdk-go-v2/service/sns/types"
+ "github.com/aws/smithy-go"
+)
+
+// openFake opens a verified cloud on the fake with handler h.
+func openFake(t *testing.T, h func(c call) (any, error)) (*cloud, *fakeAWS) {
+ t.Helper()
+ f := newFake(t)
+ f.accounts["AKIDGOOD"] = bringup(prod)
+ f.handle = h
+ cl, err := f.opener(prodCLI("AKIDGOOD")).Open(context.Background(), target)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return cl.(*cloud), f
+}
+
+func filters(fs []ec2types.Filter) map[string]string {
+ m := map[string]string{}
+ for _, f := range fs {
+ m[aws.ToString(f.Name)] = strings.Join(f.Values, ",")
+ }
+ return m
+}
+
+func tagged(name, run string) []ec2types.Tag {
+ return []ec2types.Tag{{Key: aws.String("Name"), Value: aws.String(name)}, {Key: aws.String("run"), Value: aws.String(run)}}
+}
+
+// F3: an EC2 lookup filters by the intent's Name tag, run tag and parent,
+// reads every page, and tells two resources of one type apart; with no Name
+// tag it is not definitive and makes no call.
+func TestLookupMatchesIdentity(t *testing.T) {
+ vpcs := map[string]string{"vpc-0vm": "equipo-hosted-vm", "vpc-0svc": "equipo-hosted-services"}
+ var seen []map[string]string
+ cl, f := openFake(t, func(c call) (any, error) {
+ in, ok := c.In.(*ec2.DescribeVpcsInput)
+ if !ok {
+ t.Errorf("the lookup called %s, not DescribeVpcs", c.Op)
+ return nil, errors.New("unexpected")
+ }
+ fl := filters(in.Filters)
+ seen = append(seen, fl)
+ // One VPC per page, filtered server-side as EC2 does.
+ var ids []string
+ for id := range vpcs {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ page := 0
+ fmt.Sscanf(aws.ToString(in.NextToken), "p%d", &page)
+ out := &ec2.DescribeVpcsOutput{}
+ if page < len(ids) {
+ id := ids[page]
+ if fl["tag:Name"] == vpcs[id] && fl["tag:run"] == "r1" {
+ out.Vpcs = []ec2types.Vpc{{VpcId: aws.String(id), Tags: tagged(vpcs[id], "r1")}}
+ }
+ if page+1 < len(ids) {
+ out.NextToken = aws.String(fmt.Sprintf("p%d", page+1))
+ }
+ }
+ return out, nil
+ })
+ ctx := context.Background()
+ res, err := cl.Lookup(ctx, hostedops.LookupKey{Type: "aws_vpc", NameTag: "equipo-hosted-vm", Run: "r1"})
+ if err != nil || !slices.Equal(res.IDs, []string{"vpc-0vm"}) || !res.Definitive {
+ t.Fatalf("lookup of the VM VPC = %+v, %v; want only vpc-0vm (on a later page)", res, err)
+ }
+ if fl := seen[0]; fl["tag:Name"] != "equipo-hosted-vm" || fl["tag:run"] != "r1" {
+ t.Fatalf("filters %v", fl)
+ }
+ delete(vpcs, "vpc-0vm") // partial creation: only the services VPC exists
+ if res, err := cl.Lookup(ctx, hostedops.LookupKey{Type: "aws_vpc", NameTag: "equipo-hosted-vm", Run: "r1"}); err != nil || len(res.IDs) != 0 || !res.Definitive {
+ t.Fatalf("lookup after a partial creation = %+v, %v; want a definitive miss", res, err)
+ }
+ before := len(f.ops())
+ if res, _ := cl.Lookup(ctx, hostedops.LookupKey{Type: "aws_vpc", Run: "r1"}); res.Definitive || len(res.IDs) != 0 {
+ t.Fatalf("a lookup with no Name tag = %+v; want not definitive", res)
+ }
+ if len(f.ops()) != before {
+ t.Fatal("a lookup with no identity made a call")
+ }
+}
+
+// F3: the parent ID filters a subnet lookup.
+func TestLookupFiltersByParent(t *testing.T) {
+ var got map[string]string
+ cl, _ := openFake(t, func(c call) (any, error) {
+ in, ok := c.In.(*ec2.DescribeSubnetsInput)
+ if !ok {
+ t.Errorf("the lookup called %s, not DescribeSubnets", c.Op)
+ return nil, errors.New("unexpected")
+ }
+ got = filters(in.Filters)
+ return &ec2.DescribeSubnetsOutput{Subnets: []ec2types.Subnet{{SubnetId: aws.String("subnet-0vm")}}}, nil
+ })
+ res, err := cl.Lookup(context.Background(), hostedops.LookupKey{Type: "aws_subnet", NameTag: "equipo-hosted-vm", Run: "r1", Parent: "vpc-0vm"})
+ if err != nil || len(res.IDs) != 1 || got["vpc-id"] != "vpc-0vm" {
+ t.Fatalf("subnet lookup %+v %v with filters %v", res, err, got)
+ }
+}
+
+// F4: the build log group is read directly, by exact name over every page.
+func TestLookupLogGroup(t *testing.T) {
+ const name = "/aws/lambda-microvms/equipo-hosted-image-build"
+ cl, _ := openFake(t, func(c call) (any, error) {
+ in, ok := c.In.(*cloudwatchlogs.DescribeLogGroupsInput)
+ if !ok {
+ t.Errorf("the lookup called %s", c.Op)
+ return nil, errors.New("unexpected")
+ }
+ if aws.ToString(in.LogGroupNamePrefix) != name {
+ t.Errorf("prefix %q", aws.ToString(in.LogGroupNamePrefix))
+ }
+ if in.NextToken == nil {
+ return &cloudwatchlogs.DescribeLogGroupsOutput{LogGroups: []logtypes.LogGroup{{LogGroupName: aws.String(name + "-other")}}, NextToken: aws.String("p2")}, nil
+ }
+ return &cloudwatchlogs.DescribeLogGroupsOutput{LogGroups: []logtypes.LogGroup{{LogGroupName: aws.String(name)}}}, nil
+ })
+ res, err := cl.Lookup(context.Background(), hostedops.LookupKey{Type: "aws_cloudwatch_log_group", ID: name})
+ if err != nil || !res.Definitive || !slices.Equal(res.IDs, []string{name}) {
+ t.Fatalf("log group lookup = %+v, %v", res, err)
+ }
+}
+
+// F6: the role the run first verified is bound; a later invocation whose
+// profile and keys both name another role in the same account is refused.
+func TestGuardBindsFirstRole(t *testing.T) {
+ f := newFake(t)
+ f.accounts["AKIDGOOD"] = bringup(prod)
+ f.accounts["AKIDADMIN"] = "arn:aws:sts::" + prod + ":assumed-role/Admin/equipo-hosted-bringup"
+ dir := newRun(t)
+ c := prodCLI("AKIDGOOD")
+ if code, out := runOps(t, f, c, dir, "guard"); code != 0 {
+ t.Fatalf("first guard = %d: %s", code, out)
+ }
+ c.settings["role_arn"] = "arn:aws:iam::" + prod + ":role/Admin"
+ c.key = "AKIDADMIN"
+ if code, out := runOps(t, f, c, dir, "guard"); code != hostedops.ExitStop {
+ t.Fatalf("a guard under another role = %d: %s; want 99", code, out)
+ }
+}
+
+// ctxBody fails a read once the request's context has ended.
+type ctxBody struct {
+ ctx context.Context
+ left int
+}
+
+func (b *ctxBody) Read(p []byte) (int, error) {
+ if err := b.ctx.Err(); err != nil {
+ return 0, err
+ }
+ if b.left == 0 {
+ return 0, io.EOF
+ }
+ b.left--
+ p[0] = 'x'
+ return 1, nil
+}
+func (b *ctxBody) Close() error { return nil }
+
+// F17: GetObject's deadline lasts until its body is read and closed.
+func TestGetObjectReadsWithinDeadline(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ return &s3.GetObjectOutput{Body: &ctxBody{ctx: c.Ctx, left: 5}}, nil
+ })
+ b, err := cl.GetObject(context.Background(), "equipo-hosted-trail-"+prod, prod, "k")
+ if err != nil || string(b) != "xxxxx" {
+ t.Fatalf("GetObject = %q, %v; want the whole body", b, err)
+ }
+}
+
+// The SDK calls' request shapes and pagination (Network, Trail, Inventory,
+// Quotas, alarms, SNS, the connector, IAM, MicroVMs, Lookup).
+func TestSDKRequestShapes(t *testing.T) {
+ ctx := context.Background()
+ t.Run("network", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *ec2.DescribeVpcAttributeInput:
+ if aws.ToString(in.VpcId) != "vpc-0vm" {
+ t.Errorf("vpc %s", aws.ToString(in.VpcId))
+ }
+ f := &ec2types.AttributeBooleanValue{Value: aws.Bool(false)}
+ return &ec2.DescribeVpcAttributeOutput{EnableDnsSupport: f, EnableDnsHostnames: f}, nil
+ case *ec2.DescribeRouteTablesInput:
+ fl := filters(in.Filters)
+ if fl["association.subnet-id"] == "subnet-0vm" {
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{{Routes: []ec2types.Route{
+ {DestinationCidrBlock: aws.String("10.43.0.0/16"), GatewayId: aws.String("local")},
+ {DestinationCidrBlock: aws.String("10.42.1.10/32"), VpcPeeringConnectionId: aws.String("pcx-1")}}}}}, nil
+ }
+ if fl["route-table-id"] != "rtb-svc" {
+ t.Errorf("route table filters %v", fl)
+ }
+ return &ec2.DescribeRouteTablesOutput{RouteTables: []ec2types.RouteTable{{Routes: []ec2types.Route{
+ {DestinationCidrBlock: aws.String("10.43.1.0/24"), VpcPeeringConnectionId: aws.String("pcx-1")}}}}}, nil
+ case *ec2.DescribeSecurityGroupRulesInput:
+ if filters(in.Filters)["group-id"] != "sg-0vm" {
+ t.Errorf("sg filters %v", filters(in.Filters))
+ }
+ return &ec2.DescribeSecurityGroupRulesOutput{SecurityGroupRules: []ec2types.SecurityGroupRule{{IsEgress: aws.Bool(true),
+ IpProtocol: aws.String("tcp"), FromPort: aws.Int32(8443), ToPort: aws.Int32(8443), CidrIpv4: aws.String("10.42.1.10/32")}}}, nil
+ case *ec2.DescribeVpcPeeringConnectionsInput:
+ return &ec2.DescribeVpcPeeringConnectionsOutput{VpcPeeringConnections: []ec2types.VpcPeeringConnection{{
+ Status: &ec2types.VpcPeeringConnectionStateReason{Code: ec2types.VpcPeeringConnectionStateReasonCodeActive}}}}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ nf, err := cl.Network(ctx, hostedops.NetworkIDs{VMVPC: "vpc-0vm", VMSubnet: "subnet-0vm", VMSecurityGroup: "sg-0vm", ServicesRouteTable: "rtb-svc", Peering: "pcx-1"})
+ if err != nil || nf.DNSSupport || len(nf.VMRoutes) != 2 || nf.VMRoutes[1] != (hostedops.Route{Destination: "10.42.1.10/32", Target: "pcx-1"}) ||
+ len(nf.VMSGRules) != 1 || nf.PeeringState != "active" || nf.ServicesRoutes[0].Target != "pcx-1" {
+ t.Fatalf("network facts %+v, %v", nf, err)
+ }
+ })
+ t.Run("trail", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch c.In.(type) {
+ case *cloudtrail.GetTrailStatusInput:
+ return &cloudtrail.GetTrailStatusOutput{IsLogging: aws.Bool(true)}, nil
+ case *cloudtrail.GetEventSelectorsInput:
+ return &cloudtrail.GetEventSelectorsOutput{AdvancedEventSelectors: []trailtypes.AdvancedEventSelector{
+ {FieldSelectors: []trailtypes.AdvancedFieldSelector{{Field: aws.String("eventCategory"), Equals: []string{"Management"}}}},
+ {FieldSelectors: []trailtypes.AdvancedFieldSelector{{Field: aws.String("eventCategory"), Equals: []string{"Data"}},
+ {Field: aws.String("resources.type"), Equals: []string{"AWS::Lambda::MicrovmImage"}},
+ {Field: aws.String("resources.ARN"), StartsWith: []string{"arn:aws:lambda:eu-west-1:" + prod + ":"}}}}}}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ ts, err := cl.Trail(ctx, "equipo-hosted")
+ if err != nil || !ts.Logging || !ts.ManagementSelector || !slices.Equal(ts.DataSelectorPrefixes, []string{"arn:aws:lambda:eu-west-1:" + prod + ":"}) {
+ t.Fatalf("trail %+v, %v", ts, err)
+ }
+ })
+ t.Run("inventory pages", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *ec2.DescribeVpcsInput:
+ if filters(in.Filters)["is-default"] != "false" {
+ t.Errorf("vpc filters %v", filters(in.Filters))
+ }
+ if in.NextToken == nil {
+ return &ec2.DescribeVpcsOutput{Vpcs: make([]ec2types.Vpc, 1), NextToken: aws.String("2")}, nil
+ }
+ return &ec2.DescribeVpcsOutput{Vpcs: make([]ec2types.Vpc, 2)}, nil
+ case *ec2.DescribeInstancesInput:
+ if in.NextToken == nil {
+ return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{Instances: make([]ec2types.Instance, 1)}}, NextToken: aws.String("2")}, nil
+ }
+ return &ec2.DescribeInstancesOutput{Reservations: []ec2types.Reservation{{Instances: make([]ec2types.Instance, 1)}}}, nil
+ case *s3.ListBucketsInput:
+ return &s3.ListBucketsOutput{}, nil
+ case *cloudtrail.DescribeTrailsInput:
+ return &cloudtrail.DescribeTrailsOutput{}, nil
+ case *budgets.DescribeBudgetsInput:
+ return nil, &smithy.GenericAPIError{Code: "AccessDeniedException", Message: "no"}
+ case *iam.ListRolesInput:
+ if in.Marker == nil {
+ return &iam.ListRolesOutput{Roles: []iamtypes.Role{{RoleName: aws.String("other")}}, IsTruncated: true, Marker: aws.String("m")}, nil
+ }
+ return &iam.ListRolesOutput{Roles: []iamtypes.Role{{RoleName: aws.String("equipo-hosted-controller")}}}, nil
+ case *vms.ListMicrovmImagesInput:
+ if in.NextToken == nil {
+ return &vms.ListMicrovmImagesOutput{Items: []vmtypes.MicrovmImageSummary{{Name: aws.String("x")}}, NextToken: aws.String("2")}, nil
+ }
+ return &vms.ListMicrovmImagesOutput{Items: []vmtypes.MicrovmImageSummary{{Name: aws.String("equipo-hosted-prod-old")}}}, nil
+ case *ec2.GetEbsEncryptionByDefaultInput:
+ return &ec2.GetEbsEncryptionByDefaultOutput{EbsEncryptionByDefault: aws.Bool(true)}, nil
+ }
+ if c.Op == "GetPublicAccessBlock" {
+ return nil, &smithy.GenericAPIError{Code: "NoSuchPublicAccessBlockConfiguration"}
+ }
+ return nil, fmt.Errorf("unexpected %s.%s", c.Service, c.Op)
+ })
+ inv, err := cl.Inventory(ctx)
+ if err != nil || inv.NonDefaultVPCs != 3 || inv.Instances != 2 || inv.BudgetsUnreadable == "" || !slices.Equal(inv.Roles, []string{"equipo-hosted-controller"}) ||
+ inv.MicroVMImages != 2 || !slices.Equal(inv.ImageNames, []string{"equipo-hosted-prod-old"}) || inv.AccountPublicBlock.Set || !inv.EBSDefaultEncryption {
+ t.Fatalf("inventory %+v, %v", inv, err)
+ }
+ })
+ t.Run("quotas pages", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *servicequotas.ListServicesInput:
+ if in.NextToken == nil {
+ return &servicequotas.ListServicesOutput{Services: []sqtypes.ServiceInfo{{ServiceCode: aws.String("ec2"), ServiceName: aws.String("EC2")}}, NextToken: aws.String("2")}, nil
+ }
+ return &servicequotas.ListServicesOutput{Services: []sqtypes.ServiceInfo{{ServiceCode: aws.String("lambda"), ServiceName: aws.String("AWS Lambda")}}}, nil
+ case *servicequotas.ListServiceQuotasInput:
+ if aws.ToString(in.ServiceCode) != "lambda" {
+ t.Errorf("quotas of %s", aws.ToString(in.ServiceCode))
+ }
+ if in.NextToken == nil {
+ return &servicequotas.ListServiceQuotasOutput{Quotas: []sqtypes.ServiceQuota{{QuotaName: aws.String("Concurrent executions")}}, NextToken: aws.String("2")}, nil
+ }
+ return &servicequotas.ListServiceQuotasOutput{Quotas: []sqtypes.ServiceQuota{{QuotaName: aws.String("MicroVM memory"), Value: aws.Float64(64), Unit: aws.String("GB")}}}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ qs, err := cl.Quotas(ctx)
+ if err != nil || len(qs) != 1 || qs[0].Name != "MicroVM memory" || qs[0].Value != 64 {
+ t.Fatalf("quotas %+v, %v", qs, err)
+ }
+ })
+ t.Run("alarms and subscriptions", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *cloudwatch.DescribeAlarmsInput:
+ if !slices.Equal(in.AlarmNames, []string{"a", "b"}) {
+ t.Errorf("alarm names %v", in.AlarmNames)
+ }
+ return &cloudwatch.DescribeAlarmsOutput{MetricAlarms: []cwtypes.MetricAlarm{{AlarmName: aws.String("a"), StateValue: cwtypes.StateValueOk}}}, nil
+ case *sns.ListSubscriptionsByTopicInput:
+ if in.NextToken == nil {
+ return &sns.ListSubscriptionsByTopicOutput{Subscriptions: []snstypes.Subscription{{SubscriptionArn: aws.String("PendingConfirmation")}}, NextToken: aws.String("2")}, nil
+ }
+ return &sns.ListSubscriptionsByTopicOutput{Subscriptions: []snstypes.Subscription{{SubscriptionArn: aws.String("arn:aws:sns:eu-west-1:" + prod + ":t:1")}}}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ st, err := cl.AlarmStates(ctx, []string{"a", "b"})
+ if err != nil || st["a"] != "OK" || st["b"] != "" {
+ t.Fatalf("alarms %v %v", st, err)
+ }
+ if c, p, err := cl.SubscriptionsConfirmed(ctx, "arn:aws:sns:eu-west-1:"+prod+":t"); err != nil || c != 1 || p != 1 {
+ t.Fatalf("subscriptions %d confirmed, %d pending, %v", c, p, err)
+ }
+ })
+ t.Run("connector", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *lambdacore.CreateNetworkConnectorInput:
+ v, ok := in.Configuration.(*coretypes.NetworkConnectorConfigurationMemberVpcEgressConfiguration)
+ if !ok || !slices.Equal(v.Value.SubnetIds, []string{"subnet-0vm"}) || !slices.Equal(v.Value.SecurityGroupIds, []string{"sg-0vm"}) ||
+ v.Value.ElasticIpConfiguration != nil || aws.ToString(in.ClientToken) != "tok" || in.Tags["run"] != "r1" ||
+ !slices.Equal(v.Value.AssociatedComputeResourceTypes, []coretypes.ComputeResourceType{coretypes.ComputeResourceTypeMicroVm}) {
+ t.Errorf("create input %+v", in)
+ }
+ return &lambdacore.CreateNetworkConnectorOutput{Arn: aws.String("arn:c"), Id: aws.String("nc-1"), State: coretypes.NetworkConnectorStatePending}, nil
+ case *lambdacore.GetNetworkConnectorInput:
+ return &lambdacore.GetNetworkConnectorOutput{Arn: aws.String("arn:c"), Version: aws.Int64(1), VersionArn: aws.String("arn:c:1"), State: coretypes.NetworkConnectorStateActive,
+ Configuration: &coretypes.NetworkConnectorConfigurationMemberVpcEgressConfiguration{Value: coretypes.NetworkConnectorVpcEgressConfiguration{
+ SubnetIds: []string{"subnet-0vm"}, SecurityGroupIds: []string{"sg-0vm"}}}}, nil
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ if _, err := cl.CreateConnector(ctx, hostedops.ConnectorSpec{Name: "n", Token: "tok", Subnet: "subnet-0vm", SecurityGroup: "sg-0vm", Role: "arn:r", Tags: map[string]string{"run": "r1"}}); err != nil {
+ t.Fatal(err)
+ }
+ got, err := cl.GetConnector(ctx, "arn:c:1")
+ if err != nil || got.Version != 1 || got.VersionARN != "arn:c:1" || got.Subnets[0] != "subnet-0vm" || got.ElasticIP {
+ t.Fatalf("connector %+v, %v", got, err)
+ }
+ })
+ t.Run("iam", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ switch in := c.In.(type) {
+ case *iam.PutRolePolicyInput:
+ if aws.ToString(in.RoleName) != "r" || aws.ToString(in.PolicyName) != "p" || aws.ToString(in.PolicyDocument) != "{}" {
+ t.Errorf("put %+v", in)
+ }
+ return &iam.PutRolePolicyOutput{}, nil
+ case *iam.AttachRolePolicyInput:
+ return &iam.AttachRolePolicyOutput{}, nil
+ case *iam.ListAttachedRolePoliciesInput:
+ if in.Marker == nil {
+ return &iam.ListAttachedRolePoliciesOutput{AttachedPolicies: []iamtypes.AttachedPolicy{{PolicyArn: aws.String("arn:other")}}, IsTruncated: true, Marker: aws.String("m")}, nil
+ }
+ return &iam.ListAttachedRolePoliciesOutput{AttachedPolicies: []iamtypes.AttachedPolicy{{PolicyArn: aws.String("arn:deny")}}}, nil
+ case *iam.GetRoleInput:
+ return nil, &smithy.GenericAPIError{Code: "NoSuchEntity"}
+ case *budgets.DescribeBudgetInput:
+ return nil, &budgettypes.NotFoundException{Message: aws.String("no")}
+ }
+ return nil, fmt.Errorf("unexpected %s", c.Op)
+ })
+ if err := cl.PutRolePolicy(ctx, "r", "p", "{}"); err != nil {
+ t.Fatal(err)
+ }
+ if ok, err := cl.RolePolicyAttached(ctx, "r", "arn:deny"); !ok || err != nil {
+ t.Fatalf("attached on page 2 = %t, %v", ok, err)
+ }
+ for _, k := range []hostedops.LookupKey{{Type: "aws_iam_role", ID: "arn:aws:iam::" + prod + ":role/x"}, {Type: "aws_budgets_budget", Name: "b"}} {
+ if res, err := cl.Lookup(ctx, k); err != nil || !res.Definitive || len(res.IDs) != 0 {
+ t.Fatalf("lookup %s = %+v, %v; want a definitive miss", k.Type, res, err)
+ }
+ }
+ })
+ t.Run("microvms pages", func(t *testing.T) {
+ cl, _ := openFake(t, func(c call) (any, error) {
+ in, ok := c.In.(*vms.ListMicrovmsInput)
+ if !ok {
+ return nil, errors.New("unexpected")
+ }
+ if aws.ToString(in.ImageIdentifier) != "arn:img" {
+ t.Errorf("image filter %q", aws.ToString(in.ImageIdentifier))
+ }
+ if in.NextToken == nil {
+ return &vms.ListMicrovmsOutput{Items: []vmtypes.MicrovmItem{{MicrovmId: aws.String("microvm-1"), ImageArn: aws.String("arn:img"), State: vmtypes.MicrovmStateRunning}}, NextToken: aws.String("2")}, nil
+ }
+ return &vms.ListMicrovmsOutput{Items: []vmtypes.MicrovmItem{{MicrovmId: aws.String("microvm-2"), ImageArn: aws.String("arn:other")}}}, nil
+ })
+ if _, err := cl.ListVMs(ctx, "arn:img"); err == nil {
+ t.Fatal("a listing that answered another image's VM was accepted")
+ }
+ })
+}
diff --git a/internal/isolatedjob/awsjob/opsaws/lookup.go b/internal/isolatedjob/awsjob/opsaws/lookup.go
index 3d404b3e..f01f8aa7 100644
--- a/internal/isolatedjob/awsjob/opsaws/lookup.go
+++ b/internal/isolatedjob/awsjob/opsaws/lookup.go
@@ -11,6 +11,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/budgets"
"github.com/aws/aws-sdk-go-v2/service/cloudtrail"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/aws-sdk-go-v2/service/iam"
@@ -120,13 +121,56 @@ func (c *cloud) Lookup(ctx context.Context, k hostedops.LookupKey) (hostedops.Lo
return hostedops.LookupResult{Definitive: true}, nil
}
return hostedops.LookupResult{IDs: []string{id}, Definitive: true}, nil
+ case "aws_cloudwatch_log_group":
+ p := cloudwatchlogs.NewDescribeLogGroupsPaginator(c.cl.logs, &cloudwatchlogs.DescribeLogGroupsInput{LogGroupNamePrefix: aws.String(id)})
+ for n := 0; p.HasMorePages(); n++ {
+ if n >= maxPages {
+ return hostedops.LookupResult{}, errors.New("DescribeLogGroups: too many pages")
+ }
+ r, err := p.NextPage(ctx)
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeLogGroups: %w", err)
+ }
+ for _, g := range r.LogGroups {
+ if aws.ToString(g.LogGroupName) == id {
+ return hostedops.LookupResult{IDs: []string{id}, Definitive: true}, nil
+ }
+ }
+ }
+ return hostedops.LookupResult{Definitive: true}, nil
+ case "aws_budgets_budget_action":
+ // OpenTofu's ID is ACCOUNT:ACTION:BUDGET.
+ parts := strings.SplitN(id, ":", 3)
+ if len(parts) != 3 {
+ return hostedops.LookupResult{}, fmt.Errorf("budget action ID %q is not account:action:budget", id)
+ }
+ p := budgets.NewDescribeBudgetActionsForBudgetPaginator(c.cl.budgets, &budgets.DescribeBudgetActionsForBudgetInput{
+ AccountId: aws.String(c.want.account), BudgetName: aws.String(parts[2])})
+ for n := 0; p.HasMorePages(); n++ {
+ if n >= maxPages {
+ return hostedops.LookupResult{}, errors.New("DescribeBudgetActionsForBudget: too many pages")
+ }
+ r, err := p.NextPage(ctx)
+ if isNotFound(err) {
+ return hostedops.LookupResult{Definitive: true}, nil
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeBudgetActionsForBudget: %w", err)
+ }
+ for _, a := range r.Actions {
+ if aws.ToString(a.ActionId) == parts[1] {
+ return hostedops.LookupResult{IDs: []string{id}, Definitive: true}, nil
+ }
+ }
+ }
+ return hostedops.LookupResult{Definitive: true}, nil
case "aws_budgets_budget":
_, err := c.cl.budgets.DescribeBudget(ctx, &budgets.DescribeBudgetInput{AccountId: aws.String(c.want.account), BudgetName: aws.String(id)})
return found(err, id)
case "aws_vpc", "aws_subnet", "aws_security_group", "aws_route_table", "aws_internet_gateway",
"aws_vpc_peering_connection", "aws_instance", "aws_eip", "aws_network_acl":
if k.ID == "" {
- return c.ec2ByTag(ctx, k.Type, k.Run, k.Name)
+ return c.ec2ByIdentity(ctx, k.Type, k)
}
return c.ec2ByID(ctx, k.Type, k.ID)
}
@@ -204,28 +248,162 @@ func (c *cloud) ec2ByID(ctx context.Context, typ, id string) (hostedops.LookupRe
return hostedops.LookupResult{IDs: []string{id}, Definitive: true}, nil
}
-// ec2ByTag finds a resource of typ by the run's tag (and its Name tag when
-// known). Never definitive.
-func (c *cloud) ec2ByTag(ctx context.Context, typ, run, name string) (hostedops.LookupResult, error) {
- rtype := map[string]string{"aws_vpc": "vpc", "aws_subnet": "subnet", "aws_security_group": "security-group",
- "aws_route_table": "route-table", "aws_internet_gateway": "internet-gateway", "aws_vpc_peering_connection": "vpc-peering-connection",
- "aws_instance": "instance", "aws_eip": "elastic-ip", "aws_network_acl": "network-acl"}[typ]
- filters := []ec2types.Filter{{Name: aws.String("resource-type"), Values: []string{rtype}},
- {Name: aws.String("tag:run"), Values: []string{run}}, {Name: aws.String("tag:purpose"), Values: []string{"equipo-hosted-prod", "equipo-hosted-dev"}}}
- r, err := c.cl.ec2.DescribeTags(ctx, &ec2.DescribeTagsInput{Filters: filters})
- if err != nil {
- return hostedops.LookupResult{}, fmt.Errorf("DescribeTags: %w", err)
+// ec2ByIdentity finds a resource of typ by its creation identity (F3): its
+// Name tag and the run's tag, and its parent VPC when known, over every
+// page. The stacks tag every EC2 resource when they create it (Name and
+// the provider's default run tag), so a complete listing with no match is
+// a definitive miss. With no Name tag the identity is not enough: not
+// definitive, and no call is made.
+func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.LookupKey) (hostedops.LookupResult, error) {
+ if k.NameTag == "" || k.Run == "" {
+ return hostedops.LookupResult{}, nil
+ }
+ f := []ec2types.Filter{{Name: aws.String("tag:Name"), Values: []string{k.NameTag}}, {Name: aws.String("tag:run"), Values: []string{k.Run}}}
+ if k.Parent != "" && strings.HasPrefix(k.Parent, "vpc-") {
+ switch typ {
+ case "aws_subnet", "aws_security_group", "aws_route_table", "aws_network_acl", "aws_instance":
+ f = append(f, ec2types.Filter{Name: aws.String("vpc-id"), Values: []string{k.Parent}})
+ case "aws_internet_gateway":
+ f = append(f, ec2types.Filter{Name: aws.String("attachment.vpc-id"), Values: []string{k.Parent}})
+ }
}
- seen := map[string]bool{}
var ids []string
- for _, t := range r.Tags {
- id := aws.ToString(t.ResourceId)
- if !seen[id] {
- seen[id] = true
- ids = append(ids, id)
+ page := func(n int) error {
+ if n >= maxPages {
+ return errors.New("too many pages")
+ }
+ return nil
+ }
+ switch typ {
+ case "aws_vpc":
+ p := ec2.NewDescribeVpcsPaginator(c.cl.ec2, &ec2.DescribeVpcsInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeVpcs: %w", err)
+ }
+ for _, x := range r.Vpcs {
+ ids = append(ids, aws.ToString(x.VpcId))
+ }
+ }
+ case "aws_subnet":
+ p := ec2.NewDescribeSubnetsPaginator(c.cl.ec2, &ec2.DescribeSubnetsInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeSubnets: %w", err)
+ }
+ for _, x := range r.Subnets {
+ ids = append(ids, aws.ToString(x.SubnetId))
+ }
+ }
+ case "aws_security_group":
+ p := ec2.NewDescribeSecurityGroupsPaginator(c.cl.ec2, &ec2.DescribeSecurityGroupsInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeSecurityGroups: %w", err)
+ }
+ for _, x := range r.SecurityGroups {
+ ids = append(ids, aws.ToString(x.GroupId))
+ }
+ }
+ case "aws_route_table":
+ p := ec2.NewDescribeRouteTablesPaginator(c.cl.ec2, &ec2.DescribeRouteTablesInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeRouteTables: %w", err)
+ }
+ for _, x := range r.RouteTables {
+ ids = append(ids, aws.ToString(x.RouteTableId))
+ }
+ }
+ case "aws_internet_gateway":
+ p := ec2.NewDescribeInternetGatewaysPaginator(c.cl.ec2, &ec2.DescribeInternetGatewaysInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeInternetGateways: %w", err)
+ }
+ for _, x := range r.InternetGateways {
+ ids = append(ids, aws.ToString(x.InternetGatewayId))
+ }
+ }
+ case "aws_network_acl":
+ p := ec2.NewDescribeNetworkAclsPaginator(c.cl.ec2, &ec2.DescribeNetworkAclsInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeNetworkAcls: %w", err)
+ }
+ for _, x := range r.NetworkAcls {
+ ids = append(ids, aws.ToString(x.NetworkAclId))
+ }
+ }
+ case "aws_vpc_peering_connection":
+ p := ec2.NewDescribeVpcPeeringConnectionsPaginator(c.cl.ec2, &ec2.DescribeVpcPeeringConnectionsInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeVpcPeeringConnections: %w", err)
+ }
+ for _, x := range r.VpcPeeringConnections {
+ if x.Status == nil || (x.Status.Code != ec2types.VpcPeeringConnectionStateReasonCodeDeleted && x.Status.Code != ec2types.VpcPeeringConnectionStateReasonCodeRejected) {
+ ids = append(ids, aws.ToString(x.VpcPeeringConnectionId))
+ }
+ }
+ }
+ case "aws_instance":
+ f = append(f, ec2types.Filter{Name: aws.String("instance-state-name"), Values: []string{"pending", "running", "shutting-down", "stopping", "stopped"}})
+ p := ec2.NewDescribeInstancesPaginator(c.cl.ec2, &ec2.DescribeInstancesInput{Filters: f})
+ for n := 0; p.HasMorePages(); n++ {
+ r, err := p.NextPage(ctx)
+ if err == nil {
+ err = page(n)
+ }
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeInstances: %w", err)
+ }
+ for _, res := range r.Reservations {
+ for _, x := range res.Instances {
+ ids = append(ids, aws.ToString(x.InstanceId))
+ }
+ }
+ }
+ case "aws_eip":
+ r, err := c.cl.ec2.DescribeAddresses(ctx, &ec2.DescribeAddressesInput{Filters: f}) // one page by design
+ if err != nil {
+ return hostedops.LookupResult{}, fmt.Errorf("DescribeAddresses: %w", err)
+ }
+ for _, x := range r.Addresses {
+ ids = append(ids, aws.ToString(x.AllocationId))
}
+ default:
+ return hostedops.LookupResult{}, nil
}
- return hostedops.LookupResult{IDs: ids}, nil
+ return hostedops.LookupResult{IDs: ids, Definitive: true}, nil
}
// Inventory is 0.5's read-only sweep.
diff --git a/internal/isolatedjob/awsjob/opsaws/opsaws.go b/internal/isolatedjob/awsjob/opsaws/opsaws.go
index 87a9038c..f87d0bf9 100644
--- a/internal/isolatedjob/awsjob/opsaws/opsaws.go
+++ b/internal/isolatedjob/awsjob/opsaws/opsaws.go
@@ -148,7 +148,7 @@ func (op Opener) Open(ctx context.Context, t hostedops.Target) (hostedops.Cloud,
if timeout == 0 {
timeout = 60 * time.Second
}
- c := &cloud{cl: newClients(cfg, t.Region, timeout), want: w, now: now,
+ c := &cloud{cl: newClients(cfg, t.Region, timeout), want: w, now: now, timeout: timeout,
keys: hostedops.Keys{AccessKeyID: ex.AccessKeyID, SecretAccessKey: ex.SecretAccessKey, SessionToken: ex.SessionToken}}
id, err := c.verify(ctx)
if err != nil {
diff --git a/internal/isolatedjob/awsjob/opsaws/opsaws_test.go b/internal/isolatedjob/awsjob/opsaws/opsaws_test.go
index 7b5ef356..6fae8929 100644
--- a/internal/isolatedjob/awsjob/opsaws/opsaws_test.go
+++ b/internal/isolatedjob/awsjob/opsaws/opsaws_test.go
@@ -51,6 +51,7 @@ type fakeAWS struct {
type call struct {
Service, Op, Key string
In any
+ Ctx context.Context
}
var credRe = regexp.MustCompile(`Credential=([A-Z0-9]+)/`)
@@ -58,7 +59,7 @@ var credRe = regexp.MustCompile(`Credential=([A-Z0-9]+)/`)
func (f *fakeAWS) option(s *middleware.Stack) error {
return s.Finalize.Add(middleware.FinalizeMiddlewareFunc("opsawsFake",
func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) {
- c := call{Service: awsmiddleware.GetServiceID(ctx), Op: awsmiddleware.GetOperationName(ctx)}
+ c := call{Service: awsmiddleware.GetServiceID(ctx), Op: awsmiddleware.GetOperationName(ctx), Ctx: ctx}
if r, ok := in.Request.(*smithyhttp.Request); ok {
if m := credRe.FindStringSubmatch(r.Header.Get("Authorization")); m != nil {
c.Key = m[1]
diff --git a/scripts/release-hosted.sh b/scripts/release-hosted.sh
index b0336313..685a72ae 100755
--- a/scripts/release-hosted.sh
+++ b/scripts/release-hosted.sh
@@ -31,7 +31,8 @@
# image-manifest.json that manifest, alone (what equipo-hosted-certify
# judge -release reads)
# hosted-VERSION.json the release manifest: every artifact and its
-# SHA-256, IMAGE_DIGEST, BaseImageVersion, Litestream's version and digest
+# SHA-256, IMAGE_DIGEST, BaseImageVersion, HostAMI (the hosts' AMI by
+# region, which equipo-hosted-ops tfvars reads), Litestream's version and digest
# SHA256SUMS
#
# Publishing follows scripts/publish-renderer.sh: an existing release is
@@ -170,8 +171,11 @@ else
fi
base_version=$(python3 -I -c 'import json, sys; print(json.load(open(sys.argv[1]))["BaseImageVersion"])' "$pins")
[[ -n $base_version ]] || note "BaseImageVersion is not pinned in infra/hosted/release-pins.json (slice 2 Task 34 confirms one)"
+host_ami=$(python3 -I -c 'import json, sys; print(json.load(open(sys.argv[1])).get("HostAMI", {}).get("eu-west-1", ""))' "$pins")
+[[ $host_ami =~ ^ami-[0-9a-f]{8,17}$ ]] || note "HostAMI for eu-west-1 is not pinned in infra/hosted/release-pins.json (the hosts' Amazon Linux 2023 arm64 AMI)"
if ((!dry)); then
[[ -n $image_digest && -n $base_version ]] || die "a publish needs the image digest and a pinned BaseImageVersion"
+ [[ $host_ami =~ ^ami-[0-9a-f]{8,17}$ ]] || die "a publish needs a pinned HostAMI for eu-west-1"
fi
# The release manifest and SHA256SUMS.
@@ -199,6 +203,7 @@ for name in open(assets).read().split():
ls = json.load(open(pins))["Litestream"]
m = {"Release": tag, "Commit": commit, "Dirty": dirty == "true", "DryRun": dry == "1", "URL": url,
"Artifacts": art, "IMAGE_DIGEST": digest or None, "BaseImageVersion": base or None,
+ "HostAMI": json.load(open(pins)).get("HostAMI", {}),
"RunnerRelease": runner, "Litestream": ls,
"ImageManifest": "image-manifest.json" if os.path.exists(os.path.join(out, "image-manifest.json")) else None,
"ImageSource": "image-source.tar" if os.path.exists(os.path.join(out, "image-source.tar")) else None,