region HA P3b-2 ops: fault harness review fixes (B5 R1)
7 files changed,
+304
−56
infra/modules/region-group-operator-document/README.md+2 −1scripts/region-group-fault/README.md+31 −11scripts/region-group-fault/fault.py+40 −9scripts/region-group-fault/fault.sh+3 −0scripts/region-group-fault/rehearse.py+46 −12scripts/region-group-fault/text.json+3 −1scripts/region_group_fault_test.py+179 −22
diff --git a/infra/modules/region-group-operator-document/README.md b/infra/modules/region-group-operator-document/README.md| index 8979a57ee..363042ce4 100644 |
| --- a/infra/modules/region-group-operator-document/README.md |
| +++ b/infra/modules/region-group-operator-document/README.md |
| @@ -86,6 +86,7 @@ The remaining forms are: |
| ```sh |
| /bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh arm-fault --iid IID --boot BOOT --transaction TRANSACTION --minutes MINUTES |
| /bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh arm-pause --iid IID --boot BOOT --transaction TRANSACTION --minutes MINUTES |
| +/bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh fault-now --iid IID --boot BOOT --transaction TRANSACTION --minutes MINUTES |
| ``` |
| `IID` is `i-` followed by 8 or 17 lowercase hexadecimal digits. `BOOT` has |
| @@ -97,7 +98,7 @@ identity and transaction against the member before arming a fault. |
| Use `scripts/region_group_frames.py` to build H commands without executing them: |
| `install_command(bundle_b64, sha256, nonce)` and |
| `harness_command(verb, nonce, *, iid=None, boot=None, transaction=None, minutes=None)`. |
| -The latter requires all four keyword fields for arm commands and refuses them |
| +The latter requires all four keyword fields for arm commands and `fault-now` and refuses them |
| for other verbs. The helper derives its frame from the real operator's status |
| command, so the framing stays shared without editing the operator. |
diff --git a/scripts/region-group-fault/README.md b/scripts/region-group-fault/README.md| index 3ebdbb16c..c2a2ccfdb 100644 |
| --- a/scripts/region-group-fault/README.md |
| +++ b/scripts/region-group-fault/README.md |
| @@ -22,14 +22,17 @@ and `--minutes 35`. There are no deployment defaults. |
| | `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. | |
| +| `remove` | Delete only `inet carlos_p3b2_fault` and verify absence. Stop the expiry timer after deletion. Leave the marker and drop-in 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. |
| +the roll. An END frame from `fault-now` means "not proven injected": read |
| +`status` to confirm the table and counters. R6 requires a refusal to return zero. |
| +After recovery, arm the restart fault, run the attended roll and |
| +observe Standby. After every roll, check `status` and run `disarm`, including |
| +a failed roll. 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. |
| @@ -50,20 +53,23 @@ 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. |
| +IPv6 HTTPS uses a separate expiring set that excludes `::1/128` and `fe80::/10`. |
| 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. |
| +Arming refuses a loaded expiry timer unless it is inactive. Use `remove` to |
| +delete the old table and stop that timer before arming again. |
| 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. |
| +worker, capped at 60 seconds, to keep nftables outside the edge sandbox. |
| +The worker waits up to 10 seconds for the operator lock. It never initiates |
| +an edge restart. |
| ## Controller rehearsal |
| @@ -81,14 +87,28 @@ 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. |
| +be installed on a group member. |
| + |
| +The driver extracts `60-hairpin.conf`, the hairpin reset service and the |
| +`carlos_group_imds` setup from `group-init.sh.tftpl` at the pinned commit. |
| +It installs the units and IMDS rules unchanged, resolving the runner's `carlos` |
| +uid. Evidence includes source hashes, the effective pre-start commands, the |
| +IMDS table and reset/edge journals. Hairpin installation, protected address |
| +state and sysctl setup are skipped because the runner has no signed group |
| +marker or address snapshot. The reset hook can therefore be a no-op; inspect |
| +its journal before accepting the ordering evidence. |
| + |
| +Phase 5 proves drop-in/marker file survival across unit rewrite and |
| +`daemon-reload`, not the guarded `requireGroupMaintenance("repair")` path: |
| +there is no group marker on the runner. It compares file hashes across rewriting |
| +`carlos-edge.service` and `50-group.conf`. It does not invoke `adopt`. |
| +Only each phase's deliberate restart may restart the edge while armed. |
| 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. |
| +requests termination on exit or SIGINT/SIGTERM/SIGHUP, retries failures and |
| +waits for the terminated state. The root volume mapping uses the AMI's |
| +`RootDeviceName` from `describe-images`. |
| 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/fault.py b/scripts/region-group-fault/fault.py| index 336e1c1d6..47b8f2b4f 100644 |
| --- a/scripts/region-group-fault/fault.py |
| +++ b/scripts/region-group-fault/fault.py |
| @@ -155,9 +155,14 @@ class Harness: |
| 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) |
| + '--property=NextElapseUSecMonotonic', '--property=LoadState', check=False) |
| + values = dict(line.split('=', 1) for line in p.stdout.splitlines() if '=' in line) |
| + require(p.returncode == 0 or values.get('LoadState') == 'not-found') |
| + return values |
| + |
| + def timer_available(self): |
| + timer = self.timer() |
| + require(timer.get('LoadState') == 'not-found' or timer.get('ActiveState') == 'inactive') |
| def rules(self, marker, nets, timeout=True): |
| allowed = nets + [ipaddress.IPv4Network('127.0.0.0/8'), |
| @@ -173,11 +178,16 @@ class Harness: |
| 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)) |
| + remaining6 = [ipaddress.IPv6Network('::/0')] |
| + for skip in (ipaddress.IPv6Network('::1/128'), ipaddress.IPv6Network('fe80::/10')): |
| + remaining6 = [part for net in remaining6 for part in ( |
| + net.address_exclude(skip) if skip.subnet_of(net) else [net])] |
| + v6 = ', '.join(str(n) + ttl for n in sorted(remaining6)) |
| 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 element inet {TABLE} fault_dst6 {{ {v6} }}', |
| 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' |
| @@ -193,6 +203,7 @@ class Harness: |
| def inject(self, marker, nets): |
| require(self.table() is None) |
| + self.timer_available() |
| minutes = marker['minutes'] |
| # Only the isolated rehearsal runner writes this root-owned file. |
| delay = self.state / 'rehearsal-timer-minutes' |
| @@ -235,6 +246,7 @@ class Harness: |
| nets = self.identity(marker, False) |
| require(not (self.state / 'marker.json').exists()) |
| require(self.table() is None) |
| + self.timer_available() |
| if verb == 'fault-now': |
| self.log('fault-now', **marker) |
| self.inject(marker, nets) |
| @@ -265,11 +277,18 @@ class Harness: |
| 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) |
| + try: |
| + table = self.table() |
| + if table is not None: |
| + record('counters', packets=packets(table)) |
| + except (OSError, ValueError, subprocess.SubprocessError): |
| + pass |
| + # Counter evidence must never gate removal. Readback decides success. |
| + run('nft', 'delete', 'table', 'inet', TABLE, check=False) |
| require(self.table() is None) |
| + if event == 'remove': |
| + run('systemctl', 'stop', TIMER + '.timer', check=False) |
| + self.timer_available() |
| record(event) |
| record('removal-readback', table_present=False) |
| @@ -331,6 +350,18 @@ def emit(data): |
| print(body) |
| +def acquire_lock(lock, wait=False): |
| + deadline = time.monotonic() + 10 |
| + while True: |
| + try: |
| + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| + return |
| + except BlockingIOError: |
| + if not wait or time.monotonic() >= deadline: |
| + raise |
| + time.sleep(0.05) |
| + |
| + |
| def main(): |
| os.umask(0o077) |
| h = None |
| @@ -357,7 +388,7 @@ def main(): |
| 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) |
| + acquire_lock(lock, wait=verb == 'consume') |
| if verb in {'arm-fault', 'arm-pause', 'fault-now'}: |
| h.arm(verb, sys.argv[2:]) |
| else: |
diff --git a/scripts/region-group-fault/fault.sh b/scripts/region-group-fault/fault.sh| index 2fe6fec9d..32c4918b4 100644 |
| --- a/scripts/region-group-fault/fault.sh |
| +++ b/scripts/region-group-fault/fault.sh |
| @@ -1,12 +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 |
| + [ "${1-}" = prestart ] && exit 0 |
| exit 77 |
| fi |
| if [ "${CARLOS_P3B2_FAULT_TEST_ROOT+x}" != x ]; then |
| PATH=/usr/sbin:/usr/bin:/sbin:/bin |
| export PATH |
| fi |
| +LC_ALL=C |
| +export LC_ALL |
| here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 0 |
| if [ "${1-}" = prestart ]; then |
| python3 -I -B "$here/fault.py" "$@" |
diff --git a/scripts/region-group-fault/rehearse.py b/scripts/region-group-fault/rehearse.py| index 4acc0b414..88d7bc002 100644 |
| --- a/scripts/region-group-fault/rehearse.py |
| +++ b/scripts/region-group-fault/rehearse.py |
| @@ -1,4 +1,5 @@ |
| import argparse |
| +import ast |
| import base64 |
| import hashlib |
| import json |
| @@ -22,6 +23,9 @@ 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') |
| +GROUP_INIT = 'infra/modules/region-host/group-init.sh.tftpl' |
| +HAIRPIN_FILES = ('/etc/systemd/system/carlos-edge.service.d/60-hairpin.conf', |
| + '/etc/systemd/system/carlos-hairpin-reset.service') |
| def check(value): |
| @@ -132,7 +136,19 @@ while True: |
| 'https://ssm.' + region + '.amazonaws.com/') |
| -def setup_commands(args, binary_url, units): |
| +def group_setup(source): |
| + # Parse literals from the pinned template; never execute its bootstrap. |
| + hairpin = source.split("python3 - <<'PYHAIRPIN'\n", 1)[1].split('\nPYHAIRPIN', 1)[0] |
| + assignments = [n for n in ast.parse(hairpin).body if isinstance(n, ast.Assign) |
| + and any(isinstance(t, ast.Name) and t.id == 'files' for t in n.targets)] |
| + check(len(assignments) == 1) |
| + files = ast.literal_eval(assignments[0].value) |
| + imds = source.split('# harden metadata\n', 1)[1].split('\n# install maintenance channel', 1)[0] |
| + check('table inet carlos_group_imds {' in imds and '${' not in imds) |
| + return {name: files[name] for name in HAIRPIN_FILES}, imds |
| + |
| + |
| +def setup_commands(args, binary_url, units, group_files, imds_setup): |
| 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, |
| @@ -143,6 +159,9 @@ def setup_commands(args, binary_url, units): |
| 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')) |
| + for path, data in group_files.items(): |
| + lines.append(write_command(path, data, '0644')) |
| + lines += ['CARLOS_UID=$(id -u carlos); export CARLOS_UID', imds_setup] |
| 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)), |
| @@ -160,8 +179,10 @@ class Rehearsal: |
| self.iid = None |
| self.boot = BOOT |
| self.verdicts = {phase: 'NOT RUN' for phase in PHASES} |
| - self.evidence = {} |
| + self.evidence = {'repair_scope': TEXT['repair_scope'], 'hairpin_scope': TEXT['hairpin_scope']} |
| self.units = {} |
| + self.group_files = {} |
| + self.imds_setup = '' |
| self.installed = False |
| def wait(self, predicate, seconds=240): |
| @@ -187,12 +208,17 @@ class Rehearsal: |
| return self.api.remote(self.iid, list(commands), wait=wait) |
| def launch(self): |
| + images = self.api.call('ec2', 'describe-images', '--image-ids', self.a.ami) |
| + # Dry run cannot resolve the AMI; keep the dependency visible in its command. |
| + root_device = '<AMI RootDeviceName>' if self.a.dry_run else images['Images'][0]['RootDeviceName'] |
| + check(root_device and (self.a.dry_run or root_device.startswith('/dev/'))) |
| + self.evidence['root_device'] = root_device |
| 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': { |
| + '--block-device-mappings', json.dumps([{'DeviceName': root_device, 'Ebs': { |
| 'VolumeSize': 8, 'VolumeType': 'gp3', 'Encrypted': True, 'DeleteOnTermination': True}}]), |
| '--tag-specifications', json.dumps([{'ResourceType': 'instance', 'Tags': [ |
| {'Key': 'purpose', 'Value': 'p3b2-fault-rehearsal'}]}]), |
| @@ -218,8 +244,12 @@ class Rehearsal: |
| self.evidence['iid'] = self.iid |
| self.frame('install') |
| self.installed = True |
| + self.evidence['group_setup_sha256'] = {k: hashlib.sha256(v.encode()).hexdigest() |
| + for k, v in self.group_files.items()} |
| + self.evidence['group_setup_sha256'][GROUP_INIT + ':imds'] = hashlib.sha256(self.imds_setup.encode()).hexdigest() |
| 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)) |
| + output = self.api.remote(self.iid, setup_commands(self.a, urls['carlos'] or '<presigned-binary>', |
| + self.units, self.group_files, self.imds_setup)) |
| if not self.a.dry_run: |
| self.boot = output.strip().splitlines()[-1] |
| self.wait(lambda: self.has_baseline(), 60) |
| @@ -231,7 +261,9 @@ 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} |
| + 'edge_prestart':subprocess.run(['systemctl','show','carlos-edge.service','--property=ExecStartPre'],capture_output=True,text=True).stdout, |
| + 'imds':subprocess.run(['nft','-j','list','table','inet','carlos_group_imds'],capture_output=True,text=True).stdout, |
| + 'journal':subprocess.run(['journalctl','--no-pager','-n','30','-u','carlos-p3b2-fault-expire.service','-u','carlos-p3b2-fault-prestart.service','-u','carlos-hairpin-reset.service','-u','carlos-edge.service'],capture_output=True,text=True).stdout} |
| print(base64.b64encode(zlib.compress(json.dumps(v).encode())).decode()) |
| """ |
| output = self.remote('python3 -c ' + q(code)) |
| @@ -338,15 +370,13 @@ print(base64.b64encode(zlib.compress(json.dumps(v).encode())).decode()) |
| 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') |
| + self.remote(write_command('/etc/systemd/system/carlos-edge.service', |
| + self.units['carlos-edge.service'], '0644'), |
| + write_command('/etc/systemd/system/carlos-edge.service.d/50-group.conf', |
| + self.units['carlos-edge-group.conf'], '0644'), 'systemctl daemon-reload') |
| 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') |
| @@ -409,7 +439,7 @@ print(base64.b64encode(zlib.compress(json.dumps(v).encode())).decode()) |
| def interrupted(signum, _frame): |
| raise InterruptedError(str(signum)) |
| try: |
| - for sig in (signal.SIGINT, signal.SIGTERM): |
| + for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): |
| handlers[sig] = signal.signal(sig, interrupted) |
| self.launch() |
| self.prepare() |
| @@ -455,6 +485,10 @@ def main(): |
| 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 |
| + group_source = subprocess.run(['git', 'show', a.commit + ':' + GROUP_INIT], |
| + text=True, capture_output=True, check=True).stdout |
| + runner.group_files, runner.imds_setup = group_setup(group_source) |
| + runner.evidence['group_init_sha256'] = hashlib.sha256(group_source.encode()).hexdigest() |
| a.evidence_dir = a.evidence_dir / runner.token |
| if not a.dry_run: |
| a.evidence_dir.mkdir(mode=0o700, parents=True, exist_ok=False) |
diff --git a/scripts/region-group-fault/text.json b/scripts/region-group-fault/text.json| index 8b466b2bf..799cd183d 100644 |
| --- a/scripts/region-group-fault/text.json |
| +++ b/scripts/region-group-fault/text.json |
| @@ -13,5 +13,7 @@ |
| "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." |
| + "log_failed": "Local evidence could not be written. Fault removal continues.", |
| + "repair_scope": "Phase 5 proves drop-in and marker file survival across unit rewrite and daemon-reload. It does not exercise requireGroupMaintenance(\"repair\"): there is no group marker on the runner. No adopt command runs while armed.", |
| + "hairpin_scope": "The pinned 60-hairpin.conf, reset service and carlos_group_imds setup are installed. Reset hooks run in the pinned order. Hairpin installation, address state and sysctl setup are skipped because the runner has no signed group marker or protected address snapshot; reset can be a no-op. Inspect the journal and ExecStartPre evidence before accepting ordering." |
| } |
diff --git a/scripts/region_group_fault_test.py b/scripts/region_group_fault_test.py| index fbdc615e8..288343e31 100644 |
| --- a/scripts/region_group_fault_test.py |
| +++ b/scripts/region_group_fault_test.py |
| @@ -61,27 +61,30 @@ elif name == 'systemd-run': |
| 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))}) |
| + save('timer', {'LoadState': 'loaded', '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'} |
| + values = json.loads((root / 'timer').read_text()) if (root / 'timer').exists() else {'LoadState': 'not-found', 'ActiveState': 'inactive', 'NextElapseUSecMonotonic': '0'} |
| + if config.get('timer_state'): values.update(config['timer_state']) |
| 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)) |
| + if config.get('timer_missing_error'): sys.exit(1) |
| elif args[0] == 'stop': |
| + if config.get('timer_missing_error'): sys.exit(5) |
| 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'): |
| + if config.get('list_error') or (config.get('list_error_present') and (root / 'table').exists()): |
| 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() |
| + (root / 'table').unlink(missing_ok=True) |
| elif args in [['-c', '-f', '-'], ['-f', '-']]: |
| rules = sys.stdin.read() |
| with (root / 'rules').open('a') as f: f.write(rules) |
| @@ -101,7 +104,7 @@ class HarnessTests(unittest.TestCase): |
| 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.tmp = tempfile.TemporaryDirectory(prefix='b5-test-') |
| 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') |
| @@ -158,7 +161,7 @@ class HarnessTests(unittest.TestCase): |
| 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']) |
| + verify = next(i for i, c in enumerate(calls) if i > timer and c[:2] == ['systemctl', 'show']) |
| self.assertIn(['marker-at-timer', False], calls) |
| self.assertNotIn(['marker-at-timer', True], calls) |
| self.assertLess(timer, verify) |
| @@ -183,6 +186,7 @@ class HarnessTests(unittest.TestCase): |
| self.assertNotIn(['nft', '-f', '-'], self.calls()) |
| self.change(**{setting: False}) |
| self.call('disarm') |
| + self.call('remove') |
| def test_mismatches_do_not_consume_or_inject(self): |
| self.arm() |
| @@ -237,7 +241,12 @@ class HarnessTests(unittest.TestCase): |
| self.prestart() |
| rules = (self.root / 'rules').read_text() |
| self.assertIn('flags interval, timeout', rules) |
| - self.assertIn('::/0 timeout 35m', rules) |
| + v6 = re.search(r'add element inet carlos_p3b2_fault fault_dst6 \{ (.*?) \}', rules)[1] |
| + nets6 = [ipaddress.ip_network(e.split(' timeout ')[0]) for e in v6.split(', ')] |
| + self.assertTrue(all(e.endswith(' timeout 35m') for e in v6.split(', '))) |
| + for value in ('::1', 'fe80::1', 'febf:ffff::1'): |
| + self.assertFalse(any(ipaddress.ip_address(value) in n for n in nets6)) |
| + self.assertTrue(any(ipaddress.ip_address('2606:4700::1111') in n for n in nets6)) |
| 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) |
| @@ -253,7 +262,7 @@ class HarnessTests(unittest.TestCase): |
| 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.call('remove') |
| (self.root / 'rules').unlink() |
| def test_expire_is_local_scoped_and_absence_succeeds(self): |
| @@ -288,7 +297,80 @@ class HarnessTests(unittest.TestCase): |
| 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()) |
| + self.assertIn(['nft', 'delete', 'table', 'inet', fault.TABLE], self.calls()) |
| + |
| + def test_existing_timer_refuses_every_arm_without_consuming_marker(self): |
| + for state in ({'LoadState': 'loaded', 'ActiveState': 'active'}, |
| + {'LoadState': 'loaded', 'ActiveState': 'activating'}, |
| + {'LoadState': 'loaded', 'ActiveState': 'failed'}): |
| + self.change(timer_state=state) |
| + for verb in ('arm-fault', 'arm-pause', 'fault-now'): |
| + with self.subTest(state=state, verb=verb): |
| + result = self.call(verb, *ARGS, check=False) |
| + self.assertEqual(result.returncode, 0 if verb == 'fault-now' else 1) |
| + self.assertFalse((self.state / 'marker.json').exists()) |
| + self.assertNotIn(['nft', '-f', '-'], self.calls()) |
| + self.change(timer_state={'LoadState': 'loaded', 'ActiveState': 'inactive'}) |
| + self.arm() |
| + |
| + def test_unloaded_timer_can_be_armed_and_removed_when_systemctl_returns_nonzero(self): |
| + self.change(timer_missing_error=True) |
| + self.arm() |
| + self.call('disarm') |
| + self.call('remove') |
| + self.assertIn(['nft', 'delete', 'table', 'inet', fault.TABLE], self.calls()) |
| + |
| + def test_failed_inject_requires_timer_cleanup_before_next_arm(self): |
| + self.change(add_error=True) |
| + self.call('fault-now', *ARGS) |
| + self.change(add_error=False) |
| + self.assertNotEqual(self.call('arm-fault', *ARGS, check=False).returncode, 0) |
| + self.call('remove') |
| + self.arm() |
| + self.prestart() |
| + self.assertTrue((self.root / 'table').exists()) |
| + |
| + def test_remove_stops_timer_after_deletion_and_allows_next_fault(self): |
| + self.call('fault-now', *ARGS) |
| + self.call('remove') |
| + calls = self.calls() |
| + self.assertLess(calls.index(['nft', 'delete', 'table', 'inet', fault.TABLE]), |
| + calls.index(['systemctl', 'stop', fault.TIMER + '.timer'])) |
| + self.assertEqual(json.loads((self.root / 'timer').read_text())['ActiveState'], 'inactive') |
| + self.arm() |
| + self.prestart() |
| + self.assertTrue((self.root / 'table').exists()) |
| + |
| + def test_unknown_counter_read_failure_still_deletes_and_checks_absence(self): |
| + for verb in ('expire', 'remove'): |
| + with self.subTest(verb=verb): |
| + self.call('remove') |
| + self.call('fault-now', *ARGS) |
| + self.change(list_error_present=True) |
| + self.call(verb) |
| + self.assertFalse((self.root / 'table').exists()) |
| + self.assertEqual(self.events()[-1]['event'], 'removal-readback') |
| + self.change(list_error_present=False) |
| + |
| + def test_consume_waits_for_concurrent_operator_lock(self): |
| + import fcntl |
| + self.arm() |
| + with (self.state / 'lock').open('w') as lock: |
| + fcntl.flock(lock, fcntl.LOCK_EX) |
| + proc = subprocess.Popen(['/bin/sh', str(self.lib / 'fault.sh'), 'consume'], |
| + env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| + try: |
| + time.sleep(0.4) |
| + self.assertIsNone(proc.poll()) |
| + self.assertTrue((self.state / 'marker.json').exists()) |
| + fcntl.flock(lock, fcntl.LOCK_UN) |
| + _, err = proc.communicate(timeout=15) |
| + self.assertEqual(proc.returncode, 0, err) |
| + self.assertTrue((self.root / 'table').exists()) |
| + finally: |
| + if proc.poll() is None: |
| + proc.kill() |
| + proc.communicate() |
| def test_kernel_fallback_is_loud_and_timer_verified(self): |
| self.change(no_timeout=True) |
| @@ -339,6 +421,31 @@ class StaticTests(unittest.TestCase): |
| self.assertIn('"$(/usr/bin/id -u)" = 0', source) |
| self.assertIn('exit 77', source) |
| + def test_root_test_variable_prestart_succeeds_other_verbs_refuse(self): |
| + with tempfile.TemporaryDirectory(prefix='b5-root-') as folder: |
| + script = Path(folder) / 'fault.sh' |
| + script.write_text((DIR / 'fault.sh').read_text().replace('/usr/bin/id -u', 'printf 0')) |
| + for verb in ('prestart', 'consume', 'status', 'fault-now', 'expire'): |
| + p = subprocess.run(['/bin/sh', str(script), verb], capture_output=True, |
| + env=dict(os.environ, CARLOS_P3B2_FAULT_TEST_ROOT=folder)) |
| + self.assertEqual(p.returncode, 0 if verb == 'prestart' else 77) |
| + |
| + def test_consume_lock_wait_is_bounded_under_sixty_seconds(self): |
| + with patch.object(fault.fcntl, 'flock', side_effect=BlockingIOError), \ |
| + patch.object(fault.time, 'monotonic', side_effect=[0, 0, 10]), \ |
| + patch.object(fault.time, 'sleep'): |
| + with self.assertRaises(BlockingIOError): |
| + fault.acquire_lock(None, wait=True) |
| + |
| + def test_shell_exports_c_locale(self): |
| + with tempfile.TemporaryDirectory(prefix='b5-locale-') as folder: |
| + script = Path(folder) / 'fault.sh' |
| + script.write_text((DIR / 'fault.sh').read_text()) |
| + (Path(folder) / 'fault.py').write_text('import os; print(os.environ.get("LC_ALL"))') |
| + p = subprocess.run(['/bin/sh', str(script), 'status'], capture_output=True, text=True, |
| + env=dict(os.environ, LC_ALL='POSIX', CARLOS_P3B2_FAULT_TEST_ROOT=folder)) |
| + self.assertEqual(p.stdout.strip(), 'C') |
| + |
| def test_systemctl_timespan(self): |
| self.assertAlmostEqual(fault.span('1d 2h 3min 4s 500ms'), 93784.5) |
| self.assertEqual(fault.span('123000000'), 123) |
| @@ -374,7 +481,7 @@ class RehearsalTests(unittest.TestCase): |
| 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: |
| + with tempfile.TemporaryDirectory(prefix='b5-dry-') as folder: |
| folder = Path(folder) |
| aws = folder / 'aws' |
| aws.write_text('#!/bin/sh\necho forbidden > "' + str(folder / 'called') + '"\nexit 99\n') |
| @@ -416,6 +523,8 @@ class RehearsalTests(unittest.TestCase): |
| history = [] |
| def call(self, *args, **kwargs): |
| calls.append(args) |
| + if args[:2] == ('ec2', 'describe-images'): |
| + return {'Images': [{'RootDeviceName': '/dev/xvda'}]} |
| if args[:2] == ('ec2', 'run-instances'): |
| if stage == 'lost-launch': raise RuntimeError('lost response') |
| return {'Instances': [{'InstanceId': IID}]} |
| @@ -430,23 +539,71 @@ class RehearsalTests(unittest.TestCase): |
| 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): |
| + def test_signals_after_launch_still_terminate(self): |
| import signal |
| + for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): |
| + with self.subTest(signal=sig): |
| + calls = [] |
| + class Fake: |
| + history = [] |
| + def call(self, *args, **kwargs): |
| + calls.append(args) |
| + if args[:2] == ('ec2', 'describe-images'): |
| + return {'Images': [{'RootDeviceName': '/dev/xvda'}]} |
| + if args[:2] == ('ec2', 'run-instances'): |
| + return {'Instances': [{'InstanceId': IID}]} |
| + return {} |
| + r = rehearse.Rehearsal(self.args(), Fake(), sleep=lambda _: None) |
| + def interrupt(): |
| + handler = signal.getsignal(sig) |
| + self.assertTrue(callable(handler)) |
| + handler(sig, 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_launch_uses_ami_root_device(self): |
| 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) |
| + if args[:2] == ('ec2', 'describe-images'): |
| + return {'Images': [{'RootDeviceName': '/dev/xvda'}]} |
| + return {'Instances': [{'InstanceId': IID}]} |
| + r = rehearse.Rehearsal(self.args(), Fake()) |
| + r.launch() |
| + self.assertEqual(calls[0], ('ec2', 'describe-images', '--image-ids', r.a.ami)) |
| + launch = calls[-1] |
| + mapping = json.loads(launch[launch.index('--block-device-mappings') + 1]) |
| + self.assertEqual(mapping[0]['DeviceName'], '/dev/xvda') |
| + |
| + def test_pinned_hairpin_and_imds_setup_and_repair_without_adopt(self): |
| + source = (ROOT / 'infra/modules/region-host/group-init.sh.tftpl').read_text() |
| + files, imds = rehearse.group_setup(source) |
| + drop = '/etc/systemd/system/carlos-edge.service.d/60-hairpin.conf' |
| + reset = '/etc/systemd/system/carlos-hairpin-reset.service' |
| + self.assertIn('ExecStartPre=+/usr/bin/systemctl start carlos-hairpin-reset.service', files[drop]) |
| + self.assertIn('ExecStart=/opt/carlos/carlos instance-control --group-hairpin-reset', files[reset]) |
| + self.assertIn('table inet carlos_group_imds {', imds) |
| + self.assertIn('meta skuid != { 0, $CARLOS_UID }', imds) |
| + self.assertIn(imds, source) |
| + r = rehearse.Rehearsal(self.args(), None) |
| + r.a.dry_run = True |
| + r.units = {'carlos-edge-group.conf': '[Service]\nRestart=no\n', |
| + 'carlos-edge.service': '[Service]\nExecStart=/opt/carlos/carlos agent\n'} |
| + r.group_files, r.imds_setup = files, imds |
| + lines = rehearse.setup_commands(r.a, 'example-url', r.units, files, imds) |
| + self.assertIn(imds, lines) |
| + self.assertIn(rehearse.write_command(drop, files[drop], '0644'), lines) |
| + commands = [] |
| + with patch.object(r, 'frame'), patch.object(r, 'collect', return_value={}), \ |
| + patch.object(r, 'remote', side_effect=lambda *cmds, **kw: commands.extend(cmds)): |
| + r.phases() |
| + self.assertFalse(any('/opt/carlos/carlos adopt' in cmd for cmd in commands)) |
| + self.assertEqual(sum('systemctl restart carlos-edge.service' in cmd for cmd in commands), 3) |
| + self.assertIn('requireGroupMaintenance("repair")', r.evidence['repair_scope']) |
| + self.assertIn('no group marker', r.evidence['repair_scope']) |
| def test_phase_assertions_reject_old_expiry_and_counters(self): |
| r = rehearse.Rehearsal(self.args(), None) |