232 lines
12 KiB
Python
232 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""Собственные проверки lab2 (дополняют публичный smoke, ничего не ослабляют).
|
||
|
||
python student-tests/lab2_checks.py --base-url http://localhost:8080 # основные
|
||
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}
|
||
|
||
|
||
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"}, bearer(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}, bearer(a_tok))
|
||
check("sender_id в запросе не принимается -> 400", s == 400, str(s))
|
||
s, _, _ = api("POST", f"/chats/{cid}/messages", {"text": " "}, bearer(a_tok))
|
||
check("пробельный текст -> 400", s == 400, str(s))
|
||
s, _, b = api("POST", f"/chats/{cid}/messages", {"text": "привет 👋"}, bearer(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}"}, bearer(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 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", "ttl"], default="main")
|
||
a = ap.parse_args()
|
||
api = Api(a.base_url.rstrip("/"))
|
||
(ttl_checks if a.mode == "ttl" 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)
|