265 lines
13 KiB
Python
265 lines
13 KiB
Python
#!/usr/bin/env python3
|
||
"""Студенческие тесты lab2 (Bearer-аутентификация). Одна команда:
|
||
python student-tests/run_tests.py --base-url http://localhost:8080
|
||
"""
|
||
import argparse
|
||
import base64
|
||
import json
|
||
import threading
|
||
import urllib.error
|
||
import urllib.request
|
||
import uuid
|
||
|
||
FAILURES = []
|
||
BASE = "http://localhost:8080"
|
||
PASSWORD = "Example-only-not-a-real-secret-123" # 38 code points: в диапазоне 12..128
|
||
|
||
|
||
def check(name, cond, detail=""):
|
||
if not cond:
|
||
FAILURES.append(name)
|
||
print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" -- {detail}" if not cond and detail else ""))
|
||
|
||
|
||
def _lower_headers(headers):
|
||
"""Ключи заголовков в нижнем регистре.
|
||
Go шлёт WWW-Authenticate как "Www-Authenticate" (каноническая MIME-форма),
|
||
а dict(headers) сохраняет регистр как пришёл. Чтобы тест не зависел от
|
||
регистра, всегда ищем заголовки в lower-case."""
|
||
return {k.lower(): v for k, v in headers.items()}
|
||
|
||
|
||
def www_auth(hdr):
|
||
"""Значение WWW-Authenticate независимо от регистра ключа."""
|
||
return hdr.get("www-authenticate", "")
|
||
|
||
|
||
def req(method, path, body=None, raw=None, token=None, basic=None,
|
||
ctype="application/json", extra_headers=None):
|
||
headers, data = {}, None
|
||
if raw is not None:
|
||
data, headers["Content-Type"] = raw.encode("utf-8"), ctype
|
||
elif body is not None:
|
||
data, headers["Content-Type"] = json.dumps(body, ensure_ascii=False).encode("utf-8"), ctype
|
||
if token:
|
||
headers["Authorization"] = "Bearer " + token
|
||
if basic:
|
||
headers["Authorization"] = "Basic " + base64.b64encode(basic.encode("utf-8")).decode("ascii")
|
||
if extra_headers:
|
||
headers.update(extra_headers)
|
||
r = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||
try:
|
||
with urllib.request.urlopen(r, timeout=30) as resp:
|
||
payload = resp.read().decode("utf-8")
|
||
return resp.status, _lower_headers(resp.headers), (json.loads(payload) if payload else None)
|
||
except urllib.error.HTTPError as e:
|
||
payload = e.read().decode("utf-8")
|
||
try:
|
||
return e.code, _lower_headers(e.headers), json.loads(payload)
|
||
except ValueError:
|
||
return e.code, _lower_headers(e.headers), None
|
||
|
||
|
||
def register(username=None, password=PASSWORD, display="Тест Юникод ✓"):
|
||
username = username or "u" + uuid.uuid4().hex[:12]
|
||
return req("POST", "/api/v1/users",
|
||
{"username": username, "display_name": display, "password": password})
|
||
|
||
|
||
def login(username, password=PASSWORD):
|
||
return req("POST", "/api/v1/auth/sessions", basic=f"{username}:{password}")
|
||
|
||
|
||
def main():
|
||
global BASE
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--base-url", default=BASE)
|
||
BASE = ap.parse_args().base_url
|
||
|
||
# ── health и номерки ──
|
||
st, hdr, body = req("GET", "/health/live")
|
||
check("health live 200", st == 200 and body == {"status": "ok"})
|
||
check("X-Request-Id present", bool(hdr.get("x-request-id")))
|
||
st, _, body = req("GET", "/health/ready")
|
||
check("health ready 200", st == 200 and body == {"status": "ok"})
|
||
|
||
# ── валидация регистрации ──
|
||
st, _, _ = req("POST", "/api/v1/users", raw='{"username": "abc",')
|
||
check("malformed JSON -> 400", st == 400)
|
||
st, _, _ = req("POST", "/api/v1/users",
|
||
{"username": "extrafield1", "display_name": "x", "password": PASSWORD, "junk": 1})
|
||
check("extra field -> 400", st == 400)
|
||
st, _, _ = req("POST", "/api/v1/users", {"username": "BadName", "display_name": "x", "password": PASSWORD})
|
||
check("username pattern -> 400", st == 400)
|
||
st, _, _ = req("POST", "/api/v1/users", {"username": "wsname1", "display_name": " ", "password": PASSWORD})
|
||
check("whitespace display_name -> 400", st == 400)
|
||
st, _, _ = req("POST", "/api/v1/users", {"username": "shortpw1", "display_name": "x", "password": "short"})
|
||
check("password < 12 -> 400", st == 400)
|
||
st, _, _ = req("POST", "/api/v1/users", {"username": "longpw1", "display_name": "x", "password": "x" * 129})
|
||
check("password > 128 -> 400", st == 400)
|
||
st, _, _ = req("POST", "/api/v1/users", {"username": "wspw1", "display_name": "x", "password": " "})
|
||
check("whitespace password -> 400", st == 400)
|
||
|
||
st, _, alice = register()
|
||
check("register 201", st == 201)
|
||
check("no password/hash in User response",
|
||
isinstance(alice, dict) and "password" not in alice and "password_hash" not in alice)
|
||
st2, _, _ = register(username=alice["username"])
|
||
check("duplicate username -> 409", st2 == 409)
|
||
|
||
# ── вход: неверные/неизвестные/успех ──
|
||
st, hdr, _ = login(alice["username"], "Wrong-" + PASSWORD)
|
||
check("wrong password -> 401", st == 401)
|
||
check("wrong password WWW-Authenticate Basic", www_auth(hdr).startswith("Basic"),
|
||
f"got {www_auth(hdr)!r}")
|
||
st, hdr, _ = login("nosuchuser" + uuid.uuid4().hex[:6])
|
||
check("unknown user -> 401 same shape",
|
||
st == 401 and www_auth(hdr).startswith("Basic"), f"got {www_auth(hdr)!r}")
|
||
st, _, sess = login(alice["username"])
|
||
check("login 201 session", st == 201 and sess["token_type"] == "Bearer" and len(sess["token"]) >= 32)
|
||
check("session has expires_at and user", "expires_at" in sess and "user" in sess)
|
||
token_a = sess["token"]
|
||
|
||
_, _, bob = register(); _, _, sess_b = login(bob["username"]); token_b = sess_b["token"]
|
||
_, _, carol = register(); _, _, sess_c = login(carol["username"]); token_c = sess_c["token"]
|
||
|
||
# ── правила аутентификации lab2 ──
|
||
st, hdr, _ = req("GET", "/api/v1/users/me")
|
||
check("no auth -> 401 + Bearer header",
|
||
st == 401 and www_auth(hdr).startswith("Bearer"), f"got {www_auth(hdr)!r}")
|
||
st, _, _ = req("GET", "/api/v1/users/me", extra_headers={"X-User-Id": alice["id"]})
|
||
check("X-User-Id ignored -> 401", st == 401)
|
||
st, hdr, _ = req("GET", "/api/v1/users/me", basic=f"{alice['username']}:{PASSWORD}")
|
||
check("Basic on business endpoint -> 401 Bearer",
|
||
st == 401 and www_auth(hdr).startswith("Bearer"), f"got {www_auth(hdr)!r}")
|
||
st, _, _ = req("GET", "/api/v1/users/me", token="not-a-valid-token")
|
||
check("garbage Bearer -> 401", st == 401)
|
||
st, _, me = req("GET", "/api/v1/users/me", token=token_a)
|
||
check("me with Bearer 200", st == 200 and me["id"] == alice["id"])
|
||
|
||
# ── чаты и доступ ──
|
||
st, _, chat = req("POST", "/api/v1/chats",
|
||
{"title": "Проект по ВНП", "member_ids": [alice["id"], bob["id"]]}, token=token_a)
|
||
check("create chat 201", st == 201)
|
||
cid = chat["id"]
|
||
st, _, _ = req("GET", f"/api/v1/chats/{cid}", token=token_c)
|
||
check("outsider GET chat -> 404", st == 404)
|
||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": "hi"}, token=token_c)
|
||
check("outsider POST message -> 404", st == 404)
|
||
st, _, body = req("GET", "/api/v1/chats", token=token_c)
|
||
check("outsider list hides foreign chat", st == 200 and all(c["id"] != cid for c in body["items"]))
|
||
|
||
# ── валидация сообщений ──
|
||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": ""}, token=token_a)
|
||
check("empty text -> 400", st == 400)
|
||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": " \n "}, token=token_a)
|
||
check("whitespace text -> 400", st == 400)
|
||
st, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": "x" * 4001}, token=token_a)
|
||
check("text > 4000 -> 400", st == 400)
|
||
text = "Привет, Боб! 🚀 Ünïcödé ✓"
|
||
st, _, msg = req("POST", f"/api/v1/chats/{cid}/messages", {"text": text}, token=token_a)
|
||
check("unicode round-trip exact", st == 201 and msg["text"] == text)
|
||
|
||
# ── пагинация ──
|
||
for i in range(24):
|
||
req("POST", f"/api/v1/chats/{cid}/messages", {"text": f"msg-{i:02d}"}, token=token_b)
|
||
hist, cursor, pages = [], None, 0
|
||
while True:
|
||
q = f"/api/v1/chats/{cid}/messages?limit=10" + (f"&cursor={cursor}" if cursor else "")
|
||
st, _, page = req("GET", q, token=token_b)
|
||
pages += 1
|
||
hist.extend(page["items"])
|
||
cursor = page["next_cursor"]
|
||
if not cursor:
|
||
break
|
||
ids = [m["id"] for m in hist]
|
||
check("25 msgs -> 3 pages, no repeats", pages == 3 and len(ids) == 25 and len(set(ids)) == 25)
|
||
pairs = [(m["created_at"], m["id"]) for m in hist]
|
||
bad = [i for i in range(len(pairs) - 1) if pairs[i] > pairs[i + 1]]
|
||
check("history ordered by (created_at, id)", not bad, f"{len(bad)} inversions")
|
||
|
||
st, _, chat2 = req("POST", "/api/v1/chats",
|
||
{"title": "other", "member_ids": [alice["id"], bob["id"]]}, token=token_a)
|
||
req("POST", f"/api/v1/chats/{chat2['id']}/messages", {"text": "o1"}, token=token_a)
|
||
req("POST", f"/api/v1/chats/{chat2['id']}/messages", {"text": "o2"}, token=token_a)
|
||
_, _, p2 = req("GET", f"/api/v1/chats/{chat2['id']}/messages?limit=1", token=token_a)
|
||
st, _, _ = req("GET", f"/api/v1/chats/{cid}/messages?limit=10&cursor={p2['next_cursor']}", token=token_a)
|
||
check("cursor from another chat -> 400", st == 400)
|
||
ok = True
|
||
for v in ("0", "101", "abc"):
|
||
st, _, _ = req("GET", f"/api/v1/chats/{cid}/messages?limit={v}", token=token_a)
|
||
ok = ok and st == 400
|
||
check("limit 0/101/abc -> 400", ok)
|
||
|
||
# ── logout и отзыв ──
|
||
_, _, sess_b2 = login(bob["username"])
|
||
token_b2 = sess_b2["token"]
|
||
st, _, _ = req("DELETE", "/api/v1/auth/sessions/current", token=token_b2)
|
||
check("logout -> 204", st == 204)
|
||
st, _, _ = req("GET", "/api/v1/users/me", token=token_b2)
|
||
check("revoked token -> 401", st == 401)
|
||
st, _, _ = req("GET", "/api/v1/users/me", token=token_b)
|
||
check("other session of same user still valid", st == 200)
|
||
|
||
# ── гонка регистрации: UNIQUE-ограничение (имя БЕЗ дефиса: маска username) ──
|
||
race_name = "race" + uuid.uuid4().hex[:10]
|
||
results, lock = [], threading.Lock()
|
||
def racer():
|
||
s, _, _ = register(username=race_name)
|
||
with lock:
|
||
results.append(s)
|
||
ts = [threading.Thread(target=racer) for _ in range(10)]
|
||
for t in ts: t.start()
|
||
for t in ts: t.join()
|
||
check("race registration: one 201, rest 409",
|
||
results.count(201) == 1 and results.count(409) == 9, str(results))
|
||
|
||
# ── rollback составной операции ──
|
||
_, _, before = req("GET", "/api/v1/chats", token=token_a)
|
||
n_before = len(before["items"])
|
||
st, _, _ = req("POST", "/api/v1/chats",
|
||
{"title": "rollback-probe", "member_ids": [alice["id"], str(uuid.uuid4())]}, token=token_a)
|
||
check("chat with unknown member -> 400", st == 400)
|
||
_, _, after = req("GET", "/api/v1/chats", token=token_a)
|
||
check("rollback: no partial chat",
|
||
len(after["items"]) == n_before and all(c["title"] != "rollback-probe" for c in after["items"]))
|
||
|
||
# ── конкурентные записи ──
|
||
errs = []
|
||
def writer(idx):
|
||
for j in range(10):
|
||
s, _, _ = req("POST", f"/api/v1/chats/{cid}/messages", {"text": f"c{idx}-{j}"}, token=token_b)
|
||
if s != 201:
|
||
errs.append((idx, j, s))
|
||
ts = [threading.Thread(target=writer, args=(i,)) for i in range(10)]
|
||
for t in ts: t.start()
|
||
for t in ts: t.join()
|
||
check("100 concurrent sends all 201", not errs, str(errs[:5]))
|
||
items, cur = [], None
|
||
while True:
|
||
q = f"/api/v1/chats/{cid}/messages?limit=100" + (f"&cursor={cur}" if cur else "")
|
||
st, _, page = req("GET", q, token=token_b)
|
||
items.extend(page["items"])
|
||
cur = page["next_cursor"]
|
||
if not cur:
|
||
break
|
||
expected = {f"c{i}-{j}" for i in range(10) for j in range(10)}
|
||
got = {m["text"] for m in items}
|
||
check("exactly 100 unique concurrent messages", expected <= got and len(got & expected) == 100)
|
||
|
||
# ── прочее контрактное ──
|
||
st, _, _ = req("POST", "/api/v1/users",
|
||
raw='{"username":"cttest1","display_name":"x","password":"' + PASSWORD + '"}',
|
||
ctype="text/plain")
|
||
check("wrong Content-Type -> 415", st == 415)
|
||
st, _, body = req("GET", "/nope")
|
||
check("unknown route -> 404 envelope", st == 404 and body and body["error"]["code"] == "not_found")
|
||
|
||
if FAILURES:
|
||
print(f"FAILED {len(FAILURES)}: {FAILURES}")
|
||
raise SystemExit(1)
|
||
print("ALL STUDENT TESTS PASSED")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |