Files
2026-11-29 21:59:16 +03:00

141 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Public authorization, rate limit, expiry and telemetry checks using HTTPS."""
import argparse
import base64
import json
from http.client import HTTPSConnection
from pathlib import Path
import secrets
import ssl
import sys
import time
import urllib.parse
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check, timestamp
def basic(username, password):
return "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
def authorization(client, cafile):
alice, bob, eve, chat = client.bootstrap()
attachment, _ = client.attachment(alice, chat)
client.wait_ready(alice, attachment)
other = client.call("POST", "/api/v1/chats", 201, actor=eve,
body={"title": "ACL isolation", "member_ids": [eve["id"], bob["id"]]},
schema="Chat")["json"]
path = "/api/v1/chats/" + other["id"] + "/messages"
client.call("POST", path, 404, body={"text": "", "attachment_ids": [attachment["id"]]},
actor=eve, headers={"Idempotency-Key": secrets.token_hex(8)})
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 404, actor=eve,
headers={"X-User-Id": alice["id"]})
upload = "/api/v1/chats/" + chat["id"] + "/attachments?filename=test.png"
parsed = urllib.parse.urlsplit(client.base)
connection = HTTPSConnection(parsed.hostname, parsed.port, context=ssl.create_default_context(cafile=cafile),
timeout=4)
connection.putrequest("POST", upload)
connection.putheader("Authorization", "Bearer " + alice["token"])
connection.putheader("Content-Type", "image/png")
connection.putheader("Content-Length", str(10 * 1024 * 1024 + 1))
connection.putheader("Expect", "100-continue")
connection.endheaders()
with connection.getresponse() as response:
check(response.status == 413, "ingress accepted oversized body")
details = json.loads(response.read())["error"]
check(details["request_id"] == response.getheader("X-Request-Id"), "ingress mismatch request ID")
connection.close()
print("PASS cross-chat attachment, spoofed identity and oversized upload denied")
def rate_limit(client):
username = "canary_" + secrets.token_hex(8)
auth = {"Authorization": basic(username, "synthetic-wrong-password")}
instances = set()
latencies = []
for index in range(10):
result = client.call("POST", "/api/v1/auth/sessions", 401 if index < 8 else 429, headers=auth)
instances.add(result["headers"]["X-Instance-Id"])
if index < 8:
latencies.append(round(result["elapsed"] * 1000, 1))
else:
check(0 < int(result["headers"]["Retry-After"]) <= 30, "Retry-After outside window")
check(len(instances) >= 2, "test must traverse two API replicas")
print(json.dumps({"limit_scope": "shared between replicas", "replicas": len(instances),
"account_window": 30, "kdf_http_ms": latencies, "allowed": 8, "http_429": 2}))
def expiry(client):
actor = client.user("expiry")
reg = actor["registration"]
result = client.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
headers={"Authorization": basic(reg["username"], reg["password"])})["json"]
delay = timestamp(result["expires_at"]).timestamp() - time.time()
check(0 < delay <= 15, "launch API with SESSION_TTL_SECONDS=8 for this check")
actor["token"] = result["token"]
client.call("GET", "/api/v1/users/me", actor=actor)
time.sleep(delay + 0.3)
client.call("GET", "/api/v1/users/me", 401, actor=actor)
print("PASS session expiry enforced with a previously valid token")
def telemetry(client, cafile):
actor = client.user("telemetry")
password, username = actor["registration"]["password"], actor["registration"]["username"]
basic_header = basic(username, password)
login = client.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": basic_header},
schema="Session")
trace_id = login["headers"]["X-Trace-Id"]
request_id = login["headers"]["X-Request-Id"]
actor["token"] = login["json"]["token"]
me = client.call("GET", "/api/v1/users/me", actor=actor)
markers = tuple(item.encode() for item in (password, username, basic_header, actor["token"]))
ca = ssl.create_default_context(cafile=cafile)
admin_password = (ROOT / ".runtime/bootstrap/grafana/GRAFANA_PASSWORD").read_text()
def via_grafana(source, path):
target = f"https://localhost:13000/api/datasources/proxy/uid/{source}{path}"
request = urllib.request.Request(target, headers={"Authorization": basic("admin", admin_password)})
with urllib.request.urlopen(request, timeout=4, context=ca) as response:
return response.read()
deadline = time.monotonic() + 45
while True:
try:
traces = [via_grafana("tempo", "/api/traces/" + tid)
for tid in (trace_id, me["headers"]["X-Trace-Id"])]
query = urllib.parse.urlencode({"query": '{service_name="messenger-api"} |= "' + request_id + '"',
"start": time.time_ns() - 120_000_000_000})
logs = via_grafana("loki", "/loki/api/v1/query_range?" + query)
if request_id.encode() in logs:
break
except OSError:
pass
check(time.monotonic() < deadline, "trace or correlated logs missing from Grafana query")
time.sleep(1)
query = urllib.parse.urlencode({"query": 'messenger_http_requests_total{route="/api/v1/auth/sessions"}'})
metrics = via_grafana("prometheus", "/api/v1/query?" + query)
check(bool(json.loads(metrics)["data"]["result"]), "login metric missing")
check(all(value not in doc for value in markers for doc in [*traces, logs, metrics]),
"secret canary found in telemetry")
print("PASS correlated login logs, traces and metrics present; no credential canaries")
if __name__ == "__main__":
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("check", choices=("authorization", "rate", "expiry", "telemetry"))
p.add_argument("--base-url", default="https://localhost:8443")
p.add_argument("--ca-file", default=str(ROOT / ".runtime/trust/ca.crt"))
options = p.parse_args()
client = Client(options.base_url, options.ca_file)
if options.check == "telemetry":
telemetry(client, options.ca_file)
elif options.check == "authorization":
authorization(client, options.ca_file)
else:
{"rate": rate_limit, "expiry": expiry}[options.check](client)