hostedops: Task 33 after-cap fix, Astra round 3 N1 N2 N6
After-cap fix (t33-r3.md, rulings in task-33-fix3.md), red first. N1: a unit's program keeps the INVOCATION_ID systemd gives the unit (a shell wrapper around env -i), so cgroup membership reads true inside it; safe-stop --recovery refuses (99) outside the recovery unit; a requester whose start collides with another's joins and waits. N2: a gateway's absence needs an unfiltered listing of every gateway, each accounted to another intent (attachment is not containment); deleted-parent inference only for subnets, route tables, security groups and network ACLs. N6: plan-check --adopt accepts unchanged managed dependencies (no-op, no import, no move); a subnet adoption beside its managed VPC goes through the real plan-check, the destroy and verify-gone. Extras: every plan span, bare names included, through the real dispatcher (a bare group answers with its subcommands); Inventory's budget pages. Mutations T1 to T8.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+537
−57
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+40 −0infra/hosted/scripts/plan-check.py+8 −2infra/hosted/scripts/plan_check_test.py+23 −0internal/hostedops/fake_test.go+34 −10internal/hostedops/fix1_test.go+35 −35internal/hostedops/fix3_test.go+237 −0internal/hostedops/ops.go+12 −0internal/hostedops/stop.go+11 −2internal/hostedops/tf.go+7 −1internal/hostedops/units.go+10 −2internal/isolatedjob/awsjob/opsaws/fix3_test.go+101 −0internal/isolatedjob/awsjob/opsaws/lookup.go+18 −4
CI failed — run details
CI log
=== prepare ===
ci-box: machine: aarch64, 32 CPUs, 62 GiB memory, kernel 7.0.0-1017-aws
ci-box: python 3.12.3; Docker version 29.1.3, build 29.1.3-0ubuntu3~24.04.2
ci-box: user namespaces allowed: 233151
ci-box: cgroup: cgroup2fs
ci-box: disk /home/ci/work/repos/oficina__equipo/wt/hosted-runners-2: Type Size Avail | ext4 96G 84G
ci-box: disk /home/ci/.cache/equipo-ci-box: Type Size Avail | ext4 96G 84G
ci-box: bwrap: fetched and verified in 0.3s
ci-box: claude: fetched and verified in 1.6s
ci-box: codex: fetched and verified in 3.5s
ci-box: codex-code-mode-host: fetched and verified in 1.4s
ci-box: libwrap: fetched and verified in 0.3s
ci-box: socat: fetched and verified in 0.3s
ci-box: tofu: fetched and verified in 1.6s
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
ci-box: image pulled in 9.9s
ci-box: pi: installed and verified in 7.7s
ci-box: opencode: installed and verified in 2.5s
ci-box: chromium 156.0.8078.79-1~deb13u1: 76 packages fetched, verified and unpacked in 8.8s
ci-box: clone deepened in 5.4s
ci-box: file times set from content: 4036 files, 302 directories
ci-box: ready in 19.5s
=== copy ===
EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$' -count=1
--- FAIL: TestReleaseCopyReviewed (0.09s)
task_pages_test.go:236: COPY REVIEW REQUIRED: copy-status.py verify found copy pending review or stale bookkeeping
FAIL
rastrillo-budget/v1 ran 89ms
FAIL amadan.net/oficina/equipo/internal/equipotest 0.240s
FAIL
make: *** [Makefile:322: copy-release-check] Error 1
amadan: step copy failed: exit status 2
amadan: job failed at step copy — its output is above, not at the tail of this log
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 39298f2f..bb1234a1 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 6575 - 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. Fix round 2 (t33-r2 N1 to N6): the one recovery unit and its lock, cgroup membership, identity lookups that prove absence only under the recorded parent, settlement after a second fence, IAM action matching, launches bound at their intent, and adoption through a checked import plan rebuilt from durable records; 6575. |
| +size internal/hostedops 6610 - 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. Fix round 2 (t33-r2 N1 to N6): the one recovery unit and its lock, cgroup membership, identity lookups that prove absence only under the recorded parent, settlement after a second fence, IAM action matching, launches bound at their intent, and adoption through a checked import plan rebuilt from durable records; 6575. After-cap fix (t33-r3): the unit wrapper keeping INVOCATION_ID, recovery only inside its unit, joining a start collision, contained types for deleted-parent inference, the group usage line; 6610. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 756089c6..5fd233ac 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -3067,3 +3067,43 @@ Mutation checks (each applied alone, restored byte for byte and checked): |
| - S24 F4 a covered type passes with its parent present. `TestVerifyGoneCoveredParentStillThere`: exit 1 | fix2_test.go:294: the covered policy was not reported with its parent: | restored |
| - S25 Network: one page of security group rules. `TestSDKShapesAndPages`: exit 1 | fix2_test.go:154: network over two pages: {DNSSupport:false DNSHostnames:false VMRoutes:[{Destination:10.43.0.0/16 Target:local}] ServicesRoutes:[{Destination:10.43.0.0/16 Target:local}] VMSGRules:[{Egress:true Protocol:tcp FromPort:8443 ToPort:8443 CIDR:10.42 | restored |
| - S26 Network: one page of route tables. `TestSDKShapesAndPages`: exit 1 | fix2_test.go:154: network over two pages: {DNSSupport:false DNSHostnames:false VMRoutes:[] ServicesRoutes:[] VMSGRules:[] PeeringState:}, DescribeRouteTables: 0 tables, want one | restored |
| + |
| +### Task 33 after-cap fix |
| + |
| +Findings: `t33-r3.md` (Astra round 3: N3 to N5 closed; N1, N2 and N6 left, plus two extras); rulings: `task-33-fix3.md`. The base is `80801ccb`. |
| + |
| +This fix was red-first. The only change made before the red run was the skeleton `var containedTypes []string` (empty, and not yet used). The fake systemd also gained a forced-state hook, a start collision (it refuses an active unit name, as systemd-run does), and a probe that follows the new shell wrapper. Existing tests still passed before the red run. |
| + |
| +RED (Go: `CGO_ENABLED=0 go test ./internal/hostedops ./internal/isolatedjob/awsjob/opsaws -count=1 -run '<the new tests>'`): |
| +- TestPlanInvocationsParse: fix1_test.go:576: ops vms (a name in prose) is not a command its parser knows: usage: unknown command "vms"; commands: assert, block, bucket create, bucket delete, bucket empty, bundle, cloudtrail sto |
| +- TestUnitEnvKeepsInvocationID: fix3_test.go:43: the unit's program would run without its INVOCATION_ID: env [PATH=/home/paulca/.local/go-dist/bin:/home/paulca/.local/bin:/home/paulca/bin:/home/paulca/.local/go/bin:/home/paulca/go/b |
| +- TestRecoveryRefusedOutsideItsUnit: fix3_test.go:65: ops safe-stop --recovery = 0, want 99: |
| +- TestConcurrentRequestersJoinOneRecovery: fix3_test.go:123: a requester returned before recovery ran: block 99 |
| +- TestDeletedParentOnlyForContainedTypes: fix3_test.go:171: ops tf reconcile network = 0, want 99: |
| +- TestAdoptionBesideManagedDependency: fix3_test.go:223: ops tf network destroy-network = 99, want 0: |
| +- TestGatewayAbsenceNeedsExhaustiveListing: fix3_test.go:56: gateway lookup {IDs:[] Definitive:true}, <nil>; want definitive false |
| + |
| +RED (plan-check: `python3 -I infra/hosted/scripts/plan_check_test.py`): |
| +- FAIL: test_unchanged_managed_dependency_accepted (__main__.Adopt.test_unchanged_managed_dependency_accepted) |
| +- AssertionError: Lists differ: ['module.network.aws_vpc.vm is in an adoption plan but is not an adoption'] != [] |
| + |
| +Not red-first, and recorded as such: |
| +- `TestInventoryBudgetsTwoPages` is coverage: Inventory already used the budget paginator. |
| +- `Adopt.test_dependency_that_imports_changes_or_moves_refused` passed on the old code, which refused every address outside the adoption map; T7 shows it now holds by its own check. |
| + |
| +GREEN: |
| +- `CGO_ENABLED=0 go test ./internal/hostedops/... ./internal/isolatedjob/... ./cmd/equipo-hosted-ops ./internal/hostedclient -count=1`: all ok. `TestConcurrentRequestersJoinOneRecovery` passed 30 runs out of 30 (`-count=30`). |
| +- plan_check_test.py: 111 tests ok. |
| +- `make build vet govulncheck budget lanes-check fmt-check hosted-infra-check` ok; the budget record is now `size internal/hostedops 6610`, with its reason. |
| +- staticcheck is clean; the darwin and windows builds succeed; `git diff --check` is clean. |
| + |
| +Mutation checks (each applied alone, restored byte for byte and checked): |
| +- T1 the wrapper drops INVOCATION_ID. `TestUnitEnvKeepsInvocationID`: exit 1 | fix3_test.go:43: the unit's program would run without its INVOCATION_ID: env [PATH=/home/paulca/.local/go-dist/bin:/home/paulca/.local/bin:/home/paulca/bin:/home/paulca/.local/go/bin:/home/paulca/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/bin HO | restored |
| +- T2 recovery runs outside its unit. `TestRecoveryRefusedOutsideItsUnit`: exit 1 | fix3_test.go:65: ops safe-stop --recovery = 0, want 99: | restored |
| +- T3 a start collision returns, not joins. `TestConcurrentRequestersJoinOneRecovery`: exit 1 | fix3_test.go:125: a requester returned before recovery ran: block 99 | restored |
| +- T4 a gateway's absence by attachment. `TestGatewayAbsenceNeedsExhaustiveListing`: exit 1 | fix3_test.go:56: gateway lookup {IDs:[] Definitive:true}, <nil>; want definitive false | restored |
| +- T5 deleted-parent inference for every type. `TestDeletedParentOnlyForContainedTypes`: exit 1 | fix3_test.go:173: ops tf reconcile network = 0, want 99: | restored |
| +- T6 plan-check: a managed no-op refused. `Adopt.test_unchanged_managed_dependency_accepted`: exit 1 | AssertionError: Lists differ: ['module.network.aws_vpc.vm is in an adopt[66 chars]rce'] != [] | restored |
| +- T6b the same, through ops and the real plan-check. `TestAdoptionBesideManagedDependency`: exit 1 | fix3_test.go:225: ops tf network destroy-network = 99, want 0: | restored |
| +- T7 plan-check: an importing dependency passes. `Adopt.test_dependency_that_imports_changes_or_moves_refused`: exit 1 | AssertionError: [] is not true : the plan was accepted | restored |
| +- T8 a bare group is an unknown command. `TestPlanInvocationsParse`: exit 1 | fix1_test.go:576: ops vms (a name in prose) is not a command its parser knows: usage: unknown command "vms"; commands: assert, block, bucket create, bucket delete, bucket empty, bundle, cloudtrail stop-logging, connector create, connector delete, estimate, fac | restored |
diff --git a/infra/hosted/scripts/plan-check.py b/infra/hosted/scripts/plan-check.py| index f93b0e8a..cb1ae50f 100644 |
| --- a/infra/hosted/scripts/plan-check.py |
| +++ b/infra/hosted/scripts/plan-check.py |
| @@ -7,7 +7,8 @@ |
| instead: equipo-hosted-ops imports a resource it found outside state |
| through a run-local import block and a plan that targets it, and that plan |
| may only import exactly those addresses at those IDs, each listed for the |
| -create phase P and planned with no change. |
| +create phase P and planned with no change; any other address must be an |
| +unchanged managed resource of the phase (no-op, no import, no move). |
| plan.json is `tofu show -json` of a saved plan. equipo-hosted-ops tf runs this |
| between `tofu plan -out` and `tofu apply` (account plan, "Rules for every |
| @@ -1078,7 +1079,12 @@ def check_adopt(p, listed, adopt): |
| actions = change.get("actions") |
| got = (change.get("importing") or {}).get("id") |
| if address not in adopt: |
| - out.append("%s is in an adoption plan but is not an adoption" % address) |
| + # A managed dependency the targeted plan brings in, unchanged |
| + # (after-cap fix 3): no-op, no import, no move. |
| + if actions != ["no-op"] or change.get("importing") or "previous_address" in rc or "deposed" in rc: |
| + out.append("%s is in an adoption plan but is neither an adoption nor an unchanged managed resource" % address) |
| + elif address not in listed: |
| + out.append("%s is not listed for this phase" % address) |
| continue |
| if address not in listed: |
| out.append("%s is not listed for this phase" % address) |
diff --git a/infra/hosted/scripts/plan_check_test.py b/infra/hosted/scripts/plan_check_test.py| index 5f01e527..adf072e4 100644 |
| --- a/infra/hosted/scripts/plan_check_test.py |
| +++ b/infra/hosted/scripts/plan_check_test.py |
| @@ -259,6 +259,29 @@ class Adopt(Base): |
| def test_import_without_adopt_refused(self): |
| self.assertRefused(check(self.adopt_plan()), "aws_vpc.vm") |
| + def beside_vpc(self, **vpc_change): |
| + p = copy.deepcopy(FRESH) |
| + vpc = copy.deepcopy(change(p, NET + "aws_vpc.vm")) |
| + sub = copy.deepcopy(change(p, NET + "aws_subnet.vm")) |
| + vpc["change"]["actions"] = ["no-op"] |
| + vpc["change"].update(vpc_change) |
| + sub["change"]["actions"] = ["no-op"] |
| + sub["change"]["importing"] = {"id": "subnet-0abc"} |
| + p["resource_changes"] = [vpc, sub] |
| + return p |
| + |
| + def test_unchanged_managed_dependency_accepted(self): |
| + # Targeting the subnet brings in its managed VPC, unchanged. |
| + self.assertEqual(check(self.beside_vpc(), adopt={NET + "aws_subnet.vm": "subnet-0abc"}), []) |
| + |
| + def test_dependency_that_imports_changes_or_moves_refused(self): |
| + adopt = {NET + "aws_subnet.vm": "subnet-0abc"} |
| + self.assertRefused(check(self.beside_vpc(importing={"id": "vpc-0abc"}), adopt=adopt), "aws_vpc.vm") |
| + self.assertRefused(check(self.beside_vpc(actions=["update"]), adopt=adopt), "aws_vpc.vm") |
| + p = self.beside_vpc() |
| + p["resource_changes"][0]["previous_address"] = NET + "aws_vpc.old" |
| + self.assertRefused(check(p, adopt=adopt), "aws_vpc.vm") |
| + |
| class Actions(Base): |
| def test_update_refused(self): |
diff --git a/internal/hostedops/fake_test.go b/internal/hostedops/fake_test.go| index ee34a6b1..d44b04ac 100644 |
| --- a/internal/hostedops/fake_test.go |
| +++ b/internal/hostedops/fake_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "fmt" |
| "os" |
| "path/filepath" |
| + "regexp" |
| "slices" |
| "sort" |
| "strings" |
| @@ -330,6 +331,26 @@ type fakeSystemd struct { |
| status map[string]string // unit -> its status file |
| timeouts map[string]time.Duration |
| run func(unit string, argv []string) (int, bool) |
| + override func(unit string) (string, bool) // a forced State answer |
| +} |
| + |
| +// unitEnv is what a unit's program runs with, as systemd and the wrapper |
| +// would give it: the wrapper's kept INVOCATION_ID (invocation), then the |
| +// env -i assignments; and the program's argv. |
| +func unitEnv(argv []string, invocation string) (env, prog []string) { |
| + i := 0 |
| + if len(argv) >= 4 && argv[0] == "/bin/sh" && argv[1] == "-c" { |
| + if strings.Contains(argv[2], `"INVOCATION_ID=${INVOCATION_ID:-}"`) { |
| + env = append(env, "INVOCATION_ID="+invocation) |
| + } |
| + i = 4 // the script and its $0 |
| + } else if len(argv) >= 2 && argv[0] == "/usr/bin/env" && argv[1] == "-i" { |
| + i = 2 |
| + } |
| + for ; i < len(argv) && regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*=`).MatchString(argv[i]); i++ { |
| + env = append(env, argv[i]) |
| + } |
| + return env, argv[i:] |
| } |
| func (s *fakeSystemd) Start(unit, wd, out, status, ep string, stopTimeout time.Duration, argv []string) error { |
| @@ -348,6 +369,9 @@ func (s *fakeSystemd) Start(unit, wd, out, status, ep string, stopTimeout time.D |
| } |
| } |
| }() |
| + if s.states[unit] == "running" { // systemd-run refuses a unit name that is active |
| + return fmt.Errorf("Unit %s was already loaded or has a fragment file", unit) |
| + } |
| s.started = append(s.started, unit) |
| if s.timeouts == nil { |
| s.timeouts = map[string]time.Duration{} |
| @@ -358,22 +382,22 @@ func (s *fakeSystemd) Start(unit, wd, out, status, ep string, stopTimeout time.D |
| 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) |
| + // A probe unit writes its environment to the file its shell command |
| + // names, as the real one does: the env -i assignments, plus the |
| + // INVOCATION_ID systemd gives the unit when the wrapper keeps it. |
| + if env, prog := unitEnv(argv, "inv-"+unit); len(prog) >= 4 && strings.Contains(prog[len(prog)-2], "env > ") { |
| + os.WriteFile(prog[len(prog)-1], []byte(strings.Join(env, "\n")+"\n"), 0o600) |
| } |
| return nil |
| } |
| func (s *fakeSystemd) State(u string) string { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| + if s.override != nil { |
| + if st, ok := s.override(u); ok { |
| + return st |
| + } |
| + } |
| if st, ok := s.states[u]; ok { |
| return st |
| } |
diff --git a/internal/hostedops/fix1_test.go b/internal/hostedops/fix1_test.go| index 74a7d84c..ec018d4d 100644 |
| --- a/internal/hostedops/fix1_test.go |
| +++ b/internal/hostedops/fix1_test.go |
| @@ -540,11 +540,14 @@ func TestUnitProbe(t *testing.T) { |
| r.want(ExitStop, "unit", "probe") |
| } |
| -// Extra (round 2): every ops invocation in the account plan and in Task |
| -// 34's text passes the real parsers, flags included; nothing is skipped. A |
| -// span that is only a command's name (prose such as "`ops assert`") has no |
| -// flags to parse, so its name must resolve; every other span is expanded |
| -// (a|b alternatives, the plan's upper-case placeholders) and run. |
| +// Extra (rounds 2 and 3): every ops invocation in the account plan and in |
| +// Task 34's text runs through the real dispatcher and parsers; nothing is |
| +// skipped. A span that is only a command's or group's name (prose such as |
| +// "`ops assert`", "`ops vms`", "`ops tf reconcile`") has no arguments, so |
| +// its answer must come from that command's own parser: success, or its own |
| +// usage line, never "unknown command" or a flag error. Every other span |
| +// (expanded: a|b alternatives, the plan's upper-case placeholders) must |
| +// parse with no usage error at all. |
| func TestPlanInvocationsParse(t *testing.T) { |
| read := func(name string) string { |
| b, err := os.ReadFile(filepath.Join("..", "..", "docs", "superpowers", "plans", name)) |
| @@ -558,37 +561,28 @@ func TestPlanInvocationsParse(t *testing.T) { |
| account := read("2026-11-30-hosted-prod-account-plan.md") |
| t.Chdir(t.TempDir()) // the plan writes some files by relative path (9.4's bundle) |
| var invs [][]string |
| - names := 0 |
| for _, src := range []string{account, task34} { |
| - for _, inv := range planInvocations(src) { |
| - if strings.Join(inv, " ") == "tf reconcile" { // the documented subform, named in prose |
| - names++ |
| - continue |
| - } |
| - if len(inv) <= 2 { |
| - if name, _, rest, ok := lookup(inv); ok && len(rest) == 0 && (len(inv) == 1 || strings.Contains(name, " ")) && commands[name].run != nil { |
| - if needsArgs(name) { |
| - names++ |
| - continue |
| - } |
| - } else if len(inv) == 1 && isGroup(inv[0]) { |
| - names++ |
| - continue |
| - } |
| - } |
| - invs = append(invs, inv) |
| - } |
| - } |
| - if len(invs) < 60 || names < 10 { |
| - t.Fatalf("only %d invocations and %d name references found", len(invs), names) |
| + invs = append(invs, planInvocations(src)...) |
| } |
| + bareN := 0 |
| 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()) |
| + out := r.out.String() |
| + if bare(inv) { |
| + bareN++ |
| + if strings.Contains(out, "unknown command") || strings.Contains(out, "flag provided") || strings.Contains(out, "invalid value") { |
| + t.Errorf("ops %s (a name in prose) is not a command its parser knows: %s", strings.Join(inv, " "), out) |
| + } |
| + continue |
| } |
| + if strings.Contains(out, "usage:") { |
| + t.Errorf("ops %s: %s", strings.Join(inv, " "), out) |
| + } |
| + } |
| + if len(invs) < 70 || bareN < 10 { |
| + t.Fatalf("only %d invocations, %d of them bare names", len(invs), bareN) |
| } |
| r := newRig(t, "REC microvm-image "+image1) |
| r.ops("vms", "settle", "--image", image1, "--bogus") |
| @@ -597,14 +591,20 @@ func TestPlanInvocationsParse(t *testing.T) { |
| } |
| } |
| -// needsArgs: a command that cannot run bare (so a bare mention is prose). |
| -func needsArgs(name string) bool { |
| - switch name { |
| - case "guard", "inventory", "quota", "mfa-check", "fence", "safe-stop", "verify-gone", "report", "estimate", |
| - "vms reconcile", "ledger reconcile", "cloudtrail stop-logging", "connector delete", "unit probe", "status", "vms adopt", "ledger show": |
| +// bare: the span is only command words, no flags or arguments. |
| +func bare(inv []string) bool { |
| + if len(inv) > 2 { |
| return false |
| } |
| - return true |
| + for _, w := range inv { |
| + if !regexp.MustCompile(`^[a-z][a-z-]*$`).MatchString(w) { |
| + return false |
| + } |
| + } |
| + if name, _, rest, ok := lookup(inv); ok { |
| + return len(rest) == 0 || (name == "tf" && slices.Equal(rest, []string{"reconcile"})) |
| + } |
| + return len(inv) == 1 && isGroup(inv[0]) |
| } |
| func isGroup(word string) bool { |
diff --git a/internal/hostedops/fix3_test.go b/internal/hostedops/fix3_test.go| new file mode 100644 |
| index 00000000..d9f330fa |
| --- /dev/null |
| +++ b/internal/hostedops/fix3_test.go |
| @@ -0,0 +1,237 @@ |
| +package hostedops |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// After-cap fix (t33-r3.md, task-33-fix3.md): each test written and seen |
| +// failing before its fix. |
| + |
| +// pollClock stands still and yields on each sleep, so concurrent waiters |
| +// wait in real time and never reach a bound. |
| +type pollClock struct{ now time.Time } |
| + |
| +func (c pollClock) Now() time.Time { return c.now } |
| +func (c pollClock) Sleep(ctx context.Context, d time.Duration) error { |
| + if ctx != nil && ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + time.Sleep(time.Millisecond) |
| + return nil |
| +} |
| + |
| +// 1 (N1): the unit's program keeps the INVOCATION_ID systemd gives the |
| +// unit, so its own membership reads true from the cgroup. No SelfUnit is |
| +// injected: the argv the code builds is examined as systemd and the |
| +// wrapper would run it. |
| +func TestUnitEnvKeepsInvocationID(t *testing.T) { |
| + r := newRig(t) |
| + r.deps.SelfUnit = nil |
| + r.want(0, "unit", "start", "5.2", "--", "/bin/true") |
| + env, prog := unitEnv(r.systemd.argv["hprod-r1-5.2.service"], "inv-123") |
| + if !slices.Contains(env, "INVOCATION_ID=inv-123") { |
| + t.Fatalf("the unit's program would run without its INVOCATION_ID: env %v", env) |
| + } |
| + if !slices.Equal(prog, []string{"/bin/true"}) { |
| + t.Fatalf("the unit's program is %v", prog) |
| + } |
| + cg := "0::/user.slice/user-1001.slice/user@1001.service/app.slice/hprod-r1-5.2.service\n" |
| + inv := "" |
| + for _, kv := range env { |
| + if v, ok := strings.CutPrefix(kv, "INVOCATION_ID="); ok { |
| + inv = v |
| + } |
| + } |
| + if got := unitFromCgroup(cg, inv); got != "hprod-r1-5.2.service" { |
| + t.Fatalf("inside the unit, membership reads %q", got) |
| + } |
| +} |
| + |
| +// 1 (N1): recovery runs only inside the recovery unit. |
| +func TestRecoveryRefusedOutsideItsUnit(t *testing.T) { |
| + r := newRig(t, "REC microvm-image "+image1) |
| + r.deps.SelfUnit = nil |
| + t.Setenv("INVOCATION_ID", "") |
| + r.want(ExitStop, "safe-stop", "--recovery") |
| + if r.has("SAFE-STOP", "start") || len(r.cloud.log()) != 0 { |
| + t.Fatal("recovery ran outside the recovery unit") |
| + } |
| +} |
| + |
| +// 1 (N1): two requesters at once (an operator, and a block that receives |
| +// SIGTERM while it runs) see no recovery and both try to start one; the |
| +// loser of the start collision joins. Exactly one recovery runs, and both |
| +// wait for it. |
| +func TestConcurrentRequestersJoinOneRecovery(t *testing.T) { |
| + r := settleRig(t, nil, "VM microvm-a source=controller", "UNIT hprod-r1-6.2.service") |
| + r.systemd.states["hprod-r1-6.2.service"] = "running" |
| + r.deps.Clock = pollClock{now: t0} |
| + r.autoRecover = false |
| + var mu sync.Mutex |
| + early := 2 // both requesters read the recovery unit's state before either starts it |
| + r.systemd.override = func(u string) (string, bool) { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if u == recoveryUnit && early > 0 { |
| + early-- |
| + return "done", true |
| + } |
| + return "", false |
| + } |
| + global := []string{"-dir", r.dir, "-run", "r1", "-profile", "p", "-account", ProdAccount, "-region", testRegion} |
| + sigterm := make(chan struct{}) |
| + codes := make(chan string, 2) |
| + block := r.deps |
| + block.SelfUnit = func() string { return "hprod-r1-6.2.service" } |
| + block.Exec = func(ctxT, []string, []string, wT, wT) int { <-sigterm; return 143 } |
| + go func() { |
| + codes <- fmt.Sprint("block ", Main(context.Background(), append(append([]string{}, global...), "block", "6.2", "--", "x"), block)) |
| + }() |
| + for i := 0; !r.has("BLOCK", "6.2 start"); i++ { |
| + if i > 5000 { |
| + t.Fatal("the block did not start") |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + operator := r.deps |
| + go func() { |
| + codes <- fmt.Sprint("operator ", Main(context.Background(), append(append([]string{}, global...), "safe-stop"), operator)) |
| + }() |
| + for i := 0; !r.has("RECOVERY", "starting"); i++ { |
| + if i > 5000 { |
| + t.Fatal("the operator did not ask for recovery") |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + close(sigterm) // the block's unit is told to stop |
| + for i := 0; strings.Count(journalText(r), "RECOVERY") < 2; i++ { |
| + if i > 5000 { |
| + t.Fatalf("the block did not ask for recovery:\n%s", journalText(r)) |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + select { |
| + case c := <-codes: |
| + t.Fatalf("a requester returned before recovery ran: %s\n%s", c, journalText(r)) |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + if code := r.runUnit(recoveryUnit); code != 0 { |
| + t.Fatalf("the recovery unit exited %d", code) |
| + } |
| + r.systemd.mu.Lock() |
| + r.systemd.states[recoveryUnit] = "done" |
| + r.systemd.mu.Unlock() |
| + os.WriteFile(filepath.Join(r.dir, "units", "recovery.status"), []byte("0\n"), 0o600) |
| + got := []string{} |
| + for range 2 { |
| + select { |
| + case c := <-codes: |
| + got = append(got, c) |
| + case <-time.After(10 * time.Second): |
| + t.Fatalf("a requester never returned; got %v", got) |
| + } |
| + } |
| + slices.Sort(got) |
| + if !slices.Equal(got, []string{"block 99", "operator 0"}) { |
| + t.Fatalf("requesters ended %v, want the block 99 and the operator 0", got) |
| + } |
| + n := 0 |
| + for _, u := range r.systemd.started { |
| + if u == recoveryUnit { |
| + n++ |
| + } |
| + } |
| + if n != 1 || strings.Count(journalText(r), "SAFE-STOP start") != 1 || !r.has("RECOVERY", "joining") { |
| + t.Fatalf("recovery started %d times and ran %d times, joined %t; want once, once, true", n, strings.Count(journalText(r), "SAFE-STOP start"), r.has("RECOVERY", "joining")) |
| + } |
| +} |
| + |
| +func journalText(r *rig) string { |
| + b, _ := os.ReadFile(filepath.Join(r.dir, JournalFile)) |
| + return string(b) |
| +} |
| + |
| +// 2 (N2): a deleted VPC does not prove a gateway gone (a gateway can be |
| +// detached, or never attached); deleted-parent inference is only for types |
| +// that cannot outlive their parent. |
| +func TestDeletedParentOnlyForContainedTypes(t *testing.T) { |
| + r, fake := tfRig(t, "REC tf network/module.network.aws_vpc.services id=vpc-0svc type=aws_vpc source=state", |
| + "DELETED tf network/module.network.aws_vpc.services read-gone", |
| + "INTENT tf network/module.network.aws_internet_gateway.services - type=aws_internet_gateway run=r1 nametag=equipo-hosted-services parent=vpc-0svc") |
| + os.WriteFile(filepath.Join(fake, "plan.json"), []byte(`{"planned_values":{"root_module":{}}}`), 0o600) |
| + r.cloud.lookup = func(LookupKey) (LookupResult, error) { return LookupResult{}, nil } |
| + r.want(ExitStop, "tf", "reconcile", "network") |
| + if r.ledger().CreationState("tf", "network/module.network.aws_internet_gateway.services") != StateUnresolved { |
| + t.Fatal("a gateway was resolved absent by its VPC's deletion") |
| + } |
| + for _, typ := range containedTypes { |
| + if typ == "aws_internet_gateway" || typ == "aws_eip" || typ == "aws_instance" { |
| + t.Fatalf("%s can outlive its parent and is not a contained type", typ) |
| + } |
| + } |
| +} |
| + |
| +// genuinePlan is the prod network fixture with the root's own provider |
| +// expressions put back (plan_check_test.py's genuine()), edited by edit. |
| +func genuinePlan(t *testing.T, name, edit string) []byte { |
| + t.Helper() |
| + scripts, _ := filepath.Abs(filepath.Join("..", "..", "infra", "hosted", "scripts")) |
| + prog := `import json, sys |
| +sys.path.insert(0, sys.argv[1]) |
| +import plan_check_test as t |
| +p = t.genuine(sys.argv[2]) |
| +NET = t.NET |
| +` + edit + ` |
| +json.dump(p, sys.stdout)` |
| + out, err := exec.Command("python3", "-I", "-c", prog, scripts, name).Output() |
| + if err != nil { |
| + t.Fatalf("building the plan: %v", err) |
| + } |
| + return out |
| +} |
| + |
| +// 3 (N6): adopting a subnet whose VPC the run already manages: the |
| +// targeted plan imports the subnet and lists the VPC as an unchanged |
| +// managed no-op. The real plan-check accepts it, the import applies, the |
| +// destroy removes both, and verify-gone proves them gone. |
| +func TestAdoptionBesideManagedDependency(t *testing.T) { |
| + r, fake := tfRig(t, "REC tf network/module.network.aws_vpc.vm id=vpc-0vm type=aws_vpc source=state", |
| + "INTENT tf network/module.network.aws_subnet.vm - type=aws_subnet run=r1 nametag=equipo-hosted-vm parent=vpc-0vm", |
| + "ADOPT network/module.network.aws_subnet.vm subnet-0orphan", |
| + "REC tf network/module.network.aws_subnet.vm id=subnet-0orphan type=aws_subnet source=outside-state") |
| + adopt := genuinePlan(t, "prod-network", `vpc = [rc for rc in p["resource_changes"] if rc["address"] == NET + "aws_vpc.vm"][0] |
| +sub = [rc for rc in p["resource_changes"] if rc["address"] == NET + "aws_subnet.vm"][0] |
| +vpc["change"]["actions"] = ["no-op"] |
| +sub["change"]["actions"] = ["no-op"] |
| +sub["change"]["importing"] = {"id": "subnet-0orphan"} |
| +p["resource_changes"] = [vpc, sub]`) |
| + destroy := genuinePlan(t, "prod-network-destroy", "") |
| + os.WriteFile(filepath.Join(fake, "plan-adopt-network.json"), adopt, 0o600) |
| + os.WriteFile(filepath.Join(fake, "plan-destroy-network.json"), destroy, 0o600) |
| + os.WriteFile(filepath.Join(fake, "state.json"), []byte(`{"values":{"root_module":{}}}`), 0o600) |
| + scripts, _ := filepath.Abs(filepath.Join("..", "..", "infra", "hosted", "scripts", "plan-check.py")) |
| + r.deps.PlanCheck = []string{"python3", "-I", scripts} |
| + r.cloud.lookup = func(LookupKey) (LookupResult, error) { return LookupResult{Definitive: true}, nil } |
| + r.want(0, "tf", "network", "destroy-network") |
| + if !r.has("IMPORTED", "network/module.network.aws_subnet.vm subnet-0orphan checked-plan") || |
| + !r.has("DELETED", "tf network/module.network.aws_subnet.vm") || !r.has("DELETED", "tf network/module.network.aws_vpc.vm") { |
| + t.Fatalf("the adoption and destroy did not both complete:\n%s", journalText(r)) |
| + } |
| + r.want(0, "verify-gone") |
| + var d struct { |
| + Changes []json.RawMessage `json:"resource_changes"` |
| + } |
| + if json.Unmarshal(destroy, &d) != nil || len(d.Changes) < 20 { |
| + t.Fatal("the destroy plan is not the genuine fixture") |
| + } |
| +} |
diff --git a/internal/hostedops/ops.go b/internal/hostedops/ops.go| index 861d5e13..dba8b74f 100644 |
| --- a/internal/hostedops/ops.go |
| +++ b/internal/hostedops/ops.go |
| @@ -382,6 +382,18 @@ func (o *Ops) main(args []string) int { |
| } |
| o.j = &Journal{Path: o.path(JournalFile), Now: o.Clock.Now, noSync: o.noSync} |
| name, c, rest, ok := lookup(fs.Args()) |
| + if !ok && len(fs.Args()) >= 1 { |
| + var subs []string |
| + for n := range commands { |
| + if strings.HasPrefix(n, fs.Args()[0]+" ") { |
| + subs = append(subs, n) |
| + } |
| + } |
| + if len(subs) > 0 { // a group named without its subcommand |
| + sort.Strings(subs) |
| + return o.report(usagef("%s needs a subcommand: %s", fs.Args()[0], strings.Join(subs, ", "))) |
| + } |
| + } |
| if !ok { |
| return o.report(usagef("unknown command %q; commands: %s", strings.Join(fs.Args(), " "), commandNames())) |
| } |
diff --git a/internal/hostedops/stop.go b/internal/hostedops/stop.go| index 28e1a06d..86897765 100644 |
| --- a/internal/hostedops/stop.go |
| +++ b/internal/hostedops/stop.go |
| @@ -101,6 +101,11 @@ const RecoveryBlock = "recovery" |
| func cmdSafeStop(o *Ops, args []string) error { |
| switch { |
| case len(args) == 1 && args[0] == "--recovery": |
| + // Recovery runs only in the recovery unit (after-cap fix 1). |
| + if u := o.unitName(RecoveryBlock); o.selfUnit() != u { |
| + _ = o.jw("ABORT", "safe-stop --recovery outside %s", u) |
| + return stopf("safe-stop --recovery runs only inside %s; this process is in %q", u, o.selfUnit()) |
| + } |
| return o.recover() |
| case len(args) != 0: |
| return usagef("safe-stop takes no arguments") |
| @@ -121,11 +126,15 @@ func (o *Ops) requestRecovery() error { |
| return o.recover() |
| } |
| if o.Systemd.State(u) == "running" { |
| - _ = o.jw("RECOVERY", "requested; %s is already running", u) |
| + _ = o.jw("RECOVERY", "requested; joining %s, already running", u) |
| } else { |
| _ = o.jw("RECOVERY", "requested; starting %s", u) |
| if err := o.startUnit(RecoveryBlock, o.selfArgv("safe-stop", "--recovery"), SafeStopBound+5*time.Minute, true); err != nil { |
| - return stopf("the recovery unit did not start: %v", err) |
| + // A start collision (another requester started it first) joins. |
| + if o.Systemd.State(u) != "running" { |
| + return stopf("the recovery unit did not start: %v", err) |
| + } |
| + _ = o.jw("RECOVERY", "joining %s: another requester started it (%v)", u, err) |
| } |
| } |
| end := o.Clock.Now().Add(SafeStopBound + 5*time.Minute) |
diff --git a/internal/hostedops/tf.go b/internal/hostedops/tf.go| index 3c3aea39..3138dc4e 100644 |
| --- a/internal/hostedops/tf.go |
| +++ b/internal/hostedops/tf.go |
| @@ -541,7 +541,7 @@ func (o *Ops) tfReconcile(root string) error { |
| } |
| continue |
| } |
| - if p := in.Attr("parent"); p != "" && parentDeleted(l, p) { |
| + if p := in.Attr("parent"); p != "" && slices.Contains(containedTypes, in.Attr("type")) && parentDeleted(l, p) { |
| // The parent's verified deletion took its children with it (N2). |
| if err := o.jw("NOTCREATED", "tf %s parent-deleted %s", in.Name, p); err != nil { |
| return err |
| @@ -889,3 +889,9 @@ func (o *Ops) adoptPending(root, dir, vars string) error { |
| } |
| return clear() |
| } |
| + |
| +// containedTypes are the types deleted-parent inference applies to: each |
| +// lives inside its VPC, which EC2 will not delete while it exists, so a |
| +// verified VPC deletion proves it gone. A gateway, an Elastic IP or an |
| +// instance can outlive or leave a VPC, and is not here (after-cap fix 2). |
| +var containedTypes = []string{"aws_subnet", "aws_route_table", "aws_security_group", "aws_network_acl"} |
diff --git a/internal/hostedops/units.go b/internal/hostedops/units.go| index 1bf4df05..763fe32b 100644 |
| --- a/internal/hostedops/units.go |
| +++ b/internal/hostedops/units.go |
| @@ -44,6 +44,10 @@ var UnitEnv = []string{"PATH", "HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "L |
| "GOENV", "SSL_CERT_FILE", "SSL_CERT_DIR", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", |
| "no_proxy", "CGO_ENABLED"} |
| +// unitWrapper starts a unit's program with only the allowlisted |
| +// assignments that follow it and the unit's own INVOCATION_ID. |
| +const unitWrapper = `exec /usr/bin/env -i "INVOCATION_ID=${INVOCATION_ID:-}" "$@"` |
| + |
| var blockPattern = regexp.MustCompile(`^[0-9A-Za-z][0-9A-Za-z.-]{0,30}$`) |
| const exitPost = `#!/bin/sh |
| @@ -113,7 +117,11 @@ func (o *Ops) startUnit(block string, argv []string, stopTimeout time.Duration, |
| if err := os.MkdirAll(o.path("units"), 0o700); err != nil { |
| return failf("%v", err) |
| } |
| - full := []string{"/usr/bin/env", "-i"} |
| + // The unit's program runs under env -i with the allowlist, keeping only |
| + // the INVOCATION_ID systemd gives this unit (not a secret; known only |
| + // when the unit starts, so a shell passes it through): its own |
| + // membership then reads true from /proc/self/cgroup (after-cap fix 1). |
| + full := []string{"/bin/sh", "-c", unitWrapper, "equipo-hosted-unit"} |
| for _, v := range UnitEnv { |
| if val, ok := os.LookupEnv(v); ok { |
| full = append(full, v+"="+val) |
| @@ -418,7 +426,7 @@ func cmdUnitProbe(o *Ops, args []string) error { |
| 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") |
| + allowed := append(append([]string{}, UnitEnv...), "PWD", "SHLVL", "_", "EQUIPO_HOSTED_OPS_BLOCK", "INVOCATION_ID") |
| for _, line := range strings.Split(strings.TrimSpace(string(env)), "\n") { |
| n, _, _ := strings.Cut(line, "=") |
| up := strings.ToUpper(n) |
diff --git a/internal/isolatedjob/awsjob/opsaws/fix3_test.go b/internal/isolatedjob/awsjob/opsaws/fix3_test.go| new file mode 100644 |
| index 00000000..4ab6a1bc |
| --- /dev/null |
| +++ b/internal/isolatedjob/awsjob/opsaws/fix3_test.go |
| @@ -0,0 +1,101 @@ |
| +package opsaws |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "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" |
| + "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" |
| + vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/aws/smithy-go" |
| +) |
| + |
| +// After-cap fix: written and seen failing before the fix. |
| + |
| +// 2 (N2): attachment is not containment. A gateway that was never |
| +// attached (an interrupted attachment) or was detached, and is untagged, |
| +// is missed by both the identity listing and any attachment listing; only |
| +// an unfiltered listing of every gateway, each accounted to another intent, |
| +// proves this one absent. |
| +func TestGatewayAbsenceNeedsExhaustiveListing(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + accounted []string |
| + definite bool |
| + }{ |
| + {"interrupted attachment, untagged survivor", nil, false}, |
| + {"detached untagged survivor accounted to another intent", []string{"igw-0loose"}, true}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + var unfiltered bool |
| + cl, _ := openFake(t, func(call call) (any, error) { |
| + in, ok := call.In.(*ec2.DescribeInternetGatewaysInput) |
| + if !ok { |
| + return nil, fmt.Errorf("unexpected %s", call.Op) |
| + } |
| + if len(in.Filters) > 0 { // tags or attachment: the loose gateway has neither |
| + return &ec2.DescribeInternetGatewaysOutput{}, nil |
| + } |
| + unfiltered = true |
| + if in.NextToken == nil { // over two pages |
| + return &ec2.DescribeInternetGatewaysOutput{NextToken: aws.String("p2")}, nil |
| + } |
| + return &ec2.DescribeInternetGatewaysOutput{InternetGateways: []ec2types.InternetGateway{{InternetGatewayId: aws.String("igw-0loose")}}}, nil |
| + }) |
| + res, err := cl.Lookup(context.Background(), hostedops.LookupKey{Type: "aws_internet_gateway", NameTag: "equipo-hosted-services", |
| + Run: "r1", Parent: "vpc-0svc", Accounted: c.accounted}) |
| + if err != nil || res.Definitive != c.definite || len(res.IDs) != 0 { |
| + t.Fatalf("gateway lookup %+v, %v; want definitive %t", res, err, c.definite) |
| + } |
| + if !unfiltered { |
| + t.Fatal("no unfiltered listing of every gateway was read") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Extra: Inventory reads DescribeBudgets over two pages. |
| +func TestInventoryBudgetsTwoPages(t *testing.T) { |
| + cl, _ := openFake(t, func(c call) (any, error) { |
| + switch in := c.In.(type) { |
| + case *budgets.DescribeBudgetsInput: |
| + if aws.ToString(in.AccountId) != prod { |
| + t.Errorf("budgets of %q", aws.ToString(in.AccountId)) |
| + } |
| + if in.NextToken == nil { |
| + return &budgets.DescribeBudgetsOutput{Budgets: []budgettypes.Budget{{BudgetName: aws.String("a")}}, NextToken: aws.String("p2")}, nil |
| + } |
| + return &budgets.DescribeBudgetsOutput{Budgets: []budgettypes.Budget{{BudgetName: aws.String("b")}, {BudgetName: aws.String("c")}}}, nil |
| + case *ec2.DescribeVpcsInput: |
| + return &ec2.DescribeVpcsOutput{}, nil |
| + case *ec2.DescribeInstancesInput: |
| + return &ec2.DescribeInstancesOutput{}, nil |
| + case *s3.ListBucketsInput: |
| + return &s3.ListBucketsOutput{}, nil |
| + case *cloudtrail.DescribeTrailsInput: |
| + return &cloudtrail.DescribeTrailsOutput{}, nil |
| + case *iam.ListRolesInput: |
| + return &iam.ListRolesOutput{}, nil |
| + case *vms.ListMicrovmImagesInput: |
| + return &vms.ListMicrovmImagesOutput{}, nil |
| + case *ec2.GetEbsEncryptionByDefaultInput: |
| + return &ec2.GetEbsEncryptionByDefaultOutput{}, nil |
| + } |
| + if c.Op == "GetPublicAccessBlock" { |
| + return nil, &smithy.GenericAPIError{Code: "NoSuchPublicAccessBlockConfiguration"} |
| + } |
| + return nil, fmt.Errorf("unexpected %s", c.Op) |
| + }) |
| + inv, err := cl.Inventory(context.Background()) |
| + if err != nil || inv.Budgets != 3 || inv.BudgetsUnreadable != "" { |
| + t.Fatalf("inventory budgets %d (%q), %v; want 3 over two pages", inv.Budgets, inv.BudgetsUnreadable, err) |
| + } |
| +} |
diff --git a/internal/isolatedjob/awsjob/opsaws/lookup.go b/internal/isolatedjob/awsjob/opsaws/lookup.go| index 77d0309c..547c720f 100644 |
| --- a/internal/isolatedjob/awsjob/opsaws/lookup.go |
| +++ b/internal/isolatedjob/awsjob/opsaws/lookup.go |
| @@ -272,10 +272,11 @@ func (c *cloud) ec2ByIdentity(ctx context.Context, typ string, k hostedops.Looku |
| if len(ids) > 0 { |
| return hostedops.LookupResult{IDs: ids, Definitive: true}, nil |
| } |
| - if pf == nil { |
| + af, provable := absenceListing(typ, k.Parent) |
| + if !provable { |
| return hostedops.LookupResult{}, nil |
| } |
| - all, _, err := c.listEC2(ctx, typ, []ec2types.Filter{*pf}) |
| + all, _, err := c.listEC2(ctx, typ, af) |
| if err != nil { |
| return hostedops.LookupResult{}, err |
| } |
| @@ -295,12 +296,25 @@ func parentFilter(typ, parent string) *ec2types.Filter { |
| switch typ { |
| case "aws_subnet", "aws_security_group", "aws_route_table", "aws_network_acl", "aws_instance": |
| return &ec2types.Filter{Name: aws.String("vpc-id"), Values: []string{parent}} |
| - case "aws_internet_gateway": |
| - return &ec2types.Filter{Name: aws.String("attachment.vpc-id"), Values: []string{parent}} |
| } |
| return nil |
| } |
| +// absenceListing is the listing that can prove an intent's resource |
| +// absent: every resource of the type under its recorded parent, or, for a |
| +// gateway (which attachment does not contain: it can be detached or never |
| +// attached), every gateway in the account (after-cap fix 2). ok is false |
| +// when no listing can. |
| +func absenceListing(typ, parent string) (f []ec2types.Filter, ok bool) { |
| + if typ == "aws_internet_gateway" { |
| + return nil, true |
| + } |
| + if pf := parentFilter(typ, parent); pf != nil { |
| + return []ec2types.Filter{*pf}, true |
| + } |
| + return nil, false |
| +} |
| + |
| // listEC2 lists the live resources of typ matching f, over every page; |
| // ok is false for a type it cannot list. |
| func (c *cloud) listEC2(ctx context.Context, typ string, f []ec2types.Filter) (ids []string, ok bool, err error) { |