Files
mtusi2026lab7/tests/lifecycle_probe.py
T
vozzhin 94a8a5c1da
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Реализовать ЛР 7 на оценку 4
2026-12-04 16:15:18 +03:00

66 lines
2.7 KiB
Python

"""Network-side probes for the operator's rotation demonstration."""
import asyncio
import json
from pathlib import Path
import socket
import ssl
import sys
import tempfile
import asyncpg
from security_internal import require, tls
async def check_passwords(values):
for label, url in values.items():
dsn = url.replace('postgresql+asyncpg://', 'postgresql://', 1)
try:
connection = await asyncpg.connect(dsn, ssl=tls(), timeout=5)
except asyncpg.InvalidPasswordError:
require(label == 'old', 'PostgreSQL refused the replacement credential')
else:
try:
require(label == 'new', 'PostgreSQL accepted the old credential on a fresh connection')
require(await connection.fetchval('SELECT current_user') == 'messenger_worker',
'Unexpected PostgreSQL identity')
finally:
await connection.close()
print('PASS: worker password rotated; fresh PostgreSQL connections reject the old password')
def check_leaves(previous):
request = b'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n'
addresses = {info[4][0] for info in socket.getaddrinfo('api', 8443, type=socket.SOCK_STREAM)}
require(len(addresses) == 2, 'Expected both API replicas after leaf rotation')
with tempfile.TemporaryDirectory() as directory:
key, cert = Path(directory) / 'old.key', Path(directory) / 'old.crt'
key.write_text(previous['private.key'])
key.chmod(0o600)
cert.write_text(previous['public.crt'])
for host in addresses:
old = tls()
old.load_cert_chain(cert, key)
for context, permitted in ((tls('lb'), True), (old, False)):
with socket.create_connection((host, 8443), timeout=5) as conn:
try:
with context.wrap_socket(conn, server_hostname='api') as channel:
channel.sendall(request)
result = channel.recv(4096)
except ssl.SSLCertVerificationError:
raise
except (ssl.SSLError, BrokenPipeError, ConnectionResetError):
result = b''
require(result.startswith(b'HTTP/1.1 200 ') if permitted else not result,
'API leaf trust did not switch from the old LB certificate to the new one')
print('PASS: both API replicas reject the old LB leaf and accept the new leaf')
if __name__ == '__main__':
payload = json.load(sys.stdin)
if sys.argv[1] == 'postgres':
asyncio.run(check_passwords(payload))
else:
check_leaves(payload)