| index 8954cb595..805ae6560 100644 |
| --- a/scripts/region-group-boot-witness.py |
| +++ b/scripts/region-group-boot-witness.py |
| @@ -4,22 +4,24 @@ import argparse |
| import base64 |
| import difflib |
| import email.policy |
| +import fcntl |
| from email.parser import BytesParser |
| import gzip |
| import hashlib |
| -import io |
| import json |
| import os |
| from pathlib import Path |
| import re |
| import secrets |
| -import shlex |
| import shutil |
| import signal |
| import subprocess |
| import sys |
| import tarfile |
| import time |
| +import uuid |
| +from contextlib import contextmanager |
| +from datetime import datetime, timezone |
| |
| ROOT = Path(__file__).resolve().parents[1] |
| SCRATCH = Path('/home/paulca/.cache/p3b1-f4-work') |
| @@ -35,16 +37,25 @@ FIXED = {'i-046c7fe43620944bc', 'i-05498eada6f0afd23'} |
| TGS = [f'arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT}:targetgroup/{x}' for x in |
| ('carlos-dev-ie-nlb-80/2f5186277337ce74', 'carlos-dev-ie-nlb-443/c33262405df2e5df')] |
| SUBNET = 'subnet-0975dda9ac0e65347' |
| -MOUNTS = ['/run', '/tmp', '/dev/shm', '/var/tmp', '/var/lib', '/var/lib/cloud', |
| - '/var/lib/carlos-group-boot', '/opt', '/etc', '/data'] |
| +MOUNTS = ['/run', '/tmp', '/dev/shm', '/var/tmp', '/var/run', '/var/lock', '/var/lib', '/var/lib/cloud', |
| + '/var/lib/carlos-group-boot', '/opt', '/etc', '/data', |
| + '/data/instances', '/run/carlos/instances', '/run/carlos/logs'] |
| UNITS = ['carlos-edge', 'carlos-hairpin-reset', 'carlos-instance-control', 'nftables', 'chrony'] |
| -# These are incompatible requirements in the implementer brief, not AMI failures. |
| -# No switch bypasses this gate. Resolve the read contract before spending a run. |
| -LIVE_BLOCKERS = ( |
| - 'FetchGroup requires ssm:GetParametersByPath on shared and regional scratch paths; GetParameter(s) is insufficient.', |
| - 'install-channel requires signed channel, floor, manifest and artifact reads; bootstrap-key-only S3 cannot install.', |
| - 'A fresh random release public key cannot verify the dev signed channel/floor. A scratch signed release fixture is required.', |
| -) |
| +LIVE_BLOCKERS = () |
| +FLOOR_LABEL = 'floor=absent-expected (Paul 2026-11-04 21:09Z)' |
| +POINTER_KEY = 'control/system/router/stable.json' |
| +FLOOR_KEYS = ['control/moves-protocol.json', 'control/moves-protocol-auth.json'] |
| +EDGES_PREFIX = 'control/edges/' # internal/host/edgesfile.go:edgesFilePrefix |
| +PURPOSE = 'p3b1-f4-witness' |
| +SIGNALS = (signal.SIGINT, signal.SIGTERM, signal.SIGHUP) |
| + |
| + |
| +def dev_config(): |
| + config = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text()) |
| + # The witness and third dev window both use Paul's artifact pin. The |
| + # historical module fixture still tests its original version input. |
| + config['CARLOS_RELEASE'] = BOOT_SHA |
| + return config |
| |
| |
| def require(ok, message): |
| @@ -79,7 +90,7 @@ def witness_config(dev, s): |
| |
| |
| def check_diff(dev, witness, s): |
| - config = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text()) |
| + config = dev_config() |
| require(dev == plain_render(config), 'module real-dev render differs from the real-dev fixture') |
| expected = plain_render(witness_config(config, s)) |
| require(witness == expected, 'witness differs beyond deployment/pool substitutions') |
| @@ -113,9 +124,12 @@ def render(tofu, directory, s): |
| require(json.loads(subprocess.check_output([str(tofu), 'version', '-json']))['terraform_version'] == '1.13.1', |
| 'OpenTofu 1.13.1 required') |
| module = directory / 'module' |
| - shutil.copytree(ROOT / 'infra/modules/region-host', module, dirs_exist_ok=True, |
| + require(not module.exists(), 'render directory already exists') |
| + shutil.copytree(ROOT / 'infra/modules/region-host', module, |
| ignore=shutil.ignore_patterns('.terraform', '.terraform.lock.hcl')) |
| - env = dict(os.environ, AWS_EC2_METADATA_DISABLED='true', AWS_CONFIG_FILE='/dev/null', |
| + provider_cache = directory.parent / 'witness-provider-cache' |
| + provider_cache.mkdir(exist_ok=True) |
| + env = dict(os.environ, TF_PLUGIN_CACHE_DIR=str(provider_cache), AWS_EC2_METADATA_DISABLED='true', AWS_CONFIG_FILE='/dev/null', |
| AWS_SHARED_CREDENTIALS_FILE='/dev/null', AWS_ACCESS_KEY_ID='mock', AWS_SECRET_ACCESS_KEY='mock', |
| TMPDIR=str(directory), TF_IN_AUTOMATION='1') |
| env.pop('AWS_PROFILE', None) |
| @@ -129,6 +143,8 @@ def render(tofu, directory, s): |
| (directory / 'init.log').write_text(run('init', '-backend=false', '-input=false', '-no-color')) |
| test = module / 'tests/group_user_data.tftest.hcl' |
| original = test.read_text().split('run "oversize_user_data"')[0] |
| + require(original.count('release = "v0.34.2"') == 1, 'module release input drift') |
| + original = original.replace('release = "v0.34.2"', 'release = "' + BOOT_SHA + '"') |
| result = [] |
| try: |
| for label, content in [('dev', original), ('witness', original.replace('deployment = "dev"', |
| @@ -157,43 +173,61 @@ def render(tofu, directory, s): |
| return result[1] |
| |
| |
| -def policy(s, kms_key): |
| +def artifact_key(pointer): |
| + require(pointer.get('component') == 'router' and pointer.get('channel') == 'stable', 'pointer scope drift') |
| + current = pointer['current'] |
| + art = current['artifacts']['linux-arm64'] |
| + require(current['version'] == 'v0.34.2' and art['sha256'] == BOOT_SHA, 'release pin drift') |
| + require(art['key'] == 'bootstrap/router/v0.34.2/carlos-linux-arm64', 'artifact key drift') |
| + return art['key'] |
| + |
| + |
| +def policy(s, kms_key, pointer): |
| parameter = f'arn:aws:ssm:{REGION}:{ACCOUNT}:parameter' |
| + names = list(seed(s, 'policy-only', 'public-key-placeholder')) |
| return {'Version': '2012-10-17', 'Statement': [ |
| {'Effect': 'Allow', 'Action': ['ssm:GetParameter', 'ssm:GetParameters'], |
| - 'Resource': [parameter + s['prefix'] + '/*', parameter + s['shared'] + '/*']}, |
| + 'Resource': [parameter + name for name in names]}, |
| + {'Effect': 'Allow', 'Action': 'ssm:GetParametersByPath', |
| + 'Resource': [parameter + s['shared'], parameter + s['prefix']], |
| + 'Condition': {'Bool': {'ssm:Recursive': 'false'}}}, |
| {'Effect': 'Allow', 'Action': 'kms:Decrypt', 'Resource': kms_key, |
| 'Condition': {'StringEquals': {'kms:ViaService': f'ssm.{REGION}.amazonaws.com'}, |
| 'StringLike': {'kms:EncryptionContext:PARAMETER_ARN': |
| - [parameter + s['prefix'] + '/*', parameter + s['shared'] + '/*']}}}, |
| - {'Effect': 'Allow', 'Action': ['s3:GetObject', 's3:GetObjectVersion'], 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['key']}, |
| + parameter + s['prefix'] + '/CARLOS_SECRETS_KEY'}}}, |
| + {'Effect': 'Allow', 'Action': 's3:GetObject', |
| + 'Resource': [f'arn:aws:s3:::{BUCKET}/' + key for key in |
| + [s['key'], POINTER_KEY, artifact_key(pointer), *FLOOR_KEYS]]}, |
| + {'Effect': 'Allow', 'Action': 's3:GetObjectVersion', 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['key']}, |
| + {'Effect': 'Allow', 'Action': ['s3:ListBucket', 's3:GetBucketLocation'], |
| + 'Resource': f'arn:aws:s3:::{BUCKET}'}, |
| {'Effect': 'Allow', 'Action': 's3:PutObject', 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['evidence'] + '/*'}, |
| ]} |
| |
| |
| -def seed(s, version): |
| +def seed(s, version, pubkey): |
| dev = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text()) |
| values = dict(AWS_REGION=REGION, CARLOS_POOLS='witness', CARLOS_DEPLOYMENT_BUCKET=BUCKET, |
| CARLOS_HIBERNATE_BUCKET=dev['CARLOS_GROUP_DATA_BUCKET'], CARLOS_HIBERNATE_REGION=REGION, |
| CARLOS_HIBERNATE_PREFIX='instances', CARLOS_REGION_HA='true', CARLOS_GROUP_ADMISSION='1', |
| CARLOS_CHANGE_INDEX='read', CARLOS_HOST_METRICS='cloudwatch', CARLOS_SYSTEM_CHANNEL='stable', |
| CARLOS_ALERT_SNS_TOPIC_ARN=f'arn:aws:sns:{REGION}:{ACCOUNT}:' + s['role'], |
| - CARLOS_RELEASE_PUBKEY=base64.b64encode(secrets.token_bytes(32)).decode(), |
| + CARLOS_RELEASE_PUBKEY=pubkey, |
| CARLOS_SECRETS_KEY=base64.b64encode(secrets.token_bytes(32)).decode(), |
| CARLOS_HA_FIXED_BOX_IDENTITIES='{}', CARLOS_SWAP='0') |
| require(len(values) == 16, 'env seed count') |
| values.update({'boot/bootstrap-object': json.dumps(dict(key=s['key'], version=version, known_readers=[], |
| - deployment_aws_region=REGION, floor='required')), |
| + deployment_aws_region=REGION, floor='absent-expected')), |
| 'boot/bootstrap-sha256': BOOT_SHA, 'boot/ingress': '["54.77.110.223","18.203.21.74"]', |
| 'boot/CARLOS_TERMINATION_QUEUE_URL': dev['CARLOS_TERMINATION_QUEUE_URL']}) |
| return {s['prefix'] + '/' + k: v for k, v in values.items()} |
| |
| |
| COLLECTOR = r'''#!/usr/bin/python3 |
| -import hashlib,io,json,os,pathlib,shlex,subprocess,tarfile,time,urllib.request |
| +import hashlib,io,json,os,pathlib,re,shlex,stat,subprocess,tarfile,time,urllib.request |
| os.umask(0o077) |
| print('WITNESS collector-start', flush=True) |
| -root=pathlib.Path('/var/lib/carlos-witness-@RUN@');root.mkdir(mode=0o700) |
| +root=pathlib.Path('/var/lib/carlos-witness-@RUN@');root.mkdir(mode=0o700,exist_ok=True) |
| redactions=[] |
| host=pathlib.Path('/etc/carlos/host.env') |
| if host.exists(): |
| @@ -211,29 +245,47 @@ def command(args): |
| p=subprocess.run(args,capture_output=True,text=True,timeout=20) |
| return dict(argv=args,rc=p.returncode,out=redact(p.stdout+p.stderr)) |
| except Exception as e:return dict(argv=args,rc=255,out=str(e)) |
| +deadline=time.monotonic()+120 |
| +while time.monotonic()<deadline: |
| + journal=command(['journalctl','-b','-u','carlos-edge','--no-pager']) |
| + if re.search(r'agent: edges file pass failed[^\n]*AccessDenied',journal['out']):break |
| + if not host.exists():break |
| + time.sleep(2) |
| +(root/'observer-stop').touch() |
| +for attempt in range(30): |
| + if (root/'observer-done').exists():break |
| + time.sleep(0.1) |
| e=dict(commands={},files={},mounts={},time=time.time()) |
| +try:e['staging_observer']=json.loads((root/'observer.json').read_text()) |
| +except (OSError,ValueError) as ex:e['observer_error']=str(ex) |
| + |
| for path in @MOUNTS@: |
| p=pathlib.Path(path) |
| probe=p |
| while not probe.exists():probe=probe.parent |
| e['mounts'][path]=dict(probe=str(probe),flags=os.statvfs(probe).f_flag, |
| - noexec=bool(os.statvfs(probe).f_flag & os.ST_NOEXEC), |
| + noexec=bool(os.statvfs(probe).f_flag & os.ST_NOEXEC),dev=probe.stat().st_dev,realpath=str(probe.resolve()), |
| findmnt=command(['findmnt','-T',str(probe),'-o','TARGET,SOURCE,FSTYPE,OPTIONS'])) |
| for name,args in { |
| 'cloud-status':['cloud-init','status','--long'], |
| - 'nft':['nft','list','ruleset'], 'nft-persist':['cat','/etc/nftables.conf'], |
| + 'nft':['nft','list','ruleset'], 'nft-json':['nft','-j','-n','list','ruleset'], 'nft-persist':['cat','/etc/nftables.conf'], |
| 'sysctl':['sysctl','net.ipv4.conf.all.arp_ignore','net.ipv4.conf.default.arp_ignore','net.ipv4.conf.all.arp_announce','net.ipv4.conf.default.arp_announce'], |
| 'apparmor':['aa-status'], 'lsm':['cat','/sys/kernel/security/lsm'], |
| 'mac-denials':['journalctl','-k','-b','--no-pager','--grep','apparmor="DENIED"|avc:.*denied'], |
| 'packages':['dpkg-query','-W','python3','coreutils','passwd','libc-bin','nftables','procps','chrony','awscli','systemd','cloud-init','apparmor','needrestart','selinux-basics'], |
| 'user':['getent','passwd','carlos'], 'group':['getent','group','carlos'], |
| - 'tools':['/bin/sh','-c','command -v python3 timeout useradd getent install nft sysctl chronyc aws systemctl; python3 --version; aws --version; systemctl --version'], |
| + 'tools':['/bin/sh','-c','for t in python3 timeout useradd getent install nft sysctl chronyc aws systemctl; do command -v "$t" || exit 1; done; python3 --version; aws --version; systemctl --version'], |
| 'chrony':['chronyc','-n','sources'], |
| 'timesyncd':['systemctl','is-active','systemd-timesyncd'], |
| 'directories':['ls','-ld','/etc/carlos','/var/lib/carlos-group-boot','/opt/carlos','/data'], |
| 'listing':['ls','-la','/etc/carlos','/var/lib/carlos-group-boot','/opt/carlos'], |
| 'kernel':['uname','-a'], |
| - 'link':['ip','-d','link','show'], |
| + 'link':['ip','-j','-d','link','show'], |
| + 'addresses':['ip','-j','-4','addr','show'], |
| + 'groups':['id','carlos'], |
| + 'bootstrap-tools':['/bin/sh','-c','for t in groupadd chown chmod systemd-tmpfiles usermod; do command -v "$t" || exit 1; done'], |
| + 'apt-masks':['systemctl','is-enabled','apt-daily.timer','apt-daily-upgrade.timer','apt-daily.service','apt-daily-upgrade.service','unattended-upgrades.service'], |
| + |
| 'nft-check':['nft','-c','-f','/etc/nftables.conf'], |
| 'mount-units':['systemctl','is-active','data-instances.mount','run-carlos-instances.mount','run-carlos-logs.mount'], |
| 'selinux':['ls','-ld','/sys/fs/selinux'], |
| @@ -243,24 +295,31 @@ for name,args in { |
| for unit in @UNITS@: |
| for op,args in [('status',['systemctl','status',unit,'--no-pager']), |
| ('journal',['journalctl','-b','-u',unit,'--no-pager','-o','short-monotonic']), |
| - ('show',['systemctl','show',unit,'-p','Restart','-p','ActiveState','-p','ExecMainStartTimestampMonotonic','-p','ExecMainStatus','-p','Result','-p','ExecStartPre','-p','RestrictAddressFamilies','-p','ReadWritePaths'])]: |
| + ('show',['systemctl','show',unit,'-p','Restart','-p','ActiveState','-p','ExecMainStartTimestampMonotonic','-p','ExecMainStatus','-p','Result','-p','ExecStartPre','-p','RestrictAddressFamilies','-p','ReadWritePaths','-p','User','-p','Group','-p','NoNewPrivileges','-p','CapabilityBoundingSet','-p','AmbientCapabilities','-p','ProtectSystem','-p','ProtectHome','-p','PrivateTmp','-p','PrivateDevices','-p','ProtectKernelTunables','-p','ProtectKernelModules','-p','MemoryDenyWriteExecute','-p','MainPID'])]: |
| e['commands'][unit+'-'+op]=command(args) |
| for path in ['/etc/carlos/group.json','/etc/carlos/group-ingress.json','/etc/carlos/region-config.json', |
| '/etc/carlos/group-identity.json','/etc/carlos/host.env','/etc/nftables.conf','/opt/carlos/carlos', |
| '/var/lib/carlos-group-boot','/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf']: |
| p=pathlib.Path(path) |
| try: |
| - st=p.stat();info=dict(uid=st.st_uid,gid=st.st_gid,mode=oct(st.st_mode & 0o7777),mtime=st.st_mtime_ns) |
| + st=p.lstat();info=dict(uid=st.st_uid,gid=st.st_gid,mode=oct(st.st_mode & 0o7777),mtime=st.st_mtime_ns,nlink=st.st_nlink,regular=stat.S_ISREG(st.st_mode)) |
| if p.is_file() and path.endswith('.json'):info['keys']=sorted(json.loads(p.read_text())) |
| if path.endswith('/group.json'):info['box_iid']=json.loads(p.read_text())['instance_id'] |
| + if path.endswith('/group-ingress.json'):info['ingress']=json.loads(p.read_text()) |
| if path.endswith('/host.env'):info['keys']=[x.split('=',1)[0] for x in p.read_text().splitlines() if '=' in x] |
| e['files'][path]=info |
| except FileNotFoundError:e['files'][path]=None |
| + except (OSError,ValueError,KeyError) as ex:e['files'][path]=dict(error=redact(str(ex))) |
| try: |
| opener=urllib.request.build_opener(urllib.request.ProxyHandler({})) |
| t=opener.open(urllib.request.Request('http://169.254.169.254/latest/api/token',method='PUT',headers={'X-aws-ec2-metadata-token-ttl-seconds':'60'}),timeout=2).read().decode() |
| e['identity']=json.loads(opener.open(urllib.request.Request('http://169.254.169.254/latest/dynamic/instance-identity/document',headers={'X-aws-ec2-metadata-token':t}),timeout=2).read()) |
| except Exception as ex:e['identity_error']=str(ex) |
| +try: |
| + pid=int(e['commands']['carlos-edge-show']['out'].split('MainPID=')[1].splitlines()[0]) |
| + e['edge_process_status']=pathlib.Path('/proc/'+str(pid)+'/status').read_text() if pid>0 else '' |
| + e['edge_process_mounts']=pathlib.Path('/proc/'+str(pid)+'/mountinfo').read_text() if pid>0 else '' |
| +except (OSError,ValueError,IndexError) as ex:e['process_error']=str(ex) |
| for name,path in [('cloud-init-output.log','/var/log/cloud-init-output.log'),('cloud-init.log','/var/log/cloud-init.log')]: |
| try:(root/name).write_text(redact(pathlib.Path(path).read_text(errors='replace'))) |
| except OSError as ex:(root/name).write_text(str(ex)) |
| @@ -275,22 +334,79 @@ print('WITNESS collector-done',flush=True) |
| ''' |
| |
| |
| +OBSERVER = r'''#cloud-boothook |
| +#!/usr/bin/python3 |
| +import base64,json,os,pathlib,subprocess,time |
| +os.umask(0o077) |
| +root=pathlib.Path('/var/lib/carlos-witness-@RUN@') |
| +root.mkdir(mode=0o700,exist_ok=True) |
| +if os.fork():raise SystemExit(0) |
| +os.setsid() |
| +fd=os.open('/dev/null',os.O_RDWR) |
| +for n in (0,1,2):os.dup2(fd,n) |
| +if fd>2:os.close(fd) |
| +work=pathlib.Path('/var/lib/carlos-group-boot') |
| +def sample(path): |
| + st=path.stat();flags=os.statvfs(path).f_flag |
| + return dict(path=str(path),dev=st.st_dev,ino=st.st_ino,uid=st.st_uid,gid=st.st_gid, |
| + mode=oct(st.st_mode & 0o7777),noexec=bool(flags & os.ST_NOEXEC),flags=flags, |
| + time_ns=time.time_ns(),mountinfo=pathlib.Path('/proc/self/mountinfo').read_text()) |
| +e=dict(parent_before=sample(work.parent),samples=[]) |
| +last=None |
| +deadline=time.monotonic()+1000 |
| +while time.monotonic()<deadline: |
| + try: |
| + s=sample(work) |
| + state=(s['dev'],s['ino'],s['flags'],s['mode']) |
| + if state!=last: |
| + e['samples'].append(s);last=state |
| + except FileNotFoundError: |
| + if last is not None:e['removed_ns']=time.time_ns();last=None |
| + except OSError as ex:e['error']=str(ex) |
| + if (root/'observer-stop').exists():break |
| + time.sleep(0.05) |
| +e['parent_after']=sample(work.parent) |
| +e['finished_ns']=time.time_ns() |
| +(root/'observer.json').write_text(json.dumps(e)) |
| +(root/'observer-done').touch() |
| +for n in range(60): |
| + try: |
| + p=subprocess.run(['cloud-init','status','--long'],capture_output=True,text=True,timeout=5) |
| + if 'status: running' not in p.stdout: |
| + status=dict(rc=p.returncode,out=p.stdout+p.stderr) |
| + with open('/dev/console','w') as console: |
| + console.write('WITNESS final-cloud-init '+base64.b64encode(json.dumps(status).encode()).decode()+'\n') |
| + break |
| + except Exception:pass |
| + time.sleep(2) |
| +''' |
| + |
| + |
| +def observer(s): |
| + return OBSERVER.replace('@RUN@', s['run']).encode() |
| + |
| + |
| def collector(s): |
| return COLLECTOR.replace('@RUN@', s['run']).replace('@MOUNTS@', repr(MOUNTS)).replace('@UNITS@', repr(UNITS)).encode() |
| |
| |
| -def user_data(script, collection): |
| +def user_data(script, collection, observation=None): |
| boundary = 'p3b1-f4-' + hashlib.sha256(script + collection).hexdigest()[:24] |
| body = f'MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary="{boundary}"\n\n'.encode() |
| - for name, payload in [('001-boot', script), ('002-collect', collection)]: |
| - body += (f'--{boundary}\nContent-Type: text/x-shellscript; charset="utf-8"\n' |
| + payloads = [('001-boot', 'text/x-shellscript', script), ('002-collect', 'text/x-shellscript', collection)] |
| + if observation is not None: |
| + payloads.append(('000-observe', 'text/cloud-boothook', observation)) |
| + for name, kind, payload in payloads: |
| + body += (f'--{boundary}\nContent-Type: {kind}; charset="utf-8"\n' |
| f'Content-Transfer-Encoding: 8bit\nContent-Disposition: attachment; filename="{name}"\n\n').encode() |
| body += payload + b'\n' |
| body += f'--{boundary}--\n'.encode() |
| parsed = BytesParser(policy=email.policy.default).parsebytes(body) |
| parts = list(parsed.iter_parts()) |
| - require(len(parts) == 2 and parts[0].get_payload(decode=True) == script, 'part 1 byte integrity') |
| + require(len(parts) == len(payloads) and parts[0].get_payload(decode=True) == script, 'part 1 byte integrity') |
| require(parts[1].get_payload(decode=True) == collection, 'collector byte integrity') |
| + if observation is not None: |
| + require(parts[2].get_payload(decode=True) == observation, 'observer byte integrity') |
| encoded = base64.b64encode(gzip.compress(body, mtime=0)).decode() |
| require(len(encoded) <= 16384, f'MIME encoded size {len(encoded)} exceeds 16384') |
| return encoded |
| @@ -340,21 +456,271 @@ def launch_input(lt, encoded, s): |
| return result |
| |
| |
| +class AWSError(RuntimeError): |
| + def __init__(self, service, operation, code, detail=''): |
| + super().__init__(f'{service} {operation}: {code} {detail}') |
| + self.code = code |
| + |
| + |
| class AWS: |
| - def __init__(self, dry=False): self.dry = dry |
| - def __call__(self, service, operation, **params): |
| - args = ['aws','--profile','kass','--region',REGION,'--no-cli-pager',service,operation, |
| - '--cli-input-json',json.dumps(params),'--output','json'] |
| + dry = False |
| + |
| + def __call__(self, service, operation, _file=None, _timeout=90, **params): |
| + args = ['aws', '--profile', 'kass', '--region', REGION, '--no-cli-pager', service, operation] |
| + if service == 's3api' and operation == 'get-object': |
| + # The CLI's streaming outfile customization requires these flags |
| + # even when --cli-input-json supplies the same fields. |
| + require(_file is not None and set(params) <= {'Bucket', 'Key', 'VersionId'}, 'unsupported get-object arguments') |
| + args += ['--bucket', params['Bucket'], '--key', params['Key']] |
| + if 'VersionId' in params: |
| + args += ['--version-id', params['VersionId']] |
| + args += ['--output', 'json', str(_file)] |
| + else: |
| + require(_file is None, 'unexpected outfile') |
| + args += ['--cli-input-json', json.dumps(params), '--output', 'json'] |
| safe = dict(params) |
| - if operation == 'put-parameter': safe['Value'] = '[REDACTED]' |
| - if operation == 'run-instances': safe['UserData'] = f'[base64 gzip MIME {len(params["UserData"])} bytes]' |
| - print('AWS',service,operation,json.dumps(safe,sort_keys=True),flush=True) |
| - if self.dry: return {} |
| - p = subprocess.run(args, capture_output=True, text=True, timeout=90) |
| - if p.returncode: raise RuntimeError(f'{service} {operation}: {p.stderr[:1500]}') |
| + if operation == 'put-parameter': |
| + safe['Value'] = '[REDACTED]' |
| + if operation == 'run-instances': |
| + safe['UserData'] = f'[base64 gzip MIME {len(params["UserData"])} bytes]' |
| + print('AWS', service, operation, json.dumps(safe, sort_keys=True), flush=True) |
| + env = dict(os.environ, AWS_MAX_ATTEMPTS='1', AWS_RETRY_MODE='standard', AWS_PAGER='') |
| + # No automatic mutation retries: an ambiguous response belongs to the |
| + # journal and cleanup, not a second creation attempt. |
| + p = subprocess.run(args, capture_output=True, text=True, timeout=_timeout, env=env) |
| + if p.returncode: |
| + match = re.search(r'An error occurred \(([^)]+)\)', p.stderr) |
| + raise AWSError(service, operation, match[1] if match else 'CLIError', p.stderr[:1500]) |
| return json.loads(p.stdout or '{}') |
| |
| |
| +def absent(aws, service, operation, codes, **params): |
| + try: |
| + aws(service, operation, **params) |
| + except AWSError as ex: |
| + if ex.code in codes: |
| + return True |
| + raise |
| + return False |
| + |
| + |
| +def atomic_json(path, value): |
| + path = Path(path) |
| + tmp = path.with_name(path.name + '.new') |
| + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) |
| + try: |
| + with os.fdopen(fd, 'w') as f: |
| + json.dump(value, f, indent=2, sort_keys=True) |
| + f.write('\n') |
| + f.flush() |
| + os.fsync(f.fileno()) |
| + os.replace(tmp, path) |
| + fd = os.open(path.parent, os.O_DIRECTORY) |
| + try: |
| + os.fsync(fd) |
| + finally: |
| + os.close(fd) |
| + finally: |
| + tmp.unlink(missing_ok=True) |
| + |
| + |
| +@contextmanager |
| +def exclusive(path): |
| + fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) |
| + try: |
| + try: |
| + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| + except BlockingIOError: |
| + raise ValueError('another witness/cleanup owns the ledger lock') |
| + yield |
| + finally: |
| + os.close(fd) |
| + |
| + |
| +def reserve_budget(path, run, owner): |
| + # Caller holds the process-wide scratch ledger lock throughout the run. |
| + data = json.loads(path.read_text()) if path.exists() else {'schema': 1, 'runs': []} |
| + require(data.get('schema') == 1 and isinstance(data.get('runs'), list), 'invalid budget ledger') |
| + require(len(data['runs']) < 2, 'two-run witness budget exhausted') |
| + require(not any(r['run'] == run for r in data['runs']), 'run id already spent') |
| + data['runs'].append(dict(run=run, owner=owner, reserved_at=datetime.now(timezone.utc).isoformat())) |
| + atomic_json(path, data) |
| + |
| + |
| +class Journal: |
| + def __init__(self, path, s=None, dry=False): |
| + self.path = Path(path) |
| + if s is None: |
| + self.data = json.loads(self.path.read_text()) |
| + require(self.data.get('schema') == 1, 'invalid ownership journal') |
| + require(self.data['scope'] == scope(self.data['scope']['run']), 'journal scope mismatch') |
| + require(self.data['account'] == ACCOUNT and self.data['region'] == REGION, 'journal account/region mismatch') |
| + require(self.data['dry'] == dry, 'simulation/live journal mismatch') |
| + else: |
| + require(not self.path.exists(), 'run journal exists; use cleanup-only') |
| + self.data = dict(schema=1, scope=s, account=ACCOUNT, region=REGION, dry=dry, |
| + owner=uuid.uuid4().hex, resources=[], checks=[], status='preflight') |
| + self.save() |
| + |
| + def save(self): |
| + atomic_json(self.path, self.data) |
| + |
| + def intent(self, kind, name): |
| + require(not any(r['kind'] == kind and r['name'] == name for r in self.data['resources']), 'duplicate create intent') |
| + row = dict(kind=kind, name=name, state='pending', ids={}) |
| + self.data['resources'].append(row) |
| + self.save() # fsync BEFORE the API mutation, including when its reply is lost |
| + return row |
| + |
| + def create(self, aws, row, service, operation, **params): |
| + try: |
| + return aws(service, operation, **params) |
| + except AWSError as ex: |
| + # These responses reject the request before creating a resource. |
| + # Timeouts, transport failures and service errors stay pending. |
| + if ex.code in {'AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation', |
| + 'EntityAlreadyExists', 'ParameterAlreadyExists', 'InvalidParameterValue', |
| + 'InvalidParameterCombination', 'ValidationError', 'InvalidAMIID.NotFound', |
| + 'InsufficientInstanceCapacity', 'InstanceLimitExceeded'}: |
| + row.update(state='rejected', error=str(ex)) |
| + self.save() |
| + raise |
| + |
| + def made(self, row, **ids): |
| + row.update(state='created', ids=ids) |
| + self.save() |
| + |
| + def gone(self, row): |
| + row['state'] = 'gone' |
| + self.save() |
| + |
| + def tags(self): |
| + return [dict(Key=k, Value=v) for k, v in dict(purpose=PURPOSE, |
| + witness_run=self.data['scope']['run'], witness_owner=self.data['owner']).items()] |
| + |
| + |
| +def owned(tags, journal): |
| + actual = {x['Key']: x['Value'] for x in tags} |
| + return all(actual.get(t['Key']) == t['Value'] for t in journal.tags()) |
| + |
| + |
| +def box_ref(iid): |
| + return 'g-' + hashlib.sha256(f'carlos-box-ref-v1|{ACCOUNT}|{iid}'.encode()).hexdigest()[:20] |
| + |
| + |
| +def verify_pointer(path, pubkey): |
| + result = subprocess.run(['nice', '-n', '10', 'go', 'run', './scripts/witness-pointer', str(path), str(pubkey)], |
| + cwd=ROOT, capture_output=True, text=True, timeout=180) |
| + require(result.returncode == 0, 'release pointer signature: ' + result.stderr[-2000:]) |
| + pointer = json.loads(result.stdout) |
| + artifact_key(pointer) |
| + return pointer |
| + |
| + |
| + |
| +def properties(e, unit): |
| + return dict(line.split('=', 1) for line in e.get('commands', {}).get(unit + '-show', {}).get('out', '').splitlines() if '=' in line) |
| + |
| + |
| +def decoded_command(e, name): |
| + command = e.get('commands', {}).get(name, {}) |
| + if command.get('rc') != 0: |
| + return None |
| + try: |
| + return json.loads(command['out']) |
| + except (ValueError, KeyError): |
| + return None |
| + |
| + |
| +def staging_mount_ok(e): |
| + observation = e.get('staging_observer', {}) |
| + samples = observation.get('samples', []) |
| + before, after = observation.get('parent_before', {}), observation.get('parent_after', {}) |
| + removed = observation.get('removed_ns', 0) |
| + ingress = (e.get('files', {}).get('/etc/carlos/group-ingress.json') or {}).get('mtime', 0) |
| + return bool(samples and before.get('dev') == after.get('dev') and not before.get('noexec', True) |
| + and not after.get('noexec', True) and not observation.get('error') |
| + and all(s.get('dev') == before.get('dev') and not s.get('noexec', True) |
| + and s.get('uid') == s.get('gid') == 0 and s.get('mode') == '0o700' |
| + and s.get('mountinfo') for s in samples) |
| + and samples[0]['time_ns'] < ingress < removed <= observation.get('finished_ns', 0)) |
| + |
| + |
| +def uid_binding_ok(e): |
| + cmds = e.get('commands', {}) |
| + try: |
| + passwd = cmds['user']['out'].strip().split(':') |
| + uid, gid = int(passwd[2]), int(passwd[3]) |
| + group = cmds['group']['out'].strip().split(':') |
| + require(int(group[2]) == gid, 'group gid') |
| + require(re.search(r'\buid=' + str(uid) + r'\(carlos\)', cmds['groups']['out']) |
| + and re.search(r'\bgid=' + str(gid) + r'\(carlos\)', cmds['groups']['out']), 'id membership') |
| + rules = decoded_command(e, 'nft-json')['nftables'] |
| + protected = set() |
| + for item in rules: |
| + rule = item.get('rule', {}) |
| + if rule.get('table') != 'carlos_group_imds' or rule.get('chain') != 'output': |
| + continue |
| + expr = rule.get('expr', []) |
| + uid_match = any(x.get('match', {}).get('left') == {'meta': {'key': 'skuid'}} |
| + and x['match'].get('op') == '!=' |
| + and set(x['match'].get('right', {}).get('set', [])) == {0, uid} for x in expr) |
| + if uid_match and any('reject' in x for x in expr): |
| + for x in expr: |
| + match = x.get('match', {}) |
| + if match.get('left', {}).get('payload', {}).get('field') == 'daddr': |
| + protected.add(match.get('right')) |
| + return uid > 0 and protected == {'169.254.169.254', 'fd00:ec2::254'} |
| + except (KeyError, TypeError, ValueError, IndexError, AttributeError): |
| + return False |
| + |
| + |
| +def p_assertions(e, w4): |
| + cmds = e.get('commands', {}) |
| + out = lambda k: cmds.get(k, {}).get('out', '') |
| + readback = e.get('launch_readback', {}).get('instance', {}) |
| + meta = readback.get('MetadataOptions', {}) |
| + mounts = e.get('mounts', {}) |
| + links, addresses = decoded_command(e, 'link'), decoded_command(e, 'addresses') |
| + dummy = [x for x in links or [] if x.get('ifname') == 'carlos-hairpin'] |
| + eips = {'54.77.110.223', '18.203.21.74'} |
| + assigned = {a.get('local') for link in addresses or [] for a in link.get('addr_info', [])} |
| + record_paths = ['/etc/carlos/group-identity.json', '/etc/carlos/region-config.json', |
| + '/etc/carlos/group.json', '/etc/carlos/group-ingress.json'] |
| + records = [(e.get('files', {}).get(path) or {}) for path in record_paths] |
| + edge, control = properties(e, 'carlos-edge'), properties(e, 'carlos-instance-control') |
| + security = edge.get('User') == edge.get('Group') == 'carlos' and edge.get('NoNewPrivileges') == 'yes' |
| + security = security and edge.get('CapabilityBoundingSet') == 'cap_net_bind_service' and edge.get('AmbientCapabilities') == 'cap_net_bind_service' |
| + for props in (edge, control): |
| + security = security and props.get('ProtectSystem') == 'strict' and props.get('ProtectHome') == 'yes' |
| + security = security and all(props.get(k) == 'yes' for k in ('PrivateTmp', 'PrivateDevices', 'ProtectKernelTunables', 'ProtectKernelModules', 'MemoryDenyWriteExecute')) |
| + security = security and control.get('User', '') in ('', 'root') and control.get('Group', '') in ('', 'root') |
| + security = security and 'AF_NETLINK' in control.get('RestrictAddressFamilies', '') and '/run/carlos-hairpin' in control.get('ReadWritePaths', '') |
| + status = e.get('edge_process_status', '') |
| + security = security and bool(re.search(r'^NoNewPrivs:\s+1$', status, re.M)) and bool(re.search(r'^CapEff:\s+0*400$', status, re.M)) |
| + for path in ('/data/instances', '/run/carlos/instances', '/run/carlos/logs'): |
| + mount = mounts.get(path, {}) |
| + output = mount.get('findmnt', {}).get('out', '') |
| + security = security and mount.get('probe') == path and all(x in output for x in ('nosuid', 'nodev', 'nosymfollow')) |
| + alias_ok = all(path in mounts and mounts[path].get('probe') == path and mounts[path].get('findmnt', {}).get('rc') == 0 |
| + and mounts[path].get('realpath') == target for path, target in [('/var/run', '/run'), ('/var/lock', '/run/lock')]) |
| + return [ |
| + ('P1 live metadata options', readback.get('ImageId') == AMI and meta.get('HttpTokens') == 'required' and meta.get('HttpPutResponseHopLimit') == 1, 'operator describe-instances readback'), |
| + ('P2 alias mount inventory', alias_ok, '/var/run -> /run; /var/lock -> /run/lock; findmnt + realpath'), |
| + ('P3 before/after staging mount', staging_mount_ok(e), 'early boothook observer; actual leaf before ingress, removal and parent after'), |
| + ('P4 system group and IMDS uid binding', uid_binding_ok(e), 'getent + id + parsed nft JSON, exact {0,carlos uid} for IPv4 and IPv6'), |
| + ('P5 bootstrap tools', cmds.get('bootstrap-tools', {}).get('rc') == 0 and len(out('bootstrap-tools').splitlines()) == 5, out('bootstrap-tools')), |
| + ('P6 dormant dummy and no ingress EIP', bool(len(dummy) == 1 and dummy[0].get('linkinfo', {}).get('info_kind') == 'dummy' |
| + and addresses is not None and addresses and not assigned.intersection(eips) |
| + and all(not x.get('addr_info') for x in addresses if x.get('ifname') == 'carlos-hairpin')), 'ip -j link and address inventory; no EIP on any interface'), |
| + ('P7 unattended upgrades masked', out('apt-masks').splitlines() == ['masked'] * 5, out('apt-masks')), |
| + ('P8 drop-in-only edge gate', w4, 'inferred from W4: successful hairpin installation passed the pre-base-unit edge gate'), |
| + ('P9 immutable record metadata', all(r.get('uid') == r.get('gid') == 0 and r.get('mode') == '0o644' |
| + and r.get('nlink') == 1 and r.get('regular') is True for r in records), 'lstat uid/gid/mode/nlink/type for all four records'), |
| + ('P10 installed unit security', bool(security), 'effective edge/control settings, live edge /proc privileges, bind mount flags; no tenant execution probe'), |
| + ] |
| + |
| + |
| def assertions(e): |
| files=e.get('files',{}); cmds=e.get('commands',{}) |
| out=lambda k:cmds.get(k,{}).get('out','') |
| @@ -363,8 +729,8 @@ def assertions(e): |
| ordered=['/etc/carlos/group-identity.json','/etc/carlos/region-config.json','/etc/carlos/group.json', |
| '/etc/carlos/group-ingress.json','/etc/nftables.conf','/etc/carlos/host.env'] |
| times=[files.get(k,{}).get('mtime',0) if files.get(k) else 0 for k in ordered] |
| - return [ |
| - ('W1 exec mount', not e.get('mounts',{}).get('/var/lib/carlos-group-boot',{'noexec':True})['noexec'], 'findmnt + statvfs'), |
| + rows = [ |
| + ('W1 exec mount', staging_mount_ok(e), 'observer actual leaf + parent before/after; template hash checks before all three execs'), |
| ('W2 identity verified before ingress', exists(ordered[3]) and all(times[:4]) and times[:4]==sorted(times[:4]), 'exclusive writes after identity verifier'), |
| ('W3 immutable records', all(exists(k) for k in ordered[:4]), 'group identity/region/marker/ingress'), |
| ('W4 hairpin installed', rc('nft')==0 and all(x in out('nft') for x in ('carlos_group_imds','carlos_hairpin')), out('nft')[:200]), |
| @@ -376,7 +742,7 @@ def assertions(e): |
| ('W10 work dir removed', '/var/lib/carlos-group-boot' in files and files['/var/lib/carlos-group-boot'] is None and exists('/etc/carlos/host.env'), 'final cleanup after start'), |
| ('W11 sysctl', all(f'net.ipv4.conf.{axis}.arp_{name} = {value}' in out('sysctl') for axis in ('all','default') for name,value in [('ignore',1),('announce',2)]), out('sysctl')), |
| ('W12 AMI tools', rc('tools')==0 and 'Python 3.13' in out('tools') and 'aws-cli/2.' in out('tools'), out('tools')), |
| - ('W13 MAC policy', rc('mac-denials') in (0,1) and not re.search(r'apparmor="DENIED"|avc:.*denied',out('mac-denials')), out('mac-denials')), |
| + ('W13 MAC policy', rc('apparmor') == 0 and 'apparmor module is loaded' in out('apparmor') and rc('lsm') == 0 and 'apparmor' in out('lsm') and rc('mac-denials') in (0,1) and not re.search(r'apparmor="DENIED"|avc:.*denied',out('mac-denials')), out('mac-denials')), |
| ('W14 installed binary', exists('/opt/carlos/carlos'), 'reset ExecStart path'), |
| ('W15 clock', rc('chrony')==0 and bool(re.search(r'\^[*+]\s+169\.254\.169\.123',out('chrony'))), out('chrony')), |
| ('W16 write order', all(times) and times==sorted(times), 'identity -> region -> marker -> ingress -> nft persist -> host.env'), |
| @@ -385,153 +751,694 @@ def assertions(e): |
| ('W19 mount units', rc('mount-units')==0 and out('mount-units').splitlines()==['active']*3, out('mount-units')), |
| ('W20 reset unit', 'Result=success' in out('carlos-hairpin-reset-show') and bool(re.search(r'ExecMainStartTimestampMonotonic=[1-9][0-9]*',out('carlos-hairpin-reset-show'))),out('carlos-hairpin-reset-show')), |
| ('W21 persisted nft syntax', rc('nft-check')==0, out('nft-check')), |
| - ('W22 SELinux absent', rc('selinux')==2 and 'No such file' in out('selinux') and 'selinux' not in out('lsm'),out('selinux')), |
| + ('W22 SELinux absent', rc('selinux')==2 and 'No such file' in out('selinux') and rc('lsm') == 0 and 'selinux' not in out('lsm'),out('selinux')), |
| ('W23 systemd features', 'systemd 257' in out('tools') and '/usr/bin/systemctl' in out('carlos-edge-show') and 'AF_NETLINK' in out('carlos-instance-control-show') and '/run/carlos-hairpin' in out('carlos-instance-control-show'),out('carlos-instance-control-show')), |
| ] |
| |
| - |
| -def report(path, rows, note=''): |
| - esc=lambda v:str(v).replace('|','\\|').replace('\n',' ')[:700] |
| - path.write_text('# P3b-1 F4 witness evidence\n\n'+note+'\n\n| Assertion | Status | Evidence |\n|---|---|---|\n'+ |
| - ''.join(f'| {esc(n)} | {"PASS" if ok else "FAIL"} | {esc(detail)} |\n' for n,ok,detail in rows)) |
| + return rows + p_assertions(e, rows[3][1]) |
| |
| |
| -def baseline(aws, iid=None): |
| - observed={} |
| +def snapshot(aws): |
| + observed, errors = {}, [] |
| + # A failed TG check must not suppress the other TG or edges reads. |
| for tg in TGS: |
| - rows=aws('elbv2','describe-target-health',TargetGroupArn=tg).get('TargetHealthDescriptions',[]) |
| - actual={r['Target']['Id'] for r in rows} |
| - if not aws.dry: require(actual==FIXED and iid not in actual, 'fixed target membership changed') |
| - observed[tg]=sorted(actual) |
| - # Prefix listing is controller-only. Instance policy cannot list or write it. |
| - objects=aws('s3api','list-objects-v2',Bucket=BUCKET,Prefix='control/edges/').get('Contents',[]) |
| - observed['edges']=sorted(x['Key'] for x in objects) |
| - require(not any(x.rsplit('/',1)[-1].startswith('g-') for x in observed['edges']), 'unexpected preexisting group edges') |
| + try: |
| + rows = aws('elbv2', 'describe-target-health', TargetGroupArn=tg)['TargetHealthDescriptions'] |
| + observed[tg] = sorted((r['Target'] for r in rows), key=lambda r: json.dumps(r, sort_keys=True)) |
| + except Exception as ex: |
| + errors.append(str(ex)) |
| + try: |
| + objects = aws('s3api', 'list-objects-v2', Bucket=BUCKET, Prefix=EDGES_PREFIX) |
| + require(not objects.get('IsTruncated'), 'incomplete edges listing') |
| + observed['edges'] = sorted(x['Key'] for x in objects.get('Contents', [])) |
| + except Exception as ex: |
| + errors.append(str(ex)) |
| + try: |
| + versions = aws('s3api', 'list-object-versions', Bucket=BUCKET, Prefix=EDGES_PREFIX) |
| + require(not versions.get('IsTruncated'), 'incomplete edges version listing') |
| + observed['edge_versions'] = sorted([x['Key'], x['VersionId']] for x in |
| + versions.get('Versions', []) + versions.get('DeleteMarkers', [])) |
| + except Exception as ex: |
| + errors.append(str(ex)) |
| + observed['errors'] = errors |
| return observed |
| |
| |
| -def cleanup(aws, s): |
| - leaked=[] |
| - def attempt(label, service, operation, **args): |
| - try:return aws(service,operation,**args) |
| +def check_snapshot(before, after, iids=()): |
| + errors = list(before.get('errors', [])) + list(after.get('errors', [])) |
| + for tg in TGS: |
| + ids = {r['Id'] for r in after.get(tg, [])} |
| + if ids != FIXED or ids.intersection(iids) or before.get(tg) != after.get(tg): |
| + errors.append('target membership changed: ' + tg) |
| + if before.get('edges') != after.get('edges'): |
| + errors.append('control/edges/ key set changed') |
| + # New versions of existing fixed-box objects are normal. Any version of a |
| + # newly named object, even one already deleted, is a failed witness window. |
| + new = {tuple(x) for x in after.get('edge_versions', [])} - {tuple(x) for x in before.get('edge_versions', [])} |
| + if any(key not in before.get('edges', []) for key, version in new): |
| + errors.append('new edges object during window (including deleted objects)') |
| + for iid in iids: |
| + key = EDGES_PREFIX + box_ref(iid) + '.json' |
| + if key in after.get('edges', []) or any(k == key for k, v in after.get('edge_versions', [])): |
| + errors.append('witness edges object: ' + key) |
| + return errors |
| + |
| + |
| +def object_versions(aws, key): |
| + result = aws('s3api', 'list-object-versions', Bucket=BUCKET, Prefix=key) |
| + require(not result.get('IsTruncated'), 'incomplete version listing: ' + key) |
| + return [x for x in result.get('Versions', []) if x['Key'] == key], [x for x in result.get('DeleteMarkers', []) if x['Key'] == key] |
| + |
| + |
| +def instances(aws, journal): |
| + filters = [dict(Name='tag:' + t['Key'], Values=[t['Value']]) for t in journal.tags()] |
| + result = aws('ec2', 'describe-instances', Filters=filters) |
| + return [i for r in result.get('Reservations', []) for i in r['Instances']] |
| + |
| + |
| +def collision(aws, journal, kind, name): |
| + if kind == 'role': |
| + require(absent(aws, 'iam', 'get-role', {'NoSuchEntity'}, RoleName=name), 'role collision') |
| + elif kind == 'profile': |
| + require(absent(aws, 'iam', 'get-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name), 'profile collision') |
| + elif kind == 'parameter': |
| + require(absent(aws, 'ssm', 'get-parameter', {'ParameterNotFound'}, Name=name), 'parameter collision: ' + name) |
| + elif kind == 'copy': |
| + versions, markers = object_versions(aws, name) |
| + require(not versions and not markers, 'scratch bootstrap key collision') |
| + require(absent(aws, 's3api', 'head-object', {'404', 'NoSuchKey', 'NotFound'}, Bucket=BUCKET, Key=name), 'scratch bootstrap collision') |
| + elif kind == 'instance': |
| + for tag in ('witness_run', 'Name'): |
| + result = aws('ec2', 'describe-instances', Filters=[dict(Name='tag:' + tag, |
| + Values=[journal.data['scope']['run'] if tag == 'witness_run' else name])]) |
| + require(not any(r.get('Instances') for r in result.get('Reservations', [])), 'instance name/tag collision') |
| + else: |
| + raise ValueError('unknown creation kind: ' + kind) |
| + |
| + |
| +def floor_preflight(aws): |
| + for key in FLOOR_KEYS: |
| + require(absent(aws, 's3api', 'head-object', {'404', 'NoSuchKey', 'NotFound'}, Bucket=BUCKET, Key=key), |
| + 'floor now exists; absent-expected branch changed: ' + key) |
| + print('PREFLIGHT 404', key, FLOOR_LABEL, flush=True) |
| + |
| + |
| +def input_preflight(aws, directory, pubkey_file): |
| + identity = aws('sts', 'get-caller-identity') |
| + require(identity['Account'] == ACCOUNT, 'wrong AWS account') |
| + region = aws('ec2', 'describe-regions', RegionNames=[REGION]) |
| + require([r['RegionName'] for r in region['Regions']] == [REGION], 'wrong AWS region') |
| + image = aws('ec2', 'describe-images', ImageIds=[AMI])['Images'] |
| + require(len(image) == 1 and image[0]['ImageId'] == AMI and image[0]['Architecture'] == 'arm64' |
| + and image[0]['State'] == 'available' and image[0]['RootDeviceType'] == 'ebs' |
| + and image[0]['RootDeviceName'] == '/dev/xvda' and image[0]['Name'] == 'debian-13-arm64-20261103-2651', 'AMI drift') |
| + subnet = aws('ec2', 'describe-subnets', SubnetIds=[SUBNET])['Subnets'] |
| + groups = aws('ec2', 'describe-security-groups', GroupIds=[SG])['SecurityGroups'] |
| + require(len(subnet) == len(groups) == 1, 'network readback count') |
| + subnet, group = subnet[0], groups[0] |
| + require(subnet['SubnetId'] == SUBNET and subnet['State'] == 'available' and subnet['MapPublicIpOnLaunch'] |
| + and subnet['AvailabilityZone'].startswith(REGION) and subnet['VpcId'] == group['VpcId'] |
| + and group['GroupId'] == SG and group['OwnerId'] == ACCOUNT and not group['IpPermissions'], 'subnet/SG drift') |
| + require(aws('s3api', 'get-bucket-location', Bucket=BUCKET)['LocationConstraint'] == REGION, 'bucket region drift') |
| + require(aws('s3api', 'get-bucket-versioning', Bucket=BUCKET).get('Status') == 'Enabled', 'versioned bucket required') |
| + floor_preflight(aws) |
| + pointer_path = directory / 'stable.json' |
| + meta = aws('s3api', 'get-object', Bucket=BUCKET, Key=POINTER_KEY, _file=pointer_path) |
| + pointer = verify_pointer(pointer_path, pubkey_file) |
| + for key, version in [(BOOT_KEY, BOOT_VERSION), (artifact_key(pointer), None)]: |
| + params = dict(Bucket=BUCKET, Key=key) |
| + if version: |
| + params['VersionId'] = version |
| + head = aws('s3api', 'head-object', **params) |
| + require(0 < head['ContentLength'] <= 256 * 1024 * 1024, 'artifact size out of bounds') |
| + if version: |
| + require(head['VersionId'] == version, 'bootstrap source version drift') |
| + kms = aws('kms', 'describe-key', KeyId='alias/aws/ssm')['KeyMetadata'] |
| + require(kms['Arn'].startswith(f'arn:aws:kms:{REGION}:{ACCOUNT}:key/') and kms['Enabled'] |
| + and kms['KeyState'] == 'Enabled', 'SSM KMS key drift') |
| + atomic_json(directory / 'preflight.json', dict(identity=identity, region=region, image=image, |
| + subnet=subnet, security_group=group, pointer=meta, kms=kms, floor=FLOOR_LABEL)) |
| + return pointer, kms['Arn'] |
| + |
| + |
| +def launch_readback(aws, iid, launch): |
| + rows = [i for r in aws('ec2', 'describe-instances', InstanceIds=[iid])['Reservations'] for i in r['Instances']] |
| + require(len(rows) == 1 and rows[0]['InstanceId'] == iid, 'launch readback count') |
| + instance = rows[0] |
| + for key in ('ImageId', 'InstanceType'): |
| + require(instance[key] == launch[key], 'instance launch drift: ' + key) |
| + for key, value in launch['MetadataOptions'].items(): |
| + require(instance['MetadataOptions'][key] == value, 'instance metadata drift: ' + key) |
| + require(instance['SubnetId'] == SUBNET and {g['GroupId'] for g in instance['SecurityGroups']} == {SG} |
| + and instance.get('PublicIpAddress'), 'instance network drift') |
| + profile = launch['IamInstanceProfile']['Name'] |
| + require(instance['IamInstanceProfile']['Arn'] == f'arn:aws:iam::{ACCOUNT}:instance-profile/{profile}', 'instance profile drift') |
| + require(not aws('autoscaling', 'describe-auto-scaling-instances', InstanceIds=[iid])['AutoScalingInstances'], 'witness joined ASG') |
| + expected_monitoring = 'enabled' if launch.get('Monitoring', {}).get('Enabled') else 'disabled' |
| + require(instance['Monitoring']['State'] == expected_monitoring, 'monitoring drift') |
| + attribute = aws('ec2', 'describe-instance-attribute', InstanceId=iid, Attribute='userData') |
| + require(attribute['UserData']['Value'] == launch['UserData'], 'user data readback drift') |
| + mappings = instance['BlockDeviceMappings'] |
| + require(len(mappings) == len(launch['BlockDeviceMappings']), 'block device readback count') |
| + volumes = aws('ec2', 'describe-volumes', VolumeIds=[r['Ebs']['VolumeId'] for r in mappings])['Volumes'] |
| + for want in launch['BlockDeviceMappings']: |
| + mapping = next(r for r in mappings if r['DeviceName'] == want['DeviceName']) |
| + volume = next(v for v in volumes if v['VolumeId'] == mapping['Ebs']['VolumeId']) |
| + require(mapping['Ebs']['DeleteOnTermination'] == want['Ebs']['DeleteOnTermination'], 'volume retention drift') |
| + for attr, expected in want['Ebs'].items(): |
| + if attr == 'DeleteOnTermination': |
| + continue |
| + require(volume[{'VolumeSize': 'Size'}.get(attr, attr)] == expected, 'volume drift: ' + attr) |
| + return dict(instance=instance, volumes=volumes) |
| + |
| + |
| +def cleanup_plan(journal): |
| + allowed = dict(instance={journal.data['scope']['role']}, profile={journal.data['scope']['role']}, |
| + role={journal.data['scope']['role']}, copy={journal.data['scope']['key']}, |
| + parameter=set(seed(journal.data['scope'], 'cleanup', 'public'))) |
| + resources = [r for r in journal.data['resources'] if r['state'] not in ('gone', 'rejected')] |
| + for row in resources: |
| + require(row['kind'] in allowed and row['name'] in allowed[row['kind']], 'out-of-scope journal resource') |
| + order = ['instance', 'profile', 'role', 'parameter', 'copy'] |
| + return sorted(resources, key=lambda r: order.index(r['kind'])) |
| + |
| + |
| +def cleanup_preview(journal): |
| + # A preview never changes the journal or contacts AWS, including when an |
| + # interrupted create has no returned id. Recovery then begins with tags. |
| + calls = [('sts', 'get-caller-identity', {})] |
| + def snapshots(): |
| + for tg in TGS: |
| + calls.append(('elbv2', 'describe-target-health', dict(TargetGroupArn=tg))) |
| + for op in ('list-objects-v2', 'list-object-versions'): |
| + calls.append(('s3api', op, dict(Bucket=BUCKET, Prefix=EDGES_PREFIX))) |
| + snapshots() |
| + for row in cleanup_plan(journal): |
| + kind, name = row['kind'], row['name'] |
| + if kind == 'instance': |
| + calls.append(('ec2', 'describe-instances', dict(Filters=[dict(Name='tag:'+t['Key'], Values=[t['Value']]) for t in journal.tags()]))) |
| + ids = row['ids'].get('recovered_iids') or [row['ids'].get('iid', '<owned id recovered by tags>')] |
| + calls += [('ec2', 'terminate-instances', dict(InstanceIds=ids)), ('ec2', 'describe-instances', dict(InstanceIds=ids))] |
| + elif kind == 'profile': |
| + for op, args in [('get-instance-profile', dict(InstanceProfileName=name)), |
| + ('remove-role-from-instance-profile', dict(InstanceProfileName=name, RoleName=name)), |
| + ('delete-instance-profile', dict(InstanceProfileName=name)), |
| + ('get-instance-profile', dict(InstanceProfileName=name))]: |
| + calls.append(('iam', op, args)) |
| + elif kind == 'role': |
| + for op, args in [('get-role', dict(RoleName=name)), ('delete-role-policy', dict(RoleName=name, PolicyName='witness')), |
| + ('delete-role', dict(RoleName=name)), ('get-role', dict(RoleName=name))]: |
| + calls.append(('iam', op, args)) |
| + elif kind == 'parameter': |
| + calls += [('ssm', 'get-parameter', dict(Name=name)), |
| + ('ssm', 'list-tags-for-resource', dict(ResourceType='Parameter', ResourceId=name)), |
| + ('ssm', 'delete-parameter', dict(Name=name)), ('ssm', 'get-parameter', dict(Name=name))] |
| + elif kind == 'copy': |
| + calls += [('s3api', 'list-object-versions', dict(Bucket=BUCKET, Prefix=name)), |
| + ('s3api', 'head-object', dict(Bucket=BUCKET, Key=name, VersionId='<each version; validate owner>')), |
| + ('s3api', 'delete-object', dict(Bucket=BUCKET, Key=name, VersionId='<each owned version and marker>')), |
| + ('s3api', 'list-object-versions', dict(Bucket=BUCKET, Prefix=name)), |
| + ('s3api', 'head-object', dict(Bucket=BUCKET, Key=name))] |
| + snapshots() |
| + return calls |
| + |
| + |
| +def resource_label(row, journal): |
| + kind, name, ids = row['kind'], row['name'], row['ids'] |
| + if ids.get('arn'): |
| + return ids['arn'] |
| + if kind in ('role', 'profile'): |
| + return f'arn:aws:iam::{ACCOUNT}:' + ('role/' if kind == 'role' else 'instance-profile/') + name |
| + if kind == 'parameter': |
| + return f'arn:aws:ssm:{REGION}:{ACCOUNT}:parameter' + name |
| + if kind == 'copy': |
| + return f'arn:aws:s3:::{BUCKET}/' + name |
| + return ids.get('iid') or ','.join(ids.get('recovered_iids', [])) or 'client-token:f4-' + journal.data['owner'] |
| + |
| + |
| +def cleanup(aws, journal, sleep=time.sleep): |
| + leaked = [] |
| + def retry(fn, label, attempts=12): |
| + last = None |
| + for n in range(attempts): |
| + try: |
| + return fn() |
| + except Exception as ex: |
| + last = ex |
| + if n + 1 < attempts: |
| + sleep(5) |
| + raise RuntimeError(label + ': ' + str(last)) |
| + |
| + def ignore_missing(service, operation, codes, **params): |
| + try: |
| + return aws(service, operation, **params) |
| + except AWSError as ex: |
| + if ex.code not in codes: |
| + raise |
| + return None |
| + |
| + for row in cleanup_plan(journal): |
| + name, kind = row['name'], row['kind'] |
| + try: |
| + if kind == 'instance': |
| + def terminate(): |
| + found = instances(aws, journal) |
| + known = row['ids'].get('iid') |
| + if known and all(i['InstanceId'] != known for i in found): |
| + found += [i for r in aws('ec2', 'describe-instances', InstanceIds=[known])['Reservations'] for i in r['Instances']] |
| + # A pending launch can still be propagating after a lost |
| + # reply. No instance is not proof of termination. |
| + require(found, 'launch outcome unknown; retry cleanup-only') |
| + for instance in found: |
| + require(owned(instance.get('Tags', []), journal), 'instance owner changed') |
| + require(instance['InstanceId'] not in FIXED, 'refuse fixed instance') |
| + ids = sorted({i['InstanceId'] for i in found}) |
| + row['ids']['recovered_iids'] = ids |
| + journal.save() |
| + active = [i['InstanceId'] for i in found if i['State']['Name'] != 'terminated'] |
| + if active: |
| + # Lost terminate replies are resolved by the next describe. |
| + aws('ec2', 'terminate-instances', InstanceIds=active) |
| + raise RuntimeError('termination pending') |
| + return ids |
| + retry(terminate, name, attempts=60) |
| + elif kind == 'profile': |
| + def delete_profile(): |
| + response = ignore_missing('iam', 'get-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name) |
| + if response is None: |
| + require(row['state'] != 'pending', 'profile create outcome unknown') |
| + return |
| + profile = response['InstanceProfile'] |
| + require(owned(profile.get('Tags', []), journal), 'profile owner changed') |
| + require(not row['ids'].get('id') or row['ids']['id'] == profile['InstanceProfileId'], 'profile id changed') |
| + journal.made(row, id=profile['InstanceProfileId'], arn=profile['Arn']) |
| + for role in profile['Roles']: |
| + require(role['RoleName'] == name, 'foreign role in profile') |
| + ignore_missing('iam', 'remove-role-from-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name, RoleName=name) |
| + ignore_missing('iam', 'delete-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name) |
| + require(absent(aws, 'iam', 'get-instance-profile', {'NoSuchEntity'}, InstanceProfileName=name), 'profile still exists') |
| + retry(delete_profile, name) |
| + elif kind == 'role': |
| + def delete_role(): |
| + response = ignore_missing('iam', 'get-role', {'NoSuchEntity'}, RoleName=name) |
| + if response is None: |
| + require(row['state'] != 'pending', 'role create outcome unknown') |
| + return |
| + role = response['Role'] |
| + require(owned(role.get('Tags', []), journal), 'role owner changed') |
| + require(not row['ids'].get('id') or row['ids']['id'] == role['RoleId'], 'role id changed') |
| + journal.made(row, id=role['RoleId'], arn=role['Arn']) |
| + ignore_missing('iam', 'delete-role-policy', {'NoSuchEntity'}, RoleName=name, PolicyName='witness') |
| + ignore_missing('iam', 'delete-role', {'NoSuchEntity'}, RoleName=name) |
| + require(absent(aws, 'iam', 'get-role', {'NoSuchEntity'}, RoleName=name), 'role still exists') |
| + retry(delete_role, name) |
| + elif kind == 'parameter': |
| + def delete_parameter(): |
| + if absent(aws, 'ssm', 'get-parameter', {'ParameterNotFound'}, Name=name): |
| + require(row['state'] != 'pending', 'parameter create outcome unknown') |
| + return |
| + tags = aws('ssm', 'list-tags-for-resource', ResourceType='Parameter', ResourceId=name)['TagList'] |
| + require(owned(tags, journal), 'parameter owner changed') |
| + journal.made(row, **row['ids']) |
| + ignore_missing('ssm', 'delete-parameter', {'ParameterNotFound'}, Name=name) |
| + require(absent(aws, 'ssm', 'get-parameter', {'ParameterNotFound'}, Name=name), 'parameter still exists') |
| + retry(delete_parameter, name) |
| + elif kind == 'copy': |
| + def delete_copy(): |
| + versions, markers = object_versions(aws, name) |
| + require(versions or markers or row['state'] != 'pending', 'copy outcome unknown') |
| + # Validate EVERY version before deleting any. A same-key |
| + # foreign version is not ours, even after a lost reply. |
| + for item in versions: |
| + head = aws('s3api', 'head-object', Bucket=BUCKET, Key=name, VersionId=item['VersionId']) |
| + require(head.get('Metadata', {}).get('witness-owner') == journal.data['owner'], 'object owner changed') |
| + if versions or markers: |
| + journal.made(row, **row['ids']) |
| + for item in versions + markers: |
| + aws('s3api', 'delete-object', Bucket=BUCKET, Key=name, VersionId=item['VersionId']) |
| + require(object_versions(aws, name) == ([], []), 'scratch object versions remain') |
| + require(absent(aws, 's3api', 'head-object', {'404', 'NoSuchKey', 'NotFound'}, Bucket=BUCKET, Key=name), 'scratch object still exists') |
| + retry(delete_copy, name) |
| + journal.gone(row) |
| except Exception as ex: |
| - if any(code in str(ex) for code in ('NoSuchEntity','ParameterNotFound','InvalidInstanceID.NotFound')):return {} |
| - leaked.append(label);print('LEAKED',label,str(ex),file=sys.stderr);return {} |
| - instances=attempt(s['role'], 'ec2','describe-instances',Filters=[{'Name':'tag:witness_run','Values':[s['run']]}, |
| - {'Name':'tag:purpose','Values':['p3b1-f4-witness']}]) |
| - ids=[i['InstanceId'] for r in instances.get('Reservations',[]) for i in r['Instances'] if i['State']['Name']!='terminated'] |
| - if aws.dry: ids=['<witness-instance-id>'] |
| - if ids: |
| - attempt(str(ids),'ec2','terminate-instances',InstanceIds=ids) |
| - if not aws.dry: |
| - deadline=time.monotonic()+300 |
| - while time.monotonic()<deadline: |
| - result=attempt(str(ids),'ec2','describe-instances',InstanceIds=ids) |
| - states=[i['State']['Name'] for r in result.get('Reservations',[]) for i in r['Instances']] |
| - if len(states)==len(ids) and all(x=='terminated' for x in states):break |
| - time.sleep(5) |
| - else: leaked.extend(ids);print('LEAKED',ids,'termination not verified',file=sys.stderr) |
| - attempt(s['role'],'iam','remove-role-from-instance-profile',InstanceProfileName=s['role'],RoleName=s['role']) |
| - attempt(s['role'],'iam','delete-instance-profile',InstanceProfileName=s['role']) |
| - attempt(s['role'],'iam','delete-role-policy',RoleName=s['role'],PolicyName='witness') |
| - attempt(s['role'],'iam','delete-role',RoleName=s['role']) |
| - for name in seed(s,'cleanup').keys():attempt(name,'ssm','delete-parameter',Name=name) |
| - versions=attempt(s['key'],'s3api','list-object-versions',Bucket=BUCKET,Prefix=s['key']) |
| - for item in versions.get('Versions',[])+versions.get('DeleteMarkers',[]): |
| - if item['Key']==s['key']: |
| - attempt(s['key'],'s3api','delete-object',Bucket=BUCKET,Key=s['key'],VersionId=item['VersionId']) |
| - if aws.dry:aws('s3api','delete-object',Bucket=BUCKET,Key=s['key'],VersionId='<each-scratch-version>') |
| + label = resource_label(row, journal) |
| + leaked.append(label) |
| + row['cleanup_error'] = str(ex) |
| + journal.save() |
| + print('LEAKED', label, str(ex), file=sys.stderr, flush=True) |
| + journal.data['leaked'] = leaked |
| + journal.save() |
| return leaked |
| |
| |
| -def run_calls(aws, s, launch, directory): |
| - # The controller must first resolve LIVE_BLOCKERS. No live call reaches here |
| - # from main while the supplied role cannot satisfy the boot contract. |
| - aws('sts','get-caller-identity') |
| - aws('ec2','describe-images',ImageIds=[AMI]) |
| - aws('ec2','describe-subnets',SubnetIds=[SUBNET]) |
| - aws('ec2','describe-security-groups',GroupIds=[SG]) |
| - before=baseline(aws) |
| - key=aws('kms','describe-key',KeyId='alias/aws/ssm').get('KeyMetadata',{}).get('Arn','<resolved-alias/aws/ssm-key-arn>') |
| - trust={'Version':'2012-10-17','Statement':[{'Effect':'Allow','Principal':{'Service':'ec2.amazonaws.com'},'Action':'sts:AssumeRole'}]} |
| - aws('iam','create-role',RoleName=s['role'],AssumeRolePolicyDocument=json.dumps(trust),Tags=[dict(Key='purpose',Value='p3b1-f4-witness')]) |
| - aws('iam','put-role-policy',RoleName=s['role'],PolicyName='witness',PolicyDocument=json.dumps(policy(s,key))) |
| - aws('iam','create-instance-profile',InstanceProfileName=s['role']) |
| - aws('iam','add-role-to-instance-profile',InstanceProfileName=s['role'],RoleName=s['role']) |
| - copied=aws('s3api','copy-object',Bucket=BUCKET,Key=s['key'],CopySource=f'{BUCKET}/{BOOT_KEY}?versionId={BOOT_VERSION}') |
| - version=copied.get('VersionId','<scratch-copy-version>') |
| - for name,value in seed(s,version).items(): |
| - p=dict(Name=name,Value=value,Type='SecureString' if name.endswith('/CARLOS_SECRETS_KEY') else 'String',Overwrite=False) |
| - if p['Type']=='SecureString':p['KeyId']='alias/aws/ssm' |
| - aws('ssm','put-parameter',**p) |
| - if not aws.dry:time.sleep(15) |
| - response=aws('ec2','run-instances',**launch) |
| - iid=response.get('Instances',[{'InstanceId':'<witness-instance-id>'}])[0]['InstanceId'] |
| - deadline=time.monotonic()+(0 if aws.dry else 900) |
| - while True: |
| - aws('ec2','get-console-output',InstanceId=iid,Latest=True) |
| - # get-object uses an output filename, unlike the ordinary JSON-only calls. |
| - command=['aws','--profile','kass','--region',REGION,'s3api','get-object','--bucket',BUCKET,'--key',s['evidence']+'/evidence.tar.gz',str(directory/'evidence.tar.gz')] |
| - print('AWS',shlex.join(command)) |
| - if aws.dry:break |
| - p=subprocess.run(command,capture_output=True,timeout=90) |
| - if p.returncode==0: |
| - with tarfile.open(directory/'evidence.tar.gz','r:gz') as tar: |
| - entry=tar.getmember('evidence.json');require(entry.isfile() and entry.size<4*1024*1024,'evidence bounds') |
| - evidence=json.load(tar.extractfile(entry)) |
| - rows=assertions(evidence) |
| - report(directory/'evidence.md',rows) |
| - require(all(x[1] for x in rows),'witness assertion failures') |
| +def read_archive(path): |
| + require(path.stat().st_size <= 16 * 1024 * 1024, 'archive too large') |
| + with tarfile.open(path, 'r:gz') as tar: |
| + entry = tar.getmember('evidence.json') |
| + require(entry.isfile() and entry.size <= 4 * 1024 * 1024, 'evidence bounds') |
| + return json.load(tar.extractfile(entry)) |
| + |
| + |
| +def decode_console(raw): |
| + # AWS CLI decodes EC2's base64 Output in its response customization; |
| + # raw API fixtures can still be encoded. Preserve either representation. |
| + if raw and re.fullmatch(r'[A-Za-z0-9+/]*={0,2}', raw) and len(raw) % 4 == 0: |
| + try: |
| + return base64.b64decode(raw, validate=True).decode('utf-8') |
| + except (ValueError, UnicodeError): |
| + pass |
| + return raw |
| + |
| + |
| +def cloud_status(console): |
| + matches = re.findall(r'WITNESS final-cloud-init ([A-Za-z0-9+/=]+)', console) |
| + if matches: |
| + try: |
| + status = json.loads(base64.b64decode(matches[-1], validate=True)) |
| + if status['rc'] == 0 and re.search(r'^status: done$', status['out'], re.M): |
| + return 'done' |
| + if status['rc'] != 0 or re.search(r'^status: (error|degraded)', status['out'], re.M): |
| + return 'error' |
| + except (ValueError, KeyError): |
| + return 'invalid-status' |
| + return 'running-or-unknown' |
| + |
| + |
| +def follow_boot(aws, iid, directory, journal, sleep=time.sleep): |
| + evidence = None |
| + final = 'running-or-unknown' |
| + deadline = time.monotonic() + 1200 |
| + def call(service, operation, **params): |
| + remaining = deadline - time.monotonic() |
| + require(remaining > 0, '20-minute collector deadline') |
| + return aws(service, operation, _timeout=min(30, remaining), **params) |
| + for attempt in range(120): # 20 minutes, including the final cloud-init line |
| + result = call('ec2', 'get-console-output', InstanceId=iid, Latest=True) |
| + atomic_json(directory / f'console-{attempt:03d}.json', result) |
| + raw = result.get('Output', '') |
| + decoded = decode_console(raw) |
| + (directory / f'console-{attempt:03d}.log').write_text(decoded) |
| + final = cloud_status(decoded) |
| + journal.data['cloud_init_status'] = final |
| + journal.save() |
| + if evidence is None: |
| + key = journal.data['scope']['evidence'] + '/evidence.tar.gz' |
| + try: |
| + head = call('s3api', 'head-object', Bucket=BUCKET, Key=key) |
| + require(head['ContentLength'] <= 16 * 1024 * 1024, 'evidence tarball too large') |
| + call('s3api', 'get-object', Bucket=BUCKET, Key=key, VersionId=head['VersionId'], _file=directory / 'evidence.tar.gz') |
| + evidence = read_archive(directory / 'evidence.tar.gz') |
| + atomic_json(directory / 'evidence.json', evidence) |
| + except AWSError as ex: |
| + if ex.code not in ('404', 'NoSuchKey', 'NotFound'): |
| + raise |
| + if evidence is not None and final != 'running-or-unknown': |
| + return evidence, final |
| + require(time.monotonic() < deadline, '20-minute collector deadline') |
| + sleep(min(10, max(0, deadline - time.monotonic()))) |
| + raise ValueError('20-minute collector/final cloud-init deadline') |
| + |
| + |
| +def create_resources(aws, journal, launch, directory, pointer, kms, pubkey_file, sleep): |
| + s = journal.data['scope'] |
| + role = s['role'] |
| + document = policy(s, kms, pointer) |
| + atomic_json(directory / 'policy.json', document) |
| + trust = {'Version': '2012-10-17', 'Statement': [dict(Effect='Allow', Principal={'Service': 'ec2.amazonaws.com'}, Action='sts:AssumeRole')]} |
| + collision(aws, journal, 'role', role) |
| + row = journal.intent('role', role) |
| + response = journal.create(aws, row, 'iam', 'create-role', RoleName=role, AssumeRolePolicyDocument=json.dumps(trust), Tags=journal.tags()) |
| + journal.made(row, id=response['Role']['RoleId'], arn=response['Role']['Arn']) |
| + row['policy_pending'] = True |
| + journal.save() |
| + aws('iam', 'put-role-policy', RoleName=role, PolicyName='witness', PolicyDocument=json.dumps(document)) |
| + require(aws('iam', 'get-role-policy', RoleName=role, PolicyName='witness')['PolicyDocument'] == document, 'policy readback differs') |
| + collision(aws, journal, 'profile', role) |
| + row = journal.intent('profile', role) |
| + response = journal.create(aws, row, 'iam', 'create-instance-profile', InstanceProfileName=role, Tags=journal.tags()) |
| + journal.made(row, id=response['InstanceProfile']['InstanceProfileId'], arn=response['InstanceProfile']['Arn']) |
| + row['attachment_pending'] = True |
| + journal.save() |
| + aws('iam', 'add-role-to-instance-profile', InstanceProfileName=role, RoleName=role) |
| + collision(aws, journal, 'copy', s['key']) |
| + row = journal.intent('copy', s['key']) |
| + response = journal.create(aws, row, 's3api', 'copy-object', Bucket=BUCKET, Key=s['key'], |
| + CopySource=f'{BUCKET}/{BOOT_KEY}?versionId={BOOT_VERSION}', MetadataDirective='REPLACE', |
| + Metadata={'witness-owner': journal.data['owner']}, ChecksumAlgorithm='SHA256') |
| + version = response['VersionId'] |
| + require(version and version != 'null', 'scratch copy missing version id') |
| + journal.made(row, version=version) |
| + head = aws('s3api', 'head-object', Bucket=BUCKET, Key=s['key'], VersionId=version, ChecksumMode='ENABLED') |
| + require(head['VersionId'] == version and head.get('Metadata', {}).get('witness-owner') == journal.data['owner'], 'copy identity readback') |
| + expected = hashlib.sha256(b'F4 offline bootstrap').hexdigest() if aws.dry else BOOT_SHA |
| + require(head.get('ChecksumSHA256') == base64.b64encode(bytes.fromhex(expected)).decode(), 'copy checksum readback') |
| + require(0 < head['ContentLength'] <= 256 * 1024 * 1024, 'copy size out of bounds') |
| + copy_path = directory / 'bootstrap-copy' |
| + try: |
| + downloaded = aws('s3api', 'get-object', Bucket=BUCKET, Key=s['key'], VersionId=version, _file=copy_path) |
| + require(downloaded['VersionId'] == version, 'download version readback') |
| + with copy_path.open('rb') as f: |
| + require(hashlib.file_digest(f, 'sha256').hexdigest() == expected, 'downloaded copy checksum') |
| + finally: |
| + copy_path.unlink(missing_ok=True) |
| + atomic_json(directory / 'copy-readback.json', head) |
| + values = seed(s, version, pubkey_file.read_text().strip()) |
| + for name, value in values.items(): |
| + collision(aws, journal, 'parameter', name) |
| + row = journal.intent('parameter', name) |
| + params = dict(Name=name, Value=value, Type='SecureString' if name.endswith('/CARLOS_SECRETS_KEY') else 'String', |
| + Overwrite=False, Tags=journal.tags()) |
| + if params['Type'] == 'SecureString': |
| + params['KeyId'] = 'alias/aws/ssm' |
| + response = journal.create(aws, row, 'ssm', 'put-parameter', **params) |
| + journal.made(row, version=response['Version']) |
| + actual = aws('ssm', 'get-parameter', Name=name, WithDecryption=True)['Parameter'] |
| + require(actual['Value'] == value and actual['Version'] == response['Version'] and actual['Type'] == params['Type'], 'SSM readback: ' + name) |
| + # Independently check the same nonrecursive path reader shape as hostenv. |
| + for path in (s['shared'], s['prefix']): |
| + response = aws('ssm', 'get-parameters-by-path', Path=path, Recursive=False, WithDecryption=True) |
| + require(not response.get('NextToken'), 'incomplete SSM readback') |
| + actual = {p['Name']: p['Value'] for p in response.get('Parameters', [])} |
| + expected = {k: v for k, v in values.items() if k.rsplit('/', 1)[0] == path} |
| + require(actual == expected, 'SSM path readback drift') |
| + atomic_json(directory / 'ssm-readback.json', dict(names=sorted(values), matched=True)) |
| + sleep(15) |
| + profile = aws('iam', 'get-instance-profile', InstanceProfileName=role)['InstanceProfile'] |
| + require(owned(profile.get('Tags', []), journal) and [r['RoleName'] for r in profile['Roles']] == [role], 'profile attachment readback') |
| + floor_preflight(aws) |
| + aws('s3api', 'get-object', Bucket=BUCKET, Key=POINTER_KEY, _file=directory / 'stable-prelaunch.json') |
| + require(verify_pointer(directory / 'stable-prelaunch.json', pubkey_file) == pointer, 'pointer changed during setup') |
| + collision(aws, journal, 'instance', role) |
| + row = journal.intent('instance', role) |
| + launch = json.loads(json.dumps(launch)) |
| + launch['ClientToken'] = 'f4-' + journal.data['owner'] |
| + for spec in launch['TagSpecifications']: |
| + spec['Tags'] = [t for t in spec['Tags'] if t['Key'] not in {x['Key'] for x in journal.tags()}] + journal.tags() |
| + atomic_json(directory / 'launch.json', launch) |
| + response = journal.create(aws, row, 'ec2', 'run-instances', **launch) # exactly one call; never retry |
| + require(len(response['Instances']) == 1, 'launch returned other than one instance') |
| + iid = response['Instances'][0]['InstanceId'] |
| + journal.made(row, iid=iid, box_ref=box_ref(iid)) |
| + for attempt in range(30): |
| + try: |
| + readback = launch_readback(aws, iid, launch) |
| break |
| - require(time.monotonic()<deadline,'collector deadline') |
| - time.sleep(10) |
| - after=baseline(aws,iid) |
| - require(before==after,'target/edges changes during witness') |
| + except (ValueError, KeyError, AWSError): |
| + if attempt == 29: |
| + raise |
| + sleep(2) |
| + atomic_json(directory / 'instance-readback.json', readback) |
| + journal.data['instance_readback'] = readback |
| + journal.save() |
| + return iid |
| + |
| + |
| +def write_evidence(directory, journal, rows, error=''): |
| + esc = lambda v: str(v).replace('|', '\\|').replace('\n', ' ')[:900] |
| + data = journal.data |
| + status = 'DRY RUN: simulated AWS; live assertions NOT RUN.' if data['dry'] else 'Live witness; see individual assertions.' |
| + body = '# P3b-1 F4 witness evidence\n\n' + status + '\n\n' + FLOOR_LABEL + '\n\n' |
| + body += 'Run: `' + data['scope']['run'] + '`. Account: `' + ACCOUNT + '`. Region: `' + REGION + '`.\n\n' |
| + body += 'Final cloud-init: `' + data.get('cloud_init_status', 'not observed') + '`.\n\n' |
| + if error: |
| + body += 'Failure: ' + esc(error) + '\n\n' |
| + body += '| Assertion | Status | Evidence |\n|---|---|---|\n' |
| + for name, ok, detail in rows: |
| + body += f'| {esc(name)} | {"NOT RUN" if ok is None else "PASS" if ok else "FAIL"} | {esc(detail)} |\n' |
| + body += '\n## Ownership and cleanup\n\n```json\n' + json.dumps(data, indent=2, sort_keys=True) + '\n```\n' |
| + for title, file in [('Module substitutions', 'substitutions.diff'), ('Instance policy', 'policy.json'), ('Input readbacks', 'preflight.json')]: |
| + path = directory / file |
| + if path.exists(): |
| + body += '\n## ' + title + '\n\n```\n' + path.read_text() + '\n```\n' |
| + consoles = sorted(directory.glob('console-*.log')) |
| + if consoles: |
| + body += '\n## Final console excerpt\n\n```text\n' + consoles[-1].read_text()[-7000:] + '\n```\n' |
| + (directory / 'evidence.md').write_text(body) |
| + |
| + |
| +def lifecycle(aws, journal, launch, directory, pubkey_file, ledger, cleanup_only=False, sleep=time.sleep): |
| + error, leaks, rows = '', [], [] |
| + old_handlers = {} |
| + def interrupted(signum, frame): |
| + raise KeyboardInterrupt('signal ' + str(signum)) |
| + for sig in SIGNALS: |
| + old_handlers[sig] = signal.signal(sig, interrupted) |
| + try: |
| + identity = aws('sts', 'get-caller-identity') |
| + require(identity['Account'] == ACCOUNT, 'wrong AWS account') |
| + if cleanup_only: |
| + require(journal.data.get('before'), 'journal has no original baseline') |
| + journal.data['cleanup_before'] = snapshot(aws) |
| + journal.save() |
| + else: |
| + before = snapshot(aws) |
| + journal.data['before'] = before |
| + journal.save() |
| + require(not check_snapshot(before, before), 'initial non-interference checks failed') |
| + s = journal.data['scope'] |
| + require(not aws('s3api', 'list-objects-v2', Bucket=BUCKET, Prefix=s['evidence'] + '/').get('Contents'), 'evidence prefix collision') |
| + historical = aws('s3api', 'list-object-versions', Bucket=BUCKET, Prefix=s['evidence'] + '/') |
| + require(not historical.get('Versions') and not historical.get('DeleteMarkers') and not historical.get('IsTruncated'), 'evidence history collision') |
| + pointer, kms = input_preflight(aws, directory, pubkey_file) |
| + # Check the whole namespace before spending a run, then recheck each |
| + # object immediately before journaling and creating it. |
| + for kind, name in [('role', s['role']), ('profile', s['role']), ('copy', s['key']), ('instance', s['role']), |
| + *[('parameter', name) for name in seed(s, 'preflight', 'public')]]: |
| + collision(aws, journal, kind, name) |
| + reserve_budget(ledger, s['run'], journal.data['owner']) |
| + journal.data['status'] = 'budget-reserved' |
| + journal.save() |
| + iid = create_resources(aws, journal, launch, directory, pointer, kms, pubkey_file, sleep) |
| + evidence, final = follow_boot(aws, iid, directory, journal, sleep) |
| + evidence['launch_readback'] = journal.data['instance_readback'] |
| + rows = assertions(evidence) |
| + rows.append(('final cloud-init', final == 'done', final)) |
| + if aws.dry: |
| + rows = [(name, None, 'simulation; ' + detail) for name, ok, detail in rows] |
| + else: |
| + require(all(ok for name, ok, detail in rows), 'witness assertion failures') |
| + except BaseException as ex: |
| + error = str(ex) or type(ex).__name__ |
| + finally: |
| + # Cleanup itself is not interrupted by a repeated terminal signal. |
| + for sig in SIGNALS: |
| + signal.signal(sig, signal.SIG_IGN) |
| + try: |
| + # Identity must be known before ANY cleanup mutation. A wrong |
| + # profile never licenses using ids from a different account. |
| + identity_ok = False |
| + try: |
| + identity_ok = aws('sts', 'get-caller-identity')['Account'] == ACCOUNT |
| + require(identity_ok, 'cleanup account mismatch') |
| + leaks = cleanup(aws, journal, sleep) |
| + except Exception as ex: |
| + leaks.append('cleanup: ' + str(ex)) |
| + print('LEAKED', leaks[-1], file=sys.stderr) |
| + finally: |
| + after = snapshot(aws) |
| + journal.data['after'] = after |
| + ids = [iid for r in journal.data['resources'] if r['kind'] == 'instance' |
| + for iid in r['ids'].get('recovered_iids', [r['ids'].get('iid')]) if iid] |
| + problems = check_snapshot(journal.data.get('before', {}), after, ids) |
| + if journal.data.get('cleanup_before'): |
| + problems += check_snapshot(journal.data['before'], journal.data['cleanup_before'], ids) |
| + journal.data['noninterference_errors'] = problems |
| + rows.append(('target groups and control/edges/', not problems, '; '.join(problems) or 'unchanged; no witness object')) |
| + rows.append(('cleanup verified', not leaks, ', '.join(leaks) or 'all journaled resources verified gone; evidence retained')) |
| + if not rows or error: |
| + present = {name for name, ok, detail in rows} |
| + rows += [(name, None if aws.dry else False, 'not reached: ' + error) |
| + for name, ok, detail in assertions({}) if name not in present] |
| + journal.data.update(status='failed' if error or leaks or problems else 'complete', error=error, leaked=leaks) |
| + journal.save() |
| + write_evidence(directory, journal, rows, error) |
| + finally: |
| + for sig, handler in old_handlers.items(): |
| + signal.signal(sig, handler) |
| + require(not error and not leaks and not journal.data.get('noninterference_errors'), error or 'cleanup/non-interference failure') |
| + return rows |
| |
| |
| def main(): |
| - ap=argparse.ArgumentParser() |
| - ap.add_argument('--run',default='dry-run') |
| - ap.add_argument('--dry-run',action='store_true') |
| - ap.add_argument('--execute',action='store_true') |
| - ap.add_argument('--cleanup-only',metavar='RUN') |
| - ap.add_argument('--scratch',type=Path,default=SCRATCH) |
| - ap.add_argument('--tofu',type=Path,default=SCRATCH/'tofu/tofu') |
| - args=ap.parse_args() |
| - s=scope(args.cleanup_only or args.run) |
| - os.umask(0o077) |
| - args.scratch.mkdir(parents=True,exist_ok=True) |
| - directory=args.scratch/('witness-'+s['run']);directory.mkdir(exist_ok=True) |
| - if args.cleanup_only: |
| - require(not args.execute,'cleanup-only with execute') |
| - require(args.dry_run, 'live cleanup refused: this harness has admitted no live runs; resource ownership is not established') |
| - return bool(cleanup(AWS(dry=True),s)) |
| - script,lt=render(args.tofu,directory,s) |
| - encoded=user_data(script,collector(s)) |
| - launch=launch_input(lt,encoded,s) |
| - (directory/'launch.json').write_text(json.dumps(launch,indent=2)) |
| - (directory/'collector.py').write_bytes(collector(s)) |
| - print('MIME encoded bytes:',len(encoded),'/ 16384; part 1 sha256:',hashlib.sha256(script).hexdigest()) |
| - report(directory/'evidence.md', [('render substitutions',True,'exactly deployment and pool module inputs'), |
| - ('MIME part 1 integrity',True,hashlib.sha256(script).hexdigest()),('MIME size',True,len(encoded)), |
| - *[(f'live prerequisite {n}',False,reason) for n,reason in enumerate(LIVE_BLOCKERS,1)]], |
| - 'LOCAL DRY RUN ONLY. No real-AMI assertions have run.') |
| + ap = argparse.ArgumentParser() |
| + ap.add_argument('--run', default='dry-run') |
| + ap.add_argument('--dry-run', action='store_true') |
| + ap.add_argument('--execute', action='store_true') |
| + ap.add_argument('--i-have-budget', action='store_true') |
| + ap.add_argument('--cleanup-only', metavar='RUN') |
| + ap.add_argument('--scratch', type=Path, default=SCRATCH) |
| + ap.add_argument('--tofu', type=Path, default=SCRATCH / 'tofu/tofu') |
| + ap.add_argument('--release-pubkey-file', type=Path) |
| + ap.add_argument('--pointer-file', type=Path, default=SCRATCH / 'round2-stable.json') |
| + args = ap.parse_args() |
| + require(not (args.execute and args.dry_run), 'conflicting modes') |
| + require(not args.i_have_budget or args.execute, '--i-have-budget requires --execute') |
| if args.execute: |
| - require(not args.dry_run,'conflicting modes') |
| - require(not LIVE_BLOCKERS,'live launch refused: '+' '.join(LIVE_BLOCKERS)) |
| - aws=AWS(dry=not args.execute) |
| - def interrupted(signum, frame):raise KeyboardInterrupt(f'signal {signum}') |
| - for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,interrupted) |
| - try:run_calls(aws,s,launch,directory) |
| - finally: |
| - for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,signal.SIG_IGN) |
| - leaks=cleanup(aws,s) |
| - require(not leaks,'cleanup leaks') |
| - print('DRY RUN complete; live launch blocked pending read-scope/fixture decision') |
| + require(args.i_have_budget, '--execute requires --i-have-budget') |
| + require(not LIVE_BLOCKERS, 'live blockers: ' + '; '.join(LIVE_BLOCKERS)) |
| + require(not args.cleanup_only or not args.execute, 'cleanup-only cannot execute a new launch') |
| + s = scope(args.cleanup_only or args.run) |
| + os.umask(0o077) |
| + args.scratch = args.scratch.resolve() |
| + args.scratch.mkdir(parents=True, exist_ok=True) |
| + dry = args.dry_run or (not args.execute and not args.cleanup_only) |
| + directory = args.scratch / (('dry-witness-' if dry else 'witness-') + s['run']) |
| + with exclusive(args.scratch / 'witness-budget.lock'): |
| + if args.cleanup_only: |
| + if dry and (args.scratch / ('witness-' + s['run'])).is_dir(): |
| + directory = args.scratch / ('witness-' + s['run']) |
| + require(directory.is_dir(), 'run directory missing; no ownership established') |
| + journal = Journal(directory / 'journal.json', dry=directory.name.startswith('dry-witness-')) |
| + require(journal.data['scope'] == s, 'cleanup run mismatch') |
| + if dry: |
| + for service, operation, params in cleanup_preview(journal): |
| + print('DRY CLEANUP AWS', service, operation, json.dumps(params, sort_keys=True)) |
| + return 0 |
| + require(not journal.data['dry'], 'simulated journal cannot authorize live cleanup') |
| + lifecycle(AWS(), journal, None, directory, None, None, cleanup_only=True) |
| + return 0 |
| + require(args.release_pubkey_file and args.release_pubkey_file.is_file(), '--release-pubkey-file is required') |
| + args.release_pubkey_file = args.release_pubkey_file.resolve() |
| + require(not directory.exists(), 'run directory exists; choose a fresh run id or cleanup-only') |
| + directory.mkdir(mode=0o700) |
| + journal = Journal(directory / 'journal.json', s, dry=dry) |
| + module = directory / 'module' |
| + def interrupted(signum, frame): |
| + raise KeyboardInterrupt('signal ' + str(signum)) |
| + old_handlers = {sig: signal.signal(sig, interrupted) for sig in SIGNALS} |
| + try: |
| + script, lt = render(args.tofu, directory, s) |
| + encoded = user_data(script, collector(s), observer(s)) |
| + launch = launch_input(lt, encoded, s) |
| + (directory / 'collector.py').write_bytes(collector(s)) |
| + (directory / 'observer.py').write_bytes(observer(s)) |
| + print('MIME encoded bytes:', len(encoded), '/ 16384; part 1 sha256:', hashlib.sha256(script).hexdigest()) |
| + if dry: |
| + from region_group_witness_fake import FakeAWS |
| + aws = FakeAWS(sys.modules[__name__], args.pointer_file.read_bytes(), directory) |
| + lifecycle(aws, journal, launch, directory, args.release_pubkey_file, directory / 'simulated-budget.json', sleep=lambda _: None) |
| + else: |
| + lifecycle(AWS(), journal, launch, directory, args.release_pubkey_file, args.scratch / 'witness-budget.json') |
| + except BaseException as ex: |
| + if journal.data['status'] == 'preflight': |
| + write_evidence(directory, journal, [(n, None, 'not reached') for n, ok, d in assertions({})], str(ex)) |
| + raise |
| + finally: |
| + for sig in SIGNALS: |
| + signal.signal(sig, signal.SIG_IGN) |
| + try: |
| + if module.exists(): |
| + shutil.rmtree(module) |
| + finally: |
| + for sig, handler in old_handlers.items(): |
| + signal.signal(sig, handler) |
| + print(('DRY RUN' if dry else 'WITNESS') + ' complete; ' + FLOOR_LABEL) |
| return 0 |
| |
| |
| -if __name__=='__main__': |
| - try:sys.exit(main()) |
| - except (ValueError,RuntimeError,subprocess.SubprocessError) as error: |
| - print('FAIL',error,file=sys.stderr);sys.exit(1) |
| +if __name__ == '__main__': |
| + try: |
| + sys.exit(main()) |
| + except (ValueError, RuntimeError, OSError, subprocess.SubprocessError, KeyboardInterrupt) as error: |
| + print('FAIL', error, file=sys.stderr) |
| + sys.exit(1) |