справление: U+0000 в строках сохраняется (bytea), DataError -> 400

This commit is contained in:
kalibr456
2026-10-09 18:30:42 +03:00
parent 8149a608f8
commit e17d883c15
10 changed files with 102 additions and 101 deletions
+18 -12
View File
@@ -1,10 +1,3 @@
"""Собственные тесты API (lab1 + lab2). Запуск одной командой при запущенном стенде:
python student-tests/test_api.py
Тесты lab1 переведены с X-User-Id на пароль и Bearer-токен. Добавлены тесты lab2:
вход по Basic, неверный пароль, logout, Bearer на всех защищённых запросах.
"""
import base64
import datetime as dt
import uuid
@@ -16,7 +9,6 @@ def parse_time(value):
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
# ---------- lab1 (перенесены, теперь с токенами) ----------
def test_duplicate_username():
body = {"username": "dup_" + uuid.uuid4().hex[:10], "display_name": "First user", "password": PASSWORD}
@@ -79,7 +71,6 @@ def test_pagination():
for i in range(3):
send(alice, other["id"], f"Other {i}")
first = call("GET", f"/api/v1/chats/{other['id']}/messages?limit=1", token=alice["token"]).json
# Курсор от другого чата и испорченный курсор — 400.
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor={first['next_cursor']}", 400, token=alice["token"])
call("GET", f"/api/v1/chats/{chat['id']}/messages?cursor=broken", 400, token=alice["token"])
print("PASS: pagination works across multiple pages, foreign cursor returns 400")
@@ -110,7 +101,23 @@ def test_unicode():
print("PASS: unicode text is stored as is")
# ---------- lab2: пароль, вход, Bearer, logout ----------
def test_nul_character_is_stored():
name, title, text = "A\u0000B", "Chat\u0000title", "hello\u0000world"
body = {"username": "nul_" + uuid.uuid4().hex[:10], "display_name": name, "password": "pass\u0000word-123"}
user = call("POST", "/api/v1/users", 201, body=body).json
check(user["display_name"] == name, "display_name with U+0000 changed")
token = login(body["username"], body["password"]).json["token"]
check(call("GET", "/api/v1/users/me", token=token).json["display_name"] == name, "display_name changed on read")
chat = call("POST", "/api/v1/chats", 201, token=token, body={"title": title, "member_ids": [user["id"]]}).json
check(chat["title"] == title, "title with U+0000 changed")
check(call("GET", f"/api/v1/chats/{chat['id']}", token=token).json["title"] == title, "title changed on read")
sent = call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, token=token, body={"text": text}).json
history = call("GET", f"/api/v1/chats/{chat['id']}/messages", token=token).json["items"]
check(sent["text"] == text and history[-1]["text"] == text, "text with U+0000 changed")
login("nul\u0000user", PASSWORD, expected=401)
print("PASS: strings with U+0000 are stored and returned as is")
def test_user_has_no_password():
body = {"username": "np_" + uuid.uuid4().hex[:10], "display_name": "No password", "password": PASSWORD}
@@ -155,7 +162,6 @@ def test_wrong_password():
wrong = login(user["username"], "Wrong-password-000", expected=401)
unknown = login("nobody_" + uuid.uuid4().hex[:8], PASSWORD, expected=401)
check(wrong.headers["www-authenticate"].lower().startswith("basic"), "login 401 must ask for Basic")
# Одинаковый ответ: по нему нельзя узнать, существует ли такой username.
check(wrong.json["error"]["message"] == unknown.json["error"]["message"], "different answers leak usernames")
print("PASS: wrong password and unknown user both return the same 401")
@@ -196,7 +202,6 @@ def test_x_user_id_ignored():
def test_auth_before_body():
alice = new_user("alice")
chat = new_chat(alice)
# Без токена всегда 401, даже если тело неверное или чат чужой: сначала «кто ты».
call("POST", f"/api/v1/chats/{chat['id']}/messages", 401, raw=b"not json")
call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
print("PASS: 401 comes before 400 and 404")
@@ -225,6 +230,7 @@ if __name__ == "__main__":
test_pagination,
test_chat_list_pagination,
test_unicode,
test_nul_character_is_stored,
test_user_has_no_password,
test_password_rules,
test_login_gives_token,