carlos / platform Public

Add local group boot witness rendering and blocked live plan

Render both payloads from the module, assert the exact scratch substitutions, preserve the boot MIME part, and collect redacted boot evidence. Live execution and cleanup are refused because the requested read-only role cannot complete host-env and channel installation. Preserve the unresolved scope decision explicitly.

Include the F4 census proposal and correct negative-test portability and cleanup.
Co-Authored-By: GPT-6 Astra <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev a81a885c96cc50a0518159487cbdc3e8a465b5ae parent 1a4a565
7 files changed, +671 −4
  • docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md +19 −0
  • infra/modules/region-host/group-init.sh.tftpl +2 −2
  • internal/host/group_boot_staging_test.go +6 −2
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv +5 −0
  • scripts/region-group-boot-witness.py +537 −0
  • scripts/region_group_boot_witness_test.py +101 −0
diff --git a/docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md b/docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md
new file mode 100644
index 000000000..9249e77bc
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md
@@ -0,0 +1,19 @@
+# Census approval: region-ha-p3b1-f4
+
+Ruling `census-ruling-region-ha-p3b1-f4`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `infra/modules/region-host/group-init.sh.tftpl` `external` | body | unchanged (1) | Move bootstrap and chrony staging to root:root 0700 /var/lib/carlos-group-boot through the existing O_NOFOLLOW walker; refuse unsafe preexisting directory. Bootstrap 0700; retain initial hash verification and rehash against a root-only captured SSM digest immediately before all three execs; named noexec refusal. Root reads only its own helper/hash and verified binary; no tenant/app/agent writable input or authority added. Final removal preserved. |
+
+Envelopes re-pinned: `infra/modules/region-host`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `infra/modules/region-host/group-init.sh.tftpl` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=New root user-data boot: operator Terraform/SSM supply scoped bootstrap object version/hash, queue, reader inventory and ingress; hash-verified bootstrap verifies signed IMDS identity. Root exclusively writes /etc/carlos/group.json, group-identity.json, region-config.json and group-ingress.json with current kernel boot ID; public address comes from protected IMDSv2, not signed document or headers. Install IMDS denial, chrony, dormant hairpin fence and protected drop-ins before bootstrap/install/start. No agent receipt is read by root; restart authority is separate maintenance permit. F1: operator-seeded SSM boot/bootstrap-object requires floor=absent-expected or required beside key/version/known_readers/deployment_aws_region; root copies it into group.json before config_digest. Missing or invalid floor refuses before bootstrap fetch; Terraform only names this SSM key and does not write the object. Agent and instance-control gain AF_NETLINK in their address-family allowlists, with no CAP_NET_ADMIN grant.
+
+Seal: `86aa1e39a21072d17678411a4047983a756494b84a25f7719c0cdf4a61cd1b85` → `2cac838a0f7c71af13f551e33df67a471c71a95745b46e26cf9bcefb46d02a0d`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl
index df68e9b9c..935208a50 100644
--- a/infra/modules/region-host/group-init.sh.tftpl
+++ b/infra/modules/region-host/group-init.sh.tftpl
@@ -53,11 +53,11 @@ import hashlib, os, re, stat, sys
WORK = '/var/lib/carlos-group-boot'
def regular(path, mode, owner):
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
- f = os.fdopen(fd, 'rb')
st = os.fstat(fd)
if not stat.S_ISREG(st.st_mode) or (st.st_uid, st.st_gid) != owner or stat.S_IMODE(st.st_mode) != mode or st.st_nlink != 1:
+ os.close(fd)
raise SystemExit('group_boot_bootstrap')
- return f
+ return os.fdopen(fd, 'rb')
def check(work=WORK, owner=(0, 0)):
st = os.lstat(work)
if not stat.S_ISDIR(st.st_mode) or (st.st_uid, st.st_gid) != owner or stat.S_IMODE(st.st_mode) != 0o700:
diff --git a/internal/host/group_boot_staging_test.go b/internal/host/group_boot_staging_test.go
index 37ce99e76..8833b733f 100644
--- a/internal/host/group_boot_staging_test.go
+++ b/internal/host/group_boot_staging_test.go
@@ -46,6 +46,9 @@ var groupBootTmpfs = regexp.MustCompile(`(^|[^A-Za-z0-9_./-])(/run|/tmp|/dev/shm
// executes. Every bootstrap execution must be the line right after the shared
// verification, and nothing may stage or run from a tmpfs default.
func checkGroupBootStaging(s string) error {
+ if regexp.MustCompile(`carlos-group-boot[^/'"[:space:]]`).MatchString(s) {
+ return fmt.Errorf("unexpected staging directory suffix")
+ }
if n := strings.Count(s, "carlos-group-boot"); n != strings.Count(s, groupBootStaging) {
return fmt.Errorf("staging name used outside %s", groupBootStaging)
}
@@ -83,7 +86,7 @@ func checkGroupBootStaging(s string) error {
if prev != "boot_verify.check()" {
return fmt.Errorf("line %d executes the bootstrap without the shared verification", i+1)
}
- case strings.Contains(line, "'get-object'") || strings.HasPrefix(line, "with open(work + 'bootstrap', 'rb')") || strings.HasPrefix(line, "os.chmod(work + 'bootstrap', 0o700)") || strings.HasPrefix(line, "write(work + 'bootstrap.sha256'") || strings.Contains(line, "bootstrap-object") || strings.Contains(line, "bootstrap-sha256") || strings.Contains(line, "BOOTSTRAP_") || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "# ") || strings.Contains(line, "verified bootstrap") || strings.Contains(line, "regular(work + '/bootstrap"):
+ case strings.Contains(line, "'get-object'") || strings.HasPrefix(line, "with open(work + 'bootstrap', 'rb')") || strings.HasPrefix(line, "os.chmod(work + 'bootstrap', 0o700)") || strings.HasPrefix(line, "write(work + 'bootstrap.sha256'") || strings.Contains(line, "bootstrap-object") || strings.Contains(line, "bootstrap-sha256") || strings.Contains(line, "BOOTSTRAP_") || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "# ") || strings.Contains(line, "verified bootstrap") || strings.Contains(line, "regular(work + '/bootstrap") || strings.Contains(line, "raise SystemExit('group_boot_bootstrap')") || strings.HasPrefix(line, "if not obj['key'].startswith('bootstrap/'"):
default:
return fmt.Errorf("line %d references the bootstrap outside the audited forms: %s", i+1, line)
}
@@ -248,7 +251,7 @@ func TestGroupBootWalker(t *testing.T) {
}
return
}
- if err == nil || !strings.Contains(out, c.refuse) && !strings.Contains(out, "Too many levels of symbolic links") {
+ if err == nil || !strings.Contains(out, c.refuse) && !(c.refuse == "ELOOP" && (strings.Contains(out, "Too many levels of symbolic links") || strings.Contains(out, "Not a directory"))) {
t.Fatalf("accepted: %v %s", err, out)
}
})
@@ -360,6 +363,7 @@ func TestGroupBootVerifyHelper(t *testing.T) {
}
}, want: "group_boot_directory"},
{name: "directory mode 0500", mutate: func(t *testing.T, w string) {
+ t.Cleanup(func() { _ = os.Chmod(w, 0o700) })
if err := os.Chmod(w, 0o500); err != nil {
t.Fatal(err)
}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 712863dfe..6d9627e9d 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -88,3 +88,4 @@ plan14-root-reads-region-ha-p3b.tsv face84b4c688cd3c179b0a34ced4d3521e71de8e63cb
plan14-root-reads-stateless-coordinator-oneboxfleet.tsv face84b4c688cd3c179b0a34ced4d3521e71de8e63cbd45f21c27972c5b1a921
plan14-root-reads-region-ha-group-rtb.tsv 526d434888d043a8b09d8fe196f6324782d6ca20d759b080f99daa528adf6a32
plan14-root-reads-region-ha-p3b1-fixes.tsv 86aa1e39a21072d17678411a4047983a756494b84a25f7719c0cdf4a61cd1b85
+plan14-root-reads-region-ha-p3b1-f4.tsv 2cac838a0f7c71af13f551e33df67a471c71a95745b46e26cf9bcefb46d02a0d
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv
new file mode 100644
index 000000000..b894664c8
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p3b1-f4.tsv
@@ -0,0 +1,5 @@
+# Census overlay region-ha-p3b1-f4, written by census-propose (#369). census-ruling-region-ha-p3b1-f4, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p3b1-f4.md.
+# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy d5a8d1383df545942daa6e4bfe44cee51aa162a144a8c1d3de6f518a9907e02d infra/modules/region-host/group-init.sh.tftpl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=New root user-data boot: operator Terraform/SSM supply scoped bootstrap object version/hash, queue, reader inventory and ingress; hash-verified bootstrap verifies signed IMDS identity. Root exclusively writes /etc/carlos/group.json, group-identity.json, region-config.json and group-ingress.json with current kernel boot ID; public address comes from protected IMDSv2, not signed document or headers. Install IMDS denial, chrony, dormant hairpin fence and protected drop-ins before bootstrap/install/start. No agent receipt is read by root; restart authority is separate maintenance permit. F1: operator-seeded SSM boot/bootstrap-object requires floor=absent-expected or required beside key/version/known_readers/deployment_aws_region; root copies it into group.json before config_digest. Missing or invalid floor refuses before bootstrap fetch; Terraform only names this SSM key and does not write the object. Agent and instance-control gain AF_NETLINK in their address-family allowlists, with no CAP_NET_ADMIN grant.;rev3=census-ruling-region-ha-p3b1-f4;basis=Move bootstrap and chrony staging to root:root 0700 /var/lib/carlos-group-boot through the existing O_NOFOLLOW walker; refuse unsafe preexisting directory. Bootstrap 0700; retain initial hash verification and rehash against a root-only captured SSM digest immediately before all three execs; named noexec refusal. Root reads only its own helper/hash and verified binary; no tenant/app/agent writable input or authority added. Final removal preserved. file:external@0 3caa0b1165ea720b77b282da0f2a370a16bccd1dba9b0ba8761b09fc63e178ab
+infra/modules/region-host/group-init.sh.tftpl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=New root user-data boot: operator Terraform/SSM supply scoped bootstrap object version/hash, queue, reader inventory and ingress; hash-verified bootstrap verifies signed IMDS identity. Root exclusively writes /etc/carlos/group.json, group-identity.json, region-config.json and group-ingress.json with current kernel boot ID; public address comes from protected IMDSv2, not signed document or headers. Install IMDS denial, chrony, dormant hairpin fence and protected drop-ins before bootstrap/install/start. No agent receipt is read by root; restart authority is separate maintenance permit. F1: operator-seeded SSM boot/bootstrap-object requires floor=absent-expected or required beside key/version/known_readers/deployment_aws_region; root copies it into group.json before config_digest. Missing or invalid floor refuses before bootstrap fetch; Terraform only names this SSM key and does not write the object. Agent and instance-control gain AF_NETLINK in their address-family allowlists, with no CAP_NET_ADMIN grant.;rev3=census-ruling-region-ha-p3b1-f4;basis=Move bootstrap and chrony staging to root:root 0700 /var/lib/carlos-group-boot through the existing O_NOFOLLOW walker; refuse unsafe preexisting directory. Bootstrap 0700; retain initial hash verification and rehash against a root-only captured SSM digest immediately before all three execs; named noexec refusal. Root reads only its own helper/hash and verified binary; no tenant/app/agent writable input or authority added. Final removal preserved. file:external@0 3caa0b1165ea720b77b282da0f2a370a16bccd1dba9b0ba8761b09fc63e178ab
+@coverage infra/modules/region-host 906e1139a9a5e62d61ecbf8e0dc7c48a0453b4fab17f0dcfec8ef49d1a9c8b70
diff --git a/scripts/region-group-boot-witness.py b/scripts/region-group-boot-witness.py
new file mode 100644
index 000000000..8954cb595
--- /dev/null
+++ b/scripts/region-group-boot-witness.py
@@ -0,0 +1,537 @@
+#!/usr/bin/env python3
+"""Controller-only P3b-1 witness. Default is a local dry run; never applies tofu."""
+import argparse
+import base64
+import difflib
+import email.policy
+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
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRATCH = Path('/home/paulca/.cache/p3b1-f4-work')
+ACCOUNT = '640012953448'
+REGION = 'eu-west-1'
+BUCKET = 'carlos-dev-640012953448'
+SG = 'sg-0c328faf839a02986'
+AMI = 'ami-020434b3e0470d552'
+BOOT_KEY = 'bootstrap/dev/ie/carlos-v0.34.2-linux-arm64'
+BOOT_VERSION = 'J_BSF6jwEX6Fj3HhbyKvvqpp0lidbDIT'
+BOOT_SHA = 'f837b3763457825d469c89cde80fb85fd45f50fd1872a8d53147d53fdebfdc01'
+FIXED = {'i-046c7fe43620944bc', 'i-05498eada6f0afd23'}
+TGS = [f'arn:aws:elasticloadbalancing:{REGION}:{ACCOUNT}:targetgroup/{x}' for x in
+ ('carlos-dev-ie-nlb-80/2f5186277337ce74', 'carlos-dev-ie-nlb-443/c33262405df2e5df')]
+SUBNET = 'subnet-0975dda9ac0e65347'
+MOUNTS = ['/run', '/tmp', '/dev/shm', '/var/tmp', '/var/lib', '/var/lib/cloud',
+ '/var/lib/carlos-group-boot', '/opt', '/etc', '/data']
+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.',
+)
+
+
+def require(ok, message):
+ if not ok:
+ raise ValueError(message)
+
+
+def scope(run):
+ require(bool(re.fullmatch(r'[a-z0-9][a-z0-9-]{0,31}', run)), 'invalid run id')
+ deployment = 'f4-' + run
+ return dict(run=run, deployment=deployment, prefix=f'/carlos/{deployment}/ie',
+ shared=f'/carlos/{deployment}/shared', key=f'bootstrap/{deployment}/ie/carlos-v0.34.2-linux-arm64',
+ evidence=f'root-runner/p3b1-f4-witness/{run}', role=f'p3b1-f4-witness-{run}')
+
+
+def plain_render(config):
+ template = (ROOT / 'infra/modules/region-host/group-init.sh.tftpl').read_text()
+ loop = '%{ for key, value in config ~}\n${key}=${value}\nexport ${key}\n%{ endfor ~}\n'
+ require(template.count(loop) == 1, 'template config loop changed')
+ # Tofu quotes even shell-safe values.
+ assignments = ''.join(k + "='" + v.replace("'", "'\"'\"'") + "'\nexport " + k + '\n' for k, v in sorted(config.items()))
+ return template.replace(loop, assignments).replace('$${', '${').replace('%%{', '%{').encode()
+
+
+def witness_config(dev, s):
+ result = dict(dev, CARLOS_DEPLOYMENT=s['deployment'], CARLOS_POOLS='witness')
+ for name in ('CARLOS_BOOTSTRAP_HASH_KEY', 'CARLOS_BOOTSTRAP_OBJECT_KEY', 'CARLOS_INGRESS_KEY'):
+ result[name] = dev[name].replace('/carlos/dev/ie/', s['prefix'] + '/')
+ # hapair is dev-only in GroupConfig.Validate. Two module input substitutions
+ # (deployment and pools) therefore change exactly five script assignments.
+ return result
+
+
+def check_diff(dev, witness, s):
+ config = json.loads((ROOT / 'scripts/testdata/region-group-plan/dev-boot-config.json').read_text())
+ require(dev == plain_render(config), 'module real-dev render differs from the real-dev fixture')
+ expected = plain_render(witness_config(config, s))
+ require(witness == expected, 'witness differs beyond deployment/pool substitutions')
+ require(b'/carlos/dev/ie' not in witness and b'bootstrap/dev/ie' not in witness, 'real dev namespace in witness')
+ diff = ''.join(difflib.unified_diff(dev.decode().splitlines(True), witness.decode().splitlines(True),
+ fromfile='real-dev', tofile='witness'))
+ require(len([x for x in diff.splitlines() if x.startswith('+') and not x.startswith('+++')]) == 5,
+ 'expected exactly five changed assignment lines')
+ return diff
+
+
+def configured_values(values, expressions):
+ # Mock providers invent values for optional+computed fields. Only attributes
+ # actually configured by the module may become EC2 launch arguments.
+ result = {}
+ for key, expression in expressions.items():
+ require(key in values, 'missing configured value: ' + key)
+ value = values[key]
+ if isinstance(expression, list):
+ require(len(value) == len(expression), 'configured block cardinality: ' + key)
+ result[key] = [configured_values(v, e) for v, e in zip(value, expression)]
+ else:
+ if isinstance(expression.get('constant_value'), bool):
+ require(value in (True, False, 'true', 'false'), 'boolean provider value')
+ value = value in (True, 'true')
+ result[key] = value
+ return result
+
+
+def render(tofu, directory, s):
+ require(json.loads(subprocess.check_output([str(tofu), 'version', '-json']))['terraform_version'] == '1.13.1',
+ 'OpenTofu 1.13.1 required')
+ module = directory / 'module'
+ shutil.copytree(ROOT / 'infra/modules/region-host', module, dirs_exist_ok=True,
+ ignore=shutil.ignore_patterns('.terraform', '.terraform.lock.hcl'))
+ env = dict(os.environ, AWS_EC2_METADATA_DISABLED='true', AWS_CONFIG_FILE='/dev/null',
+ AWS_SHARED_CREDENTIALS_FILE='/dev/null', AWS_ACCESS_KEY_ID='mock', AWS_SECRET_ACCESS_KEY='mock',
+ TMPDIR=str(directory), TF_IN_AUTOMATION='1')
+ env.pop('AWS_PROFILE', None)
+ env.pop('AWS_SESSION_TOKEN', None)
+ def run(*args):
+ result = subprocess.run(['nice', '-n', '10', str(tofu), f'-chdir={module}', *args],
+ env=env, capture_output=True, text=True, timeout=600)
+ require(result.returncode == 0, result.stdout[-4000:] + result.stderr[-2000:])
+ return result.stdout
+ if not (module / '.terraform').exists():
+ (directory / 'init.log').write_text(run('init', '-backend=false', '-input=false', '-no-color'))
+ test = module / 'tests/group_user_data.tftest.hcl'
+ original = test.read_text().split('run "oversize_user_data"')[0]
+ result = []
+ try:
+ for label, content in [('dev', original), ('witness', original.replace('deployment = "dev"',
+ f'deployment = "{s["deployment"]}"').replace('pools = ["hapair"]',
+ 'pools = ["witness"]'))]:
+ test.write_text(content)
+ events = run('test', '-filter=tests/group_user_data.tftest.hcl', '-json', '-verbose')
+ (directory / f'{label}-plan.jsonl').write_text(events)
+ plans = [e['test_plan'] for line in events.splitlines() if (e := json.loads(line)).get('test_plan')
+ and e.get('@testrun') == 'real_dev_user_data']
+ require(len(plans) == 1, 'missing module plan')
+ resources = {r['address']: r['values'] for r in plans[0]['planned_values']['root_module']['resources']}
+ expressions = next(r['expressions'] for r in plans[0]['configuration']['root_module']['resources']
+ if r['address'] == 'aws_launch_template.group')
+ lt = configured_values(resources['aws_launch_template.group[0]'], expressions)
+ require(len(lt['user_data']) <= 13107, 'module encoded user-data cap')
+ raw = gzip.decompress(base64.b64decode(lt['user_data']))
+ (directory / f'{label}.sh').write_bytes(raw)
+ result.append((raw, lt))
+ finally:
+ shutil.copyfile(ROOT / 'infra/modules/region-host/tests/group_user_data.tftest.hcl', test)
+ diff = check_diff(result[0][0], result[1][0], s)
+ (directory / 'substitutions.diff').write_text(diff)
+ print(diff)
+ print('MODULE real-dev encoded bytes:', len(result[0][1]['user_data']), '/ 13107')
+ return result[1]
+
+
+def policy(s, kms_key):
+ parameter = f'arn:aws:ssm:{REGION}:{ACCOUNT}:parameter'
+ return {'Version': '2012-10-17', 'Statement': [
+ {'Effect': 'Allow', 'Action': ['ssm:GetParameter', 'ssm:GetParameters'],
+ 'Resource': [parameter + s['prefix'] + '/*', parameter + s['shared'] + '/*']},
+ {'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']},
+ {'Effect': 'Allow', 'Action': 's3:PutObject', 'Resource': f'arn:aws:s3:::{BUCKET}/' + s['evidence'] + '/*'},
+ ]}
+
+
+def seed(s, version):
+ 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_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')),
+ '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
+os.umask(0o077)
+print('WITNESS collector-start', flush=True)
+root=pathlib.Path('/var/lib/carlos-witness-@RUN@');root.mkdir(mode=0o700)
+redactions=[]
+host=pathlib.Path('/etc/carlos/host.env')
+if host.exists():
+ for line in host.read_text().splitlines():
+ if '=' in line:
+ k,v=line.split('=',1)
+ if 'KEY' in k or 'SECRET' in k or 'TOKEN' in k:
+ redactions.extend([v.strip().strip('"').strip("'")])
+def redact(text):
+ for value in redactions:
+ if value: text=text.replace(value,'[REDACTED]')
+ return text
+def command(args):
+ try:
+ p=subprocess.run(args,capture_output=True,text=True,timeout=20)
+ return dict(argv=args,rc=p.returncode,out=redact(p.stdout+p.stderr))
+ except Exception as e:return dict(argv=args,rc=255,out=str(e))
+e=dict(commands={},files={},mounts={},time=time.time())
+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),
+ 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'],
+ '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'],
+ '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'],
+ 'nft-check':['nft','-c','-f','/etc/nftables.conf'],
+ 'mount-units':['systemctl','is-active','data-instances.mount','run-carlos-instances.mount','run-carlos-logs.mount'],
+ 'selinux':['ls','-ld','/sys/fs/selinux'],
+ 'free':['free','-m'],
+ 'cloud-unit':['systemctl','show','cloud-final','-p','FragmentPath','-p','ExecStart'],
+}.items(): e['commands'][name]=command(args)
+for unit in @UNITS@:
+ for op,args in [('status',['systemctl','status',unit,'--no-pager']),
+ ('journal',['journalctl','-b','-u',unit,'--no-pager','-o','short-monotonic']),
+ ('show',['systemctl','show',unit,'-p','Restart','-p','ActiveState','-p','ExecMainStartTimestampMonotonic','-p','ExecMainStatus','-p','Result','-p','ExecStartPre','-p','RestrictAddressFamilies','-p','ReadWritePaths'])]:
+ 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)
+ 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('/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
+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)
+for name,path in [('cloud-init-output.log','/var/log/cloud-init-output.log'),('cloud-init.log','/var/log/cloud-init.log')]:
+ try:(root/name).write_text(redact(pathlib.Path(path).read_text(errors='replace')))
+ except OSError as ex:(root/name).write_text(str(ex))
+(root/'evidence.json').write_text(json.dumps(e,sort_keys=True,indent=2))
+archive=root/'evidence.tar.gz'
+with tarfile.open(archive,'w:gz') as tar:
+ for name in ['evidence.json','cloud-init-output.log','cloud-init.log']:tar.add(root/name,arcname=name)
+print('WITNESS collector-evidence files='+str(len(e['files']))+' commands='+str(len(e['commands'])),flush=True)
+upload=command(['aws','--region','eu-west-1','s3api','put-object','--bucket','carlos-dev-640012953448','--key','root-runner/p3b1-f4-witness/@RUN@/evidence.tar.gz','--body',str(archive)])
+print('WITNESS upload rc='+str(upload['rc']),flush=True)
+print('WITNESS collector-done',flush=True)
+'''
+
+
+def collector(s):
+ return COLLECTOR.replace('@RUN@', s['run']).replace('@MOUNTS@', repr(MOUNTS)).replace('@UNITS@', repr(UNITS)).encode()
+
+
+def user_data(script, collection):
+ 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'
+ 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(parts[1].get_payload(decode=True) == collection, 'collector 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
+
+
+def launch_input(lt, encoded, s):
+ # Fail on new configured attributes rather than silently omitting them.
+ supported = {'image_id', 'instance_type', 'metadata_options', 'block_device_mappings', 'network_interfaces',
+ 'monitoring', 'user_data', 'iam_instance_profile', 'tags', 'name', 'default_version',
+ 'update_default_version', 'description', 'name_prefix', 'tag_specifications'}
+ computed = {'id', 'arn', 'latest_version', 'tags_all', 'region'}
+ require(not {k for k, v in lt.items() if v not in (None, [], {}, '', False) and k not in supported | computed},
+ 'unmapped launch template attributes')
+ require(lt['image_id'] == AMI, 'AMI drift')
+ metadata = lt['metadata_options'][0]
+ require(metadata.get('http_tokens') == 'required' and metadata['http_put_response_hop_limit'] == 1, 'IMDS drift')
+ meta_names = {'http_endpoint': 'HttpEndpoint', 'http_tokens': 'HttpTokens',
+ 'http_put_response_hop_limit': 'HttpPutResponseHopLimit', 'http_protocol_ipv6': 'HttpProtocolIpv6',
+ 'instance_metadata_tags': 'InstanceMetadataTags'}
+ require(not {k for k,v in metadata.items() if v not in (None,'') and k not in meta_names}, 'metadata field drift')
+ ebs_names = {'volume_size': 'VolumeSize', 'volume_type': 'VolumeType', 'encrypted': 'Encrypted',
+ 'delete_on_termination': 'DeleteOnTermination', 'iops': 'Iops', 'throughput': 'Throughput',
+ 'kms_key_id': 'KmsKeyId', 'snapshot_id': 'SnapshotId'}
+ blocks = []
+ for block in lt['block_device_mappings']:
+ ebs = block['ebs'][0]
+ require(ebs['encrypted'] is True and ebs['delete_on_termination'] is True, 'EBS safety drift')
+ require(not {k for k,v in ebs.items() if v not in (None,'',[]) and k not in ebs_names}, 'EBS field drift')
+ require(not block.get('no_device') and not block.get('virtual_name'), 'unsupported block mapping')
+ blocks.append(dict(DeviceName=block['device_name'], Ebs={ebs_names[k]:v for k,v in ebs.items() if v is not None and v != ''}))
+ require(len(lt['network_interfaces']) == 1, 'network interface count')
+ network = lt['network_interfaces'][0]
+ require(network['associate_public_ip_address'] is True and network['delete_on_termination'] is True, 'public IPv4 required')
+ allowed_net = {'associate_public_ip_address','delete_on_termination','security_groups','device_index'}
+ require(not {k for k,v in network.items() if v not in (None,[],{},'',False,0) and k not in allowed_net}, 'network field drift')
+ tags = dict(lt.get('tags') or {}, purpose='p3b1-f4-witness', Name=s['role'], witness_run=s['run'])
+ result = dict(ImageId=lt['image_id'], InstanceType=lt['instance_type'], MinCount=1, MaxCount=1,
+ ClientToken=s['role'], UserData=encoded, IamInstanceProfile={'Name':s['role']},
+ MetadataOptions={meta_names[k]:v for k,v in metadata.items() if v is not None and v != ''},
+ BlockDeviceMappings=blocks,
+ NetworkInterfaces=[dict(DeviceIndex=0, SubnetId=SUBNET, Groups=[SG], AssociatePublicIpAddress=True,
+ DeleteOnTermination=network['delete_on_termination'])],
+ TagSpecifications=[dict(ResourceType=kind, Tags=[dict(Key=k,Value=v) for k,v in tags.items()])
+ for kind in ('instance','volume')])
+ if lt.get('monitoring'):
+ result['Monitoring'] = {'Enabled': lt['monitoring'][0]['enabled']}
+ return result
+
+
+class 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']
+ 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]}')
+ return json.loads(p.stdout or '{}')
+
+
+def assertions(e):
+ files=e.get('files',{}); cmds=e.get('commands',{})
+ out=lambda k:cmds.get(k,{}).get('out','')
+ rc=lambda k:cmds.get(k,{}).get('rc',255)
+ exists=lambda k:bool(files.get(k))
+ ordered=['/etc/carlos/group-identity.json','/etc/carlos/region-config.json','/etc/carlos/group.json',
+ '/etc/carlos/group-ingress.json','/etc/nftables.conf','/etc/carlos/host.env']
+ times=[files.get(k,{}).get('mtime',0) if files.get(k) else 0 for k in ordered]
+ return [
+ ('W1 exec mount', not e.get('mounts',{}).get('/var/lib/carlos-group-boot',{'noexec':True})['noexec'], 'findmnt + statvfs'),
+ ('W2 identity verified before ingress', exists(ordered[3]) and all(times[:4]) and times[:4]==sorted(times[:4]), 'exclusive writes after identity verifier'),
+ ('W3 immutable records', all(exists(k) for k in ordered[:4]), 'group identity/region/marker/ingress'),
+ ('W4 hairpin installed', rc('nft')==0 and all(x in out('nft') for x in ('carlos_group_imds','carlos_hairpin')), out('nft')[:200]),
+ ('W5 dormant nft persisted', rc('nft-persist')==0 and all(x in out('nft-persist') for x in ('carlos_group_imds','carlos_hairpin')), out('nft-persist')[:200]),
+ ('W6 host.env installed', exists('/etc/carlos/host.env') and files['/etc/carlos/host.env']['mode']=='0o600' and files['/etc/carlos/host.env']['uid']==0, 'metadata only; values omitted'),
+ ('W7 Restart=no', 'Restart=no\n' in out('carlos-edge-show'), out('carlos-edge-show')[:250]),
+ ('W8 edge ran', bool(re.search(r'ExecMainStartTimestampMonotonic=[1-9][0-9]*',out('carlos-edge-show'))), out('carlos-edge-show')[:250]),
+ ('W9 publication denied', bool(re.search(r'agent: edges file pass failed[^\n]*AccessDenied', out('carlos-edge-journal'))) and 'tenant admission is open' not in out('carlos-edge-journal'), out('carlos-edge-journal')[-500:]),
+ ('W10 work dir removed', '/var/lib/carlos-group-boot' in files and files['/var/lib/carlos-group-boot'] is None and exists('/etc/carlos/host.env'), 'final cleanup after start'),
+ ('W11 sysctl', all(f'net.ipv4.conf.{axis}.arp_{name} = {value}' in out('sysctl') for axis in ('all','default') for name,value in [('ignore',1),('announce',2)]), out('sysctl')),
+ ('W12 AMI tools', rc('tools')==0 and 'Python 3.13' in out('tools') and 'aws-cli/2.' in out('tools'), out('tools')),
+ ('W13 MAC policy', rc('mac-denials') in (0,1) and not re.search(r'apparmor="DENIED"|avc:.*denied',out('mac-denials')), out('mac-denials')),
+ ('W14 installed binary', exists('/opt/carlos/carlos'), 'reset ExecStart path'),
+ ('W15 clock', rc('chrony')==0 and bool(re.search(r'\^[*+]\s+169\.254\.169\.123',out('chrony'))), out('chrony')),
+ ('W16 write order', all(times) and times==sorted(times), 'identity -> region -> marker -> ingress -> nft persist -> host.env'),
+ ('W17 executable install paths', all(p in e.get('mounts',{}) and not e['mounts'][p]['noexec'] for p in ('/opt','/var/lib/cloud')), 'statvfs for /opt and cloud-init'),
+ ('W18 system user', rc('user')==0 and bool(re.search(r'^carlos:[^:]*:[0-9]+:[0-9]+:[^:]*:/data:/usr/sbin/nologin',out('user'))), out('user')),
+ ('W19 mount units', rc('mount-units')==0 and out('mount-units').splitlines()==['active']*3, out('mount-units')),
+ ('W20 reset unit', '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')),
+ ('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))
+
+
+def baseline(aws, iid=None):
+ observed={}
+ 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')
+ return observed
+
+
+def cleanup(aws, s):
+ leaked=[]
+ def attempt(label, service, operation, **args):
+ try:return aws(service,operation,**args)
+ 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>')
+ 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')
+ break
+ require(time.monotonic()<deadline,'collector deadline')
+ time.sleep(10)
+ after=baseline(aws,iid)
+ require(before==after,'target/edges changes during witness')
+
+
+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.')
+ 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')
+ 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)
diff --git a/scripts/region_group_boot_witness_test.py b/scripts/region_group_boot_witness_test.py
new file mode 100644
index 000000000..241dcbc75
--- /dev/null
+++ b/scripts/region_group_boot_witness_test.py
@@ -0,0 +1,101 @@
+import base64
+import copy
+import email.policy
+from email.parser import BytesParser
+import gzip
+import importlib.util
+import json
+from pathlib import Path
+import unittest
+from unittest.mock import patch
+
+spec = importlib.util.spec_from_file_location('witness', Path(__file__).with_name('region-group-boot-witness.py'))
+w = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(w)
+
+
+class WitnessTests(unittest.TestCase):
+ def setUp(self):
+ self.s = w.scope('test-01')
+
+ def test_scope_refuses_escape_and_overlong(self):
+ for bad in ('../ie', '', 'A', 'x/y', 'x'*33, 'x;id', 'a\n'):
+ with self.subTest(bad=bad), self.assertRaises(ValueError): w.scope(bad)
+ self.assertNotIn('/carlos/dev', self.s['prefix'])
+ self.assertNotIn('bootstrap/dev', self.s['key'])
+
+ def test_exact_substitutions_and_tamper_refusal(self):
+ config = json.loads((w.ROOT/'scripts/testdata/region-group-plan/dev-boot-config.json').read_text())
+ dev = w.plain_render(config)
+ witness = w.plain_render(w.witness_config(config,self.s))
+ diff = w.check_diff(dev,witness,self.s)
+ self.assertIn("+CARLOS_POOLS='witness'",diff)
+ self.assertEqual(sum(line.startswith('+CARLOS_') for line in diff.splitlines()),5)
+ for changed in (witness+b'echo bypass\n',witness.replace(b'Restart=no',b'Restart=always')):
+ with self.assertRaises(ValueError): w.check_diff(dev,changed,self.s)
+
+ def test_mime_first_part_byte_identical(self):
+ source=b'#!/bin/sh\necho byte-identical\n'
+ encoded=w.user_data(source,w.collector(self.s))
+ parts=list(BytesParser(policy=email.policy.default).parsebytes(gzip.decompress(base64.b64decode(encoded))).iter_parts())
+ self.assertEqual(parts[0].get_payload(decode=True),source)
+ self.assertEqual(parts[1].get_payload(decode=True),w.collector(self.s))
+ self.assertEqual(parts[0].get_content_type(),'text/x-shellscript')
+ compile(w.collector(self.s),'collector','exec')
+ with self.assertRaises(ValueError):w.user_data(bytes(range(256))*100 + __import__('random').Random(5).randbytes(30000),b'x')
+
+ def test_policy_has_no_extra_authority(self):
+ statements=w.policy(self.s,'arn:aws:kms:eu-west-1:640012953448:key/test')['Statement']
+ actions=set()
+ for row in statements:
+ actions.update([row['Action']] if isinstance(row['Action'],str) else row['Action'])
+ self.assertNotIn('/carlos/dev/',json.dumps(row))
+ self.assertNotIn('bootstrap/dev/',json.dumps(row))
+ self.assertEqual(actions,{'ssm:GetParameter','ssm:GetParameters','kms:Decrypt','s3:GetObject','s3:GetObjectVersion','s3:PutObject'})
+ write=next(s for s in statements if s['Action']=='s3:PutObject')
+ self.assertEqual(write['Resource'],f'arn:aws:s3:::{w.BUCKET}/'+self.s['evidence']+'/*')
+ self.assertTrue(w.LIVE_BLOCKERS) # no false claim this policy can complete install
+
+ def test_seed_random_and_scratch_only(self):
+ a,b=w.seed(self.s,'version'),w.seed(self.s,'version')
+ self.assertEqual(len(a),20)
+ self.assertTrue(all(k.startswith(self.s['prefix']+'/') for k in a))
+ self.assertNotEqual(a[self.s['prefix']+'/CARLOS_SECRETS_KEY'],b[self.s['prefix']+'/CARLOS_SECRETS_KEY'])
+ self.assertEqual(json.loads(a[self.s['prefix']+'/boot/bootstrap-object'])['floor'],'required')
+ self.assertEqual(a[self.s['prefix']+'/CARLOS_HA_FIXED_BOX_IDENTITIES'],'{}')
+
+ def test_mock_computed_attributes_cannot_reach_launch(self):
+ values={'metadata_options':[{'http_tokens':'required','http_protocol_ipv6':'random-mock'}],
+ 'block_device_mappings':[{'ebs':[{'encrypted':'true','throughput':0}]}], 'arn':'random-mock'}
+ expr={'metadata_options':[{'http_tokens':{'constant_value':'required'}}],
+ 'block_device_mappings':[{'ebs':[{'encrypted':{'constant_value':True}}]}]}
+ actual=w.configured_values(values,expr)
+ self.assertEqual(actual,{'metadata_options':[{'http_tokens':'required'}],
+ 'block_device_mappings':[{'ebs':[{'encrypted':True}]}]})
+
+ def test_launch_uses_module_fields_and_rejects_new_authority(self):
+ lt=dict(image_id=w.AMI,instance_type='t4g.micro',metadata_options=[dict(http_tokens='required',http_endpoint='enabled',http_put_response_hop_limit=1)],
+ block_device_mappings=[dict(device_name='/dev/xvda',ebs=[dict(volume_size=20,volume_type='gp3',encrypted=True,delete_on_termination=True)])],
+ network_interfaces=[dict(associate_public_ip_address=True,delete_on_termination=True,security_groups=['original'])],tags={})
+ result=w.launch_input(lt,'encoded',self.s)
+ self.assertEqual(result['BlockDeviceMappings'][0]['Ebs']['VolumeSize'],20)
+ self.assertEqual(result['NetworkInterfaces'][0]['Groups'],[w.SG])
+ self.assertEqual(result['MinCount'],result['MaxCount']);self.assertEqual(result['MaxCount'],1)
+ self.assertNotIn('Monitoring',result)
+ for change in ({'image_id':'wrong'},{'key_name':'root-login'},{'disable_api_termination':True}):
+ with self.assertRaises(ValueError):w.launch_input(dict(lt,**change),'encoded',self.s)
+ bad=copy.deepcopy(lt);bad['block_device_mappings'][0]['ebs'][0]['encrypted']='false'
+ with self.assertRaises(ValueError):w.launch_input(bad,'encoded',self.s)
+
+ def test_empty_evidence_cannot_pass(self):
+ rows=w.assertions({})
+ self.assertGreaterEqual(len(rows),16)
+ self.assertFalse(any(row[1] for row in rows))
+
+ def test_dry_aws_never_spawns(self):
+ with patch.object(w.subprocess,'run',side_effect=AssertionError('AWS process')):
+ w.AWS(dry=True)('ec2','run-instances',UserData='abc')
+ self.assertEqual(w.cleanup(w.AWS(dry=True),self.s),[])
+
+
+if __name__=='__main__':unittest.main()