"""Inspect runtime security flags and the configured worker limits.""" import json import os import subprocess COMPOSE = ['docker', 'compose', '--env-file', os.getenv('COMPOSE_ENV_FILE', '.env')] RESTRICTED = ( 'api', 'publisher', 'worker', 'lb', 'collector-tls', 'loki-tls', 'tempo-tls', 'prometheus-tls', 's3', 'otel-collector', 'prometheus', 'loki', 'tempo', 'grafana', ) BOOTSTRAP = ('migrate', 's3-bootstrap', 'db-permissions') ROOT_ENTRYPOINTS = ('openbao', 'postgres', 'redis', 'broker') def output(*args): return subprocess.check_output(args, text=True).strip() def main(): for service in (*RESTRICTED, *BOOTSTRAP, *ROOT_ENTRYPOINTS): flags = ('--all',) if service in BOOTSTRAP else () containers = output(*COMPOSE, 'ps', '-q', *flags, service).splitlines() assert len(containers) == (2 if service == 'api' else 1), f'{service}: wrong replica count' for container in containers: data = json.loads(output('docker', 'inspect', '--format', '{{json .HostConfig}}', container)) assert 'no-new-privileges:true' in data['SecurityOpt'], service assert not data['Privileged'] and data['NetworkMode'] != 'host', service if service not in ROOT_ENTRYPOINTS: tmp = (data['Tmpfs'] or {}).get('/tmp', '').split(',') assert data['ReadonlyRootfs'] and {'rw', 'nosuid', 'nodev', 'noexec'} <= set(tmp), service assert 'ALL' in data['CapDrop'], service allowed = {'DAC_OVERRIDE'} if service in ('loki', 'tempo') else set() added = {capability.removeprefix('CAP_') for capability in data['CapAdd'] or ()} assert added == allowed, service if service in BOOTSTRAP: state = output('docker', 'inspect', '--format', '{{.State.Status}} {{.State.ExitCode}}', container) assert state == 'exited 0', service if service in ('api', 'publisher', 'worker'): assert int(output('docker', 'exec', container, 'id', '-u')) != 0, service if service == 'worker': assert data['NanoCpus'] == 1_000_000_000 assert data['Memory'] == 768 * 1024 * 1024 code = ( "from app.config import load_settings; " "assert load_settings().job_timeout_seconds == 60" ) output(*COMPOSE, 'exec', '-T', 'worker', 'python', '-c', code) print('PASS: runtime root filesystems, tmpfs, privileges and worker limits (1 CPU, 768 MiB, 60 s)') if __name__ == '__main__': main()