carlos / platform Public

region HA P3b-2 ops: Step 3 fault harness and rehearsal (B5)

claude agent, operated by paul@keymail.dev a8fa2065266af54cd8ae0ae717f57a5c40f8c42a parent 87d4d7b
11 files changed, +1,585 −6
  • infra/modules/region-group-operator-document/harness-pattern.txt +1 −1
  • scripts/region-group-fault/README.md +94 −0
  • scripts/region-group-fault/bundle.py +36 −0
  • scripts/region-group-fault/client.py +70 −0
  • scripts/region-group-fault/fault.py +396 −0
  • scripts/region-group-fault/fault.sh +15 −0
  • scripts/region-group-fault/rehearse.py +467 −0
  • scripts/region-group-fault/text.json +17 −0
  • scripts/region_group_document_test.py +2 −2
  • scripts/region_group_fault_test.py +484 −0
  • scripts/region_group_frames.py +3 −3
diff --git a/infra/modules/region-group-operator-document/harness-pattern.txt b/infra/modules/region-group-operator-document/harness-pattern.txt
index 2c9db6887..528a0b767 100644
--- a/infra/modules/region-group-operator-document/harness-pattern.txt
+++ b/infra/modules/region-group-operator-document/harness-pattern.txt
@@ -1 +1 @@
-/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((umask 077 && mkdir -p -m 0700 /run/carlos-p3b2-fault && printf %s [A-Za-z0-9+/=]{1,1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1} > /run/carlos-p3b2-fault/bundle\.b64 && base64 -d /run/carlos-p3b2-fault/bundle\.b64 > /run/carlos-p3b2-fault/bundle\.tar && \[ "\$\(sha256sum /run/carlos-p3b2-fault/bundle\.tar \| cut -c1-64\)" = HARNESS_SHA256 \] && mkdir -p -m 0700 /usr/local/lib/carlos-p3b2-fault && tar --no-same-owner --no-same-permissions -x -f /run/carlos-p3b2-fault/bundle\.tar -C /usr/local/lib/carlos-p3b2-fault && /bin/sh /usr/local/lib/carlos-p3b2-fault/fault\.sh install|/bin/sh /usr/local/lib/carlos-p3b2-fault/fault\.sh ((status|disarm|remove|uninstall)|(arm-fault|arm-pause) --iid i-([0-9a-f]{8}|[0-9a-f]{17}) --boot [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} --transaction [A-Za-z0-9_-]{1,80} --minutes [1-9][0-9]{0,2}))\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"'
+/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((umask 077 && mkdir -p -m 0700 /run/carlos-p3b2-fault && printf %s [A-Za-z0-9+/=]{1,1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1} > /run/carlos-p3b2-fault/bundle\.b64 && base64 -d /run/carlos-p3b2-fault/bundle\.b64 > /run/carlos-p3b2-fault/bundle\.tar && \[ "\$\(sha256sum /run/carlos-p3b2-fault/bundle\.tar \| cut -c1-64\)" = HARNESS_SHA256 \] && mkdir -p -m 0700 /usr/local/lib/carlos-p3b2-fault && tar --no-same-owner --no-same-permissions -x -f /run/carlos-p3b2-fault/bundle\.tar -C /usr/local/lib/carlos-p3b2-fault && /bin/sh /usr/local/lib/carlos-p3b2-fault/fault\.sh install|/bin/sh /usr/local/lib/carlos-p3b2-fault/fault\.sh ((status|disarm|remove|uninstall)|(arm-fault|arm-pause|fault-now) --iid i-([0-9a-f]{8}|[0-9a-f]{17}) --boot [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} --transaction [A-Za-z0-9_-]{1,80} --minutes [1-9][0-9]{0,2}))\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"'
diff --git a/scripts/region-group-fault/README.md b/scripts/region-group-fault/README.md
new file mode 100644
index 000000000..3ebdbb16c
--- /dev/null
+++ b/scripts/region-group-fault/README.md
@@ -0,0 +1,94 @@
+# Attended member fault harness
+
+Block one member's public HTTPS traffic for the Standby witness. Use a reviewed
+bundle through the approved session document's Branch H, after the controller
+rehearses it on the pinned build. B5 implementation made no live AWS calls.
+
+```sh
+python3 scripts/region-group-fault/bundle.py --output '<evidence-dir>/bundle.tar'
+```
+
+Record the printed SHA256 and set B2's `harness_bundle_sha256` to that digest
+for the approved window. `client.py` builds commands with
+`region_group_frames.py`. Each call requires `--profile`, `--region`,
+`--document` and `--target`; `--dry-run` prints the exact command.
+Arming also requires `--iid` matching the target, `--boot`, `--transaction`
+and `--minutes 35`. There are no deployment defaults.
+
+| Verb | Effect |
+| --- | --- |
+| `install` | Deliver and hash-check the deterministic bundle. Log installation. |
+| `status` | Return framed JSON, at most 8 KiB: installed hashes, marker state, drop-in, table, counters, timer and recent log lines. |
+| `arm-fault` | Validate iid and boot, then write the root-only marker and edge pre-start drop-in. |
+| `fault-now` | Validate iid and boot, then inject without a permit for the separate already-admitted live-process fault. It cuts its own SSM session. |
+| `arm-pause` | Arm the pre-start boundary for user `carlos`. Root SSM remains reachable for Step 6 rollback. |
+| `remove` | Delete only `inet carlos_p3b2_fault` and verify absence. Leave marker, drop-in and timer alone. |
+| `disarm` | Remove the pending marker and drop-in, then reload systemd. Leave an active fault and its timer alone. |
+| `uninstall` | Remove the fault, disarm, stop expiry units and delete installed files and harness state. Return cleanup evidence. Export the full log first. |
+
+For Window B, deliver, read status and compare hashes. Rehearse expiry on the
+member before injecting. Record the short `fault-now` outage separately from
+the roll. After recovery, arm the restart fault, run the attended roll and
+observe Standby. After expiry, read status and verify the table is absent.
+Export the log, uninstall, then check the table, drop-in, expiry units,
+installed directory and state directory are gone. Disable Branch H afterward.
+
+For Step 6, arm the pause before the roll. The new edge cannot reach public
+HTTPS, keeping admission closed before Exit intent. Use the existing operator's
+rollback for the same transaction while root SSM works. Remove the pause when
+ready to observe rollback readiness and perform the guarded return. Act within
+the pause's expiry bound.
+
+## Local evidence and removal
+
+The root-only `/var/lib/carlos-p3b2-fault/log.jsonl` records UTC arm/consume
+times, timer activation and verification, table addition, counters, expiry and
+removal readback. It is append-only until uninstall. Export it first: uninstall
+removes harness state. A lost SSM response is uncertain; inspect local evidence
+after access returns.
+
+The rules drop TCP/UDP 443 and matching replies outside IMDSv2-reported VPC
+IPv4 CIDRs, 127/8 and 169.254/16. DNS, NTP, metadata and private peer traffic
+remain available. Metrics, queues, EC2 API traffic and ACME are also affected.
+IPv6 HTTPS uses a separate expiring set.
+
+Pause mode marks only `carlos` output connections with `0xc350b205`; input
+rules require that mark and established state. An existing flow is marked on
+its next outbound packet. Reserve that mark in the member's policy: connection
+marks can outlive removal of the table and are not cleared by this harness.
+
+The local expiry timer is verified before injection. Kernel set timeouts are
+a second removal mechanism. Unsupported interval timeouts produce a warning
+and timer-only operation; the kernel-expiry rehearsal must fail in that case.
+Expiry never acquires the operator lock, restarts a service or makes a network
+call. The pre-start hook always returns zero. It waits for a separate root
+worker, capped at 60 seconds, because the edge's address-family sandbox excludes
+nftables' netlink socket. It never initiates an edge restart.
+
+## Controller rehearsal
+
+`rehearse.py` requires profile, region, subnet, security group, instance profile,
+AMI, bucket, key prefix, pinned binary path and SHA256, pinned commit and evidence
+directory. Use `--help` for flag spelling. `--dry-run` prints every AWS command
+as a JSON argument array, including teardown, without invoking AWS. It still
+checks the local binary hash and pinned git unit paths.
+
+The driver tests pre-start expiry, consumed-marker refusal, kernel expiry,
+pause isolation and drop-in survival on one disposable `t4g.small`. An independent
+local probe records root and `carlos` HTTPS transport results for S3 and SSM.
+HTTP error responses count as working transport. Session Manager `NotConnected`
+is recorded separately from the slower agent `PingStatus`.
+
+The kernel phase delays the timer to five minutes while elements last one
+minute. This root-only rehearsal switch is not a Branch H verb and must never
+be installed on a group member. The repair phase compares the marker and
+`90-p3b2-fault.conf` hashes across rewriting `50-group.conf` and invoking the
+pinned `adopt` entry. Read adopt's saved exit code: a refusal does not prove
+that guarded repair completed.
+
+Each run retains private local evidence under its run token and uploads it,
+the bundle and pinned binary under the supplied S3 prefix. The driver always
+requests termination, retries failures and waits for the terminated state.
+Unresolved cleanup prints `LEAKED`. Retain uploaded evidence under the card's
+policy. Operator wording is centralized in `text.json` and the frame helper's
+`TEXT` table for the controller's later copy pass.
diff --git a/scripts/region-group-fault/bundle.py b/scripts/region-group-fault/bundle.py
new file mode 100644
index 000000000..e246be709
--- /dev/null
+++ b/scripts/region-group-fault/bundle.py
@@ -0,0 +1,36 @@
+import argparse
+import hashlib
+import io
+import json
+from pathlib import Path
+import tarfile
+
+TEXT = json.loads(Path(__file__).with_name('text.json').read_text())
+
+MEMBERS = ('fault.py', 'fault.sh', 'text.json')
+
+
+def build(directory=None):
+ directory = Path(directory) if directory else Path(__file__).parent
+ out = io.BytesIO()
+ with tarfile.open(fileobj=out, mode='w', format=tarfile.USTAR_FORMAT) as tar:
+ for name in sorted(MEMBERS):
+ data = (directory / name).read_bytes()
+ entry = tarfile.TarInfo(name)
+ entry.size = len(data)
+ entry.mtime = entry.uid = entry.gid = 0
+ entry.mode = 0o600
+ tar.addfile(entry, io.BytesIO(data))
+ value = out.getvalue()
+ if len(value) > 45000:
+ raise ValueError(TEXT['bundle_size'])
+ return value
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--output', type=Path, required=True)
+ args = parser.parse_args()
+ data = build()
+ args.output.write_bytes(data)
+ print(hashlib.sha256(data).hexdigest())
diff --git a/scripts/region-group-fault/client.py b/scripts/region-group-fault/client.py
new file mode 100644
index 000000000..b79bc31bc
--- /dev/null
+++ b/scripts/region-group-fault/client.py
@@ -0,0 +1,70 @@
+import argparse
+import base64
+import hashlib
+import json
+from pathlib import Path
+import re
+import sys
+import uuid
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+from scripts import region_group_frames as frames
+from bundle import build
+
+TEXT = json.loads(Path(__file__).with_name('text.json').read_text())
+
+
+def command(verb, nonce, **fields):
+ if verb == 'install':
+ data = build()
+ return frames.install_command(base64.b64encode(data).decode(), hashlib.sha256(data).hexdigest(), nonce)
+ return frames.harness_command(verb, nonce, **fields)
+
+
+def result(output, nonce):
+ rows = re.findall(re.escape(nonce) + r':BEGIN\r?\n(.*?)\r?\n' +
+ re.escape(nonce) + r':END:([0-9]+)(?:\r?\n|$)', output, re.S)
+ if len(rows) != 1 or rows[0][1] != '0' or len(rows[0][0].encode()) > 8192:
+ raise RuntimeError(TEXT['remote'])
+ return rows[0][0]
+
+
+def send(config, iid, verb, **fields):
+ nonce = uuid.uuid4().hex
+ cmd = command(verb, nonce, **fields)
+ adapter = frames.roll.AWS(config)
+ try:
+ output = adapter.invoke('ssm', 'start-session', ['--target', iid,
+ '--document-name', config['document'], '--parameters', json.dumps({'command': [cmd]})],
+ timeout=120, raw=True)
+ return result(output, nonce)
+ finally:
+ if adapter.last_session_id:
+ adapter.invoke('ssm', 'terminate-session', ['--session-id', adapter.last_session_id])
+
+
+def main():
+ p = argparse.ArgumentParser(description=TEXT['required'])
+ for name in ('profile', 'region', 'document', 'target'):
+ p.add_argument('--' + name, required=True)
+ p.add_argument('verb', choices=['install', 'status', 'arm-fault', 'arm-pause', 'fault-now',
+ 'disarm', 'remove', 'uninstall'])
+ for name in ('iid', 'boot', 'transaction', 'minutes'):
+ p.add_argument('--' + name)
+ p.add_argument('--dry-run', action='store_true')
+ a = p.parse_args()
+ fields = {key: getattr(a, key) for key in ('iid', 'boot', 'transaction', 'minutes')
+ if getattr(a, key) is not None}
+ if a.verb == 'install' and fields:
+ p.error(TEXT['required'])
+ if 'iid' in fields and fields['iid'] != a.target:
+ p.error(TEXT['required'])
+ if a.dry_run:
+ print(command(a.verb, uuid.uuid4().hex, **fields))
+ else:
+ print(send(dict(profile=a.profile, region=a.region, document=a.document),
+ a.target, a.verb, **fields))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/region-group-fault/fault.py b/scripts/region-group-fault/fault.py
new file mode 100644
index 000000000..336e1c1d6
--- /dev/null
+++ b/scripts/region-group-fault/fault.py
@@ -0,0 +1,396 @@
+import fcntl
+import hashlib
+import ipaddress
+import json
+import os
+from pathlib import Path
+import re
+import stat
+import subprocess
+import sys
+import time
+
+TEXT = json.loads(Path(__file__).with_name('text.json').read_text())
+TABLE = 'carlos_p3b2_fault'
+TIMER = 'carlos-p3b2-fault-expire'
+LIB = '/usr/local/lib/carlos-p3b2-fault'
+STATE = '/var/lib/carlos-p3b2-fault'
+DROP = '/etc/systemd/system/carlos-edge.service.d/90-p3b2-fault.conf'
+PERMIT = '/run/carlos-group-maintenance/permit.json'
+MARK = '0xc350b205'
+FILES = ('fault.sh', 'fault.py', 'text.json')
+
+
+def require(ok):
+ if not ok:
+ raise ValueError(TEXT['unsafe'])
+
+
+def run(*args, data=None, check=True, timeout=15):
+ p = subprocess.run(args, input=data, text=True, capture_output=True, timeout=timeout)
+ if check:
+ require(p.returncode == 0)
+ return p
+
+
+def span(value):
+ # systemctl renders monotonic microseconds as a timespan on some versions.
+ if value.isdecimal():
+ return int(value) / 1000000
+ units = {'us': 1e-6, 'ms': .001, 's': 1, 'min': 60, 'h': 3600,
+ 'd': 86400, 'w': 604800, 'month': 2629800, 'y': 31557600}
+ parts = re.findall(r'([0-9]+(?:\.[0-9]+)?)(us|ms|min|month|s|h|d|w|y)', value)
+ require(parts and ''.join(a + b for a, b in parts) == value.replace(' ', ''))
+ return sum(float(a) * units[b] for a, b in parts)
+
+
+class Harness:
+ def __init__(self):
+ test = os.environ.get('CARLOS_P3B2_FAULT_TEST_ROOT')
+ require(not (test is not None and os.geteuid() == 0))
+ require(test is not None or os.geteuid() == 0)
+ require(test is None or (test.startswith('/') and Path(test).is_dir()))
+ self.root = test or ''
+ self.owner = os.geteuid() if test else 0
+ self.state = self.path(STATE)
+
+ def path(self, value):
+ return Path(self.root + value)
+
+ def directory(self, path, mode=0o700):
+ # Check every ancestor before creating a root-owned destination.
+ current = Path(self.root) if self.root else Path(path.anchor)
+ for part in path.relative_to(current).parts:
+ current /= part
+ if not current.exists():
+ current.mkdir(mode=mode if current == path else 0o755)
+ s = current.lstat()
+ require(stat.S_ISDIR(s.st_mode) and s.st_uid in {0, self.owner}
+ and not s.st_mode & 0o022)
+ require(path.stat().st_uid == self.owner)
+ path.chmod(mode)
+
+ def read(self, path, limit=8192):
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
+ with os.fdopen(fd, 'rb') as f:
+ s = os.fstat(f.fileno())
+ require(stat.S_ISREG(s.st_mode) and s.st_uid == self.owner
+ and not s.st_mode & 0o022 and s.st_nlink == 1 and s.st_size <= limit)
+ return f.read(limit).decode()
+
+ def write(self, path, data):
+ tmp = path.with_name(path.name + '.new')
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, 'w') as f:
+ f.write(data)
+ f.flush()
+ os.fsync(f.fileno())
+ os.replace(tmp, path)
+ self.sync(path.parent)
+
+ def sync(self, directory):
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+
+ def log(self, event, **values):
+ row = dict(at=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
+ event=event, **values)
+ fd = os.open(self.state / 'log.jsonl', os.O_WRONLY | os.O_APPEND | os.O_CREAT |
+ os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, 'a') as f:
+ s = os.fstat(f.fileno())
+ require(s.st_uid == self.owner and stat.S_ISREG(s.st_mode) and s.st_nlink == 1)
+ f.write(json.dumps(row, separators=(',', ':')) + '\n')
+ f.flush()
+ os.fsync(f.fileno())
+
+ def imds(self):
+ token = run('curl', '--noproxy', '*', '-fsS', '--connect-timeout', '2',
+ '--max-time', '3', '-X', 'PUT', '-H',
+ 'X-aws-ec2-metadata-token-ttl-seconds: 60',
+ 'http://169.254.169.254/latest/api/token').stdout.strip()
+ require(token and '\n' not in token)
+ def get(key):
+ return run('curl', '--noproxy', '*', '-fsS', '--connect-timeout', '2',
+ '--max-time', '3', '-H', 'X-aws-ec2-metadata-token: ' + token,
+ 'http://169.254.169.254/latest/meta-data/' + key).stdout.strip()
+ iid = get('instance-id')
+ macs = get('network/interfaces/macs/').split()
+ require(1 <= len(macs) <= 32)
+ cidrs = []
+ for mac in macs:
+ require(re.fullmatch(r'(?:[0-9a-f]{2}:){5}[0-9a-f]{2}/', mac))
+ cidrs += get('network/interfaces/macs/' + mac + 'vpc-ipv4-cidr-blocks').split()
+ require(cidrs and len(cidrs) <= 128)
+ nets = [ipaddress.IPv4Network(c, strict=True) for c in cidrs]
+ require(all(n.prefixlen > 0 for n in nets))
+ return iid, nets
+
+ def identity(self, marker, permit):
+ require(set(marker) == {'mode', 'iid', 'boot_id', 'transaction', 'minutes', 'armed_at'})
+ require(marker['mode'] in {'fault', 'pause'})
+ require(re.fullmatch(r'i-(?:[0-9a-f]{8}|[0-9a-f]{17})', marker['iid']))
+ require(re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', marker['boot_id']))
+ require(re.fullmatch(r'[A-Za-z0-9_-]{1,80}', marker['transaction']))
+ require(type(marker['minutes']) is int and 1 <= marker['minutes'] <= 999)
+ require(type(marker['armed_at']) in {int, float} and
+ 0 <= time.time() - marker['armed_at'] <= 3600)
+ require(marker['boot_id'] == self.path('/proc/sys/kernel/random/boot_id').read_text().strip())
+ if permit:
+ p = json.loads(self.read(self.path(PERMIT)))
+ require(p.get('transaction') == marker['transaction'])
+ iid, nets = self.imds()
+ require(marker['iid'] == iid)
+ return nets
+
+ def table(self):
+ p = run('nft', '-j', 'list', 'table', 'inet', TABLE, check=False)
+ if p.returncode:
+ require('No such file or directory' in p.stderr)
+ return None
+ return json.loads(p.stdout)
+
+ def timer(self):
+ p = run('systemctl', 'show', TIMER + '.timer', '--property=ActiveState',
+ '--property=NextElapseUSecMonotonic', check=False)
+ require(p.returncode == 0)
+ return dict(line.split('=', 1) for line in p.stdout.splitlines() if '=' in line)
+
+ def rules(self, marker, nets, timeout=True):
+ allowed = nets + [ipaddress.IPv4Network('127.0.0.0/8'),
+ ipaddress.IPv4Network('169.254.0.0/16')]
+ remaining = [ipaddress.IPv4Network('0.0.0.0/0')]
+ for skip in ipaddress.collapse_addresses(allowed):
+ out = []
+ for net in remaining:
+ if net.subnet_of(skip):
+ continue
+ out.extend(net.address_exclude(skip) if skip.subnet_of(net) else [net])
+ remaining = out
+ ttl = ' timeout %dm' % marker['minutes'] if timeout else ''
+ flags = 'interval, timeout' if timeout else 'interval'
+ v4 = ', '.join(str(n) + ttl for n in sorted(remaining))
+ rows = [f'add table inet {TABLE}',
+ f'add set inet {TABLE} fault_dst {{ type ipv4_addr; flags {flags}; }}',
+ f'add element inet {TABLE} fault_dst {{ {v4} }}',
+ f'add set inet {TABLE} fault_dst6 {{ type ipv6_addr; flags {flags}; }}',
+ f'add element inet {TABLE} fault_dst6 {{ ::/0{ttl} }}',
+ f'add chain inet {TABLE} output {{ type filter hook output priority -10; policy accept; }}',
+ f'add chain inet {TABLE} input {{ type filter hook input priority -10; policy accept; }}']
+ pause = marker['mode'] == 'pause'
+ uid = 'meta skuid "carlos" ' if pause else ''
+ mark = f'ct mark set {MARK} ' if pause else ''
+ inbound = f'ct state established ct mark {MARK} ' if pause else ''
+ for family, addrset in [('ip', 'fault_dst'), ('ip6', 'fault_dst6')]:
+ rows += [f'add rule inet {TABLE} output {uid}meta l4proto {{ tcp, udp }} '
+ f'th dport 443 {family} daddr @{addrset} {mark}counter drop',
+ f'add rule inet {TABLE} input {inbound}meta l4proto {{ tcp, udp }} '
+ f'th sport 443 {family} saddr @{addrset} counter drop']
+ return '\n'.join(rows) + '\n'
+
+ def inject(self, marker, nets):
+ require(self.table() is None)
+ minutes = marker['minutes']
+ # Only the isolated rehearsal runner writes this root-owned file.
+ delay = self.state / 'rehearsal-timer-minutes'
+ timer_minutes = minutes
+ if delay.exists():
+ timer_minutes = int(self.read(delay))
+ require(minutes < timer_minutes <= 10)
+ self.log('rehearsal', message=TEXT['rehearsal'], minutes=timer_minutes)
+ run('systemd-run', '--unit=' + TIMER, '--collect',
+ '--on-active=%dm' % timer_minutes, '--timer-property=AccuracySec=1s',
+ '--timer-property=RemainAfterElapse=no',
+ '/bin/sh', str(self.path(LIB + '/fault.sh')), 'expire')
+ self.log('timer-armed', minutes=timer_minutes)
+ timer = self.timer()
+ remaining = span(timer.get('NextElapseUSecMonotonic', '0')) - time.monotonic()
+ require(timer.get('ActiveState') == 'active' and 0 < remaining <= timer_minutes * 60 + 1)
+ self.log('timer-verified', timer=timer, remaining=remaining)
+ rules = self.rules(marker, nets)
+ if run('nft', '-c', '-f', '-', data=rules, check=False).returncode:
+ rules = self.rules(marker, nets, timeout=False)
+ run('nft', '-c', '-f', '-', data=rules)
+ self.log('timer-only', message=TEXT['fallback'])
+ print(TEXT['fallback'], file=sys.stderr)
+ timer = self.timer()
+ remaining = span(timer.get('NextElapseUSecMonotonic', '0')) - time.monotonic()
+ require(timer.get('ActiveState') == 'active' and 35 < remaining <= timer_minutes * 60 + 1)
+ run('nft', '-f', '-', data=rules)
+ table = self.table()
+ require(table is not None)
+ self.log('table-added', mode=marker['mode'], transaction=marker['transaction'],
+ minutes=minutes, kernel_timeout='flags interval, timeout' in rules,
+ rules_sha256=hashlib.sha256(rules.encode()).hexdigest())
+ self.log('counters', packets=packets(table))
+
+ def arm(self, verb, args):
+ require(len(args) == 8 and args[::2] == ['--iid', '--boot', '--transaction', '--minutes'])
+ require(re.fullmatch(r'[1-9][0-9]{0,2}', args[7]))
+ marker = dict(mode='pause' if verb == 'arm-pause' else 'fault', iid=args[1],
+ boot_id=args[3], transaction=args[5], minutes=int(args[7]), armed_at=time.time())
+ nets = self.identity(marker, False)
+ require(not (self.state / 'marker.json').exists())
+ require(self.table() is None)
+ if verb == 'fault-now':
+ self.log('fault-now', **marker)
+ self.inject(marker, nets)
+ return
+ self.directory(self.path(DROP).parent, 0o755)
+ self.write(self.state / 'marker.json', json.dumps(marker))
+ self.write(self.path(DROP), '[Service]\nExecStartPre=+/bin/sh ' + LIB + '/fault.sh prestart\n')
+ run('systemctl', 'daemon-reload')
+ self.log('arm', **marker)
+
+ def prestart(self):
+ path = self.state / 'marker.json'
+ if not path.exists():
+ return
+ marker = json.loads(self.read(path))
+ nets = self.identity(marker, True)
+ # Rename while holding the harness lock, before timer or nft mutation.
+ os.replace(path, self.state / 'consumed.json')
+ self.sync(self.state)
+ self.log('consume', **marker)
+ self.inject(marker, nets)
+
+ def remove(self, event, evidence=True):
+ def record(kind, **values):
+ if evidence:
+ try:
+ self.log(kind, **values)
+ except (OSError, ValueError):
+ print(TEXT['log_failed'], file=sys.stderr)
+
+ table = self.table()
+ if table is not None:
+ record('counters', packets=packets(table))
+ run('nft', 'delete', 'table', 'inet', TABLE, check=False)
+ require(self.table() is None)
+ record(event)
+ record('removal-readback', table_present=False)
+
+ def disarm(self):
+ (self.state / 'marker.json').unlink(missing_ok=True)
+ self.path(DROP).unlink(missing_ok=True)
+ run('systemctl', 'daemon-reload')
+ self.log('disarm')
+
+ def status(self):
+ table = self.table()
+ hashes = {f: hashlib.sha256(self.read(self.path(LIB + '/' + f), 40000).encode()).hexdigest()
+ for f in FILES}
+ marker = 'armed' if (self.state / 'marker.json').exists() else (
+ 'consumed' if (self.state / 'consumed.json').exists() else 'absent')
+ with open(self.state / 'log.jsonl', 'rb') as f:
+ f.seek(max(0, os.fstat(f.fileno()).st_size - 4096))
+ lines = f.read().decode(errors='replace').splitlines()[1:][-8:]
+ return dict(hashes=hashes, marker=marker, drop_in=self.path(DROP).exists(),
+ table_present=table is not None, packets=packets(table),
+ timer=self.timer(), log=lines)
+
+ def uninstall(self):
+ self.remove('remove')
+ self.disarm()
+ run('systemctl', 'stop', TIMER + '.timer', check=False)
+ run('systemctl', 'stop', TIMER + '.service', check=False)
+ require(self.timer().get('ActiveState') in {'inactive', 'failed'})
+ service = run('systemctl', 'show', TIMER + '.service', '--property=ActiveState')
+ require(service.stdout.strip() in {'ActiveState=inactive', 'ActiveState=failed'})
+ result = self.status()
+ for f in FILES:
+ self.path(LIB + '/' + f).unlink()
+ self.path(LIB).rmdir()
+ for name in ('bundle.b64', 'bundle.tar'):
+ self.path('/run/carlos-p3b2-fault/' + name).unlink(missing_ok=True)
+ runtime = self.path('/run/carlos-p3b2-fault')
+ if runtime.exists():
+ runtime.rmdir()
+ for name in ('marker.json', 'consumed.json', 'log.jsonl', 'lock', 'rehearsal-timer-minutes'):
+ (self.state / name).unlink(missing_ok=True)
+ self.state.rmdir()
+ result['uninstalled'] = not any(self.path(p).exists() for p in (LIB, STATE, DROP))
+ require(result['uninstalled'])
+ emit(result)
+
+
+def packets(table):
+ if isinstance(table, dict):
+ return sum(v if k == 'packets' and type(v) is int else packets(v) for k, v in table.items())
+ if isinstance(table, list):
+ return sum(packets(v) for v in table)
+ return 0
+
+
+def emit(data):
+ body = json.dumps(data, separators=(',', ':'))
+ require(len(body.encode()) <= 8192)
+ print(body)
+
+
+def main():
+ os.umask(0o077)
+ h = None
+ state_ready = False
+ verb = sys.argv[1] if len(sys.argv) > 1 else ''
+ try:
+ h = Harness()
+ if verb == 'expire':
+ require(len(sys.argv) == 2)
+ try:
+ h.directory(h.state)
+ state_ready = True
+ except (OSError, ValueError):
+ print(TEXT['log_failed'], file=sys.stderr)
+ h.remove('expire', evidence=state_ready)
+ return 0
+ h.directory(h.state)
+ state_ready = True
+ if verb == 'prestart':
+ output = run('systemd-run', '--unit=carlos-p3b2-fault-prestart', '--collect',
+ '--wait', '--pipe', '--property=RuntimeMaxSec=60s',
+ '/bin/sh', str(h.path(LIB + '/fault.sh')), 'consume', timeout=75)
+ sys.stderr.write(output.stderr)
+ return 0
+ fd = os.open(h.state / 'lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, 'w') as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ if verb in {'arm-fault', 'arm-pause', 'fault-now'}:
+ h.arm(verb, sys.argv[2:])
+ else:
+ require(len(sys.argv) == 2)
+ if verb == 'install':
+ h.directory(h.path(LIB))
+ for name in FILES:
+ h.read(h.path(LIB + '/' + name), 40000)
+ h.path(LIB + '/' + name).chmod(0o600)
+ h.log('install')
+ elif verb == 'consume':
+ h.prestart()
+ elif verb in {'expire', 'remove'}:
+ h.remove(verb)
+ elif verb == 'status':
+ emit(h.status())
+ elif verb == 'disarm':
+ h.disarm()
+ elif verb == 'uninstall':
+ h.uninstall()
+ else:
+ require(False)
+ except Exception as exc:
+ if h is not None and state_ready:
+ try:
+ h.log('refused', verb=verb, error=type(exc).__name__)
+ except Exception:
+ pass
+ print(TEXT['failed'], file=sys.stderr)
+ # An attempted fault can fail without blocking the requested edge start.
+ return 0 if verb in {'prestart', 'consume', 'fault-now'} else 1
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/region-group-fault/fault.sh b/scripts/region-group-fault/fault.sh
new file mode 100644
index 000000000..2fe6fec9d
--- /dev/null
+++ b/scripts/region-group-fault/fault.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+# Keep the edge start independent of Python and every harness failure.
+if [ "${CARLOS_P3B2_FAULT_TEST_ROOT+x}" = x ] && [ "$(/usr/bin/id -u)" = 0 ]; then
+ exit 77
+fi
+if [ "${CARLOS_P3B2_FAULT_TEST_ROOT+x}" != x ]; then
+ PATH=/usr/sbin:/usr/bin:/sbin:/bin
+ export PATH
+fi
+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0
+if [ "${1-}" = prestart ]; then
+ python3 -I -B "$here/fault.py" "$@"
+ exit 0
+fi
+exec python3 -I -B "$here/fault.py" "$@"
diff --git a/scripts/region-group-fault/rehearse.py b/scripts/region-group-fault/rehearse.py
new file mode 100644
index 000000000..4acc0b414
--- /dev/null
+++ b/scripts/region-group-fault/rehearse.py
@@ -0,0 +1,467 @@
+import argparse
+import base64
+import hashlib
+import json
+import os
+from pathlib import Path
+import shlex
+import signal
+import subprocess
+import sys
+import time
+import uuid
+import zlib
+
+from bundle import build
+from client import command, result, TEXT
+
+IID = 'i-00000000000000000'
+BOOT = '00000000-0000-0000-0000-000000000000'
+TX = 'p3b2-rehearsal'
+REMOTE = '/var/lib/carlos-p3b2-rehearsal'
+UNITS = ('carlos-edge.service', 'carlos-edge-group.conf', 'carlos.slice',
+ 'data-instances.mount', 'run-carlos-instances.mount', 'run-carlos-logs.mount')
+PHASES = ('prestart', 'consumed', 'kernel', 'pause', 'repair')
+
+
+def check(value):
+ if not value:
+ raise RuntimeError(TEXT['probe'])
+
+
+def q(value):
+ return shlex.quote(str(value))
+
+
+def write_command(path, data, mode='0600'):
+ value = base64.b64encode(data.encode()).decode()
+ return 'printf %s ' + q(value) + ' | base64 -d > ' + q(path) + '; chmod ' + mode + ' ' + q(path)
+
+
+class AWS:
+ def __init__(self, args):
+ self.a = args
+ self.history = []
+
+ def call(self, *words, raw=False):
+ cmd = ['aws', '--profile', self.a.profile, '--region', self.a.region,
+ '--output', 'json', '--no-cli-pager', '--cli-connect-timeout', '5', '--cli-read-timeout', '30', *words]
+ self.history.append(cmd)
+ if self.a.dry_run:
+ print(json.dumps(cmd))
+ return {} if not raw else ''
+ env = dict(os.environ, AWS_PAGER='', AWS_MAX_ATTEMPTS='2')
+ for key in list(env):
+ if key.startswith('AWS_ENDPOINT_URL') or key in {
+ 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN',
+ 'AWS_SECURITY_TOKEN', 'AWS_PROFILE', 'AWS_DEFAULT_PROFILE'}:
+ del env[key]
+ p = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=180)
+ if p.returncode:
+ raise RuntimeError(p.stderr)
+ return p.stdout if raw else json.loads(p.stdout or '{}')
+
+ def online(self, iid):
+ data = self.call('ssm', 'describe-instance-information', '--filters',
+ json.dumps([{'Key': 'InstanceIds', 'Values': [iid]}]))
+ return any(row.get('PingStatus') == 'Online' for row in data.get('InstanceInformationList', []))
+
+ def connected(self, iid):
+ state = self.call('ssm', 'get-connection-status', '--target', iid).get('Status')
+ check(state in {'Connected', 'NotConnected'})
+ return state == 'Connected'
+
+ def remote(self, iid, commands, wait=True):
+ value = self.call('ssm', 'send-command', '--instance-ids', iid,
+ '--document-name', 'AWS-RunShellScript', '--timeout-seconds', '60',
+ '--parameters', json.dumps({'commands': commands, 'executionTimeout': ['180']}))
+ if self.a.dry_run or not wait:
+ return ''
+ cid = value['Command']['CommandId']
+ deadline = time.monotonic() + 200
+ while time.monotonic() < deadline:
+ try:
+ reply = self.call('ssm', 'get-command-invocation', '--command-id', cid,
+ '--instance-id', iid)
+ except RuntimeError as exc:
+ if 'InvocationDoesNotExist' not in str(exc):
+ raise
+ time.sleep(2)
+ continue
+ if reply['Status'] == 'Success':
+ return reply.get('StandardOutputContent', '')
+ if reply['Status'] in {'Failed', 'Cancelled', 'TimedOut'}:
+ raise RuntimeError(reply.get('StandardErrorContent', TEXT['remote']))
+ time.sleep(2)
+ raise TimeoutError(TEXT['remote'])
+
+
+def user_data(region):
+ # Region is validated before it is embedded into the root bootstrap.
+ return '''#!/bin/sh
+set -eu
+export DEBIAN_FRONTEND=noninteractive
+apt-get update
+apt-get install -y curl python3 nftables util-linux ca-certificates
+mkdir -p -m 0700 /var/lib/carlos-p3b2-rehearsal
+curl -fsSL --connect-timeout 5 --max-time 120 -o /var/lib/carlos-p3b2-rehearsal/ssm.deb \\
+ https://s3.%s.amazonaws.com/amazon-ssm-%s/latest/debian_arm64/amazon-ssm-agent.deb
+dpkg -i /var/lib/carlos-p3b2-rehearsal/ssm.deb
+rm /var/lib/carlos-p3b2-rehearsal/ssm.deb
+systemctl enable --now amazon-ssm-agent
+''' % (region, region)
+
+
+def probe_source(region, bucket):
+ return '''import json, pathlib, subprocess, time
+root = pathlib.Path(%r)
+urls = {'s3': %r, 'ssm': %r}
+while True:
+ phase = (root / 'phase').read_text().strip()
+ for user in ('root', 'carlos'):
+ for endpoint, url in urls.items():
+ argv = (['runuser', '-u', 'carlos', '--'] if user == 'carlos' else []) + [
+ 'curl', '--noproxy', '*', '-sS', '-o', '/dev/null', '--connect-timeout', '2',
+ '--max-time', '3', url]
+ result = subprocess.run(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ with (root / 'probe.jsonl').open('a') as f:
+ f.write(json.dumps(dict(at=time.time(), phase=phase, user=user,
+ endpoint=endpoint, ok=result.returncode == 0)) + '\\n')
+ time.sleep(2)
+''' % (REMOTE, 'https://' + bucket + '.s3.' + region + '.amazonaws.com/',
+ 'https://ssm.' + region + '.amazonaws.com/')
+
+
+def setup_commands(args, binary_url, units):
+ lines = ['set -eu', 'umask 077', 'mkdir -p /opt/carlos /etc/systemd/system/carlos-edge.service.d '
+ '/run/carlos-group-maintenance /data/.instances /data/instances /run/carlos/.instances '
+ '/run/carlos/instances /run/carlos/.logs /run/carlos/logs ' + REMOTE,
+ 'id carlos >/dev/null 2>&1 || useradd --system --no-create-home carlos',
+ 'curl -fsS --max-time 120 ' + q(binary_url) + ' -o /opt/carlos/carlos',
+ 'printf %s ' + q(args.binary_sha256 + ' /opt/carlos/carlos\n') + ' | sha256sum -c -',
+ 'chmod 0755 /opt/carlos/carlos']
+ for name, data in units.items():
+ target = ('carlos-edge.service.d/50-group.conf' if name == 'carlos-edge-group.conf' else name)
+ lines.append(write_command('/etc/systemd/system/' + target, data, '0644'))
+ lines += [write_command('/run/carlos-group-maintenance/permit.json', json.dumps({'transaction': TX})),
+ write_command(REMOTE + '/phase', 'baseline'),
+ write_command(REMOTE + '/probe.py', probe_source(args.region, args.bucket)),
+ 'systemctl daemon-reload',
+ 'systemd-run --unit=carlos-p3b2-rehearsal-probe --collect '
+ '--property=RuntimeMaxSec=1800s /usr/bin/python3 ' + REMOTE + '/probe.py',
+ 'cat /proc/sys/kernel/random/boot_id']
+ return lines
+
+
+class Rehearsal:
+ def __init__(self, args, api, sleep=time.sleep, clock=time.monotonic):
+ self.a, self.api, self.sleep, self.clock = args, api, sleep, clock
+ self.token = uuid.uuid4().hex
+ self.iid = None
+ self.boot = BOOT
+ self.verdicts = {phase: 'NOT RUN' for phase in PHASES}
+ self.evidence = {}
+ self.units = {}
+ self.installed = False
+
+ def wait(self, predicate, seconds=240):
+ deadline = self.clock() + seconds
+ while self.clock() < deadline:
+ if predicate():
+ return
+ self.sleep(5)
+ raise TimeoutError(TEXT['probe'])
+
+ def frame(self, verb, minutes=1, wait=True):
+ nonce = uuid.uuid4().hex
+ fields = dict(iid=self.iid, boot=self.boot, transaction=TX, minutes=minutes) if verb in {
+ 'arm-fault', 'arm-pause', 'fault-now'} else {}
+ cmd = command(verb, nonce, **fields)
+ output = self.api.remote(self.iid, [cmd], wait=wait)
+ if self.a.dry_run or not wait:
+ return {}
+ body = result(output, nonce)
+ return json.loads(body) if verb in {'status', 'uninstall'} else {}
+
+ def remote(self, *commands, wait=True):
+ return self.api.remote(self.iid, list(commands), wait=wait)
+
+ def launch(self):
+ reply = self.api.call('ec2', 'run-instances', '--image-id', self.a.ami,
+ '--instance-type', 't4g.small', '--min-count', '1', '--max-count', '1',
+ '--subnet-id', self.a.subnet, '--security-group-ids', self.a.security_group,
+ '--iam-instance-profile', json.dumps({'Name': self.a.instance_profile}),
+ '--metadata-options', 'HttpTokens=required,HttpPutResponseHopLimit=1',
+ '--block-device-mappings', json.dumps([{'DeviceName': '/dev/sda1', 'Ebs': {
+ 'VolumeSize': 8, 'VolumeType': 'gp3', 'Encrypted': True, 'DeleteOnTermination': True}}]),
+ '--tag-specifications', json.dumps([{'ResourceType': 'instance', 'Tags': [
+ {'Key': 'purpose', 'Value': 'p3b2-fault-rehearsal'}]}]),
+ '--client-token', self.token, '--user-data', user_data(self.a.region))
+ self.iid = IID if self.a.dry_run else reply['Instances'][0]['InstanceId']
+
+ def prepare(self):
+ if not self.a.dry_run:
+ self.wait(lambda: self.api.online(self.iid), 600)
+ data = build()
+ sha = hashlib.sha256(data).hexdigest()
+ bundle_path = self.a.evidence_dir / 'bundle.tar'
+ if not self.a.dry_run:
+ bundle_path.write_bytes(data)
+ urls = {}
+ for name, path in [('bundle.tar', bundle_path), ('carlos', self.a.binary)]:
+ uri = 's3://' + self.a.bucket + '/' + self.a.key_prefix.strip('/') + '/' + self.token + '/' + name
+ self.api.call('s3', 'cp', str(path), uri, raw=True)
+ urls[name] = self.api.call('s3', 'presign', uri, '--expires-in', '3600', raw=True).strip()
+ self.evidence['bundle_sha256'] = sha
+ self.evidence['binary_sha256'] = self.a.binary_sha256
+ self.evidence['commit'] = self.a.commit
+ self.evidence['iid'] = self.iid
+ self.frame('install')
+ self.installed = True
+ self.evidence['unit_sha256'] = {k: hashlib.sha256(v.encode()).hexdigest() for k, v in self.units.items()}
+ output = self.api.remote(self.iid, setup_commands(self.a, urls['carlos'] or '<presigned-binary>', self.units))
+ if not self.a.dry_run:
+ self.boot = output.strip().splitlines()[-1]
+ self.wait(lambda: self.has_baseline(), 60)
+ self.frame('status')
+
+ def collect(self, phase):
+ code = """import base64,json,pathlib,zlib,subprocess
+p=pathlib.Path('/var/lib/carlos-p3b2-fault/log.jsonl')
+q=pathlib.Path('/var/lib/carlos-p3b2-rehearsal/probe.jsonl')
+v={'log':[json.loads(x) for x in p.read_text().splitlines()],
+ 'probe':[json.loads(x) for x in q.read_text().splitlines()] if q.exists() else [],
+ 'journal':subprocess.run(['journalctl','--no-pager','-n','30','-u','carlos-p3b2-fault-expire.service','-u','carlos-p3b2-fault-prestart.service'],capture_output=True,text=True).stdout}
+print(base64.b64encode(zlib.compress(json.dumps(v).encode())).decode())
+"""
+ output = self.remote('python3 -c ' + q(code))
+ if self.a.dry_run:
+ return {}
+ data = json.loads(zlib.decompress(base64.b64decode(output.strip(), validate=True)))
+ data['status'] = self.frame('status')
+ self.evidence[phase] = data
+ return data
+
+ def has_baseline(self):
+ data = self.collect('baseline')
+ return all(any(p['phase'] == 'baseline' and p['user'] == user and p['endpoint'] == ep and p['ok']
+ for p in data['probe']) for user in ('root', 'carlos') for ep in ('s3', 'ssm'))
+
+ def phase(self, name):
+ self.remote(write_command(REMOTE + '/phase', name))
+ self.verdicts[name] = 'FAIL'
+
+ def restart(self, wait=False):
+ # A real pinned unit start may fail without host config; its pre-start must still run.
+ self.remote('systemctl reset-failed carlos-edge.service; '
+ 'systemctl restart carlos-edge.service || true', wait=wait)
+
+ def assert_fault(self, data, name, expired):
+ status, log = data['status'], data['log']
+ index = max(i for i, x in enumerate(log) if x['event'] == 'table-added')
+ log = log[index:]
+ added = log[0]
+ check(status['marker'] == 'consumed' or name == 'kernel')
+ check(status['table_present'] is (not expired))
+ check(any(x['event'] == 'counters' and x['packets'] > 0 for x in log) or status['packets'] > 0)
+ if expired:
+ check(any(x['event'] == 'expire' for x in log))
+ else:
+ check(added['kernel_timeout'])
+ check(status['timer']['ActiveState'] == 'active')
+ for ep in ('s3', 'ssm'):
+ points = [p for p in data['probe'] if p['phase'] == name and p['endpoint'] == ep and p['user'] == 'root']
+ failed = [p['at'] for p in points if not p['ok']]
+ check(failed and any(p['ok'] and p['at'] > max(failed) for p in points))
+
+ def phases(self):
+ self.phase('prestart')
+ self.frame('arm-fault')
+ self.restart()
+ if not self.a.dry_run:
+ self.wait(lambda: not self.api.connected(self.iid), 45)
+ self.evidence['ssm-disconnected'] = True
+ self.wait(lambda: self.api.connected(self.iid) and self.api.online(self.iid), 240)
+ self.sleep(15)
+ data = self.collect('prestart')
+ if not self.a.dry_run:
+ self.assert_fault(data, 'prestart', True)
+ self.verdicts['prestart'] = 'PASS'
+
+ self.phase('consumed')
+ self.restart(wait=True)
+ if not self.a.dry_run:
+ self.sleep(10)
+ check(not self.frame('status')['table_present'])
+ self.collect('consumed')
+ self.verdicts['consumed'] = 'PASS'
+
+ self.phase('kernel')
+ self.remote(write_command('/var/lib/carlos-p3b2-fault/rehearsal-timer-minutes', '5'))
+ self.frame('fault-now', wait=False)
+ if not self.a.dry_run:
+ # Kernel expiry must restore HTTPS while the five-minute timer is still armed.
+ self.sleep(85)
+ self.wait(lambda: self.api.connected(self.iid) and self.api.online(self.iid), 120)
+ self.sleep(15)
+ data = self.collect('kernel')
+ if not self.a.dry_run:
+ self.assert_fault(data, 'kernel', False)
+ self.frame('remove')
+ self.remote('systemctl stop carlos-p3b2-fault-expire.timer; '
+ 'systemctl stop carlos-p3b2-fault-expire.service; '
+ 'rm /var/lib/carlos-p3b2-fault/rehearsal-timer-minutes')
+ self.verdicts['kernel'] = 'PASS'
+
+ self.phase('pause')
+ self.frame('arm-pause', minutes=3)
+ self.restart(wait=True)
+ if not self.a.dry_run:
+ self.sleep(20)
+ check(self.api.online(self.iid))
+ data = self.collect('pause')
+ if not self.a.dry_run:
+ check(data['status']['table_present'] and data['status']['packets'] > 0)
+ for ep in ('s3', 'ssm'):
+ points = [p for p in data['probe'] if p['phase'] == 'pause' and p['endpoint'] == ep]
+ check(any(p['user'] == 'root' and p['ok'] for p in points))
+ check(not any(p['user'] == 'root' and not p['ok'] for p in points))
+ check(any(p['user'] == 'carlos' and not p['ok'] for p in points))
+ self.frame('remove')
+ if not self.a.dry_run:
+ check(not self.frame('status')['table_present'])
+ self.remote('systemctl stop carlos-p3b2-fault-expire.timer; '
+ 'systemctl stop carlos-p3b2-fault-expire.service')
+ self.verdicts['pause'] = 'PASS'
+
+ self.phase('repair')
+ self.frame('arm-fault')
+ before = self.remote('sha256sum /etc/systemd/system/carlos-edge.service.d/90-p3b2-fault.conf '
+ '/var/lib/carlos-p3b2-fault/marker.json')
+ self.remote(write_command('/etc/systemd/system/carlos-edge.service.d/50-group.conf',
+ self.units['carlos-edge-group.conf'], '0644'), 'systemctl daemon-reload',
+ 'timeout 30s /opt/carlos/carlos adopt >/var/lib/carlos-p3b2-rehearsal/adopt.log 2>&1; '
+ 'rc=$?; printf %s \"$rc\" >/var/lib/carlos-p3b2-rehearsal/adopt.rc; exit 0')
+ after = self.remote('sha256sum /etc/systemd/system/carlos-edge.service.d/90-p3b2-fault.conf '
+ '/var/lib/carlos-p3b2-fault/marker.json')
+ check(self.a.dry_run or before == after)
+ self.evidence['adopt-repair'] = self.remote('cat /var/lib/carlos-p3b2-rehearsal/adopt.rc; '
+ 'tail -c 4000 /var/lib/carlos-p3b2-rehearsal/adopt.log')
+ data = self.collect('repair')
+ if not self.a.dry_run:
+ check(data['status']['drop_in'] and data['status']['marker'] == 'armed')
+ self.verdicts['repair'] = 'PASS'
+ self.frame('disarm')
+ self.evidence['cleanup'] = self.frame('uninstall')
+ self.installed = False
+ self.remote('systemctl stop carlos-p3b2-rehearsal-probe.service',
+ 'test ! -e /usr/local/lib/carlos-p3b2-fault; test ! -e /var/lib/carlos-p3b2-fault; '
+ 'test ! -e /etc/systemd/system/carlos-edge.service.d/90-p3b2-fault.conf; '
+ '! nft list table inet carlos_p3b2_fault')
+
+ def terminate(self):
+ if self.iid is None:
+ for attempt in range(3):
+ try:
+ response = self.api.call('ec2', 'describe-instances', '--filters',
+ json.dumps([{'Name': 'client-token', 'Values': [self.token]}]))
+ ids = [i['InstanceId'] for r in response.get('Reservations', []) for i in r['Instances']]
+ if ids or self.a.dry_run:
+ break
+ except Exception:
+ if attempt == 2:
+ print(TEXT['unknown_leak'].format(token=self.token), flush=True)
+ raise
+ if attempt == 2:
+ print(TEXT['unknown_leak'].format(token=self.token), flush=True)
+ raise RuntimeError(TEXT['probe'])
+ self.sleep(5)
+ else:
+ ids = [self.iid]
+ for iid in ids:
+ for attempt in range(3):
+ try:
+ self.api.call('ec2', 'terminate-instances', '--instance-ids', iid)
+ self.api.call('ec2', 'wait', 'instance-terminated', '--instance-ids', iid, raw=True)
+ break
+ except Exception:
+ if attempt == 2:
+ print(TEXT['leaked'].format(iid=iid), flush=True)
+ raise
+ self.sleep(5)
+
+ def save(self):
+ path = self.a.evidence_dir / 'evidence.json'
+ if self.installed and not self.a.dry_run:
+ try:
+ self.collect('final')
+ except Exception as exc:
+ self.evidence['collection_error'] = str(exc)
+ if not self.a.dry_run:
+ self.evidence['verdicts'] = self.verdicts
+ self.evidence['commands'] = self.api.history
+ path.write_text(json.dumps(self.evidence, indent=2) + '\n')
+ self.api.call('s3', 'cp', str(path), 's3://' + self.a.bucket + '/' +
+ self.a.key_prefix.strip('/') + '/' + self.token + '/evidence.json', raw=True)
+
+ def run(self):
+ handlers = {}
+ def interrupted(signum, _frame):
+ raise InterruptedError(str(signum))
+ try:
+ for sig in (signal.SIGINT, signal.SIGTERM):
+ handlers[sig] = signal.signal(sig, interrupted)
+ self.launch()
+ self.prepare()
+ self.phases()
+ finally:
+ for sig in handlers:
+ signal.signal(sig, signal.SIG_IGN)
+ try:
+ try:
+ if self.iid:
+ self.save()
+ finally:
+ self.terminate()
+ finally:
+ for sig, handler in handlers.items():
+ signal.signal(sig, handler)
+ for phase, verdict in self.verdicts.items():
+ print(TEXT['result'].format(phase=phase, result='DRY RUN' if self.a.dry_run else verdict))
+
+
+def parse(argv=None):
+ p = argparse.ArgumentParser(description=TEXT['required'])
+ for name in ('profile', 'region', 'subnet', 'security-group', 'instance-profile', 'ami',
+ 'bucket', 'key-prefix', 'binary', 'binary-sha256', 'commit', 'evidence-dir'):
+ p.add_argument('--' + name, required=True)
+ p.add_argument('--dry-run', action='store_true')
+ a = p.parse_args(argv)
+ import re
+ if not re.fullmatch(r'[a-z]{2}(?:-[a-z]+)+-\d', a.region) or not re.fullmatch(r'[0-9a-f]{64}', a.binary_sha256):
+ p.error(TEXT['required'])
+ if not re.fullmatch(r'[0-9a-f]{40}', a.commit) or not re.fullmatch(r'[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]', a.bucket):
+ p.error(TEXT['required'])
+ a.binary, a.evidence_dir = Path(a.binary), Path(a.evidence_dir)
+ return a
+
+
+def main():
+ os.umask(0o077)
+ a = parse()
+ if hashlib.sha256(a.binary.read_bytes()).hexdigest() != a.binary_sha256:
+ raise ValueError(TEXT['required'])
+ runner = Rehearsal(a, AWS(a))
+ for name in UNITS:
+ runner.units[name] = subprocess.run(['git', 'show', a.commit + ':internal/host/units/' + name],
+ text=True, capture_output=True, check=True).stdout
+ a.evidence_dir = a.evidence_dir / runner.token
+ if not a.dry_run:
+ a.evidence_dir.mkdir(mode=0o700, parents=True, exist_ok=False)
+ runner.run()
+ if a.dry_run:
+ print(TEXT['dry'])
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/region-group-fault/text.json b/scripts/region-group-fault/text.json
new file mode 100644
index 000000000..8b466b2bf
--- /dev/null
+++ b/scripts/region-group-fault/text.json
@@ -0,0 +1,17 @@
+{
+ "root": "Run the installed harness as root. Test roots are refused for root.",
+ "unsafe": "Refused unsafe harness state or arguments.",
+ "failed": "Harness command failed. Inspect the local log before proceeding.",
+ "fallback": "WARNING: kernel set timeouts are unavailable. Only the verified local timer will remove this fault.",
+ "rehearsal": "Rehearsal-only timer delay is active. Do not use this bundle on a group member.",
+ "remote": "No successful framed result. Read local evidence after access returns.",
+ "leaked": "LEAKED {iid}",
+ "result": "{phase}: {result}",
+ "dry": "Dry run. No AWS command was executed.",
+ "required": "Supply every deployment value and a pinned commit explicitly.",
+ "probe": "Rehearsal assertions failed. Retain the evidence and stop.",
+ "copy": "Operator wording awaits the controller's later copy pass.",
+ "unknown_leak": "LEAKED unknown instance for client token {token}",
+ "bundle_size": "The bundle exceeds the approved command size.",
+ "log_failed": "Local evidence could not be written. Fault removal continues."
+}
diff --git a/scripts/region_group_document_test.py b/scripts/region_group_document_test.py
index 57343abd8..0ce37b042 100644
--- a/scripts/region_group_document_test.py
+++ b/scripts/region_group_document_test.py
@@ -76,7 +76,7 @@ class DocumentPatternTests(unittest.TestCase):
def test_all_harness_verbs_and_bounds(self):
for verb in ("status", "disarm", "remove", "uninstall"):
self.assertAccepted(frames.harness_command(verb, NONCE), harness=True)
- for verb in ("arm-fault", "arm-pause"):
+ for verb in ("arm-fault", "arm-pause", "fault-now"):
for iid in ("i-01234567", ARM["iid"]):
for minutes in (1, 9, 10, 99, 100, 999):
for transaction in ("a", "A_9-" * 20):
@@ -92,7 +92,7 @@ class DocumentPatternTests(unittest.TestCase):
def test_harness_is_disabled_by_default(self):
commands = [frames.install_command("YQ==", SHA, NONCE)]
commands += [frames.harness_command(v, NONCE) for v in ("status", "disarm", "remove", "uninstall")]
- commands += [frames.harness_command(v, NONCE, **ARM) for v in ("arm-fault", "arm-pause")]
+ commands += [frames.harness_command(v, NONCE, **ARM) for v in ("arm-fault", "arm-pause", "fault-now")]
for command in commands:
self.assertRefused(command, harness=False)
diff --git a/scripts/region_group_fault_test.py b/scripts/region_group_fault_test.py
new file mode 100644
index 000000000..fbdc615e8
--- /dev/null
+++ b/scripts/region_group_fault_test.py
@@ -0,0 +1,484 @@
+import base64
+import hashlib
+import importlib.util
+import io
+import ipaddress
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import unittest
+from unittest.mock import patch
+from types import SimpleNamespace
+
+from scripts.region_group_document_test import pattern
+from scripts import region_group_frames as frames
+
+ROOT = Path(__file__).resolve().parents[1]
+DIR = ROOT / 'scripts/region-group-fault'
+sys.path.insert(0, str(DIR))
+import bundle
+import client
+import rehearse
+
+SPEC = importlib.util.spec_from_file_location('fault', DIR / 'fault.py')
+fault = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(fault)
+IID = 'i-0123456789abcdef0'
+BOOT = '01234567-89ab-cdef-0123-456789abcdef'
+ARGS = ['--iid', IID, '--boot', BOOT, '--transaction', 'witness-1', '--minutes', '35']
+
+STUB = r'''#!/usr/bin/env python3
+import json, os, pathlib, subprocess, sys, time
+root = pathlib.Path(os.environ['CARLOS_P3B2_FAULT_TEST_ROOT'])
+name = pathlib.Path(sys.argv[0]).name
+args = sys.argv[1:]
+config = json.loads((root / 'config').read_text())
+with (root / 'calls').open('a') as f:
+ f.write(json.dumps([name, *args]) + '\n')
+def save(name, value):
+ (root / name).write_text(json.dumps(value))
+if name == 'curl':
+ url = args[-1]
+ if config.get('imds_error'):
+ sys.exit(1)
+ if url.endswith('/api/token'): print('token')
+ elif url.endswith('/instance-id'): print(config['iid'])
+ elif url.endswith('/macs/'): print('aa:bb:cc:dd:ee:ff/')
+ elif url.endswith('/vpc-ipv4-cidr-blocks'): print(config.get('cidrs', '10.12.0.0/16\n10.24.0.0/16'))
+ else: sys.exit(1)
+elif name == 'systemd-run':
+ if '--unit=carlos-p3b2-fault-prestart' in args:
+ sys.exit(subprocess.run(args[args.index('/bin/sh'):]).returncode)
+ with (root / 'calls').open('a') as f:
+ f.write(json.dumps(['marker-at-timer', (root / 'var/lib/carlos-p3b2-fault/marker.json').exists()]) + '\n')
+ if config.get('timer_fail'): sys.exit(1)
+ minutes = int(next(x.split('=')[1][:-1] for x in args if x.startswith('--on-active=')))
+ save('timer', {'ActiveState': 'active', 'NextElapseUSecMonotonic': str(int((time.monotonic() + minutes * 60) * 1000000))})
+elif name == 'systemctl':
+ if args[0] == 'show':
+ values = json.loads((root / 'timer').read_text()) if (root / 'timer').exists() else {'ActiveState': 'inactive', 'NextElapseUSecMonotonic': '0'}
+ if config.get('timer_inactive'): values['ActiveState'] = 'inactive'
+ if config.get('timer_far'): values['NextElapseUSecMonotonic'] = str(int((time.monotonic() + 999999) * 1000000))
+ if config.get('timer_near'): values['NextElapseUSecMonotonic'] = str(int((time.monotonic() + 10) * 1000000))
+ print('\n'.join(k + '=' + v for k, v in values.items() if '--property=' + k in args))
+ elif args[0] == 'stop':
+ save('timer', {'ActiveState': 'inactive', 'NextElapseUSecMonotonic': '0'})
+ elif args != ['daemon-reload']:
+ sys.exit(8)
+elif name == 'nft':
+ if args == ['-j', 'list', 'table', 'inet', 'carlos_p3b2_fault']:
+ if config.get('list_error'):
+ print('Operation not permitted', file=sys.stderr); sys.exit(1)
+ if not (root / 'table').exists():
+ print('No such file or directory', file=sys.stderr); sys.exit(1)
+ print((root / 'table').read_text())
+ elif args == ['delete', 'table', 'inet', 'carlos_p3b2_fault']:
+ (root / 'table').unlink()
+ elif args in [['-c', '-f', '-'], ['-f', '-']]:
+ rules = sys.stdin.read()
+ with (root / 'rules').open('a') as f: f.write(rules)
+ if args[0] == '-c':
+ if config.get('no_timeout') and 'flags interval, timeout' in rules: sys.exit(1)
+ else:
+ if config.get('add_error'): sys.exit(1)
+ save('table', {'nftables': [{'rule': {'expr': [{'counter': {'packets': 4}}]}}]})
+ else: sys.exit(9)
+else: sys.exit(10)
+'''
+
+
+class HarnessTests(unittest.TestCase):
+ def setUp(self):
+ if os.geteuid() == 0:
+ self.skipTest('non-root harness integration tests')
+ previous_umask = os.umask(0o077)
+ self.addCleanup(os.umask, previous_umask)
+ self.tmp = tempfile.TemporaryDirectory(prefix='b5-test-', dir=ROOT / '.superpowers')
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.env = dict(os.environ, CARLOS_P3B2_FAULT_TEST_ROOT=str(self.root), PYTHONDONTWRITEBYTECODE='1')
+ self.lib = self.root / fault.LIB.lstrip('/')
+ self.lib.mkdir(parents=True, mode=0o700)
+ for name in bundle.MEMBERS:
+ shutil.copyfile(DIR / name, self.lib / name)
+ self.config = {'iid': IID}
+ (self.root / 'config').write_text(json.dumps(self.config))
+ self.bin = self.root / 'bin'
+ self.bin.mkdir()
+ for name in ('nft', 'curl', 'systemctl', 'systemd-run'):
+ p = self.bin / name
+ p.write_text(STUB)
+ p.chmod(0o700)
+ self.env['PATH'] = str(self.bin) + ':' + os.environ['PATH']
+ boot = self.root / 'proc/sys/kernel/random/boot_id'
+ boot.parent.mkdir(parents=True)
+ boot.write_text(BOOT)
+ self.permit = self.root / fault.PERMIT.lstrip('/')
+ self.permit.parent.mkdir(parents=True)
+ self.permit.write_text(json.dumps({'transaction': 'witness-1'}))
+ self.permit.chmod(0o600)
+ self.state = self.root / fault.STATE.lstrip('/')
+ self.call('install')
+
+ def call(self, *args, check=True):
+ p = subprocess.run(['/bin/sh', str(self.lib / 'fault.sh'), *args], env=self.env,
+ capture_output=True, text=True, timeout=15)
+ if check:
+ self.assertEqual(p.returncode, 0, p.stderr)
+ return p
+
+ def change(self, **values):
+ self.config.update(values)
+ (self.root / 'config').write_text(json.dumps(self.config))
+
+ def calls(self):
+ p = self.root / 'calls'
+ return [json.loads(line) for line in p.read_text().splitlines()] if p.exists() else []
+
+ def events(self):
+ return [json.loads(line) for line in (self.state / 'log.jsonl').read_text().splitlines()]
+
+ def arm(self, mode='arm-fault'):
+ self.call(mode, *ARGS)
+
+ def prestart(self):
+ self.call('prestart')
+
+ def test_timer_verified_before_drop_and_consume_first(self):
+ self.arm()
+ self.prestart()
+ calls = self.calls()
+ add = calls.index(['nft', '-f', '-'])
+ timer = next(i for i, c in enumerate(calls) if c[0] == 'systemd-run' and '--on-active=35m' in c)
+ verify = next(i for i, c in enumerate(calls) if c[:2] == ['systemctl', 'show'])
+ self.assertIn(['marker-at-timer', False], calls)
+ self.assertNotIn(['marker-at-timer', True], calls)
+ self.assertLess(timer, verify)
+ self.assertLess(verify, add)
+ events = [x['event'] for x in self.events()]
+ for a, b in [('consume', 'timer-armed'), ('timer-armed', 'timer-verified'), ('timer-verified', 'table-added')]:
+ self.assertLess(events.index(a), events.index(b))
+ self.assertFalse((self.state / 'marker.json').exists())
+ self.assertTrue((self.state / 'consumed.json').exists())
+ for cmd in calls:
+ if cmd[0] == 'systemctl':
+ self.assertNotIn(cmd[1], {'start', 'stop', 'restart', 'reboot'})
+ self.assertFalse(any(x == 'carlos-edge.service' for x in cmd))
+ self.assertTrue(any('--unit=carlos-p3b2-fault-prestart' in c for c in calls))
+
+ def test_timer_failure_and_bad_next_never_add(self):
+ for setting in ('timer_fail', 'timer_inactive', 'timer_far', 'timer_near'):
+ with self.subTest(setting=setting):
+ self.arm()
+ self.change(**{setting: True})
+ self.prestart()
+ self.assertNotIn(['nft', '-f', '-'], self.calls())
+ self.change(**{setting: False})
+ self.call('disarm')
+
+ def test_mismatches_do_not_consume_or_inject(self):
+ self.arm()
+ marker = self.state / 'marker.json'
+ original = json.loads(marker.read_text())
+ changes = [dict(iid='i-11111111111111111'), dict(boot_id='1' + BOOT[1:]),
+ dict(transaction='other'), dict(armed_at=time.time() - 3601),
+ dict(armed_at=time.time() + 60)]
+ for change in changes:
+ with self.subTest(change=change):
+ marker.write_text(json.dumps(dict(original, **change)))
+ self.prestart()
+ self.assertTrue(marker.exists())
+ self.assertNotIn(['nft', '-f', '-'], self.calls())
+ marker.write_text(json.dumps(original))
+ self.permit.unlink()
+ self.prestart()
+ self.assertTrue(marker.exists())
+ self.permit.symlink_to('/etc/hostname')
+ self.prestart()
+ self.assertTrue(marker.exists())
+ self.assertNotIn(['nft', '-f', '-'], self.calls())
+
+ def test_foreign_owned_permit_refused(self):
+ with patch.dict(os.environ, self.env):
+ h = fault.Harness()
+ actual = os.fstat
+ def foreign(fd):
+ s = actual(fd)
+ return SimpleNamespace(st_mode=s.st_mode, st_uid=s.st_uid + 1, st_nlink=s.st_nlink, st_size=s.st_size)
+ with patch.object(fault.os, 'fstat', side_effect=foreign):
+ with self.assertRaises(ValueError):
+ h.read(self.permit)
+
+ def test_prestart_errors_and_consumed_marker_always_success(self):
+ self.arm()
+ self.change(imds_error=True)
+ self.prestart()
+ self.change(imds_error=False, add_error=True)
+ self.prestart()
+ self.assertTrue((self.state / 'consumed.json').exists())
+ (self.root / 'calls').write_text('')
+ self.prestart()
+ self.assertNotIn(['nft', '-f', '-'], self.calls())
+ (self.lib / 'fault.py').write_text('raise RuntimeError("test")')
+ self.prestart()
+
+ def test_rules_scope_exclusions_timeout_and_pause_uid(self):
+ for mode in ('arm-fault', 'arm-pause'):
+ with self.subTest(mode=mode):
+ self.arm(mode)
+ self.prestart()
+ rules = (self.root / 'rules').read_text()
+ self.assertIn('flags interval, timeout', rules)
+ self.assertIn('::/0 timeout 35m', rules)
+ self.assertEqual('meta skuid "carlos"' in rules, mode == 'arm-pause')
+ self.assertEqual('ct state established ct mark 0xc350b205' in rules, mode == 'arm-pause')
+ self.assertNotIn('flush', rules)
+ for line in rules.splitlines():
+ self.assertIn('inet carlos_p3b2_fault', line)
+ content = re.search(r'add element inet carlos_p3b2_fault fault_dst \{ (.*?) \}', rules)[1]
+ nets = []
+ for element in content.split(', '):
+ network, ttl = element.split(' timeout ')
+ self.assertEqual(ttl, '35m')
+ nets.append(ipaddress.ip_network(network))
+ for value in ('10.12.0.1', '10.24.255.255', '127.1.2.3', '169.254.169.254'):
+ self.assertFalse(any(ipaddress.ip_address(value) in n for n in nets))
+ for value in ('1.1.1.1', '8.8.8.8', '10.25.0.1', '255.255.255.255'):
+ self.assertTrue(any(ipaddress.ip_address(value) in n for n in nets))
+ self.call('expire')
+ (self.root / 'rules').unlink()
+
+ def test_expire_is_local_scoped_and_absence_succeeds(self):
+ self.arm()
+ self.prestart()
+ (self.root / 'calls').write_text('')
+ self.call('expire')
+ self.call('expire')
+ for cmd in self.calls():
+ self.assertEqual(cmd[0], 'nft')
+ self.assertEqual(cmd[-2:], ['inet', fault.TABLE])
+ self.assertFalse((self.root / 'table').exists())
+ self.assertEqual(self.events()[-1]['event'], 'removal-readback')
+
+ def test_expire_does_not_wait_for_operator_lock(self):
+ import fcntl
+ self.call('fault-now', *ARGS)
+ with (self.state / 'lock').open('w') as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ self.call('expire')
+ self.assertFalse((self.root / 'table').exists())
+
+ def test_expire_removes_fault_when_log_cannot_be_written(self):
+ self.call('fault-now', *ARGS)
+ path = self.state / 'log.jsonl'
+ path.unlink()
+ path.symlink_to('/dev/full')
+ result = self.call('expire')
+ self.assertFalse((self.root / 'table').exists())
+ self.assertIn(fault.TEXT['log_failed'], result.stderr)
+
+ def test_unknown_table_read_failure_is_not_absence(self):
+ self.change(list_error=True)
+ self.assertNotEqual(self.call('expire', check=False).returncode, 0)
+ self.assertNotIn(['nft', 'delete', 'table', 'inet', fault.TABLE], self.calls())
+
+ def test_kernel_fallback_is_loud_and_timer_verified(self):
+ self.change(no_timeout=True)
+ self.arm()
+ p = self.call('prestart')
+ self.assertIn(fault.TEXT['fallback'], p.stderr)
+ self.assertIn('timer-only', [x['event'] for x in self.events()])
+ self.assertFalse([x for x in self.events() if x['event'] == 'table-added'][-1]['kernel_timeout'])
+
+ def test_fault_now_ignores_permit_but_checks_identity(self):
+ self.permit.unlink()
+ self.call('fault-now', *ARGS)
+ self.assertTrue((self.root / 'table').exists())
+ self.assertFalse((self.state / 'marker.json').exists())
+ self.call('expire')
+ self.call('fault-now', *[x if x != IID else 'i-11111111111111111' for x in ARGS])
+ self.assertFalse((self.root / 'table').exists())
+
+ def test_status_and_uninstall_readback(self):
+ self.arm()
+ self.prestart()
+ p = self.call('status')
+ self.assertLessEqual(len(p.stdout.encode()), 8192)
+ data = json.loads(p.stdout)
+ self.assertEqual(set(data['hashes']), set(bundle.MEMBERS))
+ self.assertEqual(data['marker'], 'consumed')
+ self.assertEqual(data['packets'], 4)
+ cleanup = json.loads(self.call('uninstall').stdout)
+ self.assertTrue(cleanup['uninstalled'])
+ self.assertFalse(self.state.exists())
+ self.assertFalse(self.lib.exists())
+ self.assertFalse((self.root / fault.DROP.lstrip('/')).exists())
+ self.assertFalse((self.root / 'table').exists())
+
+ def test_existing_table_is_not_replaced(self):
+ self.call('fault-now', *ARGS)
+ count = self.calls().count(['nft', '-f', '-'])
+ self.call('fault-now', *ARGS)
+ self.assertEqual(self.calls().count(['nft', '-f', '-']), count)
+
+
+class StaticTests(unittest.TestCase):
+ def test_root_test_variable_is_refused(self):
+ with patch.dict(os.environ, CARLOS_P3B2_FAULT_TEST_ROOT='/'), patch.object(fault.os, 'geteuid', return_value=0):
+ with self.assertRaises(ValueError):
+ fault.Harness()
+ source = (DIR / 'fault.sh').read_text()
+ self.assertIn('"$(/usr/bin/id -u)" = 0', source)
+ self.assertIn('exit 77', source)
+
+ def test_systemctl_timespan(self):
+ self.assertAlmostEqual(fault.span('1d 2h 3min 4s 500ms'), 93784.5)
+ self.assertEqual(fault.span('123000000'), 123)
+ with self.assertRaises(ValueError):
+ fault.span('n/a')
+
+ def test_reproducible_bundle_and_all_frames(self):
+ one, two = bundle.build(), bundle.build()
+ self.assertEqual(one, two)
+ self.assertLessEqual(len(base64.b64encode(one)), 60000)
+ with tarfile.open(fileobj=io.BytesIO(one)) as tar:
+ self.assertEqual(tar.getnames(), sorted(bundle.MEMBERS))
+ for member in tar.getmembers():
+ self.assertEqual((member.mtime, member.uid, member.gid, member.mode), (0, 0, 0, 0o600))
+ digest = hashlib.sha256(one).hexdigest()
+ nonce = 'a' * 32
+ cmds = [client.command('install', nonce)]
+ cmds += [client.command(v, nonce) for v in ('status', 'remove', 'disarm', 'uninstall')]
+ cmds += [client.command(v, nonce, iid=IID, boot=BOOT, transaction='witness-1', minutes=35)
+ for v in ('arm-fault', 'arm-pause', 'fault-now')]
+ for cmd in cmds:
+ self.assertIsNotNone(pattern(digest).fullmatch(cmd))
+ self.assertIsNone(pattern().fullmatch(cmd))
+ with self.assertRaises(RuntimeError):
+ client.result(nonce + ':BEGIN\n{}\n' + nonce + ':END:1\n', nonce)
+
+
+class RehearsalTests(unittest.TestCase):
+ def args(self):
+ return SimpleNamespace(profile='example', region='eu-west-1', subnet='subnet-example',
+ security_group='sg-example', instance_profile='example', ami='ami-example',
+ bucket='example-bucket', key_prefix='example', binary=Path('example-binary'),
+ binary_sha256='a' * 64, commit='b' * 40, evidence_dir=Path('.'), dry_run=False)
+
+ def test_dry_run_never_executes_aws_and_prints_cleanup(self):
+ with tempfile.TemporaryDirectory(prefix='b5-dry-', dir=ROOT / '.superpowers') as folder:
+ folder = Path(folder)
+ aws = folder / 'aws'
+ aws.write_text('#!/bin/sh\necho forbidden > "' + str(folder / 'called') + '"\nexit 99\n')
+ aws.chmod(0o700)
+ binary = folder / 'binary'
+ binary.write_bytes(b'pinned fixture')
+ commit = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True, text=True, check=True).stdout.strip()
+ command = [sys.executable, '-B', str(DIR / 'rehearse.py'), '--dry-run']
+ for key, value in vars(self.args()).items():
+ if key == 'dry_run': continue
+ value = {'binary': binary, 'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest(),
+ 'commit': commit, 'evidence_dir': folder / 'evidence'}.get(key, value)
+ command += ['--' + key.replace('_', '-'), str(value)]
+ p = subprocess.run(command, env=dict(os.environ, PATH=str(folder) + ':' + os.environ['PATH'],
+ PYTHONDONTWRITEBYTECODE='1'), capture_output=True, text=True, timeout=20)
+ self.assertEqual(p.returncode, 0, p.stderr)
+ self.assertFalse((folder / 'called').exists())
+ self.assertFalse((folder / 'evidence').exists())
+ self.assertIn('terminate-instances', p.stdout)
+ self.assertIn('instance-terminated', p.stdout)
+ self.assertIn('kernel: DRY RUN', p.stdout)
+ # Inspect the literal commands from every rehearsal SendCommand call.
+ sha = hashlib.sha256(bundle.build()).hexdigest()
+ for line in p.stdout.splitlines():
+ if not line.startswith('["aws"'): continue
+ words = json.loads(line)
+ if 'send-command' not in words: continue
+ commands = json.loads(words[words.index('--parameters') + 1])['commands']
+ for cmd in commands:
+ if cmd.startswith('/usr/bin/env -i '):
+ self.assertIsNotNone(pattern(sha).fullmatch(cmd))
+ self.assertIsNone(pattern().fullmatch(cmd))
+
+ def test_termination_after_exception_launch_loss_and_upload_failure(self):
+ for stage in ('after-launch', 'lost-launch', 'upload'):
+ with self.subTest(stage=stage):
+ calls = []
+ class Fake:
+ history = []
+ def call(self, *args, **kwargs):
+ calls.append(args)
+ if args[:2] == ('ec2', 'run-instances'):
+ if stage == 'lost-launch': raise RuntimeError('lost response')
+ return {'Instances': [{'InstanceId': IID}]}
+ if args[:2] == ('ec2', 'describe-instances'):
+ return {'Reservations': [{'Instances': [{'InstanceId': IID}]}]}
+ return {}
+ r = rehearse.Rehearsal(self.args(), Fake(), sleep=lambda _: None)
+ with patch.object(r, 'prepare', side_effect=RuntimeError('forced')), \
+ patch.object(r, 'save', side_effect=RuntimeError('upload') if stage == 'upload' else None):
+ with self.assertRaises(RuntimeError):
+ r.run()
+ self.assertIn(('ec2', 'terminate-instances', '--instance-ids', IID), calls)
+ self.assertIn(('ec2', 'wait', 'instance-terminated', '--instance-ids', IID), calls)
+
+ def test_signal_after_launch_still_terminates(self):
+ import signal
+ calls = []
+ class Fake:
+ history = []
+ def call(self, *args, **kwargs):
+ calls.append(args)
+ if args[:2] == ('ec2', 'run-instances'):
+ return {'Instances': [{'InstanceId': IID}]}
+ return {}
+ r = rehearse.Rehearsal(self.args(), Fake(), sleep=lambda _: None)
+ def interrupt():
+ signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None)
+ with patch.object(r, 'prepare', side_effect=interrupt), patch.object(r, 'save'):
+ with self.assertRaises(InterruptedError):
+ r.run()
+ self.assertIn(('ec2', 'terminate-instances', '--instance-ids', IID), calls)
+
+ def test_phase_assertions_reject_old_expiry_and_counters(self):
+ r = rehearse.Rehearsal(self.args(), None)
+ data = dict(status=dict(marker='consumed', table_present=False, packets=0),
+ log=[dict(event='table-added'), dict(event='counters', packets=4),
+ dict(event='expire'), dict(event='table-added'), dict(event='counters', packets=4)],
+ probe=[])
+ with self.assertRaises(RuntimeError):
+ r.assert_fault(data, 'prestart', True)
+ data['status'].update(table_present=True, timer={'ActiveState': 'active'})
+ data['log'][-2]['kernel_timeout'] = True
+ data['log'][-1]['packets'] = 0
+ with self.assertRaises(RuntimeError):
+ r.assert_fault(data, 'kernel', False)
+
+ def test_generated_probe_compiles_and_writes_newlines(self):
+ import ast
+ source = rehearse.probe_source('eu-west-1', 'example-bucket')
+ tree = ast.parse(source)
+ compile(tree, 'generated-probe', 'exec')
+ self.assertTrue(any(isinstance(n, ast.Constant) and n.value == '\n' for n in ast.walk(tree)))
+
+ def test_termination_retries_and_leak_is_explicit(self):
+ class Fake:
+ def call(self, *args, **kwargs):
+ raise RuntimeError('forced')
+ r = rehearse.Rehearsal(self.args(), Fake(), sleep=lambda _: None)
+ r.iid = IID
+ with patch('sys.stdout', new_callable=io.StringIO) as out:
+ with self.assertRaises(RuntimeError): r.terminate()
+ self.assertIn('LEAKED ' + IID, out.getvalue())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/region_group_frames.py b/scripts/region_group_frames.py
index d09c3dfe8..7953e97db 100644
--- a/scripts/region_group_frames.py
+++ b/scripts/region_group_frames.py
@@ -17,8 +17,8 @@ TEXT = {
"frame": "The maintenance command frame has changed",
"bundle": "Use 1 to 60000 base64 characters for the witness bundle",
"sha256": "Use a 64-character lowercase hexadecimal bundle SHA256 digest",
- "verb": "Use status, disarm, remove, uninstall, arm-fault or arm-pause",
- "arguments": "Only arm-fault and arm-pause accept identity and duration arguments",
+ "verb": "Use status, disarm, remove, uninstall, arm-fault, arm-pause or fault-now",
+ "arguments": "Only arm-fault, arm-pause and fault-now accept identity and duration arguments",
"iid": "Use an instance ID with 8 or 17 lowercase hexadecimal digits",
"boot": "Use a lowercase UUID for the boot ID",
"transaction": "Use 1 to 80 letters, digits, underscores or hyphens for the transaction",
@@ -68,7 +68,7 @@ def harness_command(verb, nonce, *, iid=None, boot=None, transaction=None, minut
if any(value is not None for value in (iid, boot, transaction, minutes)):
raise ValueError(TEXT["arguments"])
return frame_command(inner + verb, nonce)
- if verb not in {"arm-fault", "arm-pause"}:
+ if verb not in {"arm-fault", "arm-pause", "fault-now"}:
raise ValueError(TEXT["verb"])
_check(r"i-([0-9a-f]{8}|[0-9a-f]{17})", iid, "iid")
_check(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", boot, "boot")