forked from mtusi2026/mtusi2026lab2
186 lines
8.8 KiB
Python
186 lines
8.8 KiB
Python
"""Некорректные запросы: всегда конверт контракта, никогда — утёкшее значение.
|
|
|
|
Контракт указывает 400 для любого тела, которое сервер отклоняет, и нигде не
|
|
содержит 422, поэтому отклонённое поле не должно всплывать как стандартный
|
|
ответ валидации FastAPI. В одном из таких тел передаётся пароль — именно за
|
|
этим полем и стоит следить.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import unittest
|
|
import uuid
|
|
|
|
import harness
|
|
|
|
|
|
class RequestBodies(unittest.TestCase):
|
|
"""Некорректный JSON и некорректные поля одинаково возвращаются как 400 invalid_request."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.api = harness.client()
|
|
cls.alice = harness.account(cls.api, "val_alice")
|
|
|
|
def assert_invalid(self, response):
|
|
self.assertEqual(response["status"], 400)
|
|
self.assertEqual(response["json"]["error"]["code"], "invalid_request")
|
|
self.assertNotIn("detail", response["json"], "утёк стандартный ответ FastAPI")
|
|
return response
|
|
|
|
def test_unknown_json_field_is_refused(self):
|
|
body = {"username": harness.unique("extra"), "display_name": "Студент",
|
|
"password": harness.fresh_password(), "is_admin": True}
|
|
self.assert_invalid(self.api.call("POST", "/api/v1/users", [400], body=body))
|
|
|
|
def test_broken_json_is_refused_without_echoing_it(self):
|
|
secret = harness.fresh_password()
|
|
raw = json.dumps({"username": "broken", "password": secret}).encode()[:-1]
|
|
response = self.api.call("POST", "/api/v1/users", [400], raw=raw,
|
|
headers={"Content-Type": "application/json"})
|
|
self.assert_invalid(response)
|
|
self.assertNotIn(secret, response["bytes"].decode("utf-8", "replace"))
|
|
|
|
def test_missing_required_fields(self):
|
|
cases = (
|
|
("/api/v1/users", {"username": harness.unique("nofield")}),
|
|
("/api/v1/chats", {"title": "Чат"}),
|
|
)
|
|
for path, body in cases:
|
|
with self.subTest(path=path):
|
|
self.assert_invalid(self.api.call("POST", path, [400], actor=self.alice, body=body))
|
|
|
|
def test_username_pattern(self):
|
|
for username in ("ab", "A" * 3, "a" * 33, "with-dash", "with space", "кириллица"):
|
|
with self.subTest(username=username):
|
|
body = {"username": username, "display_name": "Студент",
|
|
"password": harness.fresh_password()}
|
|
self.assert_invalid(self.api.call("POST", "/api/v1/users", [400], body=body))
|
|
|
|
def test_display_name_and_title_limits(self):
|
|
cases = (
|
|
("/api/v1/users", {"username": harness.unique("long"), "display_name": "x" * 101,
|
|
"password": harness.fresh_password()}),
|
|
("/api/v1/chats", {"title": "x" * 101, "member_ids": [self.alice["id"]]}),
|
|
("/api/v1/chats", {"title": " ", "member_ids": [self.alice["id"]]}),
|
|
("/api/v1/chats", {"title": "", "member_ids": [self.alice["id"]]}),
|
|
)
|
|
for path, body in cases:
|
|
with self.subTest(path=path, length=len(str(body))):
|
|
self.assert_invalid(self.api.call("POST", path, [400], actor=self.alice, body=body))
|
|
|
|
def test_nul_is_refused_before_it_reaches_the_store(self):
|
|
"""U+0000 не хранится в `text`: это 400, а не ложная недоступность базы."""
|
|
nul = "x\u0000y"
|
|
self.assert_invalid(self.api.call(
|
|
"POST", "/api/v1/users", [400],
|
|
body={"username": harness.unique("nul"), "display_name": nul,
|
|
"password": harness.fresh_password()},
|
|
))
|
|
self.assert_invalid(self.api.call(
|
|
"POST", "/api/v1/chats", [400], actor=self.alice,
|
|
body={"title": nul, "member_ids": [self.alice["id"]]},
|
|
))
|
|
chat = harness.chat(self.api, self.alice, [], title="NUL в сообщении")
|
|
self.assert_invalid(self.api.call(
|
|
"POST", "/api/v1/chats/" + chat["id"] + "/messages", [400],
|
|
actor=self.alice, body={"text": nul},
|
|
))
|
|
|
|
def test_message_text_limits(self):
|
|
chat = harness.chat(self.api, self.alice, [], title="Лимиты текста")
|
|
for text in ("x" * 4001, " ", ""):
|
|
with self.subTest(length=len(text)):
|
|
self.assert_invalid(self.api.call(
|
|
"POST", "/api/v1/chats/" + chat["id"] + "/messages", [400],
|
|
actor=self.alice, body={"text": text},
|
|
))
|
|
self.assertEqual(len(harness.send(self.api, self.alice, chat, "x" * 4000)["text"]), 4000)
|
|
|
|
def test_sender_id_cannot_be_injected(self):
|
|
chat = harness.chat(self.api, self.alice, [], title="Отправитель")
|
|
self.assert_invalid(self.api.call(
|
|
"POST", "/api/v1/chats/" + chat["id"] + "/messages", [400], actor=self.alice,
|
|
body={"text": "Подмена", "sender_id": str(uuid.uuid4())},
|
|
))
|
|
|
|
def test_the_password_never_appears_in_an_error(self):
|
|
secret = harness.fresh_password()
|
|
body = {"username": harness.unique("leak"), "display_name": "x" * 101, "password": secret}
|
|
response = self.api.call("POST", "/api/v1/users", [400], body=body)
|
|
self.assert_invalid(response)
|
|
raw = response["bytes"].decode("utf-8", "replace")
|
|
self.assertNotIn(secret, raw, "пароль вернулся в ответе")
|
|
self.assertNotIn(secret, response["json"]["error"]["message"])
|
|
|
|
|
|
class QueryParameters(unittest.TestCase):
|
|
"""limit и cursor проверяются до выполнения любого SQL."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.api = harness.client()
|
|
cls.alice = harness.account(cls.api, "val_page")
|
|
cls.chat = harness.chat(cls.api, cls.alice, [], title="Параметры")
|
|
|
|
def test_limit_bounds(self):
|
|
for limit, expected in ((0, 400), (101, 400), (1, 200), (100, 200)):
|
|
with self.subTest(limit=limit):
|
|
self.api.call("GET", "/api/v1/chats?limit=%d" % limit, expected,
|
|
actor=self.alice, schema="ChatPage")
|
|
self.api.call(
|
|
"GET", "/api/v1/chats/%s/messages?limit=%d" % (self.chat["id"], limit),
|
|
expected, actor=self.alice, schema="MessagePage",
|
|
)
|
|
|
|
def test_non_numeric_limit(self):
|
|
self.assert_invalid_route("/api/v1/chats?limit=many")
|
|
self.assert_invalid_route("/api/v1/chats?limit=")
|
|
|
|
def assert_invalid_route(self, path):
|
|
response = self.api.call("GET", path, [400], actor=self.alice)
|
|
self.assertEqual(response["json"]["error"]["code"], "invalid_request")
|
|
self.assertNotIn("detail", response["json"])
|
|
|
|
def test_invalid_chat_id(self):
|
|
for chat_id in ("not-a-uuid", "1234", "1-2-3-4", "x" * 36):
|
|
with self.subTest(chat_id=chat_id):
|
|
self.api.call("GET", "/api/v1/chats/" + chat_id, [400], actor=self.alice)
|
|
|
|
def test_tampered_cursor_is_refused(self):
|
|
harness.chat(self.api, self.alice, [], title="Второй чат для курсора")
|
|
page = self.api.call("GET", "/api/v1/chats?limit=1", 200, actor=self.alice,
|
|
schema="ChatPage")["json"]
|
|
cursor = page["next_cursor"]
|
|
self.assertIsNotNone(cursor)
|
|
middle = len(cursor) // 2
|
|
replaced = "A" if cursor[middle] != "A" else "B"
|
|
tampered = cursor[:middle] + replaced + cursor[middle + 1:]
|
|
self.assert_invalid_route("/api/v1/chats?limit=1&cursor=" + tampered)
|
|
|
|
def test_empty_cursor_is_refused(self):
|
|
self.assert_invalid_route("/api/v1/chats?limit=1&cursor=")
|
|
|
|
|
|
class Routing(unittest.TestCase):
|
|
"""Неизвестные маршруты и методы всё равно отвечают конвертом контракта."""
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.api = harness.client()
|
|
|
|
def test_unknown_route(self):
|
|
response = self.api.call("GET", "/api/v1/nothing-here", [404], headers={})
|
|
self.assertEqual(response["json"]["error"]["code"], "not_found")
|
|
|
|
def test_wrong_method(self):
|
|
for method, path in (("PATCH", "/api/v1/users/me"), ("PUT", "/health/live"),
|
|
("DELETE", "/api/v1/chats")):
|
|
with self.subTest(method=method, path=path):
|
|
response = self.api.call(method, path, [405], headers={})
|
|
self.assertEqual(response["json"]["error"]["code"], "invalid_request")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|