carlos / platform Public

scripts: PPv2 step gate, convergence record and probe

ppv2-step.py is the only way the NLB target group attributes change:
apply checks state address, live state (S0-S3), the move, the
predecessor record, health and every target's trust-status, then a
targeted tofu plan of exactly one attribute, restoring the tfvars file
on any refusal. converge writes the next step's evidence; prereq writes
prereq.json. ppv2-probe.py is the per-address convergence and forgery
probe. Tests use recorded JSON and fake aws/tofu; no network.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 900852a9a4a83da4fc620bb26dd953d8891f2f7b parent 755e33f
8 files changed, +2,097 −0
  • scripts/ppv2-probe.py +322 −0
  • scripts/ppv2-step.py +739 −0
  • scripts/ppv2_probe_test.py +180 −0
  • scripts/ppv2_step_test.py +746 −0
  • scripts/testdata/ppv2/plan-a80.json +59 −0
  • scripts/testdata/ppv2/probe-responses.json +36 −0
  • scripts/testdata/ppv2/tofu-state-show-tg80.jsonl +2 −0
  • scripts/testdata/ppv2/trust-status.json +13 −0
diff --git a/scripts/ppv2-probe.py b/scripts/ppv2-probe.py
new file mode 100755
index 000000000..9817b2974
--- /dev/null
+++ b/scripts/ppv2-probe.py
@@ -0,0 +1,322 @@
+#!/usr/bin/env python3
+"""The PPv2 convergence and forgery probe (edge PPv2 spec 6.4, 10).
+
+Run on the probe host in the NLB's region, one process per NLB address and
+port, each with its own source port range so the probe never sends one source
+port to both addresses. Every 2 s it opens two fresh connections:
+
+ plain a request to the echo app, which answers with the X-Forwarded-For it
+ received (its body's first line). :443 must answer 200 with the
+ last entry equal to --expect-client; :80 must answer 302 (today's
+ redirect to HTTPS), which is not followed.
+ marker a PPv2 header claiming source 192.0.2.1 (TEST-NET-1), then the same
+ request. In S0 the edge ignores a client's header, so the marker
+ answers like plain. In S1 and S2 the NLB's header comes first and
+ the marker is payload, so it fails: a 400, a TLS alert or a close.
+
+It passes after 30 consecutive attempts that match --expect. It fails at once
+when plain answers anything else, or when any echo carries 192.0.2.1: a
+forged marker believed is S3 (spec 6.2). The record (--out) carries nlb_ip,
+port, started_at, passed and every attempt; `ppv2-step.py converge` reads it.
+
+Exit codes: 0 passed, 1 failed or timed out, 2 invalid arguments.
+"""
+import argparse
+from datetime import datetime, timezone
+import errno
+import ipaddress
+import json
+import os
+from pathlib import Path
+import re
+import socket
+import ssl
+import struct
+import sys
+import time
+
+SIGNATURE = b'\r\n\r\n\x00\r\nQUIT\n'
+MARKER_SOURCE = '192.0.2.1'
+MARKER_NET = ipaddress.ip_network('192.0.2.0/24')
+NEEDED = 30
+INTERVAL = 2.0
+CONNECT_TIMEOUT = 5.0
+READ_LIMIT = 64 * 1024
+MIN_PORTS = 64 # 2 connections every 2 s; a port comes back after TIME_WAIT (60 s)
+STATUS_RE = re.compile(rb'^HTTP/\d(?:\.\d)? (\d{3})')
+
+
+def now_iso():
+ return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
+
+
+def marker_header(dst_ip, dst_port, src_port):
+ """PPv2, command PROXY, INET/STREAM, from 192.0.2.1:src_port to dst_ip:dst_port."""
+ return (SIGNATURE + bytes([0x21, 0x11]) + struct.pack('!H', 12) + socket.inet_aton(MARKER_SOURCE)
+ + socket.inet_aton(dst_ip) + struct.pack('!HH', src_port, dst_port))
+
+
+def request_bytes(host, path):
+ return (f'GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: carlos-ppv2-probe\r\n'
+ f'Accept: */*\r\nConnection: close\r\n\r\n').encode('ascii')
+
+
+def dechunk(body):
+ out = b''
+ while body:
+ size_line, sep, rest = body.partition(b'\r\n')
+ if not sep:
+ break
+ try:
+ size = int(size_line.split(b';')[0].strip(), 16)
+ except ValueError:
+ break
+ if size == 0:
+ break
+ out += rest[:size]
+ body = rest[size + 2:]
+ return out
+
+
+def outcome_from_raw(raw):
+ """What came back on a connection that closed (or stopped) after raw."""
+ if not raw:
+ return {'kind': 'closed', 'detail': 'closed with no answer'}
+ head, _, body = raw.partition(b'\r\n\r\n')
+ match = STATUS_RE.match(head)
+ if not match:
+ return {'kind': 'garbled', 'detail': repr(raw[:80])}
+ headers = {}
+ for line in head.split(b'\r\n')[1:]:
+ name, _, value = line.partition(b':')
+ headers[name.strip().lower().decode('latin-1')] = value.strip().decode('latin-1')
+ if 'chunked' in headers.get('transfer-encoding', '').lower():
+ body = dechunk(body)
+ elif headers.get('content-length', '').isdigit():
+ body = body[:int(headers['content-length'])]
+ out = {'kind': 'answer', 'status': int(match.group(1)), 'body': body[:512].decode('latin-1')}
+ if 'location' in headers:
+ out['location'] = headers['location']
+ return out
+
+
+def outcome_from_error(exc):
+ """What an exception before any answer means."""
+ detail = f'{type(exc).__name__}: {exc}'
+ if isinstance(exc, ssl.SSLCertVerificationError):
+ return {'kind': 'error', 'detail': detail}
+ if isinstance(exc, ssl.SSLEOFError):
+ return {'kind': 'closed', 'detail': detail}
+ if isinstance(exc, ssl.SSLError):
+ return {'kind': 'tls_alert', 'detail': detail}
+ if isinstance(exc, (ConnectionResetError, BrokenPipeError, ConnectionAbortedError)):
+ return {'kind': 'closed', 'detail': detail}
+ return {'kind': 'error', 'detail': detail}
+
+
+def xff_entries(outcome):
+ if outcome.get('kind') != 'answer':
+ return []
+ lines = outcome.get('body', '').strip().splitlines()
+ return [e.strip() for e in lines[0].split(',')] if lines else []
+
+
+def echoed_client(outcome):
+ """The last X-Forwarded-For entry the echo app saw, or None."""
+ entries = xff_entries(outcome)
+ return entries[-1] if entries else None
+
+
+def forged(outcome):
+ for entry in xff_entries(outcome):
+ try:
+ if ipaddress.ip_address(entry) in MARKER_NET:
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+def describe(outcome):
+ if outcome.get('kind') == 'answer':
+ return f"answered {outcome['status']}"
+ return f"no answer ({outcome.get('kind')}: {outcome.get('detail')})"
+
+
+def plain_refusal(port, outcome, expect_client):
+ """Why outcome is not the port's plain answer, or None."""
+ want = 200 if int(port) == 443 else 302
+ if outcome.get('kind') != 'answer' or outcome['status'] != want:
+ return f'{describe(outcome)}, expected {want}'
+ if want == 200 and echoed_client(outcome) != expect_client:
+ return f'answered 200 with client {echoed_client(outcome)}, not {expect_client}'
+ return None
+
+
+def judge(expect, port, plain, marker, expect_client):
+ """('match' | 'mismatch' | 'fail', reason) for one attempt.
+
+ fail ends the run at once; mismatch resets the run of matches."""
+ for label, outcome in (('plain', plain), ('marker', marker)):
+ if forged(outcome):
+ return 'fail', f'the {label} echo carries {MARKER_SOURCE}: the edge believed a forged header (S3)'
+ reason = plain_refusal(port, plain, expect_client)
+ if reason:
+ return 'fail', f'plain {reason}'
+ if marker.get('kind') == 'answer' and marker['status'] == 200 and echoed_client(marker) != expect_client:
+ return 'fail', f'marker answered 200 with client {echoed_client(marker)}, not {expect_client}'
+ if expect == 's0':
+ reason = plain_refusal(port, marker, expect_client)
+ if reason:
+ return 'mismatch', f'marker {reason}; S0 answers it like plain'
+ return 'match', 'marker answered like plain'
+ failed = (marker.get('kind') == 'answer' and marker['status'] == 400) or marker.get('kind') in ('tls_alert', 'closed')
+ if failed:
+ return 'match', f'marker failed: {describe(marker)}'
+ return 'mismatch', f'marker {describe(marker)}; {expect.upper()} fails it (400, TLS alert or close)'
+
+
+def run_probe(attempt, expect, port, expect_client, needed=NEEDED, interval=INTERVAL, timeout=1800.0,
+ clock=time.monotonic, sleep=time.sleep, now=now_iso):
+ """Runs attempts every interval until `needed` consecutive matches, a fail or the timeout."""
+ record = {'started_at': now(), 'passed': False, 'reason': None, 'attempts': []}
+ start, streak, n = clock(), 0, 0
+ try:
+ while True:
+ if clock() - start >= timeout:
+ record['reason'] = f'timed out after {timeout:g} s with {streak} of {needed} consecutive matches'
+ break
+ at = now()
+ plain, marker = attempt()
+ verdict, reason = judge(expect, port, plain, marker, expect_client)
+ record['attempts'].append({'at': at, 'plain': plain, 'marker': marker, 'verdict': verdict, 'reason': reason})
+ if verdict == 'fail':
+ record['reason'] = reason
+ break
+ streak = streak + 1 if verdict == 'match' else 0
+ if streak >= needed:
+ record['passed'], record['reason'] = True, f'{needed} consecutive attempts matched {expect}'
+ break
+ n += 1
+ wait = start + interval * n - clock()
+ if wait > 0:
+ sleep(wait)
+ except KeyboardInterrupt:
+ record['reason'] = 'interrupted'
+ record['finished_at'] = now()
+ return record
+
+
+def parse_ports(text):
+ match = re.fullmatch(r'(\d+)-(\d+)', text or '')
+ if not match:
+ raise ValueError(f'source ports must be <lo>-<hi>, not {text!r}')
+ lo, hi = int(match.group(1)), int(match.group(2))
+ if not 1024 <= lo <= hi <= 65535:
+ raise ValueError(f'source ports must lie within 1024-65535, low first: {text}')
+ if hi - lo + 1 < MIN_PORTS:
+ raise ValueError(f'source ports need at least {MIN_PORTS} ports so none is reused inside TIME_WAIT: {text}')
+ return lo, hi
+
+
+class Connector:
+ """Fresh connections to one NLB address, each from the next port of the range."""
+
+ def __init__(self, nlb_ip, port, host, path, ports):
+ self.nlb_ip, self.port, self.host = nlb_ip, port, host
+ self.request = request_bytes(host, path)
+ self.lo, self.hi = ports
+ self.next = self.lo
+ self.tls = ssl.create_default_context()
+ self.tls.set_alpn_protocols(['http/1.1'])
+
+ def bound(self):
+ for _ in range(self.hi - self.lo + 1):
+ source, self.next = self.next, self.lo if self.next >= self.hi else self.next + 1
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ sock.bind(('', source))
+ return sock, source
+ except OSError as err:
+ sock.close()
+ if err.errno != errno.EADDRINUSE:
+ raise
+ raise OSError(errno.EADDRINUSE, f'no free source port in {self.lo}-{self.hi}')
+
+ def exchange(self, marker):
+ sock = None
+ try:
+ sock, source = self.bound()
+ sock.settimeout(CONNECT_TIMEOUT)
+ sock.connect((self.nlb_ip, self.port))
+ if marker:
+ sock.sendall(marker_header(self.nlb_ip, self.port, source))
+ if self.port == 443:
+ sock = self.tls.wrap_socket(sock, server_hostname=self.host)
+ sock.sendall(self.request)
+ raw = b''
+ while len(raw) < READ_LIMIT:
+ try:
+ chunk = sock.recv(READ_LIMIT - len(raw))
+ except (socket.timeout, TimeoutError):
+ if raw:
+ break
+ raise
+ if not chunk:
+ break
+ raw += chunk
+ return outcome_from_raw(raw)
+ except Exception as exc: # every failure is an outcome the judge reads
+ return outcome_from_error(exc)
+ finally:
+ if sock is not None:
+ sock.close()
+
+ def attempt(self):
+ return self.exchange(False), self.exchange(True)
+
+
+def write_record(path, doc):
+ tmp = path.with_name(path.name + '.tmp')
+ tmp.write_text(json.dumps(doc, indent=2) + '\n')
+ os.replace(tmp, path)
+
+
+def main(argv=None):
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument('--nlb-ip', required=True, help='one public address of the NLB')
+ p.add_argument('--port', required=True, type=int, choices=[80, 443])
+ p.add_argument('--host', required=True, help='the echo app host')
+ p.add_argument('--path', required=True, help='the echo app path')
+ p.add_argument('--expect-client', required=True, help='this probe host\'s public address')
+ p.add_argument('--source-ports', required=True, help='<lo>-<hi>, this process\'s own range')
+ p.add_argument('--expect', required=True, choices=['s0', 's1', 's2'])
+ p.add_argument('--out', required=True, help='the record to write')
+ p.add_argument('--timeout', type=float, default=1800.0, help='seconds before giving up (default 1800)')
+ args = p.parse_args(argv)
+ try:
+ ports = parse_ports(args.source_ports)
+ for flag, value in (('--nlb-ip', args.nlb_ip), ('--expect-client', args.expect_client)):
+ if ipaddress.ip_address(value).version != 4:
+ raise ValueError(f'{flag} must be an IPv4 address')
+ except ValueError as err:
+ p.error(str(err))
+ if not args.path.startswith('/') or any(c.isspace() for c in args.host + args.path):
+ p.error('--path must start with / and neither --host nor --path may hold spaces')
+ out = Path(args.out)
+ if not out.parent.is_dir():
+ p.error(f'the directory of --out does not exist: {out.parent}')
+ connector = Connector(args.nlb_ip, args.port, args.host, args.path, ports)
+ record = run_probe(connector.attempt, args.expect, args.port, args.expect_client, timeout=args.timeout)
+ record = dict({'nlb_ip': args.nlb_ip, 'port': args.port, 'host': args.host, 'path': args.path,
+ 'expect': args.expect, 'expect_client': args.expect_client,
+ 'source_ports': args.source_ports, 'needed': NEEDED, 'interval_s': INTERVAL}, **record)
+ write_record(out, record)
+ print(f"{'passed' if record['passed'] else 'FAILED'}: {args.nlb_ip}:{args.port} {record['reason']}; "
+ f"{len(record['attempts'])} attempts, record {out}")
+ return 0 if record['passed'] else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/ppv2-step.py b/scripts/ppv2-step.py
new file mode 100755
index 000000000..7c5b47d44
--- /dev/null
+++ b/scripts/ppv2-step.py
@@ -0,0 +1,739 @@
+#!/usr/bin/env python3
+"""The PPv2 cutover step gate (edge PPv2 spec 6.2-6.4).
+
+This script is the only way a region NLB target group's client IP
+preservation and PROXY protocol v2 attributes change. Each target group is
+in one of four states:
+
+ S0 preservation on, PPv2 off today
+ S1 preservation on, PPv2 on
+ S2 preservation off, PPv2 on the target
+ S3 preservation off, PPv2 off FORBIDDEN: a client's own header is trusted
+
+The only moves are S0 to S1 and S1 to S2 forward, and S2 to S1 back. None of
+them changes PPv2 while preservation is off, so no node can pass through S3.
+
+ prereq checks the prerequisites (spec 6.1) and writes prereq.json.
+ apply makes one step on one target group through a targeted tofu plan
+ and writes <step>-applied.json with every target's baseline.
+ converge after apply, polls health and trust counters until both probe
+ records are in, then writes <step>.json, the next step's evidence.
+
+Steps: A80, A443 (PPv2 on), B80, B443 (preservation off), R443, R80
+(preservation back on). Nothing turns PPv2 off; there is no step for it.
+
+The root passes the two maps to the ingress module from ppv2.auto.tfvars.json
+in the root directory, which this script owns:
+ {"ppv2_preserve_client_ip":{"80":true,"443":true},
+ "ppv2_proxy_protocol_v2":{"80":false,"443":false}}
+
+Exit codes: 0 done or passed, 1 refused or failed, 2 invalid arguments.
+"""
+import argparse
+from collections import namedtuple
+from datetime import datetime, timezone
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import time
+
+Step = namedtuple('Step', 'port attribute value source target forward')
+STEPS = {
+ 'A80': Step('80', 'proxy_protocol_v2', True, 'S0', 'S1', True),
+ 'A443': Step('443', 'proxy_protocol_v2', True, 'S0', 'S1', True),
+ 'B80': Step('80', 'preserve_client_ip', False, 'S1', 'S2', True),
+ 'B443': Step('443', 'preserve_client_ip', False, 'S1', 'S2', True),
+ 'R443': Step('443', 'preserve_client_ip', True, 'S2', 'S1', False),
+ 'R80': Step('80', 'preserve_client_ip', True, 'S2', 'S1', False),
+}
+# The record each step needs, passed and for the same NLB (spec 6.2, 6.4).
+PREDECESSOR = {'A80': 'prereq', 'A443': 'A80', 'B80': 'A443', 'B443': 'B80', 'R443': None, 'R80': None}
+# A reverse step undoes this forward step's evidence.
+SUPERSEDES = {'R443': 'B443', 'R80': 'B80'}
+ALLOWED = (('S0', 'S1'), ('S1', 'S2'), ('S2', 'S1'))
+STATE = {(True, False): 'S0', (True, True): 'S1', (False, True): 'S2', (False, False): 'S3'}
+LIVE_KEY = {'preserve_client_ip': 'preserve_client_ip.enabled', 'proxy_protocol_v2': 'proxy_protocol_v2.enabled'}
+TFVARS_FILE = 'ppv2.auto.tfvars.json'
+TFVARS_KEY = {'preserve_client_ip': 'ppv2_preserve_client_ip', 'proxy_protocol_v2': 'ppv2_proxy_protocol_v2'}
+COUNTERS = ('proxied', 'no_client', 'no_client_refused', 'ignored', 'ignored_private',
+ 'marker_trusted', 'malformed', 'timeout')
+# Counters that must not move from the apply's baseline until convergence.
+STILL = ('malformed', 'timeout', 'ignored_private', 'marker_trusted', 'no_client_refused')
+PROBE_EXPECT = {'A': 's1', 'B': 's2', 'R': 's1'}
+TRUST_STATUS = '/opt/carlos/carlos system edge trust-status'
+ARMED_LINE = 'edge: proxy protocol: armed on'
+JOURNAL = "journalctl -u carlos-edge.service -o cat --no-pager | grep -F '%s' | tail -n 1" % ARMED_LINE
+ARMED_RE = re.compile(r'edge: proxy protocol: armed on :80 and :443, trusting (\S+), barrier (up|down)')
+HEALTH_EVERY = 10.0
+TRUST_EVERY = 30.0
+SSM_BOUND = 120.0
+
+
+class Refused(Exception):
+ pass
+
+
+def now_iso():
+ return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
+
+
+def parse_time(text):
+ return datetime.fromisoformat(text.replace('Z', '+00:00'))
+
+
+def state_of(preserve, ppv2):
+ return STATE[(preserve, ppv2)]
+
+
+def move_refusal(current, target):
+ """Why the move from current to target is refused, or None."""
+ if current == 'S3':
+ return 'the target group is in S3 (forbidden); no step moves from S3. Run the S3 incident procedure (spec 6.5)'
+ if (current, target) in ALLOWED:
+ return None
+ if current == target:
+ return f'the move from {current} to {target} is no change'
+ return f'the move from {current} to {target} is not one of S0 to S1, S1 to S2, S2 to S1'
+
+
+def step_refusal(step, live):
+ """Why `step` is refused against live {'preserve_client_ip': bool, 'proxy_protocol_v2': bool}."""
+ s = STEPS[step]
+ current = state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])
+ after = dict(live, **{s.attribute: s.value})
+ target = state_of(after['preserve_client_ip'], after['proxy_protocol_v2'])
+ if current == 'S3':
+ return f'step {step}: {move_refusal(current, target)}'
+ if not after['proxy_protocol_v2']:
+ return f'step {step} would leave PPv2 off ({current} to {target})'
+ reason = move_refusal(current, target)
+ if reason:
+ return f'step {step}: {reason}'
+ if (current, target) != (s.source, s.target):
+ return f'step {step} moves {s.source} to {s.target}; the target group is in {current}'
+ return None
+
+
+def norm(value):
+ if isinstance(value, bool):
+ return 'true' if value else 'false'
+ return str(value).lower() if isinstance(value, str) else value
+
+
+def unknown_keys(tree):
+ if isinstance(tree, dict):
+ return any(unknown_keys(v) for v in tree.values())
+ if isinstance(tree, list):
+ return any(unknown_keys(v) for v in tree)
+ return tree is True
+
+
+def plan_refusal(plan, address, attribute, before, after):
+ """Why the plan is not exactly `attribute` from `before` to `after` on `address`, or None."""
+ if not isinstance(plan, dict) or not isinstance(plan.get('resource_changes'), list):
+ return 'the plan has no resource_changes'
+ if plan.get('errored'):
+ return 'the plan errored'
+ changes = [c for c in plan['resource_changes'] if c.get('change', {}).get('actions') != ['no-op']]
+ if len(changes) != 1:
+ listed = ', '.join(f"{c.get('address')} ({'/'.join(c.get('change', {}).get('actions') or [])})" for c in changes)
+ return f'the plan has {len(changes)} resource changes ({listed}); exactly one is allowed'
+ change = changes[0]
+ if change.get('address') != address:
+ return f"the plan changes {change.get('address')}, not {address}"
+ if change.get('mode') != 'managed' or change.get('type') != 'aws_lb_target_group':
+ return f'the plan changes {address} as {change.get("mode")} {change.get("type")}, not a managed aws_lb_target_group'
+ body = change['change']
+ if body.get('actions') != ['update']:
+ return f"the plan would {', '.join(body.get('actions') or [])} {address}; only an in-place update is allowed"
+ old, new = body.get('before'), body.get('after')
+ if not isinstance(old, dict) or not isinstance(new, dict):
+ return f'the plan does not show {address} before and after'
+ differing = sorted(k for k in set(old) | set(new) if old.get(k) != new.get(k))
+ unknown = sorted(k for k, v in (body.get('after_unknown') or {}).items() if unknown_keys(v))
+ differing = sorted(set(differing) | set(unknown))
+ if differing != [attribute]:
+ return f"the plan changes {', '.join(differing) or 'nothing'} on {address}; only {attribute} may change"
+ if (norm(old[attribute]), norm(new[attribute])) != (norm(before), norm(after)):
+ return (f'the plan sets {attribute} from {norm(old[attribute])} to {norm(new[attribute])}; '
+ f'this step sets it from {norm(before)} to {norm(after)}')
+ return None
+
+
+def parse_trust(text):
+ """The trust-status line in text, validated, or None."""
+ lines = [line for line in (text or '').splitlines() if line.strip()]
+ if not lines:
+ return None
+ try:
+ doc = json.loads(lines[-1])
+ except ValueError:
+ return None
+ if not isinstance(doc, dict) or set(doc) != {'armed', 'barrier', 'counters', 'proxied_by_node'}:
+ return None
+ if not isinstance(doc['armed'], bool) or not isinstance(doc['barrier'], bool):
+ return None
+ counters, nodes = doc['counters'], doc['proxied_by_node']
+ if not isinstance(counters, dict) or set(counters) != set(COUNTERS):
+ return None
+ if not all(type(v) is int and v >= 0 for v in counters.values()):
+ return None
+ if not isinstance(nodes, dict) or not all(isinstance(k, str) and type(v) is int and v >= 0 for k, v in nodes.items()):
+ return None
+ return doc
+
+
+def first_json(stdout, key):
+ """The JSON document in stdout carrying key: the whole output, or one of its lines."""
+ try:
+ doc = json.loads(stdout)
+ if isinstance(doc, dict) and key in doc:
+ return doc
+ except ValueError:
+ pass
+ for line in stdout.splitlines():
+ try:
+ doc = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(doc, dict) and key in doc:
+ return doc
+ return None
+
+
+def find_resource(module, address):
+ found = [r for r in module.get('resources') or [] if r.get('address') == address]
+ for child in module.get('child_modules') or []:
+ found.extend(find_resource(child, address))
+ return found
+
+
+class Cloud:
+ """The aws and tofu calls, through the executables on PATH."""
+
+ def __init__(self, profile, region, sleep=time.sleep, clock=time.monotonic):
+ self.profile, self.region = profile, region
+ self.sleep, self.clock = sleep, clock
+
+ def aws(self, *args):
+ result = subprocess.run(['aws', '--profile', self.profile, '--region', self.region, '--output', 'json', *args],
+ capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ if result.returncode != 0:
+ raise Refused(f"aws {' '.join(args[:2])} failed: {result.stderr.strip()}")
+ try:
+ return json.loads(result.stdout)
+ except ValueError:
+ raise Refused(f"aws {' '.join(args[:2])} printed no JSON")
+
+ def attributes(self, tg_arn):
+ doc = self.aws('elbv2', 'describe-target-group-attributes', '--target-group-arn', tg_arn)
+ values = {a.get('Key'): a.get('Value') for a in doc.get('Attributes') or []}
+ live = {}
+ for attribute, key in LIVE_KEY.items():
+ if values.get(key) not in ('true', 'false'):
+ raise Refused(f'target group {tg_arn} has no readable {key} ({values.get(key)!r})')
+ live[attribute] = values[key] == 'true'
+ return live
+
+ def target_group(self, tg_arn, nlb_arn, port):
+ groups = self.aws('elbv2', 'describe-target-groups', '--target-group-arns', tg_arn).get('TargetGroups') or []
+ if len(groups) != 1 or groups[0].get('TargetGroupArn') != tg_arn:
+ raise Refused(f'target group {tg_arn} not found')
+ if nlb_arn not in (groups[0].get('LoadBalancerArns') or []):
+ raise Refused(f'target group {tg_arn} is not attached to {nlb_arn}')
+ if str(groups[0].get('Port')) != port:
+ raise Refused(f"target group {tg_arn} listens on port {groups[0].get('Port')}, not {port}")
+
+ def health(self, tg_arn):
+ doc = self.aws('elbv2', 'describe-target-health', '--target-group-arn', tg_arn)
+ return {d['Target']['Id']: d['TargetHealth']['State'] for d in doc.get('TargetHealthDescriptions') or []}
+
+ def ssm(self, targets, command):
+ """{instance: (response code, stdout, stderr)} for command run on every target."""
+ cid = self.aws('ssm', 'send-command', '--document-name', 'AWS-RunShellScript',
+ '--comment', 'ppv2-step', '--timeout-seconds', '60', '--instance-ids', *targets,
+ '--parameters', json.dumps({'commands': [command]}))['Command']['CommandId']
+ results, until = {}, self.clock() + SSM_BOUND
+ while len(results) < len(targets):
+ for iid in targets:
+ if iid in results:
+ continue
+ try:
+ doc = self.aws('ssm', 'get-command-invocation', '--command-id', cid, '--instance-id', iid)
+ except Refused:
+ doc = {} # InvocationDoesNotExist until the command registers
+ if doc.get('Status') in ('Success', 'Failed', 'TimedOut', 'Cancelled', 'Cancelling'):
+ results[iid] = (doc.get('ResponseCode'), doc.get('StandardOutputContent') or '',
+ doc.get('StandardErrorContent') or '')
+ if len(results) < len(targets):
+ if self.clock() > until:
+ missing = ', '.join(t for t in targets if t not in results)
+ raise Refused(f'SSM command {cid} did not finish on {missing}')
+ self.sleep(2)
+ return results
+
+ def trust(self, targets):
+ """{instance: trust-status dict, or a string saying why there is none}."""
+ out = {}
+ for iid, (code, stdout, stderr) in self.ssm(targets, TRUST_STATUS).items():
+ if code == 2:
+ out[iid] = f'{iid} is not armed: {stderr.strip()}'
+ elif code != 0:
+ out[iid] = f'{iid}: trust-status failed ({code}): {stderr.strip()}'
+ else:
+ doc = parse_trust(stdout)
+ out[iid] = doc if doc else f'{iid}: trust-status answered something that is not a status line'
+ return out
+
+ def tofu(self, root, *args):
+ return subprocess.run(['tofu', f'-chdir={root}', *args], capture_output=True, text=True,
+ stdin=subprocess.DEVNULL)
+
+
+def registered_refusals(health, targets):
+ reasons = []
+ for iid in targets:
+ if iid not in health:
+ reasons.append(f'{iid} is not registered')
+ elif health[iid] != 'healthy':
+ reasons.append(f'{iid} is {health[iid]}')
+ for iid in sorted(set(health) - set(targets)):
+ reasons.append(f'{iid} is registered but not in --targets')
+ return reasons
+
+
+def load_record(path):
+ try:
+ doc = json.loads(path.read_text())
+ except FileNotFoundError:
+ return None
+ except ValueError:
+ raise Refused(f'{path.name} is not JSON')
+ if not isinstance(doc, dict):
+ raise Refused(f'{path.name} is not a record')
+ return doc
+
+
+def write_record(path, doc):
+ tmp = path.with_name(path.name + '.tmp')
+ tmp.write_text(json.dumps(doc, indent=2, sort_keys=True) + '\n')
+ os.replace(tmp, path)
+
+
+def predecessor_refusal(step, record_dir, nlb_arn):
+ pred = PREDECESSOR[step]
+ if pred is None:
+ return None
+ record = load_record(record_dir / f'{pred}.json')
+ if record is None:
+ return f'step {step} needs {pred}.json in {record_dir}'
+ if record.get('passed') is not True:
+ return f'{pred}.json did not pass'
+ if record.get('nlb_arn') != nlb_arn:
+ return f"{pred}.json is for another load balancer ({record.get('nlb_arn')})"
+ if pred != 'prereq':
+ if record.get('step') != pred:
+ return f"{pred}.json is a record of {record.get('step')}"
+ applied = load_record(record_dir / f'{pred}-applied.json')
+ if applied is None or applied.get('applied_at') != record.get('applied_at') or applied.get('nlb_arn') != nlb_arn:
+ return (f"{pred}.json is not for its latest apply ({pred}-applied.json applied_at "
+ f"{(applied or {}).get('applied_at')}, {pred}.json {record.get('applied_at')})")
+ return None
+
+
+def tfvars_check(doc, port, live):
+ if not isinstance(doc, dict) or set(doc) != set(TFVARS_KEY.values()):
+ return f'{TFVARS_FILE} must hold exactly {", ".join(sorted(TFVARS_KEY.values()))}'
+ for attribute, key in TFVARS_KEY.items():
+ values = doc[key]
+ if not isinstance(values, dict) or set(values) != {'80', '443'} or not all(isinstance(v, bool) for v in values.values()):
+ return f'{TFVARS_FILE} {key} must set true or false for exactly "80" and "443"'
+ if values[port] != live[attribute]:
+ return (f'{TFVARS_FILE} {key}["{port}"] is {norm(values[port])}, which disagrees with the live '
+ f'target group ({norm(live[attribute])}); reconcile it before any step')
+ return None
+
+
+def check_state_address(cloud, args):
+ result = cloud.tofu(args.root, 'state', 'show', '-json', args.tg_address)
+ if result.returncode != 0:
+ raise Refused(f'tofu state show {args.tg_address} failed: {result.stderr.strip()}')
+ doc = first_json(result.stdout, 'values')
+ if doc is None:
+ raise Refused(f'tofu state show {args.tg_address} printed no state')
+ found = find_resource((doc.get('values') or {}).get('root_module') or {}, args.tg_address)
+ if len(found) != 1:
+ raise Refused(f'tofu state show {args.tg_address} found {len(found)} resources')
+ values = found[0].get('values') or {}
+ if values.get('arn') != args.tg_arn:
+ raise Refused(f"{args.tg_address} has arn {values.get('arn')}, not {args.tg_arn}")
+ if str(values.get('port')) != args.port:
+ raise Refused(f"{args.tg_address} has port {values.get('port')}, not {args.port}")
+
+
+def cmd_apply(args, cloud):
+ step = STEPS[args.step]
+ if step.port != args.port:
+ raise Refused(f'step {args.step} is for port {step.port}, not {args.port}')
+ record_dir = Path(args.record_dir)
+ if not record_dir.is_dir():
+ raise Refused(f'--record-dir {record_dir} is not a directory')
+ targets = split(args.targets)
+ # Before anything else: the address names the target group we were given.
+ check_state_address(cloud, args)
+ cloud.target_group(args.tg_arn, args.nlb_arn, args.port)
+ live = cloud.attributes(args.tg_arn)
+ reason = step_refusal(args.step, live)
+ if reason:
+ raise Refused(reason)
+ reason = predecessor_refusal(args.step, record_dir, args.nlb_arn)
+ if reason:
+ raise Refused(reason)
+ reasons = registered_refusals(cloud.health(args.tg_arn), targets)
+ if step.forward and reasons:
+ raise Refused('every target must be registered and healthy: ' + '; '.join(reasons))
+ baseline = cloud.trust(targets)
+ if step.forward:
+ for iid in targets:
+ status = baseline[iid]
+ if isinstance(status, str):
+ raise Refused(status)
+ if not status['armed']:
+ raise Refused(f'{iid} is not armed')
+ if status['barrier']:
+ raise Refused(f'the trust barrier is up on {iid}; no forward step while it is up (spec 4.7)')
+ tfvars = Path(args.root) / TFVARS_FILE
+ try:
+ original = tfvars.read_bytes()
+ doc = json.loads(original)
+ except (OSError, ValueError) as err:
+ raise Refused(f'cannot read {tfvars}: {err}')
+ reason = tfvars_check(doc, args.port, live)
+ if reason:
+ raise Refused(reason)
+ doc[TFVARS_KEY[step.attribute]][args.port] = step.value
+ planfile = f'ppv2-{args.step}.tfplan'
+ tfvars.write_bytes((json.dumps(doc, indent=2) + '\n').encode())
+ try:
+ result = cloud.tofu(args.root, 'plan', '-input=false', '-lock=true', f'-target={args.tg_address}',
+ f'-out={planfile}')
+ if result.returncode != 0:
+ raise Refused(f'tofu plan failed: {result.stderr.strip()[-2000:]}')
+ shown = cloud.tofu(args.root, 'show', '-json', planfile)
+ if shown.returncode != 0:
+ raise Refused(f'tofu show failed: {shown.stderr.strip()}')
+ plan = first_json(shown.stdout, 'resource_changes')
+ reason = plan_refusal(plan, args.tg_address, step.attribute, live[step.attribute], step.value)
+ if reason:
+ raise Refused(reason)
+ except BaseException:
+ tfvars.write_bytes(original)
+ remove_quietly(Path(args.root) / planfile)
+ raise
+ # From here the file keeps the new value: if the apply fails part way,
+ # the attribute may already have changed, and a file put back would ask
+ # the next ordinary plan to undo it.
+ applied_at = now_iso()
+ result = cloud.tofu(args.root, 'apply', '-input=false', planfile)
+ remove_quietly(Path(args.root) / planfile)
+ if result.returncode != 0:
+ raise Refused(f'tofu apply failed; {tfvars.name} keeps the new value; read the live attributes '
+ f'before anything else: {result.stderr.strip()[-2000:]}')
+ supersede(record_dir, SUPERSEDES.get(args.step), applied_at)
+ write_record(record_dir / f'{args.step}-applied.json', {
+ 'nlb_arn': args.nlb_arn, 'port': args.port, 'step': args.step, 'applied_at': applied_at,
+ 'tg_arn': args.tg_arn, 'tg_address': args.tg_address, 'targets': targets,
+ 'from': step.source, 'to': step.target, 'baseline': baseline})
+ print(f'{args.step} applied to {args.tg_address} at {applied_at}: {step.source} to {step.target}. '
+ f'Now run the probes on both NLB addresses and `converge`.')
+ return 0
+
+
+def supersede(record_dir, forward, applied_at):
+ if not forward:
+ return
+ stamp = re.sub(r'[^0-9]', '', applied_at)
+ for name in (f'{forward}.json', f'{forward}-applied.json'):
+ path = record_dir / name
+ if path.exists():
+ os.replace(path, record_dir / name.replace('.json', f'.superseded-{stamp}.json'))
+
+
+def remove_quietly(path):
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ pass
+
+
+def split(text):
+ items = [t.strip() for t in text.split(',') if t.strip()]
+ if not items or len(set(items)) != len(items):
+ raise Refused(f'a comma-separated list without repeats is required, not {text!r}')
+ return items
+
+
+def probe_findings(paths, applied, step):
+ """(reasons, summaries) for the two probe records against the applied record."""
+ reasons, summaries, addresses = [], [], []
+ expect = PROBE_EXPECT[step[0]]
+ applied_at = parse_time(applied['applied_at'])
+ for path in paths:
+ try:
+ doc = json.loads(Path(path).read_text())
+ except (OSError, ValueError):
+ reasons.append(f'probe record {Path(path).name} did not arrive or is not JSON')
+ continue
+ name = Path(path).name
+ addresses.append(doc.get('nlb_ip'))
+ if str(doc.get('port')) != applied['port']:
+ reasons.append(f"probe record {name} is for port {doc.get('port')}, not {applied['port']}")
+ if doc.get('expect') != expect:
+ reasons.append(f"probe record {name} expected {doc.get('expect')}; step {step} needs {expect}")
+ try:
+ started = parse_time(doc['started_at'])
+ except (KeyError, TypeError, ValueError):
+ started = None
+ if started is None or started <= applied_at:
+ reasons.append(f"probe record {name} started before the apply ({doc.get('started_at')})")
+ if doc.get('passed') is not True:
+ reasons.append(f"probe record {name} did not pass: {doc.get('reason')}")
+ summaries.append({'record': str(path), 'nlb_ip': doc.get('nlb_ip'), 'port': doc.get('port'),
+ 'started_at': doc.get('started_at'), 'finished_at': doc.get('finished_at'),
+ 'passed': doc.get('passed'), 'attempts': len(doc.get('attempts') or []),
+ 'propagation_s': propagation(doc, applied_at)})
+ if len(addresses) == 2 and (addresses[0] == addresses[1] or None in addresses):
+ reasons.append(f'the probe records must cover both NLB addresses; got {addresses[0]} and {addresses[1]}')
+ return reasons, summaries
+
+
+def propagation(doc, applied_at):
+ """Seconds from the apply to the start of the final run of matching attempts."""
+ attempts = doc.get('attempts') or []
+ start = None
+ for attempt in attempts:
+ if attempt.get('verdict') == 'match':
+ start = start or attempt
+ else:
+ start = None
+ try:
+ return round((parse_time(start['at']) - applied_at).total_seconds(), 3) if start else None
+ except (KeyError, TypeError, ValueError):
+ return None
+
+
+def trust_findings(poll, baseline, targets):
+ reasons = []
+ for iid in targets:
+ status, base = poll.get(iid), baseline.get(iid)
+ if isinstance(status, str) or status is None:
+ reasons.append(status or f'{iid}: no trust-status')
+ continue
+ if not status['armed']:
+ reasons.append(f'{iid} is not armed')
+ if status['barrier']:
+ reasons.append(f'{iid}: barrier is up')
+ if not isinstance(base, dict) or 'counters' not in base:
+ reasons.append(f'{iid}: the apply recorded no baseline')
+ continue
+ for counter in STILL:
+ if status['counters'][counter] != base['counters'][counter]:
+ reasons.append(f"{iid}: {counter} moved from {base['counters'][counter]} to {status['counters'][counter]}")
+ return reasons
+
+
+def cmd_converge(args, cloud, clock=time.monotonic, sleep=time.sleep):
+ record_dir = Path(args.record_dir)
+ paths = split(args.probe_records)
+ if len(paths) != 2:
+ raise Refused('converge needs exactly two probe records, one per NLB address')
+ targets = split(args.targets)
+ applied = load_record(record_dir / f'{args.step}-applied.json')
+ if applied is None:
+ raise Refused(f'no {args.step}-applied.json in {record_dir}; run apply first')
+ if applied.get('step') != args.step or applied.get('tg_arn') != args.tg_arn:
+ raise Refused(f'{args.step}-applied.json is for {applied.get("step")} on {applied.get("tg_arn")}')
+ baseline = applied.get('baseline') or {}
+ health_polls, trust_polls, reasons = [], [], []
+
+ def poll_health():
+ at = now_iso()
+ try:
+ health = cloud.health(args.tg_arn)
+ bad = registered_refusals(health, targets)
+ except Refused as err:
+ health, bad = {}, [str(err)]
+ health_polls.append({'at': at, 'health': health})
+ reasons.extend(f'health poll at {at}: {r}' for r in bad)
+
+ def poll_trust():
+ at = now_iso()
+ try:
+ poll = cloud.trust(targets)
+ except Refused as err:
+ poll = {t: str(err) for t in targets}
+ trust_polls.append({'at': at, 'status': poll})
+ reasons.extend(f'trust poll at {at}: {r}' for r in trust_findings(poll, baseline, targets))
+ return poll
+
+ def arrived():
+ return all(Path(p).exists() for p in paths)
+
+ deadline = clock() + args.timeout
+ next_health = next_trust = clock()
+ while True:
+ if clock() >= next_health:
+ poll_health()
+ next_health = clock() + HEALTH_EVERY
+ if clock() >= next_trust:
+ poll_trust()
+ next_trust = clock() + TRUST_EVERY
+ if arrived() or clock() >= deadline:
+ break
+ sleep(1)
+ # A last look at both, after the probes finished.
+ poll_health()
+ final = poll_trust()
+ # The evidence is for the state the step made; the target group must still be in it.
+ try:
+ live = cloud.attributes(args.tg_arn)
+ state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])
+ except Refused as err:
+ state = None
+ reasons.append(str(err))
+ if state is not None and state != STEPS[args.step].target:
+ reasons.append(f'the target group is in {state}, not {STEPS[args.step].target}')
+ probe_reasons, probes = probe_findings(paths, applied, args.step)
+ reasons.extend(probe_reasons)
+ if args.step.startswith('B'):
+ prereq = load_record(record_dir / 'prereq.json')
+ nodes = (prereq or {}).get('sources')
+ if not prereq or prereq.get('nlb_arn') != applied.get('nlb_arn') or not nodes:
+ reasons.append('prereq.json for this load balancer, naming its node addresses, is needed to check proxied rose')
+ else:
+ for iid in targets:
+ status, base = final.get(iid), baseline.get(iid)
+ if not isinstance(status, dict) or not isinstance(base, dict):
+ continue
+ for node in nodes:
+ was, now = base.get('proxied_by_node', {}).get(node, 0), status['proxied_by_node'].get(node, 0)
+ if now <= was:
+ reasons.append(f'{iid}: proxied from node {node} did not rise ({was} to {now})')
+ passed = not reasons
+ write_record(record_dir / f'{args.step}.json', {
+ 'nlb_arn': applied.get('nlb_arn'), 'port': applied.get('port'), 'step': args.step,
+ 'tg_arn': args.tg_arn, 'applied_at': applied.get('applied_at'), 'converged_at': now_iso(),
+ 'state': state, 'passed': passed, 'reasons': reasons, 'probes': probes, 'targets': targets,
+ 'health_polls': health_polls, 'trust_polls': trust_polls})
+ if passed:
+ print(f'{args.step} converged; {args.step}.json passed')
+ return 0
+ for reason in reasons:
+ print(f'not converged: {reason}', file=sys.stderr)
+ return 1
+
+
+def cmd_prereq(args, cloud):
+ record_dir = Path(args.record_dir)
+ if not record_dir.is_dir():
+ raise Refused(f'--record-dir {record_dir} is not a directory')
+ targets = split(args.targets)
+ sources = sorted(split(args.sources))
+ reasons, groups = [], {}
+ for port, tg_arn in (('80', args.tg_arn_80), ('443', args.tg_arn_443)):
+ try:
+ cloud.target_group(tg_arn, args.nlb_arn, port)
+ live = cloud.attributes(tg_arn)
+ state = state_of(live['preserve_client_ip'], live['proxy_protocol_v2'])
+ groups[port] = {'tg_arn': tg_arn, 'state': state}
+ if state != 'S0':
+ reasons.append(f'target group {tg_arn} is in {state}, not S0')
+ reasons.extend(f'{tg_arn}: {r}' for r in registered_refusals(cloud.health(tg_arn), targets))
+ except Refused as err:
+ reasons.append(str(err))
+ status = cloud.trust(targets)
+ for iid in targets:
+ s = status[iid]
+ if isinstance(s, str):
+ reasons.append(s)
+ elif not s['armed']:
+ reasons.append(f'{iid} is not armed')
+ elif s['barrier']:
+ reasons.append(f'the trust barrier is up on {iid}')
+ lines = {}
+ for iid, (code, stdout, _) in cloud.ssm(targets, JOURNAL).items():
+ match = ARMED_RE.search(stdout or '')
+ lines[iid] = stdout.strip()
+ if code != 0 or not match:
+ reasons.append(f'{iid}: no armed line in the carlos-edge journal')
+ elif sorted(match.group(1).split(',')) != sources:
+ reasons.append(f"{iid} trusts {match.group(1)}, not {','.join(sources)}")
+ alarms = cloud.aws('cloudwatch', 'describe-alarms', '--alarm-names', args.alarm).get('MetricAlarms') or []
+ alarm = [a for a in alarms if a.get('AlarmName') == args.alarm]
+ if not alarm:
+ reasons.append(f'alarm {args.alarm} not found')
+ elif alarm[0].get('StateValue') != 'OK':
+ reasons.append(f"alarm {args.alarm} is {alarm[0].get('StateValue')}, not OK")
+ passed = not reasons
+ write_record(record_dir / 'prereq.json', {
+ 'nlb_arn': args.nlb_arn, 'sources': sources, 'targets': targets, 'target_groups': groups,
+ 'alarm': args.alarm, 'checked_at': now_iso(), 'passed': passed, 'reasons': reasons,
+ 'trust_status': status, 'armed_lines': lines})
+ if passed:
+ print('prerequisites hold; prereq.json passed')
+ return 0
+ for reason in reasons:
+ print(f'refused: {reason}', file=sys.stderr)
+ return 1
+
+
+def parser():
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = p.add_subparsers(dest='command', required=True)
+ a = sub.add_parser('apply', help='make one step on one target group')
+ a.add_argument('--root', required=True, help='the tofu root directory holding ppv2.auto.tfvars.json')
+ a.add_argument('--nlb-arn', required=True)
+ a.add_argument('--tg-arn', required=True)
+ a.add_argument('--tg-address', required=True, help='the target group\'s tofu address')
+ a.add_argument('--port', required=True, choices=['80', '443'])
+ a.add_argument('--step', required=True, choices=list(STEPS))
+ a.add_argument('--record-dir', required=True)
+ c = sub.add_parser('converge', help='gather convergence evidence after apply')
+ c.add_argument('--step', required=True, choices=list(STEPS))
+ c.add_argument('--record-dir', required=True)
+ c.add_argument('--probe-records', required=True, help='two probe record paths, comma-separated')
+ c.add_argument('--tg-arn', required=True)
+ c.add_argument('--timeout', type=float, default=1800.0, help='seconds to wait for the probe records')
+ r = sub.add_parser('prereq', help='check the prerequisites and write prereq.json')
+ r.add_argument('--nlb-arn', required=True)
+ r.add_argument('--tg-arn-80', required=True)
+ r.add_argument('--tg-arn-443', required=True)
+ r.add_argument('--sources', required=True, help='the ingress module\'s proxy_protocol_sources, comma-separated')
+ r.add_argument('--alarm', required=True, help='the proxy trust alarm name')
+ r.add_argument('--record-dir', required=True)
+ for s in (a, c, r):
+ s.add_argument('--profile', required=True)
+ s.add_argument('--region', required=True)
+ s.add_argument('--targets', required=True, help='every target instance id, comma-separated')
+ return p
+
+
+def main(argv=None):
+ args = parser().parse_args(argv)
+ cloud = Cloud(args.profile, args.region)
+ try:
+ if args.command == 'apply':
+ return cmd_apply(args, cloud)
+ if args.command == 'converge':
+ return cmd_converge(args, cloud)
+ return cmd_prereq(args, cloud)
+ except Refused as err:
+ print(f'refused: {err}', file=sys.stderr)
+ return 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/ppv2_probe_test.py b/scripts/ppv2_probe_test.py
new file mode 100644
index 000000000..75d8684da
--- /dev/null
+++ b/scripts/ppv2_probe_test.py
@@ -0,0 +1,180 @@
+"""Tests for scripts/ppv2-probe.py, the PPv2 convergence and forgery probe (spec 6.4, 10).
+
+The decision logic is tested on recorded responses; no socket is opened.
+Run from the repo root: python3 -m unittest scripts/ppv2_probe_test.py
+"""
+import importlib.util
+import ipaddress
+import json
+from pathlib import Path
+import ssl
+import struct
+import subprocess
+import sys
+import unittest
+
+SCRIPT = Path(__file__).with_name('ppv2-probe.py')
+DATA = json.loads((Path(__file__).parent / 'testdata' / 'ppv2' / 'probe-responses.json').read_text())
+CLIENT = DATA['expect_client']
+ERRORS = {'SSLError': lambda d: ssl.SSLError(1, d), 'SSLEOFError': lambda d: ssl.SSLEOFError(8, d),
+ 'ConnectionResetError': lambda d: ConnectionResetError(104, d), 'TimeoutError': TimeoutError}
+
+
+def load_script():
+ spec = importlib.util.spec_from_file_location('ppv2_probe', SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+probe = load_script()
+
+
+def recorded(name):
+ """The outcome the probe's socket layer makes of a recorded exchange."""
+ response = DATA['responses'][name]
+ if 'raw' in response:
+ return probe.outcome_from_raw(response['raw'].encode('latin-1'))
+ return probe.outcome_from_error(ERRORS[response['error']](response['detail']))
+
+
+class FakeClock:
+ def __init__(self):
+ self.t = 0.0
+
+ def __call__(self):
+ return self.t
+
+ def sleep(self, seconds):
+ self.t += seconds
+
+
+def run(attempts, needed=30, timeout=600.0):
+ """Runs the probe loop over a list of (plain, marker) recorded names, s1 on :443."""
+ clock = FakeClock()
+ feed = iter(attempts)
+ calls = []
+
+ def attempt():
+ calls.append(clock())
+ plain, marker = next(feed)
+ return recorded(plain), recorded(marker)
+
+ record = probe.run_probe(attempt, expect='s1', port=443, expect_client=CLIENT, needed=needed,
+ interval=2.0, timeout=timeout, clock=clock, sleep=clock.sleep)
+ return record, calls
+
+
+class ProbeTests(unittest.TestCase):
+ def test_expectations_table(self):
+ for row in DATA['table']:
+ plain, marker = recorded(row['plain']), recorded(row['marker'])
+ for expect in ('s0', 's1', 's2'):
+ with self.subTest(row=row, expect=expect):
+ verdict, reason = probe.judge(expect, row['port'], plain, marker, CLIENT)
+ # S1 and S2 answer alike (spec 6.2: the probe cannot tell them apart).
+ same = (expect == row['state']) or {expect, row['state']} == {'s1', 's2'}
+ self.assertEqual('match' if same else 'mismatch', verdict, reason)
+ # S3 on a node: plain answers 503, so the probe fails at once whatever it expects.
+ for row in DATA['s3']:
+ for expect in ('s0', 's1', 's2'):
+ with self.subTest(s3=row, expect=expect):
+ verdict, reason = probe.judge(expect, row['port'], recorded(row['plain']),
+ recorded(row['marker']), CLIENT)
+ self.assertEqual('fail', verdict)
+ self.assertIn('503', reason)
+ # Plain that is not the port's answer fails at once, in every state.
+ for port, plain in [(443, 'redirect-302'), (80, 'echo-200'), (443, 'timeout'), (80, 'reset'),
+ (443, 'bad-request-400')]:
+ for expect in ('s0', 's1', 's2'):
+ with self.subTest(port=port, plain=plain, expect=expect):
+ verdict, _ = probe.judge(expect, port, recorded(plain), recorded('tls-alert'), CLIENT)
+ self.assertEqual('fail', verdict)
+ # A marker that neither answers like plain nor fails the expected way is a
+ # mismatch (still propagating, or noise), not a pass.
+ verdict, _ = probe.judge('s1', 443, recorded('echo-200'), recorded('timeout'), CLIENT)
+ self.assertEqual('mismatch', verdict)
+ verdict, _ = probe.judge('s0', 80, recorded('redirect-302'), recorded('timeout'), CLIENT)
+ self.assertEqual('mismatch', verdict)
+ # The parsed outcomes themselves.
+ self.assertEqual({'kind': 'answer', 'status': 302}, {k: recorded('redirect-302')[k] for k in ('kind', 'status')})
+ self.assertEqual('203.0.113.9', probe.echoed_client(recorded('echo-200-chunked')))
+ self.assertEqual('tls_alert', recorded('tls-alert')['kind'])
+ self.assertEqual('closed', recorded('tls-eof')['kind'])
+ self.assertEqual('closed', recorded('closed-empty')['kind'])
+ self.assertEqual('error', recorded('timeout')['kind'])
+
+ def test_wrong_client_echo_fails(self):
+ # The same wrong address on plain and marker is consistent, and still a failure:
+ # the edge is not seeing the client.
+ for expect in ('s0', 's1', 's2'):
+ with self.subTest(expect=expect):
+ verdict, reason = probe.judge(expect, 443, recorded('echo-other-client'),
+ recorded('echo-other-client'), CLIENT)
+ self.assertEqual('fail', verdict)
+ self.assertIn('198.51.100.7', reason)
+ verdict, _ = probe.judge('s1', 443, recorded('echo-200'), recorded('echo-other-client'), CLIENT)
+ self.assertEqual('fail', verdict)
+ record, calls = run([('echo-200', 'tls-alert')] * 3 + [('echo-other-client', 'tls-alert')] + [('echo-200', 'tls-alert')] * 40)
+ self.assertFalse(record['passed'])
+ self.assertEqual(4, len(record['attempts']))
+
+ def test_forgery_echo_fails_fast(self):
+ for expect in ('s0', 's1', 's2'):
+ with self.subTest(expect=expect):
+ verdict, reason = probe.judge(expect, 443, recorded('echo-200'), recorded('echo-forged'), CLIENT)
+ self.assertEqual('fail', verdict)
+ self.assertIn('192.0.2.1', reason)
+ # The marker's address anywhere in the echo fails, even when the last
+ # entry is the probe's own (where S0 would otherwise call it a match).
+ verdict, reason = probe.judge(expect, 443, recorded('echo-200'), recorded('echo-forged-chain'), CLIENT)
+ self.assertEqual('fail', verdict)
+ self.assertIn('forged', reason)
+ record, calls = run([('echo-200', 'tls-alert')] * 5 + [('echo-200', 'echo-forged')] + [('echo-200', 'tls-alert')] * 40)
+ self.assertFalse(record['passed'])
+ self.assertEqual(6, len(record['attempts']))
+ self.assertIn('192.0.2.1', record['reason'])
+ self.assertEqual('fail', record['attempts'][-1]['verdict'])
+ # The marker the probe sends is the spec's: PPv2 PROXY INET/STREAM from 192.0.2.1.
+ header = probe.marker_header('54.77.110.223', 443, 40001)
+ self.assertEqual(b'\r\n\r\n\x00\r\nQUIT\n', header[:12])
+ self.assertEqual((0x21, 0x11, 12), struct.unpack('!BBH', header[12:16]))
+ self.assertEqual(16 + 12, len(header))
+ self.assertEqual(ipaddress.ip_address('192.0.2.1'), ipaddress.ip_address(header[16:20]))
+ self.assertEqual(ipaddress.ip_address('54.77.110.223'), ipaddress.ip_address(header[20:24]))
+ self.assertEqual((40001, 443), struct.unpack('!HH', header[24:28]))
+
+ def test_thirty_consecutive_needed(self):
+ ok, propagating = ('echo-200', 'tls-alert'), ('echo-200', 'echo-200')
+ record, calls = run([ok] * 29 + [propagating] + [ok] * 30 + [ok] * 10)
+ self.assertTrue(record['passed'])
+ self.assertEqual(60, len(record['attempts']))
+ self.assertEqual('mismatch', record['attempts'][29]['verdict'])
+ # Every 2 s, from the start.
+ self.assertEqual([2.0 * i for i in range(60)], calls)
+ record, _ = run([ok] * 29, timeout=58.0)
+ self.assertFalse(record['passed'])
+ self.assertIn('timed out', record['reason'])
+ record, _ = run([ok] * 30)
+ self.assertTrue(record['passed'])
+
+ def test_record_and_arguments(self):
+ record, _ = run([('echo-200', 'tls-alert')] * 30)
+ for key in ('passed', 'reason', 'attempts'):
+ self.assertIn(key, record)
+ attempt = record['attempts'][0]
+ self.assertEqual(('match', 'tls_alert', 200), (attempt['verdict'], attempt['marker']['kind'], attempt['plain']['status']))
+ self.assertEqual((40000, 40127), probe.parse_ports('40000-40127'))
+ for bad in ('40000', '40127-40000', '80-200', '40000-40010', '40000-70000'):
+ with self.subTest(bad=bad):
+ with self.assertRaises(ValueError):
+ probe.parse_ports(bad)
+ result = subprocess.run([sys.executable, str(SCRIPT), '--nlb-ip', '54.77.110.223', '--port', '8080',
+ '--host', 'echo.example.com', '--path', '/xff', '--expect-client', CLIENT,
+ '--source-ports', '40000-40127', '--expect', 's1', '--out', '/nonexistent/x.json'],
+ capture_output=True, text=True, timeout=30)
+ self.assertEqual(2, result.returncode)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/ppv2_step_test.py b/scripts/ppv2_step_test.py
new file mode 100644
index 000000000..1203b194f
--- /dev/null
+++ b/scripts/ppv2_step_test.py
@@ -0,0 +1,746 @@
+"""Tests for scripts/ppv2-step.py, the PPv2 cutover step gate (edge PPv2 spec 6.2-6.4).
+
+Every AWS and tofu call goes to fake `aws` and `tofu` executables on PATH that
+answer from a JSON world file and log their argv; nothing reaches AWS or tofu.
+Run from the repo root: python3 -m unittest scripts/ppv2_step_test.py
+"""
+import copy
+import importlib.util
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+SCRIPT = Path(__file__).with_name('ppv2-step.py')
+DATA = Path(__file__).parent / 'testdata' / 'ppv2'
+
+NLB = 'arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/carlos-dev-ie/0123456789abcdef'
+OTHER_NLB = 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/carlos-dev-us/fedcba9876543210'
+TG = {'80': 'arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-80/1111111111111111',
+ '443': 'arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-443/2222222222222222'}
+ADDR = {port: f'module.ingress_ie.aws_lb_target_group.target["{port}"]' for port in TG}
+TARGETS = ['i-0aaaaaaaaaaaaaaa1', 'i-0bbbbbbbbbbbbbbb2']
+SOURCES = ['172.31.11.189', '172.31.29.110']
+ALARM = 'carlos-dev-ie-proxy-trust'
+APPLIED_AT = '2026-11-12T10:00:00.000000Z'
+STATES = {'S0': ('true', 'false'), 'S1': ('true', 'true'), 'S2': ('false', 'true'), 'S3': ('false', 'false')}
+# The tfvars file as an operator might have formatted it: the restore must
+# give these exact bytes back, not a re-serialisation.
+TFVARS = (b'{ "ppv2_preserve_client_ip": {"80": true, "443": true},\n'
+ b' "ppv2_proxy_protocol_v2": {"80": false, "443": false} }\n')
+
+FAKE = r'''
+import json, os, sys
+from pathlib import Path
+
+name = Path(sys.argv[0]).name
+args = sys.argv[1:]
+world_path = Path(os.environ['PPV2_FAKE_WORLD'])
+world = json.loads(world_path.read_text())
+seq_path = world_path.with_suffix('.seq')
+seq = json.loads(seq_path.read_text()) if seq_path.exists() else {}
+entry = {'cli': name, 'args': args}
+
+def save():
+ seq_path.write_text(json.dumps(seq))
+
+def nxt(key, items):
+ i = seq.get(key, 0)
+ seq[key] = i + 1
+ save()
+ return items[min(i, len(items) - 1)]
+
+def opt(flag):
+ return args[args.index(flag) + 1] if flag in args else None
+
+def many(flag):
+ out = []
+ if flag in args:
+ for a in args[args.index(flag) + 1:]:
+ if a.startswith('--'):
+ break
+ out.append(a)
+ return out
+
+def done(code=0, out=None, err=''):
+ with open(os.environ['PPV2_FAKE_CALLS'], 'a') as f:
+ f.write(json.dumps(entry) + '\n')
+ if out is not None:
+ sys.stdout.write(out if isinstance(out, str) else json.dumps(out))
+ sys.stderr.write(err)
+ sys.exit(code)
+
+if name == 'aws':
+ i = 0
+ rest = []
+ while i < len(args):
+ if args[i] in ('--profile', '--region', '--output'):
+ entry[args[i][2:]] = args[i + 1]
+ i += 2
+ continue
+ rest = args[i:]
+ break
+ svc, op = rest[0], rest[1]
+ entry['op'] = svc + ' ' + op
+ if op == 'describe-target-group-attributes':
+ arn = opt('--target-group-arn')
+ if arn not in world['attributes']:
+ done(254, err='TargetGroupNotFound')
+ attrs = world['attributes'][arn]
+ done(out={'Attributes': [{'Key': k, 'Value': v} for k, v in attrs.items()]})
+ if op == 'describe-target-groups':
+ arn = many('--target-group-arns')[0]
+ tg = world['target_groups'][arn]
+ done(out={'TargetGroups': [dict(tg, TargetGroupArn=arn)]})
+ if op == 'describe-target-health':
+ arn = opt('--target-group-arn')
+ rows = nxt('health:' + arn, world['health'][arn])
+ done(out={'TargetHealthDescriptions': [
+ {'Target': {'Id': iid, 'Port': 80}, 'TargetHealth': {'State': state}} for iid, state in rows]})
+ if op == 'send-command':
+ n = seq.get('commands', 0) + 1
+ seq['commands'] = n
+ cid = 'cmd-%d' % n
+ seq['text:' + cid] = json.loads(opt('--parameters'))['commands'][0]
+ save()
+ entry['instances'] = many('--instance-ids')
+ entry['document'] = opt('--document-name')
+ done(out={'Command': {'CommandId': cid}})
+ if op == 'get-command-invocation':
+ cid, iid = opt('--command-id'), opt('--instance-id')
+ text = seq['text:' + cid]
+ if 'trust-status' in text:
+ sample = nxt('trust:' + iid, world['trust'][iid])
+ if 'rc' in sample:
+ done(out={'Status': 'Failed', 'ResponseCode': sample['rc'],
+ 'StandardOutputContent': '', 'StandardErrorContent': sample['stderr']})
+ done(out={'Status': 'Success', 'ResponseCode': 0,
+ 'StandardOutputContent': json.dumps(sample) + '\n', 'StandardErrorContent': ''})
+ if 'journalctl' in text:
+ done(out={'Status': 'Success', 'ResponseCode': 0,
+ 'StandardOutputContent': world['journal'][iid] + '\n', 'StandardErrorContent': ''})
+ done(1, err='unknown command ' + text)
+ if op == 'describe-alarms':
+ names = many('--alarm-names')
+ done(out={'MetricAlarms': [{'AlarmName': n, 'StateValue': world['alarms'][n]}
+ for n in names if n in world['alarms']]})
+ done(1, err='fake aws: unhandled ' + ' '.join(args))
+
+if name == 'tofu':
+ chdir = None
+ if args and args[0].startswith('-chdir='):
+ chdir = args[0][len('-chdir='):]
+ args = args[1:]
+ entry['chdir'] = chdir
+ entry['args'] = args
+ if args[:3] == ['state', 'show', '-json']:
+ addr = args[3]
+ if addr not in world['state']:
+ done(1, err='No instance found for the given address!')
+ done(out=world['state'][addr])
+ if args[0] == 'plan':
+ entry['tfvars'] = (Path(chdir) / 'ppv2.auto.tfvars.json').read_text()
+ out = [a for a in args if a.startswith('-out=')][0][len('-out='):]
+ Path(chdir, out).write_text('fake plan')
+ done(world.get('plan_rc', 0))
+ if args[:2] == ['show', '-json']:
+ done(out=world['plan'])
+ if args[0] == 'apply':
+ done(world.get('apply_rc', 0))
+ done(1, err='fake tofu: unhandled ' + ' '.join(args))
+'''
+
+
+def load_script():
+ spec = importlib.util.spec_from_file_location('ppv2_step', SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def trust(name):
+ return copy.deepcopy(json.loads((DATA / 'trust-status.json').read_text())[name])
+
+
+def state_output(port):
+ text = (DATA / 'tofu-state-show-tg80.jsonl').read_text()
+ if port == '443':
+ text = text.replace('carlos-dev-ie-80/1111111111111111', 'carlos-dev-ie-443/2222222222222222')
+ text = text.replace('target[\\"80\\"]', 'target[\\"443\\"]').replace('"index":"80"', '"index":"443"')
+ text = text.replace('"port":80', '"port":443').replace('"name":"carlos-dev-ie-80"', '"name":"carlos-dev-ie-443"')
+ return text
+
+
+# What each step's plan looks like when tofu does exactly the one change.
+STEP_PLAN = {
+ 'A80': ('80', 'proxy_protocol_v2', {'preserve_client_ip': 'true', 'proxy_protocol_v2': False},
+ {'preserve_client_ip': 'true', 'proxy_protocol_v2': True}),
+ 'A443': ('443', 'proxy_protocol_v2', {'preserve_client_ip': 'true', 'proxy_protocol_v2': False},
+ {'preserve_client_ip': 'true', 'proxy_protocol_v2': True}),
+ 'B80': ('80', 'preserve_client_ip', {'preserve_client_ip': 'true', 'proxy_protocol_v2': True},
+ {'preserve_client_ip': 'false', 'proxy_protocol_v2': True}),
+ 'B443': ('443', 'preserve_client_ip', {'preserve_client_ip': 'true', 'proxy_protocol_v2': True},
+ {'preserve_client_ip': 'false', 'proxy_protocol_v2': True}),
+ 'R80': ('80', 'preserve_client_ip', {'preserve_client_ip': 'false', 'proxy_protocol_v2': True},
+ {'preserve_client_ip': 'true', 'proxy_protocol_v2': True}),
+ 'R443': ('443', 'preserve_client_ip', {'preserve_client_ip': 'false', 'proxy_protocol_v2': True},
+ {'preserve_client_ip': 'true', 'proxy_protocol_v2': True}),
+}
+STEP_FROM = {'A80': 'S0', 'A443': 'S0', 'B80': 'S1', 'B443': 'S1', 'R80': 'S2', 'R443': 'S2'}
+
+
+def plan_for_step(step):
+ port, attribute, before, after = STEP_PLAN[step]
+ doc = json.loads((DATA / 'plan-a80.json').read_text())
+ change = doc['resource_changes'][0]
+ change['address'] = ADDR[port]
+ change['index'] = port
+ for side, values in (('before', before), ('after', after)):
+ change['change'][side].update(values)
+ change['change'][side].update(arn=TG[port], port=int(port), name='carlos-dev-ie-' + port)
+ return doc
+
+
+def tfvars_for(states):
+ """The tfvars file agreeing with live states {'80': 'S0', '443': 'S1'}."""
+ return (json.dumps({
+ 'ppv2_preserve_client_ip': {p: STATES[s][0] == 'true' for p, s in states.items()},
+ 'ppv2_proxy_protocol_v2': {p: STATES[s][1] == 'true' for p, s in states.items()},
+ }) + '\n').encode()
+
+
+class Harness(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR'))
+ self.addCleanup(self.tmp.cleanup)
+ base = Path(self.tmp.name)
+ self.bin = base / 'bin'
+ self.bin.mkdir()
+ for name in ('aws', 'tofu'):
+ shim = self.bin / name
+ shim.write_text('#!' + sys.executable + '\n' + FAKE)
+ shim.chmod(0o755)
+ self.root = base / 'root'
+ self.root.mkdir()
+ self.tfvars = self.root / 'ppv2.auto.tfvars.json'
+ self.records = base / 'records'
+ self.records.mkdir()
+ self.probes = base / 'probes'
+ self.probes.mkdir()
+ self.world_path = base / 'world.json'
+ self.calls_path = base / 'calls.jsonl'
+ self.world = {
+ 'attributes': {},
+ 'target_groups': {TG[p]: {'Port': int(p), 'Protocol': 'TCP', 'LoadBalancerArns': [NLB]} for p in TG},
+ 'health': {TG[p]: [[[t, 'healthy'] for t in TARGETS]] for p in TG},
+ 'trust': {t: [trust('baseline')] for t in TARGETS},
+ 'journal': {t: 'edge: proxy protocol: armed on :80 and :443, trusting 172.31.11.189,172.31.29.110, barrier down'
+ for t in TARGETS},
+ 'alarms': {ALARM: 'OK'},
+ 'state': {ADDR[p]: state_output(p) for p in TG},
+ 'plan': None,
+ }
+ self.live({'80': 'S0', '443': 'S0'})
+
+ def live(self, states):
+ for port, state in states.items():
+ preserve, ppv2 = STATES[state]
+ self.world['attributes'][TG[port]] = {
+ 'deregistration_delay.timeout_seconds': '30', 'preserve_client_ip.enabled': preserve,
+ 'proxy_protocol_v2.enabled': ppv2, 'stickiness.enabled': 'false'}
+ self.tfvars.write_bytes(tfvars_for(states))
+
+ def run_step(self, *args, expect=None):
+ self.world_path.write_text(json.dumps(self.world))
+ env = dict(os.environ, PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
+ PPV2_FAKE_WORLD=str(self.world_path), PPV2_FAKE_CALLS=str(self.calls_path))
+ result = subprocess.run([sys.executable, str(SCRIPT), *args], env=env, text=True,
+ capture_output=True, timeout=60, stdin=subprocess.DEVNULL)
+ if expect is not None:
+ self.assertEqual(expect, result.returncode, result.stdout + result.stderr)
+ return result
+
+ def calls(self):
+ if not self.calls_path.exists():
+ return []
+ return [json.loads(line) for line in self.calls_path.read_text().splitlines()]
+
+ def ops(self):
+ return [c.get('op') or ' '.join(c['args'][:2]) for c in self.calls()]
+
+ def apply(self, step, port=None, expect=None, targets=None, nlb=NLB):
+ port = port or STEP_PLAN[step][0]
+ return self.run_step('apply', '--root', str(self.root), '--profile', 'kass', '--region', 'eu-west-1',
+ '--nlb-arn', nlb, '--tg-arn', TG[port], '--tg-address', ADDR[port],
+ '--port', port, '--step', step, '--targets', ','.join(targets or TARGETS),
+ '--record-dir', str(self.records), expect=expect)
+
+ def record(self, name, **values):
+ doc = dict(values)
+ (self.records / (name + '.json')).write_text(json.dumps(doc))
+
+ def prereq(self, nlb=NLB, passed=True):
+ self.record('prereq', nlb_arn=nlb, passed=passed, sources=SOURCES, targets=TARGETS,
+ checked_at='2026-11-12T09:00:00.000000Z')
+
+ def converged(self, step, nlb=NLB, passed=True, applied_at=APPLIED_AT):
+ port = STEP_PLAN[step][0]
+ self.record(step + '-applied', nlb_arn=nlb, port=port, step=step, applied_at=applied_at,
+ tg_arn=TG[port], baseline={})
+ self.record(step, nlb_arn=nlb, port=port, step=step, applied_at=applied_at, passed=passed)
+
+ def assert_refused(self, result, text):
+ self.assertEqual(1, result.returncode, result.stdout + result.stderr)
+ self.assertIn(text, result.stderr)
+
+ def assert_not_changed(self, original):
+ self.assertEqual(original, self.tfvars.read_bytes())
+ self.assertNotIn('apply', [c['args'][0] for c in self.calls() if c['cli'] == 'tofu'])
+
+ def ready_for(self, step):
+ """World and records in which `step` is allowed."""
+ port = STEP_PLAN[step][0]
+ other = '443' if port == '80' else '80'
+ before = {'A80': 'S0', 'A443': 'S1', 'B80': 'S1', 'B443': 'S2', 'R443': 'S2', 'R80': 'S1'}[step]
+ self.live({port: STEP_FROM[step], other: before})
+ self.world['plan'] = plan_for_step(step)
+ self.prereq()
+ for pred in {'A443': ['A80'], 'B80': ['A80', 'A443'], 'B443': ['A80', 'A443', 'B80']}.get(step, []):
+ self.converged(pred)
+
+
+class StepGateTests(Harness):
+ def test_allowed_moves(self):
+ gate = load_script()
+ self.assertEqual({('S0', 'S1'), ('S1', 'S2'), ('S2', 'S1')}, set(gate.ALLOWED))
+ for step in ('A80', 'A443', 'B80', 'B443', 'R443', 'R80'):
+ with self.subTest(step=step):
+ self.setUp()
+ self.ready_for(step)
+ original = self.tfvars.read_bytes()
+ result = self.apply(step, expect=0)
+ port, attribute = STEP_PLAN[step][:2]
+ # Exactly one key moved in the file, the plan saw it, and the saved plan was applied.
+ before, after = json.loads(original), json.loads(self.tfvars.read_text())
+ key = 'ppv2_' + attribute
+ self.assertEqual(not before[key][port], after[key][port])
+ before[key][port] = after[key][port]
+ self.assertEqual(before, after)
+ plans = [c for c in self.calls() if c['cli'] == 'tofu' and c['args'][0] == 'plan']
+ self.assertEqual(1, len(plans))
+ self.assertIn('-target=' + ADDR[port], plans[0]['args'])
+ self.assertEqual(json.loads(plans[0]['tfvars']), after)
+ applies = [c for c in self.calls() if c['cli'] == 'tofu' and c['args'][0] == 'apply']
+ self.assertEqual(1, len(applies))
+ planfile = [a for a in plans[0]['args'] if a.startswith('-out=')][0][len('-out='):]
+ self.assertEqual(planfile, applies[0]['args'][-1])
+ record = json.loads((self.records / (step + '-applied.json')).read_text())
+ self.assertEqual((NLB, port, step, TG[port]),
+ (record['nlb_arn'], record['port'], record['step'], record['tg_arn']))
+ self.assertIn('applied_at', record)
+ self.assertEqual(sorted(TARGETS), sorted(record['baseline']))
+ self.assertEqual(trust('baseline'), record['baseline'][TARGETS[0]])
+ self.assertIn('applied', result.stdout)
+ # Every aws call named the profile and region.
+ for call in self.calls():
+ if call['cli'] == 'aws':
+ self.assertEqual(('kass', 'eu-west-1'), (call['profile'], call['region']))
+ sent = [c for c in self.calls() if c.get('op') == 'ssm send-command']
+ self.assertTrue(sent)
+ self.assertEqual('AWS-RunShellScript', sent[0]['document'])
+ self.assertEqual(sorted(TARGETS), sorted(sent[0]['instances']))
+
+ def test_refused_moves(self):
+ gate = load_script()
+ for current, target in [('S0', 'S2'), ('S2', 'S0'), ('S1', 'S0'), ('S3', 'S0'), ('S3', 'S1'),
+ ('S3', 'S2'), ('S0', 'S3'), ('S1', 'S3'), ('S2', 'S3'), ('S0', 'S0')]:
+ with self.subTest(move=(current, target)):
+ self.assertIsNotNone(gate.move_refusal(current, target))
+ for current, target in gate.ALLOWED:
+ self.assertIsNone(gate.move_refusal(current, target))
+ # Through the script: each step from a state it must not leave that way.
+ cases = [
+ ('B80', 'S0', 'S0 to S3'), # preservation off with PPv2 off: S3
+ ('R80', 'S1', 'no change'), # nothing to do; never a way to S0
+ ('A80', 'S2', 'no change'),
+ ('A80', 'S3', 'from S3'),
+ ('B80', 'S3', 'from S3'),
+ ('R80', 'S3', 'from S3'),
+ ('B80', 'S2', 'S2 to S2'),
+ ]
+ for step, state, text in cases:
+ with self.subTest(step=step, state=state):
+ self.setUp()
+ self.ready_for(step)
+ self.live({'80': state, '443': 'S0'})
+ original = self.tfvars.read_bytes()
+ self.assert_refused(self.apply(step), text)
+ self.assert_not_changed(original)
+ self.assertNotIn('plan', [c['args'][0] for c in self.calls() if c['cli'] == 'tofu'])
+ # A step for one port refused against the other port's target group.
+ self.setUp()
+ self.ready_for('A80')
+ result = self.run_step('apply', '--root', str(self.root), '--profile', 'kass', '--region', 'eu-west-1',
+ '--nlb-arn', NLB, '--tg-arn', TG['443'], '--tg-address', ADDR['443'],
+ '--port', '443', '--step', 'A80', '--targets', ','.join(TARGETS),
+ '--record-dir', str(self.records))
+ self.assert_refused(result, 'step A80 is for port 80')
+ # No step turns PPv2 off: the choices stop at argparse.
+ self.assertEqual(2, self.apply('X80', port='80').returncode)
+ for step, (port, attribute, before, after) in STEP_PLAN.items():
+ self.assertFalse(after['proxy_protocol_v2'] is False and attribute == 'proxy_protocol_v2')
+ self.assertEqual(attribute, gate.STEPS[step].attribute)
+
+ def test_predecessor_map(self):
+ gate = load_script()
+ self.assertEqual({'A80': 'prereq', 'A443': 'A80', 'B80': 'A443', 'B443': 'B80', 'R443': None, 'R80': None},
+ gate.PREDECESSOR)
+ for step, pred in [('A80', 'prereq'), ('A443', 'A80'), ('B80', 'A443'), ('B443', 'B80')]:
+ for fault in ('missing', 'not passed', 'other NLB', 'stale'):
+ if pred == 'prereq' and fault == 'stale':
+ continue
+ with self.subTest(step=step, fault=fault):
+ self.setUp()
+ self.ready_for(step)
+ original = self.tfvars.read_bytes()
+ path = self.records / (pred + '.json')
+ if fault == 'missing':
+ path.unlink()
+ text = pred + '.json'
+ elif fault == 'not passed':
+ doc = json.loads(path.read_text())
+ doc['passed'] = False
+ path.write_text(json.dumps(doc))
+ text = 'did not pass'
+ elif fault == 'other NLB':
+ doc = json.loads(path.read_text())
+ doc['nlb_arn'] = OTHER_NLB
+ path.write_text(json.dumps(doc))
+ text = 'another load balancer'
+ else:
+ # A later apply of the predecessor that has not converged yet.
+ applied = self.records / (pred + '-applied.json')
+ doc = json.loads(applied.read_text())
+ doc['applied_at'] = '2026-11-12T11:00:00.000000Z'
+ applied.write_text(json.dumps(doc))
+ text = 'not for its latest apply'
+ self.assert_refused(self.apply(step), text)
+ self.assert_not_changed(original)
+ self.assertNotIn('ssm send-command', self.ops())
+ # Reverse steps need no record at all.
+ for step in ('R443', 'R80'):
+ with self.subTest(step=step):
+ self.setUp()
+ self.ready_for(step)
+ (self.records / 'prereq.json').unlink()
+ self.apply(step, expect=0)
+ # A reverse step supersedes the forward record for its port, so the
+ # next forward step needs fresh evidence.
+ self.setUp()
+ self.ready_for('R80')
+ self.converged('B80')
+ self.apply('R80', expect=0)
+ self.assertFalse((self.records / 'B80.json').exists())
+ self.assertTrue(list(self.records.glob('B80.superseded-*.json')))
+ self.live({'80': 'S1', '443': 'S1'})
+ self.world['plan'] = plan_for_step('B443')
+ self.assert_refused(self.apply('B443'), 'B80.json')
+
+ def test_address_must_match_state(self):
+ for fault in ('arn', 'port', 'missing'):
+ with self.subTest(fault=fault):
+ self.setUp()
+ self.ready_for('A80')
+ original = self.tfvars.read_bytes()
+ if fault == 'arn':
+ self.world['state'][ADDR['80']] = state_output('80').replace(
+ '"arn":"arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-80/1111111111111111"',
+ '"arn":"' + TG['443'] + '"')
+ text = 'has arn'
+ elif fault == 'port':
+ self.world['state'][ADDR['80']] = state_output('80').replace('"port":80', '"port":443')
+ text = 'has port 443'
+ else:
+ del self.world['state'][ADDR['80']]
+ text = 'tofu state show'
+ self.assert_refused(self.apply('A80'), text)
+ self.assert_not_changed(original)
+ # Checked before anything else: no AWS call at all.
+ self.assertEqual([], [c for c in self.calls() if c['cli'] == 'aws'])
+ # The target group must belong to the named load balancer and port.
+ self.setUp()
+ self.ready_for('A80')
+ self.world['target_groups'][TG['80']]['LoadBalancerArns'] = [OTHER_NLB]
+ self.assert_refused(self.apply('A80'), 'not attached to')
+
+ def test_plan_must_change_one_attribute(self):
+ gate = load_script()
+ good = plan_for_step('A80')
+ self.assertIsNone(gate.plan_refusal(good, ADDR['80'], 'proxy_protocol_v2', False, True))
+ two_attributes = copy.deepcopy(good)
+ two_attributes['resource_changes'][0]['change']['after']['deregistration_delay'] = '0'
+ two_resources = copy.deepcopy(good)
+ extra = copy.deepcopy(good['resource_changes'][0])
+ extra['address'] = ADDR['443']
+ two_resources['resource_changes'].append(extra)
+ other_address = copy.deepcopy(good)
+ other_address['resource_changes'][0]['address'] = ADDR['443']
+ replace = copy.deepcopy(good)
+ replace['resource_changes'][0]['change']['actions'] = ['delete', 'create']
+ unknown = copy.deepcopy(good)
+ unknown['resource_changes'][0]['change']['after_unknown']['arn'] = True
+ wrong_way = plan_for_step('A80')
+ wrong_way['resource_changes'][0]['change']['before']['proxy_protocol_v2'] = True
+ wrong_way['resource_changes'][0]['change']['after']['proxy_protocol_v2'] = False
+ other_attribute = plan_for_step('B80')
+ other_attribute['resource_changes'][0]['address'] = ADDR['80']
+ nothing = copy.deepcopy(good)
+ nothing['resource_changes'] = [good['resource_changes'][1]]
+ cases = {'two attributes': (two_attributes, 'deregistration_delay'),
+ 'two resources': (two_resources, '2 resource changes'),
+ 'another address': (other_address, ADDR['443']),
+ 'replace': (replace, 'delete'),
+ 'unknown': (unknown, 'arn'),
+ 'PPv2 off': (wrong_way, 'proxy_protocol_v2'),
+ 'another attribute': (other_attribute, 'preserve_client_ip'),
+ 'no change': (nothing, '0 resource changes')}
+ for name, (plan, text) in cases.items():
+ with self.subTest(case=name):
+ self.assertIsNotNone(gate.plan_refusal(plan, ADDR['80'], 'proxy_protocol_v2', False, True))
+ self.setUp()
+ self.ready_for('A80')
+ self.tfvars.write_bytes(TFVARS)
+ self.world['plan'] = plan
+ result = self.apply('A80')
+ self.assert_refused(result, text)
+ # The plan ran on the edited file, then the file came back byte for byte.
+ self.assertIn('plan', [c['args'][0] for c in self.calls() if c['cli'] == 'tofu'])
+ self.assert_not_changed(TFVARS)
+ # A plan that fails also restores the file.
+ self.setUp()
+ self.ready_for('A80')
+ self.tfvars.write_bytes(TFVARS)
+ self.world['plan_rc'] = 1
+ self.assert_refused(self.apply('A80'), 'tofu plan')
+ self.assert_not_changed(TFVARS)
+ # A file that disagrees with the live target group is refused before the edit.
+ self.setUp()
+ self.ready_for('A80')
+ drift = TFVARS.replace(b'"80": false', b'"80": true')
+ self.tfvars.write_bytes(drift)
+ self.assert_refused(self.apply('A80'), 'disagrees with the live')
+ self.assert_not_changed(drift)
+
+ def test_barrier_up_refuses(self):
+ for step in ('A80', 'B80'):
+ with self.subTest(step=step):
+ self.setUp()
+ self.ready_for(step)
+ self.world['trust'][TARGETS[1]] = [trust('barrier_up')]
+ original = self.tfvars.read_bytes()
+ self.assert_refused(self.apply(step), 'barrier is up on ' + TARGETS[1])
+ self.assert_not_changed(original)
+ # Rollback is the safe direction; a raised barrier does not hold it.
+ self.setUp()
+ self.ready_for('R80')
+ self.world['trust'][TARGETS[1]] = [trust('barrier_up')]
+ self.apply('R80', expect=0)
+
+ def test_unarmed_target_refuses(self):
+ self.ready_for('A80')
+ self.world['trust'][TARGETS[0]] = [trust('not_armed')]
+ original = self.tfvars.read_bytes()
+ self.assert_refused(self.apply('A80'), TARGETS[0] + ' is not armed')
+ self.assert_not_changed(original)
+ # A target missing from --targets is refused too: the gate must see every target.
+ self.setUp()
+ self.ready_for('A80')
+ self.assert_refused(self.apply('A80', targets=TARGETS[:1]), TARGETS[1])
+ # An answer that is not a trust-status line is refused, never read as armed.
+ self.setUp()
+ self.ready_for('A80')
+ partial = trust('baseline')
+ del partial['counters']['marker_trusted']
+ self.world['trust'][TARGETS[0]] = [partial]
+ self.assert_refused(self.apply('A80'), 'trust-status')
+
+
+class ConvergeTests(Harness):
+ def setUp(self):
+ super().setUp()
+ self.prereq()
+
+ def applied(self, step, baseline='baseline'):
+ port = STEP_PLAN[step][0]
+ self.live({port: {'A': 'S1', 'B': 'S2', 'R': 'S1'}[step[0]]})
+ self.record(step + '-applied', nlb_arn=NLB, port=port, step=step, applied_at=APPLIED_AT,
+ tg_arn=TG[port], tg_address=ADDR[port],
+ baseline={t: trust(baseline) for t in TARGETS})
+
+ def probe(self, name, nlb_ip, port, expect, passed=True, started_at='2026-11-12T10:00:05.000000Z'):
+ attempts = [{'at': '2026-11-12T10:00:%02d.000000Z' % (5 + 2 * i), 'verdict': 'match'} for i in range(30)]
+ doc = {'nlb_ip': nlb_ip, 'port': int(port), 'expect': expect, 'started_at': started_at,
+ 'finished_at': '2026-11-12T10:01:05.000000Z', 'passed': passed, 'attempts': attempts}
+ path = self.probes / name
+ path.write_text(json.dumps(doc))
+ return path
+
+ def converge(self, step, probes, expect=None):
+ return self.run_step('converge', '--step', step, '--record-dir', str(self.records),
+ '--probe-records', ','.join(str(p) for p in probes),
+ '--targets', ','.join(TARGETS), '--profile', 'kass', '--region', 'eu-west-1',
+ '--tg-arn', TG[STEP_PLAN[step][0]], '--timeout', '0', expect=expect)
+
+ def result(self, step):
+ return json.loads((self.records / (step + '.json')).read_text())
+
+ def test_converge_needs_both_probe_records(self):
+ a = lambda **kw: self.probe('a.json', '54.77.110.223', 80, 's1', **kw)
+ b = lambda **kw: self.probe('b.json', '54.77.110.224', 80, 's1', **kw)
+ self.applied('A80')
+ self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
+ # The good case first.
+ self.converge('A80', [a(), b()], expect=0)
+ record = self.result('A80')
+ self.assertTrue(record['passed'])
+ self.assertEqual((NLB, '80', 'A80', APPLIED_AT),
+ (record['nlb_arn'], record['port'], record['step'], record['applied_at']))
+ self.assertEqual(['54.77.110.223', '54.77.110.224'], sorted(p['nlb_ip'] for p in record['probes']))
+ self.assertTrue(all(p['propagation_s'] == 5.0 for p in record['probes']))
+ # The target group must still be in the state the step made.
+ self.live({'80': 'S0'})
+ self.assertEqual(1, self.converge('A80', [a(), b()]).returncode)
+ self.assertIn('the target group is in S0, not S1', self.result('A80')['reasons'])
+ self.live({'80': 'S1'})
+ # One record only: refused outright.
+ self.assert_refused(self.converge('A80', [a()]), 'two probe records')
+ # Each case writes its records when it runs, so no case sees another's files.
+ cases = {
+ 'same address': (lambda: [a(), self.probe('c.json', '54.77.110.223', 80, 's1')], 'both NLB addresses'),
+ 'one failed': (lambda: [a(), b(passed=False)], 'did not pass'),
+ 'started before apply': (lambda: [a(), b(started_at='2026-11-12T09:59:59.000000Z')], 'before the apply'),
+ 'other port': (lambda: [a(), self.probe('c.json', '54.77.110.224', 443, 's1')], 'port 443'),
+ 'other expectation': (lambda: [a(), self.probe('c.json', '54.77.110.224', 80, 's0')], 'expected s0'),
+ 'missing': (lambda: [a(), self.probes / 'never.json'], 'never.json'),
+ }
+ for name, (paths, text) in cases.items():
+ with self.subTest(case=name):
+ result = self.converge('A80', paths())
+ self.assertEqual(1, result.returncode, result.stderr)
+ record = self.result('A80')
+ self.assertFalse(record['passed'])
+ self.assertTrue(any(text in reason for reason in record['reasons']), record['reasons'])
+ # No applied record: nothing to converge.
+ (self.records / 'A80-applied.json').unlink()
+ self.assert_refused(self.converge('A80', [a(), b()]), 'A80-applied.json')
+
+ def test_converge_fails_on_counter_move(self):
+ for sample, counter in [('malformed_moved', 'malformed'), ('marker_trusted_moved', 'marker_trusted'),
+ ('no_client_refused_moved', 'no_client_refused'), ('barrier_up', 'barrier')]:
+ with self.subTest(counter=counter):
+ self.setUp()
+ self.applied('A443')
+ self.world['trust'][TARGETS[1]] = [trust('after_a'), trust(sample)]
+ result = self.converge('A443', [self.probe('a.json', '54.77.110.223', 443, 's1'),
+ self.probe('b.json', '54.77.110.224', 443, 's1')])
+ self.assertEqual(1, result.returncode)
+ record = self.result('A443')
+ self.assertFalse(record['passed'])
+ self.assertTrue(any(counter in r and TARGETS[1] in r for r in record['reasons']), record['reasons'])
+ # Counters that may move (proxied, no_client, ignored) do not fail it.
+ self.setUp()
+ self.applied('A443')
+ self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
+ self.converge('A443', [self.probe('a.json', '54.77.110.223', 443, 's1'),
+ self.probe('b.json', '54.77.110.224', 443, 's1')], expect=0)
+
+ def test_converge_fails_on_unhealthy_poll(self):
+ for rows, text in [([[TARGETS[0], 'healthy'], [TARGETS[1], 'unhealthy']], 'unhealthy'),
+ ([[TARGETS[0], 'healthy']], 'not registered'),
+ ([[TARGETS[0], 'healthy'], [TARGETS[1], 'healthy'], ['i-0ccccccccccccccc3', 'healthy']],
+ 'i-0ccccccccccccccc3')]:
+ with self.subTest(rows=rows):
+ self.setUp()
+ self.applied('A80')
+ self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
+ # The bad poll is the first one; the last poll is healthy again.
+ self.world['health'][TG['80']] = [rows, [[t, 'healthy'] for t in TARGETS]]
+ result = self.converge('A80', [self.probe('a.json', '54.77.110.223', 80, 's1'),
+ self.probe('b.json', '54.77.110.224', 80, 's1')])
+ self.assertEqual(1, result.returncode)
+ record = self.result('A80')
+ self.assertFalse(record['passed'])
+ self.assertTrue(any(text in r for r in record['reasons']), record['reasons'])
+ self.assertGreaterEqual(len(record['health_polls']), 2)
+
+ def test_b_convergence_needs_both_nodes(self):
+ probes = lambda: [self.probe('a.json', '54.77.110.223', 80, 's2'),
+ self.probe('b.json', '54.77.110.224', 80, 's2')]
+ self.applied('B80', baseline='before_b')
+ self.world['trust'] = {TARGETS[0]: [trust('b_both_nodes')], TARGETS[1]: [trust('b_one_node')]}
+ result = self.converge('B80', probes())
+ self.assertEqual(1, result.returncode)
+ record = self.result('B80')
+ self.assertFalse(record['passed'])
+ self.assertTrue(any(TARGETS[1] in r and '172.31.11.189' in r for r in record['reasons']), record['reasons'])
+ self.assertFalse(any(TARGETS[0] in r for r in record['reasons']), record['reasons'])
+ # Both nodes on every target: passed.
+ self.setUp()
+ self.applied('B80', baseline='before_b')
+ self.world['trust'] = {t: [trust('b_both_nodes')] for t in TARGETS}
+ self.converge('B80', probes(), expect=0)
+ self.assertTrue(self.result('B80')['passed'])
+ # The node addresses come from prereq.json; without it B cannot converge.
+ (self.records / 'prereq.json').unlink()
+ result = self.converge('B80', probes())
+ self.assertEqual(1, result.returncode)
+ self.assertTrue(any('prereq.json' in r for r in self.result('B80')['reasons']))
+ # A steps do not need the nodes to rise.
+ self.setUp()
+ self.applied('A80')
+ self.world['trust'] = {t: [trust('after_a')] for t in TARGETS}
+ self.converge('A80', [self.probe('a.json', '54.77.110.223', 80, 's1'),
+ self.probe('b.json', '54.77.110.224', 80, 's1')], expect=0)
+
+
+class PrereqTests(Harness):
+ def run_prereq(self, expect=None):
+ return self.run_step('prereq', '--profile', 'kass', '--region', 'eu-west-1', '--nlb-arn', NLB,
+ '--tg-arn-80', TG['80'], '--tg-arn-443', TG['443'],
+ '--targets', ','.join(TARGETS), '--sources', ','.join(reversed(SOURCES)),
+ '--alarm', ALARM, '--record-dir', str(self.records), expect=expect)
+
+ def test_prereq_record(self):
+ self.run_prereq(expect=0)
+ record = json.loads((self.records / 'prereq.json').read_text())
+ self.assertTrue(record['passed'])
+ self.assertEqual((NLB, SOURCES), (record['nlb_arn'], record['sources']))
+ cases = {
+ 'TG not in S0': (lambda: self.live({'80': 'S1', '443': 'S0'}), 'S1'),
+ 'other addresses': (lambda: self.world['journal'].update(
+ {TARGETS[1]: 'edge: proxy protocol: armed on :80 and :443, trusting 172.31.29.110, barrier down'}),
+ 'trusts 172.31.29.110'),
+ 'never armed': (lambda: self.world['journal'].update({TARGETS[1]: ''}), 'no armed line'),
+ 'barrier up': (lambda: self.world['trust'].update({TARGETS[0]: [trust('barrier_up')]}), 'barrier'),
+ 'not armed': (lambda: self.world['trust'].update({TARGETS[0]: [trust('not_armed')]}), 'not armed'),
+ 'alarm': (lambda: self.world['alarms'].update({ALARM: 'INSUFFICIENT_DATA'}), 'INSUFFICIENT_DATA'),
+ 'alarm missing': (lambda: self.world.update(alarms={}), ALARM),
+ 'unhealthy': (lambda: self.world['health'].update(
+ {TG['443']: [[[TARGETS[0], 'healthy'], [TARGETS[1], 'draining']]]}), 'draining'),
+ }
+ for name, (fault, text) in cases.items():
+ with self.subTest(case=name):
+ self.setUp()
+ fault()
+ result = self.run_prereq()
+ self.assertEqual(1, result.returncode, result.stderr)
+ self.assertIn(text, result.stderr)
+ record = json.loads((self.records / 'prereq.json').read_text())
+ self.assertFalse(record['passed'])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/testdata/ppv2/plan-a80.json b/scripts/testdata/ppv2/plan-a80.json
new file mode 100644
index 000000000..ca09f771a
--- /dev/null
+++ b/scripts/testdata/ppv2/plan-a80.json
@@ -0,0 +1,59 @@
+{
+ "format_version": "1.2",
+ "terraform_version": "1.12.5",
+ "errored": false,
+ "resource_changes": [
+ {
+ "address": "module.ingress_ie.aws_lb_target_group.target[\"80\"]",
+ "module_address": "module.ingress_ie",
+ "mode": "managed",
+ "type": "aws_lb_target_group",
+ "name": "target",
+ "index": "80",
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {
+ "actions": ["update"],
+ "before": {
+ "arn": "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-80/1111111111111111",
+ "connection_termination": false,
+ "deregistration_delay": "30",
+ "name": "carlos-dev-ie-80",
+ "port": 80,
+ "preserve_client_ip": "true",
+ "protocol": "TCP",
+ "proxy_protocol_v2": false,
+ "tags": {},
+ "tags_all": {},
+ "target_type": "instance",
+ "vpc_id": "vpc-0123456789abcdef0"
+ },
+ "after": {
+ "arn": "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-80/1111111111111111",
+ "connection_termination": false,
+ "deregistration_delay": "30",
+ "name": "carlos-dev-ie-80",
+ "port": 80,
+ "preserve_client_ip": "true",
+ "protocol": "TCP",
+ "proxy_protocol_v2": true,
+ "tags": {},
+ "tags_all": {},
+ "target_type": "instance",
+ "vpc_id": "vpc-0123456789abcdef0"
+ },
+ "after_unknown": {"tags": {}, "tags_all": {}},
+ "before_sensitive": {"tags": {}, "tags_all": {}},
+ "after_sensitive": {"tags": {}, "tags_all": {}}
+ }
+ },
+ {
+ "address": "module.ingress_ie.aws_lb.nlb",
+ "module_address": "module.ingress_ie",
+ "mode": "managed",
+ "type": "aws_lb",
+ "name": "nlb",
+ "provider_name": "registry.opentofu.org/hashicorp/aws",
+ "change": {"actions": ["no-op"], "before": {"name": "carlos-dev-ie"}, "after": {"name": "carlos-dev-ie"}, "after_unknown": {}}
+ }
+ ]
+}
diff --git a/scripts/testdata/ppv2/probe-responses.json b/scripts/testdata/ppv2/probe-responses.json
new file mode 100644
index 000000000..f4ad2ede2
--- /dev/null
+++ b/scripts/testdata/ppv2/probe-responses.json
@@ -0,0 +1,36 @@
+{
+ "_comment": "Recorded probe exchanges (spec 6.4 table). raw is the bytes read back until close; error is the exception class the socket or TLS layer raised before any answer. The probe's public address is 203.0.113.9.",
+ "expect_client": "203.0.113.9",
+ "responses": {
+ "echo-200": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 12\r\nConnection: close\r\n\r\n203.0.113.9\n"},
+ "echo-200-chunked": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n18\r\n10.20.30.40, 203.0.113.9\r\n0\r\n\r\n"},
+ "redirect-302": {"raw": "HTTP/1.1 302 Found\r\nContent-Type: text/html; charset=utf-8\r\nLocation: https://echo.example.com/xff\r\nContent-Length: 50\r\nConnection: close\r\n\r\n<a href=\"https://echo.example.com/xff\">Found</a>.\n"},
+ "bad-request-400": {"raw": "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n400 Bad Request"},
+ "tls-alert": {"error": "SSLError", "detail": "[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:1029)"},
+ "tls-eof": {"error": "SSLEOFError", "detail": "[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1029)"},
+ "reset": {"error": "ConnectionResetError", "detail": "[Errno 104] Connection reset by peer"},
+ "closed-empty": {"raw": ""},
+ "refused-503": {"raw": "HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 20\r\n\r\nService Unavailable\n"},
+ "timeout": {"error": "TimeoutError", "detail": "timed out"},
+ "echo-other-client": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\n198.51.100.7\n"},
+ "echo-forged": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 10\r\n\r\n192.0.2.1\n"},
+ "echo-forged-chain": {"raw": "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 23\r\n\r\n192.0.2.1, 203.0.113.9\n"}
+ },
+ "table": [
+ {"state": "s0", "port": 443, "plain": "echo-200", "marker": "echo-200"},
+ {"state": "s0", "port": 443, "plain": "echo-200-chunked", "marker": "echo-200"},
+ {"state": "s1", "port": 443, "plain": "echo-200", "marker": "tls-alert"},
+ {"state": "s1", "port": 443, "plain": "echo-200", "marker": "tls-eof"},
+ {"state": "s1", "port": 443, "plain": "echo-200", "marker": "reset"},
+ {"state": "s2", "port": 443, "plain": "echo-200", "marker": "tls-alert"},
+ {"state": "s2", "port": 443, "plain": "echo-200", "marker": "closed-empty"},
+ {"state": "s0", "port": 80, "plain": "redirect-302", "marker": "redirect-302"},
+ {"state": "s1", "port": 80, "plain": "redirect-302", "marker": "bad-request-400"},
+ {"state": "s2", "port": 80, "plain": "redirect-302", "marker": "bad-request-400"},
+ {"state": "s2", "port": 80, "plain": "redirect-302", "marker": "reset"}
+ ],
+ "s3": [
+ {"port": 443, "plain": "refused-503", "marker": "closed-empty"},
+ {"port": 80, "plain": "refused-503", "marker": "closed-empty"}
+ ]
+}
diff --git a/scripts/testdata/ppv2/tofu-state-show-tg80.jsonl b/scripts/testdata/ppv2/tofu-state-show-tg80.jsonl
new file mode 100644
index 000000000..5bd35de2c
--- /dev/null
+++ b/scripts/testdata/ppv2/tofu-state-show-tg80.jsonl
@@ -0,0 +1,2 @@
+{"@level":"info","@message":"OpenTofu 1.12.5","@module":"tofu.ui","@timestamp":"2026-11-12T23:30:21.346124Z","tofu":"1.12.5","type":"version","ui":"1.2"}
+{"format_version":"1.0","terraform_version":"1.12.5","values":{"root_module":{"child_modules":[{"resources":[{"address":"module.ingress_ie.aws_lb_target_group.target[\"80\"]","mode":"managed","type":"aws_lb_target_group","name":"target","index":"80","provider_name":"registry.opentofu.org/hashicorp/aws","schema_version":0,"values":{"arn":"arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-80/1111111111111111","arn_suffix":"targetgroup/carlos-dev-ie-80/1111111111111111","connection_termination":false,"deregistration_delay":"30","id":"arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/carlos-dev-ie-80/1111111111111111","ip_address_type":"ipv4","load_balancer_arns":["arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/carlos-dev-ie/0123456789abcdef"],"name":"carlos-dev-ie-80","port":80,"preserve_client_ip":"true","protocol":"TCP","proxy_protocol_v2":false,"tags":{},"tags_all":{},"target_type":"instance","vpc_id":"vpc-0123456789abcdef0"},"sensitive_values":{"load_balancer_arns":[false],"tags":{},"tags_all":{}}}],"address":"module.ingress_ie"}]}}}
diff --git a/scripts/testdata/ppv2/trust-status.json b/scripts/testdata/ppv2/trust-status.json
new file mode 100644
index 000000000..615f2476f
--- /dev/null
+++ b/scripts/testdata/ppv2/trust-status.json
@@ -0,0 +1,13 @@
+{
+ "_comment": "Recorded `carlos system edge trust-status` lines (one JSON line each on the box), keyed by situation. Shapes follow internal/host/edgetrust.go trustStatus.",
+ "baseline": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5120, "no_client_refused": 0, "ignored": 0, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
+ "after_a": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5180, "no_client_refused": 0, "ignored": 412, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
+ "before_b": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 6010, "no_client_refused": 0, "ignored": 1830, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
+ "b_both_nodes": {"armed": true, "barrier": false, "counters": {"proxied": 377, "no_client": 6070, "no_client_refused": 0, "ignored": 1902, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {"172.31.11.189": 181, "172.31.29.110": 196}},
+ "b_one_node": {"armed": true, "barrier": false, "counters": {"proxied": 196, "no_client": 6070, "no_client_refused": 0, "ignored": 1902, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {"172.31.29.110": 196}},
+ "malformed_moved": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5180, "no_client_refused": 0, "ignored": 412, "ignored_private": 0, "marker_trusted": 0, "malformed": 1, "timeout": 0}, "proxied_by_node": {}},
+ "marker_trusted_moved": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5180, "no_client_refused": 0, "ignored": 412, "ignored_private": 0, "marker_trusted": 2, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
+ "no_client_refused_moved": {"armed": true, "barrier": false, "counters": {"proxied": 0, "no_client": 5180, "no_client_refused": 7, "ignored": 412, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
+ "barrier_up": {"armed": true, "barrier": true, "counters": {"proxied": 0, "no_client": 5120, "no_client_refused": 0, "ignored": 0, "ignored_private": 0, "marker_trusted": 0, "malformed": 0, "timeout": 0}, "proxied_by_node": {}},
+ "not_armed": {"rc": 2, "stderr": "edge: this box is not armed for PROXY protocol\n"}
+}