scripts: G2 first-service trigger matches whole lines; fixture path safe
docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md+1 −1scripts/region-ha-g2/FIXTURES.md+15 −1scripts/region-ha-g2/fixture/main.go+19 −1scripts/region-ha-g2/fixture/main_test.go+19 −0scripts/region-ha-g2/g2-firstserve-stop.sh+22 −8scripts/region_ha_g2_firstserve_test.py+145 −20
Intent
<task-notification> <task-id>bcwktiajx</task-id> <tool-use-id>toolu_017kZFZTmGHqvGBGg4fiWP7R</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/bcwktiajx.output</output-file> <status>completed</status> <summary>Background command "Wait for Tasks 6 and 8" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>af3ba57b512b6d0a2</task-id> <tool-use-id>toolu_01K5Q5SdugPi2fPET5h8gALU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/af3ba57b512b6d0a2.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 6" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Task 6 needs fixes, mainly because a slow request leaves silent gaps in the per-second evidence, which is the concern you raised. The full review is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-6-review.md`. I ran the offline unittest once: 19 tests, OK. **Spec verdict:** โ Issues found. The brief asks for one request per second per stream, and `periodic` (g2-probe.py:332-344) sends them one at a time and skips the seconds a slow request used up. Everything else in the brief is present and tested. Two things can't be checked offline: what the real AWS CLI prints for a missing key under `s3 cp`, and whether `s3 cp` retries at the transfer layer. **Quality verdict:** Needs fixes. **Critical** - A slow or hung request leaves silent gaps (g2-probe.py:332-344, 248-249, with a test that enshrines it at test:578-588). - A 5 s timeout leaves about 5 seconds with no record, and the output has no slot field or skipped row to show it. - The summary gives no expected-versus-recorded sample counts, and the longest non-200 run counts records, not seconds. A 30 s outage would show as a run of about 6. - Addendum ยง3 says missing samples mean FAIL, so these gaps fail the run. - Fix: send a request every second without waiting for the last one, with at most 6 in flight per stream. Add a `slot` field and explicit skipped rows, and have the summary report missing slots and the non-200 run in seconds. **Important** - An absent lock will probably be recorded as `read_error`, not `lock_absent` (g2-probe.py:144-147). `aws s3 cp` checks the object with HeadObject first, so a missing key reports `(404) ... HeadObject`, not `(NoSuchKey)`. The test encodes the wrong error text. Use `s3api get-object` as Task 5 does, or match the 404 HeadObject message. - Write numbers restart at 1 on every run (g2-probe.py:347-353). The fixture ignores duplicate numbers but still answers 200. So after a probe restart against the same fixture, numbers already stored count as acknowledged, and `--compare` can hide real losses. Make n unique across runs. **Minor** - The "lock reader stopped at the cap" line and worker failures go to stdout only. Add them to the JSONL. - `.acks` is written only at exit, so a SIGTERM loses it. Compare could rebuild it from the JSONL instead. - If `.acks` already exists, the probe still leaves a new empty evidence file behind. - Every curl failure except a timeout is logged as `curl_error`. Record curl's exit code. - The release-marker owner pattern requires an iid, so a marker written without one also loses its ref. - The budget preflight undercounts by one read per fixture. Use `ceil(duration / lock-every)`. - The budget refusal should show the estimate and the cap. The "pending review" header comment will go stale once copy review is done.</result> <usage><subagent_tokens>99318</subagent_tokens><tool_uses>12</tool_uses><duration_ms>163497</duration_ms></usage> </task-notification>
<task-notification> <task-id>a24b5ad82182d1b4a</task-id> <tool-use-id>toolu_01PRVssUjQ1WNDUKzBWJ3Hd9</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a24b5ad82182d1b4a.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 8" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Spec verdict:** โ Compliant. Every brief item is implemented and tested. Two things can't be confirmed from the diff and need checking: - whether the delivery line actually runs on the box (Important 1); - the "within about a second" latency, which is window rehearsal work. **Quality verdict:** Needs fixes. Tests were not re-run; the reported 25-test run and the 19 mutation logs covered everything I needed. **Critical:** none. **Important:** 1. The mandated `systemd-run ... /run/g2-firstserve.sh` line runs the script straight from `/run`, which is probably mounted noexec on these boxes. That fails safe (no stop), but it costs drill 3's narrow delivery window. - I didn't check the boxes' `/run` mount. The repo already treats tmpfs as possibly noexec (`infra/modules/region-host/group-init.sh.tftpl:19,65`). - Fix: run it through `/bin/bash /run/g2-firstserve.sh`. Self-removal still works. 2. Any HTTP client that can reach the fixture host can fire the trigger early, and it doesn't need a 200. - The script matches an unanchored `grep -F` substring (sh:69,74). The fixture logs the decoded `r.URL.Path` unsanitised (main.go:75). A crafted path such as `/x%20g2fixture%20status=200%20host=<fixture>%20` matches on a 503, 404 or 421. With `%0A` it splits into a second journal line that starts with the match text, so anchoring alone doesn't close it. - A tenant app on the same box could also print the text: app output reaches carlos-edge's journal raw, with no app prefix. - What limits the damage: it's armed only in the window, on one dev replacement box. It fires once and stops only the verified MainPID, and the operator can resume it. The real cost is a false drill 3 result, because t0 is the stamp. - Fix across two tasks: Task 7 sanitises or quotes the logged path, and Task 8 anchors the match with `^g2fixture status=200 host=<escaped> path=/`. **Minors:** 1. The MainPID read, exe check and STOP are separate steps. A restart in between fails safe (the kill finds nothing and the script refuses); only near-instant PID reuse could hit the wrong process. Optional: re-check MainPID and exe after the STOP and warn on a change. 2. The stamp records the moment just before the STOP, not the time of the matched 200, so the "within about a second" gap goes unrecorded. The stamp and the journal both vanish when the ASG terminates the box, so the card should say to read the stamp promptly. 3. `rm -f -- "$0"` runs on every exit, so running the script from a checkout deletes the tracked source. 4. `--fixture carlos` is accepted, which would let the activator readiness probe fire the trigger. 5. The forbidden-command scan misses a bare `kill "$pid"`, `pkill`, `killall`, `systemctl --signal`, `reboot` and `shutdown`. It should allowlist the four expected lines instead. 6. The `PROC_ROOT` and `ID_CMD` test hooks are honoured from the environment in a root script. systemd-run's clean environment makes this low risk; the delivery note should say not to pass `--setenv`. 7. The match-prefix test doesn't check anchoring. It changes along with Important 2. 8. If the backhauled request reaches the fixture as `host:443`, the trigger never fires. That fails safe; the rehearsal should confirm the logged host form. 9. shellcheck wasn't available, so no static lint ran on this root script. The full review is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-8-review.md`.</result> <usage><subagent_tokens>93096</subagent_tokens><tool_uses>11</tool_uses><duration_ms>240979</duration_ms></usage> </task-notification>
<task-notification> <task-id>b8lntsmk7</task-id> <tool-use-id>toolu_01TkdQx8f7mZqsHFeBoVCp3h</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/b8lntsmk7.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 6 fix round" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 88.4 g CO₂e (11,319,704 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2-prep, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md b/docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md| index c8aebd189..b55d08efa 100644 |
| --- a/docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md |
| +++ b/docs/superpowers/plans/2026-11-05-region-ha-g2-prep.md |
| @@ -489,7 +489,7 @@ GOOS=windows go build -o /dev/null ./scripts/region-ha-g2/fixture |
| - write the UTC time (`date -u +%FT%T.%NZ`) and the pid to the stamp with `set -o noclobber`. |
| 4. Then poll `/proc/<pid>/stat` once a second until the state is no longer `T` or the pid is gone. Then exit. |
| 5. `trap` on EXIT, INT and TERM: kill the `journalctl` child and `rm -f -- "$0"`. On timeout without a match, exit, remove itself and write no stamp. |
| -6. In the header, the delivery: `systemd-run --unit=g2-firstserve --collect /run/g2-firstserve.sh --fixture <host>`, so it outlives the SSM session. Record the sha256 in the window log. |
| +6. In the header, the delivery: `systemd-run --unit=g2-firstserve --collect /bin/bash /run/g2-firstserve.sh --fixture <host>`, so it outlives the SSM session and works when `/run` is mounted with `noexec`. Do not pass `--setenv` or `-E`; `PROC_ROOT` and `ID_CMD` are only for offline tests. Record the sha256 in the window log. |
| **Refusals that must hold.** |
| - It never restarts, kills or terminates anything. The only signal it sends is `-STOP`, once, to the verified `carlos-edge` MainPID. |
diff --git a/scripts/region-ha-g2/FIXTURES.md b/scripts/region-ha-g2/FIXTURES.md| index 721a143bb..d3ba74a6f 100644 |
| --- a/scripts/region-ha-g2/FIXTURES.md |
| +++ b/scripts/region-ha-g2/FIXTURES.md |
| @@ -11,7 +11,7 @@ Tasks 6 and 8 parse these formats. The exported constants in `fixture/main.go` d |
| | `FetchFormat` | `fetch status=<code> ms=<n>` | |
| | `FetchErrorFormat` | `fetch error=<class>` | |
| | `HairpinNotConfigured` | `hairpin address not configured.` | |
| -| `LogFormat` | `g2fixture status=<code> host=<r.Host> path=<path> rid=<rid>` | |
| +| `LogFormat` | `g2fixture status=<code> host=<r.Host> path=<sanitised path> rid=<rid>` | |
| | `InvalidNumberBody` | `n must be a positive integer.` | |
| | `DatabaseErrorBody` | `database error.` | |
| | `NotFoundBody` | `not found.` | |
| @@ -20,10 +20,24 @@ Tasks 6 and 8 parse these formats. The exported constants in `fixture/main.go` d |
| `POST /write?n=<int>` inserts a positive decimal integer of at most 9223372036854775807. A duplicate is ignored. A 200 write response means the write committed locally and the WAL was fsynced. It does not mean the write was replicated. `GET /` reports the same database count and maximum without writing. An empty database reports `hits=0 max=0`. `box` is the operating system hostname. In both the body and log, `rid` keeps only `[A-Za-z0-9._:-]` from `X-Request-Id`, then truncates to 64 characters. An empty result becomes `-`. Invalid numbers return 400. Database failures return 500 without `hits=`. `GET /ranges` reports the stored numbers in ascending order. Responses use `Cache-Control: no-store`. |
| +The log prefix stays `g2fixture status=<code> host=<host> path=`. The logged path comes from the decoded request path. It keeps `[A-Za-z0-9._~/%-]`, replaces every other character with `_`, then truncates to 128 characters. Spaces, newlines and control characters cannot introduce fields or log lines. This changes only the log, not request routing. |
| + |
| Set `G2_FIXTURE_HOSTS` to the fixture's own hostname. This optional comma-separated list matches the request Host exactly, including any port. Spaces around list entries are ignored. When configured, every request with an unlisted Host returns 421. This includes `/fetch`, which refuses before making an outgoing request. When unset, all Hosts are accepted. |
| The activator's readiness probe logs `host=carlos path=/` on wake. With the host list set to the fixture's hostname, this probe gets 421, which the activator accepts because it is below 500. Evidence consumers must match on the fixture host so readiness probes do not enter the drill evidence. |
| +For T4, the rehearsal must confirm that a backhauled request logs the exact fixture hostname without a port. The trigger accepts a plain lowercase DNS name with at least one dot and matches `g2fixture status=200 host=<fixture> path=/` only at the start of a line. Another app on the box can still print that line. Keep the drill's journal sources controlled during the approved window. |
| + |
| +Deliver the trigger through Bash so it works when `/run` is mounted with `noexec`: |
| + |
| +```sh |
| +systemd-run --unit=g2-firstserve --collect /bin/bash /run/g2-firstserve.sh --fixture <host> |
| +``` |
| + |
| +Do not pass `--setenv` or `-E`. `PROC_ROOT` and `ID_CMD` are only for offline tests. Record the delivered script's SHA-256 in the window log. The script removes itself only when its path is under `/run`. |
| + |
| +Read and save the stamp promptly through the window's approved SSM session because the Auto Scaling Group (ASG) terminates the box. The stamp records `match_read_utc`, `stop_utc` and `pid`. The first time is when the script read the matching line, not the journal entry's original time. The second is immediately before STOP. Both times are UTC. The script also prints both times and the PID. |
| + |
| `GET /fetch` makes an HTTPS GET of `/` on the incoming Host, with that hostname as TLS Server Name Indication (SNI). A Host port is retained in the URL and removed from SNI. The connection goes only to `G2_HAIRPIN_ADDR`, with no proxy or redirect following and a five-second timeout. TLS certificates must validate against the system trust store. The outer response is 200 when an HTTP response arrives, including a redirect; `status` is that response's code and `ms` is elapsed whole milliseconds. An unset address returns 503. A request failure returns 502 with class `timeout`, `tls`, `connect` or `request`. `request` means the URL could not be built; other transport failures use `connect`. No error body contains raw network errors. |
| ## Create the window fixtures. |
diff --git a/scripts/region-ha-g2/fixture/main.go b/scripts/region-ha-g2/fixture/main.go| index 14528f906..74bbc0c33 100644 |
| --- a/scripts/region-ha-g2/fixture/main.go |
| +++ b/scripts/region-ha-g2/fixture/main.go |
| @@ -24,6 +24,9 @@ import ( |
| // the logger supplies the log line's LF without a timestamp or prefix. |
| // ResponseFormat and LogFormat use a rid containing only [A-Za-z0-9._:-], |
| // truncated to 64 characters after filtering, with "-" for an empty result. |
| +// LogFormat keeps the prefix "g2fixture status=<code> host=<host> path=". |
| +// Its path keeps [A-Za-z0-9._~/%-], replaces other characters with "_", and |
| +// truncates to 128 characters so decoded request paths cannot forge log lines. |
| const ( |
| ResponseFormat = "g2fixture box=%s hits=%d max=%d rid=%s\n" |
| RangesFormat = "%s\n" |
| @@ -72,7 +75,22 @@ func (f *fixture) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| w.WriteHeader(status) |
| fmt.Fprint(w, body) |
| - f.logger.Printf(LogFormat, status, r.Host, r.URL.Path, rid) |
| + f.logger.Printf(LogFormat, status, r.Host, logPath(r.URL.Path), rid) |
| +} |
| + |
| +func logPath(raw string) string { |
| + var path strings.Builder |
| + for _, c := range raw { |
| + if c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.ContainsRune("._~/%-", c) { |
| + path.WriteByte(byte(c)) |
| + } else { |
| + path.WriteByte('_') |
| + } |
| + if path.Len() == 128 { |
| + break |
| + } |
| + } |
| + return path.String() |
| } |
| func requestID(raw string) string { |
diff --git a/scripts/region-ha-g2/fixture/main_test.go b/scripts/region-ha-g2/fixture/main_test.go| index 4d6f1fb65..d218094c3 100644 |
| --- a/scripts/region-ha-g2/fixture/main_test.go |
| +++ b/scripts/region-ha-g2/fixture/main_test.go |
| @@ -141,6 +141,25 @@ func TestFixtureRequestID(t *testing.T) { |
| } |
| } |
| +func TestFixturePathLog(t *testing.T) { |
| + f, logs := testFixture(t) |
| + for _, tc := range []struct{ target, path string }{ |
| + {"/x%20g2fixture%20status=200%20host=example.com%20path=/%0Ag2fixture%20status=200%20host=example.com%20path=/", "/x_g2fixture_status_200_host_example.com_path_/_g2fixture_status_200_host_example.com_path_/"}, |
| + {"/Az09._~/%25-", "/Az09._~/%-"}, |
| + {"/x%00%09%0D%1B%7F%C3%A9", "/x______"}, |
| + {"/" + strings.Repeat("a", 128), "/" + strings.Repeat("a", 127)}, |
| + } { |
| + t.Run(tc.target, func(t *testing.T) { |
| + logs.Reset() |
| + w := request(f, "GET", tc.target, "") |
| + want := "g2fixture status=404 host=fixture.invalid path=" + tc.path + " rid=-\n" |
| + if w.Code != 404 || logs.String() != want { |
| + t.Fatalf("status=%d log=%q want=%q", w.Code, logs.String(), want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| func TestFixtureInvalidNumber(t *testing.T) { |
| f, _ := testFixture(t) |
| for _, n := range []string{"", "0", "-1", "1.2", "x", "%2B1", "1%20", "9223372036854775808", "1&n=2"} { |
diff --git a/scripts/region-ha-g2/g2-firstserve-stop.sh b/scripts/region-ha-g2/g2-firstserve-stop.sh| index 69aac59c7..2b468747b 100755 |
| --- a/scripts/region-ha-g2/g2-firstserve-stop.sh |
| +++ b/scripts/region-ha-g2/g2-firstserve-stop.sh |
| @@ -1,7 +1,10 @@ |
| #!/usr/bin/env bash |
| # Deliver a copy to /run/g2-firstserve.sh during the approved drill window. |
| -# systemd-run --unit=g2-firstserve --collect /run/g2-firstserve.sh --fixture <host> |
| -# Record its sha256 in the window log. This one-shot removes its own script. |
| +# systemd-run --unit=g2-firstserve --collect /bin/bash /run/g2-firstserve.sh --fixture <host> |
| +# Do not pass --setenv or -E. PROC_ROOT and ID_CMD are only for offline tests. |
| +# Record its sha256 in the window log. Only copies under /run remove themselves. |
| +# The rehearsal must confirm that the logged host is the fixture name without a port. |
| +# Read the stamp promptly. The ASG terminates the box and the stamp is lost. |
| set -u -o pipefail |
| @@ -29,7 +32,9 @@ cleanup() { |
| local status=$? |
| trap - EXIT INT TERM |
| stop_journal |
| - rm -f -- "$0" |
| + if [[ "$0" == /run/* && "$0" != */../* ]]; then |
| + rm -f -- "$0" |
| + fi |
| printf 'First-service trigger exited with status %s.\n' "$status" |
| exit "$status" |
| } |
| @@ -57,7 +62,8 @@ while (( $# )); do |
| esac |
| done |
| -[[ "$fixture" =~ ^[A-Za-z0-9][A-Za-z0-9.:-]*$ ]] || refuse "A fixture host is required without spaces or control characters." |
| +dns_label='[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?' |
| +[[ ${#fixture} -le 253 && "$fixture" =~ ^${dns_label}(\.${dns_label})+$ ]] || refuse "The fixture must be a plain lowercase DNS name with at least one dot." |
| [[ "$stamp" == /* && "$stamp" != *$'\n'* ]] || refuse "The stamp path must be absolute without a newline." |
| [[ "$timeout" =~ ^[1-9][0-9]*$ && ${#timeout} -le 10 ]] && (( timeout <= 2147483647 )) || refuse "The timeout must be a positive whole number of seconds up to 2147483647." |
| uid=$("$ID_CMD" -u) || refuse "Could not verify the current user." |
| @@ -66,26 +72,34 @@ systemctl is-active --quiet carlos-edge || refuse "The carlos-edge service is no |
| [[ ! -e "$stamp" && ! -L "$stamp" ]] || refuse "The stamp already exists." |
| printf 'Waiting for the first successful fixture response for %s.\n' "$fixture" |
| -match="g2fixture status=200 host=${fixture} " |
| +fixture_regex=${fixture//./\\.} |
| +match="^g2fixture status=200 host=${fixture_regex} path=/" |
| # Separate descriptors keep a quiet journal from holding up timeout or cleanup. |
| # Use exec so the recorded child is journalctl itself, not a pipeline shell. |
| exec {journal_fd}< <(exec journalctl -u carlos-edge -f -n0 -o cat) |
| journal_pid=$! |
| -exec {match_fd}< <(exec grep -F --line-buffered -m1 -- "$match" <&"$journal_fd") |
| +exec {match_fd}< <(exec grep -E --line-buffered -m1 -- "$match" <&"$journal_fd") |
| matcher_pid=$! |
| IFS= read -r -t "$timeout" matched <&"$match_fd" || refuse "No matching response arrived before the journal ended or the timeout expired." |
| +match_read_utc=$(date -u +%FT%T.%NZ) || refuse "Could not read the UTC time." |
| printf 'Matched the first successful fixture response for %s.\n' "$fixture" |
| pid=$(systemctl show -p MainPID --value carlos-edge) || refuse "Could not read the carlos-edge MainPID." |
| [[ "$pid" =~ ^[1-9][0-9]*$ && "$pid" != 1 ]] || refuse "The carlos-edge MainPID is not a process that can be suspended." |
| exe=$(readlink -- "$PROC_ROOT/$pid/exe") || refuse "Could not verify the carlos-edge executable." |
| [[ "$exe" == /opt/carlos/?* ]] || refuse "The carlos-edge executable is outside /opt/carlos." |
| -timestamp=$(date -u +%FT%T.%NZ) || refuse "Could not read the UTC time." |
| [[ ! -e "$stamp" && ! -L "$stamp" ]] || refuse "The stamp already exists." |
| +stop_utc=$(date -u +%FT%T.%NZ) || refuse "Could not read the UTC time." |
| env kill -STOP "$pid" || refuse "Could not suspend carlos-edge." |
| -if ! (set -o noclobber; printf '%s %s\n' "$timestamp" "$pid" > "$stamp"); then |
| +post_pid=$(systemctl show -p MainPID --value carlos-edge) || post_pid='' |
| +post_exe=$(readlink -- "$PROC_ROOT/$pid/exe") || post_exe='' |
| +if [[ "$post_pid" != "$pid" || "$post_exe" != "$exe" ]]; then |
| + printf 'Warning: The carlos-edge MainPID or executable changed after STOP.\n' >&2 |
| +fi |
| +if ! (set -o noclobber; printf 'match_read_utc=%s stop_utc=%s pid=%s\n' "$match_read_utc" "$stop_utc" "$pid" > "$stamp"); then |
| refuse "The process was suspended but its stamp could not be written." |
| fi |
| +printf 'Recorded match read UTC %s and pre-STOP UTC %s for PID %s.\n' "$match_read_utc" "$stop_utc" "$pid" |
| stop_journal |
| while [[ -e "$PROC_ROOT/$pid/stat" ]]; do |
diff --git a/scripts/region_ha_g2_firstserve_test.py b/scripts/region_ha_g2_firstserve_test.py| index b5ade9cc8..c04591b5f 100644 |
| --- a/scripts/region_ha_g2_firstserve_test.py |
| +++ b/scripts/region_ha_g2_firstserve_test.py |
| @@ -1,4 +1,4 @@ |
| -"""Offline tests for the copied, self-removing G2 drill script.""" |
| +"""Offline tests for the G2 drill script with signals and service calls shimmed.""" |
| import json |
| import os |
| @@ -40,7 +40,11 @@ elif name == 'systemctl': |
| if args == ['is-active', '--quiet', 'carlos-edge']: |
| sys.exit(0 if os.environ.get('ACTIVE', '1') == '1' else 1) |
| assert args == ['show', '-p', 'MainPID', '--value', 'carlos-edge'] |
| - print(os.environ['MAIN_PID']) |
| + stopped = any(json.loads(line)[0] == 'kill' |
| + for line in pathlib.Path(os.environ['CALLS']).read_text().splitlines()) |
| + if stopped and os.environ.get('POST_PID_FAIL'): |
| + sys.exit(1) |
| + print(os.environ.get('POST_PID', os.environ['MAIN_PID']) if stopped else os.environ['MAIN_PID']) |
| elif name == 'journalctl': |
| assert args == ['-u', 'carlos-edge', '-f', '-n0', '-o', 'cat'] |
| def finish(*_): |
| @@ -61,9 +65,20 @@ elif name == 'kill': |
| assert len(args) == 2 and args[0] == '-STOP' |
| if os.environ.get('STAMP_RACE') == '1': |
| pathlib.Path(os.environ['STAMP']).write_text('Another run.\n') |
| + if 'POST_EXE' in os.environ: |
| + exe = pathlib.Path(os.environ['PROC_ROOT']) / args[1] / 'exe' |
| + exe.unlink() |
| + if os.environ['POST_EXE']: |
| + exe.symlink_to(os.environ['POST_EXE']) |
| elif name == 'date': |
| assert args == ['-u', '+%FT%T.%NZ'] |
| - print('2026-11-05T12:34:56.123456789Z') |
| + count = sum(json.loads(line)[0] == 'date' |
| + for line in pathlib.Path(os.environ['CALLS']).read_text().splitlines()) |
| + if count == 2 and os.environ.get('FAIL_SECOND_CLOCK'): |
| + sys.exit(1) |
| + print(f'2026-11-05T12:34:{55 + count}.123456789Z') |
| +elif name == 'rm': |
| + assert args == ['-f', '--', os.environ['SCRIPT_ARGV0']] |
| else: |
| raise AssertionError(name) |
| ''' |
| @@ -78,7 +93,7 @@ class FirstServeStopTests(unittest.TestCase): |
| self.root = Path(self.tmp.name) |
| self.bin = self.root / 'bin' |
| self.bin.mkdir() |
| - for name in ('fake-id', 'systemctl', 'journalctl', 'kill', 'date'): |
| + for name in ('fake-id', 'systemctl', 'journalctl', 'kill', 'date', 'rm'): |
| shim = self.bin / name |
| shim.write_text(SHIM) |
| shim.chmod(0o700) |
| @@ -118,12 +133,18 @@ class FirstServeStopTests(unittest.TestCase): |
| def signals(self): |
| return [call[1:] for call in self.calls() if call[0] == 'kill'] |
| - def start(self, args=None, **env): |
| + def start(self, args=None, argv0=None, **env): |
| self.copy.write_text(SCRIPT.read_text()) |
| - self.copy.chmod(0o700) |
| + self.copy.chmod(0o600) |
| if args is None: |
| args = ['--fixture', HOST, '--stamp', str(self.stamp), '--timeout', '1'] |
| - child = subprocess.Popen(['bash', str(self.copy), *args], env=dict(self.env, **env), |
| + command = ['/bin/bash', str(self.copy), *args] |
| + if argv0 is not None: |
| + # Exercise delivery's $0 without writing to /run. rm is a recording shim. |
| + command = ['/bin/bash', '-c', 'script=$1; shift; source "$script"', |
| + argv0, str(self.copy), *args] |
| + env['SCRIPT_ARGV0'] = argv0 |
| + child = subprocess.Popen(command, env=dict(self.env, **env), |
| stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, |
| start_new_session=True) |
| self.addCleanup(self.reap, child) |
| @@ -139,7 +160,7 @@ class FirstServeStopTests(unittest.TestCase): |
| def finish(self, child): |
| stdout, stderr = child.communicate(timeout=6) |
| - self.assertFalse(self.copy.exists(), stdout + stderr) |
| + self.assertTrue(self.copy.exists(), stdout + stderr) |
| if self.journal_pid.exists(): |
| self.assertTrue(self.journal_exit.exists(), stdout + stderr) |
| with self.assertRaises(ProcessLookupError): |
| @@ -170,23 +191,83 @@ class FirstServeStopTests(unittest.TestCase): |
| fixture_line(host=HOST + ':443')) |
| self.assert_refused() |
| + def test_midline_match_never_triggers(self): |
| + self.lines.write_text('another app: ' + fixture_line()) |
| + self.assert_refused(JOURNAL_EOF='1') |
| + |
| + def test_sanitised_spoofed_path_never_triggers(self): |
| + # The decoded %20 and %0A attack in TestFixturePathLog has this log path. |
| + path = '/x_g2fixture_status_200_host_example.com_path_/_g2fixture_status_200_host_example.com_path_/' |
| + self.lines.write_text(LOG_FORMAT % (404, HOST, path, '-') + '\n') |
| + self.assert_refused(JOURNAL_EOF='1') |
| + |
| + def test_fixture_dots_are_literal(self): |
| + self.lines.write_text(fixture_line(host='exampleXcom')) |
| + self.assert_refused(JOURNAL_EOF='1') |
| + |
| + def test_path_field_is_required(self): |
| + self.lines.write_text(f'g2fixture status=200 host={HOST} rid=-\n') |
| + self.assert_refused(JOURNAL_EOF='1') |
| + |
| def test_matching_200_stops_once_and_stamps(self): |
| self.lines.write_text(fixture_line() * 5) |
| code, output = self.run_script() |
| self.assertEqual(code, 0, output) |
| self.assertEqual(self.signals(), [['-STOP', self.pid]]) |
| - self.assertEqual(self.stamp.read_text(), f'2026-11-05T12:34:56.123456789Z {self.pid}\n') |
| - self.assertIn(['systemctl', 'show', '-p', 'MainPID', '--value', 'carlos-edge'], self.calls()) |
| + self.assertEqual(self.stamp.read_text(), |
| + 'match_read_utc=2026-11-05T12:34:56.123456789Z ' |
| + f'stop_utc=2026-11-05T12:34:57.123456789Z pid={self.pid}\n') |
| + calls = self.calls() |
| + show = ['systemctl', 'show', '-p', 'MainPID', '--value', 'carlos-edge'] |
| + self.assertEqual(calls.count(show), 2) |
| + self.assertLess(calls.index(['date', '-u', '+%FT%T.%NZ']), calls.index(show)) |
| + stop = calls.index(['kill', '-STOP', self.pid]) |
| + self.assertEqual(calls[stop - 1], ['date', '-u', '+%FT%T.%NZ']) |
| + self.assertEqual(calls[stop + 1], show) |
| + self.assertNotIn('Warning:', output) |
| for line in output.splitlines(): |
| self.assertTrue(line.endswith('.'), line) |
| def test_match_prefix_comes_from_frozen_constant(self): |
| - expected = (LOG_FORMAT % (200, HOST, '/', '-')).split('path=', 1)[0] |
| + expected = '^' + re.escape((LOG_FORMAT % (200, HOST, '/', '-')).split(' rid=', 1)[0]) |
| source = SCRIPT.read_text() |
| match = re.search(r'^match="([^"]+)"$', source, re.M) |
| self.assertIsNotNone(match) |
| - self.assertEqual(match.group(1).replace('${fixture}', HOST), expected) |
| - self.assertIn('grep -F --line-buffered -m1 -- "$match"', source) |
| + self.assertEqual(match.group(1).replace('${fixture_regex}', HOST.replace('.', r'\.')), |
| + expected.replace(r'\ ', ' ')) |
| + self.assertIn('grep -E --line-buffered -m1 -- "$match"', source) |
| + |
| + def test_delivery_and_self_removal(self): |
| + self.assertIn('systemd-run --unit=g2-firstserve --collect /bin/bash ' |
| + '/run/g2-firstserve.sh --fixture <host>', SCRIPT.read_text()) |
| + for argv0, removed in (('/run/g2-firstserve.sh', True), |
| + ('/run/g2-test/g2-firstserve.sh', True), |
| + (str(self.copy), False), |
| + ('/run/../checkout/g2-firstserve.sh', False), |
| + ('/runner/g2-firstserve.sh', False)): |
| + with self.subTest(argv0=argv0): |
| + self.calls_path.unlink(missing_ok=True) |
| + self.assert_refused(argv0=argv0, TEST_UID='1000') |
| + removals = [call for call in self.calls() if call[0] == 'rm'] |
| + self.assertEqual(removals, [['rm', '-f', '--', argv0]] if removed else []) |
| + self.calls_path.unlink(missing_ok=True) |
| + code, output = self.run_script(argv0='/run/g2-firstserve.sh') |
| + self.assertEqual(code, 0, output) |
| + self.assertIn(['rm', '-f', '--', '/run/g2-firstserve.sh'], self.calls()) |
| + |
| + def test_identity_changes_after_stop_warn(self): |
| + for env in ({'POST_PID': '999999'}, {'POST_EXE': '/opt/carlos/other'}, |
| + {'POST_PID_FAIL': '1'}, {'POST_EXE': ''}): |
| + with self.subTest(env=env): |
| + self.calls_path.unlink(missing_ok=True) |
| + self.stamp.unlink(missing_ok=True) |
| + (self.process / 'exe').unlink(missing_ok=True) |
| + (self.process / 'exe').symlink_to('/opt/carlos/carlos') |
| + code, output = self.run_script(**env) |
| + self.assertEqual(code, 0, output) |
| + self.assertIn('Warning: The carlos-edge MainPID or executable changed after STOP.', output) |
| + self.assertEqual(self.signals(), [['-STOP', self.pid]]) |
| + self.assertTrue(self.stamp.exists()) |
| def test_state_leaving_T_exits(self): |
| self.set_state('T') |
| @@ -277,6 +358,9 @@ class FirstServeStopTests(unittest.TestCase): |
| def test_failed_clock_does_not_stop(self): |
| self.assert_refused(FAIL_AT='date -u +%FT%T.%NZ') |
| + def test_failed_second_clock_does_not_stop(self): |
| + self.assert_refused(FAIL_SECOND_CLOCK='1') |
| + |
| def test_stamp_created_after_start_refuses_before_stop(self): |
| gate = self.root / 'release-lines' |
| child = self.start(WAIT_FOR_LINES=str(gate)) |
| @@ -351,18 +435,59 @@ class FirstServeStopTests(unittest.TestCase): |
| self.assertFalse(self.stamp.exists()) |
| self.assertEqual(self.calls(), []) |
| - def test_forbidden_commands(self): |
| - source = SCRIPT.read_text() |
| - forbidden = (r'\bsystemctl\b[^\n;|&]*\b(?:restart|stop|kill)\b' |
| - r'|\bkill\s+-(?:9|KILL)\b|\baws\b|CompleteLifecycleAction|ABANDON') |
| - self.assertNotRegex(source, forbidden) |
| + def test_fixture_must_be_plain_lowercase_dns_name(self): |
| + for host in ('carlos', 'localhost', 'Example.com', 'example.com:443', |
| + 'a..b', '.example.com', 'example.com.', '-a.example', |
| + 'a-.example', 'a_b.example', 'a/b.example', 'a\nb.example', |
| + 'a' * 64 + '.example', '.'.join(['a' * 63] * 4)): |
| + with self.subTest(host=host): |
| + self.calls_path.unlink(missing_ok=True) |
| + self.assert_refused(args=['--fixture', host, '--stamp', str(self.stamp)]) |
| + self.assertEqual(self.calls(), []) |
| + |
| + def test_dns_label_boundaries_are_accepted(self): |
| + for host in ('a.b', 'g2-fixture.example.com', 'a' * 63 + '.example', |
| + '.'.join(['a' * 63] * 3 + ['b' * 61])): |
| + with self.subTest(host=host): |
| + self.calls_path.unlink(missing_ok=True) |
| + self.stamp.unlink(missing_ok=True) |
| + self.lines.write_text(fixture_line(host=host)) |
| + code, output = self.run_script(args=['--fixture', host, '--stamp', str(self.stamp), |
| + '--timeout', '1']) |
| + self.assertEqual(code, 0, output) |
| + self.assertEqual(self.signals(), [['-STOP', self.pid]]) |
| + |
| + def assert_sensitive_commands_allowed(self, source): |
| commands = [line.strip() for line in source.splitlines() |
| - if re.search(r'\bkill\s+-', line) and not line.lstrip().startswith('#')] |
| + if re.search(r'\b(?:kill|pkill|killall|systemctl|journalctl|reboot|shutdown|' |
| + r'aws|CompleteLifecycleAction|ABANDON)\b', line) |
| + and not line.lstrip().startswith('#')] |
| self.assertEqual(commands, [ |
| 'builtin kill -TERM "$journal_pid" 2>/dev/null || true', |
| - 'env kill -STOP "$pid" || refuse "Could not suspend carlos-edge."']) |
| + 'systemctl is-active --quiet carlos-edge || refuse "The carlos-edge service is not active."', |
| + 'exec {journal_fd}< <(exec journalctl -u carlos-edge -f -n0 -o cat)', |
| + 'pid=$(systemctl show -p MainPID --value carlos-edge) || refuse "Could not read the carlos-edge MainPID."', |
| + 'env kill -STOP "$pid" || refuse "Could not suspend carlos-edge."', |
| + 'post_pid=$(systemctl show -p MainPID --value carlos-edge) || post_pid=\'\'']) |
| + |
| + def test_sensitive_command_allowlist(self): |
| + source = SCRIPT.read_text() |
| + self.assert_sensitive_commands_allowed(source) |
| self.assertNotRegex(source, '[\u2013\u2014]') |
| + def test_sensitive_command_allowlist_rejects_extra_commands(self): |
| + source = SCRIPT.read_text() |
| + for command in ('kill "$pid"', 'env kill "$pid"', 'pkill carlos', 'killall carlos', |
| + 'systemctl --signal=KILL kill carlos-edge', |
| + 'systemctl kill --signal TERM carlos-edge', |
| + 'systemctl restart carlos-edge', 'systemctl stop carlos-edge', |
| + 'kill -9 "$pid"', 'reboot', 'shutdown -h now', |
| + 'journalctl --rotate', 'aws autoscaling complete-lifecycle-action', |
| + 'CompleteLifecycleAction', 'echo ABANDON'): |
| + with self.subTest(command=command): |
| + with self.assertRaises(AssertionError): |
| + self.assert_sensitive_commands_allowed(source + '\n' + command) |
| + |
| if __name__ == '__main__': |
| unittest.main() |