Check rendered kustomize output in the deploy policy (M9.8f review)

The policy check now renders every overlay with pinned, checksum-verified
kustomize v5.8.1 (ADR-0088) and validates effective namespaces, session/input/
listener environment and arguments, ports, Services, quotas, policies, Ingresses
and Secrets, so inline/JSON patches and namespace changes cannot bypass it.
Route enabling is gated on an ADR-0087 amendment with tested server windows, route
addresses must be RFC 1918 or explicitly approved, and the Local health-check node
port is documented with its enabling evidence. Self-test grows to 33 cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-02 18:02:57 -04:00
co-authored by Claude Opus 5.5
parent 9f622cf6b3
commit 8a1e5ef53d
12 changed files with 386 additions and 32 deletions
+146 -9
View File
@@ -28,10 +28,31 @@ environment-isolation or World0-protection invariant is broken:
- the dev session route (ADR-0087): loopback listener everywhere except the
evolution-dev route component; that component is the only LoadBalancer and the
only Service on the session port, narrowly shaped, and it cannot be enabled while
markers are unresolved or before server-enforced session windows exist.
markers are unresolved or before server-enforced session windows exist;
- rendered output (ADR-0088): every overlay is built with the pinned kustomize and
the effective objects are checked (namespaces, listener/session/input environment,
arguments, ports, Services, quotas, policies, Ingresses, Secrets), so inline or
JSON patches and namespace transformations cannot bypass the source checks.
"""
import ipaddress
import re
# Enabling the dev session route needs ADR-0087 to be amended with the implemented
# session-window argument contract and runtime expiry tests (expiry during a session,
# restart after expiry, delayed application, extend/close races, clock movement,
# synthetic inputs stopping while commits drain). Until then this stays False; a
# string such as --session-window in a manifest is not proof of enforcement.
ROUTE_ENABLING_PERMITTED = False
# Addresses the route may use: RFC 1918 plus internal ranges the maintainer has
# explicitly approved in ADR-0087 (none yet; the cluster LAN 172.10.0.0/16 is not
# RFC 1918 and needs that approval before use).
APPROVED_INTERNAL = []
INTERNAL = [ipaddress.ip_network(n) for n in ('10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16')] + \
[ipaddress.ip_network(n) for n in APPROVED_INTERNAL]
def internal(network):
return any(network.version == r.version and network.subnet_of(r) for r in INTERNAL)
import os
import shutil
import subprocess
@@ -315,7 +336,9 @@ for path, doc in objects:
check(len(route_ranges) >= 1, f'{path}: loadBalancerSourceRanges must name the permitted CIDRs')
if not vip.startswith('REPLACE'):
try:
check(ipaddress.ip_address(vip).is_private, f'{path}: the VIP must be an internal address')
address = ipaddress.ip_address(vip)
check(internal(ipaddress.ip_network(f'{address}/{address.max_prefixlen}')),
f'{path}: the VIP must be an internal address (RFC 1918 or approved in ADR-0087)')
except ValueError:
check(False, f'{path}: the VIP must be one IP address')
for cidr in route_ranges:
@@ -323,7 +346,7 @@ for path, doc in objects:
continue
try:
network = ipaddress.ip_network(cidr)
check(network.is_private and network.prefixlen >= (16 if network.version == 4 else 48),
check(internal(network) and network.prefixlen >= (16 if network.version == 4 else 48),
f'{path}: {cidr} must be a private range no wider than /16 (IPv6 /48)')
except ValueError:
check(False, f'{path}: {cidr} is not a CIDR')
@@ -354,11 +377,9 @@ if route_enabled:
for name in os.listdir(os.path.join(ROOT, ROUTE)):
with open(os.path.join(ROOT, ROUTE, name), encoding='utf-8') as handle:
check('REPLACE' not in handle.read(), f'{ROUTE}{name}: unresolved REPLACE marker with the route enabled')
base_script = ' '.join(' '.join(c.get('args', [])) for p, d in objects
if p == 'deploy/kubernetes/region/base/deployment.yaml' and d['kind'] == 'Deployment'
for c in d['spec']['template']['spec']['containers'])
check('--session-window' in base_script,
'the dev session route needs server-enforced session windows (--session-window, ADR-0087)')
check(ROUTE_ENABLING_PERMITTED,
'the dev session route cannot be enabled until ADR-0087 records the implemented, tested '
'server-enforced session windows')
dev_quota = [d.get('spec', {}).get('hard', {}).get('services.loadbalancers') for p, d in objects
if d['kind'] == 'ResourceQuota' and p.startswith(f'{platform}/dev/')]
check(dev_quota == ['1'], 'the dev quota must allow exactly one LoadBalancer for the route')
@@ -541,7 +562,123 @@ for tool, args, component in generators:
f'{tool}: component {component} must be admitted by the database egress policy')
check(pod['metadata'].get('namespace') == 'evolution-dev', f'{tool}: renders into its environment')
# ADR-0088: the effective configuration is what kustomize renders. Every overlay is
# built with the pinned binary and its output checked, independent of how patches,
# components or namespace transformations produced it.
def kustomize_binary():
with open(os.path.join(ROOT, 'tools', 'ci', 'prepare-kustomize.sh'), encoding='utf-8') as f:
version = re.search(r'^version=(v[0-9.]+)$', f.read(), re.M).group(1)
candidates = [os.environ.get('KUSTOMIZE', ''),
os.path.join(ROOT, '.cache', 'tools', f'kustomize-{version}', 'kustomize'),
shutil.which('kustomize') or '']
for candidate in candidates:
if candidate and os.path.isfile(candidate):
reported = subprocess.run([candidate, 'version'], capture_output=True, text=True).stdout.strip()
if reported == version:
return candidate
return None
SUPPORTED_KEYS = {'apiVersion', 'kind', 'namespace', 'resources', 'components', 'patches', 'images',
'labels', 'commonAnnotations', 'commonLabels', 'configMapGenerator', 'generatorOptions'}
for path, ds in manifests.items():
if path.endswith('kustomization.yaml') and ds:
unsupported = set(ds[0]) - SUPPORTED_KEYS
check(not unsupported, f'{path}: unsupported kustomize features {sorted(unsupported)} (ADR-0088)')
EXPECTED_NAMESPACE = {'deploy/kubernetes/dev': 'evolution-dev', 'deploy/kubernetes/stage': 'evolution-stage',
'deploy/kubernetes/monitoring': 'aevolution-monitoring'}
for env in ('dev', 'stage', 'world0'):
for component in ('platform', 'region', 'stores'):
EXPECTED_NAMESPACE[f'deploy/kubernetes/{component}/{env}'] = f'evolution-{env}'
EXPECTED_NAMESPACE['deploy/kubernetes/platform/monitoring'] = 'aevolution-monitoring'
CLUSTER_KINDS = {'Namespace', 'StorageClass', 'ValidatingAdmissionPolicy', 'ValidatingAdmissionPolicyBinding',
'ClusterRole', 'ClusterRoleBinding', 'PersistentVolume'}
binary = kustomize_binary()
check(binary is not None, 'the pinned kustomize is required: run tools/ci/prepare-kustomize.sh (ADR-0088)')
renders = {}
if binary:
for path, ds in sorted(manifests.items()):
if not path.endswith('kustomization.yaml') or not ds or ds[0].get('kind') == 'Component':
continue
overlay = os.path.dirname(path)
result = subprocess.run([binary, 'build', os.path.join(ROOT, overlay)], capture_output=True, text=True)
check(result.returncode == 0, f'{overlay}: kustomize build failed: {result.stderr.strip()[:300]}')
if result.returncode == 0:
renders[overlay] = [d for d in yaml.safe_load_all(result.stdout) if isinstance(d, dict)]
for overlay, docs in renders.items():
expected = EXPECTED_NAMESPACE.get(overlay)
route_services = [d for d in docs if d['kind'] == 'Service' and d['metadata']['name'] == 'evo-region-session']
route_active = bool(route_services)
for doc in docs:
kind, name = doc['kind'], doc['metadata'].get('name', '')
namespace = doc['metadata'].get('namespace')
where = f'{overlay} (rendered) {kind}/{name}'
if expected and kind not in CLUSTER_KINDS:
check(namespace == expected, f'{where}: renders into {namespace}, expected {expected}')
check(kind != 'Secret', f'{where}: rendered Secrets never come from Git')
if kind == 'Deployment' and name == 'evo-region':
pod = doc['spec']['template']['spec']
for container in pod.get('containers', []) + pod.get('initContainers', []):
env = {v.get('name'): v.get('value') for v in container.get('env', [])}
text = ' '.join(container.get('command', []) + container.get('args', []))
if container.get('name') == 'evo-server':
check(env.get('REGION_SESSION') == '' and env.get('REGION_INPUTS') == '',
f'{where}: sessions and synthetic inputs stay off in Git')
listen = '0.0.0.0:7400' if route_active else '127.0.0.1:7400'
check(env.get('REGION_SESSION_LISTEN') == listen,
f'{where}: REGION_SESSION_LISTEN must be {listen} (route {"on" if route_active else "off"})')
check(text.count('--session-listen') == 1 and '--session-listen "$REGION_SESSION_LISTEN"' in text,
f'{where}: one session listener, addressed only by REGION_SESSION_LISTEN')
else:
check('--session-listen' not in text and '--synthetic-inputs' not in text,
f'{where}: only evo-server may listen for sessions')
ports = sorted((p.get('name'), p.get('containerPort')) for p in container.get('ports', []))
allowed = [('ops', 9100), ('session', 7400)] if route_active else [('ops', 9100)]
if container.get('name') == 'evo-server':
check(ports == sorted(allowed), f'{where}: container ports must be {allowed}')
if kind == 'Service':
spec = doc['spec']
session = any(p.get('port') == 7400 or p.get('targetPort') in (7400, 'session')
for p in spec.get('ports', []))
if name == 'evo-region-session':
check(namespace == 'evolution-dev' and spec.get('type') == 'LoadBalancer'
and spec.get('externalTrafficPolicy') == 'Local'
and spec.get('allocateLoadBalancerNodePorts') is False
and spec.get('ports') == [{'name': 'session', 'port': 7400, 'targetPort': 'session',
'protocol': 'TCP'}],
f'{where}: the route keeps its reviewed shape in evolution-dev')
else:
check(spec.get('type', 'ClusterIP') == 'ClusterIP' and not session,
f'{where}: only the route may be a LoadBalancer or expose the session port')
if kind == 'Ingress':
check('7400' not in yaml.safe_dump(doc) and 'session' not in yaml.safe_dump(doc),
f'{where}: the dev session is never an Ingress')
if kind == 'NetworkPolicy':
for rule in doc['spec'].get('ingress', []):
if any(p.get('port') == 7400 for p in rule.get('ports', [])):
ranges = route_services[0]['spec'].get('loadBalancerSourceRanges', []) if route_services else []
blocks = [peer.get('ipBlock', {}) for peer in rule.get('from', [])]
check(name == 'evo-region-session-ingress' and route_active and blocks
and all(set(b) == {'cidr'} for b in blocks) and len(blocks) == len(rule.get('from', []))
and sorted(b['cidr'] for b in blocks) == sorted(ranges),
f'{where}: only the route policy admits TCP 7400, from exactly its source ranges')
if kind == 'ResourceQuota':
hard = doc['spec'].get('hard', {})
check(hard.get('services.nodeports') == '0', f'{where}: node ports stay forbidden')
limit = ('0', '1') if namespace == 'evolution-dev' and route_enabled else ('0',)
check(hard.get('services.loadbalancers') in limit,
f'{where}: LoadBalancers only in evolution-dev with the enabled route')
if route_active:
check(overlay in ('deploy/kubernetes/region/dev', 'deploy/kubernetes/dev'),
f'{overlay}: renders the dev session route outside evolution-dev')
check(ROUTE_ENABLING_PERMITTED,
f'{overlay}: renders the dev session route, which cannot be enabled until ADR-0087 records '
'the implemented, tested server-enforced session windows')
check('REPLACE' not in yaml.safe_dump_all(docs), f'{overlay}: unresolved REPLACE marker in the rendered route')
for message in failures:
print('FAIL', message)
print(f'deploy policy: {len(objects)} objects in {len(manifests)} files, {len(failures)} failures')
print(f'deploy policy: {len(objects)} objects in {len(manifests)} files, '
f'{sum(len(d) for d in renders.values())} rendered objects in {len(renders)} overlays, {len(failures)} failures')
sys.exit(1 if failures else 0)