Files
mtusi2026lab7/student-tests/check_dashboard.py
T
alenchha 861e7722b5 ЛР 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.
2026-11-16 10:49:13 +03:00

80 lines
4.0 KiB
Python

#!/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)