Files
mtusi2026lab7/scripts/verify.py
T
Бахрам 1df2202403
Skeleton contracts / contracts (pull_request) Canceled after 0s
Complete lab 7 TLS and secret management
2026-12-01 22:44:28 +03:00

96 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""Reproduce public acceptance, TLS-negative and local least-privilege checks."""
import datetime
import json
import os
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
os.chdir(ROOT)
PUBLIC_PORT = os.getenv('PUBLIC_PORT', '8443')
BASE_URL = 'https://localhost:' + PUBLIC_PORT
CA_FILE = str(ROOT / '.local' / 'pki' / 'external-ca.crt')
def command(*args):
print('\n$ ' + ' '.join(map(str, args)), flush=True)
subprocess.run(list(map(str, args)), check=True)
def wait():
context = ssl.create_default_context(cafile=CA_FILE)
for _ in range(120):
try:
with urllib.request.urlopen(BASE_URL + '/health/ready', context=context, timeout=3) as response:
if response.status == 200:
status = subprocess.check_output(['docker', 'compose', 'ps', '--format', 'json', 'api1', 'api2'], text=True)
docs = [json.loads(line) for line in status.splitlines() if line.strip()]
if len(docs) == 2 and all(doc.get('Health') == 'healthy' for doc in docs):
return
except Exception:
pass
time.sleep(1)
raise RuntimeError('HTTPS ingress or API replicas did not become ready')
def state():
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q'], text=True).split()
if ids:
command('docker', 'inspect', '--format', '{{.Name}} {{.Config.Hostname}} {{.State.Status}} {{.State.StartedAt}}', *ids)
print('Verification UTC:', datetime.datetime.now(datetime.timezone.utc).isoformat(), flush=True)
command('docker', 'compose', 'config', '--quiet')
command(sys.executable, 'scripts/check_contract.py')
wait()
command('docker', 'compose', 'ps')
command(sys.executable, 'tests/smoke.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/security.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/security_runtime.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/acceptance_extra.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/worker_flow.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/retry_limit.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
print('\nBefore persistence:', flush=True)
state()
command(sys.executable, 'tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart.sh',
'--base-url', BASE_URL, '--ca-file', CA_FILE)
wait()
print('\nAfter persistence:', flush=True)
state()
command(sys.executable, 'tests/resilience.py', '--mode', 'failover', '--action-script', 'scripts/stop-one.sh',
'--base-url', BASE_URL, '--ca-file', CA_FILE)
state()
command('docker', 'compose', 'ps', '--all')
command('docker', 'compose', 'up', '-d', 'api1', 'api2', 'worker')
wait()
command(sys.executable, 'tests/attachment_failover.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/storage_failure.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
wait()
command(sys.executable, 'tests/observability.py')
anonymous_probe = '''import os,ssl,psycopg,urllib.request,urllib.error
from app.secrets import load_secrets
load_secrets()
with psycopg.connect(os.environ['DATABASE_URL']) as db:
ident=str(db.execute("SELECT id FROM attachments WHERE doc->>'status'='ready' LIMIT 1").fetchone()[0])
url=os.environ['S3_ENDPOINT']+'/'+os.environ['S3_ORIGINAL_BUCKET']+'/original/'+ident
ctx=ssl.create_default_context(cafile=os.environ['S3_CA_CERT'])
try:
urllib.request.urlopen(url,context=ctx,timeout=5)
except urllib.error.HTTPError as e:
assert e.code in (401,403), e.code
print('PASS: anonymous GET of existing private S3 object denied:',e.code)
else:
raise AssertionError('Private object publicly accessible')
'''
print('\nChecking private bucket from the application network', flush=True)
subprocess.run(['docker', 'compose', 'exec', '-T', 'api1', 'python', '-c', anonymous_probe], check=True)
command('docker', 'compose', 'ps')
print('\nPASS: all recorded checks', flush=True)