forked from mtusi2026/mtusi2026lab2
справление: U+0000 в строках сохраняется (bytea), DataError -> 400
This commit is contained in:
@@ -1,31 +1,24 @@
|
||||
-- Обоснование индекса истории messages_history (migrations/001_init.sql).
|
||||
-- Запуск: python student-tests/explain.py (результат -> evidence/explain-history.txt)
|
||||
--
|
||||
-- Всё в одной транзакции, в конце ROLLBACK: тестовые данные не остаются в базе,
|
||||
-- скрипт можно запускать сколько угодно раз.
|
||||
|
||||
\pset footer off
|
||||
BEGIN;
|
||||
|
||||
-- Тестовые данные: один большой чат на 15 000 сообщений и 50 маленьких по 100,
|
||||
-- всего 20 000 сообщений. Чужие сообщения в таблице есть, как в настоящей базе.
|
||||
CREATE TEMP TABLE seed_chats AS
|
||||
SELECT gen_random_uuid() AS id, n, CASE WHEN n = 0 THEN 15000 ELSE 100 END AS size
|
||||
FROM generate_series(0, 50) AS n;
|
||||
CREATE TEMP TABLE seed_user AS SELECT gen_random_uuid() AS id;
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
SELECT id, 'explain_' || substr(md5(random()::text), 1, 10), 'Explain', 'not-a-real-hash' FROM seed_user;
|
||||
INSERT INTO chats (id, title) SELECT id, 'explain ' || n FROM seed_chats;
|
||||
SELECT id, 'explain_' || substr(md5(random()::text), 1, 10), convert_to('Explain', 'UTF8'), 'not-a-real-hash'
|
||||
FROM seed_user;
|
||||
INSERT INTO chats (id, title) SELECT id, convert_to('explain ' || n, 'UTF8') FROM seed_chats;
|
||||
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM seed_chats c, seed_user u;
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), c.id, u.id, 'message ' || g,
|
||||
SELECT gen_random_uuid(), c.id, u.id, convert_to('message ' || g, 'UTF8'),
|
||||
timestamptz '2026-09-01 00:00:00+00' + g * interval '1 second'
|
||||
FROM seed_chats c, seed_user u, generate_series(1, c.size) AS g;
|
||||
ANALYZE messages;
|
||||
|
||||
SELECT id AS big_chat FROM seed_chats WHERE n = 0 \gset
|
||||
-- Курсор глубоко в истории: ключ (created_at, id) 10 000-го сообщения большого чата.
|
||||
SELECT created_at AS cursor_time, id AS cursor_id FROM messages
|
||||
WHERE chat_id = :'big_chat' ORDER BY created_at, id OFFSET 9999 LIMIT 1 \gset
|
||||
|
||||
|
||||
+18
-12
@@ -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,
|
||||
|
||||
@@ -1,14 +1,3 @@
|
||||
"""Проверки на уровне базы данных. Запуск при запущенном стенде:
|
||||
|
||||
python student-tests/test_db.py
|
||||
|
||||
SQL выполняется в контейнере postgres через `docker compose exec postgres psql`.
|
||||
1. Откат составной операции: чат с несуществующим участником -> 400, и в базе
|
||||
не остаётся ни чата, ни участников, хотя строка чата успела вставиться.
|
||||
2. База сама не даёт записать сообщение от не-участника (внешний ключ).
|
||||
3. Пароль хранится как хеш Argon2id, а не как текст или быстрый хеш.
|
||||
4. Миграции: после перезапуска API ничего не применяется повторно.
|
||||
"""
|
||||
import time
|
||||
import uuid
|
||||
|
||||
@@ -26,14 +15,12 @@ def test_create_chat_rolls_back():
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
inserted_before = int(sql_value("SELECT n_tup_ins FROM pg_stat_user_tables WHERE relname = 'chats'"))
|
||||
|
||||
# Второй участник не существует: INSERT чата пройдёт, INSERT участника упадёт на внешнем ключе.
|
||||
call("POST", "/api/v1/chats", 400, token=alice["token"],
|
||||
body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
|
||||
|
||||
left = sql_value(f"SELECT count(*) FROM chats WHERE title = '{title}'")
|
||||
orphans = sql_value("SELECT count(*) FROM chats c WHERE NOT EXISTS "
|
||||
"(SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)")
|
||||
# Статистика PostgreSQL считает и отменённые вставки; она обновляется с задержкой до ~1 с.
|
||||
inserted_after = inserted_before
|
||||
deadline = time.monotonic() + 15
|
||||
while inserted_after == inserted_before and time.monotonic() < deadline:
|
||||
@@ -48,7 +35,7 @@ def test_create_chat_rolls_back():
|
||||
|
||||
def test_message_needs_membership_in_db():
|
||||
code, _, error = psql("INSERT INTO messages (id, chat_id, sender_id, text) "
|
||||
f"VALUES ('{uuid.uuid4()}', '{uuid.uuid4()}', '{uuid.uuid4()}', 'direct insert')")
|
||||
f"VALUES ('{uuid.uuid4()}', '{uuid.uuid4()}', '{uuid.uuid4()}', convert_to('direct insert', 'UTF8'))")
|
||||
print(f"direct INSERT of a message from a non-member -> exit code {code}: {error.splitlines()[0] if error else ''}")
|
||||
check(code != 0 and "foreign key" in error, "database accepted a message from a non-member")
|
||||
print("PASS: the database itself rejects a message from a non-member")
|
||||
|
||||
Reference in New Issue
Block a user