Files
mtusi2026lab4/scripts/container-checks.py

233 lines
12 KiB
Python
Executable File

#!/usr/bin/env python3
"""Lab4 infrastructure evidence from actual Docker state, not compose.yaml.
Checks:
* at least two API processes with distinct container ids and hostnames;
* only HAProxy is published, on 127.0.0.1, and API/S3/admin ports are not;
* API is non-root, read-only, cap-drop ALL, no state volume; S3 has its data volume;
* every stand service has CPU and memory limits; named volumes use the lab prefix;
* the API S3 identity is bucket-scoped and differs from the admin identity,
and the admin identity is never present in an API container;
* the bucket bootstrap is idempotent (second run reports created=false);
* an anonymous S3 GET/list outside the API is denied;
* one session is served by both API replicas through the LB.
Python 3.9+, standard library only. Requires the running stand and Docker.
Writes evidence/container-checks.json and .txt.
"""
import json
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
def docker_exec(container, *args):
return subprocess.run(['docker', 'exec', container] + list(args),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def wait_exited(container, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
state = M.inspect(container).get('State', {})
if state.get('Status') == 'exited':
return state.get('ExitCode')
time.sleep(0.5)
raise RuntimeError('container did not exit: ' + container)
def main():
args = arguments('Lab4 container, S3 privacy and credential checks')
checks = {}
failures = []
compose_text = (ROOT / 'compose.yaml').read_text()
checks['no_container_name_in_compose'] = not re.search(r'^\s*container_name\s*:', compose_text, re.MULTILINE)
images = re.findall(r'^\s*image:\s*(\S+)', compose_text, re.MULTILINE)
third_party = [image for image in images if not image.startswith('${API_IMAGE')]
checks['third_party_images_pinned_by_digest'] = all('@sha256:' in image for image in third_party)
checks['third_party_images'] = third_party
api = M.containers('api')
lb = M.containers('lb')
postgres = M.containers('postgres')
valkey = M.containers('valkey')
s3 = M.containers('s3')
check(len(api) >= 2, 'expected at least two API containers')
check(len(lb) == 1 and len(postgres) == 1 and len(valkey) == 1 and len(s3) == 1,
'expected one LB, PostgreSQL, Valkey and S3 container')
checks['api_replica_count'] = len(api)
checks['api_container_ids_distinct'] = len({item['container_id'] for item in api}) == len(api)
checks['api_hostnames_distinct'] = len({item['hostname'] for item in api}) == len(api)
checks['api_image_ids'] = sorted({item['image_id'] for item in api})
checks['s3_image_id'] = s3[0]['image_id']
checks['git_revision'] = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
api_ports = {item['name']: M.run(['docker', 'port', item['container_id']]).stdout.strip() for item in api}
s3_ports = M.run(['docker', 'port', s3[0]['container_id']]).stdout.strip()
lb_ports = M.run(['docker', 'port', lb[0]['container_id']]).stdout.strip()
checks['api_ports'] = api_ports
checks['s3_published_ports'] = s3_ports
checks['lb_ports'] = lb_ports
checks['api_has_no_published_ports'] = all(value == '' for value in api_ports.values())
checks['s3_has_no_published_ports'] = s3_ports == ''
checks['lb_published_loopback_only'] = ('127.0.0.1:' in lb_ports and '8080' in lb_ports)
limits = {}
for service, items in (('api', api), ('postgres', postgres), ('valkey', valkey), ('s3', s3), ('lb', lb)):
rows = []
for item in items:
data = M.inspect(item['container_id'])
host = data.get('HostConfig', {})
rows.append({
'name': item['name'],
'nano_cpus': host.get('NanoCpus'),
'memory_bytes': host.get('Memory'),
'readonly_rootfs': host.get('ReadonlyRootfs'),
'cap_drop': host.get('CapDrop'),
'security_opt': host.get('SecurityOpt'),
'user': data.get('Config', {}).get('User'),
'mounts': [mount.get('Name') or mount.get('Source') for mount in data.get('Mounts', [])],
'volume_mounts': [mount.get('Name') for mount in data.get('Mounts', [])
if mount.get('Type') == 'volume'],
})
limits[service] = rows
checks['limits'] = limits
checks['all_services_have_cpu_and_memory_limits'] = all(
row['nano_cpus'] and row['memory_bytes']
for rows in limits.values() for row in rows)
checks['api_non_root'] = all((row['user'] or '').startswith('10001') for row in limits['api'])
checks['api_read_only_rootfs'] = all(row['readonly_rootfs'] for row in limits['api'])
checks['api_cap_drop_all'] = all(row['cap_drop'] == ['ALL'] for row in limits['api'])
checks['api_no_new_privileges'] = all(
any('no-new-privileges' in value for value in (row['security_opt'] or []))
for row in limits['api'])
checks['api_has_no_state_volume'] = all(not row['mounts'] for row in limits['api'])
checks['s3_has_data_volume'] = any(
row['volume_mounts'] and all(name.startswith(M.PROJECT + '-') for name in row['volume_mounts'])
for row in limits['s3'])
volume_names = set()
for item in postgres + valkey + s3:
for mount in M.inspect(item['container_id']).get('Mounts', []):
if mount.get('Type') == 'volume':
volume_names.add(mount.get('Name'))
checks['named_volumes'] = sorted(volume_names)
checks['volumes_have_prefix'] = all(name.startswith(M.PROJECT + '-') for name in volume_names)
# S3 credentials: the API must not receive the administrative identity and
# must fail on a bucket outside its grant.
api_env = api[0]['env']
s3_init = M.compose('ps', '-a', '-q', 's3-init').stdout.strip()
check(s3_init != '', 's3-init container is missing')
init_env = M.inspect(s3_init).get('Config', {}).get('Env', [])
admin_access = ''
for item in init_env:
if item.startswith('S3_ADMIN_ACCESS_KEY='):
admin_access = item.split('=', 1)[1]
checks['api_s3_access_key_present'] = bool(api_env.get('S3_ACCESS_KEY'))
checks['api_s3_secret_present'] = bool(api_env.get('S3_SECRET_KEY'))
checks['api_credentials_differ_from_admin'] = (
bool(admin_access) and api_env.get('S3_ACCESS_KEY') != admin_access)
checks['api_has_no_admin_credentials'] = not any(
key.startswith('S3_ADMIN_') for key in api_env)
buckets = M.s3ctl('-op', 'list', '-prefix', '').stdout
checks['api_credentials_can_list_own_bucket'] = '"objects"' in buckets
other = M.s3ctl('-op', 'list', '-prefix', '', '-bucket', 'definitely-not-granted', check=False)
checks['api_credentials_denied_other_bucket'] = other.returncode != 0
# Bucket bootstrap is idempotent: run the same one-shot container again.
first = M.run(['docker', 'start', '-a', s3_init.strip()], check=False)
code = wait_exited(s3_init.strip())
logs = M.run(['docker', 'logs', '--tail', '5', s3_init.strip()]).stdout + M.run(
['docker', 'logs', '--tail', '5', s3_init.strip()]).stderr
checks['bucket_bootstrap_second_run_exit'] = code
checks['bucket_bootstrap_second_run_created_false'] = '"created":false' in logs
checks['bucket_bootstrap_second_run_verified'] = '"verified":true' in logs
# Anonymous access outside the API must not return an object or a listing.
alice, bob, eve, chat = Client(args.base_url, args.ca_file).bootstrap()
attachment, content = Client(args.base_url, args.ca_file).attachment(alice, chat)
object_key = M.psql(
"SELECT object_key FROM attachments WHERE id = '%s'" % attachment['id'])
bucket = api_env.get('S3_BUCKET', '')
check(bucket and object_key, 'cannot resolve bucket/object key for the privacy probe')
anonymous_object = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '/' + object_key)
anonymous_list = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '?list-type=2')
checks['anonymous_object_get_status'] = anonymous_object.stderr + anonymous_object.stdout
checks['anonymous_object_get_denied'] = (
anonymous_object.returncode != 0 and '403' in checks['anonymous_object_get_status'])
checks['anonymous_list_status'] = anonymous_list.stderr + anonymous_list.stdout
checks['anonymous_list_denied'] = (
anonymous_list.returncode != 0 and '403' in checks['anonymous_list_status'])
checks['attachment_download_still_authorized'] = (
Client(args.base_url, args.ca_file).call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)['bytes'] == content)
# One session crosses the real replicas through the LB.
client = Client(args.base_url, args.ca_file)
observed = set()
for _ in range(40):
response = client.call('GET', '/api/v1/users/me', actor=alice, schema='User')
observed.add(response['headers']['X-Instance-Id'])
checks['observed_instances'] = sorted(observed)
checks['session_crosses_replicas'] = len(observed) >= 2
checks['session_instances_are_api_hostnames'] = observed.issubset({item['hostname'] for item in api})
checks['health_ready_via_lb'] = client.call('GET', '/health/ready', schema='Health')['status'] == 200
for key, value in checks.items():
if isinstance(value, bool) and not value:
failures.append(key)
checks['result'] = 'PASS' if not failures else 'FAIL'
checks['failed'] = failures
checks['checked_at'] = M.now_iso()
checks['base_url'] = args.base_url
output = ROOT / 'evidence' / 'container-checks.json'
output.parent.mkdir(parents=True, exist_ok=True)
M.write_json(output, checks)
lines = [
'lab4 container checks at ' + checks['checked_at'],
'result: ' + checks['result'],
'git revision: ' + checks['git_revision'],
'API replicas: %d (%s)' % (len(api), ', '.join(item['hostname'] for item in api)),
'API image ids: ' + ', '.join(checks['api_image_ids']),
'S3 image id: ' + checks['s3_image_id'],
'API ports published: %r' % api_ports,
'S3 ports published: %r' % s3_ports,
'LB ports: ' + lb_ports,
'volumes: ' + ', '.join(checks['named_volumes']),
'limits: ' + json.dumps(limits, separators=(',', ':')),
'observed session instances: ' + ', '.join(sorted(observed)),
'anonymous object GET denied: %r' % checks['anonymous_object_get_denied'],
'anonymous bucket list denied: %r' % checks['anonymous_list_denied'],
'bootstrap second run: exit=%r created_false=%r' % (
checks['bucket_bootstrap_second_run_exit'],
checks['bucket_bootstrap_second_run_created_false']),
]
(ROOT / 'evidence' / 'container-checks.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8')
print('\n'.join(lines))
if failures:
raise SystemExit('FAILED checks: ' + ', '.join(failures))
print('PASS: container, S3 privacy and credential checks')
if __name__ == '__main__':
try:
main()
except Exception as exc: # noqa: BLE001
import traceback
traceback.print_exc()
print('FAIL:', exc)
raise SystemExit(1)