forked from mtusi2026/mtusi2026lab7
ЛР 7 — БПИ2303 — Лазарев — на 3
Перенесена реализация lab6; бизнес-API без изменений, транспорт — HTTPS. - Внешний HTTPS (public-ca) на 127.0.0.1:8443; HSTS, TLS >= 1.2. - Обязательное mTLS LB -> каждая API-реплика: API проверяет цепочку internal-ca и SAN клиента (allowlist: lb); health только на 127.0.0.1. - TLS с проверкой сервера ко всем зависимостям: PostgreSQL verify-full (pg_hba только hostssl), HTTPS S3, AMQPS, OTLP/HTTPS с client cert, mTLS Collector -> Prometheus/Loki/Tempo, Grafana -> datasources, scrape. - OpenBao 2.7.2 не в dev-mode: Raft на volume, init/unseal оператором, auth/cert с ролью и policy на сервис, TTL 15 мин + renew/re-login. - Отдельные роли PostgreSQL с грантами по таблицам; разные ключи S3 и пользователи брокера выдаются из OpenBao. - Argon2id (m=19 MiB, t=2, p=1, замер на стенде) и rehash при входе. - Случайный X-Instance-Id; hardening контейнеров (non-root, cap_drop ALL, no-new-privileges, read-only, лимиты); TCP_NODELAY на сокете API. - Модель угроз, trust matrix, отрицательные тесты TLS/mTLS, API, OpenBao, hardening; evidence, в т.ч. прогон из чистого clone.
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
"""Помощники lab6: запросы к Prometheus / Loki / Tempo ЧЕРЕЗ Grafana (datasource proxy).
|
||||
|
||||
Так проверка заодно подтверждает, что Grafana видит все три хранилища по provisioning.
|
||||
Пароль admin Grafana читается из secrets/grafana_admin_password и нигде не печатается.
|
||||
Только стандартная библиотека.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GRAFANA = os.environ.get("GRAFANA_URL", "https://localhost:%s" % os.environ.get("GRAFANA_PORT", "3000"))
|
||||
# Lab7: Grafana — HTTPS с сертификатом public-ca (SAN localhost/127.0.0.1); проверка обязательна.
|
||||
import ssl # noqa: E402
|
||||
_CTX = ssl.create_default_context(cafile=os.environ.get("CA_FILE") or str(ROOT / "secrets/pki/public-ca.crt"))
|
||||
|
||||
|
||||
def _auth_header():
|
||||
password = (ROOT / "secrets/grafana_admin_password").read_text(encoding="utf-8").strip()
|
||||
return "Basic " + base64.b64encode(("admin:" + password).encode()).decode()
|
||||
|
||||
|
||||
def grafana(path, params=None, timeout=20, accept="application/json"):
|
||||
url = GRAFANA + path + ("?" + urllib.parse.urlencode(params, doseq=True) if params else "")
|
||||
req = urllib.request.Request(url, headers={"Authorization": _auth_header(), "Accept": accept})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout, context=_CTX) as resp:
|
||||
return json.loads(resp.read() or b"null")
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return None
|
||||
raise RuntimeError("grafana %s -> HTTP %d: %s" % (path, exc.code, exc.read()[:300]))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Prometheus
|
||||
def prom(path, **params):
|
||||
return grafana("/api/datasources/proxy/uid/prometheus/api/v1/" + path, params)
|
||||
|
||||
|
||||
def prom_query(expr, at=None):
|
||||
params = {"query": expr}
|
||||
if at is not None:
|
||||
params["time"] = "%.3f" % at
|
||||
data = prom("query", **params)
|
||||
return data["data"]["result"]
|
||||
|
||||
|
||||
def prom_value(expr, at=None, default=None):
|
||||
res = prom_query(expr, at)
|
||||
if not res:
|
||||
return default
|
||||
return float(res[0]["value"][1])
|
||||
|
||||
|
||||
def prom_range(expr, start, end, step=15):
|
||||
data = prom("query_range", query=expr, start="%.3f" % start, end="%.3f" % end, step=str(step))
|
||||
return data["data"]["result"]
|
||||
|
||||
|
||||
def prom_alerts():
|
||||
return prom("alerts")["data"]["alerts"]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Loki
|
||||
def loki_query(query, start, end, limit=100, direction="forward"):
|
||||
data = grafana("/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
|
||||
{"query": query, "start": str(int(start * 1e9)), "end": str(int(end * 1e9)),
|
||||
"limit": str(limit), "direction": direction})
|
||||
out = []
|
||||
for stream in data["data"]["result"]:
|
||||
for ts, line, *meta in stream["values"]:
|
||||
item = {"ts": int(ts) / 1e9, "line": line, "labels": stream["stream"]}
|
||||
if meta:
|
||||
item["metadata"] = meta[0]
|
||||
out.append(item)
|
||||
out.sort(key=lambda x: x["ts"])
|
||||
return out
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ Tempo
|
||||
def tempo_trace(trace_id):
|
||||
"""Трасса в формате OTLP JSON (batches/resourceSpans) или None, если ещё не доступна."""
|
||||
return grafana("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id)
|
||||
|
||||
|
||||
def tempo_search(traceql, start, end, limit=20):
|
||||
return grafana("/api/datasources/proxy/uid/tempo/api/search",
|
||||
{"q": traceql, "start": str(int(start)), "end": str(int(end)), "limit": str(limit)})
|
||||
|
||||
|
||||
def _attr_value(v):
|
||||
for key in ("stringValue", "intValue", "boolValue", "doubleValue"):
|
||||
if key in v:
|
||||
return v[key]
|
||||
return v
|
||||
|
||||
|
||||
def _hex(b64_or_hex):
|
||||
if not b64_or_hex:
|
||||
return ""
|
||||
if len(b64_or_hex) in (16, 32) and all(c in "0123456789abcdef" for c in b64_or_hex):
|
||||
return b64_or_hex
|
||||
return base64.b64decode(b64_or_hex).hex()
|
||||
|
||||
|
||||
def flatten_spans(trace):
|
||||
"""[{service, name, kind, span_id, parent_id, start, end, duration_ms, status, attrs}]"""
|
||||
spans = []
|
||||
batches = (trace or {}).get("batches") or (trace or {}).get("resourceSpans") or []
|
||||
for batch in batches:
|
||||
res = {a["key"]: _attr_value(a["value"]) for a in batch.get("resource", {}).get("attributes", [])}
|
||||
for scope in batch.get("scopeSpans") or batch.get("instrumentationLibrarySpans") or []:
|
||||
for s in scope.get("spans", []):
|
||||
start, end = int(s["startTimeUnixNano"]), int(s["endTimeUnixNano"])
|
||||
spans.append({
|
||||
"service": res.get("service.name"), "instance": res.get("service.instance.id"),
|
||||
"name": s["name"], "kind": s.get("kind", ""), "span_id": _hex(s.get("spanId")),
|
||||
"parent_id": _hex(s.get("parentSpanId")), "trace_id": _hex(s.get("traceId")),
|
||||
"start": start / 1e9, "end": end / 1e9, "duration_ms": round((end - start) / 1e6, 3),
|
||||
"status": (s.get("status") or {}).get("code", "STATUS_CODE_UNSET"),
|
||||
"attrs": {a["key"]: _attr_value(a["value"]) for a in s.get("attributes", [])}})
|
||||
spans.sort(key=lambda x: x["start"])
|
||||
return spans
|
||||
|
||||
|
||||
def wait_trace(trace_id, predicate=None, timeout=60, interval=2):
|
||||
"""Ждём, пока трасса появится в Tempo (и удовлетворит predicate(spans))."""
|
||||
deadline = time.monotonic() + timeout
|
||||
spans = []
|
||||
while time.monotonic() < deadline:
|
||||
tr = tempo_trace(trace_id)
|
||||
spans = flatten_spans(tr) if tr else []
|
||||
if spans and (predicate is None or predicate(spans)):
|
||||
return spans
|
||||
time.sleep(interval)
|
||||
return spans
|
||||
|
||||
|
||||
def tree(spans):
|
||||
"""Текстовое дерево трассы (для evidence): отступ = глубина, длительность, сервис."""
|
||||
by_parent = {}
|
||||
ids = {s["span_id"] for s in spans}
|
||||
for s in spans:
|
||||
by_parent.setdefault(s["parent_id"] if s["parent_id"] in ids else "", []).append(s)
|
||||
t0 = min((s["start"] for s in spans), default=0)
|
||||
lines = []
|
||||
|
||||
def walk(pid, depth):
|
||||
for s in sorted(by_parent.get(pid, []), key=lambda x: x["start"]):
|
||||
lines.append("%s%-44s %-17s +%8.1fms %9.1fms %s%s" % (
|
||||
" " * depth, s["name"][:44], s["service"] or "", (s["start"] - t0) * 1000, s["duration_ms"],
|
||||
s["kind"].replace("SPAN_KIND_", ""), " ERROR" if s["status"] == "STATUS_CODE_ERROR" else ""))
|
||||
walk(s["span_id"], depth + 1)
|
||||
walk("", 0)
|
||||
return lines
|
||||
Reference in New Issue
Block a user