forked from mtusi2026/mtusi2026lab7
57 lines
2.5 KiB
Python
57 lines
2.5 KiB
Python
"""Send a synthetic marker as a credential and check exported signals for it."""
|
|
import base64
|
|
import json
|
|
import secrets
|
|
import ssl
|
|
import subprocess
|
|
import time
|
|
from urllib.error import HTTPError
|
|
from urllib.request import Request, urlopen
|
|
|
|
from check_grade3_signals import TLS, query
|
|
|
|
|
|
def main():
|
|
marker = "lab7-secret-" + secrets.token_hex(16)
|
|
encoded = base64.b64encode(("lab7_probe:" + marker).encode()).decode()
|
|
context = ssl.create_default_context(cafile=str(TLS / "lab7-ingress-ca.crt"))
|
|
started = int(time.time()) - 1
|
|
req = Request("https://localhost:8443/api/v1/auth/sessions", data=b"",
|
|
headers={"Authorization": "Basic " + encoded})
|
|
try:
|
|
with urlopen(req, context=context, timeout=5):
|
|
raise AssertionError("Synthetic invalid login succeeded")
|
|
except HTTPError as error:
|
|
assert error.code == 401
|
|
request_id = error.headers["X-Request-Id"]
|
|
assert request_id
|
|
for _ in range(30):
|
|
now = int(time.time()) + 1
|
|
selector = '{service_name="messenger-api"} | request_id=`' + request_id + '`'
|
|
window = {"start": started * 10**9, "end": now * 10**9, "limit": 10}
|
|
logs = query("loki", 3100, "/loki/api/v1/query_range",
|
|
{**window, "query": selector})
|
|
correlated = query("loki", 3100, "/loki/api/v1/query_range",
|
|
{**window, "query": selector + ' | line_format "{{.trace_id}}"'})
|
|
trace_id = next((entry[1] for stream in correlated["data"]["result"]
|
|
for entry in stream["values"] if len(entry[1]) == 32), None)
|
|
if trace_id:
|
|
trace = query("tempo", 3200, "/api/traces/" + trace_id, {}, allow_missing=True)
|
|
metrics = query("prometheus", 9090, "/api/v1/query", {
|
|
"query": 'messenger_http_requests_total{http_route="/api/v1/auth/sessions",http_status_class="4xx"}',
|
|
})["data"]["result"]
|
|
if trace and metrics:
|
|
break
|
|
time.sleep(2)
|
|
else:
|
|
raise AssertionError("Missing correlated log, trace or ingress metric for synthetic request")
|
|
container_logs = subprocess.check_output(
|
|
["docker", "compose", "logs", "--since", str(started), "api", "otel-collector"], text=True)
|
|
for output in (json.dumps(logs), json.dumps(trace), json.dumps(metrics), container_logs):
|
|
assert marker not in output and encoded not in output
|
|
print("PASS: synthetic Basic secret absent from correlated log, correlated trace, metric labels and container logs")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|