Files
mtusi2026lab7/student-tests/test_auth_acl.py
T
alenchha 861e7722b5
Skeleton contracts / contracts (pull_request) Canceled after 0s
Application stand (lab7) / stand (pull_request) Canceled after 0s
ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
2026-11-16 10:49:13 +03:00

136 lines
7.8 KiB
Python

#!/usr/bin/env python3
"""Level 3-4 negative tests of the application layer over HTTPS (CA verified, no --insecure):
1. outsider (eve) cannot read chat / history / attachment metadata / content, cannot post, cannot attach
another chat's attachment; forged X-User-Id never changes the Bearer identity; Basic on business endpoints = 401
2. logout revokes the token on every replica; an expired session is rejected on every replica
3. login rate limit shared by the replicas: 5 failures per username -> 429 + Retry-After (even with the right
password), counted across api-1 and api-2; per-IP limit -> 429
4. request size limits: JSON > 64 KiB -> 413, upload > 10 MiB -> 413
5. Argon2id: stored hash has salt + parameters; an old-parameter hash is upgraded on the next successful login
python3 student-tests/test_auth_acl.py (stand running; ~2 min because of the expiry and rate-limit windows)
"""
import base64
import hashlib
import json
import time
import uuid
from stand import SAMPLE, Client, check, compose, log, run, sql, upload, wait_status
RESULTS = []
def ok(name, detail=""):
RESULTS.append(name)
log("PASS %s %s" % (name, detail))
def instances(responses):
return sorted({r["headers"].get("X-Instance-Id") for r in responses})
def basic(username, password):
return {"Authorization": "Basic " + base64.b64encode(("%s:%s" % (username, password)).encode()).decode()}
def main():
c = Client()
alice, bob, eve, chat = c.bootstrap()
att = upload(c, alice, chat)
wait_status(c, alice, att["id"], ("ready",), 90)
cid, aid = chat["id"], att["id"]
# ------------------------------------------------------------------ 1. ACL
for method, path, body in (("GET", "/api/v1/chats/%s" % cid, None), ("GET", "/api/v1/chats/%s/messages" % cid, None),
("GET", "/api/v1/attachments/%s" % aid, None),
("GET", "/api/v1/attachments/%s/content" % aid, None),
("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % aid, None)):
r = c.call(method, path, 404, actor=eve)
check(r["json"]["error"]["code"] == "not_found", "outsider must get a generic 404")
c.call("POST", "/api/v1/chats/%s/messages" % cid, 404, actor=eve, body={"text": "чужой"},
headers={"Idempotency-Key": uuid.uuid4().hex})
own = c.call("POST", "/api/v1/chats", 201, actor=eve, body={"title": "eve", "member_ids": [eve["id"]]},
schema="Chat")["json"]
c.call("POST", "/api/v1/chats/%s/messages" % own["id"], 404, actor=eve, body={"text": "", "attachment_ids": [aid]},
headers={"Idempotency-Key": uuid.uuid4().hex})
listed = c.call("GET", "/api/v1/chats", actor=eve, schema="ChatPage")["json"]["items"]
check(cid not in [x["id"] for x in listed], "foreign chat must not be listed")
ok("acl_outsider", "eve: 404 on chat/history/metadata/content/variant/post, cannot attach a foreign file")
me = c.call("GET", "/api/v1/users/me", actor=eve, headers={"X-User-Id": alice["id"]}, schema="User")["json"]
check(me["id"] == eve["id"], "X-User-Id must not change the Bearer identity")
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
c.call("GET", "/api/v1/chats/%s/messages" % cid, 401, headers=basic(alice["user"]["username"],
alice["registration"]["password"]))
ok("identity_spoofing", "forged X-User-Id ignored; without Bearer 401; Basic on business endpoint 401")
# ------------------------------------------------------------------ 2. logout and expiry on every replica
s = c.user("logout")
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=s)
seen = [c.call("GET", "/api/v1/users/me", 401, actor=s) for _ in range(6)]
check(len(instances(seen)) == 2, "revocation must be checked on both replicas, saw %s" % instances(seen))
ok("logout", "revoked token: 401 on %s" % instances(seen))
x = c.user("expiry")
c.call("GET", "/api/v1/users/me", actor=x, schema="User")
digest = hashlib.sha256(x["token"].encode()).hexdigest()
sql("UPDATE sessions SET expires_at = now() - interval '1 second' WHERE token_hash = '\\x%s'" % digest)
log("session expires_at moved to the past in PostgreSQL; the Valkey cache entry lives at most 30 s")
time.sleep(32)
seen = [c.call("GET", "/api/v1/users/me", 401, actor=x) for _ in range(6)]
ok("expiry", "expired session: 401 on %s after the 30 s cache bound" % instances(seen))
# ------------------------------------------------------------------ 5. Argon2id parameters and rehash
r = c.user("argon")
row = sql("SELECT password_hash FROM users WHERE id = '%s'" % r["id"])[0][0]
check(row.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and row.count("$") == 5, "PHC string with params + salt")
weak = compose("exec", "-T", "api-1", "python", "-c",
"from argon2 import PasswordHasher;import sys;"
"print(PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(sys.argv[1]))",
r["registration"]["password"]).strip()
sql("UPDATE users SET password_hash = '%s' WHERE id = '%s'" % (weak, r["id"]))
username, password = r["user"]["username"], r["registration"]["password"]
c.call("POST", "/api/v1/auth/sessions", 201, headers=basic(username, password), schema="Session")
upgraded = sql("SELECT password_hash FROM users WHERE id = '%s'" % r["id"])[0][0]
check(upgraded.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and upgraded != weak, "hash must be upgraded")
ok("rehash", "stored %s -> %s after a successful login" % (weak.split("$")[3], upgraded.split("$")[3]))
# ------------------------------------------------------------------ 4. size limits
big = {"text": "x" * 70000}
r413 = c.call("POST", "/api/v1/chats/%s/messages" % cid, 413, actor=alice, body=big,
headers={"Idempotency-Key": uuid.uuid4().hex})
c.call("POST", "/api/v1/chats/%s/attachments?filename=big.png" % cid, 413, actor=alice,
raw=SAMPLE + b"\0" * (10 * 1024 * 1024), headers={"Content-Type": "image/png"})
ok("size_limits", "JSON 70 kB -> 413 (%s), upload > 10 MiB -> 413" % r413["json"]["error"]["code"])
# ------------------------------------------------------------------ 3. shared login rate limit
victim = c.user("brute")
name = victim["user"]["username"]
fails = [c.call("POST", "/api/v1/auth/sessions", 401, headers=basic(name, "wrong-password-123")) for _ in range(5)]
limited = c.call("POST", "/api/v1/auth/sessions", 429, headers=basic(name, victim["registration"]["password"]))
retry = int(limited["headers"]["Retry-After"])
check(limited["json"]["error"]["code"] == "rate_limited" and 1 <= retry <= 60, "429 rate_limited + Retry-After")
check(len(instances(fails + [limited])) == 2, "the 6 attempts must hit both replicas")
body = json.dumps(limited["json"], ensure_ascii=False)
check(victim["registration"]["password"] not in body and "argon" not in body.lower(), "no credential detail")
ok("rate_limit_user", "5 failures on %s -> 429 Retry-After=%ds even with the right password" % (
instances(fails + [limited]), retry))
statuses = []
for i in range(130):
statuses.append(c.call("POST", "/api/v1/auth/sessions", [401, 429],
headers=basic("nouser_%d" % i, "wrong-password-123"))["status"])
if statuses[-1] == 429:
break
check(statuses[-1] == 429, "per-IP limit must trigger within 130 attempts")
ok("rate_limit_ip", "per-IP limit: 429 after %d attempts from one address" % len(statuses))
log("waiting for the rate-limit window to expire so that later tests are not affected")
time.sleep(61)
print("PASS: %s" % ", ".join(RESULTS))
if __name__ == "__main__":
run(main)