forked from mtusi2026/mtusi2026lab4
@@ -0,0 +1,56 @@
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
from urllib.parse import urlsplit
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client as PublicClient
|
||||
from scripts import lab
|
||||
|
||||
|
||||
def project_name():
|
||||
name = os.environ.get("LAB4_PROJECT", lab.settings().get("COMPOSE_PROJECT_NAME", "kuznetsov-lab4"))
|
||||
if name != "kuznetsov-lab4" and not name.startswith("kuznetsov-lab4-"):
|
||||
raise RuntimeError("Tests only operate on Kuznetsov lab4 projects")
|
||||
return name
|
||||
|
||||
|
||||
class Client(PublicClient):
|
||||
def __init__(self, base_url=None, ca_file=None, timeout=10):
|
||||
project_name()
|
||||
port = int(os.environ.get("LAB4_PORT", lab.settings().get("HTTP_PORT", "18104")))
|
||||
target = base_url or os.environ.get("BASE_URL") or f"http://127.0.0.1:{port}"
|
||||
parsed = urlsplit(target)
|
||||
if parsed.scheme != "http" or parsed.hostname not in ("127.0.0.1", "localhost") or parsed.port != port:
|
||||
raise RuntimeError("BASE_URL must match this lab's local port")
|
||||
super().__init__(target, ca_file=ca_file, timeout=timeout)
|
||||
|
||||
|
||||
def image_bytes(kind="PNG", size=(32, 24), mode="RGB"):
|
||||
with Image.new(mode, size, (35, 120, 200, 255) if mode == "RGBA" else (35, 120, 200)) as image:
|
||||
output = io.BytesIO()
|
||||
image.save(output, format=kind)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)
|
||||
|
||||
|
||||
def padded_png(size):
|
||||
base = image_bytes()
|
||||
padding = b"p" * (size - len(base) - 12)
|
||||
return base[:-12] + chunk(b"raNd", padding) + base[-12:]
|
||||
|
||||
|
||||
def oversized_pixels():
|
||||
header = struct.pack(">IIBBBBB", 8000, 5001, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IEND", b"")
|
||||
@@ -0,0 +1,182 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from helpers import Client
|
||||
from client import timestamp
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:18104"))
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def error(self, method, path, status=400, **kwargs):
|
||||
if method == "POST" and path.endswith("/messages"):
|
||||
kwargs.setdefault("headers", {}).setdefault("Idempotency-Key", uuid4().hex)
|
||||
response = self.client.call(method, path, status, **kwargs)
|
||||
code = {400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 415: "unsupported_media_type"}[status]
|
||||
self.assertEqual(response["json"]["error"]["code"], code)
|
||||
|
||||
def get_page(self, path, actor=None, **query):
|
||||
schema = "MessagePage" if path.endswith("/messages") else "ChatPage"
|
||||
return self.client.call("GET", path + "?" + urlencode(query), actor=actor or self.alice, schema=schema)["json"]
|
||||
|
||||
def new_chat(self):
|
||||
return self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "Ещё чат", "member_ids": [self.alice["id"], self.bob["id"]]}, schema="Chat")["json"]
|
||||
|
||||
def test_user_fields(self):
|
||||
name = "u_" + uuid4().hex[:20]
|
||||
bodies = [
|
||||
{"username": "ab", "display_name": "Имя"},
|
||||
{"username": "ABC", "display_name": "Имя"},
|
||||
{"username": "valid\n", "display_name": "Имя"},
|
||||
{"username": 123, "display_name": "Имя"},
|
||||
{"username": name, "display_name": " \t\n"},
|
||||
{"username": name, "display_name": 123},
|
||||
{"username": name, "display_name": None},
|
||||
{"username": name, "display_name": "я" * 101},
|
||||
{"username": name, "display_name": "Имя", "password": "extra"},
|
||||
{"username": name},
|
||||
]
|
||||
for body in bodies:
|
||||
body.setdefault("password", "T3st-password-123")
|
||||
with self.subTest(fields=sorted(body)):
|
||||
self.error("POST", "/api/v1/users", body=body)
|
||||
user = self.client.call("POST", "/api/v1/users", 201,
|
||||
body={"username": name, "display_name": "👋" * 100, "password": "T3st-password-123"}, schema="User")["json"]
|
||||
self.assertEqual(user["display_name"], "👋" * 100)
|
||||
self.error("POST", "/api/v1/users", 409, body={"username": name, "display_name": "Повтор", "password": "T3st-password-123"})
|
||||
|
||||
def test_invalid_json_and_content_type(self):
|
||||
for raw in (b'{"username":', b"null", b"[]", b"true", b"\xff", '{}'.encode('utf-16')):
|
||||
with self.subTest(raw=raw):
|
||||
self.error("POST", "/api/v1/users", raw=raw, headers={"Content-Type": "application/json"})
|
||||
self.error("POST", "/api/v1/users", 415, raw=b"text", headers={"Content-Type": "text/plain"})
|
||||
self.error("POST", "/api/v1/users", 415, raw=b"{}")
|
||||
|
||||
def test_auth_and_access(self):
|
||||
self.error("GET", "/api/v1/users/me", 401)
|
||||
for value in (str(uuid4()), "bad-id"):
|
||||
self.error("GET", "/api/v1/users/me", 401, headers={"X-User-Id": value})
|
||||
self.error("GET", "/api/v1/chats/bad-id", 401)
|
||||
self.error("GET", "/api/v1/chats/bad-id", actor=self.alice)
|
||||
self.error("GET", "/api/v1/chats/" + str(uuid4()), 404, actor=self.alice)
|
||||
self.error("GET", self.path, 404, actor=self.eve)
|
||||
self.error("GET", self.path + "/messages", 404, actor=self.eve)
|
||||
self.error("POST", self.path + "/messages", 404, actor=self.eve, body={"text": "Чужое"})
|
||||
self.assertEqual(self.get_page("/api/v1/chats", self.eve)["items"], [])
|
||||
|
||||
def test_chat_validation_is_atomic(self):
|
||||
before = self.get_page("/api/v1/chats")["items"]
|
||||
valid = [self.alice["id"], self.bob["id"]]
|
||||
for members in ([], [self.bob["id"]], [self.alice["id"], str(uuid4())],
|
||||
[self.alice["id"], self.alice["id"].upper()], ["bad-id"], valid * 51):
|
||||
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": members})
|
||||
for title in ("", " \t", "я" * 101, 123):
|
||||
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": title, "member_ids": valid})
|
||||
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": valid, "extra": 1})
|
||||
self.assertEqual(before, self.get_page("/api/v1/chats")["items"])
|
||||
|
||||
def test_message_fields_and_unicode(self):
|
||||
bodies = [{"text": value} for value in ("", " \t\n", "я" * 4001, None, 123, True, [])]
|
||||
bodies += [{}, {"text": "Hi", "sender_id": self.bob["id"]}, {"text": "Hi", "unexpected": []}]
|
||||
for body in bodies:
|
||||
self.error("POST", self.path + "/messages", actor=self.alice, body=body)
|
||||
for text in (" Привет, мир 👋\n", "👋" * 4000):
|
||||
message = self.client.message(self.alice, self.chat, text)["json"]
|
||||
self.assertEqual(message["text"], text)
|
||||
self.assertEqual(message["sender_id"], self.alice["id"])
|
||||
|
||||
def test_message_pagination(self):
|
||||
self.assertEqual(self.get_page(self.path + "/messages"), {"items": [], "next_cursor": None})
|
||||
self.assertEqual(self.get_page(self.path + "/messages", limit="0000000001")["items"], [])
|
||||
sent = [self.client.message(self.alice if i % 2 else self.bob, self.chat, str(i))["json"] for i in range(6)]
|
||||
received, cursor = [], None
|
||||
for limit in (2, 3, 1):
|
||||
query = {"limit": limit}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
page = self.get_page(self.path + "/messages", self.bob, **query)
|
||||
received.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
self.assertIsNone(cursor)
|
||||
self.assertEqual(received, sorted(sent, key=lambda item: (timestamp(item["created_at"]), item["id"])))
|
||||
|
||||
def test_chat_pagination(self):
|
||||
chats = [self.chat] + [self.new_chat() for _ in range(4)]
|
||||
received, cursor = [], None
|
||||
while True:
|
||||
query = {"limit": 2}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
page = self.get_page("/api/v1/chats", **query)
|
||||
received += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(received, sorted(chats, key=lambda item: (timestamp(item["created_at"]), item["id"])))
|
||||
cursor = self.get_page("/api/v1/chats", limit=1)["next_cursor"]
|
||||
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.bob)
|
||||
|
||||
def test_bad_cursors_and_limits(self):
|
||||
for i in range(2):
|
||||
self.client.message(self.alice, self.chat, str(i))
|
||||
cursor = self.get_page(self.path + "/messages", limit=1)["next_cursor"]
|
||||
for value in ("", "bad", cursor[:-1] + ("0" if cursor[-1] != "0" else "1")):
|
||||
self.error("GET", self.path + "/messages?" + urlencode({"cursor": value}), actor=self.alice)
|
||||
other = self.new_chat()
|
||||
self.error("GET", "/api/v1/chats/" + other["id"] + "/messages?" + urlencode({"cursor": cursor}), actor=self.alice)
|
||||
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.alice)
|
||||
for path in ("/api/v1/chats", self.path + "/messages"):
|
||||
for value in ("", "0", "-1", "101", "1.5", "true", "9" * 500):
|
||||
self.error("GET", path + "?" + urlencode({"limit": value}), actor=self.alice)
|
||||
|
||||
def test_read_after_write(self):
|
||||
first = self.client.message(self.alice, self.chat, "Первое")["json"]
|
||||
second = self.client.message(self.bob, self.chat, "Второе")["json"]
|
||||
page = self.get_page(self.path + "/messages", limit=1)
|
||||
third = self.client.message(self.bob, self.chat, "Новое")["json"]
|
||||
rest = self.get_page(self.path + "/messages", self.bob, cursor=page["next_cursor"])
|
||||
self.assertEqual(page["items"] + rest["items"], [first, second, third])
|
||||
self.assertIsNone(rest["next_cursor"])
|
||||
|
||||
def test_parallel_messages(self):
|
||||
def send(worker):
|
||||
client = Client(self.client.base)
|
||||
return [client.message(self.alice, self.chat, f"{worker}:{i}")["json"]["id"] for i in range(10)]
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
sent = [item for group in pool.map(send, range(10)) for item in group]
|
||||
received, cursor = [], None
|
||||
while True:
|
||||
query = {"limit": 17}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
page = self.get_page(self.path + "/messages", self.bob, **query)
|
||||
received += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(received), 100)
|
||||
self.assertEqual(len({item["text"] for item in received}), 100)
|
||||
self.assertEqual({item["id"] for item in received}, set(sent))
|
||||
|
||||
def test_parallel_username(self):
|
||||
body = {"username": "u_" + uuid4().hex[:20], "display_name": "Один", "password": "T3st-password-123"}
|
||||
def create(_):
|
||||
return Client(self.client.base).call("POST", "/api/v1/users", [201, 409], body=body, schema="User")["status"]
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
statuses = list(pool.map(create, range(10)))
|
||||
self.assertEqual(statuses.count(201), 1)
|
||||
self.assertEqual(statuses.count(409), 9)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,117 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
import unittest
|
||||
|
||||
from helpers import Client, ROOT, image_bytes, oversized_pixels, padded_png
|
||||
|
||||
|
||||
class AttachmentTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(timeout=60)
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def upload(self, content=None, media="image/png", name="photo.png", expected=201, actor=None):
|
||||
return self.client.call(
|
||||
"POST", self.path + "/attachments?" + urlencode({"filename": name}), expected,
|
||||
actor=actor or self.alice, raw=image_bytes() if content is None else content,
|
||||
headers={"Content-Type": media}, schema="Attachment" if expected == 201 else None,
|
||||
)
|
||||
|
||||
def test_original_png_jpeg_and_unicode_filename(self):
|
||||
for kind, media in (("PNG", "image/png"), ("JPEG", "image/jpeg")):
|
||||
raw = image_bytes(kind)
|
||||
att = self.upload(raw, media, "фото 👋." + kind.lower())["json"]
|
||||
self.assertEqual(att["owner_id"], self.alice["id"])
|
||||
self.assertEqual(att["sha256"], hashlib.sha256(raw).hexdigest())
|
||||
self.assertEqual(att["size_bytes"], len(raw))
|
||||
self.assertEqual((att["status"], att["variants"], att["error_code"]), ("ready", [], None))
|
||||
path = "/api/v1/attachments/" + att["id"]
|
||||
metadata = self.client.call("GET", path, actor=self.bob, schema="Attachment")["json"]
|
||||
self.assertEqual(metadata, att)
|
||||
downloaded = self.client.call("GET", path + "/content", actor=self.bob)
|
||||
self.assertEqual(downloaded["bytes"], raw)
|
||||
self.assertEqual(downloaded["headers"].get_content_type(), media)
|
||||
self.assertNotIn("object_key", metadata)
|
||||
self.assertNotIn("Location", downloaded["headers"])
|
||||
|
||||
def test_filename_validation(self):
|
||||
for name in ("", " \t", "../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\n.png", "a\x7f.png", "я" * 256):
|
||||
self.upload(name=name, expected=400)
|
||||
self.assertEqual(self.upload(name="я" * 255)["json"]["filename"], "я" * 255)
|
||||
|
||||
def test_corrupt_images_mime_and_multipart(self):
|
||||
png, jpeg = image_bytes(), image_bytes("JPEG")
|
||||
for content, media in ((b"", "image/png"), (b"not an image", "image/png"),
|
||||
(png[:-8], "image/png"), (jpeg[:-8], "image/jpeg"),
|
||||
(png, "image/jpeg"), (jpeg, "image/png"),
|
||||
(image_bytes("GIF"), "image/png"), (png, "multipart/form-data")):
|
||||
self.upload(content, media, expected=415)
|
||||
|
||||
def test_byte_limit_and_original_at_exact_boundary(self):
|
||||
raw = padded_png(10485760)
|
||||
att = self.upload(raw)["json"]
|
||||
downloaded = self.client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=self.bob)
|
||||
self.assertEqual(downloaded["bytes"], raw)
|
||||
self.upload(raw + b"x", expected=413)
|
||||
|
||||
def test_chunked_body_cannot_bypass_size_limit(self):
|
||||
def blocks():
|
||||
for _ in range(161):
|
||||
yield b"x" * 65536
|
||||
self.upload(blocks(), expected=413)
|
||||
|
||||
def test_pixel_boundary_and_decompression_bomb(self):
|
||||
self.upload(oversized_pixels(), expected=413)
|
||||
self.assertEqual(self.upload(image_bytes(size=(8000, 5000)))["json"]["status"], "ready")
|
||||
|
||||
def test_attachment_access_and_unknown_ids(self):
|
||||
att = self.upload()["json"]
|
||||
for suffix in ("", "/content"):
|
||||
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, actor=self.eve)
|
||||
self.client.call("GET", "/api/v1/attachments/" + str(uuid4()) + suffix, 404, actor=self.alice)
|
||||
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 401)
|
||||
self.upload(actor=self.eve, expected=404)
|
||||
|
||||
def test_messages_keep_attachment_order_and_allow_empty_text(self):
|
||||
ids = [self.upload()["json"]["id"] for _ in range(2)]
|
||||
for text in ("", " \t\n", "с картинками"):
|
||||
message = self.client.message(self.bob, self.chat, text, attachments=ids[::-1])["json"]
|
||||
self.assertEqual(message["attachment_ids"], ids[::-1])
|
||||
self.assertEqual(message["text"], text)
|
||||
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
|
||||
self.assertEqual([m["attachment_ids"] for m in page["items"]], [ids[::-1]] * 3)
|
||||
|
||||
def test_bad_attachment_list_and_other_chat_do_not_create_messages(self):
|
||||
att = self.upload()["json"]["id"]
|
||||
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
|
||||
foreign = self.client.attachment(self.alice, other)[0]["id"]
|
||||
for ids, status in (([att, att], 400), ([str(uuid4()) for _ in range(11)], 400),
|
||||
(["bad"], 400), ([str(uuid4())], 404), ([foreign], 404)):
|
||||
self.client.call("POST", self.path + "/messages", status, actor=self.alice,
|
||||
body={"text": "test", "attachment_ids": ids}, headers={"Idempotency-Key": uuid4().hex})
|
||||
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
|
||||
self.assertEqual(page["items"], [])
|
||||
|
||||
def test_idempotency_defaults_and_attachment_replay(self):
|
||||
key = uuid4().hex
|
||||
original = self.client.message(self.alice, self.chat, "text", key=key)["json"]
|
||||
explicit = self.client.message(self.alice, self.chat, "text", key=key, attachments=[])["json"]
|
||||
self.assertEqual(original, explicit)
|
||||
att = self.upload()["json"]["id"]
|
||||
key = uuid4().hex
|
||||
def send(_):
|
||||
return Client(timeout=30).message(self.alice, self.chat, "", key=key, attachments=[att])
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(10)))
|
||||
self.assertEqual(len({r["json"]["id"] for r in responses}), 1)
|
||||
self.assertEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
|
||||
self.client.call("POST", self.path + "/messages", 409, actor=self.alice,
|
||||
body={"text": "different", "attachment_ids": [att]}, headers={"Idempotency-Key": key})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,140 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from helpers import Client, project_name
|
||||
|
||||
|
||||
class IdempotencyTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:18104"))
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
|
||||
def history(self):
|
||||
return self.client.call("GET", self.path + "?limit=100", actor=self.alice, schema="MessagePage")["json"]["items"]
|
||||
|
||||
def sql(self, statement):
|
||||
project = project_name()
|
||||
command = ["docker", "compose", "--project-name", project, "--env-file", ".env",
|
||||
"exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-v", "ON_ERROR_STOP=1", "-At", "-c", statement]
|
||||
result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8")
|
||||
if result.returncode:
|
||||
raise AssertionError("Database test command failed")
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_key_required_and_format(self):
|
||||
for key in (None, "", "two words", "a/b", "é", "a" * 129):
|
||||
headers = {} if key is None else {"Idempotency-Key": key}
|
||||
self.client.call("POST", self.path, 400, actor=self.alice, body={"text": "test"}, headers=headers)
|
||||
for key in ("a", ".:_-", "a" * 128):
|
||||
self.client.message(self.alice, self.chat, key, key=key)
|
||||
self.assertEqual(len(self.history()), 3)
|
||||
|
||||
def test_replay_normalizes_json(self):
|
||||
key = uuid4().hex
|
||||
text = "Привет 👋"
|
||||
first = self.client.message(self.alice, self.chat, text, key=key)
|
||||
raw = json.dumps({"text": text}, ensure_ascii=True, indent=4).encode("ascii")
|
||||
second = self.client.call("POST", self.path, 201, actor=self.alice, raw=raw,
|
||||
headers={"Idempotency-Key": key, "Content-Type": "application/json"}, schema="Message")
|
||||
self.assertEqual(first["json"], second["json"])
|
||||
self.assertNotEqual(first["headers"]["X-Request-Id"], second["headers"]["X-Request-Id"])
|
||||
self.assertEqual(len(self.history()), 1)
|
||||
|
||||
def test_different_body_conflicts(self):
|
||||
key = uuid4().hex
|
||||
original = self.client.message(self.alice, self.chat, "first", key=key)["json"]
|
||||
self.client.call("POST", self.path, 409, actor=self.alice,
|
||||
body={"text": "second"}, headers={"Idempotency-Key": key})
|
||||
self.assertEqual(self.client.message(self.alice, self.chat, "first", key=key)["json"], original)
|
||||
self.assertEqual(self.history(), [original])
|
||||
|
||||
def test_twenty_concurrent_requests_use_both_replicas(self):
|
||||
key = uuid4().hex
|
||||
def send(_):
|
||||
return Client(self.client.base).message(self.alice, self.chat, "one message", key=key)
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
responses = list(pool.map(send, range(20)))
|
||||
self.assertEqual(len({item["json"]["id"] for item in responses}), 1)
|
||||
self.assertEqual(len({item["headers"]["X-Instance-Id"] for item in responses}), 2)
|
||||
self.assertTrue(all(item["json"] == responses[0]["json"] for item in responses))
|
||||
self.assertEqual(self.history(), [responses[0]["json"]])
|
||||
|
||||
def test_scope_is_user_and_chat_not_session(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "shared", key=key)["json"]
|
||||
second = self.client.message(self.bob, self.chat, "shared", key=key)["json"]
|
||||
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
|
||||
third = self.client.message(self.alice, other, "shared", key=key)["json"]
|
||||
self.assertEqual(len({first["id"], second["id"], third["id"]}), 3)
|
||||
source = self.alice["registration"]
|
||||
value = base64.b64encode((source["username"] + ":" + source["password"]).encode()).decode()
|
||||
session = self.client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers={"Authorization": "Basic " + value}, schema="Session")["json"]
|
||||
actor = {"id": self.alice["id"], "token": session["token"]}
|
||||
self.assertEqual(self.client.message(actor, self.chat, "shared", key=key)["json"], first)
|
||||
|
||||
def test_replay_still_checks_access_and_session(self):
|
||||
key = uuid4().hex
|
||||
self.client.message(self.alice, self.chat, "private", key=key)
|
||||
self.client.call("POST", self.path, 404, actor=self.eve,
|
||||
body={"text": "private"}, headers={"Idempotency-Key": key})
|
||||
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
|
||||
self.client.call("POST", self.path, 401, actor=self.alice,
|
||||
body={"text": "private"}, headers={"Idempotency-Key": key})
|
||||
|
||||
def test_failure_rolls_back_message_and_key(self):
|
||||
key = "fault-" + uuid4().hex
|
||||
constraint = "test_reject_" + uuid4().hex[:12]
|
||||
self.sql("ALTER TABLE idempotency_keys ADD CONSTRAINT " + constraint
|
||||
+ " CHECK(request_key <> '" + key + "') NOT VALID")
|
||||
try:
|
||||
self.client.call("POST", self.path, 500, actor=self.alice,
|
||||
body={"text": "rollback"}, headers={"Idempotency-Key": key})
|
||||
self.assertEqual(self.history(), [])
|
||||
self.assertEqual(self.sql("SELECT count(*) FROM idempotency_keys WHERE request_key='" + key + "'"), "0")
|
||||
finally:
|
||||
self.sql("ALTER TABLE idempotency_keys DROP CONSTRAINT " + constraint)
|
||||
result = self.client.message(self.alice, self.chat, "rollback", key=key)["json"]
|
||||
self.assertEqual(self.client.message(self.alice, self.chat, "rollback", key=key)["json"], result)
|
||||
self.assertEqual(self.history(), [result])
|
||||
|
||||
def test_retention_and_expired_key_reuse(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "old", key=key)["json"]
|
||||
retained = self.sql("SELECT expires_at-created_at > INTERVAL '23 hours 59 minutes 59 seconds'"
|
||||
+ " FROM idempotency_keys WHERE request_key='" + key + "'")
|
||||
self.assertEqual(retained, "t")
|
||||
self.sql("UPDATE idempotency_keys SET expires_at=created_at + INTERVAL '1 microsecond'"
|
||||
+ " WHERE request_key='" + key + "'")
|
||||
second = self.client.message(self.alice, self.chat, "new", key=key)["json"]
|
||||
self.assertNotEqual(first["id"], second["id"])
|
||||
self.assertEqual(self.history(), [first, second])
|
||||
|
||||
def test_same_session_on_both_instances(self):
|
||||
responses = [self.client.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
|
||||
for _ in range(12)]
|
||||
self.assertEqual(len({item["headers"]["X-Instance-Id"] for item in responses}), 2)
|
||||
self.assertTrue(all(item["json"] == self.alice["user"] for item in responses))
|
||||
|
||||
def test_invalid_body_does_not_reserve_key(self):
|
||||
key = uuid4().hex
|
||||
self.client.call("POST", self.path, 400, actor=self.alice,
|
||||
body={"text": ""}, headers={"Idempotency-Key": key})
|
||||
result = self.client.message(self.alice, self.chat, "fixed", key=key)["json"]
|
||||
self.assertEqual(self.history(), [result])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,96 @@
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from helpers import Client
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
value = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + value}
|
||||
|
||||
|
||||
class SessionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:18104"))
|
||||
self.actor = self.client.user("auth")
|
||||
|
||||
def register(self, password):
|
||||
body = {"username": "p_" + uuid4().hex[:20], "display_name": "Пароль", "password": password}
|
||||
user = self.client.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
session = self.client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(body["username"], password), schema="Session")["json"]
|
||||
self.assertEqual(session["user"], user)
|
||||
self.assertEqual(set(session), {"token", "token_type", "expires_at", "user"})
|
||||
self.assertTrue(re.fullmatch(r"[A-Za-z0-9_-]{43}", session["token"]), "Invalid token format")
|
||||
return body, session
|
||||
|
||||
def test_password_required_and_limits(self):
|
||||
source = self.actor["registration"]
|
||||
for password in ("x" * 11, "x" * 129, " " * 12, None, 123, True, "a" * 12 + "\x00"):
|
||||
body = {**source, "username": "p_" + uuid4().hex[:20], "password": password}
|
||||
self.client.call("POST", "/api/v1/users", 400, body=body)
|
||||
missing = {key: value for key, value in source.items() if key != "password"}
|
||||
self.client.call("POST", "/api/v1/users", 400, body=missing)
|
||||
raw = json.dumps({**source, "username": "p_" + uuid4().hex[:20], "password": "\ud800" * 12}).encode()
|
||||
self.client.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
|
||||
|
||||
def test_password_boundaries_unicode_colon_spaces(self):
|
||||
for password in ("x" * 12, "🙂" * 127 + ":", " Привет:пароль🙂 "):
|
||||
body, session = self.register(password)
|
||||
actor = {"id": session["user"]["id"], "token": session["token"]}
|
||||
self.client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
changed = password.strip() if password != password.strip() else password + "!"
|
||||
self.client.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers=basic(body["username"], changed))
|
||||
|
||||
def test_wrong_and_unknown_credentials(self):
|
||||
source = self.actor["registration"]
|
||||
wrong = self.client.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers=basic(source["username"], "wrong-password-123"))
|
||||
unknown = self.client.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers=basic("unknown_" + uuid4().hex[:12], source["password"]))
|
||||
self.assertEqual(wrong["json"]["error"]["message"], unknown["json"]["error"]["message"])
|
||||
self.assertEqual(wrong["headers"]["WWW-Authenticate"], 'Basic realm="messenger", charset="UTF-8"')
|
||||
|
||||
def test_malformed_basic_and_body(self):
|
||||
for value in ("", "Basic", "Basic !!!", "Bearer " + self.actor["token"],
|
||||
"Basic " + base64.b64encode(b"missing-colon").decode(),
|
||||
"Basic " + base64.b64encode(b"\xff:some-password").decode()):
|
||||
self.client.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": value})
|
||||
source = self.actor["registration"]
|
||||
self.client.call("POST", "/api/v1/auth/sessions", 400, body={},
|
||||
headers=basic(source["username"], source["password"]))
|
||||
|
||||
def test_only_bearer_identifies_user(self):
|
||||
source = self.actor["registration"]
|
||||
for value in ("", "Bearer", "Bearer bad", "Bearer " + "x" * 43,
|
||||
basic(source["username"], source["password"])["Authorization"]):
|
||||
self.client.call("GET", "/api/v1/users/me", 401, headers={"Authorization": value})
|
||||
self.client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": self.actor["id"]})
|
||||
other = self.client.user("other")
|
||||
result = self.client.call("GET", "/api/v1/users/me", actor=self.actor,
|
||||
headers={"X-User-Id": other["id"]}, schema="User")
|
||||
self.assertEqual(result["json"]["id"], self.actor["id"])
|
||||
self.client.call("GET", "/api/v1/users/me", schema="User",
|
||||
headers={"Authorization": "bEaReR " + self.actor["token"]})
|
||||
|
||||
def test_logout_only_revokes_current_session(self):
|
||||
source = self.actor["registration"]
|
||||
second = self.client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(source["username"], source["password"]), schema="Session")["json"]
|
||||
other_session = {"id": self.actor["id"], "token": second["token"]}
|
||||
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.actor)
|
||||
for method, path in (("GET", "/api/v1/users/me"), ("DELETE", "/api/v1/auth/sessions/current")):
|
||||
self.client.call(method, path, 401, actor=self.actor)
|
||||
self.client.call("GET", "/api/v1/users/me", actor=other_session, schema="User")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user