add level 3

This commit is contained in:
Матвей
2026-10-20 17:24:32 +03:00
parent 3b52b91fb7
commit e9ef559c34
33 changed files with 1138 additions and 96 deletions
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Create local credentials without printing or overwriting existing values."""
import json
from pathlib import Path
import secrets
root = Path(__file__).resolve().parents[1] / "secrets"
root.mkdir(mode=0o700, exist_ok=True)
def write(name, value):
path = root / name
if path.exists():
return path.read_text().strip()
with path.open("x") as stream:
path.chmod(0o600)
stream.write(value + "\n")
return value
password = write("postgres_password", secrets.token_hex(32))
write("database_url", f"postgresql://messenger:{password}@postgres:5432/messenger")
write("cursor_secret", secrets.token_hex(32))
admin_key = write("s3_admin_key", secrets.token_hex(16))
admin_secret = write("s3_admin_secret", secrets.token_hex(32))
app_key = write("s3_access_key_id", secrets.token_hex(16))
app_secret = write("s3_secret_access_key", secrets.token_hex(32))
write("s3.json", json.dumps({"identities": [
{"name": "bootstrap", "credentials": [{"accessKey": admin_key, "secretKey": admin_secret}],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]},
{"name": "api", "credentials": [{"accessKey": app_key, "secretKey": app_secret}],
"actions": ["Read:messenger-attachments", "Write:messenger-attachments", "List:messenger-attachments"]},
]}, indent=2))
print("Local secrets ready; existing values preserved.")
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Sanitized environment and source fingerprint for local test evidence."""
from datetime import datetime, timezone
from hashlib import sha256
import json
from pathlib import Path
import platform
import subprocess
root = Path(__file__).resolve().parents[1]
def command(*args):
return subprocess.check_output(args, cwd=root, text=True).strip()
paths = [root / name for name in ('Dockerfile', 'compose.yaml', 'pyproject.toml', 'uv.lock', 'Makefile')]
for directory in ('src', 'migrations', 'infra', 'scripts', 'student-tests'):
paths.extend(path for path in (root / directory).rglob('*')
if path.is_file() and '__pycache__' not in path.parts)
report = {
'recorded_at_utc': datetime.now(timezone.utc).isoformat(),
'base_commit': command('git', 'rev-parse', 'HEAD'),
'branch': command('git', 'branch', '--show-current'),
'note': 'Results apply to this working tree, not only the base commit. Functional tests; no load benchmark.',
'host': platform.platform(),
'docker': json.loads(command('docker', 'info', '--format',
'{"server":"{{.ServerVersion}}","cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}}}')),
'compose_version': command('docker', 'compose', 'version', '--short'),
'sources_sha256': {str(path.relative_to(root)): sha256(path.read_bytes()).hexdigest() for path in sorted(paths)},
'services': {},
}
for service in ('postgres', 's3', 'api-a', 'api-b', 'load_balancer'):
container = command('docker', 'compose', 'ps', '-q', service)
info = json.loads(command('docker', 'inspect', container))[0]
report['services'][service] = {
'image': info['Config']['Image'], 'image_id': info['Image'],
'state': info['State']['Status'], 'health': info['State'].get('Health', {}).get('Status'),
'memory_limit_bytes': info['HostConfig']['Memory'],
'nano_cpus_limit': info['HostConfig']['NanoCpus'],
'volumes': [mount['Name'] for mount in info['Mounts'] if mount['Type'] == 'volume'],
}
(root / 'evidence/environment.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
print('PASS: sanitized environment and source hashes saved')
+2 -2
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose restart postgres
docker compose up -d --wait postgres
docker compose restart postgres s3
docker compose up -d --wait postgres s3
docker compose restart api-a api-b load_balancer
docker compose up -d --wait api-a api-b load_balancer
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Public persistence test plus proof of actual container restarts."""
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def snapshot():
result = {}
for service in ('postgres', 's3', 'api-a', 'api-b', 'load_balancer'):
container = subprocess.check_output(['docker', 'compose', 'ps', '-q', service], cwd=ROOT, text=True).strip()
started = subprocess.check_output(['docker', 'inspect', '--format', '{{.State.StartedAt}}', container], text=True).strip()
result[service] = {'container': container[:12], 'started_at': started}
return result
before = snapshot()
print('Before:', json.dumps(before, sort_keys=True), flush=True)
subprocess.run([sys.executable, 'tests/resilience.py', '--mode', 'persistence',
'--action-script', 'scripts/restart.sh'], cwd=ROOT, check=True)
after = snapshot()
print('After:', json.dumps(after, sort_keys=True), flush=True)
assert all(before[key]['started_at'] != after[key]['started_at'] for key in before)
print('PASS: PostgreSQL, S3, both API replicas and LB actually restarted; volumes preserved')