"""Verify the dedicated local Lab 7 deployment with synthetic users and data.""" import argparse import base64 from http.client import HTTPSConnection import json import os from pathlib import Path import socket import ssl import subprocess import sys import time from urllib.parse import urlsplit from urllib.request import HTTPSHandler, ProxyHandler, build_opener ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure, check def compose(*args, source=None, env=None): return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, input=source, env=env, text=True, encoding="utf-8").strip() def wait_ready(client): deadline = time.monotonic() + 70 while time.monotonic() < deadline: try: return client.call("GET", "/health/ready", schema="Health") except Failure: time.sleep(0.5) raise Failure("HTTPS readiness did not recover") def verify_hostname(url, ca): endpoint = urlsplit(url) context = ssl.create_default_context(cafile=str(ca)) with socket.create_connection((endpoint.hostname, endpoint.port or 443), timeout=5) as conn: try: with context.wrap_socket(conn, server_hostname="wrong-name.invalid"): raise Failure("Unexpected success with wrong hostname") except ssl.SSLCertVerificationError as error: check(error.verify_code == 62, "The negative test did not fail on hostname verification") return "hostname mismatch rejected" def verify_mtls(): code = """ import http.client import json import ssl def attempt(host, mode): context = ssl.create_default_context(cafile='/run/tls/ca.crt') if mode == 'allowed': context.load_cert_chain('/run/tls/lb-ingress.pem') elif mode != 'absent': context.load_cert_chain(f'/run/tls/{mode}.crt', f'/run/tls/{mode}.key') connection = http.client.HTTPSConnection(host, 8080, context=context, timeout=5) try: connection.request('GET', '/health/live') response = connection.getresponse() return {'status': response.status, 'instance': response.getheader('X-Instance-Id')} except (ssl.SSLError, http.client.RemoteDisconnected, ConnectionResetError) as error: return {'rejected': type(error).__name__} finally: connection.close() results = {} for host in ('api1', 'api2'): results[host] = dict((mode, attempt(host, mode)) for mode in ('allowed', 'absent', 'foreign-role', 'other-role')) print(json.dumps(results)) """ results = json.loads(compose("run", "--rm", "--no-deps", "-T", "probe", "python", "-", source=code)) for replica in results.values(): check(replica["allowed"]["status"] == 200 and replica["allowed"]["instance"], "LB cert rejected") check(all("rejected" in replica[case] for case in ("absent", "foreign-role", "other-role")), "API accepted a prohibited client certificate") return results def verify_scoped_access(): code = """ import json import os from urllib.error import HTTPError from src.bao import client role = os.environ['BAO_ROLE'] other = 'api' if role == 'worker' else 'worker' request = client(role) auth = request('auth/cert/login', {'name': role})['auth'] token = auth['client_token'] def forbidden(path, payload=None): try: request(path, payload, token) except HTTPError as error: assert error.code == 403 return error.code raise AssertionError('OpenBao allowed an out-of-scope operation') own = request('messenger/data/' + role, token=token)['data']['data'] out = {'allowed_keys': sorted(own), 'ttl_seconds': auth['lease_duration'], 'other_role': forbidden('messenger/data/' + other), 'policy_write': forbidden('sys/policies/acl/lab7-test', {'policy': ''})} request('auth/token/revoke-self', {}, token) out['after_revocation'] = forbidden('messenger/data/' + role) assert 0 < out['ttl_seconds'] <= 300 if role == 'worker': import psycopg from src.jobs import database with database() as db: out['postgres_tls'] = db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()['ssl'] try: db.execute('SELECT count(*) FROM users') except psycopg.errors.InsufficientPrivilege: out['users_table'] = 'denied' else: raise AssertionError('Worker can read the users table') from pika.exceptions import ChannelClosedByBroker from src.jobs import QUEUE, broker with broker() as connection: channel = connection.channel() channel.confirm_delivery() try: channel.basic_publish('', QUEUE, b'{}', mandatory=True) except ChannelClosedByBroker as error: assert error.reply_code == 403 out['broker_publish'] = error.reply_code else: raise AssertionError('Worker can publish to its queue') from uuid import uuid4 from botocore.exceptions import ClientError from src.objects import Objects objects = Objects() prefix = 'originals/' if role == 'api' else 'system/' try: objects.client.put_object(Bucket=objects.bucket, Key=prefix + str(uuid4()), Body=b'probe') except ClientError as error: assert error.response['ResponseMetadata']['HTTPStatusCode'] == 403 out['s3_write_other_prefix'] = 403 else: raise AssertionError('S3 allowed a write outside the service prefix') finally: objects.close() print(json.dumps(out)) """ roles = {role: json.loads(compose("exec", "-T", service, "python", "-", source=code)) for role, service in (("api", "api1"), ("worker", "worker"))} check(roles["worker"]["postgres_tls"], "Worker DB connection is plaintext") check("CURSOR_SECRET_FILE" not in roles["worker"]["allowed_keys"], "Worker got the API cursor secret") return roles def verify_telemetry_restrictions(): code = """ import http.client import json import ssl context = ssl.create_default_context(cafile='/run/tls/ca.crt') results = {} for name, host, port, path, method in ( ('collector_ingest', 'otel-collector', 4318, '/v1/traces', 'POST'), ('prometheus_query', 'telemetry-edge', 9440, '/api/v1/query', 'GET'), ('loki_query', 'telemetry-edge', 9441, '/loki/api/v1/labels', 'GET'), ('tempo_query', 'telemetry-edge', 9442, '/api/search', 'GET'), ('loki_ingest', 'telemetry-edge', 9443, '/otlp/v1/logs', 'POST'), ('tempo_ingest', 'telemetry-edge', 9444, '/v1/traces', 'POST'), ): with_context = http.client.HTTPSConnection(host, port, context=context, timeout=5) try: with_context.request(method, path, headers={'Content-Type':'application/x-protobuf'}) response = with_context.getresponse() assert response.status in (401, 403), (name, response.status) results[name] = response.status finally: with_context.close() print(json.dumps(results)) """ return json.loads(compose("run", "--rm", "--no-deps", "-T", "probe", "python", "-", source=code)) def argon_sample(): code = """ import json import statistics import time from src.security import HASHER samples=[] for _ in range(10): started=time.perf_counter() value=HASHER.hash('synthetic-password-for-benchmark') samples.append((time.perf_counter()-started)*1000) assert value.startswith('$argon2id$') and HASHER.verify(value,'synthetic-password-for-benchmark') print(json.dumps({'memory_kib':HASHER.memory_cost,'time_cost':HASHER.time_cost, 'parallelism':HASHER.parallelism,'hash_p50_ms':round(statistics.median(samples),2), 'hash_max_ms':round(max(samples),2),'samples':len(samples)})) """ return json.loads(compose("exec", "-T", "api1", "python", "-", source=code)) def verify_openbao_restart(bao_url, ca_file, operator_file): context = ssl.create_default_context(cafile=str(ca_file)) opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context)) def seal_status(): with opener.open(bao_url + "/v1/sys/seal-status", timeout=5) as response: data = json.load(response) return {"initialized": data["initialized"], "sealed": data["sealed"]} compose("restart", "openbao") try: deadline = time.monotonic() + 30 while time.monotonic() < deadline: try: before = seal_status() break except OSError: time.sleep(0.5) else: raise Failure("OpenBao did not return after restart") check(before == {"initialized": True, "sealed": True}, "Unexpected state after OpenBao restart") finally: subprocess.check_call([sys.executable, "-X", "utf8", str(ROOT / "scripts/bao.py"), "unseal", "--url", bao_url, "--operator-file", str(operator_file)], cwd=ROOT) after = seal_status() check(after == {"initialized": True, "sealed": False}, "Unexpected state after OpenBao unseal") return {"after_restart": before, "after_operator_unseal": after} def verify_api(client, mtls): alice, bob, eve, chat = client.bootstrap() attachment, uploaded = client.attachment(alice, chat) client.wait_ready(bob, attachment) path = "/api/v1/attachments/" + attachment["id"] impersonation = {"X-User-Id": alice["id"]} client.call("GET", path, 404, actor=eve, headers=impersonation) client.call("GET", path + "/content", 404, actor=eve, headers=impersonation) other_chat = client.call("POST", "/api/v1/chats", 201, actor=eve, body={"title": "Проверка ACL", "member_ids": [eve["id"]]}, schema="Chat")["json"] client.call("POST", "/api/v1/chats/" + other_chat["id"] + "/messages", 404, actor=eve, body={"text": "", "attachment_ids": [attachment["id"]]}, headers={"Idempotency-Key": "acl-" + attachment["id"], **impersonation}) client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=eve) client.call("GET", "/api/v1/users/me", 401, actor=eve) client.call("POST", "/api/v1/users", 413, raw=b" " * 66000, headers={"Content-Type": "application/json"}) before = client.message(alice, chat, "Проверка сохранности")["json"] failover = {} for replica in ("api1", "api2"): try: compose("stop", replica) instance = wait_ready(client)["headers"]["X-Instance-Id"] deadline = time.monotonic() + 20 while instance == mtls[replica]["allowed"]["instance"] and time.monotonic() < deadline: time.sleep(0.4) instance = wait_ready(client)["headers"]["X-Instance-Id"] check(instance != mtls[replica]["allowed"]["instance"], "Stopped replica still received requests") client.message(alice, chat, f"Доступ при остановке {replica}") failover[replica] = instance finally: compose("start", replica) wait_ready(client) compose("restart", "db", "s3", "broker") compose("restart", "api1", "api2") wait_ready(client) after = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"] check(before in after["items"], "Message missing after restart") check(client.call("GET", path + "/content", actor=bob)["bytes"] == uploaded, "Original changed after restart") return {"outsider_meta_content_attach": 404, "revoked_session": 401, "oversize_json": 413, "surviving_instances": failover, "message_and_original_after_restart": True} def verify_expiry(client): short_ttl = dict(os.environ, SESSION_TTL_SECONDS="2") try: compose("up", "-d", "--no-deps", "--force-recreate", "api1", "api2", env=short_ttl) wait_ready(client) actor = client.user("expiry") time.sleep(2.5) client.call("GET", "/api/v1/users/me", 401, actor=actor) finally: compose("up", "-d", "--no-deps", "--force-recreate", "api1", "api2") wait_ready(client) return 401 def verify_rate_limit(client, ca_file): time.sleep(10) invalid = base64.b64encode(b"nonexistent:synthetic-wrong-password").decode() endpoint = urlsplit(client.base) context = ssl.create_default_context(cafile=str(ca_file)) connection = HTTPSConnection(endpoint.hostname, endpoint.port or 443, context=context, timeout=5) try: for attempt in range(1, 16): connection.request("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + invalid}) response = connection.getresponse() payload = json.loads(response.read()) check(response.status in (401, 429), "Unexpected login response") if response.status == 429: delay = int(response.headers["Retry-After"]) request_id = response.headers["X-Request-Id"] check(delay > 0 and payload["error"]["request_id"] == request_id, "Invalid 429 response") check(payload["error"]["code"] == "rate_limited", "Unexpected rate-limit error code") return {"status": 429, "request_number": attempt, "retry_after_seconds": delay} finally: connection.close() raise Failure("Login never reached its rate limit") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base-url", default="https://localhost:8443") parser.add_argument("--ca-file", type=Path, default=ROOT / "secrets/pki/ca.crt") parser.add_argument("--bao-url", default="https://localhost:18207") parser.add_argument("--operator-file", type=Path, default=ROOT / "secrets/operator/openbao.json") parser.add_argument("--output", type=Path) args = parser.parse_args() client = Client(args.base_url, str(args.ca_file)) hostname = verify_hostname(args.base_url, args.ca_file) mtls = verify_mtls() result = {"hostname": hostname, "replica_mtls": mtls, "openbao_restart": verify_openbao_restart(args.bao_url, args.ca_file, args.operator_file), "scoped_access": verify_scoped_access(), "telemetry_without_credentials": verify_telemetry_restrictions(), "argon2id": argon_sample(), "https_api": verify_api(client, mtls), "expired_session": verify_expiry(client), "rate_limit": verify_rate_limit(client, args.ca_file)} if args.output: args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") print("PASS: verified TLS, mTLS identity, least privilege, sessions, rate limit and restart/failover.") if __name__ == "__main__": for name in ("NO_PROXY", "no_proxy"): os.environ[name] = ",".join(filter(None, (os.environ.get(name), "127.0.0.1", "localhost"))) main()