forked from mtusi2026/mtusi2026lab7
ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия: - внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial; - TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL), Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA; - OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь; - роли БД, S3-политики и права брокера по принципу минимальных прав; - Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS; - hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия; - отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Every Prometheus query of the provisioned dashboard must parse and return data (after some traffic).
|
||||
|
||||
python3 student-tests/check_dashboard.py
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
dash = json.loads((ROOT / "infra/grafana/dashboards/messenger.json").read_text(encoding="utf-8"))
|
||||
bad = 0
|
||||
for panel in dash["panels"]:
|
||||
for t in panel.get("targets", []):
|
||||
if t.get("datasource", {}).get("type") != "prometheus":
|
||||
continue
|
||||
expr = t["expr"].replace("$__rate_interval", "2m")
|
||||
try:
|
||||
rows = obs.prom(expr)
|
||||
status = "ok %3d series" % len(rows) if rows else "EMPTY"
|
||||
except urllib.error.HTTPError as exc:
|
||||
status, rows = "ERROR %s" % exc.read()[:120], None
|
||||
if not rows:
|
||||
bad += 1
|
||||
print("%-16s %-48s %s" % (status, panel["title"][:48], t.get("legendFormat", "")))
|
||||
print("panels: %d, prometheus queries without data: %d" % (len(dash["panels"]), bad))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the same panels executed BY GRAFANA (/api/ds/query)
|
||||
# Proves the provisioned datasources work from Grafana itself (Prometheus, Loki and Tempo), with Grafana macros.
|
||||
import base64 # noqa: E402
|
||||
import urllib.request # noqa: E402
|
||||
|
||||
password = (ROOT / "secrets/bootstrap/grafana_admin_password").read_text().strip()
|
||||
import ssl # noqa: E402
|
||||
GRAFANA_TLS = ssl.create_default_context(cafile=str(ROOT / "secrets/pki/ca.crt")) # lab7: Grafana is HTTPS-only
|
||||
auth = "Basic " + base64.b64encode(("admin:" + password).encode()).decode()
|
||||
via_bad = 0
|
||||
for panel in dash["panels"]:
|
||||
for t in panel.get("targets", []):
|
||||
q = dict(t)
|
||||
q.setdefault("datasource", panel.get("datasource"))
|
||||
if q["datasource"]["type"] == "tempo":
|
||||
# Grafana 11 runs TraceQL search in the browser through the datasource proxy, not /api/ds/query
|
||||
# ("backend TraceQL search queries are not supported"): check exactly that proxy path.
|
||||
import time as _t
|
||||
import urllib.parse as _p
|
||||
url = ("https://localhost:3000/api/datasources/proxy/uid/tempo/api/search?" +
|
||||
_p.urlencode({"q": q["query"], "limit": q.get("limit", 20), "start": int(_t.time()) - 1800,
|
||||
"end": int(_t.time())}))
|
||||
req = urllib.request.Request(url, headers={"Authorization": auth})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60, context=GRAFANA_TLS) as response:
|
||||
n = len(json.loads(response.read()).get("traces", []))
|
||||
status = "ok %5d traces" % n if n else "EMPTY"
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = "ERROR HTTP %s" % exc.code
|
||||
if not status.startswith("ok"):
|
||||
via_bad += 1
|
||||
print("grafana %-8s %-18s %-48s (datasource proxy)" % ("tempo", status, panel["title"][:48]))
|
||||
continue
|
||||
body = json.dumps({"queries": [q], "from": "now-30m", "to": "now"}).encode()
|
||||
req = urllib.request.Request("https://localhost:3000/api/ds/query", data=body, method="POST",
|
||||
headers={"Content-Type": "application/json", "Authorization": auth})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60, context=GRAFANA_TLS) as response:
|
||||
res = json.loads(response.read())["results"][q["refId"]]
|
||||
frames = res.get("frames", [])
|
||||
rows = sum(len((f.get("data") or {}).get("values", [[]])[0] or []) for f in frames)
|
||||
status = "ERROR %s" % res["error"][:100] if res.get("error") else ("ok %5d values" % rows if rows else "EMPTY")
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = "ERROR HTTP %s %s" % (exc.code, exc.read()[:100])
|
||||
if not status.startswith("ok"):
|
||||
via_bad += 1
|
||||
print("grafana %-8s %-18s %-48s" % (q["datasource"]["type"], status, panel["title"][:48]))
|
||||
print("via Grafana: queries without data or with errors: %d" % via_bad)
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 3-4 hardening audit from the REAL container state (docker inspect), not from compose.yaml.
|
||||
|
||||
Checks every running container of the project: non-root user, not privileged, no host network/PID/IPC, no Docker
|
||||
socket mount, all capabilities dropped (no cap_add), no-new-privileges, read-only root FS (+ tmpfs list), CPU/memory/
|
||||
PIDs limits, and that only the allowed ports are published, and only on 127.0.0.1.
|
||||
python3 student-tests/check_hardening.py [--output evidence/hardening.json]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ALLOWED_PUBLISHED = {"8443": "nginx business ingress (TLS)", "3000": "Grafana (HTTPS + login)",
|
||||
"9090": "Prometheus (mTLS operator)", "3100": "Loki (mTLS operator)", "3200": "Tempo (mTLS operator)"}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--output", default="")
|
||||
a = p.parse_args()
|
||||
ids = subprocess.run(["docker", "ps", "-q", "--filter", "label=com.docker.compose.project=mtusi-lab7"],
|
||||
capture_output=True, text=True).stdout.split()
|
||||
rows, failures = [], []
|
||||
for info in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True).stdout):
|
||||
name = info["Name"].strip("/").replace("mtusi-lab7-", "")
|
||||
hc, cfg = info["HostConfig"], info["Config"]
|
||||
user = cfg.get("User") or "root(image default)"
|
||||
mounts = [m.get("Source", "") for m in info["Mounts"]]
|
||||
published = []
|
||||
for port, binds in (info["NetworkSettings"]["Ports"] or {}).items():
|
||||
for b in binds or []:
|
||||
published.append("%s:%s->%s" % (b["HostIp"], b["HostPort"], port))
|
||||
row = {
|
||||
"container": name, "user": user, "privileged": hc["Privileged"], "network": hc["NetworkMode"],
|
||||
"pid": hc.get("PidMode") or "private", "cap_drop": hc.get("CapDrop"), "cap_add": hc.get("CapAdd"),
|
||||
"no_new_privileges": "no-new-privileges:true" in (hc.get("SecurityOpt") or []),
|
||||
"read_only_rootfs": hc["ReadonlyRootfs"], "tmpfs": sorted((hc.get("Tmpfs") or {}).keys()),
|
||||
"cpus": hc["NanoCpus"] / 1e9, "memory_mib": hc["Memory"] // 1048576, "pids_limit": hc.get("PidsLimit"),
|
||||
"docker_socket": any("docker.sock" in m for m in mounts), "published": published,
|
||||
}
|
||||
problems = []
|
||||
if user.split(":")[0] in ("", "0", "root", "root(image default)"):
|
||||
problems.append("runs as root")
|
||||
if row["privileged"] or row["network"] == "host" or row["pid"] == "host" or row["docker_socket"]:
|
||||
problems.append("privileged/host namespace/docker socket")
|
||||
if row["cap_drop"] != ["ALL"] or row["cap_add"]:
|
||||
problems.append("capabilities not fully dropped")
|
||||
if not row["no_new_privileges"]:
|
||||
problems.append("no-new-privileges missing")
|
||||
if not row["read_only_rootfs"]:
|
||||
problems.append("writable root FS")
|
||||
if not (row["cpus"] and row["memory_mib"] and row["pids_limit"]):
|
||||
problems.append("missing CPU/memory/PIDs limit")
|
||||
for pub in published:
|
||||
host_ip, rest = pub.split(":", 1)
|
||||
if host_ip != "127.0.0.1" or rest.split("->")[0] not in ALLOWED_PUBLISHED:
|
||||
problems.append("unexpected published port " + pub)
|
||||
row["problems"] = problems
|
||||
rows.append(row)
|
||||
failures += ["%s: %s" % (name, x) for x in problems]
|
||||
rows.sort(key=lambda r: r["container"])
|
||||
print("%-16s %-11s %-6s %-5s %-4s %-5s %-9s %-24s %s" % ("container", "user", "capDrop", "nnp", "ro", "cpus",
|
||||
"mem/pids", "published", "problems"))
|
||||
for r in rows:
|
||||
print("%-16s %-11s %-6s %-5s %-4s %-5s %-9s %-24s %s" % (
|
||||
r["container"][:16], r["user"][:11], "ALL" if r["cap_drop"] == ["ALL"] else r["cap_drop"],
|
||||
r["no_new_privileges"], r["read_only_rootfs"], r["cpus"], "%d/%s" % (r["memory_mib"], r["pids_limit"]),
|
||||
",".join(x.split("->")[0] for x in r["published"]) or "-", "; ".join(r["problems"]) or "ok"))
|
||||
print("published ports allowed: %s" % ALLOWED_PUBLISHED)
|
||||
print("%d containers, %d problems" % (len(rows), len(failures)))
|
||||
if a.output:
|
||||
with open(a.output, "w", encoding="utf-8") as handle:
|
||||
json.dump(rows, handle, ensure_ascii=False, indent=1)
|
||||
sys.exit(1 if failures else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Argon2id parameters and the login DoS budget, measured on the stand (level 3 + level 4).
|
||||
|
||||
bench inside api-1 (same CPU limit 0.5 core as production replicas): time and peak RSS of one hash for
|
||||
several parameter sets -> justification of m=19 MiB, t=2, p=1
|
||||
flood N concurrent attackers send wrong-password logins (distinct usernames, so per-user limits do not
|
||||
help; the per-IP limit must be raised for this run to model a distributed attacker) while a probe
|
||||
client sends normal requests; reports login throughput, 503 hash_busy share, API CPU/RSS and probe
|
||||
latency vs. a baseline without the flood.
|
||||
|
||||
LOGIN_RATE_LIMIT_PER_IP=1000000 docker compose --env-file .env up -d --no-deps api-1 api-2 # experiment only
|
||||
python3 student-tests/login_budget.py --output evidence/login_budget.json
|
||||
docker compose --env-file .env up -d --no-deps api-1 api-2 # restore limits
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import ssl
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from stand import ROOT, Client, log
|
||||
|
||||
BENCH = r'''
|
||||
import json, resource, time
|
||||
from argon2 import PasswordHasher
|
||||
out = []
|
||||
for m, t, p in ((19456, 2, 1), (12288, 3, 1), (47104, 1, 1), (65536, 3, 1), (65536, 3, 4)):
|
||||
h = PasswordHasher(time_cost=t, memory_cost=m, parallelism=p)
|
||||
h.hash("warm-up-password")
|
||||
times = []
|
||||
for _ in range(10):
|
||||
t0 = time.perf_counter(); h.hash("benchmark-password-123"); times.append((time.perf_counter() - t0) * 1000)
|
||||
times.sort()
|
||||
out.append({"m_kib": m, "t": t, "p": p, "p50_ms": round(times[5], 1), "max_ms": round(times[-1], 1),
|
||||
"peak_rss_mib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024, 1)})
|
||||
print(json.dumps(out))
|
||||
'''
|
||||
|
||||
|
||||
def ctx():
|
||||
return ssl.create_default_context(cafile=str(ROOT / "secrets/pki/ca.crt"))
|
||||
|
||||
|
||||
def request(conn, method, path, headers, body=None):
|
||||
conn.request(method, path, body=body, headers=headers)
|
||||
r = conn.getresponse()
|
||||
r.read()
|
||||
return r.status
|
||||
|
||||
|
||||
def cgroup_cpu():
|
||||
"""CPU seconds of api-1 + api-2 from the Docker API (exact over a window)."""
|
||||
host = subprocess.run(["docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
|
||||
capture_output=True, text=True).stdout.strip().replace("unix://", "")
|
||||
total = 0.0
|
||||
for name in ("mtusi-lab7-api-1-1", "mtusi-lab7-api-2-1"):
|
||||
raw = subprocess.run(["curl", "-s", "--unix-socket", host,
|
||||
"http://localhost/containers/%s/stats?stream=false&one-shot=true" % name],
|
||||
capture_output=True, text=True).stdout
|
||||
total += json.loads(raw)["cpu_stats"]["cpu_usage"]["total_usage"] / 1e9
|
||||
return total
|
||||
|
||||
|
||||
def max_rss():
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
|
||||
capture_output=True, text=True).stdout
|
||||
return {l.split()[0]: l.split()[1] for l in out.splitlines() if "api-" in l and "lab7" in l}
|
||||
|
||||
|
||||
def probe(actor, chat, stop, lat):
|
||||
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
||||
headers = {"Authorization": "Bearer " + actor["token"], "Content-Type": "application/json"}
|
||||
while not stop.is_set():
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
h = dict(headers, **{"Idempotency-Key": uuid.uuid4().hex})
|
||||
status = request(conn, "POST", "/api/v1/chats/%s/messages" % chat["id"], h, b'{"text":"probe"}')
|
||||
lat.append((time.perf_counter() - t0, status))
|
||||
except (OSError, http.client.HTTPException):
|
||||
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def attacker(stop, results):
|
||||
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
||||
while not stop.is_set():
|
||||
name = "nouser_" + uuid.uuid4().hex[:12]
|
||||
auth = base64.b64encode((name + ":wrong-password-123").encode()).decode()
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
status = request(conn, "POST", "/api/v1/auth/sessions", {"Authorization": "Basic " + auth})
|
||||
except (OSError, http.client.HTTPException):
|
||||
conn = http.client.HTTPSConnection("localhost", 8443, context=ctx(), timeout=30)
|
||||
status = "conn_error"
|
||||
results.append((time.perf_counter() - t0, status))
|
||||
|
||||
|
||||
def phase(actor, chat, attackers, duration):
|
||||
stop, lat, logins = threading.Event(), [], []
|
||||
threads = [threading.Thread(target=probe, args=(actor, chat, stop, lat))]
|
||||
threads += [threading.Thread(target=attacker, args=(stop, logins)) for _ in range(attackers)]
|
||||
cpu0, t0 = cgroup_cpu(), time.time()
|
||||
for t in threads:
|
||||
t.start()
|
||||
rss = []
|
||||
while time.time() - t0 < duration:
|
||||
time.sleep(5)
|
||||
rss.append(max_rss())
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join(40)
|
||||
elapsed = time.time() - t0
|
||||
cpu = (cgroup_cpu() - cpu0) / elapsed * 100
|
||||
ok = sorted(x for x, s in lat if s == 201)
|
||||
codes = {}
|
||||
for _, s in logins:
|
||||
codes[str(s)] = codes.get(str(s), 0) + 1
|
||||
login_lat = sorted(x for x, s in logins if s == 401)
|
||||
pct = lambda v, q: round(v[min(len(v) - 1, int(q * len(v)))] * 1000, 1) if v else None # noqa: E731
|
||||
return {"attackers": attackers, "seconds": round(elapsed), "login_attempts_per_s": round(len(logins) / elapsed, 1),
|
||||
"login_status_counts": codes, "login_401_p50_ms": pct(login_lat, .5), "login_401_p99_ms": pct(login_lat, .99),
|
||||
"probe_ok": len(ok), "probe_errors": sum(1 for _, s in lat if s != 201),
|
||||
"probe_p50_ms": pct(ok, .5), "probe_p99_ms": pct(ok, .99),
|
||||
"api_cpu_pct_of_one_core_both_replicas": round(cpu, 1), "api_rss_samples": rss[-1] if rss else {}}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--duration", type=int, default=30)
|
||||
p.add_argument("--attackers", type=int, default=32)
|
||||
p.add_argument("--output", default=str(ROOT / "evidence/login_budget.json"))
|
||||
a = p.parse_args()
|
||||
bench = json.loads(subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "-c", BENCH], cwd=ROOT,
|
||||
capture_output=True, text=True, check=True).stdout)
|
||||
for row in bench:
|
||||
log("argon2id m=%(m_kib)d KiB t=%(t)d p=%(p)d: p50 %(p50_ms)s ms, max %(max_ms)s ms, peak RSS %(peak_rss_mib)s MiB" % row)
|
||||
c = Client()
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
base = phase(alice, chat, 0, a.duration)
|
||||
log("baseline: %s" % base)
|
||||
flood = phase(alice, chat, a.attackers, a.duration)
|
||||
log("flood: %s" % flood)
|
||||
result = {"argon2_bench_api_container_0_5_cpu": bench, "baseline": base, "flood": flood,
|
||||
"config": {"PASSWORD_HASH_CONCURRENCY_per_replica": 4, "PASSWORD_HASH_QUEUE_SECONDS": 3,
|
||||
"replicas": 2, "api_cpu_limit": 0.5, "api_mem_limit_mib": 512}}
|
||||
Path(a.output).write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(result, ensure_ascii=False, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""In-network probe: GET /health/ready on an API replica with a given client certificate from /pki.
|
||||
docker compose run --rm --no-deps -v ./secrets/pki:/pki:ro -v ./student-tests:/audit:ro --entrypoint python \
|
||||
worker /audit/mtls_probe.py api-1 lb-client [lb-client-old ...] -> one JSON line per certificate
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, "/audit")
|
||||
import tls_audit # noqa: E402
|
||||
|
||||
host = sys.argv[1]
|
||||
for name in sys.argv[2:]:
|
||||
verdict, detail = tls_audit.http_get(host, 8080, "/health/ready", name)
|
||||
print(json.dumps({"host": host, "cert": name, "verdict": verdict, "detail": detail}))
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Query helpers for the telemetry backends (stdlib only). Backends listen on 127.0.0.1 (compose.yaml).
|
||||
|
||||
Never prints tokens or passwords; callers print only ids, counts, span names and attributes.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
|
||||
# lab7: the backends accept only clients of the "Telemetry Clients CA": evidence scripts use the operator cert.
|
||||
PROM = os.environ.get("PROM_URL", "https://localhost:9090")
|
||||
LOKI = os.environ.get("LOKI_URL", "https://localhost:3100")
|
||||
TEMPO = os.environ.get("TEMPO_URL", "https://localhost:3200")
|
||||
_PKI = Path(__file__).resolve().parents[1] / "secrets/pki"
|
||||
TLS = ssl.create_default_context(cafile=str(_PKI / "ca.crt"))
|
||||
TLS.load_cert_chain(str(_PKI / "operator.crt"), str(_PKI / "operator.key"))
|
||||
|
||||
|
||||
def _get(url, params=None, timeout=15):
|
||||
if params:
|
||||
url += "?" + urllib.parse.urlencode(params)
|
||||
with urllib.request.urlopen(url, timeout=timeout, context=TLS) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def prom(expr, at=None):
|
||||
"""Instant query -> list of (labels, float value)."""
|
||||
params = {"query": expr}
|
||||
if at:
|
||||
params["time"] = at
|
||||
data = _get(PROM + "/api/v1/query", params)["data"]["result"]
|
||||
return [(r["metric"], float(r["value"][1])) for r in data]
|
||||
|
||||
|
||||
def prom_scalar(expr, default=0.0, at=None):
|
||||
rows = prom(expr, at)
|
||||
return rows[0][1] if rows else default
|
||||
|
||||
|
||||
def prom_range(expr, start, end, step=5):
|
||||
data = _get(PROM + "/api/v1/query_range", {"query": expr, "start": start, "end": end, "step": step})
|
||||
return data["data"]["result"]
|
||||
|
||||
|
||||
def alerts():
|
||||
"""{alertname: state} for pending/firing alerts in Prometheus."""
|
||||
out = {}
|
||||
for a in _get(PROM + "/api/v1/alerts")["data"]["alerts"]:
|
||||
out[a["labels"]["alertname"]] = a["state"]
|
||||
return out
|
||||
|
||||
|
||||
def loki(query, minutes=15, limit=500):
|
||||
end = time.time_ns()
|
||||
data = _get(LOKI + "/loki/api/v1/query_range", {"query": query, "limit": limit, "direction": "forward",
|
||||
"start": end - minutes * 60 * 10**9, "end": end})
|
||||
lines = []
|
||||
for stream in data["data"]["result"]:
|
||||
for ts, line in stream["values"]:
|
||||
lines.append({"ts": int(ts), "line": line, **stream["stream"]})
|
||||
return sorted(lines, key=lambda item: item["ts"])
|
||||
|
||||
|
||||
def tempo_search(traceql, minutes=30, limit=100, start=None, end=None):
|
||||
end = int(end or time.time() + 60)
|
||||
start = int(start or end - 60 - minutes * 60)
|
||||
data = _get(TEMPO + "/api/search", {"q": traceql, "start": start, "end": end, "limit": limit, "spss": 50},
|
||||
timeout=60)
|
||||
return data.get("traces", [])
|
||||
|
||||
|
||||
def _hex(value):
|
||||
return base64.b64decode(value).hex() if value else None
|
||||
|
||||
|
||||
def _attr(value):
|
||||
for key in ("stringValue", "intValue", "boolValue", "doubleValue"):
|
||||
if key in value:
|
||||
return value[key]
|
||||
return None
|
||||
|
||||
|
||||
def tempo_trace(trace_id):
|
||||
"""Flat list of spans: service, name, kind, span_id, parent_id, duration_ms, status, attrs (dict)."""
|
||||
try:
|
||||
data = _get(TEMPO + "/api/traces/" + trace_id)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return []
|
||||
raise
|
||||
spans = []
|
||||
for batch in data.get("batches", []):
|
||||
service = {a["key"]: _attr(a["value"]) for a in batch["resource"]["attributes"]}.get("service.name")
|
||||
for scope in batch.get("scopeSpans", []):
|
||||
for s in scope["spans"]:
|
||||
spans.append({
|
||||
"service": service, "name": s["name"], "kind": s.get("kind", "").replace("SPAN_KIND_", ""),
|
||||
"span_id": _hex(s["spanId"]), "parent_id": _hex(s.get("parentSpanId")),
|
||||
"start": int(s["startTimeUnixNano"]),
|
||||
"duration_ms": (int(s["endTimeUnixNano"]) - int(s["startTimeUnixNano"])) / 1e6,
|
||||
"status": s.get("status", {}).get("code", "").replace("STATUS_CODE_", "") or "UNSET",
|
||||
"attrs": {a["key"]: _attr(a["value"]) for a in s.get("attributes", [])},
|
||||
})
|
||||
return sorted(spans, key=lambda item: item["start"])
|
||||
|
||||
|
||||
def tempo_raw(trace_id):
|
||||
with urllib.request.urlopen(TEMPO + "/api/traces/" + trace_id, timeout=15, context=TLS) as response:
|
||||
return response.read().decode("utf-8", "replace")
|
||||
|
||||
|
||||
def print_tree(spans, out=print, skip_db=False):
|
||||
children = {}
|
||||
ids = {s["span_id"] for s in spans}
|
||||
for s in spans:
|
||||
children.setdefault(s["parent_id"] if s["parent_id"] in ids else None, []).append(s)
|
||||
|
||||
def walk(parent, depth):
|
||||
for s in children.get(parent, []):
|
||||
if skip_db and s["kind"] == "CLIENT" and s["name"].split()[0] in ("SELECT", "UPDATE", "INSERT", "DELETE"):
|
||||
continue
|
||||
extra = {k: v for k, v in s["attrs"].items() if k.startswith(("messenger.", "messaging.message", "db.system",
|
||||
"http.response.status_code", "rpc.method"))}
|
||||
out("%s%-8s %-9s %-44s %8.1f ms %-5s %s" % (" " * depth, s["service"].replace("messenger-", ""), s["kind"],
|
||||
s["name"][:44], s["duration_ms"], s["status"],
|
||||
json.dumps(extra, ensure_ascii=False)))
|
||||
walk(s["span_id"], depth + 1)
|
||||
|
||||
walk(None, 0)
|
||||
|
||||
|
||||
def wait_for(predicate, seconds=60, interval=2):
|
||||
deadline = time.monotonic() + seconds
|
||||
value = None
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(interval)
|
||||
return value
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Open-loop load generator (stdlib only): fixed arrival rate, latency measured from the SCHEDULED send time,
|
||||
so a slow server cannot slow down the generator (no coordinated omission while threads are available).
|
||||
|
||||
Mix per arrival: 75% POST message, 25% GET history (limit=20); plus an independent upload stream (sample.png).
|
||||
Rare injected requests (FAULT_INJECTION=1 on the stand): `X-Fault: slow` (+600 ms) and `X-Fault: error` (500)
|
||||
are added to GET history with the given percentages, to measure whether such traces survive sampling.
|
||||
|
||||
python3 student-tests/openloop.py --rate 40 --duration 60 --upload-rate 1 --slow-pct 1 --error-pct 1 \
|
||||
--output evidence/x.json
|
||||
Tokens stay in memory; the summary contains counts, percentiles and timestamps only.
|
||||
"""
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import random
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
os.environ.setdefault("CA_FILE", str(ROOT / "secrets/pki/ca.crt"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
k = max(0, min(len(values) - 1, int(round(p / 100.0 * len(values) + 0.5)) - 1))
|
||||
return values[k]
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, base_url, users=4, threads=64, timeout=30.0):
|
||||
self.base = urlsplit(base_url)
|
||||
self.tls = ssl.create_default_context(cafile=os.environ.get("CA_FILE") or str(ROOT / "secrets/pki/ca.crt"))
|
||||
self.threads = threads
|
||||
self.timeout = timeout
|
||||
c = Client(base_url)
|
||||
self.actors = []
|
||||
for i in range(users):
|
||||
a, b = c.user("load%da" % i), c.user("load%db" % i)
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=a,
|
||||
body={"title": "load %d" % i, "member_ids": [a["id"], b["id"]]}, schema="Chat")["json"]
|
||||
self.actors.append((a["token"], chat["id"]))
|
||||
self.lock = threading.Lock()
|
||||
self.results = []
|
||||
self.local = threading.local()
|
||||
|
||||
def conn(self):
|
||||
c = getattr(self.local, "conn", None)
|
||||
if c is None:
|
||||
if self.base.scheme == "https": # lab7: TLS verified against the stand CA, never unverified
|
||||
c = http.client.HTTPSConnection(self.base.hostname, self.base.port or 443, timeout=self.timeout,
|
||||
context=self.tls)
|
||||
else:
|
||||
c = http.client.HTTPConnection(self.base.hostname, self.base.port or 80, timeout=self.timeout)
|
||||
self.local.conn = c
|
||||
return c
|
||||
|
||||
def request(self, method, path, body=None, headers=None):
|
||||
for attempt in (1, 2): # second attempt only for a dropped keep-alive connection BEFORE sending
|
||||
conn = self.conn()
|
||||
try:
|
||||
conn.request(method, path, body=body, headers=headers or {})
|
||||
response = conn.getresponse()
|
||||
response.read()
|
||||
return response.status, response.getheader("X-Request-Id")
|
||||
except (http.client.RemoteDisconnected, ConnectionResetError, BrokenPipeError) as exc:
|
||||
conn.close()
|
||||
self.local.conn = None
|
||||
if attempt == 2:
|
||||
return "conn_error:" + type(exc).__name__, None
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
conn.close()
|
||||
self.local.conn = None
|
||||
return "error:" + type(exc).__name__, None
|
||||
return "error", None
|
||||
|
||||
def one(self, kind, fault, scheduled):
|
||||
token, chat = random.choice(self.actors)
|
||||
headers = {"Authorization": "Bearer " + token}
|
||||
if fault:
|
||||
headers["X-Fault"] = fault
|
||||
if kind == "post_message":
|
||||
headers.update({"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex})
|
||||
status, rid = self.request("POST", "/api/v1/chats/%s/messages" % chat,
|
||||
json.dumps({"text": "нагрузка " + uuid.uuid4().hex[:8]}).encode(), headers)
|
||||
elif kind == "get_history":
|
||||
status, rid = self.request("GET", "/api/v1/chats/%s/messages?limit=20" % chat, None, headers)
|
||||
else:
|
||||
headers["Content-Type"] = "image/png"
|
||||
status, rid = self.request("POST", "/api/v1/chats/%s/attachments?filename=load.png" % chat, SAMPLE, headers)
|
||||
done = time.monotonic()
|
||||
with self.lock:
|
||||
self.results.append({"kind": kind, "fault": fault, "status": status, "latency": done - scheduled,
|
||||
"at": time.time(), "rid": rid})
|
||||
|
||||
def run(self, rate, duration, upload_rate=0.0, slow_pct=0.0, error_pct=0.0, stop_event=None):
|
||||
work = queue.Queue()
|
||||
start = time.monotonic()
|
||||
self.started_at = time.time()
|
||||
|
||||
def worker():
|
||||
while True:
|
||||
item = work.get()
|
||||
if item is None:
|
||||
return
|
||||
self.one(*item)
|
||||
|
||||
pool = [threading.Thread(target=worker, daemon=True) for _ in range(self.threads)]
|
||||
for t in pool:
|
||||
t.start()
|
||||
|
||||
def schedule(r, picker):
|
||||
if r <= 0:
|
||||
return
|
||||
n = 0
|
||||
while True:
|
||||
due = start + n / r
|
||||
if due - start >= duration or (stop_event and stop_event.is_set()):
|
||||
return
|
||||
delay = due - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
work.put(picker() + (due,))
|
||||
n += 1
|
||||
|
||||
def pick_main():
|
||||
if random.random() < 0.75:
|
||||
return ("post_message", None)
|
||||
roll = random.random() * 100
|
||||
fault = "slow" if roll < slow_pct * 4 else "error" if roll < (slow_pct + error_pct) * 4 else None
|
||||
return ("get_history", fault) # 25% share * 4 = requested share of ALL requests
|
||||
|
||||
schedulers = [threading.Thread(target=schedule, args=(rate, pick_main), daemon=True),
|
||||
threading.Thread(target=schedule, args=(upload_rate, lambda: ("upload", None)), daemon=True)]
|
||||
for t in schedulers:
|
||||
t.start()
|
||||
for t in schedulers:
|
||||
t.join()
|
||||
backlog = work.qsize()
|
||||
for _ in pool:
|
||||
work.put(None)
|
||||
for t in pool:
|
||||
t.join(self.timeout + 5)
|
||||
self.finished_at = time.time()
|
||||
return self.summary(rate, duration, upload_rate, slow_pct, error_pct, backlog)
|
||||
|
||||
def summary(self, rate, duration, upload_rate, slow_pct, error_pct, backlog):
|
||||
res = self.results
|
||||
ok = [r for r in res if isinstance(r["status"], int) and r["status"] < 400]
|
||||
plain_ok = [r["latency"] for r in ok if r["fault"] is None and r["kind"] != "upload"]
|
||||
out = {
|
||||
"profile": {"rate_rps": rate, "duration_s": duration, "upload_rate_rps": upload_rate,
|
||||
"slow_pct": slow_pct, "error_pct": error_pct, "threads": self.threads,
|
||||
"mix": "75% POST message / 25% GET history(limit=20); uploads separate"},
|
||||
"started_at": self.started_at, "finished_at": self.finished_at, "generator_backlog_at_end": backlog,
|
||||
"requests": len(res), "ok": len(ok),
|
||||
"successful_rps": round(len(ok) / max(duration, 1e-9), 2),
|
||||
"status_counts": {},
|
||||
"server_errors_unexpected": sum(1 for r in res if r["fault"] != "error" and (
|
||||
not isinstance(r["status"], int) or r["status"] >= 500)),
|
||||
"latency_ms_plain_ok": {p: round(percentile(plain_ok, q) * 1000, 2) if plain_ok else None
|
||||
for p, q in (("p50", 50), ("p95", 95), ("p99", 99), ("max", 100))},
|
||||
"faults_sent": {"slow": sum(1 for r in res if r["fault"] == "slow"),
|
||||
"error": sum(1 for r in res if r["fault"] == "error")},
|
||||
"by_kind": {},
|
||||
}
|
||||
for r in res:
|
||||
key = str(r["status"])
|
||||
out["status_counts"][key] = out["status_counts"].get(key, 0) + 1
|
||||
for kind in ("post_message", "get_history", "upload"):
|
||||
lat = [r["latency"] for r in ok if r["kind"] == kind and r["fault"] is None]
|
||||
out["by_kind"][kind] = {"n": sum(1 for r in res if r["kind"] == kind),
|
||||
"p50_ms": round(percentile(lat, 50) * 1000, 2) if lat else None,
|
||||
"p99_ms": round(percentile(lat, 99) * 1000, 2) if lat else None}
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--base-url", default="https://localhost:8443")
|
||||
p.add_argument("--rate", type=float, default=40)
|
||||
p.add_argument("--duration", type=float, default=60)
|
||||
p.add_argument("--upload-rate", type=float, default=0)
|
||||
p.add_argument("--slow-pct", type=float, default=0)
|
||||
p.add_argument("--error-pct", type=float, default=0)
|
||||
p.add_argument("--threads", type=int, default=64)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
load = Load(a.base_url, threads=a.threads)
|
||||
summary = load.run(a.rate, a.duration, a.upload_rate, a.slow_pct, a.error_pct)
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if a.output:
|
||||
Path(a.output).write_text(text + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# Checks that need the OPERATOR material of OpenBao (unseal shares / root token in secrets/operator/).
|
||||
# Run by the operator from the repository root: sh student-tests/operator_checks.sh
|
||||
# Every step writes its output to evidence/; nothing secret is printed.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
CA="$PWD/secrets/pki/ca.crt"
|
||||
run() { name=$1; shift; printf '%-28s ' "$name"; if "$@" > "evidence/$name.txt" 2>&1; then echo PASS; else echo "FAIL (see evidence/$name.txt)"; fi; }
|
||||
ps_state() { docker compose ps --format '{{.Name}} {{.Status}}' | grep -vE 'migrate|minio-init'; }
|
||||
|
||||
echo "1/5 unseal OpenBao and wait for the services"
|
||||
sh scripts/bao.sh unseal
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 240 >/dev/null 2>&1 && echo " stand healthy"
|
||||
|
||||
echo "2/5 operator checks"
|
||||
run secret_rotation caffeinate -i python3 -u student-tests/test_secret_rotation.py
|
||||
run bao_sealed caffeinate -i python3 -u student-tests/test_bao_sealed.py
|
||||
|
||||
echo "3/5 persistence (restart of every store incl. OpenBao + unseal, volumes kept)"
|
||||
{ echo "# $(date -u +%FT%TZ) scripts/restart.sh"; echo '$ docker compose ps (before)'; ps_state
|
||||
echo '$ make test-persistence ACTION_SCRIPT=scripts/restart.sh'
|
||||
caffeinate -i make test-persistence ACTION_SCRIPT=scripts/restart.sh CA_FILE="$CA" 2>&1 | tail -2
|
||||
echo '$ docker compose ps (after)'; ps_state; } > evidence/persistence.txt 2>&1
|
||||
grep -q "^PASS" evidence/persistence.txt && echo " persistence PASS" || echo " persistence FAIL (evidence/persistence.txt)"
|
||||
|
||||
echo "4/5 failover of each API replica"
|
||||
sleep 20
|
||||
{ echo "# $(date -u +%FT%TZ)"
|
||||
for i in 1 2; do
|
||||
echo "\$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh (run $i)"
|
||||
caffeinate -i make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE="$CA" 2>&1 | tail -3
|
||||
docker compose ps --format '{{.Name}} {{.Status}}' | grep api
|
||||
echo '$ docker compose start api-1 api-2'; docker compose start api-1 api-2 >/dev/null 2>&1; sleep 30
|
||||
done; } > evidence/failover.txt 2>&1
|
||||
echo " failover: $(grep -c '^PASS' evidence/failover.txt)/2 PASS"
|
||||
|
||||
echo "5/5 smoke and full TLS audit after everything"
|
||||
run smoke make test CA_FILE="$CA"
|
||||
run tls_audit_final docker compose run --rm --no-deps -v ./secrets/pki:/pki:ro -v ./secrets/bootstrap:/bootstrap:ro \
|
||||
-v ./student-tests:/audit:ro -v ./evidence:/evidence --entrypoint python worker /audit/tls_audit.py \
|
||||
--output /evidence/tls_audit.json
|
||||
tail -1 evidence/tls_audit_final.txt
|
||||
@@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 1: the queue under load. Open-loop upload arrivals against the running stack, metrics from the DB.
|
||||
|
||||
Each run:
|
||||
1. (re)creates the worker service with WORKER_REPLICAS / WORKER_CONCURRENCY / WORKER_PREFETCH
|
||||
2. sends uploads at a FIXED arrival rate (open loop: the schedule does not wait for responses)
|
||||
3. samples worker container memory (docker stats) and accepted-but-unfinished jobs once per second
|
||||
4. waits until every accepted upload is ready/failed and computes from attachment_jobs:
|
||||
queue lag = first_started_at - created_at (time a job waited for a worker)
|
||||
time to ready = finished_at - attachment.created_at
|
||||
throughput = finished jobs / (last finish - first arrival)
|
||||
Rejections (503 queue_full from admission control) are counted, not retried.
|
||||
|
||||
python3 student-tests/queue_load.py run --size medium --rate 4 --duration 30 --concurrency 2 --prefetch 2
|
||||
python3 student-tests/queue_load.py overload --max-pending 30 --size medium --rate 12 --duration 30
|
||||
Results are appended as JSON lines to evidence/track1/results.jsonl.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from stand import ROOT, Client, Failure, compose, log, sql, wait_http_ready
|
||||
|
||||
OUT = ROOT / "evidence/track1"
|
||||
SIZES = {"small": (640, 400, "JPEG"), "medium": (4000, 3000, "JPEG"), "large": (6000, 4000, "PNG")}
|
||||
|
||||
GEN = r'''
|
||||
import io, random, sys
|
||||
from PIL import Image, ImageChops, ImageDraw
|
||||
w, h, fmt = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3]
|
||||
if fmt == "JPEG": # photo-like noise: realistic JPEG sizes
|
||||
chan = [Image.effect_noise((max(8, w // 24), max(8, h // 24)), 90).resize((w, h), Image.Resampling.BICUBIC) for _ in range(3)]
|
||||
grain = Image.effect_noise((w, h), 12)
|
||||
img = Image.merge("RGB", [ImageChops.add(c, grain, 1.0, -6) for c in chan])
|
||||
else: # graphics-like PNG: compresses well (stays under 10 MiB) but must be fully decoded (no DCT scaling)
|
||||
img = Image.linear_gradient("L").resize((w, h)).convert("RGB")
|
||||
draw, rnd = ImageDraw.Draw(img), random.Random(1)
|
||||
for _ in range(400):
|
||||
x, y, r = rnd.randrange(w), rnd.randrange(h), rnd.randrange(20, 300)
|
||||
draw.ellipse((x, y, x + r, y + r), fill=(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, fmt, **({"quality": 90} if fmt == "JPEG" else {"compress_level": 6}))
|
||||
sys.stdout.buffer.write(buf.getvalue())
|
||||
'''
|
||||
|
||||
|
||||
def image(size):
|
||||
w, h, fmt = SIZES[size]
|
||||
cache = OUT / ("fixture-%s.%s" % (size, fmt.lower()))
|
||||
if not cache.exists():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
data = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "-c", GEN, str(w), str(h), fmt],
|
||||
cwd=ROOT, capture_output=True, check=True).stdout
|
||||
cache.write_bytes(data)
|
||||
return cache.read_bytes(), "image/png" if fmt == "PNG" else "image/jpeg"
|
||||
|
||||
|
||||
def set_worker(replicas, concurrency, prefetch, cpus="2.00"):
|
||||
env = dict(os.environ, WORKER_REPLICAS=str(replicas), WORKER_CONCURRENCY=str(concurrency),
|
||||
WORKER_PREFETCH=str(prefetch), WORKER_CPUS=cpus)
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--wait", "worker"],
|
||||
cwd=ROOT, env=env, check=True, capture_output=True, timeout=180)
|
||||
|
||||
|
||||
def set_admission(max_pending):
|
||||
env = dict(os.environ, MAX_PENDING_JOBS=str(max_pending))
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--wait", "api-1", "api-2"],
|
||||
cwd=ROOT, env=env, check=True, capture_output=True, timeout=180)
|
||||
|
||||
|
||||
def parse_mem(text):
|
||||
value = text.split("/")[0].strip()
|
||||
for unit, mult in (("GiB", 1024), ("MiB", 1), ("KiB", 1 / 1024), ("B", 1 / 1048576)):
|
||||
if value.endswith(unit):
|
||||
return float(value[: -len(unit)]) * mult
|
||||
return 0.0
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
def __init__(self, tag):
|
||||
super().__init__(daemon=True)
|
||||
self.tag = tag
|
||||
self.stop = threading.Event()
|
||||
self.rss, self.pending, self.cpu = [], [], []
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
ids = compose("ps", "-q", "worker", check_rc=False).split()
|
||||
if ids:
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}|{{.CPUPerc}}", *ids],
|
||||
capture_output=True, text=True).stdout
|
||||
rows = [line.split("|") for line in out.splitlines() if "|" in line]
|
||||
self.rss.append(sum(parse_mem(r[0]) for r in rows))
|
||||
self.cpu.append(sum(float(r[1].rstrip("%") or 0) for r in rows))
|
||||
try:
|
||||
self.pending.append(int(sql("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
|
||||
" WHERE a.filename LIKE 'load-%s-%%' AND j.state IN ('queued','processing')"
|
||||
% self.tag)[0][0]))
|
||||
except Exception:
|
||||
pass
|
||||
self.stop.wait(1.0)
|
||||
|
||||
|
||||
def pct(values, q):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
return round(values[min(len(values) - 1, int(round(q * (len(values) - 1))))], 3)
|
||||
|
||||
|
||||
def drive(c, actor, chat, body, ctype, rate, duration, tag):
|
||||
"""Open-loop: request i is sent at t0 + i/rate regardless of earlier responses."""
|
||||
total = int(rate * duration)
|
||||
results = {"accepted": 0, "rejected_503": 0, "other_errors": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
def one(i):
|
||||
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote("load-%s-%05d.img" % (tag, i)))
|
||||
try:
|
||||
r = c.call("POST", path, [202, 503], actor=actor, raw=body, headers={"Content-Type": ctype})
|
||||
key = "accepted" if r["status"] == 202 else "rejected_503"
|
||||
except Exception: # connection errors, timeouts: counted, never retried
|
||||
key = "other_errors"
|
||||
with lock:
|
||||
results[key] += 1
|
||||
|
||||
t0 = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=64) as pool:
|
||||
for i in range(total):
|
||||
delay = t0 + i / rate - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
pool.submit(one, i)
|
||||
results["send_seconds"] = round(time.monotonic() - t0, 2)
|
||||
results["offered"] = total
|
||||
return results
|
||||
|
||||
|
||||
def wait_drained(tag, seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
left = int(sql("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
|
||||
" WHERE a.filename LIKE 'load-%s-%%' AND j.state IN ('queued','processing')" % tag)[0][0])
|
||||
if left == 0:
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def job_metrics(tag):
|
||||
rows = sql(
|
||||
"SELECT extract(epoch FROM a.created_at), extract(epoch FROM j.first_started_at), extract(epoch FROM j.finished_at),"
|
||||
" j.state, j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
|
||||
" WHERE a.filename LIKE 'load-%s-%%'" % tag)
|
||||
done = [(float(a), float(s), float(f)) for a, s, f, st, _ in rows if st == "succeeded"]
|
||||
lag = [s - a for a, s, f in done]
|
||||
ttr = [f - a for a, s, f in done]
|
||||
span = (max(f for _, _, f in done) - min(a for a, _, _ in done)) if done else 0
|
||||
return {
|
||||
"succeeded": len(done), "failed": sum(1 for r in rows if r[3] == "failed"),
|
||||
"retries": sum(int(r[4]) - 1 for r in rows),
|
||||
"throughput_jobs_s": round(len(done) / span, 3) if span else None,
|
||||
"lag_p50_s": pct(lag, 0.5), "lag_p95_s": pct(lag, 0.95), "lag_max_s": pct(lag, 1.0),
|
||||
"ttr_p50_s": pct(ttr, 0.5), "ttr_p95_s": pct(ttr, 0.95), "ttr_max_s": pct(ttr, 1.0),
|
||||
}
|
||||
|
||||
|
||||
def record(summary):
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
with open(OUT / "results.jsonl", "a") as handle:
|
||||
handle.write(json.dumps(summary, ensure_ascii=False) + "\n")
|
||||
log(json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
|
||||
def experiment(args, label, max_pending=None):
|
||||
c = Client(timeout=60)
|
||||
wait_http_ready(c)
|
||||
alice = c.user("load")
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "load", "member_ids": [alice["id"]]},
|
||||
schema="Chat")["json"]
|
||||
body, ctype = image(args.size)
|
||||
set_worker(args.replicas, args.concurrency, args.prefetch)
|
||||
time.sleep(2)
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
sampler = Sampler(tag)
|
||||
sampler.start()
|
||||
log("run %s tag=%s size=%s (%d KiB) rate=%s/s duration=%ss workers=%dx(c=%d,p=%d)" % (
|
||||
label, tag, args.size, len(body) >> 10, args.rate, args.duration, args.replicas, args.concurrency, args.prefetch))
|
||||
sent = drive(c, alice, chat, body, ctype, args.rate, args.duration, tag)
|
||||
load_end = time.monotonic()
|
||||
drained = wait_drained(tag, args.drain_timeout)
|
||||
drain_seconds = round(time.monotonic() - load_end, 2)
|
||||
sampler.stop.set()
|
||||
sampler.join()
|
||||
summary = {"label": label, "tag": tag, "size": args.size, "file_kib": len(body) >> 10, "rate": args.rate,
|
||||
"duration": args.duration, "replicas": args.replicas, "concurrency": args.concurrency,
|
||||
"prefetch": args.prefetch, "max_pending": max_pending, **sent, "drained": drained,
|
||||
"drain_after_load_s": drain_seconds, **job_metrics(tag),
|
||||
"pending_max": max(sampler.pending or [0]),
|
||||
"worker_mem_peak_mib": round(max(sampler.rss or [0]), 1),
|
||||
"worker_mem_median_mib": round(statistics.median(sampler.rss), 1) if sampler.rss else None,
|
||||
"worker_cpu_peak_pct": round(max(sampler.cpu or [0]), 1),
|
||||
"at": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
||||
return summary, c, alice, chat
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("mode", choices=["run", "overload"])
|
||||
parser.add_argument("--size", choices=sorted(SIZES), default="medium")
|
||||
parser.add_argument("--rate", type=float, default=4)
|
||||
parser.add_argument("--duration", type=float, default=30)
|
||||
parser.add_argument("--replicas", type=int, default=1)
|
||||
parser.add_argument("--concurrency", type=int, default=2)
|
||||
parser.add_argument("--prefetch", type=int, default=2)
|
||||
parser.add_argument("--max-pending", type=int, default=30)
|
||||
parser.add_argument("--drain-timeout", type=float, default=600)
|
||||
parser.add_argument("--label", default="")
|
||||
args = parser.parse_args()
|
||||
if args.mode == "run":
|
||||
summary, *_ = experiment(args, args.label or "c%d-p%d" % (args.concurrency, args.prefetch))
|
||||
record(summary)
|
||||
return
|
||||
# Overload: admission limit on, offered rate far above capacity, then recovery.
|
||||
set_admission(args.max_pending)
|
||||
try:
|
||||
summary, c, alice, chat = experiment(args, args.label or "overload", args.max_pending)
|
||||
# Recovery probe: after the backlog drained, a fresh upload must be ready quickly again.
|
||||
body, ctype = image("small")
|
||||
t = time.monotonic()
|
||||
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=probe.png" % chat["id"], 202, actor=alice, raw=body,
|
||||
headers={"Content-Type": ctype}, schema="Attachment")["json"]
|
||||
while c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]["status"] != "ready":
|
||||
time.sleep(0.2)
|
||||
summary["recovery_probe_ready_s"] = round(time.monotonic() - t, 2)
|
||||
record(summary)
|
||||
finally:
|
||||
set_admission(200)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+138
@@ -0,0 +1,138 @@
|
||||
"""Helpers for student resilience tests: the public HTTP client plus docker compose / psql / mc access.
|
||||
|
||||
Standard library only (Python 3.9+). Images that need Pillow are generated inside the API container.
|
||||
Never prints tokens or secrets.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
# lab7: every student test talks HTTPS to https://localhost:8443 and verifies it against the stand CA.
|
||||
os.environ.setdefault("CA_FILE", str(ROOT / "secrets/pki/ca.crt"))
|
||||
os.environ.setdefault("BASE_URL", "https://localhost:8443")
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check, run # noqa: E402,F401
|
||||
|
||||
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def log(*parts):
|
||||
print(time.strftime("%H:%M:%S"), *parts, flush=True)
|
||||
|
||||
|
||||
def compose(*args, check_rc=True, capture=True, timeout=180):
|
||||
done = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=capture, text=True, timeout=timeout)
|
||||
if check_rc and done.returncode != 0:
|
||||
raise Failure("docker compose %s failed: %s" % (" ".join(args[:2]), (done.stderr or "")[-300:]))
|
||||
return done.stdout if capture else ""
|
||||
|
||||
|
||||
def started_at(*services):
|
||||
"""Container name -> State.StartedAt, proof that a restart really happened."""
|
||||
ids = compose("ps", "-q", *services).split()
|
||||
out = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.StartedAt}}", *ids],
|
||||
capture_output=True, text=True).stdout
|
||||
return "; ".join(line.strip("/")[:60] for line in out.splitlines())
|
||||
|
||||
|
||||
def sql(query):
|
||||
"""Run a read query in postgres; returns rows as lists of strings (tab separated)."""
|
||||
out = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-F", "\t", "-c", query)
|
||||
return [line.split("\t") for line in out.splitlines() if line]
|
||||
|
||||
|
||||
def s3_keys(prefix):
|
||||
"""Object keys starting with prefix, listed with the root credentials inside a throwaway minio-init container."""
|
||||
wanted, prefix = prefix, prefix[:prefix.rfind("/") + 1]
|
||||
script = ('mkdir -p /tmp/mc/certs/CAs && cp /run/secrets/ca.crt /tmp/mc/certs/CAs/ca.crt && '
|
||||
'mc alias set l https://minio:9000 "$(cat /run/secrets/minio_root_user)" '
|
||||
'"$(cat /run/secrets/minio_root_password)" >/dev/null && '
|
||||
'mc ls --recursive --json l/messenger-attachments/%s || true' % prefix)
|
||||
out = compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "sh", "minio-init", "-c", script)
|
||||
keys = []
|
||||
for line in out.splitlines():
|
||||
try:
|
||||
item = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if item.get("key"):
|
||||
keys.append(prefix + item["key"])
|
||||
return sorted(k for k in keys if k.startswith(wanted))
|
||||
|
||||
|
||||
def queue_depth(queue="attachments.process"):
|
||||
"""None while the broker node is still booting (right after a restart); callers poll (wait_queue)."""
|
||||
out = compose("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "--vhost", "messenger", "list_queues",
|
||||
"name", "messages", "messages_ready", "messages_unacknowledged", check_rc=False)
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if parts and parts[0] == queue and len(parts) == 4 and parts[1].isdigit():
|
||||
return {"messages": int(parts[1]), "ready": int(parts[2]), "unacked": int(parts[3])}
|
||||
return None
|
||||
|
||||
|
||||
def wait_queue(min_ready=1, seconds=30):
|
||||
"""Quorum queue counters are refreshed by the stats emitter (~5 s), so poll."""
|
||||
deadline = time.monotonic() + seconds
|
||||
depth = None
|
||||
while time.monotonic() < deadline:
|
||||
depth = queue_depth()
|
||||
if depth and depth["ready"] >= min_ready:
|
||||
return depth
|
||||
time.sleep(1)
|
||||
return depth
|
||||
|
||||
|
||||
def jobs_cli(*args):
|
||||
done = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "scripts/jobs.py", *args],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=60)
|
||||
return done.returncode, json.loads(done.stdout) if done.stdout.strip() else None
|
||||
|
||||
|
||||
def wait_http_ready(c, seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/health/ready", 200)
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure("API not ready after %ds" % seconds)
|
||||
|
||||
|
||||
def upload(c, actor, chat, body=SAMPLE, filename="sample.png", ctype="image/png", expected=202):
|
||||
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
|
||||
schema = "Attachment" if expected == 202 else None
|
||||
return c.call("POST", path, expected, actor=actor, raw=body, headers={"Content-Type": ctype}, schema=schema)["json"]
|
||||
|
||||
|
||||
def get(c, actor, att_id):
|
||||
return c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
|
||||
|
||||
|
||||
def wait_status(c, actor, att_id, statuses, seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
seen = []
|
||||
while time.monotonic() < deadline:
|
||||
att = get(c, actor, att_id)
|
||||
if not seen or seen[-1] != att["status"]:
|
||||
seen.append(att["status"])
|
||||
if att["status"] in statuses:
|
||||
return att, seen
|
||||
time.sleep(0.5)
|
||||
raise Failure("attachment %s did not reach %s in %ds (seen %s)" % (att_id, statuses, seconds, seen))
|
||||
|
||||
|
||||
def objects_of(att_id):
|
||||
return s3_keys("attachments/%s/" % att_id) + s3_keys("staging/%s" % att_id)
|
||||
|
||||
|
||||
def unique_name(fault=None):
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
return ("fault-%s-%s.png" % (fault, tag)) if fault else ("plain-%s.png" % tag)
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 3-4 negative tests of the application layer over HTTPS (CA verified, no --insecure):
|
||||
|
||||
1. outsider (eve) cannot read chat / history / attachment metadata / content, cannot post, cannot attach
|
||||
another chat's attachment; forged X-User-Id never changes the Bearer identity; Basic on business endpoints = 401
|
||||
2. logout revokes the token on every replica; an expired session is rejected on every replica
|
||||
3. login rate limit shared by the replicas: 5 failures per username -> 429 + Retry-After (even with the right
|
||||
password), counted across api-1 and api-2; per-IP limit -> 429
|
||||
4. request size limits: JSON > 64 KiB -> 413, upload > 10 MiB -> 413
|
||||
5. Argon2id: stored hash has salt + parameters; an old-parameter hash is upgraded on the next successful login
|
||||
|
||||
python3 student-tests/test_auth_acl.py (stand running; ~2 min because of the expiry and rate-limit windows)
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from stand import SAMPLE, Client, check, compose, log, run, sql, upload, wait_status
|
||||
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def ok(name, detail=""):
|
||||
RESULTS.append(name)
|
||||
log("PASS %s %s" % (name, detail))
|
||||
|
||||
|
||||
def instances(responses):
|
||||
return sorted({r["headers"].get("X-Instance-Id") for r in responses})
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return {"Authorization": "Basic " + base64.b64encode(("%s:%s" % (username, password)).encode()).decode()}
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
att = upload(c, alice, chat)
|
||||
wait_status(c, alice, att["id"], ("ready",), 90)
|
||||
cid, aid = chat["id"], att["id"]
|
||||
|
||||
# ------------------------------------------------------------------ 1. ACL
|
||||
for method, path, body in (("GET", "/api/v1/chats/%s" % cid, None), ("GET", "/api/v1/chats/%s/messages" % cid, None),
|
||||
("GET", "/api/v1/attachments/%s" % aid, None),
|
||||
("GET", "/api/v1/attachments/%s/content" % aid, None),
|
||||
("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % aid, None)):
|
||||
r = c.call(method, path, 404, actor=eve)
|
||||
check(r["json"]["error"]["code"] == "not_found", "outsider must get a generic 404")
|
||||
c.call("POST", "/api/v1/chats/%s/messages" % cid, 404, actor=eve, body={"text": "чужой"},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
own = c.call("POST", "/api/v1/chats", 201, actor=eve, body={"title": "eve", "member_ids": [eve["id"]]},
|
||||
schema="Chat")["json"]
|
||||
c.call("POST", "/api/v1/chats/%s/messages" % own["id"], 404, actor=eve, body={"text": "", "attachment_ids": [aid]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
listed = c.call("GET", "/api/v1/chats", actor=eve, schema="ChatPage")["json"]["items"]
|
||||
check(cid not in [x["id"] for x in listed], "foreign chat must not be listed")
|
||||
ok("acl_outsider", "eve: 404 on chat/history/metadata/content/variant/post, cannot attach a foreign file")
|
||||
|
||||
me = c.call("GET", "/api/v1/users/me", actor=eve, headers={"X-User-Id": alice["id"]}, schema="User")["json"]
|
||||
check(me["id"] == eve["id"], "X-User-Id must not change the Bearer identity")
|
||||
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
|
||||
c.call("GET", "/api/v1/chats/%s/messages" % cid, 401, headers=basic(alice["user"]["username"],
|
||||
alice["registration"]["password"]))
|
||||
ok("identity_spoofing", "forged X-User-Id ignored; without Bearer 401; Basic on business endpoint 401")
|
||||
|
||||
# ------------------------------------------------------------------ 2. logout and expiry on every replica
|
||||
s = c.user("logout")
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=s)
|
||||
seen = [c.call("GET", "/api/v1/users/me", 401, actor=s) for _ in range(6)]
|
||||
check(len(instances(seen)) == 2, "revocation must be checked on both replicas, saw %s" % instances(seen))
|
||||
ok("logout", "revoked token: 401 on %s" % instances(seen))
|
||||
|
||||
x = c.user("expiry")
|
||||
c.call("GET", "/api/v1/users/me", actor=x, schema="User")
|
||||
digest = hashlib.sha256(x["token"].encode()).hexdigest()
|
||||
sql("UPDATE sessions SET expires_at = now() - interval '1 second' WHERE token_hash = '\\x%s'" % digest)
|
||||
log("session expires_at moved to the past in PostgreSQL; the Valkey cache entry lives at most 30 s")
|
||||
time.sleep(32)
|
||||
seen = [c.call("GET", "/api/v1/users/me", 401, actor=x) for _ in range(6)]
|
||||
ok("expiry", "expired session: 401 on %s after the 30 s cache bound" % instances(seen))
|
||||
|
||||
# ------------------------------------------------------------------ 5. Argon2id parameters and rehash
|
||||
r = c.user("argon")
|
||||
row = sql("SELECT password_hash FROM users WHERE id = '%s'" % r["id"])[0][0]
|
||||
check(row.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and row.count("$") == 5, "PHC string with params + salt")
|
||||
weak = compose("exec", "-T", "api-1", "python", "-c",
|
||||
"from argon2 import PasswordHasher;import sys;"
|
||||
"print(PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(sys.argv[1]))",
|
||||
r["registration"]["password"]).strip()
|
||||
sql("UPDATE users SET password_hash = '%s' WHERE id = '%s'" % (weak, r["id"]))
|
||||
username, password = r["user"]["username"], r["registration"]["password"]
|
||||
c.call("POST", "/api/v1/auth/sessions", 201, headers=basic(username, password), schema="Session")
|
||||
upgraded = sql("SELECT password_hash FROM users WHERE id = '%s'" % r["id"])[0][0]
|
||||
check(upgraded.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and upgraded != weak, "hash must be upgraded")
|
||||
ok("rehash", "stored %s -> %s after a successful login" % (weak.split("$")[3], upgraded.split("$")[3]))
|
||||
|
||||
# ------------------------------------------------------------------ 4. size limits
|
||||
big = {"text": "x" * 70000}
|
||||
r413 = c.call("POST", "/api/v1/chats/%s/messages" % cid, 413, actor=alice, body=big,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
c.call("POST", "/api/v1/chats/%s/attachments?filename=big.png" % cid, 413, actor=alice,
|
||||
raw=SAMPLE + b"\0" * (10 * 1024 * 1024), headers={"Content-Type": "image/png"})
|
||||
ok("size_limits", "JSON 70 kB -> 413 (%s), upload > 10 MiB -> 413" % r413["json"]["error"]["code"])
|
||||
|
||||
# ------------------------------------------------------------------ 3. shared login rate limit
|
||||
victim = c.user("brute")
|
||||
name = victim["user"]["username"]
|
||||
fails = [c.call("POST", "/api/v1/auth/sessions", 401, headers=basic(name, "wrong-password-123")) for _ in range(5)]
|
||||
limited = c.call("POST", "/api/v1/auth/sessions", 429, headers=basic(name, victim["registration"]["password"]))
|
||||
retry = int(limited["headers"]["Retry-After"])
|
||||
check(limited["json"]["error"]["code"] == "rate_limited" and 1 <= retry <= 60, "429 rate_limited + Retry-After")
|
||||
check(len(instances(fails + [limited])) == 2, "the 6 attempts must hit both replicas")
|
||||
body = json.dumps(limited["json"], ensure_ascii=False)
|
||||
check(victim["registration"]["password"] not in body and "argon" not in body.lower(), "no credential detail")
|
||||
ok("rate_limit_user", "5 failures on %s -> 429 Retry-After=%ds even with the right password" % (
|
||||
instances(fails + [limited]), retry))
|
||||
|
||||
statuses = []
|
||||
for i in range(130):
|
||||
statuses.append(c.call("POST", "/api/v1/auth/sessions", [401, 429],
|
||||
headers=basic("nouser_%d" % i, "wrong-password-123"))["status"])
|
||||
if statuses[-1] == 429:
|
||||
break
|
||||
check(statuses[-1] == 429, "per-IP limit must trigger within 130 attempts")
|
||||
ok("rate_limit_ip", "per-IP limit: 429 after %d attempts from one address" % len(statuses))
|
||||
log("waiting for the rate-limit window to expire so that later tests are not affected")
|
||||
time.sleep(61)
|
||||
print("PASS: %s" % ", ".join(RESULTS))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4: bounded behaviour while OpenBao is sealed (operator incident drill).
|
||||
|
||||
1. operator seals OpenBao (scripts/bao.sh seal)
|
||||
2. running API/worker keep the secrets they hold: public smoke + an upload pipeline still pass;
|
||||
the refresher logs openbao_unavailable (no crash, no fallback to anything weaker)
|
||||
3. a worker restarted while sealed does NOT start with missing/empty credentials: it waits (openbao_not_ready),
|
||||
stays unhealthy, and the other worker keeps processing
|
||||
4. operator unseals (scripts/bao.sh unseal): the waiting worker logs in, becomes healthy; times are recorded
|
||||
python3 student-tests/test_bao_sealed.py (needs the operator OpenBao material)
|
||||
"""
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from stand import ROOT, Client, check, compose, log, run, upload, wait_status
|
||||
|
||||
WORKER2 = "mtusi-lab7-worker-2"
|
||||
|
||||
|
||||
def bao(cmd):
|
||||
out = subprocess.run(["sh", "scripts/bao.sh", cmd], cwd=ROOT, capture_output=True, text=True)
|
||||
check(out.returncode == 0, "bao.sh %s failed: %s" % (cmd, out.stderr[-200:]))
|
||||
return out.stdout.strip().splitlines()[-1]
|
||||
|
||||
|
||||
def health(container):
|
||||
return subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", container],
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
t0 = time.time()
|
||||
log(bao("seal"))
|
||||
try:
|
||||
status = compose("exec", "-T", "-e", "BAO_ADDR=https://127.0.0.1:8200", "-e", "BAO_CACERT=/run/secrets/ca.crt",
|
||||
"openbao", "bao", "status", check_rc=False)
|
||||
check("Sealed true" in status, "OpenBao must be sealed")
|
||||
smoke = subprocess.run(["make", "test", "CA_FILE=%s" % (ROOT / "secrets/pki/ca.crt")], cwd=ROOT,
|
||||
capture_output=True, text=True)
|
||||
check(smoke.returncode == 0, "public smoke must pass while OpenBao is sealed")
|
||||
log("sealed: running services keep working -> %s" % smoke.stdout.strip().splitlines()[-1])
|
||||
time.sleep(20)
|
||||
logs = compose("logs", "--since", "60s", "api-1", "worker")
|
||||
check("openbao_unavailable" in logs, "refresher must report the sealed OpenBao")
|
||||
log("refresher: openbao_unavailable ... keeping cached secret version (seen in API/worker logs)")
|
||||
|
||||
subprocess.run(["docker", "restart", "-t", "20", WORKER2], capture_output=True, check=True)
|
||||
time.sleep(35)
|
||||
state = health(WORKER2)
|
||||
wlogs = subprocess.run(["docker", "logs", "--since", "40s", WORKER2], capture_output=True, text=True)
|
||||
waiting = "openbao_not_ready" in (wlogs.stdout + wlogs.stderr)
|
||||
log("worker-2 restarted while sealed: health=%s, waiting for OpenBao=%s" % (state, waiting))
|
||||
check(state != "healthy" and waiting, "a restarted worker must wait, not run without credentials")
|
||||
att = upload(c, alice, chat, filename="sealed.png")
|
||||
wait_status(c, alice, att["id"], ("ready",), 90)
|
||||
log("upload during the seal processed by the remaining worker: ready")
|
||||
finally:
|
||||
t1 = time.time()
|
||||
log(bao("unseal"))
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline and health(WORKER2) != "healthy":
|
||||
time.sleep(2)
|
||||
check(health(WORKER2) == "healthy", "worker-2 must recover after unseal")
|
||||
log("worker-2 healthy %.0f s after unseal (sealed for %.0f s in total)" % (time.time() - t1, t1 - t0))
|
||||
print("PASS: sealed OpenBao -> running services continue, new process waits, recovery after unseal")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4: rotation of a leaf certificate WITHOUT rebuilding images, revocation of the old identity, expiry.
|
||||
|
||||
Leaf: lb-client (identity lb.client.messenger), the only client allowed by the API replicas.
|
||||
1. background HTTPS traffic through nginx for the whole test (errors are counted)
|
||||
2. scripts/pki.sh issue lb-client new key + serial, files overwritten in place (bind-mounted secrets)
|
||||
3. nginx -s reload new upstream connections present the new certificate; no image build,
|
||||
no container recreate
|
||||
4. old and new certificate both still accepted (old is valid until revoked)
|
||||
5. scripts/pki.sh revoke-serial <old> appended to revoked-serials.txt; the API re-reads it within ~1 s
|
||||
6. old certificate -> refused (reason=revoked in the API log), new -> 200, expired copy -> refused by TLS
|
||||
7. public smoke afterwards
|
||||
New connections are what proves revocation: established keep-alive/TLS sessions are not re-checked, so nginx's
|
||||
upstream keep-alive (4 s) is the upper bound for an already open connection of the old identity.
|
||||
|
||||
python3 student-tests/test_cert_rotation.py
|
||||
"""
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
from openloop import Load
|
||||
from stand import ROOT, check, compose, log, run
|
||||
|
||||
PKI = ROOT / "secrets/pki"
|
||||
|
||||
|
||||
def sh(*args):
|
||||
return subprocess.run(["sh", *args], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip()
|
||||
|
||||
|
||||
def probe(host, *certs):
|
||||
out = compose("run", "--rm", "--no-deps", "-v", "./secrets/pki:/pki:ro", "-v", "./student-tests:/audit:ro",
|
||||
"--entrypoint", "python", "worker", "/audit/mtls_probe.py", host, *certs)
|
||||
return {r["cert"]: r for r in (json.loads(line) for line in out.splitlines() if line.startswith("{"))}
|
||||
|
||||
|
||||
def main():
|
||||
load = Load("https://localhost:8443", users=2, threads=32)
|
||||
stop, summary = threading.Event(), {}
|
||||
thread = threading.Thread(target=lambda: summary.update(load.run(10, 900, stop_event=stop)), daemon=True)
|
||||
thread.start()
|
||||
time.sleep(5)
|
||||
old = sh("scripts/pki.sh", "serial", "lb-client")
|
||||
log("current lb-client serial %s" % old)
|
||||
t0 = time.time()
|
||||
log(sh("scripts/pki.sh", "issue", "lb-client").splitlines()[0])
|
||||
shutil.copy(PKI / "lb-client.crt.previous", PKI / "lb-client-old.crt")
|
||||
shutil.copy(PKI / "lb-client.key.previous", PKI / "lb-client-old.key")
|
||||
new = sh("scripts/pki.sh", "serial", "lb-client")
|
||||
check(new != old, "a new serial must be issued")
|
||||
compose("exec", "-T", "nginx", "nginx", "-s", "reload")
|
||||
log("nginx reloaded with the new client certificate (%.1f s after issue)" % (time.time() - t0))
|
||||
if not (PKI / "lb-client-expired.crt").exists():
|
||||
sh("scripts/pki.sh", "expired", "lb-client")
|
||||
before = probe("api-1", "lb-client-old", "lb-client")
|
||||
check(before["lb-client-old"]["verdict"] == "accepted" and before["lb-client"]["verdict"] == "accepted",
|
||||
"both certificates valid before revocation: %s" % before)
|
||||
log("before revocation: old=%s new=%s" % (before["lb-client-old"]["detail"], before["lb-client"]["detail"]))
|
||||
log(sh("scripts/pki.sh", "revoke-serial", old))
|
||||
time.sleep(2)
|
||||
for api in ("api-1", "api-2"):
|
||||
after = probe(api, "lb-client-old", "lb-client", "lb-client-expired")
|
||||
check(after["lb-client-old"]["verdict"] == "rejected", "%s: revoked old cert must be refused" % api)
|
||||
check(after["lb-client"]["verdict"] == "accepted", "%s: new cert must work" % api)
|
||||
check(after["lb-client-expired"]["verdict"] == "rejected", "%s: expired cert must be refused" % api)
|
||||
log("%s after revocation: old -> %s | new -> %s | expired -> %s" % (
|
||||
api, after["lb-client-old"]["detail"], after["lb-client"]["detail"], after["lb-client-expired"]["detail"]))
|
||||
logs = compose("logs", "--since", "2m", "api-1", "api-2")
|
||||
check("reason=revoked" in logs and old in logs.upper(), "API must log the revoked serial")
|
||||
log("API log: mtls_client_rejected reason=revoked serial=%s" % old)
|
||||
time.sleep(5)
|
||||
stop.set()
|
||||
thread.join(60)
|
||||
bad = summary.get("server_errors_unexpected")
|
||||
log("traffic during rotation: %s requests, %s ok, unexpected errors %s" % (
|
||||
summary.get("requests"), summary.get("ok"), bad))
|
||||
check(bad == 0, "rotation must not break traffic")
|
||||
out = subprocess.run(["make", "test", "CA_FILE=%s" % (PKI / "ca.crt")], cwd=ROOT, capture_output=True, text=True)
|
||||
check(out.returncode == 0, "smoke after rotation")
|
||||
log(out.stdout.strip().splitlines()[-1])
|
||||
print("PASS: lb-client rotated (%s -> %s) without image rebuild, old serial revoked, expired cert refused" % (old, new))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded buffering at the limit: Tempo stopped under 100 req/s until the exporter queue is FULL.
|
||||
Expected: queue_size stops at capacity, extra spans are dropped and counted, collector RSS stays under the container
|
||||
limit, API has no unexpected errors. python3 student-tests/test_exporter_queue_full.py (~5 min)
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import check, compose, log, run
|
||||
from test_incidents import docker_mem
|
||||
|
||||
|
||||
def value(expr):
|
||||
return obs.prom_scalar("sum(%s)" % expr)
|
||||
|
||||
|
||||
def main():
|
||||
load = Load("https://localhost:8443", users=4, threads=96)
|
||||
stop, summary = threading.Event(), {}
|
||||
thread = threading.Thread(target=lambda: summary.update(load.run(100, 900, 1, stop_event=stop)), daemon=True)
|
||||
thread.start()
|
||||
time.sleep(20)
|
||||
q = 'otelcol_exporter_queue_size{exporter="otlp/tempo"}'
|
||||
capacity = value('otelcol_exporter_queue_capacity{exporter="otlp/tempo"}')
|
||||
dropped0, refused0 = value("otelcol_exporter_enqueue_failed_spans_total"), value("otelcol_receiver_refused_spans_total")
|
||||
compose("stop", "-t", "5", "tempo")
|
||||
t0 = time.time()
|
||||
log("tempo stopped; 100 req/s + 1 upload/s; exporter queue capacity=%.0f batches" % capacity)
|
||||
peak_q, mems = 0, []
|
||||
try:
|
||||
for _ in range(16):
|
||||
time.sleep(12)
|
||||
size, mem = value(q), docker_mem("otel-collector")[0]
|
||||
peak_q, _ = max(peak_q, size), mems.append(mem)
|
||||
log(" +%3d s queue=%.0f/%.0f collector_rss=%s dropped=%.0f refused=%.0f" % (
|
||||
time.time() - t0, size, capacity, mem, value("otelcol_exporter_enqueue_failed_spans_total") - dropped0,
|
||||
value("otelcol_receiver_refused_spans_total") - refused0))
|
||||
dropped = value("otelcol_exporter_enqueue_failed_spans_total") - dropped0
|
||||
refused = value("otelcol_receiver_refused_spans_total") - refused0
|
||||
finally:
|
||||
compose("start", "tempo")
|
||||
stop.set()
|
||||
thread.join(60)
|
||||
log("result: peak queue=%.0f/%.0f, dropped by full queue=%.0f spans, refused by memory_limiter=%.0f spans, peak RSS=%s MiB"
|
||||
% (peak_q, capacity, dropped, refused, max(float(m.replace("MiB", "")) for m in mems)))
|
||||
log("API: requests=%s ok=%s unexpected_errors=%s p99=%s ms" % (
|
||||
summary["requests"], summary["ok"], summary["server_errors_unexpected"], summary["latency_ms_plain_ok"]["p99"]))
|
||||
check(peak_q <= capacity, "queue must stay within capacity")
|
||||
check(peak_q >= capacity * 0.95 or refused > 0, "the limit must really be reached")
|
||||
check(dropped + refused > 0, "overflow must be counted")
|
||||
check(summary["server_errors_unexpected"] == 0, "API must be unaffected")
|
||||
print("PASS: exporter buffering is bounded, overflow is dropped and counted, API unaffected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Executable
+194
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 4 fault-injection suite (needs FAULT_INJECTION=1 on the stand, see REPORT.md).
|
||||
|
||||
Each scenario uploads a file whose display name selects an injected fault (app/faults.py) and checks the
|
||||
recovery through the public API plus DB/S3/broker state:
|
||||
A api_crash_after_commit crash between COMMIT(job+outbox) and publish -> another replica's relay publishes
|
||||
B worker_crash_after_put crash after S3 writes, before result COMMIT -> lease expiry -> same keys, one result
|
||||
C worker_crash_after_commit crash after COMMIT, before ack -> redelivery is a no-op
|
||||
D transient3 3 transient errors -> retries with growing jittered backoff -> ready
|
||||
E permanent permanent error -> failed at attempt 1, no retry, content/attach 409
|
||||
F transient6 attempts exhausted -> failed/retry_exhausted -> registry -> explicit replay -> ready;
|
||||
replay of a ready job is refused
|
||||
G worker_hang hung worker (no heartbeats) -> other worker takes over, hung one is fenced
|
||||
H poison message invalid broker message -> DLQ, not retried forever
|
||||
I broker down RabbitMQ stopped: upload still 202 (job waits in outbox) -> broker back -> ready
|
||||
usage: python3 student-tests/test_failure_windows.py [A B C ...]
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
from stand import (Client, Failure, check, compose, get, jobs_cli, log, objects_of, queue_depth, run, sql, upload,
|
||||
unique_name, wait_http_ready, wait_status)
|
||||
|
||||
|
||||
def audit(att_id):
|
||||
return sql("SELECT action, actor, attempt, coalesce(detail->>'error_code',''), coalesce(detail->>'delay_seconds','')"
|
||||
" FROM job_audit WHERE attachment_id='%s' ORDER BY id" % att_id)
|
||||
|
||||
|
||||
def show_audit(att_id):
|
||||
for action, actor, attempt, code, delay in audit(att_id):
|
||||
log(" audit attempt=%s %-16s %-28s %s %s" % (attempt, action, actor[:28], code, ("delay=%ss" % delay) if delay else ""))
|
||||
|
||||
|
||||
def one_result(att_id):
|
||||
variants = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att_id)[0][0]
|
||||
succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att_id)[0][0]
|
||||
keys = objects_of(att_id)
|
||||
check(variants == "3", "exactly one set of 3 variant rows, got %s" % variants)
|
||||
check(succeeded == "1", "exactly one committed success, got %s" % succeeded)
|
||||
check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys),
|
||||
"original + 3 variants, staging cleaned: %s" % keys)
|
||||
|
||||
|
||||
def ready_and_single(c, actor, att_id, seconds=120):
|
||||
att, seen = wait_status(c, actor, att_id, ("ready", "failed"), seconds)
|
||||
check(att["status"] == "ready", "expected ready, got %s/%s" % (att["status"], att["error_code"]))
|
||||
log(" statuses:", " -> ".join(seen))
|
||||
show_audit(att_id)
|
||||
one_result(att_id)
|
||||
return att
|
||||
|
||||
|
||||
def scenario_a(c, alice, bob, chat):
|
||||
name = unique_name("api_crash_after_commit")
|
||||
try:
|
||||
upload(c, alice, chat, filename=name, expected=[202, 500, 502, 503])
|
||||
except Failure as exc:
|
||||
log(" client saw:", exc)
|
||||
wait_http_ready(c)
|
||||
rows = sql("SELECT id FROM attachments WHERE filename='%s'" % name)
|
||||
check(len(rows) == 1, "committed attachment must exist after API crash")
|
||||
att_id = rows[0][0]
|
||||
log(" committed attachment %s survived the API crash" % att_id)
|
||||
ready_and_single(c, bob, att_id)
|
||||
pub = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
|
||||
" WHERE j.attachment_id='%s' AND o.published_at IS NOT NULL" % att_id)[0][0]
|
||||
check(pub == "1", "outbox row published exactly once by the relay")
|
||||
|
||||
|
||||
def scenario_b(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("worker_crash_after_put"))
|
||||
ready_and_single(c, bob, att["id"])
|
||||
actions = [r[0] for r in audit(att["id"])]
|
||||
check("retry_scheduled" in actions, "lease expiry must schedule a new attempt")
|
||||
|
||||
|
||||
def scenario_c(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("worker_crash_after_commit"))
|
||||
ready_and_single(c, bob, att["id"])
|
||||
time.sleep(8)
|
||||
logs = compose("logs", "--since", "60s", "worker")
|
||||
check("decision=done" in logs, "redelivered message after crash must be a no-op")
|
||||
one_result(att["id"])
|
||||
|
||||
|
||||
def scenario_d(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("transient3"))
|
||||
ready_and_single(c, bob, att["id"])
|
||||
delays = [float(r[4]) for r in audit(att["id"]) if r[0] == "retry_scheduled"]
|
||||
check(len(delays) == 3, "three retries expected, got %s" % delays)
|
||||
bounds = [(1, 2), (2, 4), (4, 8)]
|
||||
check(all(lo <= d <= hi for d, (lo, hi) in zip(delays, bounds)), "equal-jitter backoff bounds %s" % delays)
|
||||
log(" backoff delays:", delays)
|
||||
|
||||
|
||||
def scenario_e(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("permanent"))
|
||||
failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 60)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", "permanent -> failed/invalid_image")
|
||||
check(failed["variants"] == [], "failed attachment has no variants")
|
||||
show_audit(att["id"])
|
||||
check([r[0] for r in audit(att["id"])].count("claimed") == 1, "permanent errors are not retried")
|
||||
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
|
||||
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice,
|
||||
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "k-" + att["id"]})
|
||||
|
||||
|
||||
def scenario_f(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("transient6"))
|
||||
failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 120)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "exhausted -> retry_exhausted")
|
||||
attempts = sql("SELECT attempt, max_attempts FROM attachment_jobs WHERE attachment_id='%s'" % att["id"])[0]
|
||||
check(attempts == ["5", "5"], "bounded: stopped at attempt 5 of 5, got %s" % attempts)
|
||||
rc, registry = jobs_cli("failed")
|
||||
check(any(r["attachment_id"] == att["id"] for r in registry), "failed job listed in operator registry")
|
||||
log(" failed registry contains the job; replay")
|
||||
rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite")
|
||||
check(rc == 0 and result["result"] == "queued", "replay must queue: %s" % result)
|
||||
ready_and_single(c, bob, att["id"], 120)
|
||||
rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite")
|
||||
check(rc == 3 and result["result"] == "refused", "replay of a ready job must be refused: %s" % result)
|
||||
log(" second replay refused:", result["reason"])
|
||||
one_result(att["id"])
|
||||
|
||||
|
||||
def scenario_g(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("worker_hang"))
|
||||
ready_and_single(c, bob, att["id"], 150)
|
||||
rows = audit(att["id"])
|
||||
check(any(r[0] == "retry_scheduled" and r[3] == "lease_expired" for r in rows), "lease expiry detected")
|
||||
time.sleep(30) # the hung worker wakes up and must be fenced
|
||||
logs = compose("logs", "--since", "180s", "worker")
|
||||
check("lease_lost" in logs or "job_result_not_committed" in logs, "hung worker must be fenced by the lease")
|
||||
one_result(att["id"])
|
||||
|
||||
|
||||
POISON = ("import asyncio, aio_pika\n"
|
||||
"from app import config, broker\n"
|
||||
"async def m():\n"
|
||||
" conn = await broker.connect(); ch = await conn.channel(publisher_confirms=True)\n"
|
||||
" ex = await broker.get_exchange(ch)\n"
|
||||
" await ex.publish(aio_pika.Message(b'{not json', delivery_mode=2), routing_key=broker.ROUTING_KEY)\n"
|
||||
" await conn.close()\n"
|
||||
"asyncio.run(m())\n")
|
||||
|
||||
|
||||
def scenario_h(c, alice, bob, chat):
|
||||
before = (queue_depth("attachments.dlq") or {}).get("messages", 0)
|
||||
compose("exec", "-T", "api-1", "python", "-c", POISON)
|
||||
deadline = time.monotonic() + 30
|
||||
after = before
|
||||
while time.monotonic() < deadline and after <= before:
|
||||
time.sleep(1)
|
||||
after = (queue_depth("attachments.dlq") or {}).get("messages", 0)
|
||||
check(after == before + 1, "poison message must land in attachments.dlq (%s -> %s)" % (before, after))
|
||||
log(" DLQ depth %s -> %s" % (before, after))
|
||||
|
||||
|
||||
def scenario_i(c, alice, bob, chat):
|
||||
compose("stop", "-t", "10", "rabbitmq")
|
||||
try:
|
||||
att = upload(c, alice, chat, filename=unique_name())
|
||||
check(att["status"] == "queued", "upload accepted while broker is down")
|
||||
c.message(alice, chat, "", attachments=[att["id"]])
|
||||
time.sleep(3)
|
||||
pending = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
|
||||
" WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0]
|
||||
check(pending == "1", "job must wait in the outbox, got %s" % pending)
|
||||
check(get(c, bob, att["id"])["status"] == "queued", "still queued while broker is down")
|
||||
log(" broker down: upload 202, outbox holds 1 unpublished job")
|
||||
finally:
|
||||
compose("start", "rabbitmq")
|
||||
ready_and_single(c, bob, att["id"], 120)
|
||||
|
||||
|
||||
SCENARIOS = {"A": scenario_a, "B": scenario_b, "C": scenario_c, "D": scenario_d, "E": scenario_e,
|
||||
"F": scenario_f, "G": scenario_g, "H": scenario_h, "I": scenario_i}
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
picked = sys.argv[1:] or list(SCENARIOS)
|
||||
for key in picked:
|
||||
log("scenario %s: %s" % (key, SCENARIOS[key].__name__))
|
||||
started = time.monotonic()
|
||||
SCENARIOS[key](c, alice, bob, chat)
|
||||
log("scenario %s PASS (%.1fs)" % (key, time.monotonic() - started))
|
||||
print("PASS: failure windows %s" % " ".join(picked))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,269 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4 controlled incidents, diagnosed ONLY from stored telemetry (Prometheus / Loki / Tempo), with alert
|
||||
firing -> resolved timings. A background open-loop traffic (messages + history, 2% slow handler requests) runs all
|
||||
the time so that error ratios have a denominator.
|
||||
|
||||
A. worker stopped -> MessengerQueueLagGrowing firing; start worker -> backlog drains -> resolved
|
||||
B. DB table lock (slow DB) -> MessengerApiHighErrorRate firing; trace shows the INSERT span waiting 5 s on the lock
|
||||
(vs. an X-Fault: slow request: long handler, short DB spans); unlock -> resolved
|
||||
C. Tempo + Loki stopped -> API keeps working, collector queue bounded, drops counted, TelemetryExportFailing;
|
||||
collector stopped -> API keeps working, SDK queues bounded (RSS flat)
|
||||
|
||||
python3 student-tests/test_incidents.py [--only A,B,C] (stack running, FAULT_INJECTION=1; ~15 min)
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import Client, check, compose, log, run, upload, wait_status
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULTS = {}
|
||||
|
||||
|
||||
def docker_mem(service):
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}\t{{.CPUPerc}}"],
|
||||
capture_output=True, text=True).stdout
|
||||
for line in out.splitlines():
|
||||
name, mem, cpu = line.split("\t")
|
||||
if name.startswith("mtusi-lab6-%s-" % service):
|
||||
return mem.split(" / ")[0], cpu
|
||||
return "stopped", "-"
|
||||
|
||||
|
||||
def wait_alert(name, want, seconds, t0):
|
||||
"""want='firing' waits for firing; want='resolved' waits until the alert is gone. Returns seconds since t0."""
|
||||
deadline = time.monotonic() + seconds
|
||||
pending_at = None
|
||||
while time.monotonic() < deadline:
|
||||
state = obs.alerts().get(name)
|
||||
if state == "pending" and pending_at is None:
|
||||
pending_at = time.time() - t0
|
||||
log(" %s pending (+%.0f s)" % (name, pending_at))
|
||||
if (want == "firing" and state == "firing") or (want == "resolved" and state is None):
|
||||
elapsed = time.time() - t0
|
||||
log(" %s %s (+%.0f s)" % (name, want, elapsed))
|
||||
return elapsed, pending_at
|
||||
time.sleep(5)
|
||||
raise AssertionError("%s did not become %s within %d s" % (name, want, seconds))
|
||||
|
||||
|
||||
def psql(query):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", query)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ A
|
||||
def incident_worker(c, alice, chat):
|
||||
log("=== A. worker stopped (queue lag)")
|
||||
t0 = time.time()
|
||||
compose("stop", "-t", "20", "worker")
|
||||
log("worker stopped at %s" % time.strftime("%H:%M:%S"))
|
||||
atts = [upload(c, alice, chat, filename="incident-a.png") for _ in range(3)]
|
||||
log("3 uploads accepted (202) while worker is down: %s" % [a["id"][:8] for a in atts])
|
||||
firing, pending = wait_alert("MessengerQueueLagGrowing", "firing", 300, t0)
|
||||
|
||||
log("diagnosis from telemetry:")
|
||||
age = obs.prom_scalar('max(messenger_queue_oldest_age_seconds{queue="attachments.process"})')
|
||||
depth = {m["state"]: v for m, v in obs.prom('max by (state) (messenger_queue_depth{queue="attachments.process"})')}
|
||||
processed = obs.prom_scalar('sum(rate(messenger_jobs_processed_total[1m]))')
|
||||
log(" metrics: oldest job age=%.0f s, depth=%s, worker jobs/s over 1m=%.3f" % (age, depth, processed))
|
||||
since = int((time.time() - t0) / 60) + 1
|
||||
worker_lines = obs.loki('{service_name="messenger-worker"} | event=~"job_.*"', minutes=since)
|
||||
worker_lines = [l for l in worker_lines if l["ts"] / 1e9 > t0 + 25]
|
||||
stop_lines = obs.loki('{service_name="messenger-worker"} | event=~"worker_stop.*"', minutes=since + 1)
|
||||
log(" logs: worker job_* events after stop: %d; last worker events: %s" % (
|
||||
len(worker_lines), [l.get("event") for l in stop_lines[-2:]]))
|
||||
traces = obs.tempo_search('{span.messenger.attachment_id="%s"}' % atts[0]["id"], minutes=since + 1)
|
||||
spans = obs.tempo_trace(traces[0]["traceID"]) if traces else []
|
||||
kinds = sorted({s["kind"] for s in spans if s["kind"] != "CLIENT"})
|
||||
log(" trace of upload %s: span kinds %s -> published, no CONSUMER: the job waits in the queue" % (
|
||||
atts[0]["id"][:8], kinds))
|
||||
check("PRODUCER" in kinds and "CONSUMER" not in kinds, "trace must stop at the producer while worker is down")
|
||||
|
||||
t1 = time.time()
|
||||
compose("start", "worker")
|
||||
log("worker started (+%.0f s)" % (t1 - t0))
|
||||
for att in atts:
|
||||
wait_status(c, alice, att["id"], ("ready",), 120)
|
||||
drained = time.time() - t1
|
||||
log("backlog drained: all 3 ready %.1f s after worker start" % drained)
|
||||
resolved, _ = wait_alert("MessengerQueueLagGrowing", "resolved", 300, t1)
|
||||
RESULTS["A_worker_stopped"] = {"alert_pending_s": pending, "alert_firing_s": round(firing), "age_at_firing_s":
|
||||
round(age), "drain_after_restart_s": round(drained, 1),
|
||||
"resolved_after_restart_s": round(resolved), "lost_jobs": 0}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ B
|
||||
def incident_db(c):
|
||||
log("=== B. DB lock on messages (slow/unavailable DB for writes and history reads)")
|
||||
t0 = time.time()
|
||||
locker = subprocess.Popen(
|
||||
["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
|
||||
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(600); COMMIT;"],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
log("ACCESS EXCLUSIVE lock taken on table messages at %s" % time.strftime("%H:%M:%S"))
|
||||
try:
|
||||
firing, pending = wait_alert("MessengerApiHighErrorRate", "firing", 300, t0)
|
||||
log("diagnosis from telemetry:")
|
||||
ratio = obs.prom_scalar("messenger:http_error_ratio:rate2m")
|
||||
p95 = obs.prom_scalar("messenger:http_latency_p95:rate5m")
|
||||
by_route = obs.prom('sum by (http_route, http_response_status_code) (rate(http_server_request_duration_seconds_count'
|
||||
'{service_name="messenger-api",http_response_status_code=~"5.."}[1m]))')
|
||||
waiting = obs.prom_scalar("max(db_client_connection_pending_requests)")
|
||||
used = obs.prom_scalar('max(db_client_connection_count{service_name="messenger-api",db_client_connection_state="used"})')
|
||||
log(" metrics: 5xx ratio=%.1f%%, p95=%.2f s, pool used(max replica)=%.0f waiting=%.0f" % (
|
||||
ratio * 100, p95, used, waiting))
|
||||
for m, v in by_route:
|
||||
log(" 5xx/s %-40s %s %.2f" % (m.get("http_route"), m.get("http_response_status_code"), v))
|
||||
db_err = obs.tempo_search('{resource.service.name="messenger-api" && span.db.operation.name="INSERT"'
|
||||
' && status=error}', minutes=5, limit=5)
|
||||
check(db_err, "no trace with a failed DB span")
|
||||
spans = obs.tempo_trace(db_err[0]["traceID"])
|
||||
log(" trace %s (failed request):" % db_err[0]["traceID"])
|
||||
obs.print_tree(spans, out=lambda line: print(" " + line))
|
||||
raw = obs.tempo_raw(db_err[0]["traceID"])
|
||||
cause = next((name for name in ("LockNotAvailable", "QueryCanceled", "PoolTimeout") if name in raw), "?")
|
||||
db_span = max((s for s in spans if s["attrs"].get("db.system") == "postgresql"), key=lambda s: s["duration_ms"])
|
||||
server = [s for s in spans if s["kind"] == "SERVER"][0]
|
||||
log(" => DB span %s took %.0f ms of %.0f ms request, status %s, exception %s: the time is spent in PostgreSQL"
|
||||
% (db_span["name"], db_span["duration_ms"], server["duration_ms"], db_span["status"], cause))
|
||||
slow = obs.tempo_search('{span.messenger.fault="slow" && span.http.route="/api/v1/chats/{chat_id}/messages"}',
|
||||
minutes=10, limit=50)
|
||||
contrast = None
|
||||
for item in slow:
|
||||
sp = obs.tempo_trace(item["traceID"])
|
||||
srv = [s for s in sp if s["kind"] == "SERVER"]
|
||||
dbs = [s["duration_ms"] for s in sp if s["attrs"].get("db.system") == "postgresql"]
|
||||
if srv and dbs and srv[0]["attrs"].get("http.response.status_code") in ("200", 200) and max(dbs) < 100:
|
||||
contrast = (item["traceID"], srv[0]["duration_ms"], max(dbs), sum(dbs))
|
||||
break
|
||||
if contrast:
|
||||
log(" contrast: slow HANDLER trace %s: request %.0f ms, longest DB span %.1f ms, all DB %.1f ms"
|
||||
% contrast)
|
||||
errors = obs.loki('{service_name="messenger-api"} | severity_text=~"WARN.*|ERROR"', minutes=5)
|
||||
log(" logs: %d API warning/error records in 5 min, events=%s" % (
|
||||
len(errors), sorted({l.get("event") for l in errors})))
|
||||
blocker = psql("SELECT pid, state, wait_event_type, left(query, 60) FROM pg_stat_activity "
|
||||
"WHERE query LIKE '%LOCK TABLE messages%' AND pid <> pg_backend_pid()").strip()
|
||||
log(" operator step (pg_stat_activity) finds the blocker: %s" % blocker)
|
||||
finally:
|
||||
t1 = time.time()
|
||||
psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE query LIKE '%LOCK TABLE messages%'"
|
||||
" AND pid <> pg_backend_pid()")
|
||||
locker.wait(30)
|
||||
log("lock released (+%.0f s)" % (t1 - t0))
|
||||
resolved, _ = wait_alert("MessengerApiHighErrorRate", "resolved", 400, t1)
|
||||
RESULTS["B_db_lock"] = {"alert_pending_s": pending, "alert_firing_s": round(firing),
|
||||
"error_ratio_at_firing": round(ratio, 3), "p95_at_firing_s": round(p95, 2),
|
||||
"db_span_ms": round(db_span["duration_ms"]), "request_ms": round(server["duration_ms"]),
|
||||
"cause": cause, "resolved_after_unlock_s": round(resolved)}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ C
|
||||
def counter(expr):
|
||||
return obs.prom_scalar("sum(%s)" % expr)
|
||||
|
||||
|
||||
def incident_telemetry(load):
|
||||
log("=== C1. Tempo and Loki stopped (telemetry backends down)")
|
||||
before_res = len(load.results)
|
||||
dropped0 = counter('otelcol_exporter_enqueue_failed_spans_total') + counter(
|
||||
'otelcol_exporter_enqueue_failed_log_records_total')
|
||||
failed0 = counter('otelcol_exporter_send_failed_spans_total') + counter(
|
||||
'otelcol_exporter_send_failed_log_records_total')
|
||||
t0 = time.time()
|
||||
compose("stop", "-t", "5", "tempo", "loki")
|
||||
samples = []
|
||||
for i in range(14): # ~140 s
|
||||
time.sleep(10)
|
||||
mem, cpu = docker_mem("otel-collector")
|
||||
q_tempo = obs.prom_scalar('sum(otelcol_exporter_queue_size{exporter="otlp/tempo"})')
|
||||
q_loki = obs.prom_scalar('sum(otelcol_exporter_queue_size{exporter="otlphttp/loki"})')
|
||||
samples.append({"t": round(time.time() - t0), "collector_mem": mem, "cpu": cpu, "queue_tempo": q_tempo,
|
||||
"queue_loki": q_loki})
|
||||
log(" +%3d s collector mem=%s cpu=%s queue tempo=%.0f loki=%.0f (capacity 100 batches)" % (
|
||||
samples[-1]["t"], mem, cpu, q_tempo, q_loki))
|
||||
alert_state = obs.alerts().get("TelemetryExportFailing")
|
||||
log(" alert TelemetryExportFailing during outage: %s" % alert_state)
|
||||
check(alert_state == "firing", "TelemetryExportFailing must fire while backends are down")
|
||||
window = [r for r in load.results[before_res:]]
|
||||
bad = [r for r in window if r["fault"] != "error" and (not isinstance(r["status"], int) or r["status"] >= 500)]
|
||||
log(" API during the outage: %d requests, unexpected errors=%d; alert TelemetryExportFailing=%s" % (
|
||||
len(window), len(bad), alert_state))
|
||||
check(not bad, "API must keep working while telemetry backends are down")
|
||||
compose("start", "tempo", "loki")
|
||||
obs.wait_for(lambda: subprocess.run(["curl", "-sf", obs.TEMPO + "/ready"], capture_output=True).returncode == 0
|
||||
and subprocess.run(["curl", "-sf", obs.LOKI + "/ready"], capture_output=True).returncode == 0, 120, 3)
|
||||
t1 = time.time()
|
||||
log(" tempo/loki started and ready (+%.0f s)" % (t1 - t0))
|
||||
fresh = obs.wait_for(lambda: obs.tempo_search('{resource.service.name="messenger-api"}', start=t1,
|
||||
end=time.time() + 5, limit=20), 90, 5)
|
||||
log(" new traces after restart visible: %d (export resumed)" % len(fresh or []))
|
||||
check(fresh, "traces must flow again after the backends are back")
|
||||
resolved, _ = wait_alert("TelemetryExportFailing", "resolved", 300, t1)
|
||||
time.sleep(20)
|
||||
dropped = counter('otelcol_exporter_enqueue_failed_spans_total') + counter(
|
||||
'otelcol_exporter_enqueue_failed_log_records_total') - dropped0
|
||||
failed = counter('otelcol_exporter_send_failed_spans_total') + counter(
|
||||
'otelcol_exporter_send_failed_log_records_total') - failed0
|
||||
log(" telemetry lost and counted: enqueue_failed(queue full)=%.0f items, send_failed(retries exhausted)=%.0f items"
|
||||
% (dropped, failed))
|
||||
RESULTS["C1_backends_down"] = {"outage_s": round(t1 - t0), "api_requests": len(window), "api_unexpected_errors":
|
||||
len(bad), "collector_samples": samples, "alert": alert_state,
|
||||
"dropped_items": dropped, "send_failed_items": failed,
|
||||
"traces_after_restart": len(fresh or []),
|
||||
"alert_resolved_after_restart_s": round(resolved)}
|
||||
|
||||
log("=== C2. Collector stopped (SDK side buffering)")
|
||||
before_res = len(load.results)
|
||||
api_before = docker_mem("api-1")[0]
|
||||
compose("stop", "-t", "5", "otel-collector")
|
||||
mems = []
|
||||
for _ in range(6):
|
||||
time.sleep(10)
|
||||
mems.append(docker_mem("api-1")[0])
|
||||
window = load.results[before_res:]
|
||||
bad = [r for r in window if r["fault"] != "error" and (not isinstance(r["status"], int) or r["status"] >= 500)]
|
||||
compose("start", "otel-collector")
|
||||
log(" api-1 RSS before=%s during=%s; %d requests, unexpected errors=%d" % (api_before, mems, len(window), len(bad)))
|
||||
check(not bad, "API must keep working while the collector is down")
|
||||
RESULTS["C2_collector_down"] = {"outage_s": 60, "api1_mem_before": api_before, "api1_mem_during": mems,
|
||||
"api_requests": len(window), "api_unexpected_errors": len(bad)}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--only", default="A,B,C")
|
||||
p.add_argument("--output", default=str(ROOT / "evidence/incidents.json"))
|
||||
args = p.parse_args()
|
||||
c = Client()
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
load = Load("https://localhost:8443", users=2, threads=48)
|
||||
stop = threading.Event()
|
||||
traffic = threading.Thread(target=lambda: RESULTS.setdefault("traffic", load.run(
|
||||
10, 3600, 0, slow_pct=2, error_pct=0, stop_event=stop)), daemon=True)
|
||||
traffic.start()
|
||||
log("background traffic: 10 req/s open-loop (75% POST message, 25% history, 2% X-Fault: slow)")
|
||||
time.sleep(30)
|
||||
try:
|
||||
if "A" in args.only:
|
||||
incident_worker(c, alice, chat)
|
||||
if "B" in args.only:
|
||||
incident_db(c)
|
||||
if "C" in args.only:
|
||||
incident_telemetry(load)
|
||||
finally:
|
||||
stop.set()
|
||||
traffic.join(60)
|
||||
Path(args.output).write_text(json.dumps(RESULTS, ensure_ascii=False, indent=2, default=str) + "\n")
|
||||
log("summary written to %s" % args.output)
|
||||
print("PASS: incidents %s diagnosed from telemetry, alerts fired and resolved" % args.only)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Levels 3-4: one controlled upload and one failed request are found in traces, logs and metrics; privacy checks.
|
||||
|
||||
1. upload with fault-transient1 (attempt 1 fails transiently, attempt 2 succeeds) -> ONE trace:
|
||||
API SERVER span -> PRODUCER -> CONSUMER (retry, ERROR) -> PRODUCER -> CONSUMER (succeeded) -> S3/DB spans
|
||||
2. the same trace_id in Loki for messenger-api and messenger-worker log records
|
||||
3. X-Request-Id of a 500 (X-Fault: error) -> Loki log line -> its trace_id -> Tempo server span with that request_id
|
||||
4. no password / token / message text / filename in logs or traces; no ids in metric labels
|
||||
5. all metric names used by the dashboard and alert rules exist and have samples
|
||||
|
||||
python3 student-tests/test_observability.py (stack from REPORT.md must be running; FAULT_INJECTION=1)
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import obs
|
||||
from stand import Client, check, log, run, unique_name, upload, wait_status
|
||||
|
||||
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
FORBIDDEN_LABELS = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "url_full", "url_query",
|
||||
"filename", "text", "http_target", "url_path"}
|
||||
REQUIRED_METRICS = [
|
||||
"http_server_request_duration_seconds_bucket", "messenger_jobs_processed_total",
|
||||
"messenger_job_duration_seconds_bucket", "messenger_attachment_time_to_ready_seconds_bucket",
|
||||
"messenger_queue_depth", "messenger_queue_oldest_age_seconds", "messenger_worker_busy",
|
||||
"messenger_worker_capacity", "db_client_connection_count", "db_client_connection_pending_requests",
|
||||
"process_cpu_time_seconds_total", "process_memory_usage_bytes", "otelcol_receiver_accepted_spans_total",
|
||||
"otelcol_exporter_sent_spans_total", "otelcol_exporter_queue_size",
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
marker = "secret-text-" + uuid.uuid4().hex
|
||||
sent = c.message(alice, chat, marker)
|
||||
msg_rid = sent["headers"]["X-Request-Id"]
|
||||
log("message sent request_id=%s (text marker kept private)" % msg_rid)
|
||||
|
||||
# ---------------------------------------------------------------- 1. upload -> retry -> ready, one trace
|
||||
filename = unique_name("transient1")
|
||||
att = upload(c, alice, chat, filename=filename)
|
||||
ready, seen = wait_status(c, bob, att["id"], ("ready", "failed"), 90)
|
||||
check(ready["status"] == "ready", "upload must become ready after one retry")
|
||||
log("upload %s: %s" % (att["id"], " -> ".join(["queued"] + seen)))
|
||||
|
||||
def find():
|
||||
found = obs.tempo_search('{span.messenger.attachment_id="%s"}' % att["id"])
|
||||
if not found:
|
||||
return None
|
||||
spans = obs.tempo_trace(found[0]["traceID"])
|
||||
consumers = [s for s in spans if s["kind"] == "CONSUMER"]
|
||||
producers = [s for s in spans if s["kind"] == "PRODUCER"]
|
||||
# Spans of one trace arrive from 3 processes with different batch delays: wait until all are in.
|
||||
return (found, spans) if len(consumers) >= 2 and len(producers) >= 2 and any(
|
||||
s["attrs"].get("messenger.job.outcome") == "succeeded" for s in consumers) else None
|
||||
|
||||
result = obs.wait_for(find, 60)
|
||||
check(result, "trace of the upload with both attempts not found in Tempo")
|
||||
found, spans = result
|
||||
trace_ids = {t["traceID"] for t in found}
|
||||
check(len(trace_ids) == 1, "upload and its jobs must be ONE trace, got %s" % trace_ids)
|
||||
trace_id = found[0]["traceID"]
|
||||
log("Tempo: trace %s, %d spans; tree (DB client spans omitted):" % (trace_id, len(spans)))
|
||||
obs.print_tree(spans, out=lambda line: print(" " + line), skip_db=True)
|
||||
|
||||
by_id = {s["span_id"]: s for s in spans}
|
||||
server = [s for s in spans if s["kind"] == "SERVER" and s["service"] == "messenger-api"]
|
||||
producers = [s for s in spans if s["kind"] == "PRODUCER"]
|
||||
consumers = [s for s in spans if s["kind"] == "CONSUMER"]
|
||||
check(len(server) == 1 and server[0]["name"] == "POST /api/v1/chats/{chat_id}/attachments", "API server span")
|
||||
check(len(producers) >= 2 and len(consumers) >= 2, "two publish/consume pairs (attempt 1 + retry)")
|
||||
for cons in consumers:
|
||||
parent = by_id.get(cons["parent_id"])
|
||||
check(parent is not None and parent["kind"] == "PRODUCER", "consumer must be a child of a producer span")
|
||||
check(by_id[producers[0]["parent_id"]]["kind"] == "SERVER", "first producer is a child of the upload request")
|
||||
retry_parent = by_id[producers[1]["parent_id"]]
|
||||
check(retry_parent["kind"] == "CONSUMER" and retry_parent["attrs"].get("messenger.job.outcome") == "retry",
|
||||
"retry producer must be a child of the failed consumer")
|
||||
check(consumers[0]["status"] == "ERROR" and consumers[-1]["attrs"].get("messenger.job.outcome") == "succeeded",
|
||||
"attempt 1 ERROR/retry, last attempt succeeded")
|
||||
worker_ops = {s["name"] for s in spans if s["service"] == "messenger-worker"}
|
||||
for op in ("S3.GetObject", "S3.CopyObject", "S3.PutObject", "imageproc"):
|
||||
check(op in worker_ops, "worker span %s missing" % op)
|
||||
check(any(s["service"] == "messenger-worker" and s["attrs"].get("db.system") == "postgresql" for s in spans),
|
||||
"worker DB spans missing")
|
||||
log("PASS: W3C context API -> outbox -> broker -> worker (retry) -> S3/DB is one trace with producer/consumer links")
|
||||
|
||||
# ---------------------------------------------------------------- 2. logs of both services with the trace_id
|
||||
lines = obs.wait_for(lambda: [l for l in obs.loki('{service_name=~"messenger-api|messenger-worker"} | trace_id="%s"'
|
||||
% trace_id) if True] or None, 30)
|
||||
check(lines, "no Loki records with the trace_id")
|
||||
services = {l["service_name"] for l in lines}
|
||||
events = [(l["service_name"].replace("messenger-", ""), l.get("event")) for l in lines]
|
||||
log("Loki: %d records with trace_id=%s: %s" % (len(lines), trace_id, events))
|
||||
check(services == {"messenger-api", "messenger-worker"}, "logs of both services must carry the trace_id")
|
||||
check({"attachment_queued", "job_attempt_failed", "job_finished"} <= {e for _, e in events},
|
||||
"expected events attachment_queued, job_attempt_failed, job_finished")
|
||||
sample = lines[0]
|
||||
log("Loki record fields: %s" % sorted(k for k in sample if k not in ("line",)))
|
||||
|
||||
# ---------------------------------------------------------------- 3. X-Request-Id of an HTTP error -> log -> trace
|
||||
err = c.call("GET", "/api/v1/chats", 500, actor=alice, headers={"X-Fault": "error"})
|
||||
rid = err["headers"]["X-Request-Id"]
|
||||
check(err["json"]["error"]["request_id"] == rid and "Traceback" not in err["bytes"].decode(), "500 body is clean")
|
||||
err_lines = obs.wait_for(lambda: obs.loki('{service_name="messenger-api"} |= "%s"' % rid, minutes=5) or None, 30)
|
||||
check(err_lines, "500 request_id not found in Loki")
|
||||
err_trace = err_lines[0].get("trace_id")
|
||||
log("HTTP 500 X-Request-Id=%s -> Loki event=%s trace_id=%s" % (rid, err_lines[0].get("event"), err_trace))
|
||||
err_spans = obs.wait_for(lambda: obs.tempo_trace(err_trace) or None, 30)
|
||||
check(err_spans, "trace of the 500 not in Tempo")
|
||||
srv = [s for s in err_spans if s["kind"] == "SERVER"][0]
|
||||
check(srv["attrs"].get("messenger.request_id") == rid and srv["status"] == "ERROR"
|
||||
and str(srv["attrs"].get("http.response.status_code")) == "500", "server span must carry request_id and ERROR")
|
||||
log("Tempo: %s status=%s request_id matches; exception event recorded=%s" % (
|
||||
srv["name"], srv["status"], "exception" in obs.tempo_raw(err_trace)))
|
||||
|
||||
msg_trace = obs.wait_for(lambda: obs.tempo_search('{span.messenger.request_id="%s"}' % msg_rid) or None, 30)
|
||||
check(msg_trace, "message request trace not found by request_id")
|
||||
msg_spans = obs.tempo_trace(msg_trace[0]["traceID"])
|
||||
log("message POST trace %s: %s" % (msg_trace[0]["traceID"], [s["name"] for s in msg_spans]))
|
||||
|
||||
# ---------------------------------------------------------------- 4. privacy
|
||||
secrets = {"password": alice["registration"]["password"], "token": alice["token"], "message text": marker,
|
||||
"filename": filename}
|
||||
raw = obs.tempo_raw(trace_id) + obs.tempo_raw(msg_trace[0]["traceID"]) + obs.tempo_raw(err_trace)
|
||||
logs_raw = "\n".join(str(l) for l in obs.loki('{service_name=~"messenger-.*"}', minutes=10, limit=5000))
|
||||
for what, value in secrets.items():
|
||||
check(value not in raw, "%s leaked into traces" % what)
|
||||
check(value not in logs_raw, "%s leaked into logs" % what)
|
||||
# Image bytes: PNG signature/IHDR chunk as raw, escaped or base64 text (sample.png starts with iVBORw0KGgo).
|
||||
for word in ("Authorization", "Bearer ", "filename=", "X-Amz-Signature", "iVBORw0KGgo", "IHDR", "\\x89PNG",
|
||||
"\\u0089PNG"):
|
||||
check(word not in raw and word not in logs_raw, "%r found in telemetry" % word)
|
||||
log("PASS: password, bearer token, message text, filename, Authorization, signed URLs, image bytes absent from "
|
||||
"traces and logs")
|
||||
|
||||
series = obs.prom('{__name__=~"messenger_.*|http_server_.*|db_client_.*|process_.*"}')
|
||||
labels = set()
|
||||
for metric, _ in series:
|
||||
labels |= set(metric)
|
||||
for name, value in metric.items():
|
||||
check(not UUID_RE.search(value), "UUID-like value in metric label %s=%s" % (name, value))
|
||||
check(not labels & FORBIDDEN_LABELS, "forbidden metric labels: %s" % (labels & FORBIDDEN_LABELS))
|
||||
log("PASS: %d series, label names: %s" % (len(series), sorted(labels)))
|
||||
routes = sorted({m.get("http_route") for m, _ in series if m.get("http_route")})
|
||||
log("http_route values (templates only): %s" % routes)
|
||||
|
||||
# ---------------------------------------------------------------- 5. metrics referenced by dashboard/alerts
|
||||
time.sleep(12) # one metric export interval
|
||||
for name in REQUIRED_METRICS:
|
||||
check(obs.prom(name), "metric %s has no samples" % name)
|
||||
log("PASS: required metrics present: %s" % ", ".join(REQUIRED_METRICS))
|
||||
print("PASS: observability levels 3-4 (traces/logs/metrics correlation and privacy)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4: rotation of one working secret without image rebuild or restart: the DB password of role app_worker.
|
||||
|
||||
1. background traffic (messages + 1 upload/s) through HTTPS for the whole test
|
||||
2. operator: scripts/bao.sh rotate-worker-db -> ALTER ROLE app_worker + new KV version messenger/worker
|
||||
3. both workers pick up the new version from OpenBao (refresh <= BAO_REFRESH_SECONDS) and switch the pool
|
||||
4. existing app_worker sessions are terminated in PostgreSQL: the pool must reconnect WITH THE NEW password
|
||||
5. old password refused, new password accepted (probe from inside the network); uploads keep reaching ready
|
||||
Passwords are held in memory only for the probes and are never printed.
|
||||
|
||||
python3 student-tests/test_secret_rotation.py (needs the operator OpenBao material: scripts/bao.sh)
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
from openloop import Load
|
||||
from stand import ROOT, Client, check, compose, log, run, sql, upload, wait_status
|
||||
|
||||
PROBE = ("import os,psycopg\n"
|
||||
"try:\n"
|
||||
" psycopg.connect('postgresql://app_worker@postgres:5432/messenger', password=os.environ['PW'],"
|
||||
" sslmode='verify-full', sslrootcert='/run/secrets/ca.crt', connect_timeout=5).close(); print('accepted')\n"
|
||||
"except psycopg.Error as e:\n print('rejected: ' + str(e).splitlines()[0][-60:])\n")
|
||||
|
||||
|
||||
def probe(password):
|
||||
out = subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-e", "PW", "--entrypoint", "python",
|
||||
"worker", "-c", PROBE], cwd=ROOT, env={**os.environ, "PW": password},
|
||||
capture_output=True, text=True).stdout
|
||||
return [line for line in out.splitlines() if line.startswith(("accepted", "rejected"))][-1]
|
||||
|
||||
|
||||
def worker_logs(since):
|
||||
return compose("logs", "--since", since, "worker")
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
load = Load("https://localhost:8443", users=2, threads=32)
|
||||
stop, summary = threading.Event(), {}
|
||||
thread = threading.Thread(target=lambda: summary.update(load.run(5, 900, 1, stop_event=stop)), daemon=True)
|
||||
thread.start()
|
||||
old = (ROOT / "secrets/bootstrap/db_worker_password").read_text().strip()
|
||||
check(probe(old) == "accepted", "old password must work before the rotation")
|
||||
before = int(sql("SELECT count(*) FROM pg_stat_activity WHERE usename = 'app_worker'")[0][0])
|
||||
log("before: old password accepted, %d app_worker connections open" % before)
|
||||
|
||||
t0 = time.time()
|
||||
out = subprocess.run(["sh", "scripts/bao.sh", "rotate-worker-db"], cwd=ROOT, capture_output=True, text=True)
|
||||
check(out.returncode == 0, "rotation script failed: %s" % out.stderr[-200:])
|
||||
log(out.stdout.strip().splitlines()[-1])
|
||||
new = (ROOT / "secrets/bootstrap/db_worker_password").read_text().strip()
|
||||
check(new != old, "password must change")
|
||||
|
||||
deadline = time.time() + 60
|
||||
while time.time() < deadline:
|
||||
logs = worker_logs("90s")
|
||||
if logs.count("db_credentials_rotated") >= 2:
|
||||
break
|
||||
time.sleep(3)
|
||||
check(logs.count("db_credentials_rotated") >= 2, "both workers must switch to the new secret version")
|
||||
log("both workers loaded the new KV version and switched the pool (%.0f s after rotation)" % (time.time() - t0))
|
||||
|
||||
sql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = 'app_worker'")
|
||||
log("terminated all existing app_worker sessions: the pools must reconnect with the new password")
|
||||
atts = [upload(c, alice, chat, filename="rotation-%d.png" % i) for i in range(3)]
|
||||
for att in atts:
|
||||
wait_status(c, alice, att["id"], ("ready",), 90)
|
||||
after = int(sql("SELECT count(*) FROM pg_stat_activity WHERE usename = 'app_worker'")[0][0])
|
||||
log("3 uploads after the forced reconnect are ready; %d app_worker connections open again" % after)
|
||||
check(after > 0, "workers must reconnect")
|
||||
old_result, new_result = probe(old), probe(new)
|
||||
log("probe: old password -> %s | new password -> %s" % (old_result, new_result))
|
||||
check(old_result.startswith("rejected") and new_result == "accepted", "old refused, new accepted")
|
||||
failed = sql("SELECT count(*) FROM attachment_jobs WHERE state = 'failed' AND updated_at > to_timestamp(%d)" % t0)[0][0]
|
||||
stop.set()
|
||||
thread.join(60)
|
||||
log("traffic: %s requests, unexpected errors %s, uploads %s; failed jobs since rotation: %s" % (
|
||||
summary.get("requests"), summary.get("server_errors_unexpected"), summary["by_kind"]["upload"]["n"], failed))
|
||||
check(summary.get("server_errors_unexpected") == 0 and failed == "0", "no errors and no failed jobs")
|
||||
print("PASS: app_worker password rotated via OpenBao without rebuild/restart; old password revoked")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 3 demo: worker stopped -> upload 202 -> message with attachment -> restart API + broker (volumes kept)
|
||||
-> worker started -> ready + thumbnail. Then an explicit duplicate delivery of the finished job is a no-op.
|
||||
|
||||
python3 student-tests/test_worker_down.py (stack from REPORT.md must be running)
|
||||
"""
|
||||
import hashlib
|
||||
import time
|
||||
|
||||
from stand import (Client, check, compose, started_at, get, log, objects_of, wait_queue, run, sql, upload, wait_http_ready,
|
||||
wait_status, unique_name, SAMPLE)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
log("stop all workers")
|
||||
compose("stop", "-t", "20", "worker")
|
||||
try:
|
||||
att = upload(c, alice, chat, filename=unique_name())
|
||||
check(att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None, "upload must be 202 queued")
|
||||
log("upload 202 queued id=%s" % att["id"])
|
||||
msg = c.message(alice, chat, "", attachments=[att["id"]])["json"]
|
||||
check(msg["attachment_ids"] == [att["id"]], "message must reference the queued attachment")
|
||||
log("message %s created with queued attachment" % msg["id"])
|
||||
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
|
||||
c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], 409, actor=bob)
|
||||
c.message(bob, chat, "другие сообщения работают")
|
||||
depth = wait_queue()
|
||||
log("broker queue while worker is down:", depth)
|
||||
check(depth and depth["ready"] >= 1, "job must be waiting in the broker")
|
||||
unpublished = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
|
||||
" WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0]
|
||||
check(unpublished == "0", "outbox row must be published with confirm")
|
||||
|
||||
log("restart api-1 api-2 rabbitmq (volumes kept)")
|
||||
before = started_at("api-1", "api-2", "rabbitmq")
|
||||
compose("restart", "-t", "10", "rabbitmq", "api-1", "api-2")
|
||||
wait_http_ready(c)
|
||||
after = started_at("api-1", "api-2", "rabbitmq")
|
||||
log("started before:", before)
|
||||
log("started after: ", after)
|
||||
check(before != after, "containers must really restart")
|
||||
check(get(c, bob, att["id"])["status"] == "queued", "still queued after restart, nothing lost")
|
||||
depth = wait_queue()
|
||||
log("broker queue after broker restart:", depth)
|
||||
check(depth and depth["ready"] >= 1, "durable message must survive broker restart")
|
||||
finally:
|
||||
log("start workers")
|
||||
compose("start", "worker")
|
||||
ready, seen = wait_status(c, bob, att["id"], ("ready", "failed"), 90)
|
||||
check(ready["status"] == "ready", "expected ready, got %s" % ready["status"])
|
||||
log("status sequence observed:", " -> ".join(seen))
|
||||
names = sorted(v["name"] for v in ready["variants"])
|
||||
check(names == ["crop", "optimized", "thumbnail"], "expected thumbnail+crop+optimized, got %s" % names)
|
||||
thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"][0]
|
||||
check((thumb["width"], thumb["height"]) == (256, 160), "thumbnail 256x160")
|
||||
body = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"]
|
||||
check(hashlib.sha256(body).hexdigest() == thumb["sha256"], "thumbnail checksum")
|
||||
orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
|
||||
check(orig == SAMPLE, "original unchanged byte for byte")
|
||||
keys = objects_of(att["id"])
|
||||
log("objects:", keys)
|
||||
check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys), "original + 3 variants, staging removed")
|
||||
|
||||
log("redelivery: republish the finished job through the outbox (duplicate message)")
|
||||
sql("INSERT INTO outbox (job_id, payload, available_at, created_at) SELECT o.job_id, o.payload, now(), now()"
|
||||
" FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='%s' ORDER BY o.id LIMIT 1"
|
||||
% att["id"])
|
||||
time.sleep(5)
|
||||
again = get(c, bob, att["id"])
|
||||
check(again["status"] == "ready" and again["variants"] == ready["variants"], "duplicate must not change the result")
|
||||
rows = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att["id"])[0][0]
|
||||
succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att["id"])[0][0]
|
||||
check(rows == "3" and succeeded == "1", "one set of variants and one success (rows=%s succeeded=%s)" % (rows, succeeded))
|
||||
check(len(objects_of(att["id"])) == 4, "no new objects after duplicate")
|
||||
noop = compose("logs", "--since", "30s", "worker")
|
||||
check("decision=done" in noop, "worker must log the duplicate as no-op")
|
||||
log("duplicate acked as no-op: variants=%s successes=%s" % (rows, succeeded))
|
||||
print("PASS: worker down / API+broker restart / redelivery no-op")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""MessengerWorkerSaturated: capacity is lowered (2 workers x 1 slot, 0.25 CPU each), uploads exceed it for longer than
|
||||
`for: 5m`; the alert must fire, and resolve after the normal configuration is restored and the backlog drains.
|
||||
|
||||
python3 student-tests/test_worker_saturation.py (stack running; ~10 min). Restores WORKER_* defaults at the end.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import check, log, run
|
||||
from test_incidents import wait_alert
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ALERT = "MessengerWorkerSaturated"
|
||||
|
||||
|
||||
def worker(env):
|
||||
done = subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--wait", "--no-deps", "--force-recreate",
|
||||
"worker"], cwd=ROOT, env={**os.environ, **env}, capture_output=True, text=True, timeout=240)
|
||||
check(done.returncode == 0, "worker recreate failed: %s" % done.stderr[-300:])
|
||||
|
||||
|
||||
def main():
|
||||
result = {}
|
||||
log("lower capacity: WORKER_CONCURRENCY=1 WORKER_PREFETCH=1 WORKER_CPUS=0.25, 2 replicas")
|
||||
worker({"WORKER_CONCURRENCY": "1", "WORKER_PREFETCH": "1", "WORKER_CPUS": "0.25"})
|
||||
load = Load("https://localhost:8443", users=2, threads=32)
|
||||
stop = threading.Event()
|
||||
summary = {}
|
||||
thread = threading.Thread(target=lambda: summary.update(load.run(0, 900, upload_rate=4, stop_event=stop)), daemon=True)
|
||||
t0 = time.time()
|
||||
thread.start()
|
||||
log("uploads: 4/s open-loop (sample.png)")
|
||||
try:
|
||||
time.sleep(60)
|
||||
capacity = obs.prom_scalar("sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 30))")
|
||||
log("fresh capacity=%.0f slots (stale series of recreated containers are excluded)" % capacity)
|
||||
check(capacity == 2, "expected 2 slots, got %s" % capacity)
|
||||
firing, pending = wait_alert(ALERT, "firing", 480, t0)
|
||||
ratio = obs.prom_scalar("messenger:worker_saturation:ratio")
|
||||
depth = obs.prom_scalar('max(messenger_queue_depth{queue="attachments.process",state="queued"})')
|
||||
age = obs.prom_scalar('max(messenger_queue_oldest_age_seconds{queue="attachments.process"})')
|
||||
rate = obs.prom_scalar('sum(rate(messenger_jobs_processed_total{outcome="succeeded"}[2m]))')
|
||||
p95 = obs.prom_scalar('histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome="succeeded"}[5m])))')
|
||||
others = obs.alerts()
|
||||
log("at firing: saturation=%.2f, queued=%.0f, oldest age=%.0f s, succeeded=%.2f jobs/s, job p95=%.2f s, alerts=%s"
|
||||
% (ratio, depth, age, rate, p95, others))
|
||||
check(ratio > 0.9, "saturation must be above the threshold")
|
||||
finally:
|
||||
stop.set()
|
||||
thread.join(60)
|
||||
log("restore default worker configuration")
|
||||
t1 = time.time()
|
||||
worker({})
|
||||
resolved, _ = wait_alert(ALERT, "resolved", 240, t1)
|
||||
drained = obs.wait_for(lambda: obs.prom_scalar('max(messenger_queue_depth{queue="attachments.process",state="queued"})',
|
||||
default=-1) == 0, 240, 5)
|
||||
log("backlog drained: %s (+%.0f s after restore)" % (bool(drained), time.time() - t1))
|
||||
check(drained, "backlog must drain")
|
||||
result.update({"alert_pending_s": pending, "alert_firing_s": round(firing), "saturation_at_firing": round(ratio, 3),
|
||||
"queued_at_firing": depth, "oldest_age_s": round(age), "jobs_per_s": round(rate, 2),
|
||||
"job_p95_s": round(p95, 2), "alerts_at_firing": others, "resolved_after_restore_s": round(resolved),
|
||||
"drained_after_restore_s": round(time.time() - t1), "uploads": summary.get("status_counts")})
|
||||
(ROOT / "evidence/worker_saturation.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
print("PASS: MessengerWorkerSaturated fired under saturation and resolved after recovery")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,461 @@
|
||||
#!/usr/bin/env python3
|
||||
"""TLS / mTLS / authorization audit of the whole trust matrix (contracts/trust-matrix.md), from INSIDE the network.
|
||||
|
||||
Run (stand up, OpenBao unsealed for section H):
|
||||
docker compose run --rm --no-deps -v ./secrets/pki:/pki:ro -v ./secrets/bootstrap:/bootstrap:ro \
|
||||
-v ./student-tests:/audit:ro --entrypoint python worker /audit/tls_audit.py [--only A,B,...]
|
||||
For every link: no client certificate / certificate of a FOREIGN CA (claims the right name) / certificate of the
|
||||
SAME CA with a wrong identity / the right identity. Stores additionally get allow/deny checks of the scoped rights.
|
||||
Credentials from /bootstrap are used only for positive probes and are never printed. Exit 1 on any mismatch.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
PKI = "/pki"
|
||||
CA = PKI + "/ca.crt"
|
||||
FOREIGN_CA = PKI + "/foreign.crt"
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def cert(name):
|
||||
return (PKI + "/%s.crt" % name, PKI + "/%s.key" % name) if name else None
|
||||
|
||||
|
||||
def secret(name):
|
||||
with open("/bootstrap/" + name, encoding="utf-8") as handle:
|
||||
return handle.read().strip()
|
||||
|
||||
|
||||
def record(section, link, case, expect, observed, ok):
|
||||
RESULTS.append({"section": section, "link": link, "case": case, "expect": expect, "observed": observed[:160],
|
||||
"pass": bool(ok)})
|
||||
print("%s %-2s %-26s %-44s expect=%-8s %s" % ("PASS" if ok else "FAIL", section, link, case, expect, observed[:110]),
|
||||
flush=True)
|
||||
|
||||
|
||||
def ctx_for(client=None, cafile=CA, alpn=None):
|
||||
ctx = ssl.create_default_context(cafile=cafile)
|
||||
if client:
|
||||
ctx.load_cert_chain(*cert(client))
|
||||
if alpn:
|
||||
ctx.set_alpn_protocols(alpn)
|
||||
return ctx
|
||||
|
||||
|
||||
def tls_exchange(host, port, client=None, cafile=CA, server_hostname=None, payload=b"", timeout=3.0, alpn=None):
|
||||
"""TLS connect + optional payload + read. Returns ('accepted', first bytes) or ('rejected', reason).
|
||||
With TLS 1.3 a missing/untrusted client certificate is reported by the server AFTER the client's handshake,
|
||||
so the verdict needs a read; a closed connection without data counts as rejected."""
|
||||
raw = socket.create_connection((host, port), timeout=timeout)
|
||||
try:
|
||||
s = ctx_for(client, cafile, alpn).wrap_socket(raw, server_hostname=server_hostname or host)
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
raw.close()
|
||||
return "rejected", "server cert verify failed: " + exc.verify_message
|
||||
except (ssl.SSLError, OSError) as exc:
|
||||
raw.close()
|
||||
return "rejected", "handshake: " + (getattr(exc, "reason", None) or type(exc).__name__)
|
||||
try:
|
||||
if payload:
|
||||
s.sendall(payload)
|
||||
data = s.recv(64)
|
||||
return ("accepted", data.decode("latin-1", "replace")) if data else ("rejected", "closed without response")
|
||||
except socket.timeout:
|
||||
return "accepted", "(open, no data within %.1fs)" % timeout
|
||||
except (ssl.SSLError, OSError) as exc:
|
||||
return "rejected", "after handshake: " + (getattr(exc, "reason", None) or type(exc).__name__)
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def http_get(host, port, path, client=None, hostname=None):
|
||||
payload = ("GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % (path, hostname or host)).encode()
|
||||
verdict, detail = tls_exchange(host, port, client, server_hostname=hostname, payload=payload)
|
||||
if verdict == "accepted" and detail.startswith("HTTP/"):
|
||||
return "accepted", detail.split("\r\n")[0]
|
||||
return verdict, detail
|
||||
|
||||
|
||||
def expect_tls(section, link, host, port, client, case, accept, path=None, payload=b"", hostname=None, alpn=None):
|
||||
if path:
|
||||
verdict, detail = http_get(host, port, path, client, hostname)
|
||||
else:
|
||||
verdict, detail = tls_exchange(host, port, client, payload=payload, server_hostname=hostname, alpn=alpn)
|
||||
record(section, link, case, "accept" if accept else "reject", "%s: %s" % (verdict, detail),
|
||||
(verdict == "accepted") == accept)
|
||||
|
||||
|
||||
def plaintext_refused(section, link, host, port, probe=b"GET / HTTP/1.0\r\n\r\n"):
|
||||
try:
|
||||
s = socket.create_connection((host, port), timeout=3)
|
||||
s.sendall(probe)
|
||||
data = s.recv(64)
|
||||
s.close()
|
||||
ok = not data.startswith((b"HTTP/1.1 200", b"AMQP", b"+PONG", b"-NOAUTH"))
|
||||
record(section, link, "plaintext client", "reject", "server answered %r" % data[:24], ok)
|
||||
except OSError as exc:
|
||||
record(section, link, "plaintext client", "reject", "connection failed: %s" % type(exc).__name__, True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- sections
|
||||
def a_lb_api():
|
||||
for api in ("api-1", "api-2"):
|
||||
link = "LB -> %s:8080" % api
|
||||
expect_tls("A", link, api, 8080, None, "no client cert", False, "/health/ready")
|
||||
expect_tls("A", link, api, 8080, "foreign-client", "foreign CA (claims lb identity)", False, "/health/ready")
|
||||
expect_tls("A", link, api, 8080, "intruder", "same CA, identity intruder", False, "/health/ready")
|
||||
expect_tls("A", link, api, 8080, "worker", "same CA, identity worker", False, "/health/ready")
|
||||
expect_tls("A", link, api, 8080, "api", "same CA, identity api", False, "/health/ready")
|
||||
expect_tls("A", link, api, 8080, "lb-client", "lb.client.messenger", True, "/health/ready")
|
||||
plaintext_refused("A", link, api, 8080)
|
||||
|
||||
|
||||
def i_ingress():
|
||||
link = "client -> nginx:8443"
|
||||
expect_tls("I", link, "nginx", 8443, None, "trusted CA, hostname nginx", True, "/health/live")
|
||||
verdict, detail = tls_exchange("nginx", 8443, cafile=FOREIGN_CA)
|
||||
record("I", link, "untrusted CA in client trust store", "reject", "%s: %s" % (verdict, detail),
|
||||
verdict == "rejected" and "verify failed" in detail)
|
||||
verdict, detail = tls_exchange("nginx", 8443, server_hostname="evil.example")
|
||||
record("I", link, "wrong hostname (evil.example)", "reject", "%s: %s" % (verdict, detail),
|
||||
verdict == "rejected" and "verify failed" in detail)
|
||||
plaintext_refused("I", link, "nginx", 8443)
|
||||
|
||||
|
||||
def b_postgres():
|
||||
import psycopg
|
||||
|
||||
link = "svc -> postgres:5432"
|
||||
url = lambda role, pw: "postgresql://%s:%s@postgres:5432/messenger" % (role, pw) # noqa: E731
|
||||
api_pw, worker_pw = secret("db_api_password"), secret("db_worker_password")
|
||||
|
||||
def connect(role, pw, **kw):
|
||||
return psycopg.connect(url(role, pw), connect_timeout=5, autocommit=True, **kw)
|
||||
|
||||
def attempt(case, accept, **kw):
|
||||
try:
|
||||
connect("app_api", api_pw, **kw).close()
|
||||
record("B", link, case, "accept" if accept else "reject", "connected", accept)
|
||||
except psycopg.Error as exc:
|
||||
record("B", link, case, "accept" if accept else "reject", type(exc).__name__ + ": " + str(exc).splitlines()[0],
|
||||
not accept)
|
||||
|
||||
attempt("plaintext (sslmode=disable)", False, sslmode="disable")
|
||||
attempt("foreign CA as root (verify-full)", False, sslmode="verify-full", sslrootcert=FOREIGN_CA)
|
||||
ip = socket.gethostbyname("postgres")
|
||||
try:
|
||||
psycopg.connect("postgresql://app_api:%s@%s:5432/messenger" % (api_pw, ip), sslmode="verify-full",
|
||||
sslrootcert=CA, connect_timeout=5).close()
|
||||
record("B", link, "hostname mismatch (IP, verify-full)", "reject", "connected", False)
|
||||
except psycopg.Error as exc:
|
||||
record("B", link, "hostname mismatch (IP, verify-full)", "reject", str(exc).splitlines()[0], True)
|
||||
attempt("TLS verify-full + app_api password", True, sslmode="verify-full", sslrootcert=CA)
|
||||
try:
|
||||
connect("app_api", "wrong-password", sslmode="verify-full", sslrootcert=CA).close()
|
||||
record("B", link, "wrong password", "reject", "connected", False)
|
||||
except psycopg.Error as exc:
|
||||
record("B", link, "wrong password", "reject", str(exc).splitlines()[0], True)
|
||||
|
||||
checks = [
|
||||
("app_worker", worker_pw, "SELECT count(*) FROM users", False),
|
||||
("app_worker", worker_pw, "SELECT count(*) FROM messages", False),
|
||||
("app_worker", worker_pw, "SELECT count(*) FROM sessions", False),
|
||||
("app_worker", worker_pw, "DELETE FROM attachments WHERE false", False),
|
||||
("app_worker", worker_pw, "SELECT count(*) FROM attachment_jobs", True),
|
||||
("app_api", api_pw, "SELECT count(*) FROM users", True),
|
||||
("app_api", api_pw, "CREATE TABLE audit_probe (x int)", False),
|
||||
("app_api", api_pw, "ALTER ROLE app_worker PASSWORD 'x'", False),
|
||||
("app_api", api_pw, "SELECT count(*) FROM schema_migrations", False),
|
||||
]
|
||||
for role, pw, query, accept in checks:
|
||||
try:
|
||||
with connect(role, pw, sslmode="verify-full", sslrootcert=CA) as conn:
|
||||
conn.execute(query)
|
||||
record("B", "%s privileges" % role, query[:44], "allow" if accept else "deny", "executed", accept)
|
||||
except psycopg.Error as exc:
|
||||
record("B", "%s privileges" % role, query[:44], "allow" if accept else "deny",
|
||||
type(exc).__name__, not accept)
|
||||
|
||||
|
||||
def c_s3():
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError, SSLError, EndpointConnectionError
|
||||
|
||||
bucket = "messenger-attachments"
|
||||
|
||||
def client(role, verify=CA, endpoint="https://minio:9000"):
|
||||
return boto3.client("s3", endpoint_url=endpoint, region_name="us-east-1", verify=verify,
|
||||
aws_access_key_id=secret("s3_%s_access_key" % role),
|
||||
aws_secret_access_key=secret("s3_%s_secret_key" % role),
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"},
|
||||
retries={"max_attempts": 0}, connect_timeout=3, read_timeout=5))
|
||||
|
||||
def op(role, case, accept, fn):
|
||||
try:
|
||||
fn(client(role))
|
||||
record("C", "%s S3 rights" % role, case, "allow" if accept else "deny", "ok", accept)
|
||||
except ClientError as exc:
|
||||
record("C", "%s S3 rights" % role, case, "allow" if accept else "deny", exc.response["Error"]["Code"],
|
||||
not accept)
|
||||
|
||||
tag = "audit-%d" % int(time.time())
|
||||
try:
|
||||
client("api", verify=FOREIGN_CA).list_objects_v2(Bucket=bucket, MaxKeys=1)
|
||||
record("C", "svc -> minio:9000", "foreign CA as trust anchor", "reject", "connected", False)
|
||||
except (SSLError, EndpointConnectionError, Exception) as exc: # noqa: B014
|
||||
record("C", "svc -> minio:9000", "foreign CA as trust anchor", "reject", type(exc).__name__, True)
|
||||
try:
|
||||
client("api", endpoint="http://minio:9000").list_objects_v2(Bucket=bucket, MaxKeys=1)
|
||||
record("C", "svc -> minio:9000", "plaintext http://", "reject", "answered", False)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
record("C", "svc -> minio:9000", "plaintext http://", "reject", type(exc).__name__, True)
|
||||
op("worker", "PUT attachments/*", True, lambda c: c.put_object(Bucket=bucket, Key="attachments/%s/x" % tag, Body=b"x"))
|
||||
op("worker", "GET attachments/*", False, lambda c: c.get_object(Bucket=bucket, Key="attachments/%s/x" % tag))
|
||||
op("worker", "DELETE attachments/*", False, lambda c: c.delete_object(Bucket=bucket, Key="attachments/%s/x" % tag))
|
||||
op("worker", "PUT staging/*", False, lambda c: c.put_object(Bucket=bucket, Key="staging/%s" % tag, Body=b"x"))
|
||||
op("worker", "LIST bucket", False, lambda c: c.list_objects_v2(Bucket=bucket, MaxKeys=1))
|
||||
op("worker", "PUT outside prefixes", False, lambda c: c.put_object(Bucket=bucket, Key="other/%s" % tag, Body=b"x"))
|
||||
op("api", "PUT staging/*", True, lambda c: c.put_object(Bucket=bucket, Key="staging/%s" % tag, Body=b"x"))
|
||||
op("api", "PUT attachments/* (only worker publishes)", False,
|
||||
lambda c: c.put_object(Bucket=bucket, Key="attachments/%s/y" % tag, Body=b"x"))
|
||||
op("api", "GET attachments/*", True, lambda c: c.get_object(Bucket=bucket, Key="attachments/%s/x" % tag))
|
||||
op("api", "LIST bucket (reconciler)", True, lambda c: c.list_objects_v2(Bucket=bucket, MaxKeys=1))
|
||||
op("api", "create bucket", False, lambda c: c.create_bucket(Bucket="audit-%s" % tag))
|
||||
op("api", "cleanup audit objects", True, lambda c: (c.delete_object(Bucket=bucket, Key="staging/%s" % tag),
|
||||
c.delete_object(Bucket=bucket, Key="attachments/%s/x" % tag)))
|
||||
|
||||
|
||||
def d_broker():
|
||||
import aio_pika
|
||||
from aiormq.exceptions import AMQPError
|
||||
|
||||
link = "svc -> rabbitmq:5671"
|
||||
url = "amqps://rabbitmq:5671/messenger?auth=external"
|
||||
plaintext_refused("D", "svc -> rabbitmq:5672", "rabbitmq", 5672, b"AMQP\x00\x00\x09\x01")
|
||||
|
||||
async def connect(client):
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
if client:
|
||||
ctx.load_cert_chain(*cert(client))
|
||||
return await aio_pika.connect(url, ssl_context=ctx, timeout=5)
|
||||
|
||||
async def run():
|
||||
for client, case in ((None, "no client cert"), ("foreign-client", "foreign CA (claims worker name)"),
|
||||
("intruder", "same CA, unknown identity intruder"), ("lb-client", "same CA, identity lb")):
|
||||
try:
|
||||
conn = await connect(client)
|
||||
await conn.close()
|
||||
record("D", link, case, "reject", "connected", False)
|
||||
except (AMQPError, ConnectionError, OSError, ssl.SSLError, asyncio.TimeoutError) as exc:
|
||||
record("D", link, case, "reject", type(exc).__name__ + " " + str(exc)[:60], True)
|
||||
|
||||
async def action(client, case, accept, fn):
|
||||
conn = None
|
||||
try:
|
||||
conn = await connect(client)
|
||||
channel = await conn.channel(publisher_confirms=True)
|
||||
await asyncio.wait_for(fn(channel), 5)
|
||||
record("D", "%s AMQP rights" % client, case, "allow" if accept else "deny", "ok", accept)
|
||||
except (AMQPError, asyncio.TimeoutError, aio_pika.exceptions.ChannelClosed) as exc:
|
||||
record("D", "%s AMQP rights" % client, case, "allow" if accept else "deny",
|
||||
type(exc).__name__ + " " + str(exc)[:70], not accept)
|
||||
finally:
|
||||
if conn is not None:
|
||||
await conn.close()
|
||||
|
||||
async def publish_unroutable(channel):
|
||||
ex = await channel.get_exchange("attachments", ensure=True)
|
||||
await ex.publish(aio_pika.Message(b"audit"), routing_key="audit.unroutable")
|
||||
|
||||
async def consume_and_cancel(channel):
|
||||
q = await channel.get_queue("attachments.process", ensure=True)
|
||||
await channel.set_qos(prefetch_count=1)
|
||||
tag = await q.consume(lambda m: m.nack(requeue=True))
|
||||
await q.cancel(tag)
|
||||
|
||||
async def declare_queue(channel):
|
||||
await channel.declare_queue("audit-probe", auto_delete=True)
|
||||
|
||||
async def publish_default(channel):
|
||||
await channel.default_exchange.publish(aio_pika.Message(b"audit"), routing_key="attachments.process")
|
||||
|
||||
await action("api", "publish to exchange attachments", True, publish_unroutable)
|
||||
await action("api", "consume attachments.process", False, consume_and_cancel)
|
||||
await action("api", "declare a queue (configure)", False, declare_queue)
|
||||
await action("api", "publish via default exchange", False, publish_default)
|
||||
await action("worker", "consume attachments.process", True, consume_and_cancel)
|
||||
await action("worker", "publish to exchange attachments", False, publish_unroutable)
|
||||
await action("worker", "declare a queue (configure)", False, declare_queue)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def e_collector():
|
||||
link = "svc -> otel-collector:4318"
|
||||
body = b"POST /v1/metrics HTTP/1.1\r\nHost: otel-collector\r\nContent-Type: application/x-protobuf\r\n" \
|
||||
b"Content-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
for client, case, accept in ((None, "no client cert", False), ("foreign-client", "foreign CA", False),
|
||||
("lb-client", "root CA identity lb (not ingest CA)", False),
|
||||
("api", "root CA identity api (not ingest CA)", False),
|
||||
("grafana-out", "telemetry CA (not ingest CA)", False),
|
||||
("api-otel", "ingest CA api.otel", True), ("worker-otel", "ingest CA worker.otel", True)):
|
||||
verdict, detail = tls_exchange("otel-collector", 4318, client, payload=body)
|
||||
ok = (verdict == "accepted" and detail.startswith("HTTP/1.1 2")) if accept else verdict == "rejected"
|
||||
record("E", link, case, "accept" if accept else "reject", "%s: %s" % (verdict, detail.split("\r\n")[0]), ok)
|
||||
|
||||
|
||||
def f_backends():
|
||||
for host, port, path in (("prometheus", 9090, "/-/ready"), ("loki", 3100, "/ready"), ("tempo", 3200, "/ready")):
|
||||
link = "-> %s:%d" % (host, port)
|
||||
for client, case, accept in ((None, "no client cert", False), ("foreign-client", "foreign CA", False),
|
||||
("api", "root CA identity api", False),
|
||||
("api-otel", "ingest CA (apps cannot bypass collector)", False),
|
||||
("collector-out", "telemetry CA collector.out", True),
|
||||
("grafana-out", "telemetry CA grafana.out", True),
|
||||
("operator", "telemetry CA operator", True)):
|
||||
expect_tls("F", link, host, port, client, case, accept, path)
|
||||
link = "collector -> tempo:4317 (gRPC)"
|
||||
preface = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
|
||||
for client, case, accept in ((None, "no client cert", False), ("api-otel", "ingest CA", False),
|
||||
("collector-out", "telemetry CA collector.out", True)):
|
||||
expect_tls("F", link, "tempo", 4317, client, case, accept, payload=preface, alpn=["h2"])
|
||||
|
||||
|
||||
def g_valkey():
|
||||
import valkey
|
||||
|
||||
link = "api -> valkey:6379"
|
||||
plaintext_refused("G", link, "valkey", 6379, b"PING\r\n")
|
||||
|
||||
def conn(user=None, password=None, cafile=CA):
|
||||
return valkey.Valkey(host="valkey", port=6379, ssl=True, ssl_ca_certs=cafile, ssl_check_hostname=True,
|
||||
username=user, password=password, socket_timeout=3, decode_responses=True)
|
||||
|
||||
def attempt(case, accept, fn):
|
||||
try:
|
||||
fn()
|
||||
record("G", link, case, "allow" if accept else "deny", "ok", accept)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
record("G", link, case, "allow" if accept else "deny", type(exc).__name__ + " " + str(exc)[:60], not accept)
|
||||
|
||||
attempt("foreign CA as trust anchor", False, lambda: conn("api", secret("valkey_api_password"), FOREIGN_CA).ping())
|
||||
attempt("no authentication (default user off)", False, lambda: conn().get("session:x"))
|
||||
attempt("user api, wrong password", False, lambda: conn("api", "wrong").ping())
|
||||
api = lambda: conn("api", secret("valkey_api_password")) # noqa: E731
|
||||
attempt("api: SET/GET session:*", True, lambda: (api().set("session:audit", "1", ex=5), api().get("session:audit")))
|
||||
attempt("api: INCR ratelimit:*", True, lambda: api().incr("ratelimit:audit"))
|
||||
attempt("api: GET outside allowed keys", False, lambda: api().get("other:audit"))
|
||||
attempt("api: FLUSHALL", False, lambda: api().flushall())
|
||||
attempt("api: CONFIG GET", False, lambda: api().config_get("*"))
|
||||
attempt("api: KEYS *", False, lambda: api().keys("*"))
|
||||
attempt("health: GET session:*", False, lambda: conn("health", "health").get("session:audit"))
|
||||
|
||||
|
||||
def h_openbao():
|
||||
base = "https://openbao:8200"
|
||||
|
||||
def call(path, client=None, token=None, body=None, method=None):
|
||||
req = urllib.request.Request(base + path, data=json.dumps(body).encode() if body is not None else None,
|
||||
method=method or ("POST" if body is not None else "GET"))
|
||||
if token:
|
||||
req.add_header("X-Vault-Token", token)
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=ctx_for(client), timeout=5) as response:
|
||||
return response.status, json.loads(response.read() or b"{}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, {}
|
||||
except (urllib.error.URLError, OSError) as exc:
|
||||
return 0, {"error": type(getattr(exc, "reason", exc)).__name__}
|
||||
|
||||
def login(client, role):
|
||||
status, body = call("/v1/auth/cert/login", client, body={"name": role})
|
||||
return status, (body.get("auth") or {}).get("client_token")
|
||||
|
||||
link = "svc -> openbao:8200"
|
||||
for client, role, case in ((None, "worker", "no client cert"), ("intruder", "worker", "same CA, identity intruder"),
|
||||
("worker", "api", "worker cert, role api"), ("api", "worker", "api cert, role worker"),
|
||||
("lb-client", "api", "lb cert, role api")):
|
||||
status, token = login(client, role)
|
||||
record("H", link, "cert login: " + case, "reject", "HTTP %s token=%s" % (status, bool(token)), not token)
|
||||
# /v1/sys/health is public by design; what matters is that a foreign certificate never becomes an identity.
|
||||
status, token = login("foreign-client", "worker")
|
||||
record("H", link, "cert login: foreign CA (claims worker name)", "reject", "HTTP %s token=%s" % (status, bool(token)),
|
||||
not token)
|
||||
for client, role, own, other in (("worker", "worker", "worker", "api"), ("api", "api", "api", "worker")):
|
||||
status, token = login(client, role)
|
||||
record("H", link, "cert login: %s cert, role %s" % (client, role), "accept", "HTTP %s token=%s" % (status, bool(token)),
|
||||
bool(token))
|
||||
if not token:
|
||||
continue
|
||||
lookup = call("/v1/auth/token/lookup-self", token=token)[1].get("data", {})
|
||||
record("H", "%s token" % role, "policies / ttl", "scoped", "policies=%s ttl=%ss" % (
|
||||
lookup.get("policies"), lookup.get("ttl")), lookup.get("policies") == ["default", "messenger-" + role]
|
||||
and 0 < lookup.get("ttl", 0) <= 900)
|
||||
status, _ = call("/v1/messenger/data/" + own, token=token)
|
||||
record("H", "%s token" % role, "read own messenger/%s" % own, "allow", "HTTP %s" % status, status == 200)
|
||||
status, _ = call("/v1/messenger/data/" + other, token=token)
|
||||
record("H", "%s token" % role, "read messenger/%s" % other, "deny", "HTTP %s" % status, status == 403)
|
||||
status, _ = call("/v1/messenger/data/" + own, token=token, body={"data": {"x": "y"}})
|
||||
record("H", "%s token" % role, "write own secret", "deny", "HTTP %s" % status, status == 403)
|
||||
status, _ = call("/v1/sys/policies/acl/messenger-" + role, token=token, body={"policy": 'path "*" {capabilities=["sudo"]}'},
|
||||
method="PUT")
|
||||
record("H", "%s token" % role, "write own policy", "deny", "HTTP %s" % status, status == 403)
|
||||
status, _ = call("/v1/sys/auth", token=token)
|
||||
record("H", "%s token" % role, "list auth methods (admin)", "deny", "HTTP %s" % status, status == 403)
|
||||
|
||||
|
||||
def j_operator():
|
||||
link = "operator -> grafana:3000"
|
||||
verdict, detail = http_get("grafana", 3000, "/api/datasources")
|
||||
record("J", link, "HTTPS without login", "reject", "%s: %s" % (verdict, detail), "401" in detail)
|
||||
plaintext_refused("J", link, "grafana", 3000)
|
||||
|
||||
|
||||
def k_bypass():
|
||||
"""Side channels must not be reachable from the network (loopback-only or not listening at all)."""
|
||||
closed = [("rabbitmq", 25672, "Erlang distribution"), ("rabbitmq", 4369, "epmd"), ("rabbitmq", 15672, "management UI"),
|
||||
("loki", 9096, "Loki internal gRPC"), ("tempo", 9095, "Tempo internal gRPC"),
|
||||
("otel-collector", 8888, "collector self-metrics"), ("otel-collector", 13133, "collector health"),
|
||||
("otel-collector", 4317, "collector OTLP/gRPC (disabled)"), ("api-1", 8081, "API loopback health"),
|
||||
("api-2", 8081, "API loopback health"), ("openbao", 8201, "OpenBao cluster port"),
|
||||
("minio", 9001, "MinIO console"), ("postgres", 5433, "no second PostgreSQL listener")]
|
||||
for host, port, what in closed:
|
||||
try:
|
||||
socket.create_connection((host, port), timeout=2).close()
|
||||
record("K", "%s:%d" % (host, port), what, "closed", "port OPEN from the network", False)
|
||||
except OSError as exc:
|
||||
record("K", "%s:%d" % (host, port), what, "closed", type(exc).__name__, True)
|
||||
|
||||
|
||||
SECTIONS = {"A": a_lb_api, "I": i_ingress, "B": b_postgres, "C": c_s3, "D": d_broker, "E": e_collector,
|
||||
"F": f_backends, "G": g_valkey, "H": h_openbao, "J": j_operator, "K": k_bypass}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--only", default=",".join(SECTIONS))
|
||||
p.add_argument("--output", default="")
|
||||
args = p.parse_args()
|
||||
for key in args.only.split(","):
|
||||
try:
|
||||
SECTIONS[key]()
|
||||
except Exception as exc: # noqa: BLE001 a section that cannot run is a failure, not a skip
|
||||
record(key, "section " + key, "runs", "run", "%s: %s" % (type(exc).__name__, str(exc)[:120]), False)
|
||||
failed = [r for r in RESULTS if not r["pass"]]
|
||||
print("\n%d checks, %d failed" % (len(RESULTS), len(failed)))
|
||||
if args.output:
|
||||
with open(args.output, "w", encoding="utf-8") as handle:
|
||||
json.dump(RESULTS, handle, ensure_ascii=False, indent=1)
|
||||
sys.exit(1 if failed else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,343 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 5.1 "Цена наблюдаемости": the same open-loop load against several telemetry configurations.
|
||||
|
||||
Configurations (applied by recreating api-1, api-2, worker and otel-collector with shell env overrides):
|
||||
off OTEL_SDK_DISABLED=true no SDK, no instrumentation (baseline)
|
||||
on100 sampler ratio 1.0, collector profile default every span exported
|
||||
head10 sampler ratio 0.1, collector profile default head sampling of root spans (children follow)
|
||||
tail sampler ratio 1.0, collector profile tail balanced: errors + >500 ms + async pipeline + 10% rest
|
||||
|
||||
Per run: recreate -> ready -> warm-up 20 s -> idle 20 s -> counters A -> load (rate, duration) -> idle 30 s ->
|
||||
counters B. Delta(B-A) = telemetry produced by the measured load. CPU is the exact cgroup delta over the load window
|
||||
(Docker API); RSS is the maximum of `docker stats` samples taken every 5 s. Afterwards Tempo is searched in the load window for traces of injected slow/error requests and
|
||||
upload pipelines, to count what survives sampling.
|
||||
|
||||
python3 student-tests/track1.py run [--configs off,on100,head10,tail] [--repeats 2] [--rate 60] [--duration 90]
|
||||
python3 student-tests/track1.py summary # evidence/track1/results.jsonl -> evidence/track1/summary.md
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import Client, log
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence/track1"
|
||||
CONFIGS = {
|
||||
"off": {"OTEL_SDK_DISABLED": "true", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "default"},
|
||||
"on100": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "default"},
|
||||
"head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "0.1", "COLLECTOR_PROFILE": "default"},
|
||||
"tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "tail"},
|
||||
}
|
||||
SERVICES = ("api-1", "api-2", "worker", "otel-collector", "tempo", "loki", "prometheus", "postgres", "nginx")
|
||||
COUNTERS = {
|
||||
# SDK side (sum over all instances; absent when the SDK is off)
|
||||
"sdk_span_decisions_sample": 'sum(messenger_telemetry_sampler_decisions_total{decision="sample"})',
|
||||
"sdk_span_decisions_drop_ratio": 'sum(messenger_telemetry_sampler_decisions_total{decision="drop",rule=~"ratio|parent"})',
|
||||
"sdk_spans_exported_ok": 'sum(messenger_telemetry_spans_exported_total{outcome="success"})',
|
||||
"sdk_spans_exported_failed": 'sum(messenger_telemetry_spans_exported_total{outcome="failure"})',
|
||||
# Collector
|
||||
"col_spans_in": "sum(otelcol_receiver_accepted_spans_total)",
|
||||
"col_logs_in": "sum(otelcol_receiver_accepted_log_records_total)",
|
||||
"col_points_in": "sum(otelcol_receiver_accepted_metric_points_total)",
|
||||
"col_spans_out": 'sum(otelcol_exporter_sent_spans_total{exporter="otlp/tempo"})',
|
||||
"col_spans_refused": "sum(otelcol_receiver_refused_spans_total)",
|
||||
"col_spans_dropped": 'sum(otelcol_exporter_enqueue_failed_spans_total) or vector(0)',
|
||||
"col_otlp_bytes_in": 'sum({__name__="http.server.request.size_bytes_total"})',
|
||||
# Backends
|
||||
"tempo_spans_in": "sum(tempo_distributor_spans_received_total)",
|
||||
"tempo_bytes_in": "sum(tempo_distributor_bytes_received_total)",
|
||||
"loki_bytes_in": "sum(loki_distributor_bytes_received_total)",
|
||||
"loki_lines_in": "sum(loki_distributor_lines_received_total)",
|
||||
"prom_samples_in": "sum(prometheus_tsdb_head_samples_appended_total)",
|
||||
}
|
||||
|
||||
|
||||
def compose(*args, env=None, timeout=300):
|
||||
done = subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, capture_output=True,
|
||||
text=True, timeout=timeout, env={**os.environ, **(env or {})})
|
||||
if done.returncode != 0:
|
||||
raise RuntimeError("compose %s: %s" % (args[:2], done.stderr[-400:]))
|
||||
return done.stdout
|
||||
|
||||
|
||||
def apply(name):
|
||||
env = CONFIGS[name]
|
||||
compose("up", "-d", "--wait", "--force-recreate", "--no-deps", "otel-collector", "api-1", "api-2", "worker",
|
||||
env=env)
|
||||
compose("restart", "nginx") # re-resolve recreated replicas
|
||||
c = Client()
|
||||
deadline = time.monotonic() + 120
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/health/ready", 200)
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
out = compose("exec", "-T", "api-1", "printenv", "OTEL_SDK_DISABLED", "OTEL_TRACES_SAMPLER_ARG")
|
||||
log("config %s applied: api-1 env %s" % (name, out.split()))
|
||||
|
||||
|
||||
def counters():
|
||||
values = {}
|
||||
for key, expr in COUNTERS.items():
|
||||
try:
|
||||
rows = obs.prom(expr)
|
||||
values[key] = rows[0][1] if rows else None
|
||||
except Exception:
|
||||
values[key] = None
|
||||
tail = {}
|
||||
for metric, value in obs.prom('{__name__=~"otelcol_processor_tail_sampling_count_traces_sampled.*"}'):
|
||||
tail["%s/%s" % (metric.get("policy"), metric.get("sampled"))] = value
|
||||
values["tail_policies"] = tail
|
||||
return values
|
||||
|
||||
|
||||
def delta(a, b):
|
||||
out = {}
|
||||
for key in COUNTERS:
|
||||
if a.get(key) is not None and b.get(key) is not None:
|
||||
out[key] = b[key] - a[key]
|
||||
elif b.get(key) is not None:
|
||||
out[key] = b[key] # series appeared during the window (counter started at 0)
|
||||
else:
|
||||
out[key] = None
|
||||
out["tail_policies"] = {k: v - a["tail_policies"].get(k, 0) for k, v in b["tail_policies"].items()}
|
||||
return out
|
||||
|
||||
|
||||
def parse_mem(text):
|
||||
"""'123.4MiB' -> 123.4 (MiB)."""
|
||||
match = re.match(r"\s*([\d.]+)\s*([A-Za-z]*)", text)
|
||||
if not match:
|
||||
return 0.0
|
||||
scale = {"B": 1 / 1048576, "kB": 1 / 1024, "KiB": 1 / 1024, "MiB": 1, "MB": 1, "GiB": 1024, "GB": 1024}
|
||||
return float(match.group(1)) * scale.get(match.group(2), 1)
|
||||
|
||||
|
||||
def sample_stats(stop, samples):
|
||||
while not stop.is_set():
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"],
|
||||
capture_output=True, text=True).stdout
|
||||
row = {}
|
||||
for line in out.splitlines():
|
||||
name, cpu, mem = line.split("\t")
|
||||
if not name.startswith("mtusi-lab6-"):
|
||||
continue
|
||||
svc = name[len("mtusi-lab6-"):].rsplit("-", 1)[0]
|
||||
cur = row.setdefault(svc, [0.0, 0.0])
|
||||
cur[0] += float(cpu.rstrip("%") or 0)
|
||||
cur[1] += parse_mem(mem.split(" / ")[0])
|
||||
samples.append(row)
|
||||
stop.wait(5)
|
||||
|
||||
|
||||
def docker_socket():
|
||||
host = subprocess.run(["docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
return host.replace("unix://", "")
|
||||
|
||||
|
||||
def cpu_seconds():
|
||||
"""Cumulative container CPU seconds per service from the Docker API (exact over a window, unlike docker stats)."""
|
||||
sock = docker_socket()
|
||||
ids = subprocess.run(["docker", "ps", "--filter", "label=com.docker.compose.project=mtusi-lab6", "--format",
|
||||
"{{.ID}} {{.Names}}"], capture_output=True, text=True).stdout.splitlines()
|
||||
out = {}
|
||||
for line in ids:
|
||||
cid, name = line.split()
|
||||
svc = name[len("mtusi-lab6-"):].rsplit("-", 1)[0]
|
||||
raw = subprocess.run(["curl", "-s", "--unix-socket", sock,
|
||||
"http://localhost/containers/%s/stats?stream=false&one-shot=true" % cid],
|
||||
capture_output=True, text=True).stdout
|
||||
out[svc] = out.get(svc, 0.0) + json.loads(raw)["cpu_stats"]["cpu_usage"]["total_usage"] / 1e9
|
||||
return out
|
||||
|
||||
|
||||
def count_traces(query, start, end):
|
||||
try:
|
||||
return len(obs.tempo_search(query, limit=10000, start=start, end=end))
|
||||
except Exception as exc:
|
||||
return "error:%s" % type(exc).__name__
|
||||
|
||||
|
||||
def one_run(name, rep, rate, duration):
|
||||
apply(name)
|
||||
load = Load("https://localhost:8443", users=4, threads=96)
|
||||
load.run(rate, 20, 0.5, 1, 1) # warm-up, same mix
|
||||
time.sleep(20)
|
||||
a = counters()
|
||||
load = Load("https://localhost:8443", users=4, threads=96)
|
||||
stop, samples = threading.Event(), []
|
||||
sampler = threading.Thread(target=sample_stats, args=(stop, samples), daemon=True)
|
||||
sampler.start()
|
||||
cpu_a = cpu_seconds()
|
||||
t_start = time.time()
|
||||
summary = load.run(rate, duration, 1, 1, 1)
|
||||
t_end = time.time()
|
||||
cpu_b = cpu_seconds()
|
||||
stop.set()
|
||||
sampler.join(15)
|
||||
time.sleep(30) # SDK batch (2 s) + collector batch (2 s) + tail decision_wait (10 s) + scrape (15 s)
|
||||
b = counters()
|
||||
d = delta(a, b)
|
||||
# % of one core averaged over the load window (cumulative cgroup CPU; several replicas of a service are summed)
|
||||
cpu = {svc: round((cpu_b[svc] - cpu_a[svc]) / (t_end - t_start) * 100, 2) for svc in cpu_b if svc in cpu_a}
|
||||
mem = {svc: round(max(s[svc][1] for s in samples if svc in s), 1) for svc in samples[0]} if samples else {}
|
||||
w0, w1 = int(t_start) - 2, int(t_end) + 15
|
||||
traces = {
|
||||
"server_api": count_traces('{resource.service.name="messenger-api" && kind=server}', w0, w1),
|
||||
"slow": count_traces('{span.messenger.fault="slow"}', w0, w1),
|
||||
"error": count_traces('{span.messenger.fault="error"}', w0, w1),
|
||||
"pipeline_consumer": count_traces('{kind=consumer && span.messenger.job.outcome="succeeded"}', w0, w1),
|
||||
}
|
||||
result = {"config": name, "rep": rep, "env": CONFIGS[name], "load": summary, "cpu_pct_avg": cpu,
|
||||
"mem_mib_max": mem, "telemetry_delta": d, "traces_in_tempo": traces,
|
||||
"window": [t_start, t_end], "stats_samples": len(samples)}
|
||||
log("%s#%d: ok_rps=%s p50/p95/p99=%s/%s/%s ms api_cpu=%s+%s%% spans_in=%s tempo_spans=%s slow=%s/%d err=%s/%d" % (
|
||||
name, rep, summary["successful_rps"], summary["latency_ms_plain_ok"]["p50"],
|
||||
summary["latency_ms_plain_ok"]["p95"], summary["latency_ms_plain_ok"]["p99"], cpu.get("api-1"),
|
||||
cpu.get("api-2"), d.get("col_spans_in"), d.get("tempo_spans_in"), traces["slow"],
|
||||
summary["faults_sent"]["slow"], traces["error"], summary["faults_sent"]["error"]))
|
||||
return result
|
||||
|
||||
|
||||
def cmd_run(args):
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
path = OUT / "results.jsonl"
|
||||
names = args.configs.split(",")
|
||||
try:
|
||||
for rep in range(1, args.repeats + 1):
|
||||
for name in names:
|
||||
result = one_run(name, rep, args.rate, args.duration)
|
||||
result["hardware"] = HARDWARE
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(result, ensure_ascii=False) + "\n")
|
||||
finally:
|
||||
log("restore default configuration (on100)")
|
||||
apply("on100")
|
||||
|
||||
|
||||
def fmt(v, digits=0):
|
||||
if v is None:
|
||||
return "—"
|
||||
if isinstance(v, str):
|
||||
return v
|
||||
return ("%%.%df" % digits) % v
|
||||
|
||||
|
||||
def metric_500s(run_result):
|
||||
"""Injected 500s as seen by METRICS for this run: metrics are computed in the SDK, before any trace sampling."""
|
||||
start, end = run_result["window"]
|
||||
if run_result["config"] == "off":
|
||||
return None
|
||||
# Exact counter difference at the window borders (increase() extrapolates and overstates by ~10% here).
|
||||
expr = 'sum(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code="500"})'
|
||||
try:
|
||||
return obs.prom_scalar(expr, at=end + 20) - obs.prom_scalar(expr, at=start - 5)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def cmd_summary(_args):
|
||||
rows = [json.loads(line) for line in (OUT / "results.jsonl").read_text(encoding="utf-8").splitlines() if line]
|
||||
by = {}
|
||||
for r in rows:
|
||||
by.setdefault(r["config"], []).append(r)
|
||||
|
||||
def values(items, fn):
|
||||
return [v for v in (fn(x) for x in items) if isinstance(v, (int, float))]
|
||||
|
||||
def avg(items, fn):
|
||||
vals = values(items, fn)
|
||||
return statistics.mean(vals) if vals else None
|
||||
|
||||
def spread(items, fn, digits=1):
|
||||
vals = values(items, fn)
|
||||
if not vals:
|
||||
return "—"
|
||||
return "%s (%s…%s)" % (fmt(statistics.mean(vals), digits), fmt(min(vals), digits), fmt(max(vals), digits))
|
||||
|
||||
lat = lambda q: (lambda x: x["load"]["latency_ms_plain_ok"][q]) # noqa: E731
|
||||
cpu = lambda *svc: (lambda x: sum(x["cpu_pct_avg"].get(s, 0) for s in svc)) # noqa: E731
|
||||
delta_of = lambda key: (lambda x: x["telemetry_delta"].get(key)) # noqa: E731
|
||||
traces = lambda key: (lambda x: x["traces_in_tempo"].get(key)) # noqa: E731
|
||||
faults = lambda key: (lambda x: x["load"]["faults_sent"][key]) # noqa: E731
|
||||
names = [n for n in CONFIGS if n in by]
|
||||
|
||||
lines = ["Среднее по прогонам (мин…макс). CPU — % одного ядра за окно нагрузки, реплики сервиса суммируются.", "",
|
||||
"| Конфигурация | Прогонов | Успешн. RPS | Неожид. ошибки | p50, ms | p95, ms | p99, ms | CPU api-1+2, % | CPU worker, % |",
|
||||
"|---|---|---|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
lines.append("| %s | %d | %s | %s | %s | %s | %s | %s | %s |" % (
|
||||
n, len(i), fmt(avg(i, lambda x: x["load"]["successful_rps"]), 1),
|
||||
fmt(avg(i, lambda x: x["load"]["server_errors_unexpected"])), spread(i, lat("p50")), spread(i, lat("p95")),
|
||||
spread(i, lat("p99")), spread(i, cpu("api-1", "api-2")), spread(i, cpu("worker"))))
|
||||
lines += ["", "| Конфигурация | CPU collector, % | CPU Tempo, % | CPU Loki, % | CPU Prometheus, % | RSS api-1 (макс), MiB | RSS collector, MiB | RSS Tempo, MiB |",
|
||||
"|---|---|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
mem = lambda s: (lambda x: x["mem_mib_max"].get(s)) # noqa: E731
|
||||
lines.append("| %s | %s | %s | %s | %s | %s | %s | %s |" % (
|
||||
n, spread(i, cpu("otel-collector"), 2), spread(i, cpu("tempo"), 2), spread(i, cpu("loki"), 2),
|
||||
spread(i, cpu("prometheus"), 2), fmt(avg(i, mem("api-1"))), fmt(avg(i, mem("otel-collector"))),
|
||||
fmt(avg(i, mem("tempo")))))
|
||||
lines += ["", "| Конфигурация | Spans → collector | Spans → Tempo | Отказы/отбросы collector | OTLP ingest, KiB | Tempo ingest, KiB | Loki ingest, KiB |",
|
||||
"|---|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
kib = lambda key: (avg(i, delta_of(key)) / 1024 if avg(i, delta_of(key)) is not None else None) # noqa: E731
|
||||
lost = avg(i, lambda x: (x["telemetry_delta"].get("col_spans_refused") or 0) + (x["telemetry_delta"].get("col_spans_dropped") or 0))
|
||||
lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (
|
||||
n, fmt(avg(i, delta_of("col_spans_in"))), fmt(avg(i, delta_of("tempo_spans_in"))), fmt(lost),
|
||||
fmt(kib("col_otlp_bytes_in")), fmt(kib("tempo_bytes_in")), fmt(kib("loki_bytes_in"))))
|
||||
lines += ["", "Сумма по всем прогонам конфигурации: сохранено трасс / отправлено. «500 в метриках» — разность счётчика HTTP в Prometheus на границах окна.", "",
|
||||
"| Конфигурация | Серверных трасс API | slow (+600 ms) | error (500) | upload-конвейеров | 500 в метриках / отправлено |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
total = lambda fn: sum(values(i, fn)) # noqa: E731
|
||||
m500 = [metric_500s(x) for x in i]
|
||||
lines.append("| %s | %d / %d | %d / %d | %d / %d | %d / %d | %s / %d |" % (
|
||||
n, total(traces("server_api")), total(lambda x: x["load"]["requests"]),
|
||||
total(traces("slow")), total(faults("slow")), total(traces("error")), total(faults("error")),
|
||||
total(traces("pipeline_consumer")), total(lambda x: x["load"]["by_kind"]["upload"]["n"]),
|
||||
"—" if None in m500 else "%.0f" % sum(m500), total(faults("error"))))
|
||||
text = "\n".join(lines) + "\n"
|
||||
(OUT / "summary.md").write_text(text, encoding="utf-8")
|
||||
print(text)
|
||||
|
||||
|
||||
HARDWARE = {}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
r = sub.add_parser("run")
|
||||
r.add_argument("--configs", default="off,on100,head10,tail")
|
||||
r.add_argument("--repeats", type=int, default=2)
|
||||
r.add_argument("--rate", type=float, default=60)
|
||||
r.add_argument("--duration", type=float, default=90)
|
||||
sub.add_parser("summary")
|
||||
args = p.parse_args()
|
||||
if args.cmd == "run":
|
||||
info = subprocess.run(["docker", "info", "--format", "{{.ServerVersion}} {{.NCPU}} {{.MemTotal}}"],
|
||||
capture_output=True, text=True).stdout.split()
|
||||
HARDWARE.update({"docker": info[0], "vm_cpus": int(info[1]), "vm_mem_gib": round(int(info[2]) / 2**30, 1)})
|
||||
cmd_run(args)
|
||||
else:
|
||||
cmd_summary(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Variant rules and worker resource limits. Runs INSIDE the worker container (Pillow + app code):
|
||||
|
||||
docker compose exec -T --index 1 worker python - < student-tests/variants_check.py
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import resource
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, "/app")
|
||||
from app import config # noqa: E402
|
||||
|
||||
FAILS = []
|
||||
|
||||
|
||||
def check(cond, msg):
|
||||
print(("ok " if cond else "FAIL ") + msg, flush=True)
|
||||
if not cond:
|
||||
FAILS.append(msg)
|
||||
|
||||
|
||||
def run_child(path, mem_mb=config.WORKER_CHILD_MEMORY_MB, cpu=config.JOB_TIMEOUT_SECONDS, max_pixels=config.MAX_IMAGE_PIXELS):
|
||||
out = tempfile.mkdtemp()
|
||||
|
||||
def limits():
|
||||
resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu + 5))
|
||||
|
||||
start = time.monotonic()
|
||||
done = subprocess.run([sys.executable, "-m", "app.imageproc", path, out, str(max_pixels)], capture_output=True,
|
||||
preexec_fn=limits, timeout=120, env={"PATH": os.environ["PATH"], "MALLOC_ARENA_MAX": "2"})
|
||||
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
produced = {v["name"]: v for v in json.loads(done.stdout)} if done.returncode == 0 else {}
|
||||
return done.returncode, produced, time.monotonic() - start, usage.ru_maxrss / 1024
|
||||
|
||||
|
||||
def save(img, fmt, **kw):
|
||||
path = tempfile.mktemp(suffix="." + fmt.lower())
|
||||
img.save(path, fmt, **kw)
|
||||
return path
|
||||
|
||||
|
||||
def dims(v):
|
||||
return v["width"], v["height"]
|
||||
|
||||
|
||||
def real(v):
|
||||
with Image.open(v["file"]) as im:
|
||||
return im.format, im.size, "exif" in im.info, im
|
||||
|
||||
|
||||
# 1. fixture 320x200 -> 256x160, crop 128, optimized not upscaled
|
||||
rc, p, _, _ = run_child("/app/tests/fixtures/sample.png" if os.path.exists("/app/tests/fixtures/sample.png") else
|
||||
save(Image.new("RGB", (320, 200), "red"), "PNG"))
|
||||
check(rc == 0 and dims(p["thumbnail"]) == (256, 160), "320x200 -> thumbnail 256x160")
|
||||
check(dims(p["crop"]) == (128, 128), "crop 128x128")
|
||||
check(dims(p["optimized"]) == (320, 200) and real(p["optimized"])[0] == "WEBP", "optimized WebP 320x200, no upscale")
|
||||
check(real(p["thumbnail"])[0] == "JPEG" and real(p["crop"])[0] == "JPEG", "thumbnail/crop are JPEG")
|
||||
|
||||
# 2. small source: no upscale for thumbnail, upscale allowed for crop
|
||||
rc, p, _, _ = run_child(save(Image.new("RGB", (40, 10), "blue"), "PNG"))
|
||||
check(dims(p["thumbnail"]) == (40, 10) and dims(p["crop"]) == (128, 128), "40x10: thumbnail 40x10, crop 128x128")
|
||||
|
||||
# 3. extreme aspect ratio: floor rounding, minimum 1 px
|
||||
rc, p, _, _ = run_child(save(Image.new("RGB", (3000, 2), "blue"), "PNG"))
|
||||
check(dims(p["thumbnail"]) == (256, 1) and dims(p["optimized"]) == (1280, 1), "3000x2 -> 256x1 / 1280x1 (min 1px)")
|
||||
rc, p, _, _ = run_child(save(Image.new("RGB", (1001, 999), "blue"), "PNG"))
|
||||
check(dims(p["thumbnail"]) == (256, 255), "1001x999 -> 256x255 (floor)")
|
||||
|
||||
# 4. EXIF orientation 6 (rotate 90): stored 400x200 -> upright 200x400 -> thumbnail 128x256; EXIF stripped
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = 6
|
||||
img = Image.new("RGB", (400, 200), "white")
|
||||
img.paste((255, 0, 0), (0, 0, 200, 200)) # left half red
|
||||
rc, p, _, _ = run_child(save(img, "JPEG", exif=exif.tobytes(), quality=95))
|
||||
fmt, size, has_exif, im = real(p["thumbnail"])
|
||||
check(size == (128, 256), "EXIF orientation applied: 400x200 (o=6) -> 128x256")
|
||||
with Image.open(p["thumbnail"]["file"]) as t:
|
||||
top = t.convert("RGB").getpixel((64, 20))
|
||||
check(top[0] > 200 and top[1] < 80, "rotated content: red half on top after orientation 6")
|
||||
check(not has_exif and "exif" not in Image.open(p["optimized"]["file"]).info, "EXIF removed from thumbnail/optimized")
|
||||
|
||||
# 5. alpha composited on white for JPEG, kept for WebP
|
||||
rgba = Image.new("RGBA", (100, 100), (0, 0, 0, 0))
|
||||
rc, p, _, _ = run_child(save(rgba, "PNG"))
|
||||
with Image.open(p["thumbnail"]["file"]) as t:
|
||||
px = t.convert("RGB").getpixel((50, 50))
|
||||
check(min(px) >= 250, "transparent PNG -> white JPEG thumbnail")
|
||||
check(Image.open(p["optimized"]["file"]).mode == "RGBA", "WebP optimized keeps alpha")
|
||||
|
||||
# 6. 16-bit grayscale PNG, CMYK JPEG, palette PNG
|
||||
rc16, _, _, _ = run_child(save(Image.new("I;16", (300, 300), 40000), "PNG"))
|
||||
rcc, _, _, _ = run_child(save(Image.new("CMYK", (300, 300), (0, 255, 0, 0)), "JPEG"))
|
||||
rcp, _, _, _ = run_child(save(Image.new("P", (300, 300), 3), "PNG", transparency=3))
|
||||
check(rc16 == 0 and rcc == 0 and rcp == 0, "16-bit PNG, CMYK JPEG, palette+transparency PNG are processed")
|
||||
|
||||
# 7. limits: pixels (exit 4), not an image (exit 3), memory (exit 5), CPU (SIGXCPU)
|
||||
rc, _, _, _ = run_child(save(Image.new("RGB", (100, 100)), "PNG"), max_pixels=5000)
|
||||
check(rc == 4, "pixel limit enforced before decode -> image_too_large (exit 4)")
|
||||
junk = tempfile.mktemp()
|
||||
open(junk, "wb").write(b"\x89PNG\r\n\x1a\n" + os.urandom(2000))
|
||||
rc, _, _, _ = run_child(junk)
|
||||
check(rc == 3, "corrupted PNG -> invalid_image (exit 3)")
|
||||
big = save(Image.new("RGB", (6000, 6000), "green"), "PNG")
|
||||
rc, _, _, _ = run_child(big, mem_mb=160)
|
||||
check(rc == 5, "36 Mpx PNG with 160 MiB address-space limit -> image_too_complex (exit 5), got %s" % rc)
|
||||
|
||||
# 8. largest allowed inputs under the real limits: time and child peak RSS
|
||||
for name, w, h, fmt in (("png", 7900, 5000, "PNG"), ("jpeg", 7900, 5000, "JPEG")):
|
||||
noise = Image.effect_noise((w // 10, h // 10), 60).convert("RGB").resize((w, h))
|
||||
path = save(noise, fmt, **({"quality": 90} if fmt == "JPEG" else {"compress_level": 1}))
|
||||
rc, p, secs, rss = run_child(path)
|
||||
check(rc == 0 and dims(p["thumbnail"]) == (256, 162), "%.1f Mpx %s (%d MB file) ok in %.1fs, peak child RSS %.0f MiB"
|
||||
% (w * h / 1e6, name.upper(), os.path.getsize(path) >> 20, secs, rss))
|
||||
if fmt == "PNG":
|
||||
rc, _, _, _ = run_child(path, cpu=0)
|
||||
check(rc == -24, "CPU limit exhausted -> SIGXCPU (worker: permanent image_too_complex), got %s" % rc)
|
||||
|
||||
print("RESULT:", "PASS" if not FAILS else "FAIL %s" % FAILS)
|
||||
sys.exit(1 if FAILS else 0)
|
||||
Reference in New Issue
Block a user