forked from mtusi2026/mtusi2026lab7
254 lines
9.0 KiB
Python
Executable File
254 lines
9.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Проверяет доставку telemetry через TLS и отсутствие чувствительных данных."""
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import re
|
|
import ssl
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import urlencode
|
|
from urllib.request import Request, urlopen
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, Failure, check, run
|
|
|
|
UPLOAD_ROUTE = "/api/v1/chats/{chat_id}/attachments"
|
|
|
|
|
|
def eventually(label, predicate, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
result = predicate()
|
|
if result:
|
|
return result
|
|
except (URLError, TimeoutError, Failure):
|
|
pass
|
|
time.sleep(1)
|
|
raise Failure(label)
|
|
|
|
|
|
class Observations:
|
|
def __init__(self, grafana, ca_file):
|
|
self.grafana = grafana.rstrip("/")
|
|
self.context = ssl.create_default_context(cafile=ca_file)
|
|
password_file = ROOT / "secrets/grafana_admin_password"
|
|
value = ("admin:" + password_file.read_text().strip()).encode()
|
|
self.authorization = "Basic " + base64.b64encode(value).decode()
|
|
|
|
def open(self, url):
|
|
request = Request(url, headers={"Authorization": self.authorization})
|
|
return urlopen(request, context=self.context, timeout=5)
|
|
|
|
def get(self, path, **params):
|
|
url = self.grafana + path + ("?" + urlencode(params) if params else "")
|
|
try:
|
|
with self.open(url) as response:
|
|
return json.load(response)
|
|
except HTTPError as error:
|
|
if error.code == 404:
|
|
raise Failure(f"Grafana endpoint {path} вернул 404") from None
|
|
raise
|
|
|
|
def query(self, expression):
|
|
data = self.get(
|
|
"/api/datasources/proxy/uid/prometheus/api/v1/query", query=expression
|
|
)
|
|
return data["data"]["result"]
|
|
|
|
def trace(self, trace_id):
|
|
try:
|
|
data = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id)
|
|
except HTTPError as error:
|
|
if error.code == 404:
|
|
return []
|
|
raise
|
|
return [
|
|
(span, attributes(batch["resource"]).get("service.name"))
|
|
for batch in data.get("batches", data.get("resourceSpans", []))
|
|
for scope in batch["scopeSpans"]
|
|
for span in scope["spans"]
|
|
]
|
|
|
|
def logs(self, service, trace_id):
|
|
data = self.get(
|
|
"/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
|
|
query=f'{{service_name="{service}"}} | trace_id="{trace_id}"',
|
|
limit=50,
|
|
)
|
|
return data["data"]["result"]
|
|
|
|
|
|
def attributes(entity):
|
|
return {
|
|
item["key"]: next(iter(item["value"].values()))
|
|
for item in entity.get("attributes", [])
|
|
}
|
|
|
|
|
|
def upload(client, actor, chat):
|
|
body = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
|
name = "private-filename-" + uuid.uuid4().hex + ".png"
|
|
response = client.call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/attachments?filename={name}",
|
|
202,
|
|
actor=actor,
|
|
raw=body,
|
|
headers={"Content-Type": "image/png"},
|
|
schema="Attachment",
|
|
)
|
|
check(response["json"]["status"] == "queued", "upload did not return queued")
|
|
trace_id = response["headers"].get("X-Trace-Id", "")
|
|
check(bool(re.fullmatch(r"[0-9a-f]{32}", trace_id)), "missing trace ID")
|
|
return response["json"], trace_id, response["headers"]["X-Request-Id"], name
|
|
|
|
|
|
def chain(obs, trace_id, attempts):
|
|
def lookup():
|
|
spans = obs.trace(trace_id)
|
|
producer = {
|
|
int(attributes(span)["job.attempt"]): span
|
|
for span, service in spans
|
|
if service == "messenger-dispatcher" and span["name"] == "rabbitmq.publish"
|
|
}
|
|
consumer = {
|
|
int(attributes(span)["job.attempt"]): span
|
|
for span, service in spans
|
|
if service == "messenger-worker" and span["name"] == "rabbitmq.consume"
|
|
}
|
|
names = {span["name"] for span, _ in spans}
|
|
if not (
|
|
{f"POST {UPLOAD_ROUTE}", "s3.put", "postgres.complete"} <= names
|
|
and attempts <= producer.keys()
|
|
and attempts <= consumer.keys()
|
|
):
|
|
return None
|
|
for attempt in attempts:
|
|
check(
|
|
consumer[attempt]["parentSpanId"] == producer[attempt]["spanId"],
|
|
"consumer parent mismatch",
|
|
)
|
|
return spans
|
|
|
|
return eventually("trace lacks upload, RabbitMQ, S3 or committed result", lookup)
|
|
|
|
|
|
def verify_signals(client, obs, alice, chat):
|
|
attachment, trace_id, request_id, filename = upload(client, alice, chat)
|
|
ready = client.wait_ready(alice, attachment)
|
|
check(len(ready["variants"]) == 3, "missing image variants")
|
|
spans = chain(obs, trace_id, {1})
|
|
api_logs = eventually(
|
|
"API log missing", lambda: obs.logs("messenger-api", trace_id)
|
|
)
|
|
worker_logs = eventually(
|
|
"worker log missing", lambda: obs.logs("messenger-worker", trace_id)
|
|
)
|
|
credentials = alice["registration"]
|
|
encoded = base64.b64encode(
|
|
f'{credentials["username"]}:{credentials["password"]}'.encode()
|
|
).decode()
|
|
login = client.call("POST", "/api/v1/auth/sessions", 201,
|
|
headers={"Authorization": "Basic " + encoded}, schema="Session")
|
|
private_message = "private-message-" + uuid.uuid4().hex
|
|
message = client.message(alice, chat, private_message)
|
|
sensitive_traces = [login["headers"]["X-Trace-Id"], message["headers"]["X-Trace-Id"]]
|
|
records = [
|
|
eventually("API event отсутствует в Loki", lambda: obs.logs("messenger-api", item))
|
|
for item in sensitive_traces
|
|
]
|
|
extra_spans = [
|
|
eventually("API trace отсутствует в Tempo", lambda: obs.trace(item))
|
|
for item in sensitive_traces
|
|
]
|
|
exported = json.dumps([spans, api_logs, worker_logs, records, extra_spans])
|
|
check(request_id in exported, "request ID absent")
|
|
check(
|
|
alice["token"] not in exported
|
|
and alice["registration"]["password"] not in exported
|
|
and login["json"]["token"] not in exported
|
|
and encoded not in exported
|
|
and private_message not in exported
|
|
and filename not in exported,
|
|
"private data exported",
|
|
)
|
|
metrics = [
|
|
"messenger_http_requests_total",
|
|
"messenger_http_duration_seconds_bucket",
|
|
"messenger_jobs_total",
|
|
"messenger_job_duration_seconds_bucket",
|
|
"messenger_attachment_ready_duration_seconds_bucket",
|
|
"messenger_queue_depth",
|
|
"messenger_queue_oldest_age_seconds",
|
|
"messenger_outbox_pending",
|
|
"messenger_db_pool",
|
|
"messenger_worker_busy",
|
|
"messenger_worker_capacity",
|
|
"messenger_process_cpu_seconds_total",
|
|
"messenger_process_memory_bytes",
|
|
"messenger_container_cpu_seconds_total",
|
|
"messenger_container_memory_bytes",
|
|
"messenger:http_availability:15m",
|
|
]
|
|
eventually(
|
|
"missing Prometheus series",
|
|
lambda: all(obs.query(metric) for metric in metrics),
|
|
)
|
|
disallowed = {
|
|
"request_id",
|
|
"user_id",
|
|
"chat_id",
|
|
"message_id",
|
|
"attachment_id",
|
|
"filename",
|
|
"url",
|
|
}
|
|
check(
|
|
not any(
|
|
disallowed & row["metric"].keys()
|
|
for metric in metrics
|
|
for row in obs.query(metric)
|
|
),
|
|
"unexpected metric labels",
|
|
)
|
|
dashboard = obs.get("/api/dashboards/uid/messenger-lab6")["dashboard"]
|
|
check(
|
|
dashboard["uid"] == "messenger-lab6" and len(dashboard["panels"]) >= 16,
|
|
"dashboard not provisioned",
|
|
)
|
|
print(
|
|
f"SIGNALS trace={trace_id} request_id={request_id} spans={len(spans)} "
|
|
f"metrics={len(metrics)} panels={len(dashboard['panels'])}",
|
|
flush=True,
|
|
)
|
|
return trace_id
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", required=True)
|
|
parser.add_argument("--grafana-url", required=True)
|
|
parser.add_argument("--ca-file", default=str(ROOT / "certs/ca.crt"))
|
|
args = parser.parse_args()
|
|
context = ssl.create_default_context(cafile=args.ca_file)
|
|
try:
|
|
with urlopen(args.grafana_url + "/api/datasources", context=context, timeout=5):
|
|
raise Failure("Grafana API принимает анонимные запросы")
|
|
except HTTPError as error:
|
|
check(error.code == 401, "Grafana отклонила запрос с неожиданным кодом")
|
|
client = Client(args.base_url, args.ca_file)
|
|
obs = Observations(args.grafana_url, args.ca_file)
|
|
alice, _, _, chat = client.bootstrap()
|
|
verify_signals(client, obs, alice, chat)
|
|
print("PASS telemetry: Grafana требует вход; Loki, Tempo и Prometheus доступны без утечек")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|