forked from mtusi2026/mtusi2026lab6
140 lines
6.3 KiB
Python
140 lines
6.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Verify Level 3+4 observability signals, redaction, and end-to-end API->Worker trace correlation."""
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
sys.path.insert(0, str(ROOT / 'student-tests'))
|
|
|
|
from client import Client, check
|
|
from grafana_helper import GrafanaClient
|
|
|
|
def extract_spans(trace_json):
|
|
spans = []
|
|
for batch in trace_json.get('batches', []):
|
|
svc = 'unknown'
|
|
for attr in batch.get('resource', {}).get('attributes', []):
|
|
if attr.get('key') == 'service.name':
|
|
svc = attr.get('value', {}).get('stringValue', 'unknown')
|
|
for ss in batch.get('scopeSpans', []):
|
|
for sp in ss.get('spans', []):
|
|
attrs = {a['key']: a.get('value', {}) for a in sp.get('attributes', [])}
|
|
spans.append({
|
|
'service': svc,
|
|
'name': sp.get('name'),
|
|
'span_id': sp.get('spanId'),
|
|
'parent_span_id': sp.get('parentSpanId'),
|
|
'attrs': attrs,
|
|
})
|
|
return spans
|
|
|
|
def main():
|
|
g = GrafanaClient('http://localhost:3000')
|
|
g.wait_ready(timeout=90)
|
|
c = Client('http://localhost:8081')
|
|
|
|
t_start = time.time()
|
|
alice, bob, _, chat = c.bootstrap()
|
|
secret_marker = 'SECRET_MSG_BODY_MUST_NOT_LEAK_' + uuid.uuid4().hex[:8]
|
|
c.message(alice, chat, secret_marker)
|
|
att, _ = c.attachment(alice, chat)
|
|
ready = c.wait_ready(bob, att, wait_seconds=60)
|
|
check(ready['status'] == 'ready', 'attachment did not finish')
|
|
|
|
# Wait for BatchSpanProcessor + PeriodicMetricReader + Prometheus scrape
|
|
time.sleep(12)
|
|
|
|
# 1. Verify dashboard provisioned in Grafana
|
|
dash = g.get_json('/api/dashboards/uid/mtusi-lab6-obs')
|
|
check(dash['dashboard']['uid'] == 'mtusi-lab6-obs', 'dashboard not provisioned')
|
|
|
|
# 2. Verify required metrics exist and have NO forbidden high-cardinality labels
|
|
forbidden = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'filename', 'text'}
|
|
required_metrics = [
|
|
'http_server_requests_total',
|
|
'http_server_request_duration_seconds_bucket',
|
|
'worker_jobs_total',
|
|
'worker_job_duration_seconds_bucket',
|
|
'attachment_time_to_ready_seconds_bucket',
|
|
'worker_queue_depth',
|
|
'worker_oldest_job_age_seconds',
|
|
'db_pool_connections',
|
|
'worker_threads',
|
|
'process_memory_rss_bytes',
|
|
]
|
|
metric_counts = {}
|
|
for m in required_metrics:
|
|
res = g.prom_query(m)
|
|
series = res.get('data', {}).get('result', [])
|
|
if not series:
|
|
all_names = g.get_json('/api/datasources/proxy/uid/prometheus/api/v1/label/__name__/values').get('data', [])
|
|
print('Available app metrics:', [x for x in all_names if any(x.startswith(p) for p in ('http_', 'worker_', 'attachment_', 'db_', 'process_', 'otelcol_'))])
|
|
check(len(series) > 0, f'missing Prometheus metric: {m}')
|
|
for s in series:
|
|
bad = forbidden.intersection(s.get('metric', {}).keys())
|
|
check(not bad, f'forbidden high-cardinality labels on {m}: {bad}')
|
|
metric_counts[m] = len(series)
|
|
|
|
# 3. Verify end-to-end trace across messenger-api and messenger-worker in Tempo
|
|
traces = []
|
|
for _ in range(15):
|
|
search = g.tempo_search('{ resource.service.name = "messenger-worker" && name = "worker.process" }', t_start - 5, time.time() + 5, limit=20)
|
|
traces = search.get('traces', [])
|
|
if traces:
|
|
break
|
|
time.sleep(1.5)
|
|
check(len(traces) > 0, 'no worker.process trace found in Tempo')
|
|
|
|
matched_trace_id = None
|
|
matched_spans = []
|
|
for item in traces:
|
|
tid = item['traceID']
|
|
tr = g.tempo_trace(tid)
|
|
spans = extract_spans(tr)
|
|
services = {s['service'] for s in spans}
|
|
names = {s['name'] for s in spans}
|
|
if 'messenger-api' in services and 'messenger-worker' in services and 'outbox.publish' in names and 'worker.process' in names:
|
|
matched_trace_id = tid
|
|
matched_spans = spans
|
|
break
|
|
check(matched_trace_id is not None, 'no unified W3C trace linking messenger-api -> outbox.publish -> worker.process found')
|
|
|
|
# 4. Verify correlated structured logs in Loki and zero secret/body leaks
|
|
ns_start = int((t_start - 5) * 1e9)
|
|
ns_end = int((time.time() + 5) * 1e9)
|
|
api_logs = g.loki_query_range('{service_name="messenger-api"}', ns_start, ns_end, limit=200)
|
|
worker_logs = g.loki_query_range('{service_name="messenger-worker"}', ns_start, ns_end, limit=200)
|
|
api_streams = api_logs.get('data', {}).get('result', [])
|
|
worker_streams = worker_logs.get('data', {}).get('result', [])
|
|
check(len(api_streams) > 0 and len(worker_streams) > 0, 'missing structured logs in Loki')
|
|
|
|
all_log_text = json.dumps(api_streams + worker_streams, ensure_ascii=False)
|
|
check(secret_marker not in all_log_text, 'LEAK: message text appeared in Loki logs')
|
|
check(alice['token'] not in all_log_text, 'LEAK: session token appeared in Loki logs')
|
|
check(alice['registration']['password'] not in all_log_text, 'LEAK: password appeared in Loki logs')
|
|
|
|
correlated = [s for s in (api_streams + worker_streams) if s.get('stream', {}).get('trace_id') == matched_trace_id or any(matched_trace_id in v[1] for v in s.get('values', []))]
|
|
check(len(correlated) > 0, f'no Loki logs correlated to trace_id={matched_trace_id}')
|
|
|
|
summary = {
|
|
'status': 'PASS',
|
|
'verified_metrics': metric_counts,
|
|
'e2e_trace_id': matched_trace_id,
|
|
'e2e_span_services': sorted({s['service'] for s in matched_spans}),
|
|
'e2e_span_names': sorted({s['name'] for s in matched_spans}),
|
|
'loki_api_streams': len(api_streams),
|
|
'loki_worker_streams': len(worker_streams),
|
|
'loki_correlated_entries': len(correlated),
|
|
'redaction_checks': {'message_body_leaked': False, 'token_leaked': False, 'password_leaked': False},
|
|
}
|
|
dest = ROOT / 'evidence/lab6-signals.json'
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
dest.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
|
|
print(json.dumps(summary, indent=2, ensure_ascii=False))
|
|
|
|
if __name__ == '__main__':
|
|
main() |