Files
mtusi2026lab7/security-tests/acl_leak.py
T
ALMiron 912a874f00
Skeleton contracts / contracts (pull_request) Blocked by required conditions
lab 7 openbao
2026-11-23 14:39:13 +03:00

100 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Lab 7 negative application tests through the public HTTPS endpoint (stdlib + tests/client.py helper).
Covers: outsider cannot read chat metadata/content or attach a foreign file; forged X-User-Id does not change the Bearer identity;
logout revokes the token; login rate limit (429 + Retry-After) shared by replicas; oversized JSON -> 413; canary password/token
never appear in container logs or in Loki (queried through the Grafana datasource proxy).
Usage: python3 security-tests/acl_leak.py --ca-file secrets/pki/ca/ca.crt [--grafana-password-file secrets/ops/grafana_admin_password]
"""
import argparse
import base64
import json
import os
import ssl
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "tests"))
from client import Client # noqa: E402
FAILS = []
PNG = open(os.path.join(os.path.dirname(__file__), "..", "tests", "fixtures", "sample.png"), "rb").read()
def ok(name, cond, detail=""):
print(("PASS " if cond else "FAIL ") + name + (f" ({detail})" if detail else ""))
if not cond:
FAILS.append(name)
def raw(base, ca, method, path, headers=None, body=None):
req = urllib.request.Request(base + path, data=body, headers=headers or {}, method=method)
try:
with urllib.request.urlopen(req, context=ssl.create_default_context(cafile=ca), timeout=15) as r:
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read() # header names are case-insensitive (uvicorn sends them lower-case)
except urllib.error.HTTPError as e:
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
def basic(u, p):
return {"Authorization": "Basic " + base64.b64encode(f"{u}:{p}".encode()).decode()}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="https://localhost:8443"); ap.add_argument("--ca-file", required=True)
ap.add_argument("--grafana-password-file")
a = ap.parse_args()
c = Client(a.base_url, a.ca_file)
alice, bob, eve, chat = c.bootstrap()
path = "/api/v1/chats/" + chat["id"]
# 1. outsider (eve) and identity forgery
s, _, _ = raw(a.base_url, a.ca_file, "GET", path, {"Authorization": "Bearer " + eve["token"]}); ok("outsider cannot read chat metadata", s == 404, s)
s, _, _ = raw(a.base_url, a.ca_file, "GET", path + "/messages", {"Authorization": "Bearer " + eve["token"]}); ok("outsider cannot read messages", s == 404, s)
s, _, _ = raw(a.base_url, a.ca_file, "POST", path + "/attachments?filename=x.png", {"Authorization": "Bearer " + eve["token"], "Content-Type": "image/png"}, PNG)
ok("outsider cannot attach a file to a foreign chat", s == 404, s)
s, _, _ = raw(a.base_url, a.ca_file, "GET", path, {"Authorization": "Bearer " + eve["token"], "X-User-Id": alice["id"]}); ok("forged X-User-Id does not change the Bearer identity", s == 404, s)
s, _, _ = raw(a.base_url, a.ca_file, "GET", "/api/v1/users/me", {"X-User-Id": alice["id"]}); ok("X-User-Id alone gives no access", s == 401, s)
# 2. logout revokes
s, _, _ = raw(a.base_url, a.ca_file, "DELETE", "/api/v1/auth/sessions/current", {"Authorization": "Bearer " + eve["token"]}); ok("logout returns 204", s == 204, s)
s, _, _ = raw(a.base_url, a.ca_file, "GET", "/api/v1/users/me", {"Authorization": "Bearer " + eve["token"]}); ok("token is dead after logout", s == 401, s)
# 3. oversized JSON
big = json.dumps({"text": "x" * 70000}).encode()
s, _, b = raw(a.base_url, a.ca_file, "POST", path + "/messages", {"Authorization": "Bearer " + alice["token"], "Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex}, big)
ok("JSON body over 64 KiB -> 413", s == 413, s)
# 4. canary credentials must never reach logs/telemetry
canary_user, canary_pw = "canary" + uuid.uuid4().hex[:8], "CANARY-pw-" + uuid.uuid4().hex
reg = json.dumps({"username": canary_user, "display_name": "Canary", "password": canary_pw}).encode()
s, _, _ = raw(a.base_url, a.ca_file, "POST", "/api/v1/users", {"Content-Type": "application/json"}, reg); ok("canary user registered", s == 201, s)
s, _, b = raw(a.base_url, a.ca_file, "POST", "/api/v1/auth/sessions", basic(canary_user, canary_pw)); ok("canary login", s == 201, s)
canary_token = json.loads(b)["token"]
s, _, _ = raw(a.base_url, a.ca_file, "POST", "/api/v1/auth/sessions", basic(canary_user, canary_pw + "x"))
logs = subprocess.run(["docker", "compose", "logs", "--no-color", "--since", "10m"], capture_output=True, text=True).stdout
ok("password and token absent from container logs", canary_pw not in logs and canary_token not in logs)
if a.grafana_password_file:
pw = open(a.grafana_password_file).read().strip()
q = urllib.parse.quote('{service_name=~".+"} |~ "CANARY-pw|' + canary_token[:12] + '"')
url = "https://localhost:3000/api/datasources/proxy/uid/loki/loki/api/v1/query_range?limit=5&since=15m&query=" + q
req = urllib.request.Request(url, headers={"Authorization": "Basic " + base64.b64encode(f"admin:{pw}".encode()).decode()})
data = json.load(urllib.request.urlopen(req, context=ssl.create_default_context(cafile=a.ca_file), timeout=15))
ok("password and token absent from Loki", data["data"]["result"] == [], len(data["data"]["result"]))
# 5. login rate limit: shared counter, 429 + Retry-After (run last: it locks the throw-away username for one window)
victim = "rl" + uuid.uuid4().hex[:10]
statuses, retry = [], None
for _ in range(14):
s, h, _ = raw(a.base_url, a.ca_file, "POST", "/api/v1/auth/sessions", basic(victim, "wrong-password-123"))
statuses.append(s)
if s == 429:
retry = h.get("retry-after")
ok("login: 429 after repeated failures, Retry-After present", 429 in statuses and retry is not None and int(retry) >= 1, f"{statuses} retry={retry}")
print("\n" + ("ALL PASS" if not FAILS else "FAILED: " + "; ".join(FAILS)))
sys.exit(1 if FAILS else 0)
if __name__ == "__main__":
main()