lab7: тесты безопасности и перевод своих тестов на HTTPS, документы (trust-matrix, THREAT_MODEL, OPERATOR, DEFENSE, WINDOWS, PR), сборщик доказательств, чистка legacy bench

This commit is contained in:
Alexey Bodanyuk
2026-11-27 17:43:14 +03:00
parent 05df1695fe
commit 84dbdb4735
44 changed files with 1644 additions and 2686 deletions
+33 -5
View File
@@ -2,7 +2,8 @@
* `unit/` — pure functions (validation, cursor, auth headers, Argon2id); no services.
* `test_*` in this folder — marker `stack`: black-box HTTP against the running compose
stand THROUGH THE LOAD BALANCER (BASE_URL, default http://127.0.0.1:8080) plus
stand THROUGH THE LOAD BALANCER (BASE_URL, default https://localhost:8443, CA_FILE = the public
CA, default secrets/pki/public-ca.crt; certificate AND hostname always verified) plus
`docker compose` for database checks (psql inside the postgres container), the HAProxy
runtime state (scripts/lbctl.py) and failure injection. Every failure test restores the
stopped/paused service or replica in `finally` and waits until HAProxy sees all replicas UP.
@@ -23,6 +24,8 @@ import uuid
from pathlib import Path
from urllib.parse import quote
import ssl
import httpx2 as httpx
import pytest
from jsonschema import Draft202012Validator
@@ -33,7 +36,29 @@ sys.path.insert(0, str(ROOT / "scripts"))
import lbctl # noqa: E402
SPEC = json.loads((ROOT / "contracts" / "openapi.json").read_text(encoding="utf-8"))
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
BASE_URL = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/")
# Lab 7: every HTTP call of these tests verifies the server against the PUBLIC CA (+ hostname).
# There is no switch to turn verification off. The wrappers below make it the default of httpx.
CA_FILE = os.environ.get("CA_FILE") or str(ROOT / "secrets" / "pki" / "public-ca.crt")
TLS = ssl.create_default_context(cafile=CA_FILE)
class _VerifiedClient(httpx.Client):
def __init__(self, *args, **kwargs):
kwargs.setdefault("verify", TLS)
super().__init__(*args, **kwargs)
def _verified(function):
def call(*args, **kwargs):
kwargs.setdefault("verify", TLS)
return function(*args, **kwargs)
return call
httpx.Client = _VerifiedClient
for _name in ("get", "post", "put", "delete", "request"):
setattr(httpx, _name, _verified(getattr(httpx, _name)))
PASSWORD = "Test-password-Ω-12345" # synthetic; 12+ code points, non-ASCII on purpose
REPLICAS = int(os.environ.get("API_REPLICAS", "2")) # replicas the stand normally runs
@@ -61,7 +86,9 @@ def compose(*args: str, check: bool = True, timeout: float = 120, stdin: str | N
def psql(sql: str) -> str:
"""Run SQL inside the postgres container (no DB port is published) and return unaligned output."""
result = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
# Lab 7: as the superuser over the container's local socket (peer auth of OS user postgres);
# pg_hba refuses the superuser over the network. Tests use it to inspect/break things on purpose.
result = compose("exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger",
"-At", "-v", "ON_ERROR_STOP=1", "-c", sql)
return result.stdout.strip()
@@ -430,9 +457,10 @@ def attachment_row(attachment_id: str) -> dict | None:
def probe_inside(replica: dict, path: str) -> int:
"""HTTP status of `path` asked inside the replica container itself (bypassing the LB)."""
"""HTTP status of `path` asked inside the replica container itself (bypassing the LB) - lab 7: on
the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client certificate."""
code = ("import urllib.request as u, urllib.error as e\n"
"try: print(u.urlopen('http://127.0.0.1:8080%s', timeout=3).status)\n"
"try: print(u.urlopen('http://127.0.0.1:8081%s', timeout=3).status)\n"
"except e.HTTPError as x: print(x.code)") % path
out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True,
timeout=30).stdout.strip()