ЛР 7: TLS, mTLS, OpenBao и безопасность — на 3
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-11-22 06:03:17 +03:00
parent 20afc2c790
commit 9fb7dde29b
112 changed files with 6226 additions and 80 deletions
+15
View File
@@ -0,0 +1,15 @@
# Проверки ЛР7 на 3
Выполняйте из корня проекта по командам в REPORT.md. Используйте запущенный независимый Compose-проект и сгенерированный CA. Команды отказов затрагивают только контейнеры проекта `mtusi-lab7-grade3`.
| Сценарий | Файл |
| --- | --- |
| TLS ingress и SAN allowlist обеих API | tls.py |
| Реальные клиенты DB, S3, RabbitMQ, Collector и OpenBao role/KV | dependencies.py |
| HTTPS telemetry access и изоляция loopback | telemetry_acl.py |
| ACL, logout и expiry, размер и частота запросов | api_security.py |
| Измерение реального KDF в контейнере API | password_benchmark.py |
| Очередь, PNG/JPEG, checksum, повторные доставки и недоступность S3 | grade3.py |
| Реальные ряды, логи, traces и панели с проверкой чувствительных полей | observability.py |
Контейнер tools не получает Docker socket. Для Make проверок с рестартом контейнер передаёт строго ограниченный запрос через отдельный временный bind mount. Реальный Docker CLI запускает операторский скрипт на Windows. Для расширенной регрессии Docker CLI вызывается из хостового Python.
+82
View File
@@ -0,0 +1,82 @@
"""Public authorization, logout, expiry, input limits and shared login throttle."""
import base64
import hashlib
import http.client
import json
import ssl
import subprocess
from grade3 import Client, PROJECT, check, run, upload
def report(case, **fields):
print(json.dumps({"case": case, "status": "PASS", **fields}), flush=True)
def main():
c = Client("https://127.0.0.1:8443", "secrets/ca/public.crt")
alice, bob, eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"]
attachment = upload(c, alice, chat)["json"]
c.wait_ready(alice, attachment)
file_path = "/api/v1/attachments/" + attachment["id"]
pretend = {"X-User-Id": alice["id"]}
c.call("GET", path, 404, actor=eve, headers=pretend)
c.call("GET", file_path, 404, actor=eve, headers=pretend)
c.call("GET", file_path + "/content", 404, actor=eve, headers=pretend)
c.call("POST", path + "/messages", 404, actor=eve, body={
"text": "", "attachment_ids": [attachment["id"]]
}, headers={**pretend, "Idempotency-Key": "denied-review"})
c.call("GET", "/api/v1/users/me", 401, headers=pretend)
report("chat and attachment ACL; spoofed X-User-Id cannot override Bearer", secret_error_bodies=False)
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=eve)
c.call("GET", "/api/v1/users/me", 401, actor=eve)
report("logout invalidates Bearer", logout=204, reuse=401)
digest = hashlib.sha256(bob["token"].encode()).hexdigest()
update = ("UPDATE sessions SET created_at=now()-interval '2 hours',expires_at=now()-interval '1 hour' "
f"WHERE token_hash=decode('{digest}','hex');")
proc = subprocess.run([
"docker", "compose", "--project-name", PROJECT, "exec", "-T", "postgres",
"psql", "-X", "-v", "ON_ERROR_STOP=1", "-U", "postgres", "-d", "messenger",
], input=update, text=True, capture_output=True)
check(proc.returncode == 0 and "UPDATE 1" in proc.stdout, "synthetic expiry clock adjustment failed")
c.call("GET", "/api/v1/users/me", 401, actor=bob)
report("expired existing session rejected on lookup", code=401)
oversized = c.call("POST", "/api/v1/users", 413, raw=b"x" * 65537,
headers={"Content-Type": "application/json"})
check(oversized["json"]["error"]["code"] == "payload_too_large", "wrong oversized body code")
tls = ssl.create_default_context(cafile="secrets/ca/public.crt")
with_chunk = http.client.HTTPSConnection("127.0.0.1", 8443, context=tls, timeout=5)
try:
with_chunk.request("POST", "/api/v1/users", [b"x" * 32769, b"x" * 32769],
{"Content-Type": "application/json"}, encode_chunked=True)
response = with_chunk.getresponse()
check(response.status == 413 and json.load(response)["error"]["code"] == "payload_too_large",
"chunked oversized request accepted")
finally:
with_chunk.close()
upload(c, alice, chat, b"x" * (10 * 1024 * 1024 + 1), expected=413)
report("fixed length and chunked body guard, image >10 MiB", code=413)
basic = base64.b64encode(b"lab_review_unknown:synthetic-password-only").decode()
denied, instances = 0, set()
for _ in range(35):
response = c.call("POST", "/api/v1/auth/sessions", [401, 429], headers={"Authorization": "Basic " + basic})
if response["status"] == 429:
check(response["json"]["error"]["code"] == "rate_limited", "unexpected rate error")
check(response["headers"]["Retry-After"] == "30", "missing Retry-After")
check(denied > 0 and instances == {"api1", "api2"}, "rate test did not exercise both replicas")
report("shared login limit", preceding_denials=denied, replicas=sorted(instances),
code=429, retry_after=30)
break
denied += 1
instances.add(response["headers"]["X-Instance-Id"])
else:
raise AssertionError("Route never rate limited")
if __name__ == "__main__":
run(main)
+144
View File
@@ -0,0 +1,144 @@
"""Run inside api1 and worker to test their actual TLS clients and permissions."""
import json
import os
import ssl
import pika
import psycopg
import requests
from botocore.exceptions import ClientError, SSLError
from src import jobs, s3
from src.config import secret
ROLE = os.environ["BAO_ROLE"]
CA = "/run/ca/server.crt"
UNRELATED = "/run/ca/unrelated.crt"
def evidence(case, **fields):
print(json.dumps({"role": ROLE, "case": case, "status": "PASS", **fields}), flush=True)
def bao():
base = os.environ["BAO_ADDR"] + "/v1/"
with requests.Session() as client:
client.trust_env = False
client.cert = ("/run/identity/client.crt", "/run/identity/client.key")
client.verify = CA
try:
client.get(base + "sys/seal-status", verify=UNRELATED, timeout=3)
except requests.exceptions.SSLError as exc:
assert "CERTIFICATE_VERIFY_FAILED" in str(exc)
evidence("Bao foreign CA")
else:
raise AssertionError("Bao trusted foreign CA")
login = client.post(base + "auth/cert/login", json={"name": ROLE}, timeout=3)
assert login.status_code == 200, login.status_code
auth = login.json()["auth"]
assert auth["policies"] == [f"lab7-{ROLE}"] and 0 < auth["lease_duration"] <= 300
headers = {"X-Vault-Token": auth["client_token"]}
peer = "worker" if ROLE == "api" else "api"
refused = client.post(base + "auth/cert/login", json={"name": peer}, timeout=3)
assert refused.status_code in (400, 403) and not refused.json().get("auth"), refused.status_code
own = client.get(base + "lab7/data/" + ROLE, headers=headers, timeout=3)
assert own.status_code == 200
assert set(own.json()["data"]["data"]) == {
"DATABASE_URL", "BROKER_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY", "OTEL_LOGIN"}
evidence("Bao own KV and peer identity rejected", ttl=auth["lease_duration"], policies=auth["policies"])
for path, method in (("lab7/data/" + peer, "GET"), ("lab7/data/admin", "GET"),
("sys/mounts", "GET"), ("sys/policies/acl/review-denied", "PUT")):
response = client.request(method, base + path, headers=headers,
json={"policy": ""} if method == "PUT" else None, timeout=3)
assert response.status_code == 403, (path, response.status_code)
evidence("Bao authorization rejection", path=path, code=403)
def postgres():
dsn = secret("DATABASE_URL")
with psycopg.connect(dsn) as conn:
info = conn.execute("SELECT current_user, ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetchone()
assert info[0] == f"lab_{ROLE}" and info[1]
evidence("PostgreSQL verify-full", identity=info[0], protocol=info[2])
try:
if ROLE == "worker":
conn.execute("SELECT token_hash FROM sessions LIMIT 0")
else:
conn.execute("CREATE TABLE review_forbidden (id int)")
except psycopg.errors.InsufficientPrivilege:
evidence("PostgreSQL ACL", sqlstate="42501")
else:
raise AssertionError("Database ACL did not reject")
for params in ({"sslrootcert": UNRELATED}, {"host": "wrong.test", "hostaddr": __import__("socket").gethostbyname("postgres")}):
try:
with psycopg.connect(dsn, connect_timeout=3, **params):
raise AssertionError("PostgreSQL trusted invalid peer")
except psycopg.OperationalError as exc:
assert "certificate" in str(exc).lower()
evidence("PostgreSQL foreign CA" if "sslrootcert" in params else "PostgreSQL wrong hostname")
def storage():
# Reading this known object is granted to API, but intentionally forbidden to worker.
if ROLE == "api":
s3.ready()
evidence("S3 verified HTTPS and authorized object HEAD")
forbidden = "staging/absent" if ROLE == "api" else "health/ready"
try:
s3.client.head_object(Bucket=s3.BUCKET, Key=forbidden)
except ClientError as exc:
assert exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403
evidence("S3 prefix ACL", object=forbidden, code=403)
else:
raise AssertionError("Object ACL did not reject")
try:
client = s3.boto3.client(
"s3", endpoint_url=os.environ["S3_ENDPOINT"], verify=UNRELATED,
aws_access_key_id=secret("S3_ACCESS_KEY_ID"), aws_secret_access_key=secret("S3_SECRET_ACCESS_KEY"),
config=s3.client.meta.config,
)
client.head_object(Bucket=s3.BUCKET, Key="health/ready")
except SSLError as exc:
assert "CERTIFICATE_VERIFY_FAILED" in str(exc)
evidence("S3 foreign CA")
else:
raise AssertionError("S3 trusted foreign CA")
def broker():
with jobs.broker() as channel:
evidence("AMQPS verified and authenticated", identity=f"lab_{ROLE}")
try:
if ROLE == "api":
channel.basic_get(jobs.QUEUE, auto_ack=False)
else:
channel.queue_declare("review-forbidden", exclusive=True)
except pika.exceptions.ChannelClosedByBroker as exc:
assert exc.reply_code == 403
evidence("RabbitMQ ACL", code=403)
else:
raise AssertionError("RabbitMQ ACL did not reject")
context = ssl.create_default_context(cafile=UNRELATED)
try:
import socket
with socket.create_connection(("broker", 5671), timeout=3) as wire:
with context.wrap_socket(wire, server_hostname="broker"):
raise AssertionError("RabbitMQ trusted foreign CA")
except ssl.SSLCertVerificationError:
evidence("RabbitMQ foreign CA")
def collector():
url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces"
user, passwd = secret("OTEL_LOGIN").split(":", 1)
with requests.Session() as client:
client.trust_env = False
options = {"data": b"", "headers": {"Content-Type": "application/x-protobuf"}, "timeout": 4}
assert client.post(url, verify=CA, auth=(user, passwd), **options).status_code == 200
assert client.post(url, verify=CA, **options).status_code == 403
evidence("OTLP TLS, authorized ingest, anonymous rejected")
if __name__ == "__main__":
for check in (bao, postgres, storage, broker, collector):
check()
+451
View File
@@ -0,0 +1,451 @@
"""Reproduce Lab 5 acceptance scenarios using only local Compose services."""
import hashlib
import json
import os
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from io import BytesIO
from pathlib import Path
import re
import subprocess
import sys
import time
from uuid import UUID, uuid4
import requests
from jsonschema import Draft202012Validator, FormatChecker
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
PROJECT = os.getenv("LAB7_PROJECT", "")
SERVICES = {"api1", "api2", "broker", "worker", "postgres", "s3", "lb"}
JOB_SCHEMA = json.loads((ROOT / "contracts/jobs.schema.json").read_text(encoding="utf-8"))
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def docker(*args):
completed = subprocess.run(["docker", *args], capture_output=True, text=True, timeout=45)
check(completed.returncode == 0, f"docker {args[0]} returned {completed.returncode}")
return completed.stdout.strip()
def container(service):
check(service in SERVICES, "unexpected service")
ids = docker("ps", "-aq", "--filter", f"label=com.docker.compose.project={PROJECT}",
"--filter", f"label=com.docker.compose.service={service}",
"--filter", "label=com.docker.compose.oneoff=False").splitlines()
check(len(ids) == 1, f"expected one container for {service}")
return ids[0]
def action(verb, *services):
ids = [container(service) for service in services]
print(f"docker {verb} {' '.join(services)} containers={','.join(ids)}")
extra = ("--time", "2") if verb in {"stop", "restart"} else ()
docker(verb, *extra, *ids)
def inspect(service, fmt):
return docker("inspect", "--format", fmt, container(service))
def inside(service, *args):
return docker("exec", container(service), *args)
def psql_args():
return ("psql", "-XAt", "-v", "ON_ERROR_STOP=1", "-U", "postgres", "-d", "messenger")
def sql(statement):
return inside("postgres", *psql_args(), "-c", statement)
@contextmanager
def block_variant_insert():
# Compatible with metadata SELECT, blocks the worker's final INSERT only.
args = ["docker", "exec", "-i", container("postgres"), *psql_args()]
proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True)
try:
proc.stdin.write("BEGIN; LOCK attachment_variants IN SHARE MODE; SELECT 'locked';\n")
proc.stdin.flush()
for _ in range(3):
if proc.stdout.readline().strip() == "locked":
break
else:
raise Failure("could not lock variants")
yield
finally:
try:
proc.communicate("COMMIT;\n", timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
raise Failure("could not release variants lock") from None
check(proc.returncode == 0, "variant lock session failed")
def eventually(description, fn, seconds=45, interval=0.2):
start = time.monotonic()
last = ""
while time.monotonic() - start < seconds:
try:
value = fn()
if value:
print(f"{description} after {time.monotonic()-start:.3f}s")
return value
except Failure as exc:
last = str(exc)
time.sleep(interval)
raise Failure(f"timeout waiting for {description}: {last}")
def ready(client):
eventually("LB ready", lambda: client.call("GET", "/health/ready", schema="Health"))
def metadata(client, actor, attachment):
path = f"/api/v1/attachments/{attachment['id']}"
return client.call("GET", path, actor=actor, schema="Attachment")["json"]
def expect_unavailable(client, actor, attachment):
path = f"/api/v1/attachments/{attachment['id']}/content"
for variant in ("original", "thumbnail"):
client.call("GET", f"{path}?variant={variant}", 409, actor=actor)
def upload(client, actor, chat, data=SAMPLE, mime="image/png", expected=202, filename="fixture"):
response = client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={filename}",
expected, actor=actor, raw=data, headers={"Content-Type": mime},
schema="Attachment" if expected == 202 else None)
if expected == 202:
row = response["json"]
check(row["status"] == "queued" and row["variants"] == [] and row["error_code"] is None,
"expected queued snapshot")
check((row["size_bytes"], row["sha256"], row["content_type"]) ==
(len(data), hashlib.sha256(data).hexdigest(), mime), "staging metadata mismatch")
return response
def assert_ready(client, actor, attachment, data, dimensions, mime="image/png"):
start = time.monotonic()
row = client.wait_ready(actor, attachment)
check(row["error_code"] is None and len(row["variants"]) == 1, "invalid ready result")
check((row["content_type"], row["size_bytes"], row["sha256"]) ==
(mime, len(data), hashlib.sha256(data).hexdigest()), "original metadata changed")
content_path = f"/api/v1/attachments/{attachment['id']}/content"
original = client.call("GET", content_path, actor=actor)
check(original["bytes"] == data and original["headers"].get_content_type() == mime,
"original content changed")
thumb = client.call("GET", content_path + "?variant=thumbnail", actor=actor)
check(thumb["headers"].get_content_type() == "image/jpeg", "thumbnail HTTP MIME")
variant = row["variants"][0]
check(variant["name"] == "thumbnail" and variant["content_type"] == "image/jpeg"
and (variant["width"], variant["height"]) == dimensions, "thumbnail metadata")
check((variant["sha256"], variant["size_bytes"]) ==
(hashlib.sha256(thumb["bytes"]).hexdigest(), len(thumb["bytes"])), "thumbnail checksum")
with Image.open(BytesIO(thumb["bytes"])) as im:
im.load()
check(im.format == "JPEG" and im.size == dimensions and not im.getexif(),
"invalid thumbnail format, dimensions or EXIF")
pixel = im.getpixel((0, 0))
print(f"ready id={row['id']} wait={time.monotonic()-start:.3f}s original_sha256={row['sha256']} "
f"jpeg={dimensions[0]}x{dimensions[1]} thumb_sha256={variant['sha256']} "
f"read={original['headers']['X-Instance-Id']}/{thumb['headers']['X-Instance-Id']}")
return row, pixel
def job_state(attachment):
aid = UUID(attachment["id"])
return sql(f"""SELECT a.status,j.attempt,COALESCE(j.last_error,''),j.max_attempts
FROM attachments a JOIN attachment_jobs j ON a.id=j.attachment_id
WHERE a.id='{aid}'""")
def private(service, key):
status = inside(service, "python", "-c", """
import sys
from urllib.error import HTTPError
from urllib.request import urlopen
import ssl
from src import s3
try:
urlopen(f"https://s3:9000/{s3.BUCKET}/{sys.argv[1]}", timeout=3, context=ssl.create_default_context(cafile="/run/ca/server.crt")).close()
except HTTPError as error:
print(error.code)
else:
print(200)
""", key)
check(status.splitlines()[-1] == "403", "unsigned S3 request was not rejected")
print("private RustFS object unsigned GET HTTP 403")
def queued_carrier():
# Observe the real persistent AMQP message and put it back without ack.
raw = docker("compose", "--project-name", PROJECT, "run", "--rm", "--no-deps", "-T", "worker", "python", "-c", """
import json
from src import jobs
with jobs.broker() as channel:
method, props, body = channel.basic_get(jobs.QUEUE, auto_ack=False)
if method:
channel.basic_nack(method.delivery_tag, requeue=True)
print(json.dumps({"delivery_mode":props.delivery_mode, "job":json.loads(body)}))
""")
check(bool(raw), "no queued job in RabbitMQ")
observed = json.loads(raw.splitlines()[-1])
check(observed["delivery_mode"] == 2, "AMQP message is not persistent")
carrier = observed["job"]
Draft202012Validator(JOB_SCHEMA, format_checker=FormatChecker()).validate(carrier)
print(f"RabbitMQ persistent carrier schema valid job={carrier['job_id']} "
f"attempt={carrier['attempt']} fields={','.join(sorted(carrier))}")
return carrier
def queue_stats():
text = inside("broker", "rabbitmqctl", "-q", "list_queues",
"-p", "jobs", "name", "durable", "messages_ready", "messages_unacknowledged")
for line in text.splitlines():
fields = line.split()
if fields and fields[0] == "attachment.process.v1":
check(fields[1] == "true", "queue durability is off")
print(f"broker queue={fields[0]} durable={fields[1]} ready={fields[2]} unacked={fields[3]}")
return tuple(map(int, fields[2:]))
raise Failure("RabbitMQ queue absent")
def duplicate(client, actor, attachment, carrier, ready_snapshot):
inside("api1", "python", "-c", """
import sys
from src import jobs
job = jobs.parse(sys.argv[1])
with jobs.broker() as channel:
jobs.publish(channel, job)
jobs.publish(channel, job)
""", json.dumps(carrier))
job_id = carrier["job_id"]
query = ('{service_name="messenger-worker"} | event="job.outcome" '
f'| job_id="{job_id}" | attempt="1" | outcome="duplicate_ready"')
def duplicates_logged():
response = requests.get("https://localhost:3443/api/datasources/proxy/uid/lab6-loki/loki/api/v1/query_range",
auth=("admin", Path("secrets/grafana/password").read_text().strip()), verify="secrets/ca/server.crt",
params={"query": query, "limit": 10}, timeout=5)
check(response.ok, "Loki duplicate query failed")
rows = response.json()["data"]["result"]
return sum(len(row["values"]) for row in rows) >= 2
eventually("worker logged two ready duplicates in Loki", duplicates_logged)
eventually("worker acknowledged all messages", lambda: queue_stats()[:2] == (0, 0))
check(metadata(client, actor, attachment) == ready_snapshot, "duplicate changed ready metadata")
aid = UUID(attachment["id"])
check(sql(f"SELECT count(*) FROM attachment_variants WHERE attachment_id='{aid}'") == "1",
"duplicate created another variant row")
print("PASS duplicate delivery: ready snapshot and thumbnail unchanged, one SQL variant row")
def restart_scenarios(c, alice, bob, eve, chat):
action("stop", "worker")
try:
a = upload(c, alice, chat)["json"]
carrier = queued_carrier()
check(carrier["attachment_id"] == a["id"] and carrier["attempt"] == 1,
"RabbitMQ job identity differs from upload")
b = upload(c, bob, chat)["json"]
check(a["id"] != b["id"], "distinct uploads reused ID")
key = uuid4().hex
with ThreadPoolExecutor(max_workers=8) as pool:
calls = list(pool.map(lambda _: c.message(bob, chat, "", key, [a["id"]]), range(8)))
check(len({x["json"]["id"] for x in calls}) == 1, "idempotency race produced duplicates")
observed = {x["headers"]["X-Instance-Id"] for x in calls}
check(observed == {"api1", "api2"}, "idempotency requests did not use both replicas")
check(calls[0]["json"]["attachment_ids"] == [a["id"]], "queued attachment link lost")
c.message(alice, chat, "ordinary text with worker stopped")
check(metadata(c, bob, a) == a, "queued metadata changed with worker stopped")
expect_unavailable(c, bob, a)
private("api1", f"staging/{a['id']}")
print(f"PASS stopped worker: uploads=202 ids={a['id']},{b['id']}; queued content=409; "
"linked and ordinary POST=201; concurrent same-key response identical via api1/api2")
starts = {s: inspect(s, "{{.State.StartedAt}}") for s in ("api1", "api2")}
action("restart", "api1", "api2")
ready(c)
for service, old in starts.items():
new = inspect(service, "{{.State.StartedAt}}")
check(new != old, f"{service} did not actually restart")
print(f"{service} started before={old} after={new}")
check(metadata(c, bob, a) == a and job_state(a).startswith("queued|1|"),
"accepted job lost after API restart")
volume_format = "{{range .Mounts}}{{if eq .Destination \"/var/lib/rabbitmq\"}}{{.Name}}{{end}}{{end}}"
volume = inspect("broker", volume_format)
check(volume == f"{PROJECT}_broker_data", "unexpected RabbitMQ volume")
check(queue_stats() == (2, 0), "expected two pending jobs before broker restart")
broker_start = inspect("broker", "{{.State.StartedAt}}")
action("restart", "broker")
eventually("broker healthy", lambda: inspect("broker", "{{.State.Health.Status}}") == "healthy")
broker_after = inspect("broker", "{{.State.StartedAt}}")
check(broker_start != broker_after and inspect("broker", volume_format) == volume,
"broker restart or volume identity mismatch")
print(f"broker started before={broker_start} after={broker_after} volume={volume}")
check(queue_stats() == (2, 0), "broker restart lost accepted jobs")
check(metadata(c, bob, b) == b, "second job metadata lost")
print("PASS both APIs + RabbitMQ restarted with queued work and unchanged RabbitMQ volume")
path = f"/api/v1/attachments/{a['id']}"
c.call("GET", path, 401)
c.call("GET", path + "/content?variant=thumbnail", 404, actor=eve)
with block_variant_insert():
action("start", "worker")
processing = eventually(
"HTTP processing state",
lambda: next((row for row in (a, b) if metadata(c, bob, row)["status"] == "processing"), None),
6, interval=0.05,
)
expect_unavailable(c, bob, processing)
c.message(bob, chat, "linked during processing", attachments=[processing["id"]])
print("PASS processing metadata visible, content=409, linking=201 before final SQL commit")
a_ready, _ = assert_ready(c, bob, a, SAMPLE, (256, 160))
assert_ready(c, alice, b, SAMPLE, (256, 160))
duplicate(c, bob, a, carrier, a_ready)
private("api1", f"originals/{a['id']}")
c.call("GET", path + "/content?variant=unknown", 404, actor=bob)
finally:
action("start", "worker")
def image_bytes(image, fmt, **kwargs):
data = BytesIO()
image.save(data, fmt, **kwargs)
return data.getvalue()
def input_and_image_cases(c, alice, eve, chat):
for data, mime, status, actor, filename in (
(SAMPLE, "image/jpeg", 415, alice, "wrong-mime"),
(SAMPLE[:-8], "image/png", 415, alice, "corrupt"),
(b"x" * (10 * 1024 * 1024 + 1), "image/png", 413, alice, "oversize"),
(SAMPLE, "image/png", 404, eve, "private"),
(SAMPLE, "image/png", 401, None, "anonymous"),
(SAMPLE, "image/png", 400, alice, "invalid%2Fname.png"),
):
upload(c, actor, chat, data, mime, status, filename)
print(f"negative upload {filename} HTTP {status}")
huge = image_bytes(Image.new("1", (8001, 5000)), "PNG")
upload(c, alice, chat, huge, expected=413)
print("negative upload 40,005,000 decoded pixels HTTP 413")
exif = Image.Exif()
exif[274] = 6
original = image_bytes(Image.new("RGB", (319, 101), "navy"), "JPEG", exif=exif)
broken = original[:100]
upload(c, alice, chat, broken, mime="image/jpeg", expected=415)
print("negative truncated JPEG HTTP 415")
oriented = upload(c, alice, chat, original, "image/jpeg")["json"]
assert_ready(c, alice, oriented, original, (81, 256), "image/jpeg")
original = image_bytes(Image.new("RGBA", (37, 19), (255, 0, 0, 0)), "PNG")
alpha = upload(c, alice, chat, original)["json"]
_, pixel = assert_ready(c, alice, alpha, original, (37, 19))
check(min(pixel) >= 250, "transparent pixel was not composited on white")
print(f"PASS true JPEG, EXIF orientation, floor rounding, no upscale, alpha pixel={pixel}")
def failure_cases(c, alice, bob, chat):
action("stop", "worker")
try:
a = upload(c, alice, chat)["json"]
action("stop", "s3")
action("start", "worker")
state = eventually("persistent retry after real S3 stop", lambda:
(s := job_state(a)) and "storage_unavailable" in s and s)
print(f"storage outage SQL status|attempt|reason|max={state}")
finally:
action("start", "s3", "worker")
ready(c)
assert_ready(c, bob, a, SAMPLE, (256, 160))
check(int(job_state(a).split("|")[1]) >= 2, "no durable retries recorded")
print("PASS temporary S3 outage recovered the same attachment")
action("stop", "worker")
try:
missing = upload(c, alice, chat)["json"]
corrupt = upload(c, alice, chat)["json"]
docker("compose", "--project-name", PROJECT, "run", "--rm", "--no-deps", "-T", "worker",
"python", "-c", "from src import s3; import sys; s3.delete('staging/' + sys.argv[1])",
missing["id"])
inside("api1", "python", "-c", """
from io import BytesIO
import sys
from src import s3
damaged = BytesIO(b"X" * int(sys.argv[2]))
s3.put(f"staging/{sys.argv[1]}", damaged, damaged.getbuffer().nbytes, "image/png")
""", corrupt["id"], str(corrupt["size_bytes"]))
finally:
action("start", "worker")
for row, error in ((corrupt, "invalid_image"), (missing, "retry_exhausted")):
failed = eventually(f"failed {row['id']}", lambda:
(meta := metadata(c, bob, row))["status"] == "failed" and meta)
check(failed["error_code"] == error and failed["variants"] == [], "unsafe failed result")
state = job_state(row)
status, current, _, maximum = state.split("|")
check(status == "failed" and int(current) == (1 if error == "invalid_image" else int(maximum)),
"unexpected number of attempts")
expect_unavailable(c, bob, row)
c.call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, actor=bob,
body={"text": "", "attachment_ids": [row["id"]]},
headers={"Idempotency-Key": uuid4().hex})
print(f"PASS safe failure code={error}; status|attempt|reason|max={state}; content/link HTTP 409")
action("stop", "broker")
try:
response = upload(c, alice, chat, expected=503)
check(response["json"]["error"]["code"] == "unavailable", "unexpected queue-down response")
c.message(alice, chat, "normal API works when broker is stopped")
print("PASS unavailable broker upload=503 (no false 202), ordinary message=201")
finally:
action("start", "broker")
eventually("broker healthy after failure case", lambda:
inspect("broker", "{{.State.Health.Status}}") == "healthy")
def replica_cases(c, alice, bob, chat):
for stopped, survivor in (("api1", "api2"), ("api2", "api1")):
action("stop", stopped)
try:
eventually(f"{survivor} handles existing Bearer with {stopped} stopped", lambda:
c.call("GET", "/api/v1/users/me", actor=bob, schema="User")["headers"]
["X-Instance-Id"] == survivor)
response = upload(c, alice, chat)
check(response["headers"]["X-Instance-Id"] == survivor, "wrong upload replica")
assert_ready(c, bob, response["json"], SAMPLE, (256, 160))
finally:
action("start", stopped)
eventually(f"{stopped} serves via mTLS", lambda:
c.call("GET", "/health/ready")["headers"]["X-Instance-Id"] == stopped)
print("PASS authorized new uploads and thumbnail reads with either replica stopped")
def main():
check(re.fullmatch(r"mtusi-lab7-grade3(?:-[a-z0-9-]+)?", PROJECT), "unsafe project name")
c = Client("https://localhost:8443", "secrets/ca/public.crt")
ready(c)
alice, bob, eve, chat = c.bootstrap()
alice_id = UUID(alice["id"])
check(sql(f"SELECT password_hash LIKE '$argon2id$%' FROM users WHERE id='{alice_id}'") == "t",
"stored verifier is not Argon2id")
print("PASS Argon2id verifier confirmed without reading hash")
restart_scenarios(c, alice, bob, eve, chat)
input_and_image_cases(c, alice, eve, chat)
failure_cases(c, alice, bob, chat)
replica_cases(c, alice, bob, chat)
check(queue_stats() == (0, 0), "queue did not drain")
print("PASS Lab 7 attachment pipeline regression")
if __name__ == "__main__":
run(main)
+296
View File
@@ -0,0 +1,296 @@
"""Exercise real OTLP storage, Grafana and two isolated Compose incidents."""
import base64
import json
import math
import re
import time
from pathlib import Path
from uuid import uuid4
import requests
from PIL import Image
from grade3 import (
Client, Failure, assert_ready, check, eventually, image_bytes, run, upload,
)
GRAFANA = "https://localhost:3443"
PROXY = GRAFANA + "/api/datasources/proxy/uid/lab6-"
PROM, LOKI, TEMPO = (PROXY + role for role in ("prometheus", "loki", "tempo"))
SERVICES = r'{service_name=~"messenger-api|messenger-worker"}'
DASH = "lab6-messenger"
SQUARE = image_bytes(Image.new("RGB", (320, 320), "navy"), "PNG")
SESSION = requests.Session()
AUTH = None
START = 0
TRACE_RECORDS = []
METRIC_RECORDS = []
def http(url, params=None, payload=None):
try:
method = "POST" if payload is not None else "GET"
response = SESSION.request(method, url, params=params, json=payload, timeout=8,
auth=AUTH, verify="secrets/ca/server.crt")
check(response.ok, f"{method} {url}: HTTP {response.status_code}")
return response
except requests.RequestException as exc:
raise Failure(f"backend connection: {url} ({type(exc).__name__})") from None
def data(url, params=None, payload=None):
return http(url, params, payload).json()
def report(event, **fields):
print(json.dumps({"evidence": event, **fields}, ensure_ascii=False, sort_keys=True))
def prom(query, when=None, base=PROM):
params = {"query": query}
if when is not None:
params["time"] = when
response = data(base + "/api/v1/query", params)
check(response["status"] == "success", "Prometheus query failed")
return response["data"]["result"]
def loki(query, base=LOKI, end=None, limit=1000):
response = data(base + "/loki/api/v1/query_range", {
"query": query, "start": START, "end": end or time.time_ns(), "limit": limit,
})
check(response["status"] == "success", "Loki query failed")
return [(ts, body, series["stream"] | (extra[0] if extra else {}))
for series in response["data"]["result"] for ts, body, *extra in series["values"]]
def value(item):
return item["value"][1]
def trace_hex(value, length):
if re.fullmatch(r"[0-9a-f]{" + str(length) + "}", value or ""):
return value
return base64.b64decode(value or "").hex()
def get_span(trace_id, span_id, service, kind, base=TEMPO):
payload = data(base + "/api/traces/" + trace_id)
for batch in payload.get("batches", payload.get("resourceSpans", [])):
attrs = {a["key"]: a["value"] for a in batch["resource"]["attributes"]}
if attrs["service.name"]["stringValue"] != service:
continue
check(attrs["service.version"]["stringValue"] == "1.7.0", "incorrect service version")
check(attrs["deployment.environment.name"]["stringValue"] == "lab", "incorrect environment")
check(attrs["service.instance.id"]["stringValue"] in {"api1", "api2", "worker"}, "bad instance")
for scope in batch.get("scopeSpans", []):
for span in scope["spans"]:
if trace_hex(span["spanId"], 16) != span_id:
continue
check(trace_hex(span["traceId"], 32) == trace_id, "trace ID mismatch")
check(span["kind"] in (kind, {2: "SPAN_KIND_SERVER", 5: "SPAN_KIND_CONSUMER"}[kind]),
"unexpected span kind")
duration = int(span["endTimeUnixNano"]) - int(span["startTimeUnixNano"])
check(duration > 0, "non-positive span duration")
TRACE_RECORDS.append(payload)
return {"trace_id": trace_id, "span_id": span_id, "duration_ns": duration,
"service": service, "resource": attrs, "span": span}
raise Failure("Tempo did not return matching service/span")
def correlate(label, selector, service, kind, key, val, outcome, status):
query = '{service_name="' + service + '"}' + selector
def linked():
rows = loki(query)
if not rows:
return None
timestamp, body, fields = rows[0]
trace_id, span_id = fields["trace_id"], fields["span_id"]
check(re.fullmatch("[0-9a-f]{32}", trace_id) and int(trace_id, 16), "invalid Loki trace ID")
check(re.fullmatch("[0-9a-f]{16}", span_id) and int(span_id, 16), "invalid Loki span ID")
check(fields.get("severity_text") in {"INFO", "WARN", "WARNING", "ERROR"}
and fields["event"] == body, "missing structured log fields")
record = get_span(trace_id, span_id, service, kind)
span = record["span"]
attrs = {a["key"]: a["value"] for a in span["attributes"]}
check(attrs[key]["stringValue"] == val and attrs["outcome"]["stringValue"] == outcome,
"different event in Tempo")
check(span["status"]["code"] in (status, {1: "STATUS_CODE_OK", 2: "STATUS_CODE_ERROR"}[status]),
"incorrect trace status")
check(int(span["startTimeUnixNano"]) <= int(timestamp) <= int(span["endTimeUnixNano"]),
"log timestamp outside span")
return {"query": query, "log": [timestamp, body, fields], "tempo": record}
result = eventually(label, linked, seconds=45, interval=1)
report(label, **result)
return result
def check_metrics():
allowed = {
"messenger_http_requests_total": {"method", "route", "status_class"},
"messenger_http_duration_seconds_sum": {"method", "route", "status_class"},
"messenger_http_duration_seconds_count": {"method", "route", "status_class"},
"messenger_http_duration_seconds_bucket": {"method", "route", "status_class", "le"},
"messenger_job_outcomes_total": {"job_type", "outcome"},
"messenger_job_duration_seconds_sum": {"job_type", "outcome"},
"messenger_job_duration_seconds_count": {"job_type", "outcome"},
"messenger_job_duration_seconds_bucket": {"job_type", "outcome", "le"},
}
paths = json.loads(Path("contracts/openapi.json").read_text())["paths"]
metrics = {}
for name, labels in allowed.items():
rows = prom(name)
check(bool(rows), f"no series for {name}")
expected_service = "messenger-api" if "http" in name else "messenger-worker"
resource_labels = {"service_name", "service_instance_id", "service_version", "deployment_environment_name"}
for row in rows:
fields = row["metric"]
check(set(fields) == labels | {"__name__", "job", "instance"} | resource_labels, f"unexpected labels on {name}")
check(fields["job"] == expected_service, "unexpected Prometheus service label")
check(fields["instance"] in ({"api1", "api2"} if "http" in name else {"worker"}),
"unexpected instance label")
check(fields["service_name"] == expected_service and fields["service_instance_id"] == fields["instance"],
"inconsistent OTLP resource identity")
if "route" in fields:
check(fields["route"] in paths or fields["route"] == "unmatched", "raw route label")
else:
check(fields["job_type"] == "attachment.process.v1", "unknown job type")
if "http" in name:
required = [row for row in rows if row["metric"]["route"] == "/api/v1/attachments/{attachment_id}/content"]
check(all(any(r["metric"]["status_class"] == status and float(value(r)) > 0
for r in required) for status in ("2xx",)), f"missing HTTP series for {name}")
else:
check(all(any(r["metric"]["outcome"] == outcome and float(value(r)) > 0
for r in rows) for outcome in ("success",)), f"missing job series for {name}")
if "bucket" in name:
check({0.005, 0.25, 60, math.inf} <= {float(r["metric"]["le"]) for r in rows}, "missing histogram buckets")
METRIC_RECORDS.extend(rows)
metrics[name] = rows
# Keep the verified dynamic routes and an actual bucket sample in review evidence.
for name, rows in metrics.items():
samples = [r for r in rows if r["metric"].get("le", "+Inf") in ("0.005", "+Inf")
and r["metric"].get("route", "/api/v1/attachments/{attachment_id}/content")
== "/api/v1/attachments/{attachment_id}/content"]
report("prometheus", query=name, checked_series=len(rows), samples=samples)
return metrics
def check_grafana(api, worker):
sources = data(GRAFANA + "/api/datasources")
for kind in ("prometheus", "loki", "tempo"):
uid = "lab6-" + kind
source = next((s for s in sources if s["uid"] == uid and s["type"] == kind), None)
check(source is not None, "Grafana datasource not provisioned")
if kind == "tempo":
# The built-in Tempo plugin in this Grafana version has no
# plugin health handler. Prove readiness and real trace queries via proxy.
status = http(GRAFANA + f"/api/datasources/proxy/uid/{uid}/ready")
health = {"http_status": status.status_code, "body": status.text.strip()}
else:
health = data(GRAFANA + f"/api/datasources/uid/{uid}/health")
check(health["status"].lower() == "ok", "Grafana datasource unhealthy")
report("grafana.datasource", uid=uid, type=kind, url=source["url"], health=health)
dashboards = data(GRAFANA + "/api/dashboards/uid/" + DASH)
panels = dashboards["dashboard"]["panels"]
check(len(panels) == 6, "expected six Grafana panels")
start_ms = str(int(START / 1_000_000) - 30_000)
end_ms = str(time.time_ns() // 1_000_000)
for panel in panels:
target = panel["targets"][0]
ds = panel["datasource"]
if ds["type"] == "prometheus":
query = target | {"datasource": ds, "intervalMs": 5000, "maxDataPoints": 120, "range": True}
response = data(GRAFANA + "/api/ds/query", payload={
"from": start_ms, "to": end_ms, "queries": [query],
})["results"]["A"]
check(not response.get("error"), "Grafana panel query failed")
frames = response.get("frames", [])
values = [v for f in frames for v in f["data"]["values"][-1]
if isinstance(v, (int, float)) and math.isfinite(v)]
check(values and any(v > 0 for v in values), f"no signal in Grafana panel {panel['id']}")
report("grafana.panel", id=panel["id"], title=panel["title"], query=target["expr"],
frames=len(frames), numeric_samples=len(values), max_value=max(values))
else:
rows = loki(target["expr"], base=GRAFANA + "/api/datasources/proxy/uid/lab6-loki")
check({fields["service_name"] for _, _, fields in rows} >= {"messenger-api", "messenger-worker"},
"Grafana Loki query missing a service")
report("grafana.panel", id=panel["id"], title=panel["title"], query=target["expr"], rows=len(rows))
link = next(s for s in sources if s["uid"] == "lab6-loki")["jsonData"]["derivedFields"][0]
check(link["datasourceUid"] == "lab6-tempo" and link["matcherRegex"] == "trace_id"
and link["url"] == "${__value.raw}", "Grafana Loki-to-Tempo link not provisioned")
for linked in (api, worker):
trace = linked["tempo"]
result = get_span(trace["trace_id"], trace["span_id"], trace["service"],
2 if trace["service"] == "messenger-api" else 5,
base=GRAFANA + "/api/datasources/proxy/uid/lab6-tempo")
report("grafana.trace", trace_id=result["trace_id"], span_id=result["span_id"])
def verify_safe(actors, marker, filename, headers):
logs = loki(SERVICES + ' | event != ""', limit=4000)
literals = [marker, filename, b"\x89PNG".hex()]
for actor in actors:
registration = actor["registration"]
password = registration["password"]
literals.extend((actor["token"], password,
base64.b64encode(f"{registration['username']}:{password}".encode()).decode()))
literals.extend(headers)
# Inspect raw backend responses in memory and emit only counts.
blob = json.dumps([logs, METRIC_RECORDS, TRACE_RECORDS], ensure_ascii=False)
matches = sum(blob.count(secret) for secret in literals)
patterns = re.compile(
r'(?i)\b(?:authorization|secret_access_key|x-amz-signature|password|bearer)\b'
r'|-----BEGIN [A-Z ]*PRIVATE KEY-----|iVBORw0KGgo|/9j/'
r'|/api/v1/(?:chats|attachments)/[0-9a-f]{8}-'
)
matches += len(patterns.findall(blob))
check(matches == 0, "sensitive data found in backend responses")
report("telemetry.scan", loki_rows=len(logs), spans_queries=len(TRACE_RECORDS),
metric_samples=len(METRIC_RECORDS), matches=matches)
def main():
global AUTH, START
AUTH = ("admin", Path("secrets/grafana/password").read_text().strip())
START = time.time_ns()
for url in (PROM + "/-/ready", LOKI + "/ready", TEMPO + "/ready", GRAFANA + "/api/health"):
eventually(url, lambda: http(url), seconds=75, interval=1)
client = Client("https://127.0.0.1:8443", "secrets/ca/public.crt", timeout=10)
alice, bob, eve, chat = client.bootstrap()
marker = "message-canary-" + uuid4().hex
filename = "filename-canary-" + uuid4().hex + ".png"
header_canary = "header-canary-" + uuid4().hex
created = client.message(alice, chat, marker, key=header_canary)
api_id = created["headers"]["X-Request-Id"]
check(created["status"] == 201, "POST must succeed")
denied = client.call("GET", "/api/v1/users/me", 401)
request_401 = denied["headers"]["X-Request-Id"]
started = time.monotonic()
for index in range(48):
client.call("GET", "/api/v1/users/me", actor=alice)
if index % 8 == 0:
client.call("GET", "/api/v1/users/me", 401)
time.sleep(0.14)
report("traffic", get=48, post_status=201, error_status=401, seconds=round(time.monotonic()-started, 3))
attachment = upload(client, alice, chat, data=SQUARE, filename=filename)["json"]
assert_ready(client, bob, attachment, SQUARE, (256, 256))
success_id = attachment["id"]
api = correlate("api.success", f' | request_id="{api_id}" | event="http.completed"',
"messenger-api", 2, "request.id", api_id, "2xx", 1)
correlate("api.401", f' | request_id="{request_401}" | event="http.completed"',
"messenger-api", 2, "request.id", request_401, "4xx", 1)
worker = correlate("worker.ready", f' | attachment_id="{success_id}" | event="job.outcome" | outcome="ready"',
"messenger-worker", 5, "attachment_id", success_id, "ready", 1)
eventually("all real counter and histogram series", check_metrics, seconds=30, interval=2)
check_grafana(api, worker)
verify_safe((alice, bob, eve), marker, filename, [header_canary, chat["id"]])
print("PASS: real metrics, logs and traces through the provisioned Grafana data sources")
if __name__ == "__main__":
run(main)
+23
View File
@@ -0,0 +1,23 @@
"""Time the actual verification settings with synthetic values."""
import json
import statistics
import time
from argon2 import Type, extract_parameters
from src.security import hasher
password = "Synthetic training password 7!"
one = hasher.hash(password)
assert one != hasher.hash(password)
params = extract_parameters(one)
assert params.type is Type.ID and params.memory_cost >= 19456 and params.time_cost >= 2
samples = []
for _ in range(12):
start = time.perf_counter()
assert hasher.verify(one, password)
samples.append(1000 * (time.perf_counter() - start))
print(json.dumps({"type": params.type.name, "memory_kib": params.memory_cost, "iterations": params.time_cost,
"parallelism": params.parallelism, "salt_bytes": params.salt_len, "runs": len(samples),
"median_ms": round(statistics.median(samples), 2), "max_ms": round(max(samples), 2),
"unique_salts": True}))
+62
View File
@@ -0,0 +1,62 @@
"""Probe the actual telemetry gateways with distinct ingest and query credentials."""
import base64
import json
import socket
from pathlib import Path
import requests
CA = "/run/ca/server.crt"
FOREIGN = "/run/ca/unrelated.crt"
def report(case, **details):
print(json.dumps({"case": case, "status": "PASS", **details}), flush=True)
def main():
values = Path("/run/check")
collector = json.loads((values / "collector.json").read_bytes())
exporters = collector["exporters"]
config = json.loads((values / "datasources.json").read_bytes())
with requests.Session() as client:
client.trust_env = False
client.verify = CA
for source, exporter, raw in zip(config["datasources"], exporters.values(), (19090, 13100, 13200)):
url = source["url"]
service = source["type"]
write_headers = exporter["headers"]
encoded = base64.b64encode(
("grafana:" + source["secureJsonData"]["basicAuthPassword"]).encode()
).decode()
read_headers = {"Authorization": "Basic " + encoded}
read = url + ("/-/ready" if service == "prometheus" else "/ready")
write = exporter["endpoint"] + {
"prometheus": "", "loki": "/v1/logs", "tempo": "/v1/traces",
}[service]
assert client.get(read, headers=read_headers, timeout=4).status_code == 200
assert client.get(read, headers=write_headers, timeout=4).status_code == 403
assert client.post(write, headers=read_headers, timeout=4).status_code == 403
assert client.post(write, timeout=4).status_code == 403
try:
client.get(read, headers=read_headers, verify=FOREIGN, timeout=4)
except requests.exceptions.SSLError as exc:
assert "CERTIFICATE_VERIFY_FAILED" in str(exc)
else:
raise AssertionError("Backend accepted an unrelated CA")
try:
with socket.create_connection((service, raw), timeout=3):
raise AssertionError("Plaintext application listener is reachable")
except ConnectionRefusedError:
pass
report(service + " restricted TLS gateway", reader=200, wrong_role=403, anonymous_write=403,
bad_ca="CERTIFICATE_VERIFY_FAILED", localhost_only_port=raw)
try:
with socket.create_connection(("otel-collector", 14318), timeout=3):
raise AssertionError("Plaintext Collector reachable")
except ConnectionRefusedError:
report("Collector plaintext receiver isolated", localhost_only_port=14318)
if __name__ == "__main__":
main()
+61
View File
@@ -0,0 +1,61 @@
"""Verify names, mTLS handshake and peer authorization at each API replica."""
import http.client
import json
import socket
import ssl
from pathlib import Path
CA = Path("/run/ca")
CERT = Path("/run/probe")
def probe(host, port, hostname, cafile, identity=None, tls12=False):
ctx = ssl.create_default_context(cafile=str(CA / cafile))
if tls12:
ctx.maximum_version = ssl.TLSVersion.TLSv1_2
if identity:
ctx.load_cert_chain(CERT / identity / "client.crt", CERT / identity / "client.key")
with socket.create_connection((host, port), timeout=4) as wire:
stage = "TLS handshake"
try:
with ctx.wrap_socket(wire, server_hostname=hostname) as tls:
stage = "HTTP after TLS handshake"
tls.sendall(b"GET /health/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
response = http.client.HTTPResponse(tls)
response.begin()
assert response.status == 200, response.status
return tls.version()
except OSError as exc:
exc.rejection_stage = stage
raise
def accepted(case, *args):
print(json.dumps({"case": case, "status": "PASS", "protocol": probe(*args)}))
def rejected(case, errors, stage, *args):
try:
probe(*args)
except errors as exc:
assert getattr(exc, "rejection_stage", None) == stage, (case, stage, type(exc).__name__)
reason = getattr(exc, "verify_message", None) or getattr(exc, "reason", None) or type(exc).__name__
print(json.dumps({"case": case, "status": "PASS", "stage": stage, "rejection": reason}))
else:
raise AssertionError(f"Accepted a rejected identity: {case}")
if __name__ == "__main__":
handshake = "TLS handshake"
accepted("trusted localhost", "localhost", 8443, "localhost", "public.crt")
rejected("foreign CA", ssl.SSLCertVerificationError, handshake, "localhost", 8443, "localhost", "unrelated.crt")
rejected("wrong hostname", ssl.SSLCertVerificationError, handshake, "localhost", 8443, "wrong.test", "public.crt")
for api in ("api1", "api2"):
backend = (api, 8444, api, "server.crt")
accepted(f"{api}: matching LB DNS SAN", *backend, "correct")
accepted(f"{api}: matching LB DNS SAN, TLS 1.2 control", *backend, "correct", True)
rejected(f"{api}: no client certificate", ssl.SSLError, handshake, *backend, None, True)
rejected(f"{api}: unrelated client CA", ssl.SSLError, handshake, *backend, "wrong-ca", True)
rejected(f"{api}: trusted issuer, disallowed DNS SAN",
(http.client.RemoteDisconnected, ConnectionResetError, ssl.SSLEOFError),
"HTTP after TLS handshake", *backend, "wrong-san")