ЛР7: TLS/mTLS по матрице доверия, OpenBao, Argon2id, ротация и отрицательные тесты

This commit is contained in:
LOSYASH
2026-12-02 23:53:37 +01:00
parent 20afc2c790
commit 8c991be7cf
105 changed files with 13881 additions and 106 deletions
+231
View File
@@ -0,0 +1,231 @@
"""lab6, уровни 3–4: сигналы приложения действительно доходят до хранилищ и связаны между собой.
Запуск (стенд поднят, Grafana https://localhost:3000, пароль в secrets/grafana_admin_password):
python student-tests/observability.py
Без Docker (прямые адреса хранилищ):
python student-tests/observability.py --prom-url https://prometheus:9090 \\
--loki-url https://loki:3100 --tempo-url https://tempo:3200 (+ TELEM_CLIENT_CERT/KEY)
Проверяется:
1. контролируемый запрос со своим traceparent → server span в Tempo + лог API с тем же
trace_id и X-Request-Id ответа в Loki;
2. upload: producer span API → consumer span worker (parent = producer) → S3/DB spans worker,
лог worker job.ready с тем же trace_id;
3. retry в одном trace (после jobs.py retry-replay): попытки 1..N — consumer spans одного trace;
4. метрики контракта есть в Prometheus, с нужными labels и единицами (секунды);
5. запрещённых labels/высокой кардинальности нет; пароль, токен, текст сообщения
и signed URL не попали ни в логи, ни в spans;
6. provisioning: datasources prom/loki/tempo здоровы, dashboard и alert rules загружены.
"""
from __future__ import annotations
import argparse
import re
import sys
import time
import uuid
sys.path.insert(0, __import__("os").path.dirname(__file__))
from common import SAMPLE_PNG, Api, Report, upload, wait_ready # noqa: E402
from telem import Telemetry, add_args, new_traceparent # noqa: E402
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", "job_id",
"url", "url_full", "http_target", "http_url", "filename", "username", "text"}
REQUIRED_METRICS = {
# имя в Prometheus: обязательные labels
"http_server_request_duration_seconds_bucket": {"http_request_method", "http_route", "http_response_status_code", "le"},
"messenger_jobs_processed_total": {"job_type", "outcome"},
"messenger_job_duration_seconds_bucket": {"job_type", "outcome", "le"},
"messenger_attachment_time_to_ready_seconds_bucket": {"le"},
"messenger_queue_depth": {"queue", "state"},
"messenger_queue_oldest_age_seconds": {"queue"},
"messenger_db_pool_connections": {"state"},
"messenger_db_pool_waiting": set(),
"messenger_db_pool_max": set(),
"messenger_worker_busy": set(),
"messenger_worker_capacity": set(),
"process_cpu_time_seconds_total": set(),
"process_memory_usage_bytes": set(),
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="https://localhost:8443")
add_args(ap)
args = ap.parse_args()
api, tel, rep = Api(args.base_url), Telemetry(args), Report()
t0 = time.monotonic()
# ------------------------------------------------------------------ подготовка
secret_text = "SECRET-BODY-" + uuid.uuid4().hex
alice = api.new_user("obs")
bob = api.new_user("obs")
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "obs", "member_ids": [alice["id"], bob["id"]]},
token=alice["token"])
assert st == 201, (st, chat)
# ------------------------------------------------------------------ 1. запрос → trace + лог
print("== контролируемый запрос: trace и лог API ==")
tid, tp = new_traceparent()
st, msg, rh = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": secret_text},
token=alice["token"], headers={"traceparent": tp})
rid = rh.get("X-Request-Id")
rep.check(st == 201, f"POST message с traceparent → 201 (trace_id {tid})")
spans = tel.wait_trace(tid, lambda s: any(x["kind"] == "SPAN_KIND_SERVER" for x in s))
server = [s for s in spans if s["kind"] == "SPAN_KIND_SERVER"]
rep.check(bool(server) and server[0]["service"] == "messenger-api",
f"Tempo: server span messenger-api найден ({len(spans)} spans)")
if server:
a = server[0]["attrs"]
rep.check(a.get("http.route") == "/api/v1/chats/{chat_id}/messages",
f"server span: http.route = шаблон ({a.get('http.route')})")
rep.check(str(a.get("http.response.status_code")) == "201", "server span: status_code 201")
rep.check(a.get("messenger.request.id") == rid, f"server span: messenger.request.id = X-Request-Id ({rid})")
res = server[0]["resource"]
rep.check(all(res.get(k) for k in ("service.version", "service.instance.id")) and
res.get("deployment.environment.name") == "lab",
f"resource: service.version={res.get('service.version')} instance={res.get('service.instance.id')} env={res.get('deployment.environment.name')}")
rep.check(any(s["attrs"].get("db.system") == "postgresql" for s in spans),
"trace запроса содержит DB spans (psycopg)")
logs = []
for _ in range(15):
logs = tel.logs(f'{{service_name="messenger-api"}} | trace_id="{tid}"', since_s=600)
if logs:
break
time.sleep(2)
http_logs = [l for l in logs if l.get("event") == "http.request"]
rep.check(bool(http_logs), f"Loki: лог API с тем же trace_id ({len(logs)} записей)")
if http_logs:
l = http_logs[0]
rep.check(l.get("request_id") == rid or l.get("request.id") == rid,
"лог: request.id = X-Request-Id ответа")
rep.check(bool(l.get("span_id")) and l.get("severity_text") in ("INFO", "WARN", "ERROR"),
f"лог: span_id={l.get('span_id')}, severity={l.get('severity_text')}, service_name={l.get('service_name')}")
# ------------------------------------------------------------------ 2. upload → worker
print("== upload: producer → consumer → S3/DB в одном trace ==")
tid2, tp2 = new_traceparent()
st, att, _ = upload(api, alice["token"], chat["id"], SAMPLE_PNG, "secret-name-photo.png",
headers={"traceparent": tp2})
rep.check(st == 202, f"upload с traceparent → 202 (trace_id {tid2})")
att = wait_ready(api, alice["token"], att["id"], 90)
rep.check(att.get("status") == "ready", "attachment → ready")
def chain_done(s):
return any(x["kind"] == "SPAN_KIND_CONSUMER" and x["attrs"].get("messenger.job.outcome") for x in s)
spans = tel.wait_trace(tid2, chain_done, 60)
by_id = {s["span_id"]: s for s in spans}
prod = [s for s in spans if s["kind"] == "SPAN_KIND_PRODUCER" and s["service"] == "messenger-api"]
cons = [s for s in spans if s["kind"] == "SPAN_KIND_CONSUMER" and s["service"] == "messenger-worker"]
rep.check(bool(prod), "producer span «send attachments:jobs» в API")
rep.check(bool(cons), "consumer span «process attachments:jobs» в worker")
if prod and cons:
rep.check(cons[0]["parent"] == prod[0]["span_id"],
"consumer.parent = producer span (W3C traceparent через сообщение broker)")
rep.check(cons[0]["attrs"].get("messenger.job.outcome") == "ready", "consumer: outcome=ready")
def under(s, root):
while s and s["parent"]:
if s["parent"] == root["span_id"]:
return True
s = by_id.get(s["parent"])
return False
if cons:
kids = [s for s in spans if under(s, cons[0])]
s3 = sorted({s["name"] for s in kids if s["attrs"].get("rpc.service") == "S3"})
db = [s for s in kids if s["attrs"].get("db.system") == "postgresql"]
rep.check({"S3.GetObject", "S3.PutObject"} <= set(s3), f"worker → S3 spans: {s3}")
rep.check(len(db) >= 3, f"worker → DB spans: {len(db)}")
rep.check(any(s["name"] == "image.render" for s in kids), "worker: span image.render")
if spans:
print(" цепочка:", " → ".join(dict.fromkeys(
f"{s['service'].split('-')[1]}:{s['name']}" for s in spans
if s["kind"] in ("SPAN_KIND_SERVER", "SPAN_KIND_PRODUCER", "SPAN_KIND_CONSUMER")
or s["name"] == "image.render")))
wlogs = []
for _ in range(15):
wlogs = tel.logs(f'{{service_name="messenger-worker"}} | trace_id="{tid2}"', since_s=600)
if any(l.get("event") == "job.ready" for l in wlogs):
break
time.sleep(2)
rep.check(any(l.get("event") == "job.ready" for l in wlogs),
f"Loki: лог worker job.ready с тем же trace_id ({len(wlogs)} записей)")
# ------------------------------------------------------------------ 3. retry в одном trace
print("== retry: все попытки задачи в одном trace ==")
found = (tel.search("{ span.messenger.job.attempt >= 3 && kind = consumer }", since_s=6 * 3600, limit=5)
or tel.search("{ span.messenger.job.attempt >= 2 && kind = consumer }", since_s=6 * 3600, limit=5))
if not found:
print(" SKIP: trace с retry не найден — сначала jobs.py --scenario retry-replay (профиль fault)")
else:
spans = tel.trace(found[0]["traceID"])
tries = sorted({int(s["attrs"]["messenger.job.attempt"]) for s in spans
if s["kind"] == "SPAN_KIND_CONSUMER" and "messenger.job.attempt" in s["attrs"]})
jobs = {s["attrs"].get("messenger.job.id") for s in spans if s["kind"] == "SPAN_KIND_CONSUMER"}
outcomes = [s["attrs"].get("messenger.job.outcome") for s in spans if s["kind"] == "SPAN_KIND_CONSUMER"]
rep.check(len(tries) >= 2 and tries[0] == 1 and len(jobs) == 1,
f"trace {found[0]['traceID'][:12]}…: попытки {tries} одной job, outcomes {outcomes}")
# ------------------------------------------------------------------ 4. метрики
print("== метрики контракта в Prometheus ==")
time.sleep(12) # интервал экспорта метрик SDK — 10 s
for name, labels in REQUIRED_METRICS.items():
series = tel.series(name)
have = set().union(*(s.keys() for s in series)) if series else set()
jobs = sorted({s.get("job") for s in series})
rep.check(bool(series) and labels <= have, f"{name}: {len(series)} серий, job={jobs}")
routes = tel.label_values("http_route")
rep.check(bool(routes) and not any(UUID_RE.search(r) for r in routes),
f"http_route — только шаблоны ({len(routes)} значений, UUID нет)")
rep.check(tel.scalar('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))') is not None,
"p95 считается из buckets (histogram_quantile по sum by le)")
le = sorted({float(s["le"]) for s in tel.series("http_server_request_duration_seconds_bucket") if s["le"] != "+Inf"})
rep.check(bool(le) and le[0] <= 0.01 and le[-1] >= 5, f"buckets HTTP в секундах: {le[0] if le else '-'} … {le[-1] if le else '-'}")
tinfo = {s.get("job") for s in tel.series('target_info{deployment_environment_name="lab"}')}
rep.check({"messenger-api", "messenger-worker"} <= tinfo, f"target_info (resource) для {sorted(tinfo)}")
# ------------------------------------------------------------------ 5. кардинальность и секреты
print("== кардинальность и утечки ==")
st, d = tel.get(tel.prom + "/api/v1/labels", {"match[]": '{__name__=~"messenger_.+|http_server_.+"}'})
names = set(d["data"]) if st == 200 else set()
rep.check(bool(names) and not (names & FORBIDDEN_LABELS),
f"нет запрещённых labels у метрик приложения ({sorted(names & FORBIDDEN_LABELS) or 'ok'})")
per_inst = int(tel.scalar('max(count by (instance) ({__name__=~"messenger_.+|http_server_.+", job=~"messenger-.+"}))', 0))
combos = int(tel.scalar('count(count by (http_route, http_request_method, http_response_status_code) '
'(http_server_request_duration_seconds_count{job="messenger-api"}))', 0))
rep.check(0 < per_inst < 1000 and combos < 100,
f"кардинальность ограничена: ≤ {per_inst} серий на процесс, {combos} комбинаций route×method×code")
for what, needle in (("пароль", alice["password"]), ("Bearer token", alice["token"]),
("текст сообщения", secret_text)):
hits = tel.logs(f'{{service_name=~"messenger-.+"}} |= "{needle}"', since_s=900, limit=5)
rep.check(not hits, f"Loki: {what} не найден в логах")
leaked = [(s["name"], k) for tr in (tid, tid2) for s in tel.trace(tr) for k, v in s["attrs"].items()
if any(x in str(v) for x in (alice["password"], alice["token"], secret_text, "X-Amz-Signature"))]
rep.check(not leaked, f"Tempo: в атрибутах spans нет пароля/токена/текста/signed URL {leaked[:3]}")
dbstmts = [s["attrs"]["db.statement"] for tr in (tid,) for s in tel.trace(tr) if "db.statement" in s["attrs"]]
rep.check(dbstmts and all(secret_text not in q for q in dbstmts),
f"db.statement — с плейсхолдерами %s, без значений ({len(dbstmts)} запросов)")
# ------------------------------------------------------------------ 6. provisioning
print("== provisioning ==")
rules = {r["name"]: r for r in tel.rules()}
for name in ("ApiHighErrorRate", "AttachmentQueueLagGrowing"):
r = rules.get(name, {})
rep.check(r.get("health") == "ok", f"alert rule {name} загружен ({r.get('state')}, for={r.get('duration')}s)")
if not tel.direct:
for uid in ("prom", "loki", "tempo"):
st, h = tel.get(f"{tel.grafana}/api/datasources/uid/{uid}/health")
rep.check(st == 200 and isinstance(h, dict) and h.get("status") == "OK",
f"Grafana datasource {uid}: {h.get('message', h) if isinstance(h, dict) else h}")
st, dash = tel.get(f"{tel.grafana}/api/dashboards/uid/messenger-lab6")
panels = [p for p in dash.get("dashboard", {}).get("panels", []) if p.get("type") != "row"] if st == 200 else []
rep.check(st == 200 and len(panels) >= 15,
f"dashboard «Messenger — lab6» из provisioning: {len(panels)} панелей, provisioned={dash.get('meta', {}).get('provisioned') if st == 200 else '-'}")
print(f" [observability: {time.monotonic() - t0:.0f}s]")
rep.finish()
if __name__ == "__main__":
main()