Files
mtusi2026lab2/scripts/container-checks.py
IvanMeln1k 6ea767732e Реализовать лабораторную 2: PostgreSQL, Bearer-сессии и Valkey
Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход,
opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON,
keyset-пагинацию по индексу, миграции, compose-стенд и собственные
проверки уровня 3/4. Трек 5 — план запроса и восстановление.
2026-11-30 23:51:33 +03:00

263 lines
12 KiB
Python

#!/usr/bin/env python3
"""Infrastructure checks for lab2: real containers, pinned images, named
volumes, network isolation, non-root read-only API, health, graceful shutdown
and absence of secrets/tokens in logs and Git.
This script never stops the main stack; the graceful-shutdown proof uses a
separate short-lived container with a unique `mtusi-lab2-melnikov-` prefix.
"""
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check # noqa: E402
API = 'mtusi-lab2-melnikov-api'
POSTGRES = 'mtusi-lab2-melnikov-postgres'
VALKEY = 'mtusi-lab2-melnikov-valkey'
GRACEFUL = 'mtusi-lab2-melnikov-graceful-check'
NETWORK = 'mtusi-lab2-melnikov-net'
VOLUMES = ['mtusi-lab2-melnikov-pgdata', 'mtusi-lab2-melnikov-valkeydata']
def docker(*args):
result = subprocess.run(['docker'] + list(args), capture_output=True, text=True)
if result.returncode != 0:
raise Failure('docker ' + ' '.join(args) + ' failed: ' + result.stderr.strip()[:300])
return result.stdout.strip()
def inspect(name):
return json.loads(docker('inspect', name))[0]
def read_env():
values = {}
for line in (ROOT / '.env').read_text().splitlines():
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
values[key.strip()] = value.strip()
return values
def api_headers(base):
import urllib.request
request = urllib.request.Request(base + '/health/live', headers={'Accept': 'application/json'})
with urllib.request.urlopen(request, timeout=10) as response:
return {'instance': response.headers.get('X-Instance-Id'),
'request': response.headers.get('X-Request-Id'),
'status': response.status}
def wait_healthy(name, timeout=45):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
state = inspect(name)['State']
if state.get('Health', {}).get('Status') == 'healthy':
return
time.sleep(0.5)
raise Failure(name + ' did not become healthy')
def main():
def configure(parser):
parser.add_argument('--image', default='mtusi-messenger-lab2-melnikov:1.0.0')
parser.add_argument('--output', default=None)
args = arguments('Container, volume, network and log checks', configure)
env = read_env()
observations = {}
# --- containers, images, volumes, network ------------------------------
for name in (API, POSTGRES, VALKEY):
wait_healthy(name)
containers = {}
for name in (API, POSTGRES, VALKEY):
data = inspect(name)
check(data['Name'] == '/' + name, 'unexpected container name ' + data['Name'])
check(data['State']['Running'], name + ' is not running')
check(data['State']['Health']['Status'] == 'healthy', name + ' is not healthy')
containers[name] = {
'image': data['Config']['Image'],
'image_id': data['Image'],
'started_at': data['State']['StartedAt'],
'restart_policy': data['HostConfig']['RestartPolicy']['Name'],
}
check(containers[POSTGRES]['image'].startswith('postgres:16.4-alpine3.20@sha256:'),
'PostgreSQL image is not pinned by digest')
check(containers[VALKEY]['image'].startswith('valkey/valkey:8.0.2-alpine@sha256:'),
'Valkey image is not pinned by digest')
api = inspect(API)
check(api['Config']['User'] == '10001:10001', 'API image user is not 10001:10001')
check(api['HostConfig']['ReadonlyRootfs'] is True, 'API root filesystem is writable')
check('ALL' in (api['HostConfig']['CapDrop'] or []), 'API does not drop all capabilities')
check(any('no-new-privileges' in item for item in (api['HostConfig']['SecurityOpt'] or [])),
'API lacks no-new-privileges')
check(docker('exec', API, 'id', '-u') == '10001', 'API process uid is not 10001')
ui = api['HostConfig']['PortBindings'].get('8080/tcp') or []
check(len(ui) == 1 and ui[0].get('HostIp') == '127.0.0.1', 'API port is not bound to loopback only')
for name in (POSTGRES, VALKEY):
data = inspect(name)
check(not data['HostConfig']['PortBindings'], name + ' publishes an internal port')
check(inspect(NETWORK)['Name'] == NETWORK, 'lab2 network missing')
volumes = {}
for name in VOLUMES:
data = inspect(name)
volumes[name] = data['Mountpoint']
check(data['Labels'].get('com.docker.compose.project') == 'mtusi-lab2-melnikov',
name + ' is not owned by the lab2 compose project')
observations['containers'] = containers
observations['volumes'] = volumes
observations['api_user'] = api['Config']['User']
observations['api_read_only'] = api['HostConfig']['ReadonlyRootfs']
observations['api_ports'] = ui
image = inspect(args.image)
check(image['Id'] == containers[API]['image_id'], 'running API image differs from inspected image')
labels = image['Config'].get('Labels') or {}
check(labels.get('org.opencontainers.image.title') == 'mtusi-messenger-lab2',
'API image label is missing')
observations['image'] = {
'reference': args.image,
'id': image['Id'],
'size_bytes': image['Size'],
'user': image['Config']['User'],
'healthcheck': image['Config'].get('Healthcheck', {}).get('Test'),
'created': image['Created'],
}
# --- Valkey is a real, persistent session store ------------------------
def valkey_cli(arguments):
return docker('exec', VALKEY, 'sh', '-c',
'valkey-cli --no-auth-warning -a "$VALKEY_PASSWORD" ' + arguments)
appendonly = valkey_cli('CONFIG GET appendonly')
appendfsync = valkey_cli('CONFIG GET appendfsync')
datadir = valkey_cli('CONFIG GET dir')
persistence = valkey_cli('INFO persistence')
dbsize = int(valkey_cli('DBSIZE'))
check('appendonly' in appendonly and 'yes' in appendonly, 'Valkey AOF is disabled')
check('appendfsync' in appendfsync and 'everysec' in appendfsync, 'Valkey appendfsync is not everysec')
check('/data' in datadir, 'Valkey data directory is not the named volume')
check('aof_enabled:1' in persistence, 'Valkey INFO does not report AOF enabled')
check('aof_last_write_status:ok' in persistence, 'Valkey AOF last write is not ok')
check(dbsize > 0, 'Valkey has no live sessions to persist')
observations['valkey'] = {
'appendonly': 'yes',
'appendfsync': 'everysec',
'dir': '/data',
'aof_enabled': True,
'aof_last_write_status': 'ok',
'session_keys': dbsize,
}
# --- health headers and instance stability -----------------------------
first = api_headers(args.base_url)
second = api_headers(args.base_url)
check(first['status'] == 200 and second['status'] == 200, 'liveness is not 200')
check(first['instance'] and first['instance'] == second['instance'], 'X-Instance-Id is not stable')
check(first['request'] and first['request'] != second['request'], 'X-Request-Id is not per-request')
observations['instance_id'] = first['instance']
# --- logs must not contain credentials or message bodies ---------------
client = Client(args.base_url, args.ca_file)
user = client.user('logs')
registration = user['registration']
chat = client.call('POST', '/api/v1/chats', 201, actor=user,
body={'title': 'Проверка логов', 'member_ids': [user['id']]}, schema='Chat')['json']
marker = 'log-secret-marker-' + registration['username']
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=user,
body={'text': marker}, schema='Message')
logs = docker('logs', '--tail', '400', API)
checks = {
'token_absent': user['token'] not in logs,
'password_absent': registration['password'] not in logs,
'message_body_absent': marker not in logs,
'authorization_header_absent': 'Authorization: Bearer' not in logs,
}
check(all(checks.values()), 'API logs leak a token, password or message body: ' + repr(checks))
observations['log_checks'] = checks
# --- graceful shutdown of a separate identical container ---------------
database_url = ('postgres://%s:%s@postgres:5432/%s?sslmode=disable'
% (env['POSTGRES_USER'], env['POSTGRES_PASSWORD'], env['POSTGRES_DB']))
cache_url = 'redis://:%s@valkey:6379/0' % env['VALKEY_PASSWORD']
started = time.monotonic()
try:
docker('run', '-d', '--name', GRACEFUL, '--network', NETWORK,
'--read-only', '--tmpfs', '/tmp', '--cap-drop', 'ALL',
'--security-opt', 'no-new-privileges:true', '--user', '10001:10001',
'-e', 'APP_HOST=0.0.0.0', '-e', 'APP_PORT=8080', '-e', 'APP_ENV=lab',
'-e', 'LOG_LEVEL=info', '-e', 'SESSION_TTL_SECONDS=3600',
'-e', 'DATABASE_URL=' + database_url, '-e', 'CACHE_URL=' + cache_url,
containers[API]['image_id'])
wait_healthy(GRACEFUL, timeout=45)
boot_seconds = time.monotonic() - started
shutdown_started = time.monotonic()
docker('stop', '--time', '15', GRACEFUL)
shutdown_seconds = time.monotonic() - shutdown_started
state = inspect(GRACEFUL)['State']
graceful_logs = docker('logs', GRACEFUL)
check(state['ExitCode'] == 0, 'graceful container exited with %r' % (state['ExitCode'],))
check('shutdown complete' in graceful_logs, 'graceful shutdown log line is missing')
check(shutdown_seconds <= 10, 'graceful shutdown took %.2fs (promised <=10s)' % shutdown_seconds)
observations['graceful_shutdown'] = {
'boot_seconds': round(boot_seconds, 3),
'shutdown_seconds': round(shutdown_seconds, 3),
'exit_code': state['ExitCode'],
}
finally:
try:
docker('rm', '-f', GRACEFUL)
except Failure:
pass
# --- secrets must not be tracked by Git --------------------------------
tracked = subprocess.run(['git', '-C', str(ROOT), 'ls-files'],
capture_output=True, text=True, check=True).stdout
tracked_files = [line for line in tracked.splitlines() if line]
forbidden = [name for name in tracked_files
if name == '.env' or name.startswith('secrets/') or name.endswith(('.pem', '.key', '.p12'))]
check(not forbidden, 'tracked secret-like files: ' + repr(forbidden))
check('.env.example' in tracked_files, '.env.example is not tracked')
check(subprocess.run(['git', '-C', str(ROOT), 'check-ignore', '-q', '.env']).returncode == 0,
'.env is not ignored by Git')
password = env['POSTGRES_PASSWORD']
if password:
leaked = subprocess.run(['git', '-C', str(ROOT), 'grep', '-F', '--', password],
capture_output=True, text=True).stdout
check(not leaked, 'a generated local password is present in tracked files')
observations['git'] = {'tracked_files': len(tracked_files), 'env_ignored': True,
'secret_like_tracked': forbidden}
observations['finished_at'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps(observations, indent=2, ensure_ascii=False) + '\n')
print(json.dumps({
'image_id': observations['image']['id'],
'image_size_bytes': observations['image']['size_bytes'],
'volumes': sorted(observations['volumes']),
'graceful_shutdown_seconds': observations['graceful_shutdown']['shutdown_seconds'],
'logs_clean': True,
'secret_like_tracked_files': forbidden,
}, ensure_ascii=False, sort_keys=True))
print('PASS: real containers, pinned images, named volumes, non-root read-only API, graceful shutdown, clean logs')
if __name__ == '__main__':
try:
main()
except AssertionError as exc:
print('FAIL:', exc)
raise SystemExit(1)