carlos / platform Public

region HA P3b-1 F4/F6: group boot works on the real Debian 13 AMI

F4: the group boot staged and ran the bootstrap from /run, which is
noexec on Debian 13. It now stages in /var/lib/carlos-group-boot (root
0700), re-checks the sha256 before each of the three execs, refuses a
noexec mount by name, and a static guard pins every exec line.

F6 (found by the real-AMI witness): the script's umask 077 reached the
bootstrap's install, so /opt/carlos was 0700 root and carlos-edge died
203/EXEC. The install now runs under umask 022 in a subshell, as on
fixed boxes. /etc/sysctl.d joins the root directory walker.

scripts/region-group-boot-witness.py launches one throwaway instance
from the module render with scratch SSM, an exact-key read-only role
and verified cleanup. Run 2 of 2 passed every boot step with the agent
running and admission closed; no target group or edges change. #421.

Astra implemented; Opus reviewed (R1 not ready, R2 and R3 ready);
census region-ha-p3b1-f4 approved by Opus.

Co-Authored-By: GPT-6 Astra <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from region-ha-p3b1-f4 into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 9dad87070757db5466a49549e22e1014968c1b26 parent e047662
15 files changed, +4,311 −19
  • docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md +19 −0
  • docs/superpowers/notes/region-ha-p3b1-f4-followups.md +132 −0
  • infra/modules/region-host/group-init.sh.tftpl +60 −13
  • internal/host/group_boot_budget_test.go +26 −5
  • internal/host/group_boot_staging_test.go +583 −0
  • internal/host/group_boot_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv +5 −0
  • scripts/region-group-boot-witness.py +1,573 −0
  • scripts/region_group_boot_umask_test.py +120 −0
  • scripts/region_group_boot_witness_test.py +785 −0
  • scripts/region_group_witness_fake.py +634 −0
  • scripts/testdata/region-group-f4w1.json +261 −0
  • scripts/witness-pointer/main.go +57 −0
  • scripts/witness-pointer/main_test.go +54 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md b/docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md
new file mode 100644
index 000000000..a34c3ad25
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md
@@ -0,0 +1,19 @@
+# Census approval: region-ha-p3b1-f4
+
+Ruling `census-ruling-region-ha-p3b1-f4`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `infra/modules/region-host/group-init.sh.tftpl` `external` | body | unchanged (1) | Move bootstrap and chrony staging to root:root 0700 /var/lib/carlos-group-boot through the existing O_NOFOLLOW walker; refuse unsafe preexisting directory. Bootstrap 0700; retain initial hash verification and rehash against a root-only captured SSM digest immediately before all three execs; named noexec refusal. Root reads only its own helper/hash and verified binary; no tenant/app/agent writable input or authority added. Final removal preserved. Round 5 adds /etc/sysctl.d to the same root-owned, non-writable, O_NOFOLLOW directory walker before its existing exclusive sysctl file write; missing directory is created, unsafe ancestors refuse. Round 6 scopes umask 022 to the verified host-env install exec in a subshell; its bootstrap/install-channel children create traversable install directories and readable unit files, matching fixed boxes. Parent umask remains 077; verify-identity is read-only and hairpin install creates only 0700/0600 private state. Explicitly chmod the freshly created instance-control drop-in directory 0755. host.env remains explicitly chmodded 0600 in unchanged released Go. No new input/read or write authority; all verification and directory trust checks remain. |
+
+Envelopes re-pinned: `infra/modules/region-host`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `infra/modules/region-host/group-init.sh.tftpl` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=New root user-data boot: operator Terraform/SSM supply scoped bootstrap object version/hash, queue, reader inventory and ingress; hash-verified bootstrap verifies signed IMDS identity. Root exclusively writes /etc/carlos/group.json, group-identity.json, region-config.json and group-ingress.json with current kernel boot ID; public address comes from protected IMDSv2, not signed document or headers. Install IMDS denial, chrony, dormant hairpin fence and protected drop-ins before bootstrap/install/start. No agent receipt is read by root; restart authority is separate maintenance permit. F1: operator-seeded SSM boot/bootstrap-object requires floor=absent-expected or required beside key/version/known_readers/deployment_aws_region; root copies it into group.json before config_digest. Missing or invalid floor refuses before bootstrap fetch; Terraform only names this SSM key and does not write the object. Agent and instance-control gain AF_NETLINK in their address-family allowlists, with no CAP_NET_ADMIN grant.
+
+Seal: `ec831d3206622f34511bfbc2ec0cccb131fbd3861ec4c6a33a2dc6dff9a1791e` → `71bbbf68863266ffab90211a00aff2f1b694bf39bb4bd62ea565c168ba884564`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/region-ha-p3b1-f4-followups.md b/docs/superpowers/notes/region-ha-p3b1-f4-followups.md
new file mode 100644
index 000000000..27b6a0477
--- /dev/null
+++ b/docs/superpowers/notes/region-ha-p3b1-f4-followups.md
@@ -0,0 +1,132 @@
+# P3b-1 F4 controller handoff
+
+F4 review round 1 remains closed: Opus reviewed a81a885c against amadan
+origin/main f6f91e2a, READY, 0 P1 / 0 P2 / 4 P3. It approved the external
+`group-init.sh.tftpl` census unit and the `infra/modules/region-host` envelope.
+The controller records that approval on #280. No implementer amadan write
+or new review was made in rounds 2–4.
+
+Implementer round 4 completes the witness lifecycle under Paul's final
+rulings: `floor=absent-expected (Paul 2026-11-04 21:09Z)`, the artifact SHA-256
+pin for both renders, the supplied dev public key verified through Go's
+release package, exact S3 object reads and the approved bucket-list statement.
+`LIVE_BLOCKERS` is empty. Execution requires both `--execute --i-have-budget`
+and an unused slot in the durable two-run ledger. The implementer ran no
+live witness and spent no live-run budget.
+
+The new AWS lifecycle code needs the controller's review before execution.
+The prior staging review did not cover live resource creation or cleanup.
+Carry the closed round history forward; implementation round 4 is not review
+round 4. Root source and census fingerprints are unchanged in this round.
+
+The four P3 items from the closed review now stand as follows:
+
+1. Exec-site audit: fixed the trailing `bootstrap.sha256` comment bypass and
+ added direct-exec, shell-wrapper and unverified-exec mutations.
+2. Staging lifetime: unchanged safe refusal. A failed boot may retain its
+ root-only staging directory. Rerunning user data refuses existing helper
+ or exclusive output files; never reuse those inputs. The witness always
+ terminates its instance, including on boot failure.
+3. Witness evidence: a separate cloud-boothook observer records the actual
+ staging leaf before ingress, its removal and the parent mount afterward.
+ Part 1 remains byte-identical to the module render. The collector waits
+ for the denied-publication journal event. The observer reports final
+ `cloud-init status --long` to the console after scripts finish.
+4. Render hygiene: each render uses a fresh module copy. Provider downloads
+ are cached outside that copy. The copy is removed in `finally`.
+
+P8 is explicitly inferred from successful W4. P10 checks effective installed
+edge/control unit settings, the live edge process's privileges and bind-mount
+flags. It does not repeat the separate active tenant/sidecar kernel drill or
+claim reboot coverage. No W/P real-AMI assertion has passed in this round;
+the dry-run table marks them NOT RUN.
+
+The controller's round-4 report, read-only preflight, dry-run call plan,
+assertion table and test logs are under
+`/home/paulca/.cache/p3b1-f4-work/`. The report is `astra-4-report.md`.
+Pending creates with no recoverable owned id remain LEAKED/unknown; a missing
+response never licenses declaring an instance terminated or deleting a
+same-name foreign resource. `--cleanup-only RUN` uses the original journal
+and baseline without spending a run; it preserves the original boot verdict
+and assertion table. Adding `--dry-run` only prints its plan.
+
+## Implementer round 5: lifecycle R1 fixes
+
+The lifecycle Opus R1 at `e8c9cd00` is NOT READY; its census verdict is
+APPROVED. This is separate from the closed staging R1 above. The round-5
+brief authorizes implementation fixes, targeted checks and local commits,
+with no live execution, push, amadan write or new review.
+
+P1-1 now passes raw gzip MIME through a private file and `--user-data
+fileb://...`; launch JSON contains no UserData. P2-1 writes redacted operator
+logs to the run directory and makes console output best-effort. P3-2,
+P3-3, P3-4, P3-5, P3-6, P3-7 and P3-10 are implemented and tested: exact
+bootstrap-line guards, the sysctl directory walker, a bounded independent
+observer service with monotonic observations, delete-marker chronology,
+resource-by-resource leak reporting, the fixed live budget path and SSM
+create rejection handling. The AWS adapter also preserves console text
+already decoded by botocore.
+
+The template changed by adding only `/etc/sysctl.d` to the existing walker.
+The census proposal was regenerated with the same name. The earlier census
+approval does not cover this new fingerprint; the controller owns the next
+review step. No implementer review was commissioned.
+
+The following lifecycle R1 findings remain notes only, as the round-5 brief
+requires. Their descriptions were not included in that brief, and no local
+copy of the lifecycle R1 findings was available; preserve the review's IDs
+without inventing their content:
+
+- P3-1 — carried forward from lifecycle R1; no code change in this round.
+- P3-8 — carried forward from lifecycle R1; no code change in this round.
+- P3-9 — carried forward from lifecycle R1; no code change in this round.
+
+The implementation report, per-call AWS encoding audit and validation logs
+are under `/home/paulca/.cache/p3b1-f4-work/`, starting with
+`astra-5-report.md`. Real-AMI assertions remain NOT RUN; all 24 simulated
+resources were confirmed gone. No live budget slot was consumed.
+
+## Implementer round 6: F6 and witness assertions
+
+Live run `f4w1` completed cloud-init but edge failed with 203/EXEC: the
+script's umask 077 reached the released v0.34.2 installer, which created
+`/opt/carlos` as root:root 0700. The installed binary itself was 0755.
+Only the host-env install exec now runs in a subshell with umask 022;
+the parent and both hairpin bootstrap calls retain 077. The template also
+chmods its new instance-control drop-in directory to 0755. Go explicitly
+chmods host.env to 0600; no released Go code changes in this branch.
+
+W20 was a false failure: the live journal records successful resets through
+edge's ExecStartPre and ExecStopPost. The later inactive unit had lost its
+execution timestamp. W20 now requires completed current-boot reset journal
+entries and successful result/status, including when that timestamp is zero.
+P10 correctly failed only its missing live edge process check; its installed
+unit and mount checks passed. W8 now refuses an exec attempt without an
+active edge PID. The selected f4w1 evidence and first budget reservation are
+committed test fixtures; the original evidence remains unchanged.
+
+**Deferred release work, not part of this branch:** make install modes
+independent of the caller's umask, using the existing descriptor-based
+path checks. Explicitly set `/opt/carlos`, `/opt/carlos/system` and
+`/opt/carlos/system/router` to 0755; do not fix only the final directory.
+Audit the other no-chmod creations listed in `astra-6-report.md`: host-env's
+missing `/etc/carlos`, any newly created intermediate bootstrap directory,
+`registry.db` (0640), embedded units and sysusers/tmpfiles/journald files
+(0644), and a newly created edge drop-in directory (0755). Preserve private
+0700/0600 runtime, journal, lock and consumption files, ownership handoffs,
+and host.env's explicit 0600. Cover the unit-refresh helper's mkdir paths
+too. Add a process-isolated install test under umask 077 that checks every
+mode and proves the carlos user and a separate DynamicUser-like principal
+can traverse the executable paths, while neither gains private-state
+access. Deliver that work in a new release; the third window must use this
+template fix with the existing v0.34.2 binary.
+
+The read-only recheck confirmed f4w1's terminated instance, absent IAM
+role/profile, empty parameter subtree and absent scratch bootstrap versions
+and delete markers. The original evidence object is deliberately retained.
+The live ledger still contains only f4w1; a new run ID can use the single
+remaining slot. No live execution, AWS write, push, amadan write or review
+was performed in round 6. The controller owns review of the changed template
+and census fingerprint, then the remaining live run. This implementation
+round does not reopen or reset the review histories above. Full audit and
+validation evidence: `/home/paulca/.cache/p3b1-f4-work/astra-6-report.md`.
diff --git a/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl
index df4abd22c..f858c5b53 100644
--- a/infra/modules/region-host/group-init.sh.tftpl
+++ b/infra/modules/region-host/group-init.sh.tftpl
@@ -16,27 +16,66 @@ fi
export DEBIAN_FRONTEND=noninteractive AWS_MAX_ATTEMPTS=1 AWS_RETRY_MODE=standard
# Only root-owned real directories may hold boot inputs or executed bytes.
+# Staging is on the root disk, never a tmpfs, which may be mounted noexec.
python3 - <<'PY'
import os, stat
-for path in ['/etc/apt/apt.conf.d', '/etc/needrestart/conf.d', '/etc/carlos', '/etc/chrony/conf.d', '/etc/systemd/system/carlos-edge.service.d', '/run/carlos-group-boot']:
+WORK = '/var/lib/carlos-group-boot'
+for path in ['/etc/apt/apt.conf.d', '/etc/needrestart/conf.d', '/etc/carlos', '/etc/chrony/conf.d', '/etc/systemd/system/carlos-edge.service.d', '/etc/sysctl.d', WORK]:
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY)
try:
- for part in path.strip('/').split('/'):
+ parts = path.strip('/').split('/')
+ for n, part in enumerate(parts):
+ final = path == WORK and n == len(parts) - 1
+ mode = 0o700 if final else 0o755
try:
- os.mkdir(part, 0o755, dir_fd=fd)
- os.chmod(part, 0o755, dir_fd=fd, follow_symlinks=False)
+ os.mkdir(part, mode, dir_fd=fd)
+ os.chmod(part, mode, dir_fd=fd, follow_symlinks=False)
except FileExistsError:
pass
child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
os.close(fd)
fd = child
st = os.fstat(fd)
- if st.st_uid != 0 or st.st_mode & 0o022:
+ if final:
+ if st.st_uid != 0 or st.st_gid != 0 or stat.S_IMODE(st.st_mode) != 0o700:
+ raise SystemExit('group_boot_directory')
+ elif st.st_uid != 0 or st.st_mode & 0o022:
raise SystemExit('group_boot_directory')
finally:
os.close(fd)
PY
+# Every execution of the bootstrap is preceded by this check of the staging
+# directory, the noexec flag and the bootstrap bytes against the SSM digest.
+# noclobber makes the redirect fail on an existing file or symlink.
+( set -C; cat > /var/lib/carlos-group-boot/carlos_group_boot_verify.py <<'PYVERIFY'
+import hashlib, os, re, stat, sys
+WORK = '/var/lib/carlos-group-boot'
+def regular(path, mode, owner):
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+ st = os.fstat(fd)
+ if not stat.S_ISREG(st.st_mode) or (st.st_uid, st.st_gid) != owner or stat.S_IMODE(st.st_mode) != mode or st.st_nlink != 1:
+ os.close(fd)
+ raise SystemExit('group_boot_bootstrap')
+ return os.fdopen(fd, 'rb')
+def check(work=WORK, owner=(0, 0)):
+ st = os.lstat(work)
+ if not stat.S_ISDIR(st.st_mode) or (st.st_uid, st.st_gid) != owner or stat.S_IMODE(st.st_mode) != 0o700:
+ raise SystemExit('group_boot_directory')
+ if os.statvfs(work).f_flag & os.ST_NOEXEC:
+ raise SystemExit('group_boot_noexec')
+ with regular(work + '/bootstrap.sha256', 0o600, owner) as f:
+ want = f.read(65).decode()
+ if not re.fullmatch('[0-9a-f]{64}', want):
+ raise SystemExit('group_boot_hash')
+ with regular(work + '/bootstrap', 0o700, owner) as f:
+ if hashlib.file_digest(f, 'sha256').hexdigest() != want:
+ raise SystemExit('group_boot_hash')
+if __name__ == '__main__':
+ check()
+PYVERIFY
+)
+
# disable unattended updates
systemctl disable --now apt-daily.timer apt-daily-upgrade.timer
systemctl mask --now apt-daily.timer apt-daily-upgrade.timer apt-daily.service apt-daily-upgrade.service unattended-upgrades.service
@@ -101,8 +140,8 @@ systemctl restart nftables.service
nft list table inet carlos_group_imds >/dev/null
# configure chrony
-printf '%s\n' 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4' > /run/carlos-group-boot/chrony.conf
-install -o root -g root -m 0644 /run/carlos-group-boot/chrony.conf /etc/chrony/conf.d/carlos-group.conf
+printf '%s\n' 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4' > /var/lib/carlos-group-boot/chrony.conf
+install -o root -g root -m 0644 /var/lib/carlos-group-boot/chrony.conf /etc/chrony/conf.d/carlos-group.conf
systemctl enable chrony.service
systemctl restart chrony.service
python3 - <<'PYCHRONY'
@@ -129,9 +168,9 @@ chronyc waitsync 20 2
# no published floor. Root binds this choice in group.json's config_digest;
# a published floor is always verified. Box roles cannot write this SSM value.
python3 - <<'PY'
-import base64, datetime, hashlib, ipaddress, json, os, re, subprocess, time, urllib.request
+import base64, datetime, hashlib, ipaddress, json, os, re, subprocess, sys, time, urllib.request
E = os.environ
-work = '/run/carlos-group-boot/'
+work = '/var/lib/carlos-group-boot/'
prefix = '/carlos/' + E['CARLOS_DEPLOYMENT'] + '/' + E['CARLOS_REGION'] + '/boot/'
def aws(*args, region=None):
return json.loads(subprocess.check_output(['aws', '--region', region or E['AWS_REGION'], '--cli-connect-timeout', '2', '--cli-read-timeout', '60', *args, '--output', 'json'], timeout=90))
@@ -164,7 +203,11 @@ aws('s3api', 'get-object', '--bucket', E['CARLOS_DEPLOYMENT_BUCKET'], '--key', o
with open(work + 'bootstrap', 'rb') as f:
if hashlib.file_digest(f, 'sha256').hexdigest() != sha:
raise SystemExit('group_boot_hash')
-os.chmod(work + 'bootstrap', 0o755)
+os.chmod(work + 'bootstrap', 0o700)
+write(work + 'bootstrap.sha256', sha.encode(), 0o600)
+sys.dont_write_bytecode = True
+sys.path.insert(0, work)
+import carlos_group_boot_verify as boot_verify
# Seven IMDS requests, reused through root snapshots. No runtime address poll.
class NoMetadataRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, response, code, message, headers, target):
@@ -228,6 +271,7 @@ marker['config_digest'] = hashlib.sha256(json.dumps(marker, sort_keys=True, sepa
write('/etc/carlos/group.json', json.dumps(marker, separators=(',', ':')).encode())
# Verify the signed document against the root marker before publishing the
# address snapshot. The public-IP leaf's provenance is protected IMDSv2.
+boot_verify.check()
subprocess.check_call([work + 'bootstrap', 'instance-control', '--group-hairpin-verify-identity'], timeout=10)
write('/etc/carlos/group-ingress.json', json.dumps(dict(v=1, region=E['CARLOS_REGION'], public_ips=ips, public_ipv4=public_ip, primary_ipv4=primary_ip, private_cidr=private_cidr, boot_id=boot_id, account=identity['accountId'], iid=iid), separators=(',', ':')).encode())
PY
@@ -245,6 +289,7 @@ files = {
'/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf': '[Service]\nRestrictAddressFamilies=AF_UNIX AF_NETLINK\nReadWritePaths=-/run/carlos-hairpin\n',
}
os.mkdir('/etc/systemd/system/carlos-instance-control.service.d', 0o755)
+os.chmod('/etc/systemd/system/carlos-instance-control.service.d', 0o755)
for path, body in files.items():
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
os.fchmod(fd, 0o644)
@@ -254,7 +299,8 @@ for path, body in files.items():
os.fsync(f.fileno())
PYHAIRPIN
sysctl -p /etc/sysctl.d/99-carlos-hairpin.conf
-/run/carlos-group-boot/bootstrap instance-control --group-hairpin-install
+python3 -I /var/lib/carlos-group-boot/carlos_group_boot_verify.py
+/var/lib/carlos-group-boot/bootstrap instance-control --group-hairpin-install
# Persist only the dormant owned tables; never persist assigned EIPs or an
# exemption. On reboot the reset operation refuses a stale boot snapshot.
python3 - <<'PYHAIRPIN'
@@ -273,11 +319,12 @@ PYHAIRPIN
test "$(cat /etc/systemd/system/carlos-edge.service.d/50-group.conf)" = "$(printf '[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nRestart=no')"
# bootstrap and install channel
-/run/carlos-group-boot/bootstrap system host-env write --group --deployment "$CARLOS_DEPLOYMENT" --region "$CARLOS_REGION" --aws-region "$AWS_REGION" --install
+python3 -I /var/lib/carlos-group-boot/carlos_group_boot_verify.py
+( umask 022; exec /var/lib/carlos-group-boot/bootstrap system host-env write --group --deployment "$CARLOS_DEPLOYMENT" --region "$CARLOS_REGION" --aws-region "$AWS_REGION" --install )
# host.env is parsed as data by the verified binary; it is never sourced.
# start guarded agent
systemctl daemon-reload
test "$(systemctl show carlos-edge.service --property=Restart --value)" = no
systemctl start carlos-edge.service
-rm -rf /run/carlos-group-boot
+rm -rf /var/lib/carlos-group-boot
diff --git a/internal/host/group_boot_budget_test.go b/internal/host/group_boot_budget_test.go
index ed6567e27..2e6cbbf49 100644
--- a/internal/host/group_boot_budget_test.go
+++ b/internal/host/group_boot_budget_test.go
@@ -279,6 +279,16 @@ func groupBootstrapBudget(t *testing.T) {
import ast, builtins, io, json, os, subprocess, hashlib, urllib.request, datetime
source = SOURCE
floor = FLOOR
+failcheck = FAILCHECK
+import sys, types
+checks = 0
+verifier = types.ModuleType('carlos_group_boot_verify')
+def check(*args, **kwargs):
+ global checks
+ checks += 1
+ if failcheck: raise SystemExit('group_boot_hash')
+verifier.check = check
+sys.modules['carlos_group_boot_verify'] = verifier
root='/carlos/dev/ie/boot/'
os.environ.update(dict(CARLOS_DEPLOYMENT='dev',CARLOS_REGION='ie',AWS_REGION='eu-west-1',CARLOS_BOOTSTRAP_OBJECT_KEY=root+'bootstrap-object',CARLOS_BOOTSTRAP_HASH_KEY=root+'bootstrap-sha256',CARLOS_TERMINATION_QUEUE_URL='queue',CARLOS_DEPLOYMENT_BUCKET='deploy',CARLOS_GROUP_ACCOUNT='123456789012',CARLOS_PLACEMENT_REGION='ie',CARLOS_INGRESS_KEY=root+'ingress',CARLOS_GROUP_DATA_BUCKET='data',CARLOS_GROUP_NAME='dev-ie',CARLOS_LAUNCH_HOOK_NAME='carlos-initial-launch',CARLOS_POOLS='hapair',CARLOS_RELEASE='v1.2.3'))
calls=[];decryptions=0;metadata=[]
@@ -316,12 +326,13 @@ urllib.request.build_opener=lambda *args:type("Opener",(),{"open":staticmethod(u
verified_identity=False
def verify_identity(args,timeout):
global verified_identity
- assert args==['/run/carlos-group-boot/bootstrap','instance-control','--group-hairpin-verify-identity'] and timeout==10
+ assert args==['/var/lib/carlos-group-boot/bootstrap','instance-control','--group-hairpin-verify-identity'] and timeout==10
+ assert checks==1, 'bootstrap executed without the shared verification'
verified_identity=True
subprocess.check_call=verify_identity
realopen=builtins.open
def fakeopen(path,*args,**kwargs):
- if path=='/run/carlos-group-boot/bootstrap':return io.BytesIO(b'bootstrap')
+ if path=='/var/lib/carlos-group-boot/bootstrap':return io.BytesIO(b'bootstrap')
if path=='/proc/sys/kernel/random/boot_id':return io.StringIO('boot')
raise AssertionError('unexpected file '+path)
builtins.open=fakeopen
@@ -329,6 +340,8 @@ os.chmod=lambda *args:None
writes=[];marker=None
def write(path,body,mode=0o644):
global marker
+ if path=='/var/lib/carlos-group-boot/bootstrap.sha256':
+ assert body==hashlib.sha256(b'bootstrap').hexdigest().encode() and mode==0o600
if path=='/etc/carlos/group.json':
marker=json.loads(body)
assert marker['floor']==floor
@@ -344,24 +357,32 @@ tree.body=[n for n in tree.body if not isinstance(n,ast.FunctionDef) or n.name!=
try:
exec(compile(tree,'group-init.sh.tftpl','exec'))
except SystemExit as err:
+ if failcheck:
+ assert str(err)=='group_boot_hash' and checks==1 and not verified_identity and '/etc/carlos/group-ingress.json' not in writes,(err,writes)
+ print('mutated bootstrap refused before exec')
+ raise SystemExit(0)
assert floor not in ('required','absent-expected') and str(err)=='group_boot_object',err
assert len(calls)==1 and not metadata and not writes,(calls,metadata,writes)
print('invalid floor refused before bootstrap fetch')
raise SystemExit(0)
assert floor in ('required','absent-expected'), 'invalid floor accepted'
assert len(calls)==3 and decryptions==4 and len(metadata)==7,(calls,decryptions,metadata)
-assert len(writes)==4,writes
+assert not failcheck and checks==1 and len(writes)==5,(checks,writes)
print(json.dumps(marker))
`
source, _ := json.Marshal(string(raw)[start : start+end])
program = strings.Replace(program, "SOURCE", string(source), 1)
- for _, floor := range []string{"absent-expected", "required", "", "none", "missing"} {
+ for _, floor := range []string{"absent-expected", "required", "", "none", "missing", "hash-mutation"} {
t.Run(floor, func(t *testing.T) {
value := fmt.Sprintf("%q", floor)
+ failcheck := "False"
if floor == "missing" {
value = "None"
}
- cmd := exec.Command("python3", "-c", strings.Replace(program, "FLOOR", value, 1))
+ if floor == "hash-mutation" {
+ value, failcheck = `"required"`, "True"
+ }
+ cmd := exec.Command("python3", "-c", strings.Replace(strings.Replace(program, "FAILCHECK", failcheck, 1), "FLOOR", value, 1))
cmd.Dir = t.TempDir()
out, err := cmd.CombinedOutput()
if err != nil {
diff --git a/internal/host/group_boot_staging_test.go b/internal/host/group_boot_staging_test.go
new file mode 100644
index 000000000..422c893ea
--- /dev/null
+++ b/internal/host/group_boot_staging_test.go
@@ -0,0 +1,583 @@
+package host
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+const (
+ groupBootStaging = "/var/lib/carlos-group-boot"
+ groupBootVerify = "python3 -I " + groupBootStaging + "/carlos_group_boot_verify.py"
+ groupBootHostenv = `( umask 022; exec ` + groupBootStaging + `/bootstrap system host-env write --group --deployment "$CARLOS_DEPLOYMENT" --region "$CARLOS_REGION" --aws-region "$AWS_REGION" --install )`
+ groupBootDropin = "/etc/systemd/system/carlos-instance-control.service.d"
+)
+
+func groupInitTemplate(t *testing.T) string {
+ t.Helper()
+ raw, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+// between returns the text between the first start marker and the next end marker.
+func between(t *testing.T, s, start, end string) string {
+ t.Helper()
+ _, rest, ok := strings.Cut(s, start)
+ if !ok {
+ t.Fatalf("missing %q", start)
+ }
+ body, _, ok := strings.Cut(rest, end)
+ if !ok {
+ t.Fatalf("missing %q", end)
+ }
+ return body
+}
+
+var groupBootTmpfs = regexp.MustCompile(`(^|[^A-Za-z0-9_./-])(/run|/tmp|/dev|/var/tmp|/var/run|/var/lock)(/|$|[^A-Za-z0-9_.-])`)
+
+// groupBootBootstrapLines are the only non-executing lines that may mention the
+// bootstrap. Each must match a template line exactly, whole.
+var groupBootBootstrapLines = map[string]bool{
+ `# Every execution of the bootstrap is preceded by this check of the staging`: true,
+ `# directory, the noexec flag and the bootstrap bytes against the SSM digest.`: true,
+ ` raise SystemExit('group_boot_bootstrap')`: true,
+ ` with regular(work + '/bootstrap.sha256', 0o600, owner) as f:`: true,
+ ` with regular(work + '/bootstrap', 0o700, owner) as f:`: true,
+ `# fetch verified bootstrap`: true,
+ `# Operator-seeded boot/bootstrap-object has exactly key, version, known_readers,`: true,
+ `if not obj['key'].startswith('bootstrap/' + E['CARLOS_DEPLOYMENT'] + '/' + E['CARLOS_REGION'] + '/') or not obj['version'] or obj['version'] == 'null':`: true,
+ `aws('s3api', 'get-object', '--bucket', E['CARLOS_DEPLOYMENT_BUCKET'], '--key', obj['key'], '--version-id', obj['version'], work + 'bootstrap', region=obj['deployment_aws_region'])`: true,
+ `with open(work + 'bootstrap', 'rb') as f:`: true,
+ `os.chmod(work + 'bootstrap', 0o700)`: true,
+ `write(work + 'bootstrap.sha256', sha.encode(), 0o600)`: true,
+ `# The verified bootstrap revalidates the signed identity and this boot's`: true,
+ `# bootstrap and install channel`: true,
+}
+
+// checkGroupBootStaging inspects the paths the script stages, writes and
+// executes. Every bootstrap execution must be the line right after the shared
+// verification, and nothing may stage or run from a tmpfs default.
+func checkGroupBootStaging(s string) error {
+ if regexp.MustCompile(`carlos-group-boot[^/'"[:space:]]`).MatchString(s) {
+ return fmt.Errorf("unexpected staging directory suffix")
+ }
+ if n := strings.Count(s, "carlos-group-boot"); n != strings.Count(s, groupBootStaging) {
+ return fmt.Errorf("staging name used outside %s", groupBootStaging)
+ }
+ if !strings.Contains(s, "WORK = '"+groupBootStaging+"'") || !strings.Contains(s, "work = '"+groupBootStaging+"/'") {
+ return fmt.Errorf("staging constants are not %s", groupBootStaging)
+ }
+ // The one runtime directory the script names is a unit's ReadWritePaths.
+ scan := strings.ReplaceAll(s, "ReadWritePaths=-/run/carlos-hairpin", "")
+ scan = strings.ReplaceAll(scan, ">/dev/null", "")
+ if m := groupBootTmpfs.FindString(scan); m != "" {
+ return fmt.Errorf("tmpfs path %q", strings.TrimSpace(m))
+ }
+ for _, banned := range []string{"mktemp", "tempfile", "TMPDIR", "mkdtemp"} {
+ if strings.Contains(s, banned) {
+ return fmt.Errorf("default scratch location via %s", banned)
+ }
+ }
+ lines := strings.Split(s, "\n")
+ // The script runs under umask 077. Only the host-env install child widens
+ // it, inside its own subshell; no other line changes the umask.
+ umasks := 0
+ for i, line := range lines {
+ if !strings.Contains(line, "umask") {
+ continue
+ }
+ umasks++
+ if line != "umask 077" && line != groupBootHostenv {
+ return fmt.Errorf("line %d changes the umask outside the audited forms: %s", i+1, line)
+ }
+ }
+ if umasks != 2 || len(lines) < 3 || lines[2] != "umask 077" {
+ return fmt.Errorf("umask forms changed")
+ }
+ for i, line := range lines {
+ if line == "os.mkdir('"+groupBootDropin+"', 0o755)" && (i+1 >= len(lines) || lines[i+1] != "os.chmod('"+groupBootDropin+"', 0o755)") {
+ return fmt.Errorf("drop-in directory is not chmodded 0755 after mkdir")
+ }
+ }
+ if strings.Count(s, "os.mkdir('"+groupBootDropin+"', 0o755)\nos.chmod('"+groupBootDropin+"', 0o755)\n") != 1 {
+ return fmt.Errorf("drop-in directory mkdir/chmod pair changed")
+ }
+ execs := 0
+ for i, line := range lines {
+ if !strings.Contains(line, "bootstrap") {
+ continue
+ }
+ prev := ""
+ if i > 0 {
+ prev = lines[i-1]
+ }
+ switch {
+ case line == groupBootStaging+"/bootstrap instance-control --group-hairpin-install" || line == groupBootHostenv:
+ execs++
+ if prev != groupBootVerify {
+ return fmt.Errorf("line %d executes the bootstrap without the shared verification", i+1)
+ }
+ case line == "subprocess.check_call([work + 'bootstrap', 'instance-control', '--group-hairpin-verify-identity'], timeout=10)":
+ execs++
+ if prev != "boot_verify.check()" {
+ return fmt.Errorf("line %d executes the bootstrap without the shared verification", i+1)
+ }
+ case groupBootBootstrapLines[line]:
+ // Audited data, check and comment lines: they run nothing.
+ default:
+ return fmt.Errorf("line %d references the bootstrap outside the audited forms: %s", i+1, line)
+ }
+ }
+ if execs != 3 {
+ return fmt.Errorf("want 3 bootstrap executions, found %d", execs)
+ }
+ if strings.Count(s, groupBootVerify+"\n") != 2 || strings.Count(s, "boot_verify.check()\n") != 1 {
+ return fmt.Errorf("verification call sites changed")
+ }
+ return nil
+}
+
+func TestGroupBootStagingGuard(t *testing.T) {
+ good := groupInitTemplate(t)
+ if err := checkGroupBootStaging(good); err != nil {
+ t.Fatal(err)
+ }
+ install := groupBootStaging + "/bootstrap instance-control --group-hairpin-install"
+ hostenv := groupBootHostenv
+ bareHostenv := strings.TrimSuffix(strings.TrimPrefix(groupBootHostenv, "( umask 022; exec "), " )")
+ mutants := map[string]func(string) string{
+ "run staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/run/carlos-group-boot") },
+ "tmp staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/tmp/carlos-group-boot") },
+ "dev shm staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/dev/shm/carlos-group-boot") },
+ "var tmp staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/var/tmp/carlos-group-boot") },
+ "dev staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/dev/carlos-group-boot") },
+ "var lock staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/var/lock/carlos-group-boot") },
+ "var run staging": func(s string) string { return strings.ReplaceAll(s, groupBootStaging, "/var/run/carlos-group-boot") },
+ "one run exec": func(s string) string {
+ return strings.Replace(s, install, "/run/carlos-group-boot/bootstrap instance-control --group-hairpin-install", 1)
+ },
+ "python work only": func(s string) string {
+ return strings.Replace(s, "work = '"+groupBootStaging+"/'", "work = '/run/carlos-group-boot/'", 1)
+ },
+ "walker constant only": func(s string) string {
+ return strings.Replace(s, "WORK = '"+groupBootStaging+"'", "WORK = '/dev/shm/carlos-group-boot'", 1)
+ },
+ "chrony in tmp": func(s string) string {
+ return strings.Replace(s, "> "+groupBootStaging+"/chrony.conf", "> /tmp/chrony.conf", 1)
+ },
+ "mktemp scratch": func(s string) string { return strings.Replace(s, "umask 077\n", "umask 077\nD=$(mktemp -d)\n", 1) },
+ "install unverified": func(s string) string { return strings.Replace(s, groupBootVerify+"\n"+install, install, 1) },
+ "host-env unverified": func(s string) string { return strings.Replace(s, groupBootVerify+"\n"+hostenv, hostenv, 1) },
+ "python unverified": func(s string) string {
+ return strings.Replace(s, "boot_verify.check()\nsubprocess.check_call([work", "subprocess.check_call([work", 1)
+ },
+ "verify not adjacent": func(s string) string {
+ return strings.Replace(s, groupBootVerify+"\n"+install, groupBootVerify+"\nsysctl -p /dev/null\n"+install, 1)
+ },
+ "extra direct exec": func(s string) string { return s + groupBootStaging + "/bootstrap version\n" },
+ "extra shell wrapper": func(s string) string { return s + "sh " + groupBootStaging + "/bootstrap version\n" },
+ "extra python exec": func(s string) string { return s + "subprocess.run([work + 'bootstrap', 'x'])\n" },
+ "extra direct exec with digest comment": func(s string) string {
+ return s + groupBootStaging + "/bootstrap version # bootstrap.sha256\n"
+ },
+ "extra shell wrapper with digest comment": func(s string) string {
+ return s + "sh " + groupBootStaging + "/bootstrap version # bootstrap.sha256\n"
+ },
+ "unverified exec with digest comment": func(s string) string {
+ return strings.Replace(s, groupBootVerify+"\n"+install, install+" # bootstrap.sha256", 1)
+ },
+ "install with verified comment": func(s string) string { return strings.Replace(s, install, install+" # verified bootstrap", 1) },
+ "install with BOOTSTRAP_": func(s string) string { return strings.Replace(s, install, install+" BOOTSTRAP_X", 1) },
+ "install with bootstrap-object": func(s string) string { return strings.Replace(s, install, install+" bootstrap-object", 1) },
+ "install with get-object": func(s string) string { return strings.Replace(s, install, install+" 'get-object'", 1) },
+ "hostenv with get-object": func(s string) string { return strings.Replace(s, hostenv, hostenv+" 'get-object'", 1) },
+ "python exec with comment": func(s string) string {
+ return strings.Replace(s, "timeout=10)\n", "timeout=10) # verified bootstrap\n", 1)
+ },
+ "extra sh bootstrap argument": func(s string) string { return s + "sh " + groupBootStaging + "/bootstrap version\n" },
+ "unknown comment": func(s string) string { return s + "# verified bootstrap\n" },
+ "verify is not helper": func(s string) string { return strings.Replace(s, groupBootVerify+"\n"+install, "true\n"+install, 1) },
+ "python3 without -I": func(s string) string {
+ return strings.Replace(s, groupBootVerify+"\n"+hostenv, "python3 "+strings.TrimPrefix(groupBootVerify, "python3 -I ")+"\n"+hostenv, 1)
+ },
+ "other staging name": func(s string) string {
+ return strings.Replace(s, groupBootStaging+"/chrony.conf", "/var/lib/carlos-group-boot-x/chrony.conf", 1)
+ },
+ "var-run in rw paths": func(s string) string { return s + "ReadWritePaths=/var/run/x\n" },
+ "unlisted tmp argument": func(s string) string { return s + "cp x /tmp\n" },
+ "parent umask changed": func(s string) string { return strings.Replace(s, "umask 077\n", "umask 027\n", 1) },
+ "parent umask removed": func(s string) string { return strings.Replace(s, "umask 077\n", "", 1) },
+ "subshell umask removed": func(s string) string {
+ return strings.Replace(s, hostenv, "( exec "+bareHostenv+" )", 1)
+ },
+ "subshell umask 077": func(s string) string { return strings.Replace(s, "umask 022; exec", "umask 077; exec", 1) },
+ "subshell umask 000": func(s string) string { return strings.Replace(s, "umask 022; exec", "umask 000; exec", 1) },
+ "leaking parent umask 022": func(s string) string {
+ return strings.Replace(s, hostenv, "umask 022\n"+bareHostenv, 1)
+ },
+ "bare hostenv exec": func(s string) string { return strings.Replace(s, hostenv, bareHostenv, 1) },
+ "subshell without exec": func(s string) string {
+ return strings.Replace(s, "umask 022; exec", "umask 022;", 1)
+ },
+ "umask near hairpin install": func(s string) string {
+ return strings.Replace(s, groupBootVerify+"\n"+install, "umask 022\n"+groupBootVerify+"\n"+install, 1)
+ },
+ "umask subshell on hairpin install": func(s string) string {
+ return strings.Replace(s, install, "( umask 022; exec "+install+" )", 1)
+ },
+ "umask near python verify": func(s string) string {
+ return strings.Replace(s, "boot_verify.check()\nsubprocess", "boot_verify.check()\nos.umask(0o022)\nsubprocess", 1)
+ },
+ "umask in python verify": func(s string) string {
+ return strings.Replace(s, "boot_verify.check()\nsubprocess", "boot_verify.check()\nos.umask(0o022); subprocess", 1)
+ },
+ "drop-in chmod removed": func(s string) string {
+ return strings.Replace(s, "os.chmod('"+groupBootDropin+"', 0o755)\n", "", 1)
+ },
+ "drop-in chmod 0700": func(s string) string {
+ return strings.Replace(s, "os.chmod('"+groupBootDropin+"', 0o755)", "os.chmod('"+groupBootDropin+"', 0o700)", 1)
+ },
+ }
+ for name, mutate := range mutants {
+ t.Run(name, func(t *testing.T) {
+ bad := mutate(good)
+ if bad == good {
+ t.Fatal("mutation did not apply")
+ }
+ if err := checkGroupBootStaging(bad); err == nil {
+ t.Fatal("guard accepted the mutant")
+ }
+ })
+ }
+}
+
+// walkerSource extracts the first Python block and points it at a scratch
+// root, expecting the current user in place of root.
+func walkerSource(t *testing.T, root string) string {
+ t.Helper()
+ src := between(t, groupInitTemplate(t), "python3 - <<'PY'\nimport os, stat\nWORK", "\nPY\n")
+ src = "import os, stat\nWORK" + src
+ for from, to := range map[string]string{
+ "os.open('/', os.O_RDONLY | os.O_DIRECTORY)": "os.open(" + fmt.Sprintf("%q", root) + ", os.O_RDONLY | os.O_DIRECTORY)",
+ "st.st_uid != 0": fmt.Sprintf("st.st_uid != %d", os.Getuid()),
+ "st.st_gid != 0": fmt.Sprintf("st.st_gid != %d", gidForTest(t)),
+ } {
+ if !strings.Contains(src, from) {
+ t.Fatalf("walker no longer contains %q", from)
+ }
+ src = strings.ReplaceAll(src, from, to)
+ }
+ return src
+}
+
+func gidForTest(t *testing.T) int {
+ t.Helper()
+ return os.Getgid()
+}
+
+func runPython(t *testing.T, dir, code string) (string, error) {
+ t.Helper()
+ cmd := exec.Command("python3", "-I", "-c", code)
+ cmd.Dir = dir
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+}
+
+func TestGroupBootWalker(t *testing.T) {
+ type tc struct {
+ name string
+ setup func(t *testing.T, root, work string)
+ refuse string
+ }
+ cases := []tc{
+ {"fresh", func(t *testing.T, root, work string) {}, ""},
+ {"preexisting 0700", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o700) }, ""},
+ {"preexisting 0755", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o755) }, "group_boot_directory"},
+ {"preexisting 0750", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o750) }, "group_boot_directory"},
+ {"preexisting 0710", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o710) }, "group_boot_directory"},
+ {"preexisting 0600", func(t *testing.T, root, work string) { mkdirMode(t, work, 0o600) }, "group_boot_directory"},
+ {"final symlink", func(t *testing.T, root, work string) {
+ target := filepath.Join(root, "elsewhere")
+ mkdirMode(t, target, 0o700)
+ if err := os.Symlink(target, work); err != nil {
+ t.Fatal(err)
+ }
+ }, "ELOOP"},
+ {"parent symlink", func(t *testing.T, root, work string) {
+ if err := os.RemoveAll(filepath.Join(root, "var", "lib")); err != nil {
+ t.Fatal(err)
+ }
+ target := filepath.Join(root, "elsewhere")
+ mkdirMode(t, target, 0o755)
+ if err := os.Symlink(target, filepath.Join(root, "var", "lib")); err != nil {
+ t.Fatal(err)
+ }
+ }, "ELOOP"},
+ {"dangling final symlink", func(t *testing.T, root, work string) {
+ if err := os.Symlink(filepath.Join(root, "absent"), work); err != nil {
+ t.Fatal(err)
+ }
+ }, "ELOOP"},
+ {"parent group writable", func(t *testing.T, root, work string) {
+ if err := os.Chmod(filepath.Join(root, "var", "lib"), 0o775); err != nil {
+ t.Fatal(err)
+ }
+ }, "group_boot_directory"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ root := t.TempDir()
+ mkdirMode(t, filepath.Join(root, "var"), 0o755)
+ mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755)
+ work := filepath.Join(root, "var", "lib", "carlos-group-boot")
+ c.setup(t, root, work)
+ out, err := runPython(t, t.TempDir(), walkerSource(t, root))
+ if c.refuse == "" {
+ if err != nil {
+ t.Fatalf("refused: %v %s", err, out)
+ }
+ info, statErr := os.Lstat(work)
+ if statErr != nil || !info.IsDir() || info.Mode().Perm() != 0o700 {
+ t.Fatalf("work dir not 0700: %v %v", info, statErr)
+ }
+ return
+ }
+ if err == nil || !strings.Contains(out, c.refuse) && !(c.refuse == "ELOOP" && (strings.Contains(out, "Too many levels of symbolic links") || strings.Contains(out, "Not a directory"))) {
+ t.Fatalf("accepted: %v %s", err, out)
+ }
+ })
+ }
+ t.Run("sysctl.d absent is created", func(t *testing.T) {
+ root := t.TempDir()
+ mkdirMode(t, filepath.Join(root, "var"), 0o755)
+ mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755)
+ if out, err := runPython(t, t.TempDir(), walkerSource(t, root)); err != nil {
+ t.Fatalf("refused: %v %s", err, out)
+ }
+ info, err := os.Lstat(filepath.Join(root, "etc", "sysctl.d"))
+ if err != nil || !info.IsDir() || info.Mode().Perm() != 0o755 {
+ t.Fatalf("sysctl.d not created 0755: %v %v", info, err)
+ }
+ })
+ for name, setup := range map[string]func(t *testing.T, dir string){
+ "sysctl.d group writable": func(t *testing.T, dir string) { mkdirMode(t, dir, 0o775) },
+ "sysctl.d world writable": func(t *testing.T, dir string) { mkdirMode(t, dir, 0o757) },
+ "sysctl.d symlink": func(t *testing.T, dir string) {
+ target := filepath.Join(filepath.Dir(filepath.Dir(dir)), "elsewhere")
+ mkdirMode(t, target, 0o755)
+ if err := os.Symlink(target, dir); err != nil {
+ t.Fatal(err)
+ }
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ root := t.TempDir()
+ mkdirMode(t, filepath.Join(root, "var"), 0o755)
+ mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755)
+ mkdirMode(t, filepath.Join(root, "etc"), 0o755)
+ setup(t, filepath.Join(root, "etc", "sysctl.d"))
+ out, err := runPython(t, t.TempDir(), walkerSource(t, root))
+ if err == nil || !strings.Contains(out, "group_boot_directory") && !strings.Contains(out, "Too many levels") && !strings.Contains(out, "Not a directory") {
+ t.Fatalf("accepted: %v %s", err, out)
+ }
+ })
+ }
+ t.Run("wrong group", func(t *testing.T) {
+ root := t.TempDir()
+ mkdirMode(t, filepath.Join(root, "var"), 0o755)
+ mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755)
+ mkdirMode(t, filepath.Join(root, "var", "lib", "carlos-group-boot"), 0o700)
+ src := strings.ReplaceAll(walkerSource(t, root), fmt.Sprintf("st.st_gid != %d", os.Getgid()), fmt.Sprintf("st.st_gid != %d", os.Getgid()+1))
+ out, err := runPython(t, t.TempDir(), src)
+ if err == nil || !strings.Contains(out, "group_boot_directory") {
+ t.Fatalf("foreign group accepted: %v %s", err, out)
+ }
+ })
+ t.Run("wrong owner", func(t *testing.T) {
+ root := t.TempDir()
+ mkdirMode(t, filepath.Join(root, "var"), 0o755)
+ mkdirMode(t, filepath.Join(root, "var", "lib"), 0o755)
+ mkdirMode(t, filepath.Join(root, "var", "lib", "carlos-group-boot"), 0o700)
+ src := strings.ReplaceAll(walkerSource(t, root), fmt.Sprintf("st.st_uid != %d", os.Getuid()), fmt.Sprintf("st.st_uid != %d", os.Getuid()+1))
+ out, err := runPython(t, t.TempDir(), src)
+ if err == nil || !strings.Contains(out, "group_boot_directory") {
+ t.Fatalf("foreign owner accepted: %v %s", err, out)
+ }
+ })
+}
+
+func mkdirMode(t *testing.T, path string, mode os.FileMode) {
+ t.Helper()
+ if err := os.Mkdir(path, mode); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(path, mode); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestGroupBootVerifyHelper(t *testing.T) {
+ template := groupInitTemplate(t)
+ helper := between(t, template, "<<'PYVERIFY'\n", "\nPYVERIFY\n") + "\n"
+ body := []byte("bootstrap bytes")
+ sum := sha256.Sum256(body)
+ digest := hex.EncodeToString(sum[:])
+ type tc struct {
+ name string
+ mutate func(t *testing.T, work string)
+ noexec bool
+ owner int
+ want string
+ }
+ write := func(t *testing.T, path string, data []byte, mode os.FileMode) {
+ t.Helper()
+ if err := os.WriteFile(path, data, mode); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(path, mode); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cases := []tc{
+ {name: "intact"},
+ {name: "bootstrap bytes mutated", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", []byte("bootstrap byteS"), 0o700) }, want: "group_boot_hash"},
+ {name: "bootstrap appended", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", append(body, 0), 0o700) }, want: "group_boot_hash"},
+ {name: "digest file swapped", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte(strings.Repeat("0", 64)), 0o600) }, want: "group_boot_hash"},
+ {name: "digest malformed", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte("ABC"), 0o600) }, want: "group_boot_hash"},
+ {name: "digest uppercase", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte(strings.ToUpper(digest)), 0o600) }, want: "group_boot_hash"},
+ {name: "digest file mode 0644", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap.sha256", []byte(digest), 0o644) }, want: "group_boot_bootstrap"},
+ {name: "bootstrap mode 0755", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", body, 0o755) }, want: "group_boot_bootstrap"},
+ {name: "bootstrap mode 0600", mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", body, 0o600) }, want: "group_boot_bootstrap"},
+ {name: "bootstrap hardlinked", mutate: func(t *testing.T, w string) {
+ if err := os.Link(w+"/bootstrap", w+"/other"); err != nil {
+ t.Fatal(err)
+ }
+ }, want: "group_boot_bootstrap"},
+ {name: "bootstrap symlink", mutate: func(t *testing.T, w string) {
+ // A symlink to correct, correctly-moded bytes is still refused.
+ write(t, w+"/real", body, 0o700)
+ if err := os.Remove(w + "/bootstrap"); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(w+"/real", w+"/bootstrap"); err != nil {
+ t.Fatal(err)
+ }
+ }, want: "Too many levels"},
+ {name: "digest symlink", mutate: func(t *testing.T, w string) {
+ write(t, w+"/real", []byte(digest), 0o600)
+ if err := os.Remove(w + "/bootstrap.sha256"); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(w+"/real", w+"/bootstrap.sha256"); err != nil {
+ t.Fatal(err)
+ }
+ }, want: "Too many levels"},
+ {name: "bootstrap removed", mutate: func(t *testing.T, w string) {
+ if err := os.Remove(w + "/bootstrap"); err != nil {
+ t.Fatal(err)
+ }
+ }, want: "FileNotFoundError"},
+ {name: "bootstrap is directory", mutate: func(t *testing.T, w string) {
+ if err := os.Remove(w + "/bootstrap"); err != nil {
+ t.Fatal(err)
+ }
+ mkdirMode(t, w+"/bootstrap", 0o700)
+ }, want: "group_boot_bootstrap"},
+ {name: "directory mode 0755", mutate: func(t *testing.T, w string) {
+ if err := os.Chmod(w, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }, want: "group_boot_directory"},
+ {name: "directory mode 0500", mutate: func(t *testing.T, w string) {
+ t.Cleanup(func() { _ = os.Chmod(w, 0o700) })
+ if err := os.Chmod(w, 0o500); err != nil {
+ t.Fatal(err)
+ }
+ }, want: "group_boot_directory"},
+ {name: "foreign owner", owner: 1, want: "group_boot_directory"},
+ {name: "noexec mount", noexec: true, want: "group_boot_noexec"},
+ {name: "noexec wins over a bad hash", noexec: true, mutate: func(t *testing.T, w string) { write(t, w+"/bootstrap", []byte("x"), 0o700) }, want: "group_boot_noexec"},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ scratch := t.TempDir()
+ write(t, scratch+"/carlos_group_boot_verify.py", []byte(helper), 0o600)
+ work := filepath.Join(scratch, "work")
+ mkdirMode(t, work, 0o700)
+ write(t, work+"/bootstrap", body, 0o700)
+ write(t, work+"/bootstrap.sha256", []byte(digest), 0o600)
+ if c.mutate != nil {
+ c.mutate(t, work)
+ }
+ stub := ""
+ if c.noexec {
+ stub = "os.statvfs = lambda path: type('V', (), {'f_flag': os.ST_NOEXEC})()\n"
+ }
+ code := fmt.Sprintf("import os, sys, traceback\nsys.dont_write_bytecode = True\nsys.path.insert(0, %q)\nimport carlos_group_boot_verify as v\n%s"+
+ "try:\n v.check(%q, (%d, %d))\nexcept SystemExit as err:\n print(err); sys.exit(3)\nexcept Exception:\n traceback.print_exc(); sys.exit(4)\n",
+ scratch, stub, work, os.Getuid()+c.owner, os.Getgid())
+ out, err := runPython(t, scratch, code)
+ if c.want == "" {
+ if err != nil {
+ t.Fatalf("refused: %v %s", err, out)
+ }
+ return
+ }
+ if err == nil || !strings.Contains(out, c.want) {
+ t.Fatalf("want %s: %v %s", c.want, err, out)
+ }
+ })
+ }
+ t.Run("default owner is root", func(t *testing.T) {
+ if os.Getuid() == 0 {
+ t.Skip("running as root")
+ }
+ scratch := t.TempDir()
+ write(t, scratch+"/carlos_group_boot_verify.py", []byte(helper), 0o600)
+ work := filepath.Join(scratch, "work")
+ mkdirMode(t, work, 0o700)
+ code := fmt.Sprintf("import sys\nsys.dont_write_bytecode = True\nsys.path.insert(0, %q)\nimport carlos_group_boot_verify as v\nv.check(%q)\n", scratch, work)
+ out, err := runPython(t, scratch, code)
+ if err == nil || !strings.Contains(out, "group_boot_directory") {
+ t.Fatalf("non-root directory accepted by default: %v %s", err, out)
+ }
+ })
+ t.Run("each execution reverifies", func(t *testing.T) {
+ // The three executions share one script. Mutating the bootstrap between
+ // any two of them must fail the next one, so run the helper as a script
+ // the way the shell does, three times, with a mutation before each.
+ for target := 1; target <= 3; target++ {
+ scratch := t.TempDir()
+ write(t, scratch+"/carlos_group_boot_verify.py", []byte(strings.Replace(helper, " check()\n", fmt.Sprintf(" check(%q, (%d, %d))\n", scratch+"/work", os.Getuid(), os.Getgid()), 1)), 0o600)
+ work := filepath.Join(scratch, "work")
+ mkdirMode(t, work, 0o700)
+ write(t, work+"/bootstrap", body, 0o700)
+ write(t, work+"/bootstrap.sha256", []byte(digest), 0o600)
+ for n := 1; n <= 3; n++ {
+ if n == target {
+ write(t, work+"/bootstrap", []byte("tampered"), 0o700)
+ }
+ cmd := exec.Command("python3", "-I", scratch+"/carlos_group_boot_verify.py")
+ out, err := cmd.CombinedOutput()
+ if n < target && err != nil {
+ t.Fatalf("exec %d refused before mutation: %v %s", n, err, out)
+ }
+ if n == target {
+ if err == nil || !strings.Contains(string(out), "group_boot_hash") {
+ t.Fatalf("exec %d ran a mutated bootstrap: %v %s", n, err, out)
+ }
+ break
+ }
+ }
+ }
+ })
+}
diff --git a/internal/host/group_boot_test.go b/internal/host/group_boot_test.go
index 7e533a022..32d9b25d0 100644
--- a/internal/host/group_boot_test.go
+++ b/internal/host/group_boot_test.go
@@ -218,7 +218,7 @@ func assertGroupClockOrder(t *testing.T, s string) {
t.Helper()
last := -1
for _, command := range []string{
- "apt-get -y -q install", "install -o root -g root -m 0644 /run/carlos-group-boot/chrony.conf",
+ "apt-get -y -q install", "install -o root -g root -m 0644 /var/lib/carlos-group-boot/chrony.conf",
"systemctl restart chrony.service", "['chronyc', '-n', 'sources']", "chronyc waitsync 20 2", "response = aws('ssm'",
} {
n := strings.Index(s, command)
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index cc8f5cb2c..6ec52e912 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -91,3 +91,4 @@ plan14-root-reads-region-ha-p3b1-fixes.tsv 86aa1e39a21072d17678411a4047983a75649
plan14-root-reads-stateless-failed-release-held.tsv 657f81eeea52785b75f92a42064f63f218787f712ef313e2acf44f7e664e16b9
plan14-root-reads-static-markdown-twins.tsv ec831d3206622f34511bfbc2ec0cccb131fbd3861ec4c6a33a2dc6dff9a1791e
plan14-root-reads-agent-start-demo-1-followups.tsv ec831d3206622f34511bfbc2ec0cccb131fbd3861ec4c6a33a2dc6dff9a1791e
+plan14-root-reads-region-ha-p3b1-f4.tsv 71bbbf68863266ffab90211a00aff2f1b694bf39bb4bd62ea565c168ba884564
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv
new file mode 100644
index 000000000..f7271a1ed
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv
@@ -0,0 +1,5 @@
+# Census overlay region-ha-p3b1-f4, written by census-propose (#369). census-ruling-region-ha-p3b1-f4, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md.
+# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy b5f3cc30f0a0bbe84955685fe50876caa2bc4f1cea8f905be308f341eaa3311b infra/modules/region-host/group-init.sh.tftpl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=New root user-data boot: operator Terraform/SSM supply scoped bootstrap object version/hash, queue, reader inventory and ingress; hash-verified bootstrap verifies signed IMDS identity. Root exclusively writes /etc/carlos/group.json, group-identity.json, region-config.json and group-ingress.json with current kernel boot ID; public address comes from protected IMDSv2, not signed document or headers. Install IMDS denial, chrony, dormant hairpin fence and protected drop-ins before bootstrap/install/start. No agent receipt is read by root; restart authority is separate maintenance permit. F1: operator-seeded SSM boot/bootstrap-object requires floor=absent-expected or required beside key/version/known_readers/deployment_aws_region; root copies it into group.json before config_digest. Missing or invalid floor refuses before bootstrap fetch; Terraform only names this SSM key and does not write the object. Agent and instance-control gain AF_NETLINK in their address-family allowlists, with no CAP_NET_ADMIN grant.;rev3=census-ruling-region-ha-p3b1-f4;basis=Move bootstrap and chrony staging to root:root 0700 /var/lib/carlos-group-boot through the existing O_NOFOLLOW walker; refuse unsafe preexisting directory. Bootstrap 0700; retain initial hash verification and rehash against a root-only captured SSM digest immediately before all three execs; named noexec refusal. Root reads only its own helper/hash and verified binary; no tenant/app/agent writable input or authority added. Final removal preserved. Round 5 adds /etc/sysctl.d to the same root-owned, non-writable, O_NOFOLLOW directory walker before its existing exclusive sysctl file write; missing directory is created, unsafe ancestors refuse. Round 6 scopes umask 022 to the verified host-env install exec in a subshell; its bootstrap/install-channel children create traversable install directories and readable unit files, matching fixed boxes. Parent umask remains 077; verify-identity is read-only and hairpin install creates only 0700/0600 private state. Explicitly chmod the freshly created instance-control drop-in directory 0755. host.env remains explicitly chmodded 0600 in unchanged released Go. No new input/read or write authority; all verification and directory trust checks remain. file:external@0 0c17d53b79760e8d5c45419b428dd1d3812ef6e457f0948891c89ef2bdfd7fb1
+infra/modules/region-host/group-init.sh.tftpl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=New root user-data boot: operator Terraform/SSM supply scoped bootstrap object version/hash, queue, reader inventory and ingress; hash-verified bootstrap verifies signed IMDS identity. Root exclusively writes /etc/carlos/group.json, group-identity.json, region-config.json and group-ingress.json with current kernel boot ID; public address comes from protected IMDSv2, not signed document or headers. Install IMDS denial, chrony, dormant hairpin fence and protected drop-ins before bootstrap/install/start. No agent receipt is read by root; restart authority is separate maintenance permit. F1: operator-seeded SSM boot/bootstrap-object requires floor=absent-expected or required beside key/version/known_readers/deployment_aws_region; root copies it into group.json before config_digest. Missing or invalid floor refuses before bootstrap fetch; Terraform only names this SSM key and does not write the object. Agent and instance-control gain AF_NETLINK in their address-family allowlists, with no CAP_NET_ADMIN grant.;rev3=census-ruling-region-ha-p3b1-f4;basis=Move bootstrap and chrony staging to root:root 0700 /var/lib/carlos-group-boot through the existing O_NOFOLLOW walker; refuse unsafe preexisting directory. Bootstrap 0700; retain initial hash verification and rehash against a root-only captured SSM digest immediately before all three execs; named noexec refusal. Root reads only its own helper/hash and verified binary; no tenant/app/agent writable input or authority added. Final removal preserved. Round 5 adds /etc/sysctl.d to the same root-owned, non-writable, O_NOFOLLOW directory walker before its existing exclusive sysctl file write; missing directory is created, unsafe ancestors refuse. Round 6 scopes umask 022 to the verified host-env install exec in a subshell; its bootstrap/install-channel children create traversable install directories and readable unit files, matching fixed boxes. Parent umask remains 077; verify-identity is read-only and hairpin install creates only 0700/0600 private state. Explicitly chmod the freshly created instance-control drop-in directory 0755. host.env remains explicitly chmodded 0600 in unchanged released Go. No new input/read or write authority; all verification and directory trust checks remain. file:external@0 0c17d53b79760e8d5c45419b428dd1d3812ef6e457f0948891c89ef2bdfd7fb1
+@coverage infra/modules/region-host 367679e9ee5bb141a5f70cd17c7963b335b28cd1828da351a4b20a80033f392d
diff --git a/scripts/region-group-boot-witness.py b/scripts/region-group-boot-witness.py
new file mode 100644
index 000000000..27f914d25
--- /dev/null
+++ b/scripts/region-group-boot-witness.py
@@ -0,0 +1,1573 @@
+#!/usr/bin/env python3
+"""Controller-only P3b-1 witness. Default is a local dry run; never applies tofu."""
+import argparse
+import base64
+import builtins
+import difflib
+import email.policy
+import fcntl
+from email.parser import BytesParser
+import gzip
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import shutil
+import signal
+import subprocess
+import sys
+import tarfile
+import time
+import uuid
+from contextlib import contextmanager
+from datetime import datetime, timezone
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRATCH = Path('/home/paulca/.cache/p3b1-f4-work')
+ACCOUNT = '640012953448'
+REGION = 'eu-west-1'
+BUCKET = 'carlos-dev-640012953448'
+SG = 'sg-0c328faf839a02986'
+AMI = 'ami-020434b3e0470d552'
+BOOT_KEY = 'bootstrap/dev/ie/carlos-v0.34.2-linux-arm64'
+BOOT_VERSION = 'J_BSF6jwEX6Fj3HhbyKvvqpp0lidbDIT'
+BOOT_SHA = 'f837b3763457825d469c89cde80fb85fd45f50fd1872a8d53147d53fdebfdc01'
+FIXED = {'i-046c7fe43620944bc', 'i-05498eada6f0afd23'}
+TGS = [f'arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT}:targetgroup/{x}' for x in
+ ('carlos-dev-ie-nlb-80/2f5186277337ce74', 'carlos-dev-ie-nlb-443/c33262405df2e5df')]
+SUBNET = 'subnet-0975dda9ac0e65347'
+MOUNTS = ['/run', '/tmp', '/dev/shm', '/var/tmp', '/var/run', '/var/lock', '/var/lib', '/var/lib/cloud',
+ '/var/lib/carlos-group-boot', '/opt', '/etc', '/data',
+ '/data/instances', '/run/carlos/instances', '/run/carlos/logs']
+UNITS = ['carlos-edge', 'carlos-hairpin-reset', 'carlos-instance-control', 'carlos-instance-control.socket', 'carlos-relay', 'nftables', 'chrony']
+LIVE_BLOCKERS = ()
+FLOOR_LABEL = 'floor=absent-expected (Paul 2026-11-04 21:09Z)'
+POINTER_KEY = 'control/system/router/stable.json'
+FLOOR_KEYS = ['control/moves-protocol.json', 'control/moves-protocol-auth.json']
+EDGES_PREFIX = 'control/edges/' # internal/host/edgesfile.go:edgesFilePrefix
+PURPOSE = 'p3b1-f4-witness'
+SIGNALS = (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)
+BUDGET = SCRATCH / 'witness-budget.json'
+LOG_PATH = None
+
+
+def print(*values, sep=' ', end='\n', file=None, flush=False):
+ # A broken terminal must never interrupt a mutation or its cleanup. Keep
+ # the same redacted messages on disk even after stdout/stderr disappears.
+ message = sep.join(str(value) for value in values) + end
+ if LOG_PATH is not None:
+ try:
+ fd = os.open(LOG_PATH, os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, 'w') as log:
+ log.write(message)
+ log.flush()
+ except OSError:
+ pass
+ try:
+ builtins.print(message, end='', file=file, flush=True)
+ except (OSError, ValueError):
+ pass
+
+
+def log_to(directory):
+ global LOG_PATH
+ LOG_PATH = directory / 'witness.log'
+
+
+def write_user_data(directory, raw):
+ require(isinstance(raw, bytes), 'user data must be raw bytes')
+ # AWS documents 16 KiB before base64 encoding. Also bound the encoded
+ # form to 16 KiB: the witness deliberately keeps the stricter cap.
+ require(max(len(raw), len(base64.b64encode(raw))) <= 16384, 'user data size exceeds 16384')
+ path = directory / 'user-data.gz'
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, 'wb') as f:
+ f.write(raw)
+ f.flush()
+ os.fsync(f.fileno())
+ return path
+
+
+def dev_config():
+ config = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text())
+ # The witness and third dev window both use Paul's artifact pin. The
+ # historical module fixture still tests its original version input.
+ config['CARLOS_RELEASE'] = BOOT_SHA
+ return config
+
+
+def require(ok, message):
+ if not ok:
+ raise ValueError(message)
+
+
+def scope(run):
+ require(bool(re.fullmatch(r'[a-z0-9][a-z0-9-]{0,31}', run)), 'invalid run id')
+ deployment = 'f4-' + run
+ return dict(run=run, deployment=deployment, prefix=f'/carlos/{deployment}/ie',
+ shared=f'/carlos/{deployment}/shared', key=f'bootstrap/{deployment}/ie/carlos-v0.34.2-linux-arm64',
+ evidence=f'root-runner/p3b1-f4-witness/{run}', role=f'p3b1-f4-witness-{run}')
+
+
+def plain_render(config):
+ template = (ROOT / 'infra/modules/region-host/group-init.sh.tftpl').read_text()
+ loop = '%{ for key, value in config ~}\n${key}=${value}\nexport ${key}\n%{ endfor ~}\n'
+ require(template.count(loop) == 1, 'template config loop changed')
+ # Tofu quotes even shell-safe values.
+ assignments = ''.join(k + "='" + v.replace("'", "'\"'\"'") + "'\nexport " + k + '\n' for k, v in sorted(config.items()))
+ return template.replace(loop, assignments).replace('$${', '${').replace('%%{', '%{').encode()
+
+
+def witness_config(dev, s):
+ result = dict(dev, CARLOS_DEPLOYMENT=s['deployment'], CARLOS_POOLS='witness')
+ for name in ('CARLOS_BOOTSTRAP_HASH_KEY', 'CARLOS_BOOTSTRAP_OBJECT_KEY', 'CARLOS_INGRESS_KEY'):
+ result[name] = dev[name].replace('/carlos/dev/ie/', s['prefix'] + '/')
+ # hapair is dev-only in GroupConfig.Validate. Two module input substitutions
+ # (deployment and pools) therefore change exactly five script assignments.
+ return result
+
+
+def check_diff(dev, witness, s):
+ config = dev_config()
+ require(dev == plain_render(config), 'module real-dev render differs from the real-dev fixture')
+ expected = plain_render(witness_config(config, s))
+ require(witness == expected, 'witness differs beyond deployment/pool substitutions')
+ require(b'/carlos/dev/ie' not in witness and b'bootstrap/dev/ie' not in witness, 'real dev namespace in witness')
+ diff = ''.join(difflib.unified_diff(dev.decode().splitlines(True), witness.decode().splitlines(True),
+ fromfile='real-dev', tofile='witness'))
+ require(len([x for x in diff.splitlines() if x.startswith('+') and not x.startswith('+++')]) == 5,
+ 'expected exactly five changed assignment lines')
+ return diff
+
+
+def configured_values(values, expressions):
+ # Mock providers invent values for optional+computed fields. Only attributes
+ # actually configured by the module may become EC2 launch arguments.
+ result = {}
+ for key, expression in expressions.items():
+ require(key in values, 'missing configured value: ' + key)
+ value = values[key]
+ if isinstance(expression, list):
+ require(len(value) == len(expression), 'configured block cardinality: ' + key)
+ result[key] = [configured_values(v, e) for v, e in zip(value, expression)]
+ else:
+ if isinstance(expression.get('constant_value'), bool):
+ require(value in (True, False, 'true', 'false'), 'boolean provider value')
+ value = value in (True, 'true')
+ result[key] = value
+ return result
+
+
+def render(tofu, directory, s):
+ require(json.loads(subprocess.check_output([str(tofu), 'version', '-json']))['terraform_version'] == '1.13.1',
+ 'OpenTofu 1.13.1 required')
+ module = directory / 'module'
+ require(not module.exists(), 'render directory already exists')
+ shutil.copytree(ROOT / 'infra/modules/region-host', module,
+ ignore=shutil.ignore_patterns('.terraform', '.terraform.lock.hcl'))
+ provider_cache = directory.parent / 'witness-provider-cache'
+ provider_cache.mkdir(exist_ok=True)
+ env = dict(os.environ, TF_PLUGIN_CACHE_DIR=str(provider_cache), AWS_EC2_METADATA_DISABLED='true', AWS_CONFIG_FILE='/dev/null',
+ AWS_SHARED_CREDENTIALS_FILE='/dev/null', AWS_ACCESS_KEY_ID='mock', AWS_SECRET_ACCESS_KEY='mock',
+ TMPDIR=str(directory), TF_IN_AUTOMATION='1')
+ env.pop('AWS_PROFILE', None)
+ env.pop('AWS_SESSION_TOKEN', None)
+ def run(*args):
+ result = subprocess.run(['nice', '-n', '10', str(tofu), f'-chdir={module}', *args],
+ env=env, capture_output=True, text=True, timeout=600)
+ require(result.returncode == 0, result.stdout[-4000:] + result.stderr[-2000:])
+ return result.stdout
+ if not (module / '.terraform').exists():
+ (directory / 'init.log').write_text(run('init', '-backend=false', '-input=false', '-no-color'))
+ test = module / 'tests/group_user_data.tftest.hcl'
+ original = test.read_text().split('run "oversize_user_data"')[0]
+ require(original.count('release = "v0.34.2"') == 1, 'module release input drift')
+ original = original.replace('release = "v0.34.2"', 'release = "' + BOOT_SHA + '"')
+ result = []
+ try:
+ for label, content in [('dev', original), ('witness', original.replace('deployment = "dev"',
+ f'deployment = "{s["deployment"]}"').replace('pools = ["hapair"]',
+ 'pools = ["witness"]'))]:
+ test.write_text(content)
+ events = run('test', '-filter=tests/group_user_data.tftest.hcl', '-json', '-verbose')
+ (directory / f'{label}-plan.jsonl').write_text(events)
+ plans = [e['test_plan'] for line in events.splitlines() if (e := json.loads(line)).get('test_plan')
+ and e.get('@testrun') == 'real_dev_user_data']
+ require(len(plans) == 1, 'missing module plan')
+ resources = {r['address']: r['values'] for r in plans[0]['planned_values']['root_module']['resources']}
+ expressions = next(r['expressions'] for r in plans[0]['configuration']['root_module']['resources']
+ if r['address'] == 'aws_launch_template.group')
+ lt = configured_values(resources['aws_launch_template.group[0]'], expressions)
+ require(len(lt['user_data']) <= 13107, 'module encoded user-data cap')
+ raw = gzip.decompress(base64.b64decode(lt['user_data']))
+ (directory / f'{label}.sh').write_bytes(raw)
+ result.append((raw, lt))
+ finally:
+ shutil.copyfile(ROOT / 'infra/modules/region-host/tests/group_user_data.tftest.hcl', test)
+ diff = check_diff(result[0][0], result[1][0], s)
+ (directory / 'substitutions.diff').write_text(diff)
+ print(diff)
+ print('MODULE real-dev encoded bytes:', len(result[0][1]['user_data']), '/ 13107')
+ return result[1]
+
+
+def artifact_key(pointer):
+ require(pointer.get('component') == 'router' and pointer.get('channel') == 'stable', 'pointer scope drift')
+ current = pointer['current']
+ art = current['artifacts']['linux-arm64']
+ require(current['version'] == 'v0.34.2' and art['sha256'] == BOOT_SHA, 'release pin drift')
+ require(art['key'] == 'bootstrap/router/v0.34.2/carlos-linux-arm64', 'artifact key drift')
+ return art['key']
+
+
+def policy(s, kms_key, pointer):
+ parameter = f'arn:aws:ssm:{REGION}:{ACCOUNT}:parameter'
+ names = list(seed(s, 'policy-only', 'public-key-placeholder'))
+ return {'Version': '2012-10-17', 'Statement': [
+ {'Effect': 'Allow', 'Action': ['ssm:GetParameter', 'ssm:GetParameters'],
+ 'Resource': [parameter + name for name in names]},
+ {'Effect': 'Allow', 'Action': 'ssm:GetParametersByPath',
+ 'Resource': [parameter + s['shared'], parameter + s['prefix']],
+ 'Condition': {'Bool': {'ssm:Recursive': 'false'}}},
+ {'Effect': 'Allow', 'Action': 'kms:Decrypt', 'Resource': kms_key,
+ 'Condition': {'StringEquals': {'kms:ViaService': f'ssm.{REGION}.amazonaws.com'},
+ 'StringLike': {'kms:EncryptionContext:PARAMETER_ARN':
+ parameter + s['prefix'] + '/CARLOS_SECRETS_KEY'}}},
+ {'Effect': 'Allow', 'Action': 's3:GetObject',
+ 'Resource': [f'arn:aws:s3:::{BUCKET}/' + key for key in
+ [s['key'], POINTER_KEY, artifact_key(pointer), *FLOOR_KEYS]]},
+ {'Effect': 'Allow', 'Action': 's3:GetObjectVersion', 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['key']},
+ {'Effect': 'Allow', 'Action': ['s3:ListBucket', 's3:GetBucketLocation'],
+ 'Resource': f'arn:aws:s3:::{BUCKET}'},
+ {'Effect': 'Allow', 'Action': 's3:PutObject', 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['evidence'] + '/*'},
+ ]}
+
+
+def seed(s, version, pubkey):
+ dev = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text())
+ values = dict(AWS_REGION=REGION, CARLOS_POOLS='witness', CARLOS_DEPLOYMENT_BUCKET=BUCKET,
+ CARLOS_HIBERNATE_BUCKET=dev['CARLOS_GROUP_DATA_BUCKET'], CARLOS_HIBERNATE_REGION=REGION,
+ CARLOS_HIBERNATE_PREFIX='instances', CARLOS_REGION_HA='true', CARLOS_GROUP_ADMISSION='1',
+ CARLOS_CHANGE_INDEX='read', CARLOS_HOST_METRICS='cloudwatch', CARLOS_SYSTEM_CHANNEL='stable',
+ CARLOS_ALERT_SNS_TOPIC_ARN=f'arn:aws:sns:{REGION}:{ACCOUNT}:' + s['role'],
+ CARLOS_RELEASE_PUBKEY=pubkey,
+ CARLOS_SECRETS_KEY=base64.b64encode(secrets.token_bytes(32)).decode(),
+ CARLOS_HA_FIXED_BOX_IDENTITIES='{}', CARLOS_SWAP='0')
+ require(len(values) == 16, 'env seed count')
+ values.update({'boot/bootstrap-object': json.dumps(dict(key=s['key'], version=version, known_readers=[],
+ deployment_aws_region=REGION, floor='absent-expected')),
+ 'boot/bootstrap-sha256': BOOT_SHA, 'boot/ingress': '["54.77.110.223","18.203.21.74"]',
+ 'boot/CARLOS_TERMINATION_QUEUE_URL': dev['CARLOS_TERMINATION_QUEUE_URL']})
+ return {s['prefix'] + '/' + k: v for k, v in values.items()}
+
+
+COLLECTOR = r'''#!/usr/bin/python3
+import hashlib,io,json,os,pathlib,re,shlex,stat,subprocess,tarfile,time,urllib.request
+os.umask(0o077)
+print('WITNESS collector-start', flush=True)
+root=pathlib.Path('/var/lib/carlos-witness-@RUN@');root.mkdir(mode=0o700,exist_ok=True)
+redactions=[]
+host=pathlib.Path('/etc/carlos/host.env')
+if host.exists():
+ for line in host.read_text().splitlines():
+ if '=' in line:
+ k,v=line.split('=',1)
+ if 'KEY' in k or 'SECRET' in k or 'TOKEN' in k:
+ redactions.extend([v.strip().strip('"').strip("'")])
+def redact(text):
+ for value in redactions:
+ if value: text=text.replace(value,'[REDACTED]')
+ return text
+def command(args):
+ try:
+ p=subprocess.run(args,capture_output=True,text=True,timeout=20)
+ return dict(argv=args,rc=p.returncode,out=redact(p.stdout+p.stderr))
+ except Exception as e:return dict(argv=args,rc=255,out=str(e))
+deadline=time.monotonic()+120
+while time.monotonic()<deadline:
+ journal=command(['journalctl','-b','-u','carlos-edge','--no-pager'])
+ if re.search(r'agent: edges file pass failed[^\n]*AccessDenied',journal['out']):break
+ if not host.exists():break
+ time.sleep(2)
+(root/'observer-stop').touch()
+for attempt in range(30):
+ if (root/'observer-done').exists():break
+ time.sleep(0.1)
+e=dict(commands={},files={},mounts={},time=time.time())
+try:e['staging_observer']=json.loads((root/'observer.json').read_text())
+except (OSError,ValueError) as ex:e['observer_error']=str(ex)
+
+for path in @MOUNTS@:
+ p=pathlib.Path(path)
+ probe=p
+ while not probe.exists():probe=probe.parent
+ e['mounts'][path]=dict(probe=str(probe),flags=os.statvfs(probe).f_flag,
+ noexec=bool(os.statvfs(probe).f_flag & os.ST_NOEXEC),dev=probe.stat().st_dev,realpath=str(probe.resolve()),
+ findmnt=command(['findmnt','-T',str(probe),'-o','TARGET,SOURCE,FSTYPE,OPTIONS']))
+for name,args in {
+ 'cloud-status':['cloud-init','status','--long'],
+ 'nft':['nft','list','ruleset'], 'nft-json':['nft','-j','-n','list','ruleset'], 'nft-persist':['cat','/etc/nftables.conf'],
+ 'sysctl':['sysctl','net.ipv4.conf.all.arp_ignore','net.ipv4.conf.default.arp_ignore','net.ipv4.conf.all.arp_announce','net.ipv4.conf.default.arp_announce'],
+ 'apparmor':['aa-status'], 'lsm':['cat','/sys/kernel/security/lsm'],
+ 'mac-denials':['journalctl','-k','-b','--no-pager','--grep','apparmor="DENIED"|avc:.*denied'],
+ 'packages':['dpkg-query','-W','python3','coreutils','passwd','libc-bin','nftables','procps','chrony','awscli','systemd','cloud-init','apparmor','needrestart','selinux-basics'],
+ 'user':['getent','passwd','carlos'], 'group':['getent','group','carlos'],
+ 'tools':['/bin/sh','-c','for t in python3 timeout useradd getent install nft sysctl chronyc aws systemctl; do command -v "$t" || exit 1; done; python3 --version; aws --version; systemctl --version'],
+ 'chrony':['chronyc','-n','sources'],
+ 'timesyncd':['systemctl','is-active','systemd-timesyncd'],
+ 'directories':['ls','-ld','/etc/carlos','/var/lib/carlos-group-boot','/opt/carlos','/data'],
+ 'listing':['ls','-la','/etc/carlos','/var/lib/carlos-group-boot','/opt/carlos'],
+ 'kernel':['uname','-a'],
+ 'link':['ip','-j','-d','link','show'],
+ 'addresses':['ip','-j','-4','addr','show'],
+ 'groups':['id','carlos'],
+ 'bootstrap-tools':['/bin/sh','-c','for t in groupadd chown chmod systemd-tmpfiles usermod; do command -v "$t" || exit 1; done'],
+ 'apt-masks':['systemctl','is-enabled','apt-daily.timer','apt-daily-upgrade.timer','apt-daily.service','apt-daily-upgrade.service','unattended-upgrades.service'],
+
+ 'nft-check':['nft','-c','-f','/etc/nftables.conf'],
+ 'mount-units':['systemctl','is-active','data-instances.mount','run-carlos-instances.mount','run-carlos-logs.mount'],
+ 'selinux':['ls','-ld','/sys/fs/selinux'],
+ 'free':['free','-m'],
+ 'cloud-unit':['systemctl','show','cloud-final','-p','FragmentPath','-p','ExecStart'],
+}.items(): e['commands'][name]=command(args)
+for unit in @UNITS@:
+ for op,args in [('status',['systemctl','status',unit,'--no-pager']),
+ ('journal',['journalctl','-b','-u',unit,'--no-pager','-o','short-monotonic']),
+ ('show',['systemctl','show',unit,'-p','Restart','-p','ActiveState','-p','ExecMainStartTimestampMonotonic','-p','ExecMainStatus','-p','Result','-p','ExecStartPre','-p','RestrictAddressFamilies','-p','ReadWritePaths','-p','User','-p','Group','-p','NoNewPrivileges','-p','CapabilityBoundingSet','-p','AmbientCapabilities','-p','ProtectSystem','-p','ProtectHome','-p','PrivateTmp','-p','PrivateDevices','-p','ProtectKernelTunables','-p','ProtectKernelModules','-p','MemoryDenyWriteExecute','-p','MainPID'])]:
+ e['commands'][unit+'-'+op]=command(args)
+for path in ['/etc/carlos/group.json','/etc/carlos/group-ingress.json','/etc/carlos/region-config.json',
+ '/etc/carlos/group-identity.json','/etc/carlos/host.env','/etc/nftables.conf','/opt/carlos/carlos',
+ '/var/lib/carlos-group-boot','/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf']:
+ p=pathlib.Path(path)
+ try:
+ st=p.lstat();info=dict(uid=st.st_uid,gid=st.st_gid,mode=oct(st.st_mode & 0o7777),mtime=st.st_mtime_ns,nlink=st.st_nlink,regular=stat.S_ISREG(st.st_mode))
+ if p.is_file() and path.endswith('.json'):info['keys']=sorted(json.loads(p.read_text()))
+ if path.endswith('/group.json'):info['box_iid']=json.loads(p.read_text())['instance_id']
+ if path.endswith('/group-ingress.json'):info['ingress']=json.loads(p.read_text())
+ if path.endswith('/host.env'):info['keys']=[x.split('=',1)[0] for x in p.read_text().splitlines() if '=' in x]
+ e['files'][path]=info
+ except FileNotFoundError:e['files'][path]=None
+ except (OSError,ValueError,KeyError) as ex:e['files'][path]=dict(error=redact(str(ex)))
+try:
+ opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
+ t=opener.open(urllib.request.Request('http://169.254.169.254/latest/api/token',method='PUT',headers={'X-aws-ec2-metadata-token-ttl-seconds':'60'}),timeout=2).read().decode()
+ e['identity']=json.loads(opener.open(urllib.request.Request('http://169.254.169.254/latest/dynamic/instance-identity/document',headers={'X-aws-ec2-metadata-token':t}),timeout=2).read())
+except Exception as ex:e['identity_error']=str(ex)
+try:
+ pid=int(e['commands']['carlos-edge-show']['out'].split('MainPID=')[1].splitlines()[0])
+ e['edge_process_status']=pathlib.Path('/proc/'+str(pid)+'/status').read_text() if pid>0 else ''
+ e['edge_process_mounts']=pathlib.Path('/proc/'+str(pid)+'/mountinfo').read_text() if pid>0 else ''
+except (OSError,ValueError,IndexError) as ex:e['process_error']=str(ex)
+for name,path in [('cloud-init-output.log','/var/log/cloud-init-output.log'),('cloud-init.log','/var/log/cloud-init.log')]:
+ try:(root/name).write_text(redact(pathlib.Path(path).read_text(errors='replace')))
+ except OSError as ex:(root/name).write_text(str(ex))
+(root/'evidence.json').write_text(json.dumps(e,sort_keys=True,indent=2))
+archive=root/'evidence.tar.gz'
+with tarfile.open(archive,'w:gz') as tar:
+ for name in ['evidence.json','cloud-init-output.log','cloud-init.log']:tar.add(root/name,arcname=name)
+print('WITNESS collector-evidence files='+str(len(e['files']))+' commands='+str(len(e['commands'])),flush=True)
+upload=command(['aws','--region','eu-west-1','s3api','put-object','--bucket','carlos-dev-640012953448','--key','root-runner/p3b1-f4-witness/@RUN@/evidence.tar.gz','--body',str(archive)])
+print('WITNESS upload rc='+str(upload['rc']),flush=True)
+print('WITNESS collector-done',flush=True)
+'''
+
+
+OBSERVER = r'''#cloud-boothook
+#!/usr/bin/python3
+import base64,json,os,pathlib,subprocess,sys,time
+os.umask(0o077)
+root=pathlib.Path('/var/lib/carlos-witness-@RUN@')
+root.mkdir(mode=0o700,exist_ok=True)
+if '--worker' not in sys.argv:
+ subprocess.run(['systemd-run','--unit','carlos-f4-observer',
+ '--property=DefaultDependencies=no','--property=Type=exec',
+ '--property=RuntimeMaxSec=1200','--property=StandardOutput=journal+console',
+ '--','/usr/bin/python3',str(pathlib.Path(__file__).resolve()),'--worker'],check=True,timeout=10)
+ deadline=time.monotonic()+5
+ while not (root/'observer-ready').exists():
+ if time.monotonic()>=deadline:raise SystemExit('observer start deadline')
+ time.sleep(0.01)
+ raise SystemExit(0)
+work=pathlib.Path('/var/lib/carlos-group-boot')
+def sample(path):
+ st=path.stat();flags=os.statvfs(path).f_flag
+ return dict(path=str(path),dev=st.st_dev,ino=st.st_ino,uid=st.st_uid,gid=st.st_gid,
+ mode=oct(st.st_mode & 0o7777),noexec=bool(flags & os.ST_NOEXEC),flags=flags,
+ monotonic_ns=time.monotonic_ns(),mountinfo=pathlib.Path('/proc/self/mountinfo').read_text())
+e=dict(clock='CLOCK_MONOTONIC',parent_before=sample(work.parent),samples=[])
+ingress=pathlib.Path('/etc/carlos/group-ingress.json')
+last=None
+(root/'observer-ready').touch()
+deadline=time.monotonic()+1000
+while time.monotonic()<deadline:
+ if ingress.exists() and 'ingress_ns' not in e:e['ingress_ns']=time.monotonic_ns()
+ try:
+ s=sample(work)
+ s['ingress_absent']=not ingress.exists()
+ state=(s['dev'],s['ino'],s['flags'],s['mode'])
+ if state!=last:
+ e['samples'].append(s);last=state
+ except FileNotFoundError:
+ if last is not None:e['removed_ns']=time.monotonic_ns();last=None
+ except OSError as ex:e['error']=str(ex)
+ if (root/'observer-stop').exists():break
+ time.sleep(0.05)
+e['parent_after']=sample(work.parent)
+e['finished_ns']=time.monotonic_ns()
+(root/'observer.json').write_text(json.dumps(e))
+(root/'observer-done').touch()
+for n in range(60):
+ try:
+ p=subprocess.run(['cloud-init','status','--long'],capture_output=True,text=True,timeout=5)
+ if 'status: running' not in p.stdout:
+ status=dict(rc=p.returncode,out=p.stdout+p.stderr)
+ with open('/dev/console','w') as console:
+ console.write('WITNESS final-cloud-init '+base64.b64encode(json.dumps(status).encode()).decode()+'\n')
+ break
+ except Exception:pass
+ time.sleep(2)
+'''
+
+
+def observer(s):
+ return OBSERVER.replace('@RUN@', s['run']).encode()
+
+
+def collector(s):
+ return COLLECTOR.replace('@RUN@', s['run']).replace('@MOUNTS@', repr(MOUNTS)).replace('@UNITS@', repr(UNITS)).encode()
+
+
+def user_data(script, collection, observation=None):
+ boundary = 'p3b1-f4-' + hashlib.sha256(script + collection).hexdigest()[:24]
+ body = f'MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary="{boundary}"\n\n'.encode()
+ payloads = [('001-boot', 'text/x-shellscript', script), ('002-collect', 'text/x-shellscript', collection)]
+ if observation is not None:
+ payloads.append(('000-observe', 'text/cloud-boothook', observation))
+ for name, kind, payload in payloads:
+ body += (f'--{boundary}\nContent-Type: {kind}; charset="utf-8"\n'
+ f'Content-Transfer-Encoding: 8bit\nContent-Disposition: attachment; filename="{name}"\n\n').encode()
+ body += payload + b'\n'
+ body += f'--{boundary}--\n'.encode()
+ parsed = BytesParser(policy=email.policy.default).parsebytes(body)
+ parts = list(parsed.iter_parts())
+ require(len(parts) == len(payloads) and parts[0].get_payload(decode=True) == script, 'part 1 byte integrity')
+ require(parts[1].get_payload(decode=True) == collection, 'collector byte integrity')
+ if observation is not None:
+ require(parts[2].get_payload(decode=True) == observation, 'observer byte integrity')
+ raw = gzip.compress(body, mtime=0)
+ require(max(len(raw), len(base64.b64encode(raw))) <= 16384, 'MIME raw/encoded size exceeds 16384')
+ return raw
+
+
+def launch_input(lt, s):
+ # Fail on new configured attributes rather than silently omitting them.
+ supported = {'image_id', 'instance_type', 'metadata_options', 'block_device_mappings', 'network_interfaces',
+ 'monitoring', 'user_data', 'iam_instance_profile', 'tags', 'name', 'default_version',
+ 'update_default_version', 'description', 'name_prefix', 'tag_specifications'}
+ computed = {'id', 'arn', 'latest_version', 'tags_all', 'region'}
+ require(not {k for k, v in lt.items() if v not in (None, [], {}, '', False) and k not in supported | computed},
+ 'unmapped launch template attributes')
+ require(lt['image_id'] == AMI, 'AMI drift')
+ metadata = lt['metadata_options'][0]
+ require(metadata.get('http_tokens') == 'required' and metadata['http_put_response_hop_limit'] == 1, 'IMDS drift')
+ meta_names = {'http_endpoint': 'HttpEndpoint', 'http_tokens': 'HttpTokens',
+ 'http_put_response_hop_limit': 'HttpPutResponseHopLimit', 'http_protocol_ipv6': 'HttpProtocolIpv6',
+ 'instance_metadata_tags': 'InstanceMetadataTags'}
+ require(not {k for k,v in metadata.items() if v not in (None,'') and k not in meta_names}, 'metadata field drift')
+ ebs_names = {'volume_size': 'VolumeSize', 'volume_type': 'VolumeType', 'encrypted': 'Encrypted',
+ 'delete_on_termination': 'DeleteOnTermination', 'iops': 'Iops', 'throughput': 'Throughput',
+ 'kms_key_id': 'KmsKeyId', 'snapshot_id': 'SnapshotId'}
+ blocks = []
+ for block in lt['block_device_mappings']:
+ ebs = block['ebs'][0]
+ require(ebs['encrypted'] is True and ebs['delete_on_termination'] is True, 'EBS safety drift')
+ require(not {k for k,v in ebs.items() if v not in (None,'',[]) and k not in ebs_names}, 'EBS field drift')
+ require(not block.get('no_device') and not block.get('virtual_name'), 'unsupported block mapping')
+ blocks.append(dict(DeviceName=block['device_name'], Ebs={ebs_names[k]:v for k,v in ebs.items() if v is not None and v != ''}))
+ require(len(lt['network_interfaces']) == 1, 'network interface count')
+ network = lt['network_interfaces'][0]
+ require(network['associate_public_ip_address'] is True and network['delete_on_termination'] is True, 'public IPv4 required')
+ allowed_net = {'associate_public_ip_address','delete_on_termination','security_groups','device_index'}
+ require(not {k for k,v in network.items() if v not in (None,[],{},'',False,0) and k not in allowed_net}, 'network field drift')
+ tags = dict(lt.get('tags') or {}, purpose='p3b1-f4-witness', Name=s['role'], witness_run=s['run'])
+ result = dict(ImageId=lt['image_id'], InstanceType=lt['instance_type'], MinCount=1, MaxCount=1,
+ ClientToken=s['role'], IamInstanceProfile={'Name':s['role']},
+ MetadataOptions={meta_names[k]:v for k,v in metadata.items() if v is not None and v != ''},
+ BlockDeviceMappings=blocks,
+ NetworkInterfaces=[dict(DeviceIndex=0, SubnetId=SUBNET, Groups=[SG], AssociatePublicIpAddress=True,
+ DeleteOnTermination=network['delete_on_termination'])],
+ TagSpecifications=[dict(ResourceType=kind, Tags=[dict(Key=k,Value=v) for k,v in tags.items()])
+ for kind in ('instance','volume')])
+ if lt.get('monitoring'):
+ result['Monitoring'] = {'Enabled': lt['monitoring'][0]['enabled']}
+ return result
+
+
+class AWSError(RuntimeError):
+ def __init__(self, service, operation, code, detail=''):
+ super().__init__(f'{service} {operation}: {code} {detail}')
+ self.code = code
+
+
+class AWS:
+ dry = False
+
+ def __call__(self, service, operation, _file=None, _timeout=90, _user_data=None, **params):
+ args = ['aws', '--profile', 'kass', '--region', REGION, '--no-cli-pager', service, operation]
+ if service == 's3api' and operation == 'get-object':
+ # The CLI's streaming outfile customization requires these flags
+ # even when --cli-input-json supplies the same fields.
+ require(_file is not None and set(params) <= {'Bucket', 'Key', 'VersionId'}, 'unsupported get-object arguments')
+ args += ['--bucket', params['Bucket'], '--key', params['Key']]
+ if 'VersionId' in params:
+ args += ['--version-id', params['VersionId']]
+ args += ['--output', 'json', str(_file)]
+ else:
+ require(_file is None, 'unexpected outfile')
+ args += ['--cli-input-json', json.dumps(params), '--output', 'json']
+ if service == 'ec2' and operation == 'run-instances':
+ require(_user_data is not None and 'UserData' not in params, 'raw user-data file required')
+ args += ['--user-data', 'fileb://' + str(Path(_user_data).resolve())]
+ else:
+ require(_user_data is None, 'unexpected user-data file')
+ safe = dict(params)
+ if operation == 'put-parameter':
+ safe['Value'] = '[REDACTED]'
+ if operation == 'run-instances':
+ safe['UserDataFile'] = str(_user_data)
+ print('AWS', service, operation, json.dumps(safe, sort_keys=True), flush=True)
+ env = dict(os.environ, AWS_MAX_ATTEMPTS='1', AWS_RETRY_MODE='standard', AWS_PAGER='')
+ # No automatic mutation retries: an ambiguous response belongs to the
+ # journal and cleanup, not a second creation attempt.
+ p = subprocess.run(args, capture_output=True, text=True, timeout=_timeout, env=env)
+ if p.returncode:
+ match = re.search(r'An error occurred \(([^)]+)\)', p.stderr)
+ raise AWSError(service, operation, match[1] if match else 'CLIError', p.stderr[:1500])
+ return json.loads(p.stdout or '{}')
+
+
+def absent(aws, service, operation, codes, **params):
+ try:
+ aws(service, operation, **params)
+ except AWSError as ex:
+ if ex.code in codes:
+ return True
+ raise
+ return False
+
+
+def atomic_json(path, value):
+ path = Path(path)
+ tmp = path.with_name(path.name + '.new')
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
+ try:
+ with os.fdopen(fd, 'w') as f:
+ json.dump(value, f, indent=2, sort_keys=True)
+ f.write('\n')
+ f.flush()
+ os.fsync(f.fileno())
+ os.replace(tmp, path)
+ fd = os.open(path.parent, os.O_DIRECTORY)
+ try:
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+ finally:
+ tmp.unlink(missing_ok=True)
+
+
+@contextmanager
+def exclusive(path):
+ fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
+ try:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ raise ValueError('another witness/cleanup owns the ledger lock')
+ yield
+ finally:
+ os.close(fd)
+
+
+def reserve_budget(path, run, owner):
+ # Caller holds the process-wide scratch ledger lock throughout the run.
+ data = json.loads(path.read_text()) if path.exists() else {'schema': 1, 'runs': []}
+ require(data.get('schema') == 1 and isinstance(data.get('runs'), list), 'invalid budget ledger')
+ require(len(data['runs']) < 2, 'two-run witness budget exhausted')
+ require(not any(r['run'] == run for r in data['runs']), 'run id already spent')
+ data['runs'].append(dict(run=run, owner=owner, reserved_at=datetime.now(timezone.utc).isoformat()))
+ atomic_json(path, data)
+
+
+class Journal:
+ def __init__(self, path, s=None, dry=False):
+ self.path = Path(path)
+ if s is None:
+ self.data = json.loads(self.path.read_text())
+ require(self.data.get('schema') == 1, 'invalid ownership journal')
+ require(self.data['scope'] == scope(self.data['scope']['run']), 'journal scope mismatch')
+ require(self.data['account'] == ACCOUNT and self.data['region'] == REGION, 'journal account/region mismatch')
+ require(self.data['dry'] == dry, 'simulation/live journal mismatch')
+ else:
+ require(not self.path.exists(), 'run journal exists; use cleanup-only')
+ self.data = dict(schema=1, scope=s, account=ACCOUNT, region=REGION, dry=dry,
+ owner=uuid.uuid4().hex, resources=[], checks=[], status='preflight')
+ self.save()
+
+ def save(self):
+ atomic_json(self.path, self.data)
+
+ def intent(self, kind, name):
+ require(not any(r['kind'] == kind and r['name'] == name for r in self.data['resources']), 'duplicate create intent')
+ row = dict(kind=kind, name=name, state='pending', ids={})
+ self.data['resources'].append(row)
+ self.save() # fsync BEFORE the API mutation, including when its reply is lost
+ return row
+
+ def create(self, aws, row, service, operation, **params):
+ try:
+ return aws(service, operation, **params)
+ except AWSError as ex:
+ # These responses reject the request before creating a resource.
+ # Timeouts, transport failures and service errors stay pending.
+ rejected = False
+ if service == 'ssm' and operation == 'put-parameter' and ex.code == 'ValidationException':
+ try:
+ rejected = absent(aws, 'ssm', 'get-parameter', {'ParameterNotFound'}, Name=params['Name'])
+ except Exception:
+ pass # An unreadable outcome is still pending.
+ if rejected or ex.code in {'AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation',
+ 'EntityAlreadyExists', 'ParameterAlreadyExists', 'InvalidParameterValue',
+ 'InvalidParameterCombination', 'ValidationError', 'InvalidAMIID.NotFound',
+ 'InsufficientInstanceCapacity', 'InstanceLimitExceeded'}:
+ row.update(state='rejected', error=str(ex))
+ self.save()
+ raise
+
+ def made(self, row, **ids):
+ row.update(state='created', ids=ids)
+ self.save()
+
+ def gone(self, row):
+ row['state'] = 'gone'
+ self.save()
+
+ def tags(self):
+ return [dict(Key=k, Value=v) for k, v in dict(purpose=PURPOSE,
+ witness_run=self.data['scope']['run'], witness_owner=self.data['owner']).items()]
+
+
+def owned(tags, journal):
+ actual = {x['Key']: x['Value'] for x in tags}
+ return all(actual.get(t['Key']) == t['Value'] for t in journal.tags())
+
+
+def box_ref(iid):
+ return 'g-' + hashlib.sha256(f'carlos-box-ref-v1|{ACCOUNT}|{iid}'.encode()).hexdigest()[:20]
+
+
+def verify_pointer(path, pubkey):
+ result = subprocess.run(['nice', '-n', '10', 'go', 'run', './scripts/witness-pointer', str(path), str(pubkey)],
+ cwd=ROOT, capture_output=True, text=True, timeout=180)
+ require(result.returncode == 0, 'release pointer signature: ' + result.stderr[-2000:])
+ pointer = json.loads(result.stdout)
+ artifact_key(pointer)
+ return pointer
+
+
+
+def properties(e, unit):
+ return dict(line.split('=', 1) for line in e.get('commands', {}).get(unit + '-show', {}).get('out', '').splitlines() if '=' in line)
+
+
+def decoded_command(e, name):
+ command = e.get('commands', {}).get(name, {})
+ if command.get('rc') != 0:
+ return None
+ try:
+ return json.loads(command['out'])
+ except (ValueError, KeyError):
+ return None
+
+
+def staging_mount_ok(e):
+ observation = e.get('staging_observer', {})
+ samples = observation.get('samples', [])
+ before, after = observation.get('parent_before', {}), observation.get('parent_after', {})
+ removed = observation.get('removed_ns', 0)
+ ingress = observation.get('ingress_ns', 0)
+ return bool(observation.get('clock') == 'CLOCK_MONOTONIC' and samples and before.get('dev') == after.get('dev') and not before.get('noexec', True)
+ and not after.get('noexec', True) and not observation.get('error')
+ and all(s.get('dev') == before.get('dev') and not s.get('noexec', True)
+ and s.get('uid') == s.get('gid') == 0 and s.get('mode') == '0o700'
+ and s.get('mountinfo') for s in samples)
+ and samples[0].get('ingress_absent')
+ and samples[0].get('monotonic_ns', 0) < ingress < removed <= observation.get('finished_ns', 0))
+
+
+def uid_binding_ok(e):
+ cmds = e.get('commands', {})
+ try:
+ passwd = cmds['user']['out'].strip().split(':')
+ uid, gid = int(passwd[2]), int(passwd[3])
+ group = cmds['group']['out'].strip().split(':')
+ require(int(group[2]) == gid, 'group gid')
+ require(re.search(r'\buid=' + str(uid) + r'\(carlos\)', cmds['groups']['out'])
+ and re.search(r'\bgid=' + str(gid) + r'\(carlos\)', cmds['groups']['out']), 'id membership')
+ rules = decoded_command(e, 'nft-json')['nftables']
+ protected = set()
+ for item in rules:
+ rule = item.get('rule', {})
+ if rule.get('table') != 'carlos_group_imds' or rule.get('chain') != 'output':
+ continue
+ expr = rule.get('expr', [])
+ uid_match = any(x.get('match', {}).get('left') == {'meta': {'key': 'skuid'}}
+ and x['match'].get('op') == '!='
+ and set(x['match'].get('right', {}).get('set', [])) == {0, uid} for x in expr)
+ if uid_match and any('reject' in x for x in expr):
+ for x in expr:
+ match = x.get('match', {})
+ if match.get('left', {}).get('payload', {}).get('field') == 'daddr':
+ protected.add(match.get('right'))
+ return uid > 0 and protected == {'169.254.169.254', 'fd00:ec2::254'}
+ except (KeyError, TypeError, ValueError, IndexError, AttributeError):
+ return False
+
+
+def reset_completed(e):
+ props = properties(e, 'carlos-hairpin-reset')
+ journal = e.get('commands', {}).get('carlos-hairpin-reset-journal', {})
+ show = e.get('commands', {}).get('carlos-hairpin-reset-show', {})
+ if show.get('rc') != 0 or journal.get('rc') != 0 or props.get('Result') != 'success' or props.get('ExecMainStatus') != '0':
+ return False
+ pending, completed = False, 0
+ for line in journal.get('out', '').splitlines():
+ match = re.fullmatch(r'\[\s*[0-9]+\.[0-9]+\] \S+ systemd\[1\]: (.*)', line)
+ if not match:
+ continue
+ message = match[1]
+ if message == 'Starting carlos-hairpin-reset.service...':
+ if pending:
+ return False
+ pending = True
+ elif message == 'Finished carlos-hairpin-reset.service.':
+ if not pending:
+ return False
+ pending, completed = False, completed + 1
+ elif 'carlos-hairpin-reset.service' in message and re.search(r'fail|timed out|error', message, re.I):
+ return False
+ return completed > 0 and not pending
+
+
+def p_assertions(e, w4):
+ cmds = e.get('commands', {})
+ out = lambda k: cmds.get(k, {}).get('out', '')
+ readback = e.get('launch_readback', {}).get('instance', {})
+ meta = readback.get('MetadataOptions', {})
+ mounts = e.get('mounts', {})
+ links, addresses = decoded_command(e, 'link'), decoded_command(e, 'addresses')
+ dummy = [x for x in links or [] if x.get('ifname') == 'carlos-hairpin']
+ eips = {'54.77.110.223', '18.203.21.74'}
+ assigned = {a.get('local') for link in addresses or [] for a in link.get('addr_info', [])}
+ record_paths = ['/etc/carlos/group-identity.json', '/etc/carlos/region-config.json',
+ '/etc/carlos/group.json', '/etc/carlos/group-ingress.json']
+ records = [(e.get('files', {}).get(path) or {}) for path in record_paths]
+ edge, control = properties(e, 'carlos-edge'), properties(e, 'carlos-instance-control')
+ security = edge.get('User') == edge.get('Group') == 'carlos' and edge.get('NoNewPrivileges') == 'yes'
+ security = security and edge.get('CapabilityBoundingSet') == 'cap_net_bind_service' and edge.get('AmbientCapabilities') == 'cap_net_bind_service'
+ for props in (edge, control):
+ security = security and props.get('ProtectSystem') == 'strict' and props.get('ProtectHome') == 'yes'
+ security = security and all(props.get(k) == 'yes' for k in ('PrivateTmp', 'PrivateDevices', 'ProtectKernelTunables', 'ProtectKernelModules', 'MemoryDenyWriteExecute'))
+ security = security and control.get('User', '') in ('', 'root') and control.get('Group', '') in ('', 'root')
+ security = security and 'AF_NETLINK' in control.get('RestrictAddressFamilies', '') and '/run/carlos-hairpin' in control.get('ReadWritePaths', '')
+ security_checks = {'unit settings': security}
+ status = e.get('edge_process_status', '')
+ security_checks['live edge process privileges'] = bool(re.search(r'^NoNewPrivs:\s+1$', status, re.M)) and bool(re.search(r'^CapEff:\s+0*400$', status, re.M))
+ security_checks['bind mount flags'] = True
+ for path in ('/data/instances', '/run/carlos/instances', '/run/carlos/logs'):
+ mount = mounts.get(path, {})
+ output = mount.get('findmnt', {}).get('out', '')
+ security_checks['bind mount flags'] &= mount.get('probe') == path and all(x in output for x in ('nosuid', 'nodev', 'nosymfollow'))
+ alias_ok = all(path in mounts and mounts[path].get('probe') == path and mounts[path].get('findmnt', {}).get('rc') == 0
+ and mounts[path].get('realpath') == target for path, target in [('/var/run', '/run'), ('/var/lock', '/run/lock')])
+ return [
+ ('P1 live metadata options', readback.get('ImageId') == AMI and meta.get('HttpTokens') == 'required' and meta.get('HttpPutResponseHopLimit') == 1, 'operator describe-instances readback'),
+ ('P2 alias mount inventory', alias_ok, '/var/run -> /run; /var/lock -> /run/lock; findmnt + realpath'),
+ ('P3 before/after staging mount', staging_mount_ok(e), 'early boothook observer; actual leaf before ingress, removal and parent after'),
+ ('P4 system group and IMDS uid binding', uid_binding_ok(e), 'getent + id + parsed nft JSON, exact {0,carlos uid} for IPv4 and IPv6'),
+ ('P5 bootstrap tools', cmds.get('bootstrap-tools', {}).get('rc') == 0 and len(out('bootstrap-tools').splitlines()) == 5, out('bootstrap-tools')),
+ ('P6 dormant dummy and no ingress EIP', bool(len(dummy) == 1 and dummy[0].get('linkinfo', {}).get('info_kind') == 'dummy'
+ and addresses is not None and addresses and not assigned.intersection(eips)
+ and all(not x.get('addr_info') for x in addresses if x.get('ifname') == 'carlos-hairpin')), 'ip -j link and address inventory; no EIP on any interface'),
+ ('P7 unattended upgrades masked', out('apt-masks').splitlines() == ['masked'] * 5, out('apt-masks')),
+ ('P8 drop-in-only edge gate', w4, 'inferred from W4: successful hairpin installation passed the pre-base-unit edge gate'),
+ ('P9 immutable record metadata', all(r.get('uid') == r.get('gid') == 0 and r.get('mode') == '0o644'
+ and r.get('nlink') == 1 and r.get('regular') is True for r in records), 'lstat uid/gid/mode/nlink/type for all four records'),
+ ('P10 installed unit security', all(security_checks.values()),
+ '; '.join(name + '=' + ('PASS' if ok else 'FAIL') for name, ok in security_checks.items()) + '; no tenant execution probe'),
+ ]
+
+
+def assertions(e):
+ files=e.get('files',{}); cmds=e.get('commands',{})
+ out=lambda k:cmds.get(k,{}).get('out','')
+ rc=lambda k:cmds.get(k,{}).get('rc',255)
+ exists=lambda k:bool(files.get(k))
+ ordered=['/etc/carlos/group-identity.json','/etc/carlos/region-config.json','/etc/carlos/group.json',
+ '/etc/carlos/group-ingress.json','/etc/nftables.conf','/etc/carlos/host.env']
+ times=[files.get(k,{}).get('mtime',0) if files.get(k) else 0 for k in ordered]
+ rows = [
+ ('W1 exec mount', staging_mount_ok(e), 'observer actual leaf + parent before/after; template hash checks before all three execs'),
+ ('W2 identity verified before ingress', exists(ordered[3]) and all(times[:4]) and times[:4]==sorted(times[:4]), 'exclusive writes after identity verifier'),
+ ('W3 immutable records', all(exists(k) for k in ordered[:4]), 'group identity/region/marker/ingress'),
+ ('W4 hairpin installed', rc('nft')==0 and all(x in out('nft') for x in ('carlos_group_imds','carlos_hairpin')), out('nft')[:200]),
+ ('W5 dormant nft persisted', rc('nft-persist')==0 and all(x in out('nft-persist') for x in ('carlos_group_imds','carlos_hairpin')), out('nft-persist')[:200]),
+ ('W6 host.env installed', exists('/etc/carlos/host.env') and files['/etc/carlos/host.env']['mode']=='0o600' and files['/etc/carlos/host.env']['uid']==0, 'metadata only; values omitted'),
+ ('W7 Restart=no', 'Restart=no\n' in out('carlos-edge-show'), out('carlos-edge-show')[:250]),
+ ('W8 edge ran', properties(e, 'carlos-edge').get('ActiveState') == 'active'
+ and bool(re.fullmatch(r'[1-9][0-9]*', properties(e, 'carlos-edge').get('MainPID', '')))
+ and bool(re.search(r'ExecMainStartTimestampMonotonic=[1-9][0-9]*',out('carlos-edge-show'))), out('carlos-edge-show')[:250]),
+ ('W9 publication denied', bool(re.search(r'agent: edges file pass failed[^\n]*AccessDenied', out('carlos-edge-journal'))) and 'tenant admission is open' not in out('carlos-edge-journal'), out('carlos-edge-journal')[-500:]),
+ ('W10 work dir removed', '/var/lib/carlos-group-boot' in files and files['/var/lib/carlos-group-boot'] is None and exists('/etc/carlos/host.env'), 'final cleanup after start'),
+ ('W11 sysctl', all(f'net.ipv4.conf.{axis}.arp_{name} = {value}' in out('sysctl') for axis in ('all','default') for name,value in [('ignore',1),('announce',2)]), out('sysctl')),
+ ('W12 AMI tools', rc('tools')==0 and 'Python 3.13' in out('tools') and 'aws-cli/2.' in out('tools'), out('tools')),
+ ('W13 MAC policy', rc('apparmor') == 0 and 'apparmor module is loaded' in out('apparmor') and rc('lsm') == 0 and 'apparmor' in out('lsm') and rc('mac-denials') in (0,1) and not re.search(r'apparmor="DENIED"|avc:.*denied',out('mac-denials')), out('mac-denials')),
+ ('W14 installed binary', exists('/opt/carlos/carlos'), 'reset ExecStart path'),
+ ('W15 clock', rc('chrony')==0 and bool(re.search(r'\^[*+]\s+169\.254\.169\.123',out('chrony'))), out('chrony')),
+ ('W16 write order', all(times) and times==sorted(times), 'identity -> region -> marker -> ingress -> nft persist -> host.env'),
+ ('W17 executable install paths', all(p in e.get('mounts',{}) and not e['mounts'][p]['noexec'] for p in ('/opt','/var/lib/cloud')), 'statvfs for /opt and cloud-init'),
+ ('W18 system user', rc('user')==0 and bool(re.search(r'^carlos:[^:]*:[0-9]+:[0-9]+:[^:]*:/data:/usr/sbin/nologin',out('user'))), out('user')),
+ ('W19 mount units', rc('mount-units')==0 and out('mount-units').splitlines()==['active']*3, out('mount-units')),
+ ('W20 reset unit', reset_completed(e), out('carlos-hairpin-reset-journal') + out('carlos-hairpin-reset-show')),
+ ('W21 persisted nft syntax', rc('nft-check')==0, out('nft-check')),
+ ('W22 SELinux absent', rc('selinux')==2 and 'No such file' in out('selinux') and rc('lsm') == 0 and 'selinux' not in out('lsm'),out('selinux')),
+ ('W23 systemd features', 'systemd 257' in out('tools') and '/usr/bin/systemctl' in out('carlos-edge-show') and 'AF_NETLINK' in out('carlos-instance-control-show') and '/run/carlos-hairpin' in out('carlos-instance-control-show'),out('carlos-instance-control-show')),
+ ]
+
+ return rows + p_assertions(e, rows[3][1])
+
+
+def snapshot(aws):
+ observed, errors = {}, []
+ # A failed TG check must not suppress the other TG or edges reads.
+ for tg in TGS:
+ try:
+ rows = aws('elbv2', 'describe-target-health', TargetGroupArn=tg)['TargetHealthDescriptions']
+ observed[tg] = sorted((r['Target'] for r in rows), key=lambda r: json.dumps(r, sort_keys=True))
+ except Exception as ex:
+ errors.append(str(ex))
+ try:
+ objects = aws('s3api', 'list-objects-v2', Bucket=BUCKET, Prefix=EDGES_PREFIX)
+ require(not objects.get('IsTruncated'), 'incomplete edges listing')
+ observed['edges'] = sorted(x['Key'] for x in objects.get('Contents', []))
+ except Exception as ex:
+ errors.append(str(ex))
+ try:
+ versions = aws('s3api', 'list-object-versions', Bucket=BUCKET, Prefix=EDGES_PREFIX)
+ require(not versions.get('IsTruncated'), 'incomplete edges version listing')
+ observed['edge_versions'] = sorted([x['Key'], x['VersionId']] for x in
+ versions.get('Versions', []) + versions.get('DeleteMarkers', []))
+ except Exception as ex:
+ errors.append(str(ex))
+ observed['errors'] = errors
+ return observed
+
+
+def check_snapshot(before, after, iids=()):
+ errors = list(before.get('errors', [])) + list(after.get('errors', []))
+ for tg in TGS:
+ ids = {r['Id'] for r in after.get(tg, [])}
+ if ids != FIXED or ids.intersection(iids) or before.get(tg) != after.get(tg):
+ errors.append('target membership changed: ' + tg)
+ if before.get('edges') != after.get('edges'):
+ errors.append('control/edges/ key set changed')
+ # New versions of existing fixed-box objects are normal. Any version of a
+ # newly named object, even one already deleted, is a failed witness window.
+ new = {tuple(x) for x in after.get('edge_versions', [])} - {tuple(x) for x in before.get('edge_versions', [])}
+ if any(key not in before.get('edges', []) for key, version in new):
+ errors.append('new edges object during window (including deleted objects)')
+ for iid in iids:
+ key = EDGES_PREFIX + box_ref(iid) + '.json'
+ if key in after.get('edges', []) or any(k == key for k, v in after.get('edge_versions', [])):
+ errors.append('witness edges object: ' + key)
+ return errors
+
+
+def s3_time(value):
+ stamp = datetime.fromisoformat(value.replace('Z', '+00:00'))
+ require(stamp.tzinfo is not None, 'S3 timestamp has no timezone')
+ return stamp
+
+
+def object_versions(aws, key):
+ result = aws('s3api', 'list-object-versions', Bucket=BUCKET, Prefix=key)
+ require(not result.get('IsTruncated'), 'incomplete version listing: ' + key)
+ return [x for x in result.get('Versions', []) if x['Key'] == key], [x for x in result.get('DeleteMarkers', []) if x['Key'] == key]
+
+
+def instances(aws, journal):
+ filters = [dict(Name='tag:' + t['Key'], Values=[t['Value']]) for t in journal.tags()]
+ result = aws('ec2', 'describe-instances', Filters=filters)
+ return [i for r in result.get('Reservations', []) for i in r['Instances']]
+
+
+def collision(aws, journal, kind, name):
+ if kind == 'role':
+ require(absent(aws, 'iam', 'get-role', {'NoSuchEntity'}, RoleName=name), 'role collision')
+ elif kind == 'profile':
+ require(absent(aws, 'iam', 'get-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name), 'profile collision')
+ elif kind == 'parameter':
+ require(absent(aws, 'ssm', 'get-parameter', {'ParameterNotFound'}, Name=name), 'parameter collision: ' + name)
+ elif kind == 'copy':
+ versions, markers = object_versions(aws, name)
+ require(not versions and not markers, 'scratch bootstrap key collision')
+ require(absent(aws, 's3api', 'head-object', {'404', 'NoSuchKey', 'NotFound'}, Bucket=BUCKET, Key=name), 'scratch bootstrap collision')
+ elif kind == 'instance':
+ for tag in ('witness_run', 'Name'):
+ result = aws('ec2', 'describe-instances', Filters=[dict(Name='tag:' + tag,
+ Values=[journal.data['scope']['run'] if tag == 'witness_run' else name])])
+ require(not any(r.get('Instances') for r in result.get('Reservations', [])), 'instance name/tag collision')
+ else:
+ raise ValueError('unknown creation kind: ' + kind)
+
+
+def floor_preflight(aws):
+ for key in FLOOR_KEYS:
+ require(absent(aws, 's3api', 'head-object', {'404', 'NoSuchKey', 'NotFound'}, Bucket=BUCKET, Key=key),
+ 'floor now exists; absent-expected branch changed: ' + key)
+ print('PREFLIGHT 404', key, FLOOR_LABEL, flush=True)
+
+
+def input_preflight(aws, directory, pubkey_file):
+ identity = aws('sts', 'get-caller-identity')
+ require(identity['Account'] == ACCOUNT, 'wrong AWS account')
+ region = aws('ec2', 'describe-regions', RegionNames=[REGION])
+ require([r['RegionName'] for r in region['Regions']] == [REGION], 'wrong AWS region')
+ image = aws('ec2', 'describe-images', ImageIds=[AMI])['Images']
+ require(len(image) == 1 and image[0]['ImageId'] == AMI and image[0]['Architecture'] == 'arm64'
+ and image[0]['State'] == 'available' and image[0]['RootDeviceType'] == 'ebs'
+ and image[0]['RootDeviceName'] == '/dev/xvda' and image[0]['Name'] == 'debian-13-arm64-20261103-2651', 'AMI drift')
+ subnet = aws('ec2', 'describe-subnets', SubnetIds=[SUBNET])['Subnets']
+ groups = aws('ec2', 'describe-security-groups', GroupIds=[SG])['SecurityGroups']
+ require(len(subnet) == len(groups) == 1, 'network readback count')
+ subnet, group = subnet[0], groups[0]
+ require(subnet['SubnetId'] == SUBNET and subnet['State'] == 'available' and subnet['MapPublicIpOnLaunch']
+ and subnet['AvailabilityZone'].startswith(REGION) and subnet['VpcId'] == group['VpcId']
+ and group['GroupId'] == SG and group['OwnerId'] == ACCOUNT and not group['IpPermissions'], 'subnet/SG drift')
+ require(aws('s3api', 'get-bucket-location', Bucket=BUCKET)['LocationConstraint'] == REGION, 'bucket region drift')
+ require(aws('s3api', 'get-bucket-versioning', Bucket=BUCKET).get('Status') == 'Enabled', 'versioned bucket required')
+ floor_preflight(aws)
+ pointer_path = directory / 'stable.json'
+ meta = aws('s3api', 'get-object', Bucket=BUCKET, Key=POINTER_KEY, _file=pointer_path)
+ pointer = verify_pointer(pointer_path, pubkey_file)
+ for key, version in [(BOOT_KEY, BOOT_VERSION), (artifact_key(pointer), None)]:
+ params = dict(Bucket=BUCKET, Key=key)
+ if version:
+ params['VersionId'] = version
+ head = aws('s3api', 'head-object', **params)
+ require(0 < head['ContentLength'] <= 256 * 1024 * 1024, 'artifact size out of bounds')
+ if version:
+ require(head['VersionId'] == version, 'bootstrap source version drift')
+ kms = aws('kms', 'describe-key', KeyId='alias/aws/ssm')['KeyMetadata']
+ require(kms['Arn'].startswith(f'arn:aws:kms:{REGION}:{ACCOUNT}:key/') and kms['Enabled']
+ and kms['KeyState'] == 'Enabled', 'SSM KMS key drift')
+ atomic_json(directory / 'preflight.json', dict(identity=identity, region=region, image=image,
+ subnet=subnet, security_group=group, pointer=meta, kms=kms, floor=FLOOR_LABEL))
+ return pointer, kms['Arn']
+
+
+def launch_readback(aws, iid, launch, raw_user_data):
+ rows = [i for r in aws('ec2', 'describe-instances', InstanceIds=[iid])['Reservations'] for i in r['Instances']]
+ require(len(rows) == 1 and rows[0]['InstanceId'] == iid, 'launch readback count')
+ instance = rows[0]
+ for key in ('ImageId', 'InstanceType'):
+ require(instance[key] == launch[key], 'instance launch drift: ' + key)
+ for key, value in launch['MetadataOptions'].items():
+ require(instance['MetadataOptions'][key] == value, 'instance metadata drift: ' + key)
+ require(instance['SubnetId'] == SUBNET and {g['GroupId'] for g in instance['SecurityGroups']} == {SG}
+ and instance.get('PublicIpAddress'), 'instance network drift')
+ profile = launch['IamInstanceProfile']['Name']
+ require(instance['IamInstanceProfile']['Arn'] == f'arn:aws:iam::{ACCOUNT}:instance-profile/{profile}', 'instance profile drift')
+ require(not aws('autoscaling', 'describe-auto-scaling-instances', InstanceIds=[iid])['AutoScalingInstances'], 'witness joined ASG')
+ expected_monitoring = 'enabled' if launch.get('Monitoring', {}).get('Enabled') else 'disabled'
+ require(instance['Monitoring']['State'] == expected_monitoring, 'monitoring drift')
+ attribute = aws('ec2', 'describe-instance-attribute', InstanceId=iid, Attribute='userData')
+ require(attribute['UserData']['Value'] == base64.b64encode(raw_user_data).decode(), 'user data readback drift')
+ mappings = instance['BlockDeviceMappings']
+ require(len(mappings) == len(launch['BlockDeviceMappings']), 'block device readback count')
+ volumes = aws('ec2', 'describe-volumes', VolumeIds=[r['Ebs']['VolumeId'] for r in mappings])['Volumes']
+ for want in launch['BlockDeviceMappings']:
+ mapping = next(r for r in mappings if r['DeviceName'] == want['DeviceName'])
+ volume = next(v for v in volumes if v['VolumeId'] == mapping['Ebs']['VolumeId'])
+ require(mapping['Ebs']['DeleteOnTermination'] == want['Ebs']['DeleteOnTermination'], 'volume retention drift')
+ for attr, expected in want['Ebs'].items():
+ if attr == 'DeleteOnTermination':
+ continue
+ require(volume[{'VolumeSize': 'Size'}.get(attr, attr)] == expected, 'volume drift: ' + attr)
+ return dict(instance=instance, volumes=volumes)
+
+
+def cleanup_plan(journal):
+ allowed = dict(instance={journal.data['scope']['role']}, profile={journal.data['scope']['role']},
+ role={journal.data['scope']['role']}, copy={journal.data['scope']['key']},
+ parameter=set(seed(journal.data['scope'], 'cleanup', 'public')))
+ resources = [r for r in journal.data['resources'] if r['state'] not in ('gone', 'rejected')]
+ for row in resources:
+ require(row['kind'] in allowed and row['name'] in allowed[row['kind']], 'out-of-scope journal resource')
+ order = ['instance', 'profile', 'role', 'parameter', 'copy']
+ return sorted(resources, key=lambda r: order.index(r['kind']))
+
+
+def cleanup_preview(journal):
+ # A preview never changes the journal or contacts AWS, including when an
+ # interrupted create has no returned id. Recovery then begins with tags.
+ calls = [('sts', 'get-caller-identity', {})]
+ def snapshots():
+ for tg in TGS:
+ calls.append(('elbv2', 'describe-target-health', dict(TargetGroupArn=tg)))
+ for op in ('list-objects-v2', 'list-object-versions'):
+ calls.append(('s3api', op, dict(Bucket=BUCKET, Prefix=EDGES_PREFIX)))
+ snapshots()
+ for row in cleanup_plan(journal):
+ kind, name = row['kind'], row['name']
+ if kind == 'instance':
+ calls.append(('ec2', 'describe-instances', dict(Filters=[dict(Name='tag:'+t['Key'], Values=[t['Value']]) for t in journal.tags()])))
+ ids = row['ids'].get('recovered_iids') or [row['ids'].get('iid', '<owned id recovered by tags>')]
+ calls += [('ec2', 'terminate-instances', dict(InstanceIds=ids)), ('ec2', 'describe-instances', dict(InstanceIds=ids))]
+ elif kind == 'profile':
+ for op, args in [('get-instance-profile', dict(InstanceProfileName=name)),
+ ('remove-role-from-instance-profile', dict(InstanceProfileName=name, RoleName=name)),
+ ('delete-instance-profile', dict(InstanceProfileName=name)),
+ ('get-instance-profile', dict(InstanceProfileName=name))]:
+ calls.append(('iam', op, args))
+ elif kind == 'role':
+ for op, args in [('get-role', dict(RoleName=name)), ('delete-role-policy', dict(RoleName=name, PolicyName='witness')),
+ ('delete-role', dict(RoleName=name)), ('get-role', dict(RoleName=name))]:
+ calls.append(('iam', op, args))
+ elif kind == 'parameter':
+ calls += [('ssm', 'get-parameter', dict(Name=name)),
+ ('ssm', 'list-tags-for-resource', dict(ResourceType='Parameter', ResourceId=name)),
+ ('ssm', 'delete-parameter', dict(Name=name)), ('ssm', 'get-parameter', dict(Name=name))]
+ elif kind == 'copy':
+ calls += [('s3api', 'list-object-versions', dict(Bucket=BUCKET, Prefix=name)),
+ ('s3api', 'head-object', dict(Bucket=BUCKET, Key=name, VersionId='<each version; validate owner>')),
+ ('s3api', 'delete-object', dict(Bucket=BUCKET, Key=name, VersionId='<each owned version and marker>')),
+ ('s3api', 'list-object-versions', dict(Bucket=BUCKET, Prefix=name)),
+ ('s3api', 'head-object', dict(Bucket=BUCKET, Key=name))]
+ snapshots()
+ return calls
+
+
+def resource_label(row, journal):
+ kind, name, ids = row['kind'], row['name'], row['ids']
+ if ids.get('arn'):
+ return ids['arn']
+ if kind in ('role', 'profile'):
+ return f'arn:aws:iam::{ACCOUNT}:' + ('role/' if kind == 'role' else 'instance-profile/') + name
+ if kind == 'parameter':
+ return f'arn:aws:ssm:{REGION}:{ACCOUNT}:parameter' + name
+ if kind == 'copy':
+ return f'arn:aws:s3:::{BUCKET}/' + name
+ return ids.get('iid') or ','.join(ids.get('recovered_iids', [])) or 'client-token:f4-' + journal.data['owner']
+
+
+def cleanup(aws, journal, sleep=time.sleep):
+ leaked = []
+ def retry(fn, label, attempts=12):
+ last = None
+ for n in range(attempts):
+ try:
+ return fn()
+ except Exception as ex:
+ last = ex
+ if n + 1 < attempts:
+ sleep(5)
+ raise RuntimeError(label + ': ' + str(last))
+
+ def ignore_missing(service, operation, codes, **params):
+ try:
+ return aws(service, operation, **params)
+ except AWSError as ex:
+ if ex.code not in codes:
+ raise
+ return None
+
+ for row in cleanup_plan(journal):
+ name, kind = row['name'], row['kind']
+ try:
+ if kind == 'instance':
+ def terminate():
+ found = instances(aws, journal)
+ known = row['ids'].get('iid')
+ if known and all(i['InstanceId'] != known for i in found):
+ found += [i for r in aws('ec2', 'describe-instances', InstanceIds=[known])['Reservations'] for i in r['Instances']]
+ # A pending launch can still be propagating after a lost
+ # reply. No instance is not proof of termination.
+ require(found, 'launch outcome unknown; retry cleanup-only')
+ for instance in found:
+ require(owned(instance.get('Tags', []), journal), 'instance owner changed')
+ require(instance['InstanceId'] not in FIXED, 'refuse fixed instance')
+ ids = sorted({i['InstanceId'] for i in found})
+ row['ids']['recovered_iids'] = ids
+ journal.save()
+ active = [i['InstanceId'] for i in found if i['State']['Name'] != 'terminated']
+ if active:
+ # Lost terminate replies are resolved by the next describe.
+ aws('ec2', 'terminate-instances', InstanceIds=active)
+ raise RuntimeError('termination pending')
+ return ids
+ retry(terminate, name, attempts=60)
+ elif kind == 'profile':
+ def delete_profile():
+ response = ignore_missing('iam', 'get-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name)
+ if response is None:
+ require(row['state'] != 'pending', 'profile create outcome unknown')
+ return
+ profile = response['InstanceProfile']
+ require(owned(profile.get('Tags', []), journal), 'profile owner changed')
+ require(not row['ids'].get('id') or row['ids']['id'] == profile['InstanceProfileId'], 'profile id changed')
+ journal.made(row, id=profile['InstanceProfileId'], arn=profile['Arn'])
+ for role in profile['Roles']:
+ require(role['RoleName'] == name, 'foreign role in profile')
+ ignore_missing('iam', 'remove-role-from-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name, RoleName=name)
+ ignore_missing('iam', 'delete-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name)
+ require(absent(aws, 'iam', 'get-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name), 'profile still exists')
+ retry(delete_profile, name)
+ elif kind == 'role':
+ def delete_role():
+ response = ignore_missing('iam', 'get-role', {'NoSuchEntity'}, RoleName=name)
+ if response is None:
+ require(row['state'] != 'pending', 'role create outcome unknown')
+ return
+ role = response['Role']
+ require(owned(role.get('Tags', []), journal), 'role owner changed')
+ require(not row['ids'].get('id') or row['ids']['id'] == role['RoleId'], 'role id changed')
+ journal.made(row, id=role['RoleId'], arn=role['Arn'])
+ ignore_missing('iam', 'delete-role-policy', {'NoSuchEntity'}, RoleName=name, PolicyName='witness')
+ ignore_missing('iam', 'delete-role', {'NoSuchEntity'}, RoleName=name)
+ require(absent(aws, 'iam', 'get-role', {'NoSuchEntity'}, RoleName=name), 'role still exists')
+ retry(delete_role, name)
+ elif kind == 'parameter':
+ def delete_parameter():
+ if absent(aws, 'ssm', 'get-parameter', {'ParameterNotFound'}, Name=name):
+ require(row['state'] != 'pending', 'parameter create outcome unknown')
+ return
+ tags = aws('ssm', 'list-tags-for-resource', ResourceType='Parameter', ResourceId=name)['TagList']
+ require(owned(tags, journal), 'parameter owner changed')
+ journal.made(row, **row['ids'])
+ ignore_missing('ssm', 'delete-parameter', {'ParameterNotFound'}, Name=name)
+ require(absent(aws, 'ssm', 'get-parameter', {'ParameterNotFound'}, Name=name), 'parameter still exists')
+ retry(delete_parameter, name)
+ elif kind == 'copy':
+ def delete_copy():
+ versions, markers = object_versions(aws, name)
+ require(versions or markers or row['state'] != 'pending', 'copy outcome unknown')
+ # Validate EVERY version before deleting any. A same-key
+ # foreign version is not ours, even after a lost reply.
+ for item in versions:
+ head = aws('s3api', 'head-object', Bucket=BUCKET, Key=name, VersionId=item['VersionId'])
+ require(head.get('Metadata', {}).get('witness-owner') == journal.data['owner'], 'object owner changed')
+ owned_at = row['ids'].get('owned_at')
+ if versions:
+ earliest = min(s3_time(item['LastModified']) for item in versions)
+ if owned_at is None:
+ owned_at = earliest.isoformat()
+ require(s3_time(owned_at) <= earliest, 'owned version timestamp drift')
+ if markers:
+ require(owned_at is not None, 'delete marker has no owned version timestamp')
+ require(all(s3_time(item['LastModified']) > s3_time(owned_at) for item in markers),
+ 'delete marker predates or coincides with owned version')
+ if versions or markers:
+ journal.made(row, **dict(row['ids'], owned_at=owned_at))
+ # Remove markers first; save the timestamp before either
+ # deletion so an interrupted cleanup can prove chronology.
+ for item in markers + versions:
+ aws('s3api', 'delete-object', Bucket=BUCKET, Key=name, VersionId=item['VersionId'])
+ require(object_versions(aws, name) == ([], []), 'scratch object versions remain')
+ require(absent(aws, 's3api', 'head-object', {'404', 'NoSuchKey', 'NotFound'}, Bucket=BUCKET, Key=name), 'scratch object still exists')
+ retry(delete_copy, name)
+ journal.gone(row)
+ except Exception as ex:
+ label = resource_label(row, journal)
+ leaked.append(label)
+ row['cleanup_error'] = str(ex)
+ journal.save()
+ print('LEAKED', label, str(ex), file=sys.stderr, flush=True)
+ journal.data['leaked'] = leaked
+ journal.save()
+ return leaked
+
+
+def read_archive(path):
+ require(path.stat().st_size <= 16 * 1024 * 1024, 'archive too large')
+ with tarfile.open(path, 'r:gz') as tar:
+ entry = tar.getmember('evidence.json')
+ require(entry.isfile() and entry.size <= 4 * 1024 * 1024, 'evidence bounds')
+ return json.load(tar.extractfile(entry))
+
+
+def decode_console(raw):
+ # botocore after-call.ec2.GetConsoleOutput already decodes Output, also
+ # with Latest=True. Decoding again would corrupt base64-looking text.
+ return raw
+
+
+def cloud_status(console):
+ matches = re.findall(r'WITNESS final-cloud-init ([A-Za-z0-9+/=]+)', console)
+ if matches:
+ try:
+ status = json.loads(base64.b64decode(matches[-1], validate=True))
+ if status['rc'] == 0 and re.search(r'^status: done$', status['out'], re.M):
+ return 'done'
+ if status['rc'] != 0 or re.search(r'^status: (error|degraded)', status['out'], re.M):
+ return 'error'
+ except (ValueError, KeyError):
+ return 'invalid-status'
+ return 'running-or-unknown'
+
+
+def follow_boot(aws, iid, directory, journal, sleep=time.sleep):
+ evidence = None
+ final = 'running-or-unknown'
+ deadline = time.monotonic() + 1200
+ def call(service, operation, **params):
+ remaining = deadline - time.monotonic()
+ require(remaining > 0, '20-minute collector deadline')
+ return aws(service, operation, _timeout=min(30, remaining), **params)
+ for attempt in range(120): # 20 minutes, including the final cloud-init line
+ result = call('ec2', 'get-console-output', InstanceId=iid, Latest=True)
+ atomic_json(directory / f'console-{attempt:03d}.json', result)
+ raw = result.get('Output', '')
+ decoded = decode_console(raw)
+ (directory / f'console-{attempt:03d}.log').write_text(decoded)
+ final = cloud_status(decoded)
+ journal.data['cloud_init_status'] = final
+ journal.save()
+ if evidence is None:
+ key = journal.data['scope']['evidence'] + '/evidence.tar.gz'
+ try:
+ head = call('s3api', 'head-object', Bucket=BUCKET, Key=key)
+ require(head['ContentLength'] <= 16 * 1024 * 1024, 'evidence tarball too large')
+ call('s3api', 'get-object', Bucket=BUCKET, Key=key, VersionId=head['VersionId'], _file=directory / 'evidence.tar.gz')
+ evidence = read_archive(directory / 'evidence.tar.gz')
+ atomic_json(directory / 'evidence.json', evidence)
+ except AWSError as ex:
+ if ex.code not in ('404', 'NoSuchKey', 'NotFound'):
+ raise
+ if evidence is not None and final != 'running-or-unknown':
+ return evidence, final
+ require(time.monotonic() < deadline, '20-minute collector deadline')
+ sleep(min(10, max(0, deadline - time.monotonic())))
+ raise ValueError('20-minute collector/final cloud-init deadline')
+
+
+def create_resources(aws, journal, launch, directory, pointer, kms, pubkey_file, sleep):
+ s = journal.data['scope']
+ role = s['role']
+ document = policy(s, kms, pointer)
+ atomic_json(directory / 'policy.json', document)
+ trust = {'Version': '2012-10-17', 'Statement': [dict(Effect='Allow', Principal={'Service': 'ec2.amazonaws.com'}, Action='sts:AssumeRole')]}
+ collision(aws, journal, 'role', role)
+ row = journal.intent('role', role)
+ response = journal.create(aws, row, 'iam', 'create-role', RoleName=role, AssumeRolePolicyDocument=json.dumps(trust), Tags=journal.tags())
+ journal.made(row, id=response['Role']['RoleId'], arn=response['Role']['Arn'])
+ row['policy_pending'] = True
+ journal.save()
+ aws('iam', 'put-role-policy', RoleName=role, PolicyName='witness', PolicyDocument=json.dumps(document))
+ require(aws('iam', 'get-role-policy', RoleName=role, PolicyName='witness')['PolicyDocument'] == document, 'policy readback differs')
+ collision(aws, journal, 'profile', role)
+ row = journal.intent('profile', role)
+ response = journal.create(aws, row, 'iam', 'create-instance-profile', InstanceProfileName=role, Tags=journal.tags())
+ journal.made(row, id=response['InstanceProfile']['InstanceProfileId'], arn=response['InstanceProfile']['Arn'])
+ row['attachment_pending'] = True
+ journal.save()
+ aws('iam', 'add-role-to-instance-profile', InstanceProfileName=role, RoleName=role)
+ collision(aws, journal, 'copy', s['key'])
+ row = journal.intent('copy', s['key'])
+ response = journal.create(aws, row, 's3api', 'copy-object', Bucket=BUCKET, Key=s['key'],
+ CopySource=f'{BUCKET}/{BOOT_KEY}?versionId={BOOT_VERSION}', MetadataDirective='REPLACE',
+ Metadata={'witness-owner': journal.data['owner']}, ChecksumAlgorithm='SHA256')
+ version = response['VersionId']
+ require(version and version != 'null', 'scratch copy missing version id')
+ journal.made(row, version=version)
+ head = aws('s3api', 'head-object', Bucket=BUCKET, Key=s['key'], VersionId=version, ChecksumMode='ENABLED')
+ require(head['VersionId'] == version and head.get('Metadata', {}).get('witness-owner') == journal.data['owner'], 'copy identity readback')
+ expected = hashlib.sha256(b'F4 offline bootstrap').hexdigest() if aws.dry else BOOT_SHA
+ require(head.get('ChecksumSHA256') == base64.b64encode(bytes.fromhex(expected)).decode(), 'copy checksum readback')
+ require(0 < head['ContentLength'] <= 256 * 1024 * 1024, 'copy size out of bounds')
+ copy_path = directory / 'bootstrap-copy'
+ try:
+ downloaded = aws('s3api', 'get-object', Bucket=BUCKET, Key=s['key'], VersionId=version, _file=copy_path)
+ require(downloaded['VersionId'] == version, 'download version readback')
+ with copy_path.open('rb') as f:
+ require(hashlib.file_digest(f, 'sha256').hexdigest() == expected, 'downloaded copy checksum')
+ finally:
+ copy_path.unlink(missing_ok=True)
+ atomic_json(directory / 'copy-readback.json', head)
+ values = seed(s, version, pubkey_file.read_text().strip())
+ for name, value in values.items():
+ collision(aws, journal, 'parameter', name)
+ row = journal.intent('parameter', name)
+ params = dict(Name=name, Value=value, Type='SecureString' if name.endswith('/CARLOS_SECRETS_KEY') else 'String',
+ Tags=journal.tags())
+ if params['Type'] == 'SecureString':
+ params['KeyId'] = 'alias/aws/ssm'
+ response = journal.create(aws, row, 'ssm', 'put-parameter', **params)
+ journal.made(row, version=response['Version'])
+ actual = aws('ssm', 'get-parameter', Name=name, WithDecryption=True)['Parameter']
+ require(actual['Value'] == value and actual['Version'] == response['Version'] and actual['Type'] == params['Type'], 'SSM readback: ' + name)
+ # Independently check the same nonrecursive path reader shape as hostenv.
+ for path in (s['shared'], s['prefix']):
+ response = aws('ssm', 'get-parameters-by-path', Path=path, Recursive=False, WithDecryption=True)
+ require(not response.get('NextToken'), 'incomplete SSM readback')
+ actual = {p['Name']: p['Value'] for p in response.get('Parameters', [])}
+ expected = {k: v for k, v in values.items() if k.rsplit('/', 1)[0] == path}
+ require(actual == expected, 'SSM path readback drift')
+ atomic_json(directory / 'ssm-readback.json', dict(names=sorted(values), matched=True))
+ sleep(15)
+ profile = aws('iam', 'get-instance-profile', InstanceProfileName=role)['InstanceProfile']
+ require(owned(profile.get('Tags', []), journal) and [r['RoleName'] for r in profile['Roles']] == [role], 'profile attachment readback')
+ floor_preflight(aws)
+ aws('s3api', 'get-object', Bucket=BUCKET, Key=POINTER_KEY, _file=directory / 'stable-prelaunch.json')
+ require(verify_pointer(directory / 'stable-prelaunch.json', pubkey_file) == pointer, 'pointer changed during setup')
+ collision(aws, journal, 'instance', role)
+ row = journal.intent('instance', role)
+ launch = json.loads(json.dumps(launch))
+ launch['ClientToken'] = 'f4-' + journal.data['owner']
+ for spec in launch['TagSpecifications']:
+ spec['Tags'] = [t for t in spec['Tags'] if t['Key'] not in {x['Key'] for x in journal.tags()}] + journal.tags()
+ atomic_json(directory / 'launch.json', launch)
+ raw_user_data = (directory / 'user-data.gz').read_bytes()
+ response = journal.create(aws, row, 'ec2', 'run-instances', _user_data=directory / 'user-data.gz', **launch) # exactly one call; never retry
+ require(len(response['Instances']) == 1, 'launch returned other than one instance')
+ iid = response['Instances'][0]['InstanceId']
+ journal.made(row, iid=iid, box_ref=box_ref(iid))
+ for attempt in range(30):
+ try:
+ readback = launch_readback(aws, iid, launch, raw_user_data)
+ break
+ except (ValueError, KeyError, AWSError):
+ if attempt == 29:
+ raise
+ sleep(2)
+ atomic_json(directory / 'instance-readback.json', readback)
+ journal.data['instance_readback'] = readback
+ journal.save()
+ return iid
+
+
+def write_evidence(directory, journal, rows, error=''):
+ esc = lambda v: str(v).replace('|', '\\|').replace('\n', ' ')[:900]
+ data = journal.data
+ status = 'DRY RUN: simulated AWS; live assertions NOT RUN.' if data['dry'] else 'Live witness; see individual assertions.'
+ body = '# P3b-1 F4 witness evidence\n\n' + status + '\n\n' + FLOOR_LABEL + '\n\n'
+ body += 'Run: `' + data['scope']['run'] + '`. Account: `' + ACCOUNT + '`. Region: `' + REGION + '`.\n\n'
+ body += 'Run status: `' + data.get('run_status', data['status']) + '`. Current status: `' + data['status'] + '`.\n\n'
+ body += 'Final cloud-init: `' + data.get('cloud_init_status', 'not observed') + '`.\n\n'
+ if error:
+ body += 'Failure: ' + esc(error) + '\n\n'
+ body += '| Assertion | Status | Evidence |\n|---|---|---|\n'
+ for name, ok, detail in rows:
+ body += f'| {esc(name)} | {"NOT RUN" if ok is None else "PASS" if ok else "FAIL"} | {esc(detail)} |\n'
+ body += '\n## Ownership and cleanup\n\n```json\n' + json.dumps(data, indent=2, sort_keys=True) + '\n```\n'
+ for title, file in [('Module substitutions', 'substitutions.diff'), ('Instance policy', 'policy.json'), ('Input readbacks', 'preflight.json')]:
+ path = directory / file
+ if path.exists():
+ body += '\n## ' + title + '\n\n```\n' + path.read_text() + '\n```\n'
+ consoles = sorted(directory.glob('console-*.log'))
+ if consoles:
+ body += '\n## Final console excerpt\n\n```text\n' + consoles[-1].read_text()[-7000:] + '\n```\n'
+ (directory / 'evidence.md').write_text(body)
+
+
+def lifecycle(aws, journal, launch, directory, pubkey_file, ledger, cleanup_only=False, sleep=time.sleep):
+ log_to(directory)
+ error, leaks = '', []
+ original_error = journal.data.get('error', '') if cleanup_only else ''
+ rows = [r for r in journal.data.get('assertions', []) if r[0] not in
+ ('target groups and control/edges/', 'cleanup verified')] if cleanup_only else []
+ old_handlers = {}
+ def interrupted(signum, frame):
+ raise KeyboardInterrupt('signal ' + str(signum))
+ for sig in SIGNALS:
+ old_handlers[sig] = signal.signal(sig, interrupted)
+ try:
+ identity = aws('sts', 'get-caller-identity')
+ require(identity['Account'] == ACCOUNT, 'wrong AWS account')
+ if cleanup_only:
+ require(journal.data.get('before'), 'journal has no original baseline')
+ journal.data['cleanup_before'] = snapshot(aws)
+ journal.save()
+ else:
+ before = snapshot(aws)
+ journal.data['before'] = before
+ journal.save()
+ require(not check_snapshot(before, before), 'initial non-interference checks failed')
+ s = journal.data['scope']
+ require(not aws('s3api', 'list-objects-v2', Bucket=BUCKET, Prefix=s['evidence'] + '/').get('Contents'), 'evidence prefix collision')
+ historical = aws('s3api', 'list-object-versions', Bucket=BUCKET, Prefix=s['evidence'] + '/')
+ require(not historical.get('Versions') and not historical.get('DeleteMarkers') and not historical.get('IsTruncated'), 'evidence history collision')
+ pointer, kms = input_preflight(aws, directory, pubkey_file)
+ # Check the whole namespace before spending a run, then recheck each
+ # object immediately before journaling and creating it.
+ for kind, name in [('role', s['role']), ('profile', s['role']), ('copy', s['key']), ('instance', s['role']),
+ *[('parameter', name) for name in seed(s, 'preflight', 'public')]]:
+ collision(aws, journal, kind, name)
+ reserve_budget(ledger, s['run'], journal.data['owner'])
+ journal.data['status'] = 'budget-reserved'
+ journal.save()
+ iid = create_resources(aws, journal, launch, directory, pointer, kms, pubkey_file, sleep)
+ evidence, final = follow_boot(aws, iid, directory, journal, sleep)
+ evidence['launch_readback'] = journal.data['instance_readback']
+ rows = assertions(evidence)
+ rows.append(('final cloud-init', final == 'done', final))
+ if aws.dry:
+ rows = [(name, None, 'simulation; ' + detail) for name, ok, detail in rows]
+ else:
+ require(all(ok for name, ok, detail in rows), 'witness assertion failures')
+ except BaseException as ex:
+ error = str(ex) or type(ex).__name__
+ finally:
+ # Cleanup itself is not interrupted by a repeated terminal signal.
+ for sig in SIGNALS:
+ signal.signal(sig, signal.SIG_IGN)
+ try:
+ # Identity must be known before ANY cleanup mutation. A wrong
+ # profile never licenses using ids from a different account.
+ identity_ok = False
+ try:
+ identity_ok = aws('sts', 'get-caller-identity')['Account'] == ACCOUNT
+ require(identity_ok, 'cleanup account mismatch')
+ leaks = cleanup(aws, journal, sleep)
+ except Exception as ex:
+ leaks.append('cleanup: ' + str(ex))
+ print('LEAKED', leaks[-1], file=sys.stderr)
+ for row in journal.data['resources']:
+ if row['state'] not in ('gone', 'rejected'):
+ label = resource_label(row, journal)
+ if label not in leaks:
+ leaks.append(label)
+ print('LEAKED', label, str(ex), file=sys.stderr)
+ finally:
+ after = snapshot(aws)
+ journal.data['after'] = after
+ ids = [iid for r in journal.data['resources'] if r['kind'] == 'instance'
+ for iid in r['ids'].get('recovered_iids', [r['ids'].get('iid')]) if iid]
+ problems = check_snapshot(journal.data.get('before', {}), after, ids)
+ if journal.data.get('cleanup_before'):
+ problems += check_snapshot(journal.data['before'], journal.data['cleanup_before'], ids)
+ journal.data['noninterference_errors'] = problems
+ rows.append(('target groups and control/edges/', not problems, '; '.join(problems) or 'unchanged; no witness object'))
+ rows.append(('cleanup verified', not leaks, ', '.join(leaks) or 'all journaled resources verified gone; evidence retained'))
+ if not rows or error:
+ present = {name for name, ok, detail in rows}
+ rows += [(name, None if aws.dry else False, 'not reached: ' + error)
+ for name, ok, detail in assertions({}) if name not in present]
+ if cleanup_only:
+ journal.data.setdefault('run_status', journal.data['status'])
+ journal.data.update(status='cleanup-failed' if error or leaks or problems else 'cleaned',
+ cleanup_error=error, leaked=leaks)
+ else:
+ status = 'failed' if error or leaks or problems else 'complete'
+ journal.data.update(status=status, run_status=status, error=error, leaked=leaks)
+ journal.data['assertions'] = rows
+ journal.save()
+ write_evidence(directory, journal, rows, error or original_error)
+ finally:
+ for sig, handler in old_handlers.items():
+ signal.signal(sig, handler)
+ require(not error and not leaks and not journal.data.get('noninterference_errors'), error or 'cleanup/non-interference failure')
+ return rows
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument('--run', default='dry-run')
+ ap.add_argument('--dry-run', action='store_true')
+ ap.add_argument('--execute', action='store_true')
+ ap.add_argument('--i-have-budget', action='store_true')
+ ap.add_argument('--cleanup-only', metavar='RUN')
+ ap.add_argument('--scratch', type=Path, default=SCRATCH)
+ ap.add_argument('--tofu', type=Path, default=SCRATCH / 'tofu/tofu')
+ ap.add_argument('--release-pubkey-file', type=Path)
+ ap.add_argument('--pointer-file', type=Path, default=SCRATCH / 'round2-stable.json')
+ args = ap.parse_args()
+ require(not (args.execute and args.dry_run), 'conflicting modes')
+ require(not args.i_have_budget or args.execute, '--i-have-budget requires --execute')
+ if args.execute:
+ require(args.i_have_budget, '--execute requires --i-have-budget')
+ require(not LIVE_BLOCKERS, 'live blockers: ' + '; '.join(LIVE_BLOCKERS))
+ require(not args.cleanup_only or not args.execute, 'cleanup-only cannot execute a new launch')
+ s = scope(args.cleanup_only or args.run)
+ os.umask(0o077)
+ args.scratch = args.scratch.resolve()
+ if args.execute or (args.cleanup_only and not args.dry_run):
+ require(args.scratch == SCRATCH, 'live witness requires fixed budget path: ' + str(BUDGET))
+ require(not BUDGET.is_symlink() and not BUDGET.with_suffix('.lock').is_symlink(), 'budget path is a symlink')
+ args.scratch.mkdir(parents=True, exist_ok=True)
+ dry = args.dry_run or (not args.execute and not args.cleanup_only)
+ directory = args.scratch / (('dry-witness-' if dry else 'witness-') + s['run'])
+ with exclusive(args.scratch / 'witness-budget.lock'):
+ if args.cleanup_only:
+ if dry and (args.scratch / ('witness-' + s['run'])).is_dir():
+ directory = args.scratch / ('witness-' + s['run'])
+ require(directory.is_dir(), 'run directory missing; no ownership established')
+ log_to(directory)
+ journal = Journal(directory / 'journal.json', dry=directory.name.startswith('dry-witness-'))
+ require(journal.data['scope'] == s, 'cleanup run mismatch')
+ if dry:
+ for service, operation, params in cleanup_preview(journal):
+ print('DRY CLEANUP AWS', service, operation, json.dumps(params, sort_keys=True))
+ return 0
+ require(not journal.data['dry'], 'simulated journal cannot authorize live cleanup')
+ lifecycle(AWS(), journal, None, directory, None, None, cleanup_only=True)
+ return 0
+ require(args.release_pubkey_file and args.release_pubkey_file.is_file(), '--release-pubkey-file is required')
+ args.release_pubkey_file = args.release_pubkey_file.resolve()
+ require(not directory.exists(), 'run directory exists; choose a fresh run id or cleanup-only')
+ directory.mkdir(mode=0o700)
+ log_to(directory)
+ journal = Journal(directory / 'journal.json', s, dry=dry)
+ module = directory / 'module'
+ def interrupted(signum, frame):
+ raise KeyboardInterrupt('signal ' + str(signum))
+ old_handlers = {sig: signal.signal(sig, interrupted) for sig in SIGNALS}
+ try:
+ script, lt = render(args.tofu, directory, s)
+ raw_user_data = user_data(script, collector(s), observer(s))
+ write_user_data(directory, raw_user_data)
+ launch = launch_input(lt, s)
+ (directory / 'collector.py').write_bytes(collector(s))
+ (directory / 'observer.py').write_bytes(observer(s))
+ print('MIME encoded bytes:', len(base64.b64encode(raw_user_data)), '/ 16384; raw bytes:', len(raw_user_data), '; part 1 sha256:', hashlib.sha256(script).hexdigest())
+ if dry:
+ from region_group_witness_fake import FakeAWS
+ aws = FakeAWS(sys.modules[__name__], args.pointer_file.read_bytes(), directory)
+ lifecycle(aws, journal, launch, directory, args.release_pubkey_file, directory / 'simulated-budget.json', sleep=lambda _: None)
+ else:
+ lifecycle(AWS(), journal, launch, directory, args.release_pubkey_file, BUDGET)
+ except BaseException as ex:
+ if journal.data['status'] == 'preflight':
+ write_evidence(directory, journal, [(n, None, 'not reached') for n, ok, d in assertions({})], str(ex))
+ raise
+ finally:
+ for sig in SIGNALS:
+ signal.signal(sig, signal.SIG_IGN)
+ try:
+ if module.exists():
+ shutil.rmtree(module)
+ finally:
+ for sig, handler in old_handlers.items():
+ signal.signal(sig, handler)
+ print(('DRY RUN' if dry else 'WITNESS') + ' complete; ' + FLOOR_LABEL)
+ return 0
+
+
+if __name__ == '__main__':
+ try:
+ sys.exit(main())
+ except (ValueError, RuntimeError, OSError, subprocess.SubprocessError, KeyboardInterrupt) as error:
+ print('FAIL', error, file=sys.stderr)
+ sys.exit(1)
diff --git a/scripts/region_group_boot_umask_test.py b/scripts/region_group_boot_umask_test.py
new file mode 100644
index 000000000..beec53984
--- /dev/null
+++ b/scripts/region_group_boot_umask_test.py
@@ -0,0 +1,120 @@
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import textwrap
+import unittest
+from pathlib import Path
+
+TEMPLATE = Path(__file__).resolve().parent.parent / 'infra/modules/region-host/group-init.sh.tftpl'
+STAGING = '/var/lib/carlos-group-boot'
+HOSTENV = '( umask 022; exec ' + STAGING + '/bootstrap system host-env write --group --deployment "$CARLOS_DEPLOYMENT" --region "$CARLOS_REGION" --aws-region "$AWS_REGION" --install )'
+HAIRPIN = STAGING + '/bootstrap instance-control --group-hairpin-install'
+IDENTITY = "subprocess.check_call([work + 'bootstrap', 'instance-control', '--group-hairpin-verify-identity'], timeout=10)"
+DROPIN = '/etc/systemd/system/carlos-instance-control.service.d'
+
+STUB = textwrap.dedent('''\
+ #!/bin/sh
+ echo "$(umask) $*" >> "$STUB_LOG"
+ mkdir "$STUB_DIR/implicit"
+ : > "$STUB_DIR/implicit/file"
+ exit "${STUB_EXIT:-0}"
+''')
+
+
+class UmaskTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.lines = TEMPLATE.read_text().split('\n')
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR'))
+ self.addCleanup(self.tmp.cleanup)
+ self.dir = Path(self.tmp.name)
+ self.stub = self.dir / 'stub'
+ self.stub.write_text(STUB)
+ self.stub.chmod(0o700)
+ self.log = self.dir / 'log'
+ self.env = dict(os.environ, STUB_LOG=str(self.log), CARLOS_DEPLOYMENT='d', CARLOS_REGION='r', AWS_REGION='a')
+
+ def run_sh(self, line, exit_code):
+ line = line.replace(STAGING + '/bootstrap', str(self.stub))
+ self.assertIn(str(self.stub), line)
+ work = self.dir / ('w%d' % exit_code)
+ work.mkdir()
+ env = dict(self.env, STUB_DIR=str(work), STUB_EXIT=str(exit_code))
+ out = subprocess.run(['sh', '-c', 'umask 077\n' + line + '\nstatus=$?\necho "parent $(umask) $status"'], env=env, capture_output=True, text=True, check=True)
+ return work, out.stdout.split()
+
+ def child_umask(self):
+ return self.log.read_text().split()[0]
+
+ def test_template_has_exact_lines(self):
+ for line in (HOSTENV, HAIRPIN, IDENTITY):
+ self.assertEqual(self.lines.count(line), 1, line)
+ self.assertEqual(self.lines[2], 'umask 077')
+ self.assertEqual(sum('umask' in line for line in self.lines), 2)
+ verify = 'python3 -I ' + STAGING + '/carlos_group_boot_verify.py'
+ self.assertEqual(self.lines[self.lines.index(HOSTENV) - 1], verify)
+
+ def test_hostenv_child_gets_022_and_parent_stays_077(self):
+ for code in (0, 3):
+ with self.subTest(exit=code):
+ self.log.unlink(missing_ok=True)
+ work, out = self.run_sh(HOSTENV, code)
+ self.assertEqual(self.child_umask(), '0022')
+ self.assertEqual(out, ['parent', '0077', str(code)])
+ self.assertEqual(stat.S_IMODE((work / 'implicit').stat().st_mode), 0o755)
+ self.assertEqual(stat.S_IMODE((work / 'implicit/file').stat().st_mode), 0o644)
+
+ def test_hairpin_install_child_keeps_077(self):
+ for code in (0, 3):
+ with self.subTest(exit=code):
+ self.log.unlink(missing_ok=True)
+ work, out = self.run_sh(HAIRPIN, code)
+ self.assertEqual(self.child_umask(), '0077')
+ self.assertEqual(out, ['parent', '0077', str(code)])
+ self.assertEqual(stat.S_IMODE((work / 'implicit').stat().st_mode), 0o700)
+ self.assertEqual(stat.S_IMODE((work / 'implicit/file').stat().st_mode), 0o600)
+
+ def test_python_identity_child_keeps_077(self):
+ for code in (0, 3):
+ with self.subTest(exit=code):
+ self.log.unlink(missing_ok=True)
+ work = self.dir / ('p%d' % code)
+ work.mkdir()
+ env = dict(self.env, STUB_DIR=str(work), STUB_EXIT=str(code))
+ src = 'import os, subprocess\nos.umask(0o077)\nwork = %r\ntry:\n %s\nexcept subprocess.CalledProcessError:\n pass\nprint(oct(os.umask(0o077)))\n' % (str(self.dir) + '/', IDENTITY)
+ src = src.replace("work + 'bootstrap'", repr(str(self.stub)))
+ out = subprocess.run([sys.executable, '-I', '-c', src], env=env, capture_output=True, text=True, check=True)
+ self.assertEqual(self.child_umask(), '0077')
+ self.assertEqual(out.stdout.strip(), '0o77')
+ self.assertEqual(stat.S_IMODE((work / 'implicit').stat().st_mode), 0o700)
+
+ def test_template_writes_stay_explicit_modes(self):
+ start = self.lines.index('def write(path, body, mode=0o644):')
+ helper = '\n'.join(self.lines[start:start + 7])
+ self.assertIn('os.fchmod(fd, mode)', helper)
+ for mode in (0o600, 0o644):
+ path = self.dir / ('f%o' % mode)
+ code = 'import os\nos.umask(0o077)\n' + helper + '\nwrite(%r, b"x", %d)\n' % (str(path), mode)
+ subprocess.run([sys.executable, '-I', '-c', code], check=True)
+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), mode)
+ self.assertIn("write(work + 'bootstrap.sha256', sha.encode(), 0o600)", self.lines)
+
+ def test_dropin_directory_chmodded_after_mkdir(self):
+ i = self.lines.index("os.mkdir('%s', 0o755)" % DROPIN)
+ self.assertEqual(self.lines[i + 1], "os.chmod('%s', 0o755)" % DROPIN)
+ root = self.dir / 'd'
+ code = 'import os\nos.umask(0o077)\nos.mkdir(%r, 0o755)\n' % str(root)
+ subprocess.run([sys.executable, '-I', '-c', code], check=True)
+ self.assertEqual(stat.S_IMODE(root.stat().st_mode), 0o700)
+ code += 'os.chmod(%r, 0o755)\n' % str(root)
+ root.rmdir()
+ subprocess.run([sys.executable, '-I', '-c', code], check=True)
+ self.assertEqual(stat.S_IMODE(root.stat().st_mode), 0o755)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/region_group_boot_witness_test.py b/scripts/region_group_boot_witness_test.py
new file mode 100644
index 000000000..914b2fbc5
--- /dev/null
+++ b/scripts/region_group_boot_witness_test.py
@@ -0,0 +1,785 @@
+import base64
+import copy
+import email.policy
+from email.parser import BytesParser
+import gzip
+import importlib.util
+import json
+from pathlib import Path
+import unittest
+import tempfile
+import io
+import sys
+from contextlib import redirect_stdout, redirect_stderr
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('witness', Path(__file__).with_name('region-group-boot-witness.py'))
+w = importlib.util.module_from_spec(spec)
+sys.modules[spec.name] = w
+spec.loader.exec_module(w)
+
+
+class WitnessTests(unittest.TestCase):
+ def setUp(self):
+ self.s = w.scope('test-01')
+
+ def test_scope_refuses_escape_and_overlong(self):
+ for bad in ('../ie', '', 'A', 'x/y', 'x'*33, 'x;id', 'a\n'):
+ with self.subTest(bad=bad), self.assertRaises(ValueError): w.scope(bad)
+ self.assertNotIn('/carlos/dev', self.s['prefix'])
+ self.assertNotIn('bootstrap/dev', self.s['key'])
+
+ def test_exact_substitutions_and_tamper_refusal(self):
+ config = w.dev_config()
+ dev = w.plain_render(config)
+ witness = w.plain_render(w.witness_config(config,self.s))
+ diff = w.check_diff(dev,witness,self.s)
+ self.assertIn("+CARLOS_POOLS='witness'",diff)
+ self.assertEqual(sum(line.startswith('+CARLOS_') for line in diff.splitlines()),5)
+ for changed in (witness+b'echo bypass\n',witness.replace(b'Restart=no',b'Restart=always')):
+ with self.assertRaises(ValueError): w.check_diff(dev,changed,self.s)
+
+ def test_mime_first_part_byte_identical(self):
+ source=b'#!/bin/sh\necho byte-identical\n'
+ encoded=w.user_data(source,w.collector(self.s))
+ parts=list(BytesParser(policy=email.policy.default).parsebytes(gzip.decompress(encoded)).iter_parts())
+ self.assertEqual(parts[0].get_payload(decode=True),source)
+ self.assertEqual(parts[1].get_payload(decode=True),w.collector(self.s))
+ self.assertEqual(parts[0].get_content_type(),'text/x-shellscript')
+ compile(w.collector(self.s),'collector','exec')
+ with self.assertRaises(ValueError):w.user_data(bytes(range(256))*100 + __import__('random').Random(5).randbytes(30000),b'x')
+
+ def test_user_data_file_is_raw_private_and_both_sizes_are_bounded(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ directory=Path(tmp)
+ raw=w.user_data(b'#!/bin/sh\ntrue\n',w.collector(self.s),w.observer(self.s))
+ path=w.write_user_data(directory,raw)
+ self.assertEqual(path.read_bytes(),raw)
+ self.assertEqual(path.stat().st_mode & 0o777,0o600)
+ self.assertTrue(gzip.decompress(raw).startswith(b'MIME-Version'))
+ self.assertLessEqual(len(raw),16384)
+ self.assertLessEqual(len(base64.b64encode(raw)),16384)
+ path.unlink()
+ with self.assertRaisesRegex(ValueError,'size'):
+ w.write_user_data(directory,b'x'*12289) # raw fits; encoded does not
+ self.assertFalse(path.exists())
+
+ def test_observer_starts_independent_service_before_boot_continues(self):
+ import os
+ with tempfile.TemporaryDirectory() as tmp:
+ root=Path(tmp)
+ real_path=Path
+ def paths(value):
+ return root if str(value).startswith('/var/lib/carlos-witness-') else real_path(value)
+ def started(*args,**kwargs):
+ (root/'observer-ready').touch()
+ with patch('pathlib.Path',side_effect=paths),patch('subprocess.run',side_effect=started) as run, \
+ patch('os.umask'),patch.object(sys,'argv',['observer']),self.assertRaises(SystemExit) as end:
+ exec(compile(w.observer(self.s),'observer','exec'),{'__file__':str(root/'boothook')})
+ self.assertEqual(end.exception.code,0)
+ args=run.call_args.args[0]
+ self.assertEqual(args[:3],['systemd-run','--unit','carlos-f4-observer'])
+ self.assertIn('--property=DefaultDependencies=no',args)
+ self.assertIn('--property=Type=exec',args)
+ self.assertIn('--property=RuntimeMaxSec=1200',args)
+ self.assertEqual(args[-1],'--worker')
+ self.assertNotIn(b'os.fork',w.observer(self.s))
+ self.assertNotIn(b'time.time',w.observer(self.s))
+
+ def test_policy_has_no_extra_authority(self):
+ pointer = {'component':'router', 'channel':'stable', 'current': {'version':'v0.34.2',
+ 'artifacts':{'linux-arm64': {'key':'bootstrap/router/v0.34.2/carlos-linux-arm64', 'sha256':w.BOOT_SHA}}}}
+ kms = 'arn:aws:kms:eu-west-1:640012953448:key/test'
+ actual = w.policy(self.s, kms, pointer)
+ param = f'arn:aws:ssm:{w.REGION}:{w.ACCOUNT}:parameter'
+ expected = {'Version':'2012-10-17', 'Statement': [
+ {'Effect':'Allow', 'Action':['ssm:GetParameter','ssm:GetParameters'],
+ 'Resource':[param+k for k in w.seed(self.s, 'v', 'pub')]},
+ {'Effect':'Allow','Action':'ssm:GetParametersByPath',
+ 'Resource':[param+self.s['shared'],param+self.s['prefix']],
+ 'Condition':{'Bool':{'ssm:Recursive':'false'}}},
+ {'Effect':'Allow','Action':'kms:Decrypt','Resource':kms,
+ 'Condition':{'StringEquals':{'kms:ViaService':'ssm.eu-west-1.amazonaws.com'},
+ 'StringLike':{'kms:EncryptionContext:PARAMETER_ARN':param+self.s['prefix']+'/CARLOS_SECRETS_KEY'}}},
+ {'Effect':'Allow','Action':'s3:GetObject',
+ 'Resource':[f'arn:aws:s3:::{w.BUCKET}/'+k for k in [self.s['key'],
+ 'control/system/router/stable.json','bootstrap/router/v0.34.2/carlos-linux-arm64',
+ 'control/moves-protocol.json','control/moves-protocol-auth.json']]},
+ {'Effect':'Allow','Action':'s3:GetObjectVersion','Resource':f'arn:aws:s3:::{w.BUCKET}/'+self.s['key']},
+ {'Effect':'Allow','Action':['s3:ListBucket','s3:GetBucketLocation'],'Resource':f'arn:aws:s3:::{w.BUCKET}'},
+ {'Effect':'Allow','Action':'s3:PutObject','Resource':f'arn:aws:s3:::{w.BUCKET}/'+self.s['evidence']+'/*'},
+ ]}
+ self.assertEqual(actual, expected)
+ self.assertEqual(w.LIVE_BLOCKERS, ())
+ for mutate in ({'version':'v0.35.0'}, {'artifacts':{'linux-arm64':{'key':'unapproved', 'sha256':w.BOOT_SHA}}}):
+ bad=copy.deepcopy(pointer);bad['current'].update(mutate)
+ with self.assertRaises(ValueError):w.policy(self.s,kms,bad)
+
+ def test_seed_random_and_scratch_only(self):
+ a,b=w.seed(self.s,'version','real-public'),w.seed(self.s,'version','real-public')
+ self.assertEqual(len(a),20)
+ self.assertTrue(all(k.startswith(self.s['prefix']+'/') for k in a))
+ self.assertNotEqual(a[self.s['prefix']+'/CARLOS_SECRETS_KEY'],b[self.s['prefix']+'/CARLOS_SECRETS_KEY'])
+ self.assertEqual(json.loads(a[self.s['prefix']+'/boot/bootstrap-object'])['floor'],'absent-expected')
+ self.assertEqual(a[self.s['prefix']+'/CARLOS_HA_FIXED_BOX_IDENTITIES'],'{}')
+
+ def test_mock_computed_attributes_cannot_reach_launch(self):
+ values={'metadata_options':[{'http_tokens':'required','http_protocol_ipv6':'random-mock'}],
+ 'block_device_mappings':[{'ebs':[{'encrypted':'true','throughput':0}]}], 'arn':'random-mock'}
+ expr={'metadata_options':[{'http_tokens':{'constant_value':'required'}}],
+ 'block_device_mappings':[{'ebs':[{'encrypted':{'constant_value':True}}]}]}
+ actual=w.configured_values(values,expr)
+ self.assertEqual(actual,{'metadata_options':[{'http_tokens':'required'}],
+ 'block_device_mappings':[{'ebs':[{'encrypted':True}]}]})
+
+ def test_launch_uses_module_fields_and_rejects_new_authority(self):
+ lt=dict(image_id=w.AMI,instance_type='t4g.micro',metadata_options=[dict(http_tokens='required',http_endpoint='enabled',http_put_response_hop_limit=1)],
+ block_device_mappings=[dict(device_name='/dev/xvda',ebs=[dict(volume_size=20,volume_type='gp3',encrypted=True,delete_on_termination=True)])],
+ network_interfaces=[dict(associate_public_ip_address=True,delete_on_termination=True,security_groups=['original'])],tags={})
+ result=w.launch_input(lt,self.s)
+ self.assertEqual(result['BlockDeviceMappings'][0]['Ebs']['VolumeSize'],20)
+ self.assertEqual(result['NetworkInterfaces'][0]['Groups'],[w.SG])
+ self.assertEqual(result['MinCount'],result['MaxCount']);self.assertEqual(result['MaxCount'],1)
+ self.assertNotIn('Monitoring',result)
+ for change in ({'image_id':'wrong'},{'key_name':'root-login'},{'disable_api_termination':True}):
+ with self.assertRaises(ValueError):w.launch_input(dict(lt,**change),self.s)
+ bad=copy.deepcopy(lt);bad['block_device_mappings'][0]['ebs'][0]['encrypted']='false'
+ with self.assertRaises(ValueError):w.launch_input(bad,self.s)
+
+ def test_empty_evidence_cannot_pass(self):
+ rows=w.assertions({})
+ self.assertGreaterEqual(len(rows),16)
+ self.assertFalse(any(row[1] for row in rows))
+
+ def test_observer_mime_and_source(self):
+ raw=w.observer(self.s)
+ compile(raw.split(b'\n',1)[1], 'observer','exec')
+ encoded=w.user_data(b'#!/bin/sh\ntrue\n',w.collector(self.s),raw)
+ parts=list(BytesParser(policy=email.policy.default).parsebytes(gzip.decompress(encoded)).iter_parts())
+ self.assertEqual(len(parts),3)
+ self.assertEqual(parts[2].get_content_type(),'text/cloud-boothook')
+ self.assertEqual(parts[2].get_payload(decode=True),raw)
+
+ def test_box_reference_matches_template(self):
+ import hashlib
+ iid='i-0123456789abcdef0'
+ self.assertEqual(w.box_ref(iid),'g-'+hashlib.sha256(('carlos-box-ref-v1|640012953448|'+iid).encode()).hexdigest()[:20])
+
+ def test_budget_persists_and_third_or_reused_run_refused(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path=Path(tmp)/'budget.json'
+ w.reserve_budget(path,'one','owner1')
+ with self.assertRaises(ValueError):w.reserve_budget(path,'one','newowner')
+ w.reserve_budget(path,'two','owner2')
+ with self.assertRaises(ValueError):w.reserve_budget(path,'three','owner3')
+ self.assertEqual(len(json.loads(path.read_text())['runs']),2)
+ self.assertEqual(path.stat().st_mode & 0o777,0o600)
+
+ def test_ledger_lock_refuses_concurrent_executor(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path=Path(tmp)/'lock'
+ with w.exclusive(path):
+ with self.assertRaises(ValueError):
+ with w.exclusive(path):pass
+
+ def test_f4w1_ledger_allows_one_new_run_and_preserves_first_reservation(self):
+ recorded = json.loads((Path(__file__).parent / 'testdata/region-group-f4w1.json').read_text())['budget']
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / 'budget.json'
+ w.atomic_json(path, recorded)
+ with self.assertRaisesRegex(ValueError, 'run id already spent'):
+ w.reserve_budget(path, 'f4w1', 'new-owner')
+ w.reserve_budget(path, 'f4w2', 'second-owner')
+ updated = json.loads(path.read_text())
+ self.assertEqual(updated['runs'][:1], recorded['runs'])
+ self.assertEqual(updated['runs'][1]['run'], 'f4w2')
+ with self.assertRaisesRegex(ValueError, 'two-run witness budget exhausted'):
+ w.reserve_budget(path, 'f4w3', 'third-owner')
+ for key in ('deployment', 'prefix', 'shared', 'key', 'evidence', 'role'):
+ self.assertNotEqual(w.scope('f4w1')[key], w.scope('f4w2')[key])
+
+ def test_journal_is_durable_before_reply_and_cleanup_scope_is_closed(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ p=Path(tmp)/'journal.json'
+ j=w.Journal(p,self.s,dry=True)
+ row=j.intent('role',self.s['role'])
+ recovered=w.Journal(p,dry=True)
+ self.assertEqual(recovered.data['resources'][0]['state'],'pending')
+ self.assertEqual(w.cleanup_plan(recovered)[0]['name'],self.s['role'])
+ with self.assertRaises(ValueError):w.Journal(p,dry=False)
+ recovered.data['resources'][0]['name']='real-dev-role'
+ with self.assertRaises(ValueError):w.cleanup_plan(recovered)
+ j.made(row,id='role-id')
+ self.assertEqual(w.Journal(p,dry=True).data['resources'][0]['ids']['id'],'role-id')
+
+ def test_console_decoding_and_final_cloud_status(self):
+ marker=lambda rc,status:'WITNESS final-cloud-init '+base64.b64encode(json.dumps({'rc':rc,'out':'status: '+status+'\n'}).encode()).decode()
+ done='WITNESS collector-done\nCloud-init v. 25.1.4 finished at Wed, 4 Nov. Up 12 seconds'
+ self.assertNotEqual(w.cloud_status(done),'done')
+ self.assertEqual(w.cloud_status(done+'\n'+marker(0,'done')),'done')
+ self.assertEqual(w.cloud_status(done+'\n'+marker(1,'error')),'error')
+ self.assertEqual(w.cloud_status(done+'\n'+marker(2,'done')),'error')
+ self.assertEqual(w.decode_console(done),done)
+ self.assertEqual(w.decode_console('dGVzdA=='),'dGVzdA==')
+
+
+
+class LifecycleTests(unittest.TestCase):
+ def setUp(self):
+ from region_group_witness_fake import FakeAWS
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.directory = Path(self.tmp.name)
+ self.s = w.scope('mock-run')
+ self.j = w.Journal(self.directory/'journal.json', self.s, dry=True)
+ self.aws = FakeAWS(w, b'signed-pointer', self.directory)
+ self.pubkey = self.directory/'pubkey'
+ self.pubkey.write_text('public')
+ self.pointer = {'component':'router', 'channel':'stable', 'current':{'version':'v0.34.2',
+ 'artifacts':{'linux-arm64':{'key':'bootstrap/router/v0.34.2/carlos-linux-arm64','sha256':w.BOOT_SHA}}}}
+ self.launch = dict(ImageId=w.AMI,InstanceType='t4g.micro',MinCount=1,MaxCount=1,ClientToken=self.s['role'],
+ IamInstanceProfile={'Name':self.s['role']},
+ MetadataOptions={'HttpEndpoint':'enabled','HttpTokens':'required','HttpPutResponseHopLimit':1},
+ BlockDeviceMappings=[{'DeviceName':'/dev/xvda','Ebs':{'VolumeSize':20,'VolumeType':'gp3','Encrypted':True,'DeleteOnTermination':True}}],
+ NetworkInterfaces=[{'DeviceIndex':0,'SubnetId':w.SUBNET,'Groups':[w.SG],'AssociatePublicIpAddress':True,'DeleteOnTermination':True}],
+ TagSpecifications=[{'ResourceType':kind,'Tags':[{'Key':'Name','Value':self.s['role']}]} for kind in ('instance','volume')])
+ self.user_data=w.user_data(b'#!/bin/sh\ntrue\n',w.collector(self.s),w.observer(self.s))
+ w.write_user_data(self.directory,self.user_data)
+ self.output=io.StringIO()
+ self.stack=__import__('contextlib').ExitStack()
+ self.addCleanup(self.stack.close)
+ self.stack.enter_context(redirect_stdout(self.output))
+ self.stack.enter_context(redirect_stderr(self.output))
+ self.stack.enter_context(patch.object(w,'verify_pointer',return_value=self.pointer))
+ self.stack.enter_context(patch.object(w.subprocess,'run',side_effect=AssertionError('network/subprocess forbidden in mock test')))
+
+ def run_lifecycle(self, cleanup_only=False):
+ return w.lifecycle(self.aws,self.j,self.launch,self.directory,self.pubkey,self.directory/'budget.json',
+ cleanup_only=cleanup_only,sleep=lambda _:None)
+
+ def assert_gone(self):
+ self.assertFalse(self.j.data.get('leaked'),self.output.getvalue()[-2000:])
+ self.assertFalse(self.aws.roles)
+ self.assertFalse(self.aws.profiles)
+ self.assertFalse(self.aws.parameters)
+ self.assertFalse(self.aws.objects.get(self.s['key']))
+ self.assertTrue(all(i['State']['Name']=='terminated' for i in self.aws.instances.values()))
+ self.assertTrue(all(r['state']=='gone' for r in self.j.data['resources']))
+
+ def test_happy_dry_lifecycle_persists_console_and_retains_only_evidence(self):
+ rows=self.run_lifecycle()
+ self.assert_gone()
+ self.assertEqual(self.j.data['status'],'complete')
+ self.assertEqual(sum(op=='run-instances' for _,op,_ in self.aws.calls),1)
+ self.assertIn(self.s['evidence']+'/evidence.tar.gz',self.aws.objects)
+ self.assertTrue((self.directory/'console-000.log').exists())
+ self.assertIn('final-cloud-init',(self.directory/'console-001.log').read_text())
+ self.assertEqual(self.j.data['cloud_init_status'],'done')
+ self.assertTrue(all(ok is None for name,ok,d in rows if name.startswith(('W','P'))))
+ self.assertIn(w.FLOOR_LABEL,(self.directory/'evidence.md').read_text())
+ self.assertIn('NOT RUN',(self.directory/'evidence.md').read_text())
+
+ def test_botocore_encodes_once_and_double_encoded_readback_fails(self):
+ original=self.aws._ec2_run_instances
+ def double_encoded(params,file):
+ params=dict(params,UserData=base64.b64encode(params['UserData']))
+ return original(params,file)
+ with patch.object(self.aws,'_ec2_run_instances',side_effect=double_encoded):
+ with self.assertRaisesRegex(ValueError,'user data readback drift'):self.run_lifecycle()
+ self.assert_gone()
+ self.assertNotIn('UserData',json.loads((self.directory/'launch.json').read_text()))
+ self.assertEqual(next(iter(self.aws.instances.values()))['UserData'],
+ base64.b64encode(base64.b64encode(self.user_data)).decode())
+
+ def test_closed_stdout_and_stderr_after_launch_cannot_skip_cleanup(self):
+ closed=io.StringIO()
+ original=self.aws._ec2_run_instances
+ def launch(params,file):
+ result=original(params,file)
+ closed.close()
+ return result
+ with redirect_stdout(closed),redirect_stderr(closed),patch.object(self.aws,'_ec2_run_instances',side_effect=launch):
+ self.run_lifecycle()
+ self.assert_gone()
+ log=(self.directory/'witness.log').read_text()
+ self.assertIn('terminate-instances',log)
+ self.assertIn('delete-role',log)
+ self.assertEqual((self.directory/'witness.log').stat().st_mode & 0o777,0o600)
+
+ def test_broken_pipe_midrun_cannot_skip_cleanup(self):
+ class Pipe:
+ def write(self,*args):raise BrokenPipeError('pipe closed')
+ def flush(self):raise OSError('pipe closed')
+ original=self.aws._ec2_run_instances
+ def launch(params,file):
+ result=original(params,file)
+ sys.stdout=Pipe()
+ return result
+ with redirect_stdout(self.output),patch.object(self.aws,'_ec2_run_instances',side_effect=launch):
+ self.run_lifecycle()
+ self.assert_gone()
+
+ def test_cleanup_wide_sts_failure_lists_every_unconfirmed_resource(self):
+ original=w.follow_boot
+ def expired(*args,**kwargs):
+ result=original(*args,**kwargs)
+ self.aws.fail_before[('sts','get-caller-identity')]=w.AWSError('sts','get-caller-identity','ExpiredToken')
+ return result
+ with patch.object(w,'follow_boot',side_effect=expired):
+ with self.assertRaises(ValueError):self.run_lifecycle()
+ for row in self.j.data['resources']:
+ label=w.resource_label(row,self.j)
+ self.assertIn(label,self.j.data['leaked'])
+ self.assertIn('LEAKED '+label,self.output.getvalue())
+ self.assertIn('LEAKED '+label,(self.directory/'witness.log').read_text())
+ self.assertFalse(any(op.startswith(('delete','terminate')) for _,op,_ in self.aws.calls))
+ self.run_lifecycle(cleanup_only=True)
+ self.assert_gone()
+
+ def test_ssm_validation_rejected_only_after_confirmed_absence(self):
+ name=next(iter(w.seed(self.s,'v','pub')))
+ row=self.j.intent('parameter',name)
+ params=dict(Name=name,Value='value',Type='String',Tags=self.j.tags())
+ self.aws.fail_before[('ssm','put-parameter')]=w.AWSError('ssm','put-parameter','ValidationException')
+ with self.assertRaises(w.AWSError):self.j.create(self.aws,row,'ssm','put-parameter',**params)
+ self.assertEqual(row['state'],'rejected')
+ for exists in (False,True):
+ row['state']='pending'
+ self.aws.fail_before[('ssm','put-parameter')]=w.AWSError('ssm','put-parameter','ValidationException')
+ if exists:
+ self.aws._ssm_put_parameter(params,None)
+ else:
+ self.aws.fail_before[('ssm','get-parameter')]=w.AWSError('ssm','get-parameter','ExpiredToken')
+ with self.assertRaises(w.AWSError):self.j.create(self.aws,row,'ssm','put-parameter',**params)
+ self.assertEqual(row['state'],'pending')
+ with self.assertRaisesRegex(w.AWSError,'ValidationException'):
+ self.aws._ssm_put_parameter(dict(params,Overwrite=False),None)
+
+ def test_tagged_parameter_creates_omit_overwrite(self):
+ self.run_lifecycle()
+ calls=[params for _,op,params in self.aws.calls if op=='put-parameter']
+ self.assertEqual(len(calls),20)
+ self.assertTrue(all('Tags' in p and 'Overwrite' not in p for p in calls))
+
+ def test_every_create_intent_precedes_api_and_lost_reply_cleanup_recovers(self):
+ cases=[('iam','create-role'),('iam','create-instance-profile'),('s3api','copy-object'),
+ ('ssm','put-parameter'),('ec2','run-instances')]
+ for service,op in cases:
+ with self.subTest(op=op):
+ # Each fixture gets its own ledger, journal and namespace.
+ other=LifecycleTests(methodName='test_happy_dry_lifecycle_persists_console_and_retains_only_evidence')
+ other.setUp()
+ try:
+ def injected():
+ pending=json.loads(other.j.path.read_text())['resources'][-1]
+ self.assertEqual(pending['state'],'pending')
+ return RuntimeError('reply lost')
+ # The exception value is set before the call; examine the
+ # durable journal inside the adapter's completed handler.
+ method='_'+service+'_'+op.replace('-','_')
+ original=getattr(other.aws,method)
+ def handler(params,file):
+ result=original(params,file)
+ raise injected()
+ with patch.object(other.aws,method,side_effect=handler):
+ with self.assertRaises(ValueError):other.run_lifecycle()
+ other.assert_gone()
+ self.assertEqual(other.j.data['status'],'failed')
+ self.assertFalse(other.j.data['noninterference_errors'])
+ self.assertIn('reply lost',(other.directory/'evidence.md').read_text())
+ finally:other.doCleanups()
+
+ def test_signal_after_launch_runs_cleanup_and_restores_handlers(self):
+ for signum in w.SIGNALS:
+ other=LifecycleTests(methodName='test_happy_dry_lifecycle_persists_console_and_retains_only_evidence')
+ other.setUp()
+ try:
+ before=w.signal.getsignal(signum)
+ original=other.aws._ec2_run_instances
+ def handler(params,file):
+ result=original(params,file)
+ w.signal.getsignal(signum)(signum,None)
+ return result
+ with patch.object(other.aws,'_ec2_run_instances',side_effect=handler):
+ with self.assertRaisesRegex(ValueError,'signal'):other.run_lifecycle()
+ other.assert_gone()
+ self.assertEqual(w.signal.getsignal(signum),before)
+ finally:other.doCleanups()
+
+ def test_floor_access_denied_and_existing_floor_refuse_before_budget(self):
+ self.aws.fail_before[('s3api','head-object')]=w.AWSError('s3api','head-object','AccessDenied')
+ with self.assertRaisesRegex(ValueError,'AccessDenied'):self.run_lifecycle()
+ self.assertFalse((self.directory/'budget.json').exists())
+ self.assertFalse(any(op.startswith(('create','put','run','copy','delete','terminate')) for _,op,_ in self.aws.calls))
+ self.assertIn('after',self.j.data)
+
+ def test_collision_never_deletes_foreign_role(self):
+ self.aws('iam','create-role',RoleName=self.s['role'],AssumeRolePolicyDocument='{}',Tags=[{'Key':'witness_owner','Value':'someone-else'}])
+ self.aws.calls.clear()
+ with self.assertRaisesRegex(ValueError,'role collision'):self.run_lifecycle()
+ self.assertTrue(self.aws.roles)
+ self.assertFalse(self.j.data['resources'])
+ self.assertFalse(any(op.startswith('delete') for _,op,_ in self.aws.calls))
+
+ def test_leaked_resource_nonzero_then_cleanup_only_recovers(self):
+ original=self.aws._iam_delete_role
+ with patch.object(self.aws,'_iam_delete_role',side_effect=RuntimeError('IAM offline')):
+ with self.assertRaises(ValueError):self.run_lifecycle()
+ self.assertIn('LEAKED',self.output.getvalue())
+ self.assertEqual(self.j.data['leaked'],[f'arn:aws:iam::{w.ACCOUNT}:role/'+self.s['role']])
+ ledger=(self.directory/'budget.json').read_bytes()
+ self.j=w.Journal(self.j.path,dry=True)
+ self.run_lifecycle(cleanup_only=True)
+ self.assert_gone()
+ self.assertEqual(ledger,(self.directory/'budget.json').read_bytes())
+
+ def test_cleanup_only_preserves_original_witness_failure(self):
+ with patch.object(w,'follow_boot',side_effect=ValueError('boot failed')):
+ with self.assertRaisesRegex(ValueError,'boot failed'):self.run_lifecycle()
+ original=[r for r in self.j.data['assertions'] if r[0].startswith(('W','P'))]
+ self.run_lifecycle(cleanup_only=True)
+ self.assertEqual(self.j.data['status'],'cleaned')
+ self.assertEqual(self.j.data['run_status'],'failed')
+ self.assertEqual(self.j.data['error'],'boot failed')
+ self.assertEqual(original,[r for r in self.j.data['assertions'] if r[0].startswith(('W','P'))])
+ self.assertIn('boot failed',(self.directory/'evidence.md').read_text())
+
+ def test_lost_terminate_and_delete_replies_resolve_by_readback(self):
+ self.aws.fail_after[('ec2','terminate-instances')]=RuntimeError('reply lost')
+ self.aws.fail_after[('iam','delete-role')]=RuntimeError('reply lost')
+ self.aws.fail_after[('iam','delete-instance-profile')]=RuntimeError('reply lost')
+ self.aws.fail_after[('ssm','delete-parameter')]=RuntimeError('reply lost')
+ self.aws.fail_after[('s3api','delete-object')]=RuntimeError('reply lost')
+ self.run_lifecycle()
+ self.assert_gone()
+
+ def test_tg_failure_does_not_skip_other_tg_or_edges_on_failure_path(self):
+ self.aws.fail_before[('elbv2','describe-target-health')]=RuntimeError('TG unavailable')
+ with self.assertRaises(ValueError):self.run_lifecycle()
+ calls=[(service,op) for service,op,p in self.aws.calls]
+ self.assertEqual(calls.count(('elbv2','describe-target-health')),4)
+ self.assertEqual(calls.count(('s3api','list-object-versions')),2)
+ self.assertIn('TG unavailable',(self.directory/'evidence.md').read_text())
+
+ def test_edges_created_then_deleted_still_fail_window(self):
+ before=w.snapshot(self.aws)
+ key=w.EDGES_PREFIX+'g-other.json'
+ self.aws._put(key,b'{}')
+ self.aws('s3api','delete-object',Bucket=w.BUCKET,Key=key)
+ after=w.snapshot(self.aws)
+ self.assertEqual(before['edges'],after['edges'])
+ self.assertTrue(w.check_snapshot(before,after))
+
+ def test_cleanup_refuses_changed_owner_and_deletes_no_foreign_resource(self):
+ row=self.j.intent('role',self.s['role'])
+ response=self.aws('iam','create-role',RoleName=self.s['role'],AssumeRolePolicyDocument='{}',Tags=[{'Key':'purpose','Value':'foreign'}])
+ self.j.made(row,id=response['Role']['RoleId'])
+ leaks=w.cleanup(self.aws,self.j,sleep=lambda _:None)
+ self.assertEqual(leaks,[f'arn:aws:iam::{w.ACCOUNT}:role/'+self.s['role']])
+ self.assertFalse(any(op.startswith('delete') for service,op,p in self.aws.calls))
+
+ def test_cli_gates_execute_before_any_render_or_aws(self):
+ for args in [['--execute'],['--execute','--dry-run','--i-have-budget'],['--i-have-budget'],
+ ['--execute','--i-have-budget','--scratch',str(self.directory/'alternate')]]:
+ with self.subTest(args=args),patch.object(w.sys,'argv',['witness',*args]),self.assertRaises(ValueError):w.main()
+
+ def test_execute_refuses_alternate_budget_before_creating_files(self):
+ alternate=self.directory/'alternate'
+ args=['witness','--execute','--i-have-budget','--scratch',str(alternate)]
+ with patch.object(w.sys,'argv',args),patch.object(w,'exclusive') as lock, \
+ patch.object(w,'render') as render,self.assertRaisesRegex(ValueError,'fixed budget path'):
+ w.main()
+ lock.assert_not_called()
+ render.assert_not_called()
+ self.assertFalse(alternate.exists())
+ self.assertEqual(w.BUDGET,Path('/home/paulca/.cache/p3b1-f4-work/witness-budget.json'))
+
+ def test_definite_create_rejection_is_not_an_ambiguous_leak(self):
+ self.aws.fail_before[('iam','create-role')]=w.AWSError('iam','create-role','AccessDenied')
+ with self.assertRaisesRegex(ValueError,'AccessDenied'):self.run_lifecycle()
+ self.assertFalse(self.j.data['leaked'])
+ self.assertEqual(self.j.data['resources'][0]['state'],'rejected')
+ self.assertFalse(any(op.startswith('delete') for _,op,p in self.aws.calls))
+
+ def test_pending_create_not_visible_is_reported_as_unknown_not_gone(self):
+ row=self.j.intent('role',self.s['role'])
+ leaks=w.cleanup(self.aws,self.j,sleep=lambda _:None)
+ self.assertEqual(leaks,[f'arn:aws:iam::{w.ACCOUNT}:role/'+self.s['role']])
+ self.assertEqual(row['state'],'pending')
+ self.assertIn('outcome unknown',row['cleanup_error'])
+
+ def test_copy_cleanup_removes_all_exact_versions_and_markers_only(self):
+ row=self.j.intent('copy',self.s['key'])
+ for _ in range(2):
+ self.aws._put(self.s['key'],b'copy',{'witness-owner':self.j.data['owner']})
+ self.aws('s3api','delete-object',Bucket=w.BUCKET,Key=self.s['key'])
+ sibling=self.s['key']+'-unrelated'
+ self.aws._put(sibling,b'foreign')
+ self.assertEqual(w.cleanup(self.aws,self.j,sleep=lambda _:None),[])
+ self.assertFalse(self.aws.objects.get(self.s['key']))
+ self.assertTrue(self.aws.objects[sibling])
+ self.assertFalse(any(p.get('Key')==sibling for _,op,p in self.aws.calls if op=='delete-object'))
+
+ def test_copy_cleanup_refuses_old_equal_or_unprovable_delete_markers(self):
+ for age in ('old','equal','unknown','no-version'):
+ with self.subTest(age=age):
+ self.j.data['resources']=[]
+ self.aws.objects.pop(self.s['key'],None)
+ row=self.j.intent('copy',self.s['key'])
+ version=self.aws._put(self.s['key'],b'ours',{'witness-owner':self.j.data['owner']})
+ self.aws('s3api','delete-object',Bucket=w.BUCKET,Key=self.s['key'])
+ marker=self.aws.objects[self.s['key']][-1]
+ if age=='old':marker['LastModified']='2000-01-01T00:00:00+00:00'
+ if age=='equal':marker['LastModified']=version['LastModified']
+ if age=='unknown':marker.pop('LastModified')
+ if age=='no-version':self.aws.objects[self.s['key']].remove(version)
+ self.aws.calls.clear()
+ self.assertEqual(w.cleanup(self.aws,self.j,sleep=lambda _:None),[f'arn:aws:s3:::{w.BUCKET}/'+self.s['key']])
+ self.assertFalse(any(op=='delete-object' for _,op,_ in self.aws.calls))
+ self.assertIn('LEAKED',self.output.getvalue())
+
+ def test_copy_cleanup_timestamp_survives_partial_delete_and_restart(self):
+ row=self.j.intent('copy',self.s['key'])
+ self.aws._put(self.s['key'],b'ours',{'witness-owner':self.j.data['owner']})
+ self.aws('s3api','delete-object',Bucket=w.BUCKET,Key=self.s['key'])
+ self.aws.fail_after[('s3api','delete-object')]=RuntimeError('reply lost')
+ self.assertEqual(w.cleanup(self.aws,self.j,sleep=lambda _:None),[])
+ self.assertIn('owned_at',row['ids'])
+ self.assertFalse(self.aws.objects.get(self.s['key']))
+
+ def test_foreign_copy_version_is_never_deleted(self):
+ row=self.j.intent('copy',self.s['key'])
+ self.aws._put(self.s['key'],b'ours',{'witness-owner':self.j.data['owner']})
+ self.aws._put(self.s['key'],b'foreign',{'witness-owner':'foreign'})
+ self.assertEqual(w.cleanup(self.aws,self.j,sleep=lambda _:None),[f'arn:aws:s3:::{w.BUCKET}/'+self.s['key']])
+ self.assertFalse(any(op=='delete-object' for _,op,p in self.aws.calls))
+
+ def test_tampered_copy_checksum_stops_before_any_parameter_or_instance(self):
+ original=self.aws._s3api_head_object
+ def head(params,file):
+ result=original(params,file)
+ if params['Key']==self.s['key'] and params.get('ChecksumMode'):
+ result['ChecksumSHA256']='wrong'
+ return result
+ with patch.object(self.aws,'_s3api_head_object',side_effect=head):
+ with self.assertRaisesRegex(ValueError,'checksum'):self.run_lifecycle()
+ self.assert_gone()
+ self.assertFalse(any(op in ('put-parameter','run-instances') for _,op,p in self.aws.calls))
+
+ def test_ssm_readback_mismatch_stops_before_launch(self):
+ original=self.aws._ssm_get_parameter
+ def get(params,file):
+ result=original(params,file)
+ if params.get('WithDecryption'):result['Parameter']['Value']='tampered'
+ return result
+ with patch.object(self.aws,'_ssm_get_parameter',side_effect=get):
+ with self.assertRaisesRegex(ValueError,'SSM readback'):self.run_lifecycle()
+ self.assert_gone()
+ self.assertFalse(any(op=='run-instances' for _,op,p in self.aws.calls))
+
+ def test_changed_pointer_and_new_floor_refuse_launch_without_widening_reads(self):
+ original=self.aws._iam_get_instance_profile
+ def get(params,file):
+ result=original(params,file)
+ self.aws._put(w.FLOOR_KEYS[0],b'new floor')
+ return result
+ with patch.object(self.aws,'_iam_get_instance_profile',side_effect=get):
+ with self.assertRaisesRegex(ValueError,'floor now exists'):self.run_lifecycle()
+ self.assert_gone()
+ self.assertFalse(any(op=='run-instances' for _,op,p in self.aws.calls))
+
+ def test_wrong_account_never_creates_or_deletes(self):
+ with patch.object(self.aws,'_sts_get_caller_identity',return_value={'Account':'other'}):
+ with self.assertRaisesRegex(ValueError,'wrong AWS account'):self.run_lifecycle()
+ self.assertFalse(any(op.startswith(('create','delete','put','run','copy','terminate')) for _,op,p in self.aws.calls))
+
+ def test_collector_timeout_still_terminates_and_persists_every_poll(self):
+ with patch.object(self.aws,'_ec2_get_console_output',return_value={'Output':'still booting'}):
+ with self.assertRaisesRegex(ValueError,'deadline'):self.run_lifecycle()
+ self.assert_gone()
+ self.assertEqual(len(list(self.directory.glob('console-*.log'))),120)
+ self.assertEqual(self.j.data['cloud_init_status'],'running-or-unknown')
+
+
+
+class AssertionTests(unittest.TestCase):
+ def live_fixture(self):
+ return json.loads((Path(__file__).parent / 'testdata/region-group-f4w1.json').read_text())
+
+ def test_f4w1_reset_completed_even_though_systemd_forgot_exec_timestamp(self):
+ e = self.live_fixture()
+ self.assertEqual(w.properties(e, 'carlos-hairpin-reset')['ExecMainStartTimestampMonotonic'], '0')
+ self.assertTrue(w.reset_completed(e))
+ rows = {n.split()[0]: (ok, detail) for n, ok, detail in w.assertions(e)}
+ self.assertTrue(rows['W20'][0])
+ self.assertFalse(rows['W8'][0])
+ self.assertFalse(rows['W9'][0])
+ self.assertFalse(rows['P10'][0])
+ self.assertEqual(rows['P10'][1], 'unit settings=PASS; live edge process privileges=FAIL; bind mount flags=PASS; no tenant execution probe')
+ e['edge_process_status'] = 'NoNewPrivs:\t1\nCapEff:\t0000000000000400\n'
+ self.assertTrue(next(ok for n, ok, detail in w.p_assertions(e, True) if n.startswith('P10 ')))
+
+ def test_reset_needs_completed_current_boot_invocations_not_default_success(self):
+ good = self.live_fixture()
+ journal = good['commands']['carlos-hairpin-reset-journal']['out']
+ mutations = [
+ '', '-- No entries --\n',
+ journal.replace('Starting carlos-hairpin-reset.service...', 'unrelated'),
+ journal.replace('Finished carlos-hairpin-reset.service.', 'unrelated'),
+ journal.replace('systemd[1]', 'carlos[1730]'),
+ journal + '[ 50.000000] host systemd[1]: Starting carlos-hairpin-reset.service...\n',
+ journal + "[ 50.000000] host systemd[1]: carlos-hairpin-reset.service: Failed with result 'exit-code'.\n",
+ ]
+ for out in mutations:
+ with self.subTest(out=out):
+ e = copy.deepcopy(good)
+ e['commands']['carlos-hairpin-reset-journal']['out'] = out
+ self.assertFalse(w.reset_completed(e))
+ for name in ['carlos-hairpin-reset-journal', 'carlos-hairpin-reset-show']:
+ e = copy.deepcopy(good)
+ e['commands'][name] = {'rc': 1, 'out': ''}
+ self.assertFalse(w.reset_completed(e))
+ e = copy.deepcopy(good)
+ e['commands']['carlos-hairpin-reset-show']['out'] = 'Result=exit-code\nExecMainStatus=1\n'
+ self.assertFalse(w.reset_completed(e))
+
+ def test_edge_run_requires_active_pid_as_well_as_exec_attempt(self):
+ e = self.live_fixture()
+ show = e['commands']['carlos-edge-show']['out']
+ for active, pid, expected in [('failed', '1749', False), ('active', '0', False), ('active', '1749', True)]:
+ with self.subTest(active=active, pid=pid):
+ e['commands']['carlos-edge-show']['out'] = show.replace('ActiveState=failed', 'ActiveState=' + active).replace('MainPID=0', 'MainPID=' + pid).replace('ExecMainStatus=203', 'ExecMainStatus=0')
+ self.assertEqual(next(ok for n, ok, detail in w.assertions(e) if n.startswith('W8 ')), expected)
+
+ def evidence(self):
+ command=lambda out,rc=0:dict(rc=rc,out=out)
+ e={'commands':{},'files':{},'mounts':{},'launch_readback':{'instance':{'ImageId':w.AMI,
+ 'MetadataOptions':{'HttpTokens':'required','HttpPutResponseHopLimit':1}}}}
+ c=e['commands']
+ c['user']=command('carlos:x:999:999::/data:/usr/sbin/nologin\n')
+ c['group']=command('carlos:x:999:\n')
+ c['groups']=command('uid=999(carlos) gid=999(carlos) groups=999(carlos)\n')
+ c['bootstrap-tools']=command('/usr/sbin/groupadd\n/usr/bin/chown\n/usr/bin/chmod\n/usr/bin/systemd-tmpfiles\n/usr/sbin/usermod\n')
+ c['apt-masks']=command('masked\n'*5,1)
+ c['link']=command(json.dumps([{'ifname':'carlos-hairpin','linkinfo':{'info_kind':'dummy'}}]))
+ c['addresses']=command(json.dumps([{'ifname':'eth0','addr_info':[{'local':'10.0.0.5'}]},
+ {'ifname':'carlos-hairpin','addr_info':[]}]))
+ rules=[]
+ for family,address in [('ip','169.254.169.254'),('ip6','fd00:ec2::254')]:
+ rules.append({'rule':{'table':'carlos_group_imds','chain':'output','expr':[
+ {'match':{'left':{'meta':{'key':'skuid'}},'op':'!=','right':{'set':[0,999]}}},
+ {'match':{'left':{'payload':{'protocol':family,'field':'daddr'}},'op':'==','right':address}},
+ {'reject':None}]}})
+ c['nft-json']=command(json.dumps({'nftables':rules}))
+ for i,p in enumerate(['/etc/carlos/group-identity.json','/etc/carlos/region-config.json',
+ '/etc/carlos/group.json','/etc/carlos/group-ingress.json'],2):
+ e['files'][p]=dict(uid=0,gid=0,mode='0o644',nlink=1,regular=True,mtime=i)
+ e['staging_observer']={'parent_before':{'dev':1,'noexec':False},'parent_after':{'dev':1,'noexec':False},
+ 'samples':[{'dev':1,'noexec':False,'uid':0,'gid':0,'mode':'0o700','mountinfo':'mounts','monotonic_ns':1,'ingress_absent':True}],
+ 'clock':'CLOCK_MONOTONIC','ingress_ns':5,'removed_ns':9,'finished_ns':10}
+ for path,target in [('/var/run','/run'),('/var/lock','/run/lock')]:
+ e['mounts'][path]=dict(probe=path,realpath=target,findmnt=command('mount details'))
+ for path in ('/data/instances','/run/carlos/instances','/run/carlos/logs'):
+ e['mounts'][path]=dict(probe=path,findmnt=command(path+' rw,nosuid,nodev,nosymfollow'))
+ security=dict(ProtectSystem='strict',ProtectHome='yes',PrivateTmp='yes',PrivateDevices='yes',
+ ProtectKernelTunables='yes',ProtectKernelModules='yes',MemoryDenyWriteExecute='yes')
+ edge=dict(security,User='carlos',Group='carlos',NoNewPrivileges='yes',
+ CapabilityBoundingSet='cap_net_bind_service',AmbientCapabilities='cap_net_bind_service')
+ control=dict(security,User='',Group='',RestrictAddressFamilies='AF_UNIX AF_NETLINK',ReadWritePaths='/run/carlos-hairpin')
+ for name,value in [('carlos-edge',edge),('carlos-instance-control',control)]:
+ c[name+'-show']=command(''.join(k+'='+v+'\n' for k,v in value.items()))
+ e['edge_process_status']='NoNewPrivs:\t1\nCapEff:\t0000000000000400\n'
+ return e
+
+ def test_all_p_assertions_accept_positive_evidence_then_reject_mutations(self):
+ good=self.evidence()
+ self.assertTrue(all(ok for n,ok,d in w.p_assertions(good,True)),w.p_assertions(good,True))
+ cases=[
+ ('P1',lambda e:e['launch_readback']['instance']['MetadataOptions'].update(HttpTokens='optional')),
+ ('P2',lambda e:e['mounts']['/var/lock'].update(realpath='/elsewhere')),
+ ('P3',lambda e:e['staging_observer']['samples'][0].update(noexec=True)),
+ ('P4',lambda e:e['commands']['groups'].update(out='uid=998(carlos) gid=999(carlos)')),
+ ('P5',lambda e:e['commands']['bootstrap-tools'].update(rc=1)),
+ ('P6',lambda e:e['commands']['addresses'].update(out=json.dumps([{'ifname':'eth0','addr_info':[{'local':'54.77.110.223'}]}]))),
+ ('P7',lambda e:e['commands']['apt-masks'].update(out='masked\n'*4)),
+ ('P9',lambda e:e['files']['/etc/carlos/group-identity.json'].update(nlink=2)),
+ ('P10',lambda e:e.update(edge_process_status='NoNewPrivs:\t0\nCapEff:\t0000000000000400\n')),
+ ]
+ for number,mutate in cases:
+ with self.subTest(number=number):
+ e=copy.deepcopy(good);mutate(e)
+ rows={n.split()[0]:ok for n,ok,d in w.p_assertions(e,True)}
+ self.assertFalse(rows[number])
+ self.assertFalse(next(ok for n,ok,d in w.p_assertions(good,False) if n.startswith('P8 ')))
+
+ def test_mount_parent_alone_is_not_historical_leaf_evidence(self):
+ e=self.evidence();e['staging_observer']['samples']=[]
+ self.assertFalse(w.staging_mount_ok(e))
+ e=self.evidence();e['staging_observer']['removed_ns']=0
+ self.assertFalse(w.staging_mount_ok(e))
+
+ def test_staging_order_uses_only_monotonic_observations(self):
+ e=self.evidence()
+ self.assertTrue(w.staging_mount_ok(e))
+ e['files']['/etc/carlos/group-ingress.json']['mtime']=-9999999999999999
+ self.assertTrue(w.staging_mount_ok(e))
+ e['staging_observer']['clock']='CLOCK_REALTIME'
+ self.assertFalse(w.staging_mount_ok(e))
+ e['staging_observer']['clock']='CLOCK_MONOTONIC'
+ e['staging_observer']['samples'][0]['ingress_absent']=False
+ self.assertFalse(w.staging_mount_ok(e))
+
+ def test_publication_requires_actual_denial_and_no_admission_open(self):
+ e=self.evidence()
+ e['commands']['carlos-edge-journal']={'rc':0,'out':'agent: edges file pass failed (#1): PutObject AccessDenied\n'}
+ self.assertTrue(next(ok for n,ok,d in w.assertions(e) if n.startswith('W9 ')))
+ e['commands']['carlos-edge-journal']['out']+='tenant admission is open\n'
+ self.assertFalse(next(ok for n,ok,d in w.assertions(e) if n.startswith('W9 ')))
+
+
+
+class AdapterTests(unittest.TestCase):
+ def test_get_object_uses_required_cli_flags_and_local_outfile(self):
+ result=__import__('subprocess').CompletedProcess([],0,stdout='{"VersionId":"v"}',stderr='')
+ with patch.object(w.subprocess,'run',return_value=result) as run,redirect_stdout(io.StringIO()):
+ self.assertEqual(w.AWS()('s3api','get-object',Bucket=w.BUCKET,Key=w.POINTER_KEY,
+ VersionId='v',_file=Path('/safe/out.json')),{'VersionId':'v'})
+ args=run.call_args.args[0]
+ self.assertNotIn('--cli-input-json',args)
+ self.assertEqual(args[args.index('--bucket')+1],w.BUCKET)
+ self.assertEqual(args[args.index('--key')+1],w.POINTER_KEY)
+ self.assertEqual(args[-1],'/safe/out.json')
+ self.assertEqual(run.call_args.kwargs['env']['AWS_MAX_ATTEMPTS'],'1')
+
+ def test_run_instances_passes_fileb_and_omits_json_user_data(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ raw=w.user_data(b'#!/bin/sh\ntrue\n',b'collector')
+ path=w.write_user_data(Path(tmp),raw)
+ result=__import__('subprocess').CompletedProcess([],0,stdout='{}',stderr='')
+ with patch.object(w.subprocess,'run',return_value=result) as run,redirect_stdout(io.StringIO()):
+ w.AWS()('ec2','run-instances',_user_data=path,ImageId=w.AMI)
+ args=run.call_args.args[0]
+ self.assertEqual(args[args.index('--user-data')+1],'fileb://'+str(path))
+ self.assertNotIn('UserData',json.loads(args[args.index('--cli-input-json')+1]))
+ with self.assertRaisesRegex(ValueError,'raw user-data'):
+ w.AWS()('ec2','run-instances',UserData=base64.b64encode(raw).decode())
+
+ def test_aws_error_code_is_exact_and_access_denied_is_not_absence(self):
+ result=__import__('subprocess').CompletedProcess([],254,stdout='',stderr='An error occurred (AccessDenied) when calling the HeadObject operation: denied')
+ with patch.object(w.subprocess,'run',return_value=result),redirect_stdout(io.StringIO()):
+ with self.assertRaises(w.AWSError) as error:
+ w.absent(w.AWS(),'s3api','head-object',{'404'},Bucket=w.BUCKET,Key=w.FLOOR_KEYS[0])
+ self.assertEqual(error.exception.code,'AccessDenied')
+
+ def test_cleanup_preview_is_readonly_and_limited_to_journal(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ j=w.Journal(Path(tmp)/'journal.json',w.scope('preview'),dry=True)
+ j.intent('role',j.data['scope']['role'])
+ before=j.path.read_bytes()
+ calls=w.cleanup_preview(j)
+ self.assertEqual(j.path.read_bytes(),before)
+ self.assertIn(('iam','delete-role',{'RoleName':j.data['scope']['role']}),calls)
+ self.assertFalse(any(service in ('ssm','ec2') and op.startswith(('delete','terminate')) for service,op,args in calls))
+
+
+if __name__=='__main__':unittest.main()
diff --git a/scripts/region_group_witness_fake.py b/scripts/region_group_witness_fake.py
new file mode 100644
index 000000000..18590f303
--- /dev/null
+++ b/scripts/region_group_witness_fake.py
@@ -0,0 +1,634 @@
+"""Offline, stateful model of the AWS calls made by region-group-boot-witness.py.
+
+Simulation only: every id, identity and evidence byte here is invented. Nothing
+in this module spawns a process, opens a socket or reads AWS credentials.
+"""
+import base64
+import copy
+import gzip
+import hashlib
+import io
+import json
+import tarfile
+from datetime import datetime, timedelta, timezone
+
+# The fixture bootstrap binary. No real artifact is available offline, so the
+# source object, the scratch copy and every download carry exactly these bytes.
+# Its SHA-256 is NOT the harness BOOT_SHA; the harness injects that comparison.
+OFFLINE_BOOTSTRAP = b'F4 offline bootstrap'
+OFFLINE_BOOTSTRAP_SHA256 = hashlib.sha256(OFFLINE_BOOTSTRAP).hexdigest()
+OFFLINE_BOOTSTRAP_CHECKSUM = base64.b64encode(hashlib.sha256(OFFLINE_BOOTSTRAP).digest()).decode()
+ARTIFACT_KEY = 'bootstrap/router/v0.34.2/carlos-linux-arm64'
+SIM_VPC = 'vpc-0f4simulated0001'
+SIM_KMS_KEY_ID = '0f4f4f4f-0000-4000-8000-00000000f4f4'
+SIM_EPOCH = datetime(2026, 11, 4, 12, 0, 0, tzinfo=timezone.utc)
+EBS_FIELDS = {'VolumeSize', 'VolumeType', 'Encrypted', 'DeleteOnTermination', 'Iops', 'Throughput',
+ 'KmsKeyId', 'SnapshotId'}
+RUN_FIELDS = ('ImageId', 'InstanceType', 'MinCount', 'MaxCount', 'ClientToken', 'UserData', 'IamInstanceProfile',
+ 'MetadataOptions', 'BlockDeviceMappings', 'NetworkInterfaces', 'TagSpecifications')
+STATES = {'pending': 0, 'running': 16, 'shutting-down': 32, 'terminated': 48}
+
+
+def _hex(*parts, n=17):
+ return hashlib.sha256('|'.join(parts).encode()).hexdigest()[:n]
+
+
+class FakeAWS:
+ dry = True
+
+ def __init__(self, harness_module, signed_pointer_bytes, directory, dry=True):
+ assert dry, 'FakeAWS is simulation only'
+ self.h = harness_module
+ self.directory = directory
+ self.dry = True
+ self.calls = []
+ self.fail_before = {}
+ self.fail_after = {}
+ self._tick = 0
+ self.roles, self.profiles = {}, {}
+ self.parameters = {} # name -> dict(type, tags, history[list of dicts])
+ self.objects = {} # key -> [version dicts, oldest first]
+ self.instances, self.volumes, self.launches = {}, {}, {}
+ self.console_polls = {}
+ self._put(self.h.POINTER_KEY, signed_pointer_bytes, version='sim-pointer-0001')
+ self._put(self.h.BOOT_KEY, OFFLINE_BOOTSTRAP, version=self.h.BOOT_VERSION)
+ self._put(ARTIFACT_KEY, OFFLINE_BOOTSTRAP, version='sim-artifact-0001')
+
+ # ---- plumbing -------------------------------------------------------
+ def __call__(self, service, operation, _file=None, _timeout=90, _user_data=None, **params):
+ if _user_data is not None:
+ assert service == 'ec2' and operation == 'run-instances' and 'UserData' not in params
+ params['UserData'] = _user_data.read_bytes()
+ self.calls.append((service, operation, copy.deepcopy(params)))
+ safe = dict(params)
+ if operation == 'put-parameter':
+ safe['Value'] = '[REDACTED]'
+ if operation == 'run-instances':
+ safe['UserData'] = f'[raw gzip MIME {len(params["UserData"])} bytes]'
+ self.h.print('SIMULATED AWS', service, operation, json.dumps(safe, sort_keys=True, default=str), flush=True)
+ key = (service, operation)
+ handler = getattr(self, ('_' + service + '_' + operation).replace('-', '_'), None)
+ if handler is None:
+ raise AssertionError(f'unmodeled AWS operation: {service} {operation}')
+ if key in self.fail_before:
+ raise self.fail_before.pop(key)
+ result = handler(params, _file)
+ if key in self.fail_after:
+ raise self.fail_after.pop(key)
+ return copy.deepcopy(result)
+
+ def _error(self, service, operation, code, detail=''):
+ return self.h.AWSError(service, operation, code, detail)
+
+ def _now(self):
+ self._tick += 1
+ return (SIM_EPOCH + timedelta(seconds=self._tick)).isoformat()
+
+ @staticmethod
+ def _check(p, required=(), optional=()):
+ missing = set(required) - set(p)
+ extra = set(p) - set(required) - set(optional)
+ if missing or extra:
+ raise AssertionError(f'unexpected AWS parameters: missing={sorted(missing)} extra={sorted(extra)}')
+
+ # ---- sts / kms ------------------------------------------------------
+ def _sts_get_caller_identity(self, p, f):
+ self._check(p)
+ return dict(UserId='AIDASIMULATEDF4', Account=self.h.ACCOUNT,
+ Arn=f'arn:aws:sts::{self.h.ACCOUNT}:assumed-role/simulated-f4/offline')
+
+ def _kms_describe_key(self, p, f):
+ self._check(p, ['KeyId'])
+ if p['KeyId'] != 'alias/aws/ssm':
+ raise self._error('kms', 'describe-key', 'NotFoundException', p['KeyId'])
+ arn = f'arn:aws:kms:{self.h.REGION}:{self.h.ACCOUNT}:key/{SIM_KMS_KEY_ID}'
+ return {'KeyMetadata': dict(AWSAccountId=self.h.ACCOUNT, KeyId=SIM_KMS_KEY_ID, Arn=arn, Enabled=True,
+ KeyState='Enabled', KeyManager='AWS', KeySpec='SYMMETRIC_DEFAULT')}
+
+ # ---- iam ------------------------------------------------------------
+ def _role_view(self, role, tags=True):
+ view = {k: role[k] for k in ('Path', 'RoleName', 'RoleId', 'Arn', 'CreateDate', 'AssumeRolePolicyDocument')}
+ if tags:
+ view['Tags'] = role['Tags']
+ return view
+
+ def _profile_view(self, profile):
+ return dict(Path='/', InstanceProfileName=profile['Name'], InstanceProfileId=profile['Id'],
+ Arn=profile['Arn'], CreateDate=profile['CreateDate'], Tags=profile['Tags'],
+ Roles=[self._role_view(self.roles[n], tags=False) for n in profile['Roles']])
+
+ def _no_role(self, op, name):
+ return self._error('iam', op, 'NoSuchEntity', f'The role with name {name} cannot be found.')
+
+ def _no_profile(self, op, name):
+ return self._error('iam', op, 'NoSuchEntity', f'Instance Profile {name} cannot be found.')
+
+ def _iam_get_role(self, p, f):
+ self._check(p, ['RoleName'])
+ if p['RoleName'] not in self.roles:
+ raise self._no_role('get-role', p['RoleName'])
+ return {'Role': self._role_view(self.roles[p['RoleName']])}
+
+ def _iam_create_role(self, p, f):
+ self._check(p, ['RoleName', 'AssumeRolePolicyDocument'], ['Tags'])
+ name = p['RoleName']
+ if name in self.roles:
+ raise self._error('iam', 'create-role', 'EntityAlreadyExists', name)
+ self.roles[name] = dict(Path='/', RoleName=name, RoleId='AROA' + _hex('role', name).upper(),
+ Arn=f'arn:aws:iam::{self.h.ACCOUNT}:role/{name}', CreateDate=self._now(),
+ AssumeRolePolicyDocument=json.loads(p['AssumeRolePolicyDocument']),
+ Tags=copy.deepcopy(p.get('Tags', [])), policies={})
+ return {'Role': self._role_view(self.roles[name])}
+
+ def _iam_put_role_policy(self, p, f):
+ self._check(p, ['RoleName', 'PolicyName', 'PolicyDocument'])
+ if p['RoleName'] not in self.roles:
+ raise self._no_role('put-role-policy', p['RoleName'])
+ self.roles[p['RoleName']]['policies'][p['PolicyName']] = json.loads(p['PolicyDocument'])
+ return {}
+
+ def _iam_get_role_policy(self, p, f):
+ self._check(p, ['RoleName', 'PolicyName'])
+ role = self.roles.get(p['RoleName'])
+ if role is None or p['PolicyName'] not in role['policies']:
+ raise self._error('iam', 'get-role-policy', 'NoSuchEntity', 'policy or role not found')
+ return dict(RoleName=p['RoleName'], PolicyName=p['PolicyName'], PolicyDocument=role['policies'][p['PolicyName']])
+
+ def _iam_delete_role_policy(self, p, f):
+ self._check(p, ['RoleName', 'PolicyName'])
+ role = self.roles.get(p['RoleName'])
+ if role is None or p['PolicyName'] not in role['policies']:
+ raise self._error('iam', 'delete-role-policy', 'NoSuchEntity', 'policy or role not found')
+ del role['policies'][p['PolicyName']]
+ return {}
+
+ def _iam_delete_role(self, p, f):
+ self._check(p, ['RoleName'])
+ name = p['RoleName']
+ if name not in self.roles:
+ raise self._no_role('delete-role', name)
+ if self.roles[name]['policies']:
+ raise self._error('iam', 'delete-role', 'DeleteConflict', 'Cannot delete entity, must delete policies first.')
+ if any(name in x['Roles'] for x in self.profiles.values()):
+ raise self._error('iam', 'delete-role', 'DeleteConflict', 'Cannot delete entity, must remove role from instance profiles first.')
+ del self.roles[name]
+ return {}
+
+ def _iam_create_instance_profile(self, p, f):
+ self._check(p, ['InstanceProfileName'], ['Tags'])
+ name = p['InstanceProfileName']
+ if name in self.profiles:
+ raise self._error('iam', 'create-instance-profile', 'EntityAlreadyExists', name)
+ self.profiles[name] = dict(Name=name, Id='AIPA' + _hex('profile', name).upper(),
+ Arn=f'arn:aws:iam::{self.h.ACCOUNT}:instance-profile/{name}',
+ CreateDate=self._now(), Tags=copy.deepcopy(p.get('Tags', [])), Roles=[])
+ return {'InstanceProfile': self._profile_view(self.profiles[name])}
+
+ def _iam_get_instance_profile(self, p, f):
+ self._check(p, ['InstanceProfileName'])
+ if p['InstanceProfileName'] not in self.profiles:
+ raise self._no_profile('get-instance-profile', p['InstanceProfileName'])
+ return {'InstanceProfile': self._profile_view(self.profiles[p['InstanceProfileName']])}
+
+ def _iam_add_role_to_instance_profile(self, p, f):
+ self._check(p, ['InstanceProfileName', 'RoleName'])
+ profile = self.profiles.get(p['InstanceProfileName'])
+ if profile is None:
+ raise self._no_profile('add-role-to-instance-profile', p['InstanceProfileName'])
+ if p['RoleName'] not in self.roles:
+ raise self._no_role('add-role-to-instance-profile', p['RoleName'])
+ if profile['Roles']:
+ raise self._error('iam', 'add-role-to-instance-profile', 'LimitExceeded', 'one role per instance profile')
+ profile['Roles'].append(p['RoleName'])
+ return {}
+
+ def _iam_remove_role_from_instance_profile(self, p, f):
+ self._check(p, ['InstanceProfileName', 'RoleName'])
+ profile = self.profiles.get(p['InstanceProfileName'])
+ if profile is None:
+ raise self._no_profile('remove-role-from-instance-profile', p['InstanceProfileName'])
+ if p['RoleName'] not in profile['Roles']:
+ raise self._no_role('remove-role-from-instance-profile', p['RoleName'])
+ profile['Roles'].remove(p['RoleName'])
+ return {}
+
+ def _iam_delete_instance_profile(self, p, f):
+ self._check(p, ['InstanceProfileName'])
+ profile = self.profiles.get(p['InstanceProfileName'])
+ if profile is None:
+ raise self._no_profile('delete-instance-profile', p['InstanceProfileName'])
+ if profile['Roles']:
+ raise self._error('iam', 'delete-instance-profile', 'DeleteConflict', 'Cannot delete entity, must remove roles from instance profile first.')
+ del self.profiles[p['InstanceProfileName']]
+ return {}
+
+ # ---- ssm ------------------------------------------------------------
+ def _param_view(self, name, entry, version, decrypt):
+ value = version['Value']
+ if entry['type'] == 'SecureString' and not decrypt:
+ value = 'simulated-ciphertext:' + hashlib.sha256(value.encode()).hexdigest()[:16]
+ return dict(Name=name, Type=entry['type'], Value=value, Version=version['Version'],
+ LastModifiedDate=version['LastModifiedDate'], DataType='text',
+ ARN=f'arn:aws:ssm:{self.h.REGION}:{self.h.ACCOUNT}:parameter{name}')
+
+ def _ssm_put_parameter(self, p, f):
+ self._check(p, ['Name', 'Value', 'Type'], ['Overwrite', 'Tags', 'KeyId'])
+ if 'Tags' in p and 'Overwrite' in p:
+ raise self._error('ssm', 'put-parameter', 'ValidationException', 'tags with overwrite')
+ name = p['Name']
+ if not name.startswith('/') or p['Type'] not in ('String', 'SecureString'):
+ raise self._error('ssm', 'put-parameter', 'ValidationException', name)
+ if 'KeyId' in p and (p['Type'] != 'SecureString' or p['KeyId'] != 'alias/aws/ssm'):
+ raise self._error('ssm', 'put-parameter', 'ValidationException', 'unsupported KeyId')
+ entry = self.parameters.get(name)
+ if entry is not None:
+ if not p.get('Overwrite'):
+ raise self._error('ssm', 'put-parameter', 'ParameterAlreadyExists', name)
+ if p.get('Tags'):
+ raise self._error('ssm', 'put-parameter', 'InvalidParameter', 'tags with overwrite')
+ if entry['type'] != p['Type']:
+ raise self._error('ssm', 'put-parameter', 'HierarchyTypeMismatchException', name)
+ else:
+ entry = self.parameters[name] = dict(type=p['Type'], tags=copy.deepcopy(p.get('Tags', [])), history=[])
+ version = len(entry['history']) + 1
+ entry['history'].append(dict(Version=version, Value=p['Value'], LastModifiedDate=self._now()))
+ return {'Version': version, 'Tier': 'Standard'}
+
+ def _ssm_get_parameter(self, p, f):
+ self._check(p, ['Name'], ['WithDecryption'])
+ entry = self.parameters.get(p['Name'])
+ if entry is None:
+ raise self._error('ssm', 'get-parameter', 'ParameterNotFound', p['Name'])
+ return {'Parameter': self._param_view(p['Name'], entry, entry['history'][-1], p.get('WithDecryption', False))}
+
+ def _ssm_get_parameter_history(self, p, f):
+ self._check(p, ['Name'], ['WithDecryption'])
+ entry = self.parameters.get(p['Name'])
+ if entry is None:
+ raise self._error('ssm', 'get-parameter-history', 'ParameterNotFound', p['Name'])
+ return {'Parameters': [self._param_view(p['Name'], entry, v, p.get('WithDecryption', False)) for v in entry['history']]}
+
+ def _ssm_get_parameters_by_path(self, p, f):
+ self._check(p, ['Path'], ['Recursive', 'WithDecryption'])
+ path = p['Path'].rstrip('/')
+ if not p['Path'].startswith('/'):
+ raise self._error('ssm', 'get-parameters-by-path', 'ValidationException', p['Path'])
+ rows = []
+ for name in sorted(self.parameters):
+ if name.startswith(path + '/') and (p.get('Recursive') or '/' not in name[len(path) + 1:]):
+ entry = self.parameters[name]
+ rows.append(self._param_view(name, entry, entry['history'][-1], p.get('WithDecryption', False)))
+ return {'Parameters': rows}
+
+ def _ssm_delete_parameter(self, p, f):
+ self._check(p, ['Name'])
+ if p['Name'] not in self.parameters:
+ raise self._error('ssm', 'delete-parameter', 'ParameterNotFound', p['Name'])
+ del self.parameters[p['Name']]
+ return {}
+
+ def _ssm_list_tags_for_resource(self, p, f):
+ self._check(p, ['ResourceType', 'ResourceId'])
+ assert p['ResourceType'] == 'Parameter', 'unmodeled SSM resource type'
+ entry = self.parameters.get(p['ResourceId'])
+ if entry is None:
+ raise self._error('ssm', 'list-tags-for-resource', 'InvalidResourceId', p['ResourceId'])
+ return {'TagList': entry['tags']}
+
+ # ---- s3 -------------------------------------------------------------
+ def _put(self, key, data, metadata=None, checksum=None, version=None):
+ versions = self.objects.setdefault(key, [])
+ version = version or f'sim-v{sum(len(v) for v in self.objects.values()) + 1:06d}'
+ versions.append(dict(VersionId=version, Data=data, Marker=False, Metadata=dict(metadata or {}),
+ Checksum=checksum, LastModified=self._now(),
+ ETag='"' + hashlib.md5(data).hexdigest() + '"'))
+ return versions[-1]
+
+ def _bucket(self, op, p):
+ if p['Bucket'] != self.h.BUCKET:
+ raise self._error('s3api', op, 'NoSuchBucket', p['Bucket'])
+
+ def _find(self, op, p, code):
+ """Resolve key/VersionId to a stored version, raising S3-shaped errors."""
+ self._bucket(op, p)
+ versions = self.objects.get(p['Key'], [])
+ if 'VersionId' in p:
+ found = next((v for v in versions if v['VersionId'] == p['VersionId']), None)
+ if found is None:
+ raise self._error('s3api', op, code, 'version not found')
+ if found['Marker']:
+ raise self._error('s3api', op, '405', 'MethodNotAllowed')
+ return found
+ if not versions or versions[-1]['Marker']:
+ raise self._error('s3api', op, code, p['Key'])
+ return versions[-1]
+
+ @staticmethod
+ def _meta(v):
+ return dict(LastModified=v['LastModified'], ContentLength=len(v['Data']), ETag=v['ETag'],
+ VersionId=v['VersionId'], ContentType='binary/octet-stream', Metadata=v['Metadata'],
+ ServerSideEncryption='AES256')
+
+ def _s3api_get_bucket_location(self, p, f):
+ self._check(p, ['Bucket'])
+ self._bucket('get-bucket-location', p)
+ return {'LocationConstraint': self.h.REGION}
+
+ def _s3api_get_bucket_versioning(self, p, f):
+ self._check(p, ['Bucket'])
+ self._bucket('get-bucket-versioning', p)
+ return {'Status': 'Enabled', 'MFADelete': 'Disabled'}
+
+ def _s3api_head_object(self, p, f):
+ self._check(p, ['Bucket', 'Key'], ['VersionId', 'ChecksumMode'])
+ v = self._find('head-object', p, '404')
+ out = self._meta(v)
+ if p.get('ChecksumMode') == 'ENABLED' and v['Checksum']:
+ out['ChecksumSHA256'] = v['Checksum']
+ return out
+
+ def _s3api_get_object(self, p, f):
+ self._check(p, ['Bucket', 'Key'], ['VersionId'])
+ assert f is not None, 'get-object without an outfile is unmodeled'
+ v = self._find('get-object', p, 'NoSuchKey')
+ with open(f, 'wb') as out:
+ out.write(v['Data'])
+ return self._meta(v)
+
+ def _s3api_copy_object(self, p, f):
+ self._check(p, ['Bucket', 'Key', 'CopySource', 'MetadataDirective', 'Metadata', 'ChecksumAlgorithm'])
+ assert p['ChecksumAlgorithm'] == 'SHA256' and p['MetadataDirective'] in ('REPLACE', 'COPY')
+ self._bucket('copy-object', p)
+ source, _, query = p['CopySource'].partition('?')
+ bucket, _, key = source.partition('/')
+ assert bucket == self.h.BUCKET, 'cross-bucket copy is unmodeled'
+ src = dict(Bucket=bucket, Key=key)
+ if query:
+ assert query.startswith('versionId='), 'unmodeled CopySource query'
+ src['VersionId'] = query[len('versionId='):]
+ found = self._find('copy-object', src, 'NoSuchKey')
+ metadata = p['Metadata'] if p['MetadataDirective'] == 'REPLACE' else found['Metadata']
+ checksum = base64.b64encode(hashlib.sha256(found['Data']).digest()).decode()
+ v = self._put(p['Key'], found['Data'], {k.lower(): x for k, x in metadata.items()}, checksum)
+ return dict(CopySourceVersionId=found['VersionId'], VersionId=v['VersionId'], ServerSideEncryption='AES256',
+ CopyObjectResult=dict(ETag=v['ETag'], LastModified=v['LastModified'], ChecksumSHA256=checksum))
+
+ def _s3api_delete_object(self, p, f):
+ self._check(p, ['Bucket', 'Key'], ['VersionId'])
+ self._bucket('delete-object', p)
+ versions = self.objects.get(p['Key'], [])
+ if 'VersionId' in p:
+ gone = [v for v in versions if v['VersionId'] == p['VersionId']]
+ versions[:] = [v for v in versions if v['VersionId'] != p['VersionId']]
+ if not versions:
+ self.objects.pop(p['Key'], None)
+ return dict(VersionId=p['VersionId'], **({'DeleteMarker': True} if gone and gone[0]['Marker'] else {}))
+ marker = dict(VersionId=f'sim-dm{sum(len(v) for v in self.objects.values()) + 1:06d}', Data=b'', Marker=True,
+ Metadata={}, Checksum=None, LastModified=self._now(), ETag='')
+ self.objects.setdefault(p['Key'], []).append(marker)
+ return dict(DeleteMarker=True, VersionId=marker['VersionId'])
+
+ def _s3api_list_objects_v2(self, p, f):
+ self._check(p, ['Bucket'], ['Prefix'])
+ self._bucket('list-objects-v2', p)
+ rows = [dict(Key=k, LastModified=v[-1]['LastModified'], ETag=v[-1]['ETag'], Size=len(v[-1]['Data']),
+ StorageClass='STANDARD') for k, v in sorted(self.objects.items())
+ if k.startswith(p.get('Prefix', '')) and not v[-1]['Marker']]
+ out = dict(IsTruncated=False, KeyCount=len(rows), MaxKeys=1000, Name=self.h.BUCKET, Prefix=p.get('Prefix', ''))
+ if rows:
+ out['Contents'] = rows
+ return out
+
+ def _s3api_list_object_versions(self, p, f):
+ self._check(p, ['Bucket'], ['Prefix'])
+ self._bucket('list-object-versions', p)
+ versions, markers = [], []
+ for key, items in sorted(self.objects.items()):
+ if not key.startswith(p.get('Prefix', '')):
+ continue
+ for i, v in reversed(list(enumerate(items))):
+ row = dict(Key=key, VersionId=v['VersionId'], IsLatest=i == len(items) - 1, LastModified=v['LastModified'])
+ if v['Marker']:
+ markers.append(row)
+ else:
+ versions.append(dict(row, ETag=v['ETag'], Size=len(v['Data']), StorageClass='STANDARD'))
+ out = dict(IsTruncated=False, MaxKeys=1000, Name=self.h.BUCKET, Prefix=p.get('Prefix', ''))
+ if versions:
+ out['Versions'] = versions
+ if markers:
+ out['DeleteMarkers'] = markers
+ return out
+
+ # ---- ec2 / asg / elbv2 ---------------------------------------------
+ def _ec2_describe_regions(self, p, f):
+ self._check(p, ['RegionNames'])
+ if p['RegionNames'] != [self.h.REGION]:
+ raise self._error('ec2', 'describe-regions', 'InvalidParameterValue', 'unknown region')
+ return {'Regions': [dict(RegionName=self.h.REGION, Endpoint=f'ec2.{self.h.REGION}.amazonaws.com',
+ OptInStatus='opt-in-not-required')]}
+
+ def _ec2_describe_images(self, p, f):
+ self._check(p, ['ImageIds'])
+ if p['ImageIds'] != [self.h.AMI]:
+ raise self._error('ec2', 'describe-images', 'InvalidAMIID.NotFound', str(p['ImageIds']))
+ return {'Images': [dict(ImageId=self.h.AMI, Architecture='arm64', State='available', RootDeviceType='ebs',
+ RootDeviceName='/dev/xvda', Name='debian-13-arm64-20261103-2651',
+ OwnerId='136693071363', Public=True, VirtualizationType='hvm')]}
+
+ def _ec2_describe_subnets(self, p, f):
+ self._check(p, ['SubnetIds'])
+ if p['SubnetIds'] != [self.h.SUBNET]:
+ raise self._error('ec2', 'describe-subnets', 'InvalidSubnetID.NotFound', str(p['SubnetIds']))
+ return {'Subnets': [dict(SubnetId=self.h.SUBNET, State='available', MapPublicIpOnLaunch=True, VpcId=SIM_VPC,
+ AvailabilityZone=self.h.REGION + 'a', OwnerId=self.h.ACCOUNT,
+ AvailableIpAddressCount=200, CidrBlock='10.0.0.0/24')]}
+
+ def _ec2_describe_security_groups(self, p, f):
+ self._check(p, ['GroupIds'])
+ if p['GroupIds'] != [self.h.SG]:
+ raise self._error('ec2', 'describe-security-groups', 'InvalidGroup.NotFound', str(p['GroupIds']))
+ return {'SecurityGroups': [dict(GroupId=self.h.SG, GroupName='simulated-no-ingress', VpcId=SIM_VPC,
+ OwnerId=self.h.ACCOUNT, Description='simulated', IpPermissions=[],
+ IpPermissionsEgress=[])]}
+
+ def _ec2_run_instances(self, p, f):
+ self._check(p, RUN_FIELDS, ['Monitoring'])
+ op = 'run-instances'
+ token = p['ClientToken']
+ if token in self.launches:
+ if self.launches[token] != p:
+ raise self._error('ec2', op, 'IdempotentParameterMismatch', token)
+ return self._reservation(self.instances[_hex('instance', token)])
+ assert not self.launches, 'FakeAWS models exactly one launch'
+ assert p['MinCount'] == p['MaxCount'] == 1, 'launch count'
+ if p['ImageId'] != self.h.AMI:
+ raise self._error('ec2', op, 'InvalidAMIID.NotFound', p['ImageId'])
+ assert len(p['NetworkInterfaces']) == 1, 'network interface count'
+ net = p['NetworkInterfaces'][0]
+ assert set(net) <= {'DeviceIndex', 'SubnetId', 'Groups', 'AssociatePublicIpAddress', 'DeleteOnTermination'}
+ if net['SubnetId'] != self.h.SUBNET:
+ raise self._error('ec2', op, 'InvalidSubnetID.NotFound', net['SubnetId'])
+ if net['Groups'] != [self.h.SG]:
+ raise self._error('ec2', op, 'InvalidGroup.NotFound', str(net['Groups']))
+ profile = self.profiles.get(p['IamInstanceProfile']['Name'])
+ if set(p['IamInstanceProfile']) != {'Name'} or profile is None:
+ raise self._error('ec2', op, 'InvalidParameterValue', 'Invalid IAM Instance Profile name')
+ iid = 'i-0' + _hex('instance', token, n=16)
+ assert iid not in self.h.FIXED
+ mappings = copy.deepcopy(p['BlockDeviceMappings'])
+ if not any(m['DeviceName'] == '/dev/xvda' for m in mappings):
+ mappings.insert(0, dict(DeviceName='/dev/xvda', Ebs={'DeleteOnTermination': True}))
+ blocks = []
+ for mapping in mappings:
+ assert set(mapping) == {'DeviceName', 'Ebs'} and set(mapping['Ebs']) <= EBS_FIELDS, 'unmodeled block mapping'
+ ebs = mapping['Ebs']
+ vid = 'vol-0' + _hex('volume', iid, mapping['DeviceName'], n=16)
+ volume = dict(VolumeId=vid, Size=ebs.get('VolumeSize', 8), VolumeType=ebs.get('VolumeType', 'gp3'),
+ Encrypted=ebs.get('Encrypted', False), State='in-use', AvailabilityZone=self.h.REGION + 'a',
+ CreateTime=self._now(), Attachments=[dict(InstanceId=iid, Device=mapping['DeviceName'])],
+ Tags=self._tags(p, 'volume'))
+ for src, dst in (('Iops', 'Iops'), ('Throughput', 'Throughput'), ('KmsKeyId', 'KmsKeyId'),
+ ('SnapshotId', 'SnapshotId')):
+ if src in ebs:
+ volume[dst] = ebs[src]
+ self.volumes[vid] = dict(view=volume, delete_on_termination=ebs.get('DeleteOnTermination', True))
+ blocks.append(dict(DeviceName=mapping['DeviceName'], Ebs=dict(
+ VolumeId=vid, Status='attached', AttachTime=volume['CreateTime'],
+ DeleteOnTermination=ebs.get('DeleteOnTermination', True))))
+ meta = {'HttpEndpoint': 'enabled', 'HttpTokens': 'optional', 'HttpPutResponseHopLimit': 1,
+ 'HttpProtocolIpv6': 'disabled', 'InstanceMetadataTags': 'disabled'}
+ meta.update(p['MetadataOptions'])
+ meta['State'] = 'applied'
+ n = len(self.instances) + 1
+ self.instances[iid] = dict(
+ InstanceId=iid, ImageId=p['ImageId'], InstanceType=p['InstanceType'], Architecture='arm64',
+ State={'Code': 0, 'Name': 'pending'}, LaunchTime=self._now(), SubnetId=self.h.SUBNET, VpcId=SIM_VPC,
+ SecurityGroups=[dict(GroupId=self.h.SG, GroupName='simulated-no-ingress')],
+ PrivateIpAddress=f'10.0.0.{n + 10}', PublicIpAddress=f'203.0.113.{n + 10}' if net.get('AssociatePublicIpAddress') else None,
+ MetadataOptions=meta, BlockDeviceMappings=blocks, Tags=self._tags(p, 'instance'),
+ IamInstanceProfile=dict(Arn=profile['Arn'], Id=profile['Id']),
+ Monitoring={'State': 'enabled' if p.get('Monitoring', {}).get('Enabled') else 'disabled'},
+ Placement=dict(AvailabilityZone=self.h.REGION + 'a', Tenancy='default'),
+ UserData=base64.b64encode(p['UserData'].encode() if isinstance(p['UserData'], str) else p['UserData']).decode(),
+ ClientToken=token)
+ if self.instances[iid]['PublicIpAddress'] is None:
+ del self.instances[iid]['PublicIpAddress']
+ self.launches[token] = copy.deepcopy(p)
+ return self._reservation(self.instances[iid])
+
+ @staticmethod
+ def _tags(p, kind):
+ for spec in p.get('TagSpecifications', []):
+ if spec['ResourceType'] == kind:
+ return copy.deepcopy(spec['Tags'])
+ return []
+
+ def _reservation(self, instance):
+ view = {k: v for k, v in instance.items() if k not in ('UserData', 'ClientToken')}
+ return dict(ReservationId='r-0' + _hex('reservation', instance['InstanceId'], n=16),
+ OwnerId=self.h.ACCOUNT, Groups=[], Instances=[view])
+
+ def _advance(self, instance):
+ name = instance['State']['Name']
+ nxt = {'pending': 'running', 'shutting-down': 'terminated'}.get(name)
+ if nxt is None:
+ return
+ instance['State'] = {'Code': STATES[nxt], 'Name': nxt}
+ if nxt == 'terminated':
+ instance.pop('PublicIpAddress', None)
+ for mapping in instance['BlockDeviceMappings']:
+ vid = mapping['Ebs']['VolumeId']
+ if vid in self.volumes and self.volumes[vid]['delete_on_termination']:
+ del self.volumes[vid]
+
+ def _ec2_describe_instances(self, p, f):
+ self._check(p, [], ['InstanceIds', 'Filters'])
+ chosen = list(self.instances.values())
+ if 'InstanceIds' in p:
+ unknown = [i for i in p['InstanceIds'] if i not in self.instances]
+ if unknown:
+ raise self._error('ec2', 'describe-instances', 'InvalidInstanceID.NotFound', str(unknown))
+ chosen = [self.instances[i] for i in p['InstanceIds']]
+ for instance in chosen:
+ self._advance(instance)
+ for flt in p.get('Filters', []):
+ name, values = flt['Name'], flt['Values']
+ if name.startswith('tag:'):
+ chosen = [i for i in chosen if {t['Key']: t['Value'] for t in i['Tags']}.get(name[4:]) in values]
+ elif name == 'instance-id':
+ chosen = [i for i in chosen if i['InstanceId'] in values]
+ elif name == 'instance-state-name':
+ chosen = [i for i in chosen if i['State']['Name'] in values]
+ else:
+ raise AssertionError('unmodeled describe-instances filter: ' + name)
+ return {'Reservations': [self._reservation(i) for i in chosen]}
+
+ def _ec2_describe_instance_attribute(self, p, f):
+ self._check(p, ['InstanceId', 'Attribute'])
+ assert p['Attribute'] == 'userData', 'unmodeled instance attribute'
+ if p['InstanceId'] not in self.instances:
+ raise self._error('ec2', 'describe-instance-attribute', 'InvalidInstanceID.NotFound', p['InstanceId'])
+ return dict(InstanceId=p['InstanceId'], UserData={'Value': self.instances[p['InstanceId']]['UserData']})
+
+ def _ec2_describe_volumes(self, p, f):
+ self._check(p, ['VolumeIds'])
+ unknown = [v for v in p['VolumeIds'] if v not in self.volumes]
+ if unknown:
+ raise self._error('ec2', 'describe-volumes', 'InvalidVolume.NotFound', str(unknown))
+ return {'Volumes': [self.volumes[v]['view'] for v in p['VolumeIds']]}
+
+ def _ec2_terminate_instances(self, p, f):
+ self._check(p, ['InstanceIds'])
+ unknown = [i for i in p['InstanceIds'] if i not in self.instances]
+ if unknown:
+ raise self._error('ec2', 'terminate-instances', 'InvalidInstanceID.NotFound', str(unknown))
+ rows = []
+ for iid in p['InstanceIds']:
+ instance = self.instances[iid]
+ previous = dict(instance['State'])
+ if previous['Name'] in ('pending', 'running'):
+ instance['State'] = {'Code': STATES['shutting-down'], 'Name': 'shutting-down'}
+ rows.append(dict(InstanceId=iid, PreviousState=previous, CurrentState=dict(instance['State'])))
+ return {'TerminatingInstances': rows}
+
+ def _ec2_get_console_output(self, p, f):
+ self._check(p, ['InstanceId'], ['Latest'])
+ instance = self.instances.get(p['InstanceId'])
+ if instance is None:
+ raise self._error('ec2', 'get-console-output', 'InvalidInstanceID.NotFound', p['InstanceId'])
+ polls = self.console_polls[p['InstanceId']] = self.console_polls.get(p['InstanceId'], 0) + 1
+ text = "Cloud-init v. 25.1.4 running 'modules:config' at Wed, 04 Nov 2026 12:00:01 +0000. Up 5.0 seconds.\n"
+ if polls >= 2:
+ run = {t['Key']: t['Value'] for t in instance['Tags']}['witness_run']
+ key = f'root-runner/p3b1-f4-witness/{run}/evidence.tar.gz'
+ if key not in self.objects:
+ self._put(key, self._evidence_tarball())
+ text += ('Cloud-init v. 25.1.4 finished at Wed, 04 Nov 2026 12:01:00 +0000. Datasource DataSourceEc2Local.'
+ ' Up 60.00 seconds\nWITNESS collector-done\n')
+ if polls >= 2:
+ status = dict(rc=0, out='status: done\n')
+ text += 'WITNESS final-cloud-init ' + base64.b64encode(json.dumps(status).encode()).decode() + '\n'
+ return dict(InstanceId=p['InstanceId'], Timestamp=self._now(), Output=text)
+
+ @staticmethod
+ def _evidence_tarball():
+ data = b'{}'
+ raw = io.BytesIO()
+ with gzip.GzipFile(fileobj=raw, mode='wb', mtime=0) as gz:
+ with tarfile.open(fileobj=gz, mode='w') as tar:
+ info = tarfile.TarInfo('evidence.json')
+ info.size, info.mtime, info.mode = len(data), 0, 0o600
+ tar.addfile(info, io.BytesIO(data))
+ return raw.getvalue()
+
+ def _autoscaling_describe_auto_scaling_instances(self, p, f):
+ self._check(p, ['InstanceIds'])
+ return {'AutoScalingInstances': []}
+
+ def _elbv2_describe_target_health(self, p, f):
+ self._check(p, ['TargetGroupArn'])
+ if p['TargetGroupArn'] not in self.h.TGS:
+ raise self._error('elbv2', 'describe-target-health', 'TargetGroupNotFound', p['TargetGroupArn'])
+ port = 80 if self.h.TGS.index(p['TargetGroupArn']) == 0 else 443
+ return {'TargetHealthDescriptions': [dict(Target=dict(Id=i, Port=port), HealthCheckPort=str(port),
+ TargetHealth={'State': 'healthy'}) for i in sorted(self.h.FIXED)]}
diff --git a/scripts/testdata/region-group-f4w1.json b/scripts/testdata/region-group-f4w1.json
new file mode 100644
index 000000000..fa0bf4438
--- /dev/null
+++ b/scripts/testdata/region-group-f4w1.json
@@ -0,0 +1,261 @@
+{
+ "budget": {
+ "runs": [
+ {
+ "owner": "5a69bface70c4690999077000352c8ce",
+ "reserved_at": "2026-11-04T22:13:39.784218+00:00",
+ "run": "f4w1"
+ }
+ ],
+ "schema": 1
+ },
+ "commands": {
+ "carlos-edge-journal": {
+ "argv": [
+ "journalctl",
+ "-b",
+ "-u",
+ "carlos-edge",
+ "--no-pager",
+ "-o",
+ "short-monotonic"
+ ],
+ "out": "[ 42.441367] ip-172-31-9-133 systemd[1]: Starting carlos-edge.service - carlos edge (TLS terminator, host router, activator, release adoption)...\n[ 42.566317] ip-172-31-9-133 systemd[1]: Started carlos-edge.service - carlos edge (TLS terminator, host router, activator, release adoption).\n[ 42.615995] ip-172-31-9-133 (carlos)[1749]: carlos-edge.service: Failed to execute /opt/carlos/carlos: Permission denied\n[ 42.616295] ip-172-31-9-133 (carlos)[1749]: carlos-edge.service: Failed at step EXEC spawning /opt/carlos/carlos: Permission denied\n[ 42.618527] ip-172-31-9-133 systemd[1]: carlos-edge.service: Main process exited, code=exited, status=203/EXEC\n[ 42.780806] ip-172-31-9-133 systemd[1]: carlos-edge.service: Failed with result 'exit-code'.\n",
+ "rc": 0
+ },
+ "carlos-edge-show": {
+ "argv": [
+ "systemctl",
+ "show",
+ "carlos-edge",
+ "-p",
+ "Restart",
+ "-p",
+ "ActiveState",
+ "-p",
+ "ExecMainStartTimestampMonotonic",
+ "-p",
+ "ExecMainStatus",
+ "-p",
+ "Result",
+ "-p",
+ "ExecStartPre",
+ "-p",
+ "RestrictAddressFamilies",
+ "-p",
+ "ReadWritePaths",
+ "-p",
+ "User",
+ "-p",
+ "Group",
+ "-p",
+ "NoNewPrivileges",
+ "-p",
+ "CapabilityBoundingSet",
+ "-p",
+ "AmbientCapabilities",
+ "-p",
+ "ProtectSystem",
+ "-p",
+ "ProtectHome",
+ "-p",
+ "PrivateTmp",
+ "-p",
+ "PrivateDevices",
+ "-p",
+ "ProtectKernelTunables",
+ "-p",
+ "ProtectKernelModules",
+ "-p",
+ "MemoryDenyWriteExecute",
+ "-p",
+ "MainPID"
+ ],
+ "out": "Restart=no\nMainPID=0\nResult=exit-code\nExecMainStartTimestampMonotonic=42565880\nExecMainStatus=203\nExecStartPre={ path=/usr/bin/systemctl ; argv[]=/usr/bin/systemctl start carlos-hairpin-reset.service ; ignore_errors=no ; start_time=[Wed 2026-11-04 22:16:49 UTC] ; stop_time=[Wed 2026-11-04 22:16:49 UTC] ; pid=1730 ; code=exited ; status=0 }\nCapabilityBoundingSet=cap_net_bind_service\nAmbientCapabilities=cap_net_bind_service\nUser=carlos\nGroup=carlos\nReadWritePaths=/data /run/carlos\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectHome=yes\nProtectSystem=strict\nNoNewPrivileges=yes\nRestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK AF_UNIX\nMemoryDenyWriteExecute=yes\nActiveState=failed\n",
+ "rc": 0
+ },
+ "carlos-edge-status": {
+ "argv": [
+ "systemctl",
+ "status",
+ "carlos-edge",
+ "--no-pager"
+ ],
+ "out": "\u00d7 carlos-edge.service - carlos edge (TLS terminator, host router, activator, release adoption)\n Loaded: loaded (/etc/systemd/system/carlos-edge.service; enabled; preset: enabled)\n Drop-In: /etc/systemd/system/carlos-edge.service.d\n \u2514\u250050-group.conf, 60-hairpin.conf\n Active: failed (Result: exit-code) since Wed 2026-11-04 22:16:49 UTC; 2min 1s ago\n Duration: 53ms\n Invocation: c68f10d8564c4b3089803481c39a07ae\n Process: 1730 ExecStartPre=/usr/bin/systemctl start carlos-hairpin-reset.service (code=exited, status=0/SUCCESS)\n Process: 1749 ExecStart=/opt/carlos/carlos agent (code=exited, status=203/EXEC)\n Process: 1754 ExecStopPost=/usr/bin/systemctl start carlos-hairpin-reset.service (code=exited, status=0/SUCCESS)\n Main PID: 1749 (code=exited, status=203/EXEC)\n Mem peak: 2.3M\n CPU: 77ms\n\nNov 04 22:16:49 ip-172-31-9-133 systemd[1]: Starting carlos-edge.service - carlos edge (TLS terminator, host router, activator, release adoption)...\nNov 04 22:16:49 ip-172-31-9-133 systemd[1]: Started carlos-edge.service - carlos edge (TLS terminator, host router, activator, release adoption).\nNov 04 22:16:49 ip-172-31-9-133 (carlos)[1749]: carlos-edge.service: Failed to execute /opt/carlos/carlos: Permission denied\nNov 04 22:16:49 ip-172-31-9-133 (carlos)[1749]: carlos-edge.service: Failed at step EXEC spawning /opt/carlos/carlos: Permission denied\nNov 04 22:16:49 ip-172-31-9-133 systemd[1]: carlos-edge.service: Main process exited, code=exited, status=203/EXEC\nNov 04 22:16:49 ip-172-31-9-133 systemd[1]: carlos-edge.service: Failed with result 'exit-code'.\n",
+ "rc": 3
+ },
+ "carlos-hairpin-reset-journal": {
+ "argv": [
+ "journalctl",
+ "-b",
+ "-u",
+ "carlos-hairpin-reset",
+ "--no-pager",
+ "-o",
+ "short-monotonic"
+ ],
+ "out": "[ 42.474452] ip-172-31-9-133 systemd[1]: Starting carlos-hairpin-reset.service...\n[ 42.561858] ip-172-31-9-133 systemd[1]: carlos-hairpin-reset.service: Deactivated successfully.\n[ 42.562082] ip-172-31-9-133 systemd[1]: Finished carlos-hairpin-reset.service.\n[ 42.666905] ip-172-31-9-133 systemd[1]: Starting carlos-hairpin-reset.service...\n[ 42.777760] ip-172-31-9-133 systemd[1]: carlos-hairpin-reset.service: Deactivated successfully.\n[ 42.777994] ip-172-31-9-133 systemd[1]: Finished carlos-hairpin-reset.service.\n",
+ "rc": 0
+ },
+ "carlos-hairpin-reset-show": {
+ "argv": [
+ "systemctl",
+ "show",
+ "carlos-hairpin-reset",
+ "-p",
+ "Restart",
+ "-p",
+ "ActiveState",
+ "-p",
+ "ExecMainStartTimestampMonotonic",
+ "-p",
+ "ExecMainStatus",
+ "-p",
+ "Result",
+ "-p",
+ "ExecStartPre",
+ "-p",
+ "RestrictAddressFamilies",
+ "-p",
+ "ReadWritePaths",
+ "-p",
+ "User",
+ "-p",
+ "Group",
+ "-p",
+ "NoNewPrivileges",
+ "-p",
+ "CapabilityBoundingSet",
+ "-p",
+ "AmbientCapabilities",
+ "-p",
+ "ProtectSystem",
+ "-p",
+ "ProtectHome",
+ "-p",
+ "PrivateTmp",
+ "-p",
+ "PrivateDevices",
+ "-p",
+ "ProtectKernelTunables",
+ "-p",
+ "ProtectKernelModules",
+ "-p",
+ "MemoryDenyWriteExecute",
+ "-p",
+ "MainPID"
+ ],
+ "out": "Restart=no\nMainPID=0\nResult=success\nExecMainStartTimestampMonotonic=0\nExecMainStatus=0\nCapabilityBoundingSet=cap_chown cap_dac_override cap_dac_read_search cap_fowner cap_fsetid cap_kill cap_setgid cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config cap_mknod cap_lease cap_audit_write cap_audit_control cap_setfcap cap_mac_override cap_mac_admin cap_syslog cap_wake_alarm cap_block_suspend cap_audit_read cap_perfmon cap_bpf cap_checkpoint_restore\nAmbientCapabilities=\nUser=\nGroup=\nReadWritePaths=\nPrivateTmp=no\nPrivateDevices=no\nProtectKernelTunables=no\nProtectKernelModules=no\nProtectHome=no\nProtectSystem=no\nNoNewPrivileges=no\nRestrictAddressFamilies=~\nMemoryDenyWriteExecute=no\nActiveState=inactive\n",
+ "rc": 0
+ },
+ "carlos-instance-control-show": {
+ "argv": [
+ "systemctl",
+ "show",
+ "carlos-instance-control",
+ "-p",
+ "Restart",
+ "-p",
+ "ActiveState",
+ "-p",
+ "ExecMainStartTimestampMonotonic",
+ "-p",
+ "ExecMainStatus",
+ "-p",
+ "Result",
+ "-p",
+ "ExecStartPre",
+ "-p",
+ "RestrictAddressFamilies",
+ "-p",
+ "ReadWritePaths",
+ "-p",
+ "User",
+ "-p",
+ "Group",
+ "-p",
+ "NoNewPrivileges",
+ "-p",
+ "CapabilityBoundingSet",
+ "-p",
+ "AmbientCapabilities",
+ "-p",
+ "ProtectSystem",
+ "-p",
+ "ProtectHome",
+ "-p",
+ "PrivateTmp",
+ "-p",
+ "PrivateDevices",
+ "-p",
+ "ProtectKernelTunables",
+ "-p",
+ "ProtectKernelModules",
+ "-p",
+ "MemoryDenyWriteExecute",
+ "-p",
+ "MainPID"
+ ],
+ "out": "Restart=no\nMainPID=0\nResult=success\nExecMainStartTimestampMonotonic=0\nExecMainStatus=0\nCapabilityBoundingSet=cap_chown cap_dac_override cap_dac_read_search cap_fowner cap_fsetid cap_kill cap_setgid cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock cap_ipc_owner cap_sys_chroot cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config cap_lease cap_audit_write cap_audit_control cap_setfcap cap_mac_override cap_mac_admin cap_wake_alarm cap_block_suspend cap_audit_read cap_perfmon cap_bpf cap_checkpoint_restore\nAmbientCapabilities=\nUser=\nGroup=\nReadWritePaths=/run/carlos-control /run/systemd/system -/run/carlos-hairpin\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectHome=yes\nProtectSystem=strict\nNoNewPrivileges=no\nRestrictAddressFamilies=AF_NETLINK AF_UNIX\nMemoryDenyWriteExecute=yes\nActiveState=inactive\n",
+ "rc": 0
+ }
+ },
+ "edge_process_status": "",
+ "mounts": {
+ "/data/instances": {
+ "dev": 66305,
+ "findmnt": {
+ "argv": [
+ "findmnt",
+ "-T",
+ "/data/instances",
+ "-o",
+ "TARGET,SOURCE,FSTYPE,OPTIONS"
+ ],
+ "out": "TARGET SOURCE FSTYPE OPTIONS\n/data/instances /dev/nvme0n1p1[/data/.instances] ext4 rw,nosuid,nodev,noexec,relatime,nosymfollow,discard,errors=remount-ro\n",
+ "rc": 0
+ },
+ "flags": 12302,
+ "noexec": true,
+ "probe": "/data/instances",
+ "realpath": "/data/instances"
+ },
+ "/run/carlos/instances": {
+ "dev": 27,
+ "findmnt": {
+ "argv": [
+ "findmnt",
+ "-T",
+ "/run/carlos/instances",
+ "-o",
+ "TARGET,SOURCE,FSTYPE,OPTIONS"
+ ],
+ "out": "TARGET SOURCE FSTYPE OPTIONS\n/run/carlos/instances tmpfs[/carlos/.instances] tmpfs rw,nosuid,nodev,noexec,relatime,nosymfollow,size=95028k,mode=755,inode64\n",
+ "rc": 0
+ },
+ "flags": 12302,
+ "noexec": true,
+ "probe": "/run/carlos/instances",
+ "realpath": "/run/carlos/instances"
+ },
+ "/run/carlos/logs": {
+ "dev": 27,
+ "findmnt": {
+ "argv": [
+ "findmnt",
+ "-T",
+ "/run/carlos/logs",
+ "-o",
+ "TARGET,SOURCE,FSTYPE,OPTIONS"
+ ],
+ "out": "TARGET SOURCE FSTYPE OPTIONS\n/run/carlos/logs tmpfs[/carlos/.logs] tmpfs rw,nosuid,nodev,noexec,relatime,nosymfollow,size=95028k,mode=755,inode64\n",
+ "rc": 0
+ },
+ "flags": 12302,
+ "noexec": true,
+ "probe": "/run/carlos/logs",
+ "realpath": "/run/carlos/logs"
+ }
+ },
+ "source": "witness-f4w1/x/evidence.json; selected fields copied without modification; budget copied from witness-budget.json"
+}
diff --git a/scripts/witness-pointer/main.go b/scripts/witness-pointer/main.go
new file mode 100644
index 000000000..7ce77d638
--- /dev/null
+++ b/scripts/witness-pointer/main.go
@@ -0,0 +1,57 @@
+package main
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type pointerStore struct {
+ release.Store
+ body []byte
+}
+
+func (s pointerStore) Get(_ context.Context, key string) ([]byte, string, error) {
+ if key != release.SystemPointerKey("router", "stable") {
+ return nil, "", fmt.Errorf("unexpected key %q", key)
+ }
+ return s.body, "local", nil
+}
+
+func verify(pointerPath, pubkeyPath string) (*release.SystemPointer, error) {
+ body, err := os.ReadFile(pointerPath)
+ if err != nil {
+ return nil, err
+ }
+ key, err := os.ReadFile(pubkeyPath)
+ if err != nil {
+ return nil, err
+ }
+ pub, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(key)))
+ if err != nil || len(pub) != ed25519.PublicKeySize {
+ return nil, fmt.Errorf("invalid release public key")
+ }
+ p, _, err := release.GetSystemPointer(context.Background(), pointerStore{body: body}, ed25519.PublicKey(pub), "router", "stable")
+ return p, err
+}
+
+func main() {
+ if len(os.Args) != 3 {
+ fmt.Fprintln(os.Stderr, "usage: witness-pointer POINTER PUBKEY")
+ os.Exit(2)
+ }
+ p, err := verify(os.Args[1], os.Args[2])
+ if err == nil {
+ err = json.NewEncoder(os.Stdout).Encode(p)
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
diff --git a/scripts/witness-pointer/main_test.go b/scripts/witness-pointer/main_test.go
new file mode 100644
index 000000000..663c9c709
--- /dev/null
+++ b/scripts/witness-pointer/main_test.go
@@ -0,0 +1,54 @@
+package main
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestVerifyUsesReleasePointerValidation(t *testing.T) {
+ pub, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ keyPath, pointerPath := filepath.Join(dir, "pub"), filepath.Join(dir, "pointer")
+ if err := os.WriteFile(keyPath, []byte(base64.StdEncoding.EncodeToString(pub)+"\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ payload := `{"schema":1,"component":"router","channel":"stable","current":{"version":"v0.34.2","artifacts":{"linux-arm64":{"key":"bootstrap/router/v0.34.2/carlos-linux-arm64","sha256":"f837b3763457825d469c89cde80fb85fd45f50fd1872a8d53147d53fdebfdc01"}}},"spread":"0s","promoted_at":"2026-11-04T17:34:03Z"}`
+ encoded := base64.StdEncoding.EncodeToString([]byte(payload))
+ sig := base64.StdEncoding.EncodeToString(ed25519.Sign(priv, []byte(encoded)))
+ for _, tc := range []struct {
+ name, body, signature string
+ grant any
+ ok bool
+ }{
+ {"valid", encoded, sig, nil, true},
+ {"tampered payload", encoded + "A", sig, nil, false},
+ {"bad signature", encoded, "AA==", nil, false},
+ {"scoped signer", encoded, sig, map[string]string{"key": "x"}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ wrapper := map[string]any{"payload": tc.body, "sig": tc.signature}
+ if tc.grant != nil {
+ wrapper["grant"] = tc.grant
+ }
+ raw, err := json.Marshal(wrapper)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(pointerPath, raw, 0600); err != nil {
+ t.Fatal(err)
+ }
+ _, err = verify(pointerPath, keyPath)
+ if (err == nil) != tc.ok {
+ t.Fatalf("verify error = %v; want success %v", err, tc.ok)
+ }
+ })
+ }
+}