#!/usr/bin/env python3 """Собственные проверки сверх публичного smoke: гонка регистрации, валидация, пагинация, безопасность.""" import base64 import json import uuid from concurrent.futures import ThreadPoolExecutor from urllib.parse import quote from common import BASE, Failure, basic, check, client, parse_json c = client() RESULTS = [] def jget(path, actor): return parse_json(c.call("GET", path, 200, actor=actor)) def case(fn): try: fn() RESULTS.append((fn.__name__, "PASS")) print("PASS", fn.__name__) except Failure as exc: RESULTS.append((fn.__name__, "FAIL")) print("FAIL", fn.__name__, "-", exc) return fn def reg(name, pw="Correct-horse-battery-1", display="X", **extra): return c.call("POST", "/api/v1/users", 201, body={"username": name, "display_name": display, "password": pw, **extra}) @case def registration_race_same_username(): name = "race_" + uuid.uuid4().hex[:12] body = {"username": name, "display_name": "Гонка", "password": "Race-password-123"} def attempt(_): return c.call("POST", "/api/v1/users", [201, 409], body=body)["status"] with ThreadPoolExecutor(max_workers=16) as pool: codes = list(pool.map(attempt, range(16))) check(codes.count(201) == 1 and codes.count(409) == 15, "ожидали ровно один 201 и 15 конфликтов: %s" % codes) @case def username_and_field_validation(): ok = {"display_name": "X", "password": "Correct-horse-battery-1"} for bad in ("ab", "UPPER_case", "has space", "a" * 33, "name\n", "имя_юзера"): # "name\n" ловит ошибку с «$» c.call("POST", "/api/v1/users", 400, body={"username": bad, **ok}) base = {"username": "val_" + uuid.uuid4().hex[:10], **ok} c.call("POST", "/api/v1/users", 400, body={**base, "password": "short"}) # < 12 c.call("POST", "/api/v1/users", 400, body={**base, "password": "x" * 129}) # > 128 c.call("POST", "/api/v1/users", 400, body={**base, "display_name": " "}) c.call("POST", "/api/v1/users", 400, body={**base, "display_name": "x" * 101}) c.call("POST", "/api/v1/users", 400, body={**base, "extra": 1}) c.call("POST", "/api/v1/users", 400, body={**base, "display_name": 5}) c.call("POST", "/api/v1/users", 400, raw=b"{not json", headers={"Content-Type": "application/json"}) c.call("POST", "/api/v1/users", 400, raw=b'{"username":"aaa","username":"bbb"}', headers={"Content-Type": "application/json"}) c.call("POST", "/api/v1/users", 415, raw=b"x", headers={"Content-Type": "text/plain"}) c.call("POST", "/api/v1/users", 413, raw=b"{" + b" " * 70000 + b"}", headers={"Content-Type": "application/json"}) c.call("POST", "/api/v1/users", 400, raw=b'{"username":"aaa","display_name":"\\ud800","password":"Correct-horse-battery-1"}', headers={"Content-Type": "application/json"}) # одиночный суррогат -> 400, а не 500 c.call("POST", "/api/v1/users", 400, raw=b'{"username":"aaa","display_name":"a\\u0000b","password":"Correct-horse-battery-1"}', headers={"Content-Type": "application/json"}) # NUL -> 400 @case def password_with_colon_and_unicode_login(): name = "uni_" + uuid.uuid4().hex[:10] pw = "парoль:с:двоеточием-🔐-123" reg(name, pw) r = c.call("POST", "/api/v1/auth/sessions", 201, headers=basic(name, pw), schema="Session") check(len(r["json"]["token"]) >= 43, "токен слишком короткий (нужно ≥256 бит)") c.call("POST", "/api/v1/auth/sessions", 401, headers=basic(name, pw + "x")) @case def login_failures_look_identical(): name = "same_" + uuid.uuid4().hex[:10] reg(name) a = c.call("POST", "/api/v1/auth/sessions", 401, headers=basic(name, "Wrong-password-123")) b = c.call("POST", "/api/v1/auth/sessions", 401, headers=basic("nobody_" + uuid.uuid4().hex[:8], "Wrong-password-123")) check(a["json"]["error"]["code"] == b["json"]["error"]["code"] and a["json"]["error"]["message"] == b["json"]["error"]["message"], "ответы различаются -> user enumeration") for headers in ({}, {"Authorization": "Basic !!!not-base64"}, {"Authorization": "Basic " + base64.b64encode(b"nocolon").decode()}, {"Authorization": "Bearer abc"}): r = c.call("POST", "/api/v1/auth/sessions", 401, headers=headers) check(r["headers"]["WWW-Authenticate"].startswith("Basic realm=\"messenger\""), "нет Basic challenge") @case def bearer_rules(): a = c.user("bearer") for bad in ({"Authorization": "Bearer " + "A" * 43}, {"Authorization": "Bearer"}, {"Authorization": "Token " + a["token"]}, {"Authorization": "bearer"}): r = c.call("GET", "/api/v1/users/me", 401, headers=bad) check(r["headers"]["WWW-Authenticate"] == 'Bearer realm="messenger"', "нет Bearer challenge") # регистр схемы не важен (RFC 7235), токен в нижнем регистре схемы работает c.call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + a["token"]}) for path in ("/api/v1/chats", "/api/v1/chats/" + str(uuid.uuid4())): c.call("GET", path, 401) @case def logout_revokes_only_that_session(): a = c.user("lo") second = c.call("POST", "/api/v1/auth/sessions", 201, headers=basic(a["registration"]["username"], a["registration"]["password"]), schema="Session")["json"] c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=a) c.call("GET", "/api/v1/users/me", 401, actor=a) c.call("GET", "/api/v1/users/me", 200, headers={"Authorization": "Bearer " + second["token"]}) @case def chat_creation_rules_and_no_side_effects(): a, b = c.user("ca"), c.user("cb") before = len(jget("/api/v1/chats?limit=100", a)["items"]) ghost = str(uuid.uuid4()) for members in ([a["id"], ghost], [a["id"], a["id"]], [b["id"]], [], ["not-a-uuid", a["id"]]): c.call("POST", "/api/v1/chats", 400, actor=a, body={"title": "t", "member_ids": members}) c.call("POST", "/api/v1/chats", 400, actor=a, body={"title": " ", "member_ids": [a["id"]]}) after = len(jget("/api/v1/chats?limit=100", a)["items"]) check(before == after, "неудачное создание чата оставило следы") c.call("POST", "/api/v1/chats", 201, actor=a, body={"title": "solo", "member_ids": [a["id"]]}, schema="Chat") @case def message_rules(): a, b, e = c.user("ma"), c.user("mb"), c.user("me") chat = c.call("POST", "/api/v1/chats", 201, actor=a, body={"title": "m", "member_ids": [a["id"], b["id"]]}, schema="Chat")["json"] p = "/api/v1/chats/%s/messages" % chat["id"] c.call("POST", p, 400, actor=a, body={"text": " "}) c.call("POST", p, 400, actor=a, body={"text": "x" * 4001}) c.call("POST", p, 201, actor=a, body={"text": "x" * 4000}) c.call("POST", p, 400, actor=a, body={"text": "hi", "sender_id": b["id"]}) # sender_id не принимается c.call("POST", p, 404, actor=e, body={"text": "hi"}) c.call("POST", p, 404, actor=e, body={"bad": "body"}) # доступ раньше валидации c.call("POST", "/api/v1/chats/%s/messages" % uuid.uuid4(), 404, actor=a, body={"text": "hi"}) c.call("POST", "/api/v1/chats/not-a-uuid/messages", 400, actor=a, body={"text": "hi"}) c.call("GET", "/api/v1/chats/%s" % chat["id"], 404, actor=e) c.call("GET", "/api/v1/chats/%s/messages" % chat["id"], 404, actor=e) @case def pagination_walk_and_cursor_binding(): a, b = c.user("pa"), c.user("pb") chats = [c.call("POST", "/api/v1/chats", 201, actor=a, body={"title": "c%d" % i, "member_ids": [a["id"], b["id"]]}, schema="Chat")["json"] for i in (1, 2)] sent = [] def send(i): return c.call("POST", "/api/v1/chats/%s/messages" % chats[0]["id"], 201, actor=a if i % 2 else b, body={"text": "m%03d" % i}, schema="Message")["json"] with ThreadPoolExecutor(max_workers=8) as pool: sent = list(pool.map(send, range(250))) seen, cursor, pages = [], None, 0 while True: url = "/api/v1/chats/%s/messages?limit=%d" % (chats[0]["id"], 100 if pages == 0 else 37) + (("&cursor=" + quote(cursor, safe="")) if cursor else "") page = c.call("GET", url, actor=b, schema="MessagePage")["json"] seen += page["items"]; pages += 1; cursor = page["next_cursor"] if not cursor: break ids = [m["id"] for m in seen] check(len(ids) == 250 and len(set(ids)) == 250, "потеряны/дублируются сообщения: %d" % len(ids)) keys = [(m["created_at"], m["id"]) for m in seen] check(keys == sorted(keys), "нарушен порядок (created_at, id)") check({m["id"] for m in sent} == set(ids), "набор сообщений отличается от отправленного") first = c.call("GET", "/api/v1/chats/%s/messages?limit=1" % chats[0]["id"], actor=a, schema="MessagePage")["json"]["next_cursor"] c.call("GET", "/api/v1/chats/%s/messages?limit=1&cursor=%s" % (chats[1]["id"], quote(first, safe="")), 400, actor=a) # чужой чат for junk in ("zzz", "e30", base64.urlsafe_b64encode(b'{"k":"messages"}').decode()): c.call("GET", "/api/v1/chats/%s/messages?cursor=%s" % (chats[0]["id"], junk), 400, actor=a) for limit in ("0", "101", "-1", "abc", ""): c.call("GET", "/api/v1/chats/%s/messages?limit=%s" % (chats[0]["id"], limit), 400, actor=a) c.call("GET", "/api/v1/chats?limit=1", 200, actor=a, schema="ChatPage") @case def chat_list_pagination_and_order(): a, b = c.user("la"), c.user("lb") ids = [c.call("POST", "/api/v1/chats", 201, actor=a, body={"title": "L%d" % i, "member_ids": [a["id"], b["id"]]}, schema="Chat")["json"]["id"] for i in range(5)] got, cursor = [], None while True: page = c.call("GET", "/api/v1/chats?limit=2" + (("&cursor=" + quote(cursor, safe="")) if cursor else ""), actor=b, schema="ChatPage")["json"] got += [x["id"] for x in page["items"]]; cursor = page["next_cursor"] if not cursor: break check(got == ids, "порядок/полнота списка чатов нарушены") c.call("GET", "/api/v1/chats?limit=1&cursor=" + quote(c.call("GET", "/api/v1/chats?limit=1", actor=a, schema="ChatPage")["json"]["next_cursor"], safe=""), 400, actor=b) # курсор другого пользователя @case def request_id_and_error_shape(): r = c.call("GET", "/api/v1/nope", 404) check(r["json"]["error"]["code"] == "not_found", "404 неизвестного маршрута не в формате ошибки") c.call("PUT", "/api/v1/users", [400, 404, 405]) if __name__ == "__main__": failed = [n for n, s in RESULTS if s == "FAIL"] print("\n%d/%d passed" % (len(RESULTS) - len(failed), len(RESULTS))) raise SystemExit(1 if failed else 0)