Files
mtusi2026lab7/tests/hardening.py
T

28 lines
1.9 KiB
Python

"""Sanitized Docker policy and secret-boundary audit, host operator only."""
import json,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['./scripts/compose.sh','ps','-q'],text=True).split()
rows=[]
for item in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
h=item['HostConfig'];c=item['Config'];role=c['Labels']['com.docker.compose.service']
assert not h['Privileged'] and h['NetworkMode']!='host'
assert h['NanoCpus']>0 and h['Memory']>0
assert 'ALL' in (h['CapDrop'] or [])
assert any('no-new-privileges' in s for s in h['SecurityOpt'])
assert not any('docker.sock' in m['Source'] for m in item['Mounts'])
if role!='db-engine':assert h['ReadonlyRootfs'] and c['User'].split(':')[0] not in ('','0')
if role in ['api','worker','publisher','observer','janitor']:
assert all(not e.startswith(('DATABASE_URL=','S3_SECRET_ACCESS_KEY=','BROKER_URL=','CACHE_URL=')) for e in c['Env'])
sources=[m['Source'] for m in item['Mounts']]
assert not any('bao-operator' in s or 'operator-env' in s or s.endswith('ca.key') for s in sources)
assert sum('/.secrets/roles/' in s for s in sources)==1
if role=='db-engine':
proc=subprocess.check_output(['docker','exec',item['Id'],'cat','/proc/1/status'],text=True)
uid=int(next(x for x in proc.splitlines() if x.startswith('Uid:')).split()[1]);assert uid==70
if role=='api':assert not h['PortBindings']
for mappings in (h['PortBindings'] or {}).values():
for p in mappings or []:assert p['HostIp']=='127.0.0.1'
rows.append({'service':role,'non_root':c['User'] not in ('','0','0:0'),'read_only':h['ReadonlyRootfs'],'drop_all':True,'no_new_privileges':True,'cpu_limit':h['NanoCpus']/1e9,'memory_mib':h['Memory']//1048576})
print(json.dumps({'status':'PASS','containers':rows,'stateful_exception':'Postgres entrypoint root with only CHOWN,DAC_OVERRIDE,FOWNER,SETUID,SETGID; postgres daemon drops to UID 70'},indent=2))