forked from mtusi2026/mtusi2026lab7
139 lines
6.6 KiB
Python
139 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Controlled request -> its trace and logs (defense scenario, steps 2-3; evidence/trace-demo.txt).
|
|
|
|
python scripts/trace_demo.py [--base-url https://localhost:8443] [--output evidence/trace-demo.txt]
|
|
|
|
1. creates a synthetic user and chat, uploads tests/fixtures/sample.png with OUR OWN W3C
|
|
`traceparent` header (trace id chosen here) and X-Request-Id;
|
|
2. waits until the attachment is ready;
|
|
3. reads the trace from Tempo and the log records of that trace from Loki (through Grafana);
|
|
4. checks: the API continued OUR trace (same trace id, the SERVER span's parent = our span id),
|
|
the chain upload -> db enqueue -> relay PRODUCER -> worker CONSUMER -> s3/db spans exists,
|
|
and api + worker log records carry this trace_id. Prints the span tree and the log lines.
|
|
No token, password or image bytes are printed.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import secrets
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "scripts"))
|
|
import obs # noqa: E402
|
|
|
|
|
|
def call(base: str, method: str, path: str, body=None, headers=None, raw: bytes | None = None):
|
|
h = dict(headers or {})
|
|
data = raw
|
|
if body is not None:
|
|
data = json.dumps(body).encode()
|
|
h["Content-Type"] = "application/json"
|
|
request = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
|
with urllib.request.urlopen(request, timeout=30, context=obs.TLS) as response:
|
|
return response.status, response.headers, json.loads(response.read() or b"null")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--base-url", default="https://localhost:8443")
|
|
parser.add_argument("--output")
|
|
args = parser.parse_args()
|
|
base = args.base_url.rstrip("/") + "/api/v1"
|
|
out: list[str] = []
|
|
|
|
def say(line: str = "") -> None:
|
|
print(line)
|
|
out.append(line)
|
|
|
|
username = "trace_" + uuid.uuid4().hex[:10]
|
|
password = "Trace-demo-" + secrets.token_hex(8)
|
|
_, _, user = call(base, "POST", "/users", {"username": username, "display_name": "Trace demo", "password": password})
|
|
auth = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
_, _, session = call(base, "POST", "/auth/sessions", headers={"Authorization": auth})
|
|
bearer = {"Authorization": "Bearer " + session["token"]}
|
|
_, _, chat = call(base, "POST", "/chats", {"title": "trace demo", "member_ids": [user["id"]]}, bearer)
|
|
|
|
trace_id, parent_span = secrets.token_hex(16), secrets.token_hex(8)
|
|
request_id = "trace-demo-" + uuid.uuid4().hex[:8]
|
|
image = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
|
status, headers, att = call(base, "POST", f"/chats/{chat['id']}/attachments?filename=sample.png", raw=image,
|
|
headers={**bearer, "Content-Type": "image/png", "X-Request-Id": request_id,
|
|
"traceparent": f"00-{trace_id}-{parent_span}-01"})
|
|
say(f"upload: HTTP {status}, status={att['status']}, X-Request-Id={headers.get('X-Request-Id')}, "
|
|
f"X-Instance-Id={headers.get('X-Instance-Id')}, X-Trace-Id={headers.get('X-Trace-Id')}")
|
|
say(f"sent traceparent: 00-{trace_id}-{parent_span}-01")
|
|
assert headers.get("X-Trace-Id") == trace_id, "the API must continue the caller's trace"
|
|
deadline = time.monotonic() + 60
|
|
while att["status"] not in ("ready", "failed"):
|
|
assert time.monotonic() < deadline, "not ready within 60 s"
|
|
time.sleep(0.5)
|
|
_, _, att = call(base, "GET", f"/attachments/{att['id']}", headers=bearer)
|
|
say(f"attachment {att['id']}: {att['status']}, variants={[v['name'] for v in att['variants']]}")
|
|
|
|
def complete(spans):
|
|
kinds = {(s["service"], s["kind"]) for s in spans}
|
|
return (("messenger-api", "SERVER") in kinds and ("messenger-relay", "PRODUCER") in kinds
|
|
and ("messenger-worker", "CONSUMER") in kinds
|
|
and any(s["name"] == "db jobs.complete" for s in spans))
|
|
spans = obs.wait_trace(trace_id, complete, timeout=90)
|
|
say(f"\nTempo: trace {trace_id}, {len(spans)} spans")
|
|
say(obs.tree(spans))
|
|
|
|
server = next(s for s in spans if s["service"] == "messenger-api" and s["kind"] == "SERVER")
|
|
producer = next(s for s in spans if s["kind"] == "PRODUCER")
|
|
consumer = next(s for s in spans if s["kind"] == "CONSUMER")
|
|
ids = {s["span_id"]: s for s in spans}
|
|
checks = {
|
|
"API SERVER span continues our traceparent (parent = our span id)": server["parent_id"] == parent_span,
|
|
"relay PRODUCER is inside the upload trace (ancestor = API SERVER span)": _ancestor(producer, server, ids),
|
|
"worker CONSUMER is a child of the PRODUCER": consumer["parent_id"] == producer["span_id"],
|
|
"worker wrote to S3 inside the job (s3 put spans)": any(
|
|
s["name"] == "s3 put" and _ancestor(s, consumer, ids) for s in spans),
|
|
"worker committed the result (db jobs.complete span)": any(
|
|
s["name"] == "db jobs.complete" and _ancestor(s, consumer, ids) for s in spans),
|
|
}
|
|
|
|
time.sleep(3)
|
|
records = obs.trace_logs(trace_id)
|
|
say(f"\nLoki: {len(records)} log records with trace_id={trace_id}")
|
|
for r in records:
|
|
m = r["metadata"]
|
|
say(f" {r['service']:<17} {r['line']:<18} span_id={m.get('span_id', '')} " + " ".join(
|
|
f"{k}={m[k]}" for k in ("request_id", "route", "status", "job_id", "outcome") if k in m))
|
|
services = {r["service"] for r in records}
|
|
checks["API log record of the request has this trace_id and our X-Request-Id"] = any(
|
|
r["service"] == "messenger-api" and r["metadata"].get("request_id") == request_id for r in records)
|
|
checks["worker log record (job_done) has this trace_id"] = any(
|
|
r["service"] == "messenger-worker" and r["line"] == "job_done" for r in records)
|
|
say("\nChecks:")
|
|
for name, ok in checks.items():
|
|
say(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
|
say(f"services in logs: {sorted(services)}")
|
|
if args.output:
|
|
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
|
Path(args.output).write_text("\n".join(out) + "\n", encoding="utf-8", newline="\n")
|
|
return 0 if all(checks.values()) else 1
|
|
|
|
|
|
def _ancestor(span: dict, ancestor: dict, ids: dict) -> bool:
|
|
seen = 0
|
|
while span["parent_id"] and seen < 100:
|
|
if span["parent_id"] == ancestor["span_id"]:
|
|
return True
|
|
span = ids.get(span["parent_id"])
|
|
if span is None:
|
|
return False
|
|
seen += 1
|
|
return False
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|