forked from mtusi2026/mtusi2026lab4
Перенос исправления PR #99 (lab3): строки с U+0000 вместо 500
Expand-миграция 0005 (*_raw bytea для text, display_name, title), app/pgtext.py, тест test_nul_in_text_roundtrip в регрессии lab3, раздел в REPORT.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,12 @@
|
||||
- Commit/PR: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/115 (ветка `solution/bvt2304-zaporozhets`, коммит 2dca5c1)
|
||||
- Использованные источники, библиотеки и помощь ИИ: документация AWS S3 (object uploads, bucket policy), RustFS (docs.rustfs.com, переменные `RUSTFS_*`), спецификация PNG (IHDR, IDAT, Adam7), Pillow (lazy open, `verify`, `draft`, `MAX_IMAGE_PIXELS`), Docker Compose (secrets, healthcheck, `service_completed_successfully`). Библиотеки: FastAPI 0.115, uvicorn 0.34, asyncpg 0.30, argon2-cffi 23.1, redis-py 5.2, **minio-py 7.2.18** (S3-клиент), **Pillow 11.3.0**. Код, конфигурации и тесты написаны с помощью ИИ-ассистента (Claude); решения разобраны и проверены автором.
|
||||
|
||||
## Исправления по замечаниям преподавателя
|
||||
|
||||
| Замечание | Причина | Исправление | Проверка |
|
||||
| --- | --- | --- | --- |
|
||||
| PR lab3 #99, `app/main.py:380`: `{"text":"abc\u0000def"}` с действующей сессией и новым ключом возвращает 500 вместо 201 | Тип `text` в PostgreSQL не может хранить байт 0x00, INSERT падал с ошибкой кодировки. Та же ошибка была у `display_name` и `title` чата | Миграция `migrations/0005_nul_safe_text.sql` (только expand) добавляет nullable `display_name_raw`, `title_raw`, `text_raw bytea`. Если строка содержит U+0000, в `*_raw` пишутся её точные UTF-8 байты, а в основной столбец — та же строка с U+FFFD вместо U+0000: длина не меняется, CHECK и предыдущая версия при rolling update продолжают работать. При чтении API отдаёт точную строку из `*_raw` (`app/pgtext.py`). Fingerprint идемпотентности считается по исходной строке | `test_nul_in_text_roundtrip`: 201, точный текст в ответе, в истории и в идемпотентном повторе; другой текст с тем же ключом → 409; `display_name` и `title` с NUL сохраняются точно (`evidence/student-tests.txt`) |
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
**Нужно:** Docker Engine/Desktop с Compose v2.20+ (проверено: Docker 29.8.2, Compose 5.6.0, Windows 11 + Docker Desktop, WSL2) и POSIX-shell (Linux/macOS или Git Bash). Python и make на хосте **не нужны**: проверки запускаются в сервисе `tester`.
|
||||
|
||||
+16
-13
@@ -21,7 +21,7 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from . import config, images, lifecycle, validation as v
|
||||
from . import config, pgtext, images, lifecycle, validation as v
|
||||
from .db import DB_UNAVAILABLE, Database
|
||||
from .errors import (ApiError, error_response, invalid, not_found, request_id_var,
|
||||
unauthorized_basic, unauthorized_bearer, unavailable)
|
||||
@@ -131,17 +131,17 @@ def ts(value: datetime) -> str:
|
||||
|
||||
def user_json(row) -> dict:
|
||||
return {'id': str(row['id']), 'username': row['username'],
|
||||
'display_name': row['display_name'], 'created_at': ts(row['created_at'])}
|
||||
'display_name': pgtext.join(row['display_name'], row['display_name_raw']), 'created_at': ts(row['created_at'])}
|
||||
|
||||
|
||||
def chat_json(row) -> dict:
|
||||
return {'id': str(row['id']), 'title': row['title'],
|
||||
return {'id': str(row['id']), 'title': pgtext.join(row['title'], row['title_raw']),
|
||||
'member_ids': [str(m) for m in row['member_ids']], 'created_at': ts(row['created_at'])}
|
||||
|
||||
|
||||
def message_json(row) -> dict:
|
||||
return {'id': str(row['id']), 'chat_id': str(row['chat_id']), 'sender_id': str(row['sender_id']),
|
||||
'text': row['text'], 'created_at': ts(row['created_at']),
|
||||
'text': pgtext.join(row['text'], row['text_raw']), 'created_at': ts(row['created_at']),
|
||||
'attachment_ids': [str(a) for a in row['attachment_ids']]}
|
||||
|
||||
|
||||
@@ -154,12 +154,12 @@ def attachment_json(row) -> dict:
|
||||
'created_at': ts(row['created_at']), 'updated_at': ts(row['updated_at'])}
|
||||
|
||||
|
||||
USER_COLUMNS = 'id, username, display_name, created_at'
|
||||
CHAT_COLUMNS = ('c.id, c.title, c.created_at, '
|
||||
USER_COLUMNS = 'id, username, display_name, display_name_raw, created_at'
|
||||
CHAT_COLUMNS = ('c.id, c.title, c.title_raw, c.created_at, '
|
||||
'ARRAY(SELECT cm.user_id FROM chat_members cm WHERE cm.chat_id = c.id ORDER BY cm.user_id) AS member_ids')
|
||||
MESSAGE_ATTACHMENTS = ('ARRAY(SELECT ma.attachment_id FROM message_attachments ma '
|
||||
'WHERE ma.message_id = {m}.id ORDER BY ma.position) AS attachment_ids')
|
||||
MESSAGE_COLUMNS = 'id, chat_id, sender_id, text, created_at, ' + MESSAGE_ATTACHMENTS.format(m='messages')
|
||||
MESSAGE_COLUMNS = 'id, chat_id, sender_id, text, text_raw, created_at, ' + MESSAGE_ATTACHMENTS.format(m='messages')
|
||||
ATTACHMENT_COLUMNS = ('a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, '
|
||||
'a.status, a.object_key, a.created_at, a.updated_at')
|
||||
|
||||
@@ -227,8 +227,9 @@ async def create_user(request: Request):
|
||||
try:
|
||||
async with db.connection() as conn:
|
||||
row = await conn.fetchrow(
|
||||
f'INSERT INTO users (username, display_name, password_hash) VALUES ($1, $2, $3) RETURNING {USER_COLUMNS}',
|
||||
username, display_name, password_hash)
|
||||
'INSERT INTO users (username, display_name, display_name_raw, password_hash) '
|
||||
f'VALUES ($1, $2, $3, $4) RETURNING {USER_COLUMNS}',
|
||||
username, *pgtext.split(display_name), password_hash)
|
||||
except asyncpg.UniqueViolationError:
|
||||
# Гонка двух одинаковых регистраций решается UNIQUE-индексом: COMMIT пройдёт только у одной.
|
||||
raise ApiError(409, 'conflict', 'username уже занят') from None
|
||||
@@ -293,7 +294,8 @@ async def create_chat(request: Request):
|
||||
# Одна транзакция: чат и все участники появляются вместе или не появляются вовсе.
|
||||
async with conn.transaction():
|
||||
chat = await conn.fetchrow(
|
||||
'INSERT INTO chats (title, created_by) VALUES ($1, $2) RETURNING id, created_at', title, user_id)
|
||||
'INSERT INTO chats (title, title_raw, created_by) VALUES ($1, $2, $3) RETURNING id, created_at',
|
||||
*pgtext.split(title), user_id)
|
||||
added = await conn.fetch(
|
||||
'INSERT INTO chat_members (chat_id, user_id) '
|
||||
'SELECT $1, u.id FROM users u WHERE u.id = ANY($2::uuid[]) RETURNING user_id',
|
||||
@@ -413,8 +415,9 @@ async def create_message(chat_id: str, request: Request):
|
||||
if found != len(attachments):
|
||||
raise not_found()
|
||||
row = await conn.fetchrow(
|
||||
'INSERT INTO messages (id, chat_id, sender_id, text) VALUES ($1, $2, $3, $4) '
|
||||
'RETURNING id, chat_id, sender_id, text, created_at', message_id, cid, user_id, text)
|
||||
'INSERT INTO messages (id, chat_id, sender_id, text, text_raw) VALUES ($1, $2, $3, $4, $5) '
|
||||
'RETURNING id, chat_id, sender_id, text, text_raw, created_at',
|
||||
message_id, cid, user_id, *pgtext.split(text))
|
||||
if attachments:
|
||||
await conn.execute(
|
||||
'INSERT INTO message_attachments (message_id, attachment_id, chat_id, position) '
|
||||
@@ -423,7 +426,7 @@ async def create_message(chat_id: str, request: Request):
|
||||
row = {**dict(row), 'attachment_ids': attachments}
|
||||
else:
|
||||
row = await conn.fetchrow(
|
||||
'SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at, '
|
||||
'SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.text_raw, m.created_at, '
|
||||
+ MESSAGE_ATTACHMENTS.format(m='m') + ' '
|
||||
'FROM idempotency_keys k JOIN messages m ON m.id = k.message_id '
|
||||
'WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3', user_id, cid, key)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Точное хранение строк с U+0000 в PostgreSQL.
|
||||
|
||||
Тип text в PostgreSQL не может содержать байт 0x00, а JSON-контракт допускает "\\u0000" в тексте
|
||||
сообщения, display_name и title. Раньше такой INSERT падал с 500 (замечание к lab3, PR #99).
|
||||
|
||||
Схема (только expand, совместима с предыдущей версией при rolling update):
|
||||
- столбец text/display_name/title получает ту же строку, где U+0000 заменён на U+FFFD: длина в code points
|
||||
не меняется, поэтому CHECK char_length и прежние реплики продолжают работать;
|
||||
- столбец *_raw bytea получает точные UTF-8 байты исходной строки, но ТОЛЬКО если в ней был U+0000
|
||||
(иначе NULL, лишнего места не занимает);
|
||||
- при чтении API возвращает декодированный *_raw, если он есть, иначе обычный столбец.
|
||||
"""
|
||||
|
||||
|
||||
def split(value: str) -> tuple[str, bytes | None]:
|
||||
if '\x00' in value:
|
||||
return value.replace('\x00', '\ufffd'), value.encode('utf-8')
|
||||
return value, None
|
||||
|
||||
|
||||
def join(text: str, raw: bytes | None) -> str:
|
||||
return bytes(raw).decode('utf-8') if raw is not None else text
|
||||
@@ -0,0 +1,7 @@
|
||||
-- 0005_nul_safe_text: точное хранение строк с U+0000 (замечание к lab3, PR #99: "abc\u0000def" давал 500).
|
||||
-- PostgreSQL text не хранит 0x00. Если строка содержит U+0000, её точные UTF-8 байты пишутся в *_raw,
|
||||
-- а в основной столбец — та же строка с U+FFFD вместо U+0000 (см. app/pgtext.py).
|
||||
-- Только expand: столбцы nullable, версия без них продолжает работать на этой схеме.
|
||||
ALTER TABLE users ADD COLUMN display_name_raw bytea CHECK (octet_length(display_name_raw) <= 400);
|
||||
ALTER TABLE chats ADD COLUMN title_raw bytea CHECK (octet_length(title_raw) <= 400);
|
||||
ALTER TABLE messages ADD COLUMN text_raw bytea CHECK (octet_length(text_raw) <= 16000);
|
||||
@@ -249,15 +249,42 @@ def test_infrastructure_rules(_c: Client):
|
||||
mounts = {m['Destination'] for m in cfg['Mounts']}
|
||||
check(mounts <= {'/run/secrets/database_url', '/run/secrets/cache_url', '/run/secrets/s3_access_key_id',
|
||||
'/run/secrets/s3_secret_access_key'}, f'api has unexpected mounts {mounts}') # lab4: + S3
|
||||
check(sql('SELECT count(*) FROM schema_migrations') == '4', 'unexpected migration count') # lab4: + 0004_attachments
|
||||
check(sql('SELECT count(*) FROM schema_migrations') == '5', 'unexpected migration count') # lab4: + 0004_attachments, 0005_nul_safe_text
|
||||
with urllib.request.urlopen(os.environ.get('LB_STATS_URL', 'http://lb:8404/stats') + ';csv', timeout=2) as r:
|
||||
text = r.read().decode()
|
||||
check(',UP,' in text or ',UP ' in text, 'LB stats show no UP backend')
|
||||
|
||||
|
||||
def test_nul_in_text_roundtrip(c: Client):
|
||||
"""Замечание к PR #99: {"text":"abc\\u0000def"} давал 500. Строка с U+0000 сохраняется точно."""
|
||||
alice, bob, _eve, _chat = c.bootstrap()
|
||||
text = 'abc\u0000def'
|
||||
chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'чат\u0000NUL', 'member_ids': [alice['id'], bob['id']]}, schema='Chat')['json']
|
||||
check(chat['title'] == 'чат\u0000NUL', 'title with NUL changed in response')
|
||||
got = c.call('GET', '/api/v1/chats/' + chat['id'], actor=bob, schema='Chat')['json']
|
||||
check(got['title'] == 'чат\u0000NUL', 'title with NUL changed on read')
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, text, key=key)['json']
|
||||
check(first['text'] == text, 'response text differs')
|
||||
replay = c.message(alice, chat, text, key=key)['json']
|
||||
check(replay == first, 'idempotent replay differs')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'abc\ufffddef'}, headers={'Idempotency-Key': key}) # U+FFFD — другой текст
|
||||
c.message(alice, chat, '\u0000') # только NUL — не пробел, допустим
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob,
|
||||
schema='MessagePage')['json']['items']
|
||||
check([m['text'] for m in history] == [text, '\u0000'], 'history lost NUL')
|
||||
name = 'Имя\u0000Фамилия'
|
||||
user = c.call('POST', '/api/v1/users', 201, body={'username': 'nul_' + uuid.uuid4().hex[:12],
|
||||
'display_name': name, 'password': 'T3st-' + uuid.uuid4().hex}, schema='User')['json']
|
||||
check(user['display_name'] == name, 'display_name with NUL changed')
|
||||
|
||||
|
||||
TESTS = [test_session_across_replicas, test_same_key_concurrent_across_replicas,
|
||||
test_same_key_concurrent_different_bodies, test_key_scope_and_format, test_replay_rechecks_session,
|
||||
test_transient_failure_not_recorded, test_sigterm_drain, test_infrastructure_rules]
|
||||
test_transient_failure_not_recorded, test_sigterm_drain, test_infrastructure_rules,
|
||||
test_nul_in_text_roundtrip]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
Reference in New Issue
Block a user