#!/usr/bin/env python3 """Негативные и контрактные проверки уровня 3/4: аутентификация, KDF, валидация, ACL, пагинация, атомарность/rollback создания чата, гонка регистрации, параметризация SQL.""" import hashlib import threading import uuid from urllib.parse import quote from common import BASE_URL, Client, Suite, basic, check, login, new_user, sql c = Client(BASE_URL) s = Suite("API, auth, validation, ACL, transactions (" + BASE_URL + ")") alice = new_user(c, "alice"); login(c, alice) bob = new_user(c, "bob"); login(c, bob) eve = new_user(c, "eve"); login(c, eve) chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", body={"title": "student-tests", "member_ids": [alice["id"], bob["id"]]})["json"] CHAT = "/api/v1/chats/" + chat["id"] @s.case("password stored only as scrypt KDF hash; User has no secret fields") def _(): row = sql("SELECT password_hash FROM users WHERE id = '%s'" % alice["id"])[0] check(row.startswith("$scrypt$ln=15,r=8,p=3$"), "unexpected hash format") check(alice["password"] not in row, "plaintext password in DB") check(set(alice["user"]) == {"id", "username", "display_name", "created_at"}, "User leaks fields") other = new_user(c, "same", password=alice["password"]) h2 = sql("SELECT password_hash FROM users WHERE id = '%s'" % other["id"])[0] check(h2 != row, "same password produced same hash: salt missing") @s.case("wrong password and unknown user: identical 401 + Basic challenge") def _(): r1 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic(alice["username"], "wrong-password-123")}) r2 = c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("no_such_user_x", "wrong-password-123")}) check(r1["json"]["error"]["message"] == r2["json"]["error"]["message"], "messages differ") check(r1["headers"]["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"', "challenge mismatch") @s.case("malformed Basic / Bearer on /auth/sessions / body on login") def _(): for value in ("Basic", "Basic !!!", "Basic " + "bm9jb2xvbg==", "Bearer " + "x" * 43): c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": value}) c.call("POST", "/api/v1/auth/sessions", 401) c.call("POST", "/api/v1/auth/sessions", 400, body={"username": alice["username"]}, headers={"Authorization": basic(alice["username"], alice["password"])}) @s.case("password with ':' and non-ASCII UTF-8 works (RFC 7617)") def _(): u = new_user(c, "colon", password="пароль:с:двоеточием-😀") login(c, u) me = c.call("GET", "/api/v1/users/me", actor=u, schema="User")["json"] check(me["id"] == u["id"], "wrong user") @s.case("opaque 256-bit token, unique per login, DB stores only SHA-256") def _(): a, b = dict(alice), dict(alice) login(c, a); login(c, b) check(a["token"] != b["token"] and len(a["token"]) == 43, "token not unique/opaque") check(a["token"] not in (alice["id"], alice["username"]), "token derived from identity") digest = hashlib.sha256(a["token"].encode()).hexdigest() check(sql("SELECT count(*) FROM sessions WHERE token_hash = decode('%s','hex')" % digest) == ["1"], "hash not found") check(sql("SELECT count(*) FROM information_schema.columns WHERE table_name = 'sessions'" " AND data_type IN ('text', 'character varying')") == ["0"], "sessions has a text column for raw token") @s.case("only Bearer accepted; Basic and X-User-Id never authenticate") def _(): c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": basic(alice["username"], alice["password"])}) c.call("GET", "/api/v1/chats", 401, headers={"X-User-Id": alice["id"]}) c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "A" * 43}) c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer short"}) me = c.call("GET", "/api/v1/users/me", actor=bob, headers={"X-User-Id": alice["id"]}, schema="User")["json"] check(me["id"] == bob["id"], "X-User-Id overrode session") @s.case("logout revokes only the current session; repeat -> 401") def _(): u = new_user(c, "logout"); first = dict(u); second = dict(u) login(c, first); login(c, second) c.call("GET", "/api/v1/users/me", actor=first, schema="User") # прогреть кэш c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=first) for path in ("/api/v1/users/me", "/api/v1/chats"): c.call("GET", path, 401, actor=first) c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=first) c.call("GET", "/api/v1/users/me", actor=second, schema="User") check(sql("SELECT count(*) FROM sessions WHERE user_id='%s' AND revoked_at IS NOT NULL" % u["id"]) == ["1"], "revocation not persisted") @s.case("strict JSON validation -> 400") def _(): base = {"username": "valid_" + uuid.uuid4().hex[:8], "display_name": "X", "password": "p" * 12} bad = [dict(base, extra=1), dict(base, username="UPPER"), dict(base, username="ab"), dict(base, display_name=" "), dict(base, display_name="x" * 101), dict(base, password="p" * 11), dict(base, password="p" * 129), dict(base, display_name=5), {"username": base["username"]}] for body in bad: c.call("POST", "/api/v1/users", 400, body=body) c.call("POST", "/api/v1/users", 400, raw=b'{"username": ', headers={"Content-Type": "application/json"}) c.call("POST", "/api/v1/users", 400, raw=b'[1,2]', headers={"Content-Type": "application/json"}) c.call("POST", "/api/v1/users", 400, raw=b'{"username":"a","username":"b"}', headers={"Content-Type": "application/json"}) c.call("POST", "/api/v1/users", 400, raw=b'username=x', headers={"Content-Type": "application/x-www-form-urlencoded"}) c.call("POST", "/api/v1/users", 413, raw=b'{"x":"' + b"a" * 70000 + b'"}', headers={"Content-Type": "application/json"}) @s.case("message text: 4000 code points OK, 4001 / whitespace / sender_id -> 400") def _(): msg = c.message(alice, chat, "😀" * 4000)["json"] check(len(msg["text"]) == 4000, "text truncated") for body in ({"text": "a" * 4001}, {"text": " \n\t "}, {"text": "x", "sender_id": bob["id"]}, {"text": None}, {}): c.call("POST", CHAT + "/messages", 400, actor=alice, body=body) @s.case("SQL is parameterized: injection payloads stored verbatim") def _(): payload = "'); DROP TABLE messages; -- \" \\ %s $1" msg = c.message(alice, chat, payload)["json"] check(msg["text"] == payload, "payload altered") c.call("GET", CHAT + "/messages?limit=1", actor=alice, schema="MessagePage") c.call("GET", "/api/v1/chats/" + quote("' OR 1=1 --", safe=""), 400, actor=alice) @s.case("ACL: outsider gets 404 everywhere (even for invalid body)") def _(): c.call("GET", CHAT, 404, actor=eve) c.call("GET", CHAT + "/messages", 404, actor=eve) c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": "x"}) c.call("POST", CHAT + "/messages", 404, actor=eve, body={"text": ""}) c.call("GET", "/api/v1/chats/" + str(uuid.uuid4()), 404, actor=alice) c.call("GET", "/api/v1/chats/not-a-uuid", 400, actor=alice) got = c.call("GET", CHAT, actor=bob, schema="Chat")["json"] check(got["member_ids"] == [alice["id"], bob["id"]], "member order/content changed") @s.case("create chat validation: duplicates, caller missing, unknown member") def _(): c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [alice["id"], alice["id"]]}) c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": [bob["id"]]}) c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": "d", "member_ids": []}) c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": " ", "member_ids": [alice["id"]]}) @s.case("compound create-chat rolls back on FK failure (no orphan chat)") def _(): title = "rollback-" + uuid.uuid4().hex before = sql("SELECT count(*) FROM chats")[0] c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}) check(sql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == ["0"], "orphan chat committed") check(sql("SELECT count(*) FROM chat_members m LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL") == ["0"], "orphan membership") return "chats before=%s, failed insert left 0 rows" % before @s.case("registration race: 20 parallel same username -> exactly one 201") def _(): username = "race_" + uuid.uuid4().hex[:12] statuses, lock = [], threading.Lock() barrier = threading.Barrier(20) def worker(): local = Client(BASE_URL, timeout=30) barrier.wait() r = local.call("POST", "/api/v1/users", [201, 409], body={"username": username, "display_name": "R", "password": "Race-password-123"}) with lock: statuses.append(r["status"]) threads = [threading.Thread(target=worker) for _ in range(20)] [t.start() for t in threads]; [t.join() for t in threads] check(sorted(statuses) == [201] + [409] * 19, "statuses: %s" % sorted(statuses)) check(sql("SELECT count(*) FROM users WHERE username = '%s'" % username) == ["1"], "duplicate rows") return "201x1, 409x19, rows=1" @s.case("keyset pagination: 120 msgs, varying limit, no gaps/duplicates") def _(): room = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat", body={"title": "pages", "member_ids": [alice["id"], bob["id"]]})["json"] path = "/api/v1/chats/" + room["id"] + "/messages" sent = [c.message(alice if i % 2 else bob, room, "m%03d" % i)["json"] for i in range(120)] got, cursor, limits, n = [], None, [7, 1, 50, 100, 3], 0 while True: q = "?limit=%d" % limits[n % len(limits)] + ("&cursor=" + quote(cursor, safe="") if cursor else "") page = c.call("GET", path + q, actor=bob, schema="MessagePage")["json"] got.extend(page["items"]); cursor = page["next_cursor"]; n += 1 if cursor is None: break check([m["id"] for m in got] == [m["id"] for m in sent], "order/completeness mismatch") first = c.call("GET", path + "?limit=2", actor=bob, schema="MessagePage")["json"] c.call("GET", CHAT + "/messages?cursor=" + quote(first["next_cursor"], safe=""), 400, actor=alice) for q in ("?limit=0", "?limit=101", "?limit=abc", "?limit=-1", "?limit=1&limit=2", "?cursor=garbage", "?cursor="): c.call("GET", path + q, 400, actor=bob) default = c.call("GET", path, actor=bob, schema="MessagePage")["json"] check(len(default["items"]) == 50 and default["next_cursor"], "default limit must be 50") return "%d pages" % n @s.case("chat list: only own chats, ordered, cursor bound to user") def _(): u = new_user(c, "lister"); login(c, u) made = [c.call("POST", "/api/v1/chats", 201, actor=u, schema="Chat", body={"title": "c%d" % i, "member_ids": [u["id"]]})["json"]["id"] for i in range(3)] got, cursor = [], None while True: page = c.call("GET", "/api/v1/chats?limit=1" + ("&cursor=" + quote(cursor, safe="") if cursor else ""), actor=u, schema="ChatPage")["json"] got += [x["id"] for x in page["items"]]; cursor = page["next_cursor"] if cursor is None: break foreign = cursor check(got == made, "chat list mismatch") c.call("GET", "/api/v1/chats?cursor=" + quote(foreign, safe=""), 400, actor=alice) @s.case("read-after-write: confirmed message visible to next read") def _(): m = c.message(bob, chat, "raw-" + uuid.uuid4().hex)["json"] items, cursor = [], None while True: page = c.call("GET", CHAT + "/messages?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else ""), actor=alice, schema="MessagePage")["json"] items += page["items"]; cursor = page["next_cursor"] if not cursor: break check(items[-1] == m, "last message is not the just-written one") @s.case("unknown route 404 / wrong method 405 in error format") def _(): c.call("GET", "/api/v1/nope", 404) r = c.call("PUT", "/api/v1/users", 405, body={}) check(r["json"]["error"]["code"] == "invalid_request", "405 code") if __name__ == "__main__": s.run()