forked from mtusi2026/mtusi2026lab3
324 lines
18 KiB
Python
324 lines
18 KiB
Python
#!/usr/bin/env python3
|
||
"""Собственные проверки lab2+lab3 (дополняют публичный smoke, ничего не ослабляют).
|
||
|
||
python student-tests/lab2_checks.py --base-url http://localhost:8080 # основные
|
||
python student-tests/lab2_checks.py --base-url http://localhost:8080 --mode idem # идемпотентность и реплики (lab3)
|
||
python student-tests/lab2_checks.py --base-url http://localhost:8080 --mode ttl # при SESSION_TTL_SECONDS=2
|
||
|
||
Только стандартная библиотека. Токены и пароли не печатаются.
|
||
"""
|
||
import argparse, base64, http.client, json, sys, threading, time, urllib.error, urllib.parse, urllib.request, uuid
|
||
|
||
PW = "correct-horse-battery"
|
||
fails = []
|
||
|
||
|
||
def call(base, method, path, body=None, headers=None, raw=None):
|
||
h = dict(headers or {})
|
||
data = raw
|
||
if body is not None:
|
||
data = json.dumps(body).encode()
|
||
h.setdefault("Content-Type", "application/json")
|
||
req = urllib.request.Request(base + path, data=data, headers=h, method=method)
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=15) as r:
|
||
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read()
|
||
except urllib.error.HTTPError as e:
|
||
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
|
||
|
||
|
||
def post_big(base, path, size):
|
||
"""POST тела size байт; сервер может ответить 413 и закрыть соединение раньше, чем тело отправлено."""
|
||
u = urllib.parse.urlsplit(base)
|
||
conn = http.client.HTTPConnection(u.hostname, u.port, timeout=15)
|
||
conn.putrequest("POST", u.path + path)
|
||
conn.putheader("Content-Type", "application/json")
|
||
conn.putheader("Content-Length", str(size))
|
||
conn.endheaders()
|
||
try:
|
||
conn.send(b"{" + b" " * (size - 2) + b"}")
|
||
except OSError:
|
||
pass # сервер уже ответил и закрыл соединение
|
||
try:
|
||
return conn.getresponse().status
|
||
except (OSError, http.client.HTTPException) as e:
|
||
return "нет ответа: %s" % type(e).__name__
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def js(b):
|
||
try:
|
||
return json.loads(b)
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def check(name, ok, detail=""):
|
||
print(("PASS" if ok else "FAIL") + ": " + name + ("" if ok else " -> " + detail))
|
||
if not ok:
|
||
fails.append(name)
|
||
|
||
|
||
def basic(u, p):
|
||
return {"Authorization": "Basic " + base64.b64encode(f"{u}:{p}".encode()).decode()}
|
||
|
||
|
||
def bearer(t):
|
||
return {"Authorization": "Bearer " + t}
|
||
|
||
|
||
def H(t, key=None):
|
||
"""Заголовки отправки сообщения (lab3): Bearer + Idempotency-Key (по умолчанию новый)."""
|
||
return {**bearer(t), "Idempotency-Key": key or uuid.uuid4().hex}
|
||
|
||
|
||
class Api:
|
||
def __init__(self, base):
|
||
self.base = base + "/api/v1"
|
||
|
||
def __call__(self, *a, **k):
|
||
return call(self.base, *a, **k)
|
||
|
||
def user(self, prefix="u"):
|
||
name = f"{prefix}_{uuid.uuid4().hex[:10]}"
|
||
s, _, b = self("POST", "/users", {"username": name, "display_name": name, "password": PW})
|
||
assert s == 201, f"create user: {s}"
|
||
u = js(b)
|
||
s, _, b = self("POST", "/auth/sessions", headers=basic(name, PW))
|
||
assert s == 201, f"login: {s}"
|
||
return name, u["id"], js(b)["token"]
|
||
|
||
|
||
def main_checks(api):
|
||
a_name, a_id, a_tok = api.user("alice")
|
||
b_name, b_id, b_tok = api.user("bob")
|
||
c_name, c_id, c_tok = api.user("carol")
|
||
|
||
# --- регистрация
|
||
s, _, _ = api("POST", "/users", {"username": a_name, "display_name": "x", "password": PW})
|
||
check("повторный username -> 409", s == 409, str(s))
|
||
s, _, b = api("POST", "/users", {"username": "x_" + uuid.uuid4().hex[:8], "display_name": "x", "password": "short"})
|
||
check("пароль короче 12 -> 400", s == 400, str(s))
|
||
s, _, b = api("POST", "/users", {"username": "x_" + uuid.uuid4().hex[:8], "display_name": "x", "password": PW, "extra": 1})
|
||
check("лишнее поле -> 400", s == 400, str(s))
|
||
s, _, b = api("GET", "/users/me", headers=bearer(a_tok))
|
||
me = js(b) or {}
|
||
check("User не содержит пароль/hash/токен", s == 200 and not ({"password", "password_hash", "token"} & set(me)), str(sorted(me)))
|
||
|
||
res = []
|
||
rname = "race_" + uuid.uuid4().hex[:10]
|
||
def reg():
|
||
res.append(api("POST", "/users", {"username": rname, "display_name": "r", "password": PW})[0])
|
||
ts = [threading.Thread(target=reg) for _ in range(10)]
|
||
[t.start() for t in ts]; [t.join() for t in ts]
|
||
check("гонка одинакового username: ровно один 201, остальные 409", sorted(res) == [201] + [409] * 9, str(sorted(res)))
|
||
|
||
# --- вход
|
||
s1, h1, b1 = api("POST", "/auth/sessions", headers=basic(a_name, "wrong-password-123"))
|
||
s2, h2, b2 = api("POST", "/auth/sessions", headers=basic("nosuchuser_zz", PW))
|
||
e1, e2 = (js(b1) or {}).get("error", {}), (js(b2) or {}).get("error", {})
|
||
check("неверный пароль и неизвестный пользователь неразличимы (401, тот же code/message/заголовок)",
|
||
s1 == s2 == 401 and e1.get("code") == e2.get("code") and e1.get("message") == e2.get("message")
|
||
and h1.get("www-authenticate") == h2.get("www-authenticate") == 'Basic realm="messenger", charset="UTF-8"',
|
||
f"{s1}/{s2} {h1.get('www-authenticate')}")
|
||
s, _, _ = api("POST", "/auth/sessions", {"username": a_name, "password": PW})
|
||
check("вход JSON-телом без Basic -> 401", s == 401, str(s))
|
||
s, _, _ = api("POST", "/auth/sessions", headers=bearer(a_tok))
|
||
check("Bearer на POST /auth/sessions -> 401", s == 401, str(s))
|
||
s, h, b = api("POST", "/auth/sessions", headers=basic(a_name, PW))
|
||
d = js(b) or {}
|
||
check("токен >=256 бит, token_type Bearer", s == 201 and len(d.get("token", "")) >= 43 and d.get("token_type") == "Bearer", str(s))
|
||
|
||
# --- бизнес-endpoint принимают только Bearer
|
||
s, h, _ = api("GET", "/users/me", headers=basic(a_name, PW))
|
||
check("Basic на бизнес-endpoint -> 401 + WWW-Authenticate: Bearer", s == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s))
|
||
s, _, _ = api("GET", "/users/me", headers={"X-User-Id": a_id})
|
||
check("один X-User-Id доступа не даёт", s == 401, str(s))
|
||
s, _, b = api("GET", "/users/me", headers={**bearer(a_tok), "X-User-Id": b_id})
|
||
check("X-User-Id игнорируется: владелец определяется токеном", s == 200 and (js(b) or {}).get("id") == a_id, str(s))
|
||
s, _, _ = api("GET", "/users/me", headers=bearer("x" * 43))
|
||
check("неизвестный токен -> 401", s == 401, str(s))
|
||
|
||
# --- запрос-идентификатор в ошибках
|
||
s, h, b = api("GET", "/chats")
|
||
check("X-Request-Id совпадает с request_id в теле ошибки", s == 401 and h.get("x-request-id") == (js(b) or {}).get("error", {}).get("request_id"), str(s))
|
||
|
||
# --- чаты и доступ
|
||
s, _, b = api("GET", "/chats", headers=bearer(a_tok))
|
||
before = len((js(b) or {}).get("items", []))
|
||
s, _, b = api("POST", "/chats", {"title": "t", "member_ids": [a_id, str(uuid.uuid4())]}, bearer(a_tok))
|
||
check("чат с неизвестным участником -> 400", s == 400, str(s))
|
||
s, _, b = api("GET", "/chats", headers=bearer(a_tok))
|
||
check("после отказа новый чат не появился (нет частичной записи)", len((js(b) or {}).get("items", [])) == before)
|
||
s, _, b = api("POST", "/chats", {"title": "ab", "member_ids": [a_id, b_id]}, bearer(a_tok))
|
||
chat = js(b) or {}
|
||
check("чат создан с обоими участниками", s == 201 and sorted(chat.get("member_ids", [])) == sorted([a_id, b_id]), str(s))
|
||
cid = chat.get("id", "")
|
||
s, _, _ = api("POST", "/chats", {"title": "ab", "member_ids": [b_id]}, bearer(a_tok))
|
||
check("создатель обязан быть среди member_ids -> 400", s == 400, str(s))
|
||
for path in (f"/chats/{cid}", f"/chats/{cid}/messages"):
|
||
s, _, _ = api("GET", path, headers=bearer(c_tok))
|
||
check(f"посторонний: GET {path.split(cid)[1] or '/chat'} -> 404", s == 404, str(s))
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "hi"}, H(c_tok))
|
||
check("посторонний не может писать -> 404", s == 404, str(s))
|
||
for path in ("/chats/not-a-uuid", "/chats/not-a-uuid/messages"):
|
||
s, _, _ = api("GET", path, headers=bearer(a_tok))
|
||
check(f"неверный UUID {path} -> 400", s == 400, str(s))
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "hi", "sender_id": b_id}, H(a_tok))
|
||
check("sender_id в запросе не принимается -> 400", s == 400, str(s))
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": " "}, H(a_tok))
|
||
check("пробельный текст -> 400", s == 400, str(s))
|
||
s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "привет 👋"}, H(b_tok))
|
||
check("отправитель берётся из токена", s == 201 and (js(b) or {}).get("sender_id") == b_id, str(s))
|
||
|
||
# --- пагинация
|
||
for i in range(5):
|
||
api("POST", f"/chats/{cid}/messages", {"text": f"m{i}"}, H(a_tok))
|
||
seen, cur, pages = [], None, 0
|
||
while True:
|
||
s, _, b = api("GET", f"/chats/{cid}/messages?limit=2" + (f"&cursor={cur}" if cur else ""), headers=bearer(a_tok))
|
||
d = js(b) or {}
|
||
seen += [m["id"] for m in d.get("items", [])]
|
||
pages += 1
|
||
cur = d.get("next_cursor")
|
||
if not cur or pages > 10:
|
||
break
|
||
check("пагинация limit=2: без повторов, все 6 сообщений", len(seen) == len(set(seen)) == 6, f"{len(seen)}/{len(set(seen))}")
|
||
s, _, b = api("GET", f"/chats/{cid}/messages?limit=2", headers=bearer(a_tok))
|
||
cur = (js(b) or {}).get("next_cursor")
|
||
s, _, b = api("POST", "/chats", {"title": "other", "member_ids": [a_id]}, bearer(a_tok))
|
||
other = (js(b) or {}).get("id")
|
||
s, _, _ = api("GET", f"/chats/{other}/messages?cursor={cur}", headers=bearer(a_tok))
|
||
check("cursor от другого чата -> 400", s == 400, str(s))
|
||
for q in ("limit=0", "limit=101", "limit=abc", "limit=%2B5", "limit=2&limit=3"):
|
||
s, _, _ = api("GET", f"/chats/{cid}/messages?{q}", headers=bearer(a_tok))
|
||
check(f"?{q} -> 400", s == 400, str(s))
|
||
|
||
# --- тело запроса
|
||
s = post_big(api.base, "/users", 1100 * 1024)
|
||
check("тело >1 MiB -> 413", s == 413, str(s))
|
||
s, _, _ = api("POST", "/users", raw=b"{}", headers={"Content-Type": "text/plain"})
|
||
check("не JSON Content-Type -> 415", s == 415, str(s))
|
||
s, _, _ = api("POST", "/users", raw=b"{", headers={"Content-Type": "application/json"})
|
||
check("битый JSON -> 400", s == 400, str(s))
|
||
|
||
# --- logout (в конце: отзывает токен)
|
||
s, _, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok))
|
||
check("logout -> 204", s == 204, str(s))
|
||
s, h, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok))
|
||
check("повторный logout с отозванным токеном -> 401", s == 401, str(s))
|
||
s, h, _ = api("GET", "/users/me", headers=bearer(a_tok))
|
||
check("отозванный токен -> 401 + WWW-Authenticate: Bearer", s == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s))
|
||
s, _, _ = api("GET", "/users/me", headers=bearer(b_tok))
|
||
check("logout одного пользователя не затрагивает чужие сессии", s == 200, str(s))
|
||
|
||
|
||
def idempotency_checks(api, min_instances):
|
||
a_name, a_id, a_tok = api.user("alice")
|
||
b_name, b_id, b_tok = api.user("bob")
|
||
c_name, c_id, c_tok = api.user("carol")
|
||
s, _, b = api("POST", "/chats", {"title": "idem", "member_ids": [a_id, b_id]}, bearer(a_tok))
|
||
cid = js(b)["id"]
|
||
s, _, b = api("POST", "/chats", {"title": "idem2", "member_ids": [a_id, b_id]}, bearer(a_tok))
|
||
cid2 = js(b)["id"]
|
||
|
||
def hist(chat, tok):
|
||
s, _, b = api("GET", f"/chats/{chat}/messages?limit=100", headers=bearer(tok))
|
||
return (js(b) or {}).get("items", [])
|
||
|
||
# --- несколько реплик за LB, одна сессия, без повторного входа
|
||
seen = set()
|
||
for _ in range(60):
|
||
s, h, _ = api("GET", "/users/me", headers=bearer(a_tok))
|
||
if s != 200:
|
||
break
|
||
seen.add(h.get("x-instance-id"))
|
||
check(f"через LB отвечают >= {min_instances} реплик с одним токеном (X-Instance-Id: {len(seen)})",
|
||
len(seen) >= min_instances and None not in seen, str(seen))
|
||
|
||
# --- базовая идемпотентность
|
||
key = "k-" + uuid.uuid4().hex
|
||
s1, h1, b1 = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(a_tok, key))
|
||
s2, h2, b2 = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(a_tok, key))
|
||
check("повтор с тем же ключом: тот же 201 и то же сообщение", s1 == s2 == 201 and js(b1) == js(b2), f"{s1}/{s2}")
|
||
check("повтор не создал дубль", len([m for m in hist(cid, a_tok) if m["text"] == "один раз"]) == 1)
|
||
s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "другой текст"}, H(a_tok, key))
|
||
check("тот же ключ с другим телом -> 409", s == 409, str(s))
|
||
s, _, b = api("POST", f"/chats/{cid}/messages", raw=b'{"text":"\xd0\xbe\xd0\xb4\xd0\xb8\xd0\xbd \xd1\x80\xd0\xb0\xd0\xb7"}',
|
||
headers={**H(a_tok, key), "Content-Type": "application/json"})
|
||
check("тот же ключ и то же тело (другое форматирование JSON) -> тот же результат", s == 201 and js(b) == js(b1), str(s))
|
||
|
||
# --- область ключа: пользователь + метод + путь
|
||
s, _, b = api("POST", f"/chats/{cid2}/messages", {"text": "один раз"}, H(a_tok, key))
|
||
check("тот же ключ в другом чате независим", s == 201 and js(b)["chat_id"] == cid2, str(s))
|
||
s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(b_tok, key))
|
||
check("тот же ключ у другого пользователя независим", s == 201 and js(b)["sender_id"] == b_id, str(s))
|
||
|
||
# --- валидация ключа и доступ
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "x"}, bearer(a_tok))
|
||
check("нет Idempotency-Key -> 400", s == 400, str(s))
|
||
for bad_key in ("bad key!", "a/b", "a" * 129, ""):
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "x"}, {**bearer(a_tok), "Idempotency-Key": bad_key})
|
||
check(f"неверный ключ {bad_key[:12]!r} -> 400", s == 400, str(s))
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(c_tok, key))
|
||
check("посторонний с тем же ключом -> 404 (доступ проверяется при повторе)", s == 404, str(s))
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "x"}, {"Idempotency-Key": "k1"})
|
||
check("без токена -> 401", s == 401, str(s))
|
||
|
||
# --- конкурентные повторы одного ключа (через LB попадают на разные реплики)
|
||
key2 = "c-" + uuid.uuid4().hex
|
||
res = []
|
||
def fire(text="конкурентно"):
|
||
s, h, b = api("POST", f"/chats/{cid}/messages", {"text": text}, H(a_tok, key2))
|
||
res.append((s, h.get("x-instance-id"), js(b)))
|
||
ts = [threading.Thread(target=fire) for _ in range(30)]
|
||
[t.start() for t in ts]; [t.join() for t in ts]
|
||
codes = sorted({r[0] for r in res})
|
||
ids = {(r[2] or {}).get("id") for r in res}
|
||
check("30 параллельных запросов с одним ключом: все 201 и одно и то же сообщение", codes == [201] and len(ids) == 1, f"{codes} {len(ids)}")
|
||
check("в истории ровно одно такое сообщение", len([m for m in hist(cid, a_tok) if m["text"] == "конкурентно"]) == 1)
|
||
print(f"INFO: параллельные повторы обслужили реплики: {sorted({r[1] for r in res})}")
|
||
|
||
key3 = "d-" + uuid.uuid4().hex
|
||
res.clear()
|
||
ts = [threading.Thread(target=lambda i=i: res.append(api("POST", f"/chats/{cid}/messages", {"text": f"вариант {i % 2}"}, H(a_tok, key3))[0])) for i in range(20)]
|
||
[t.start() for t in ts]; [t.join() for t in ts]
|
||
check("параллельно один ключ и два разных тела: победитель один, остальным другого тела -> 409",
|
||
set(res) == {201, 409} and 1 <= res.count(201), str(sorted(set(res))))
|
||
check("создано ровно одно сообщение из конкурирующих", len([m for m in hist(cid, a_tok) if m["text"].startswith("вариант")]) == 1)
|
||
|
||
# --- повтор после logout
|
||
s, _, _ = api("DELETE", "/auth/sessions/current", headers=bearer(a_tok))
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": "один раз"}, H(a_tok, key))
|
||
check("повтор с отозванным токеном -> 401", s == 401, str(s))
|
||
|
||
|
||
def ttl_checks(api):
|
||
name = api.user("ttl")[0]
|
||
s, _, b = api("POST", "/auth/sessions", headers=basic(name, PW))
|
||
d = js(b) or {}
|
||
tok = d.get("token", "")
|
||
s0, _, _ = api("GET", "/users/me", headers=bearer(tok))
|
||
check("TTL: сразу после входа токен действует (200)", s0 == 200, str(s0))
|
||
time.sleep(3.5)
|
||
s1, h, _ = api("GET", "/users/me", headers=bearer(tok))
|
||
check("TTL: через 3.5 с при SESSION_TTL_SECONDS=2 токен истёк (401)", s1 == 401 and h.get("www-authenticate", "").startswith("Bearer"), str(s1))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||
ap.add_argument("--mode", choices=["main", "idem", "ttl"], default="main")
|
||
ap.add_argument("--min-instances", type=int, default=2, help="сколько разных X-Instance-Id ожидается через LB")
|
||
a = ap.parse_args()
|
||
api = Api(a.base_url.rstrip("/"))
|
||
if a.mode == "ttl":
|
||
ttl_checks(api)
|
||
elif a.mode == "idem":
|
||
idempotency_checks(api, a.min_instances)
|
||
else:
|
||
main_checks(api)
|
||
print(("FAIL: %d проверок не прошли: %s" % (len(fails), "; ".join(fails))) if fails else "PASS: все проверки режима '%s'" % a.mode)
|
||
sys.exit(1 if fails else 0)
|