forked from mtusi2026/mtusi2026lab3
Reject NUL input before authentication and text persistence
This commit is contained in:
@@ -1,15 +1,15 @@
|
||||
## 1. Identity — минимум уровня «3»
|
||||
|
||||
- [ ] 1.1 Добавить offline-регрессии NUL в Basic username и DisplayName, зафиксировать ожидаемые падения старой версии.
|
||||
- [ ] 1.2 Отклонять NUL до VerifyCredentials и записи пользователя; проверить unit-тестами парсер, guard и доменное значение.
|
||||
- [x] 1.1 Добавить offline-регрессии NUL в Basic username и DisplayName, зафиксировать ожидаемые падения старой версии.
|
||||
- [x] 1.2 Отклонять NUL до VerifyCredentials и записи пользователя; проверить unit-тестами парсер, guard и доменное значение.
|
||||
|
||||
## 2. Messaging — валидация и доступ
|
||||
|
||||
- [ ] 2.1 Добавить регрессии ChatTitle/MessageText, зафиксировать падения старой версии и отклонять NUL собственными ошибками зоны.
|
||||
- [ ] 2.2 Проверить offline отсутствие записи через MessageLog и сохранение приоритета доступа для чужого/несуществующего чата.
|
||||
- [x] 2.1 Добавить регрессии ChatTitle/MessageText, зафиксировать падения старой версии и отклонять NUL собственными ошибками зоны.
|
||||
- [x] 2.2 Проверить offline отсутствие записи через MessageLog и сохранение приоритета доступа для чужого/несуществующего чата.
|
||||
|
||||
## 3. Проверки и передача финальному агенту
|
||||
|
||||
- [ ] 3.1 Добавить HTTP-тесты NUL: одинаковый 401, отсутствие побочных записей, исправленный повтор с прежним ключом и 404 для постороннего; собрать их через pytest --collect-only без Docker.
|
||||
- [x] 3.1 Добавить HTTP-тесты NUL: одинаковый 401, отсутствие побочных записей, исправленный повтор с прежним ключом и 404 для постороннего; собрать их через pytest --collect-only без Docker.
|
||||
- [ ] 3.2 Выполнить unit-тесты и архитектурные проверки, make check, make validate, make lint и OpenSpec strict; сохранить команды, SHA и ограничения в новом evidence.
|
||||
- [ ] 3.3 Передать обязательные динамические проверки финальному агенту через evidence, синхронизировать спецификации и архивировать change.
|
||||
|
||||
@@ -30,6 +30,8 @@ class DisplayName:
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidUserData("поле display_name должно быть строкой")
|
||||
if "\x00" in self.value:
|
||||
raise InvalidUserData("поле display_name не может содержать NUL")
|
||||
if not self.value.strip():
|
||||
raise InvalidUserData("поле display_name не может быть пустым или состоять из пробелов")
|
||||
if len(self.value) > DISPLAY_NAME_MAX:
|
||||
|
||||
@@ -37,7 +37,7 @@ def basic_credentials(value: str) -> tuple[str, str] | None:
|
||||
except Base64Error, UnicodeDecodeError:
|
||||
return None
|
||||
username, separator, password = decoded.partition(":")
|
||||
if not separator or not username.isascii():
|
||||
if not separator or not username.isascii() or "\x00" in username:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ class ChatTitle:
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidChatData("поле title должно быть строкой")
|
||||
if "\x00" in self.value:
|
||||
raise InvalidChatData("поле title не может содержать NUL")
|
||||
if not self.value.strip():
|
||||
raise InvalidChatData("поле title не может быть пустым или состоять из пробелов")
|
||||
if len(self.value) > CHAT_TITLE_MAX:
|
||||
@@ -30,6 +32,8 @@ class MessageText:
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.value, str):
|
||||
raise InvalidMessageText("поле text должно быть строкой")
|
||||
if "\x00" in self.value:
|
||||
raise InvalidMessageText("поле text не может содержать NUL")
|
||||
if not self.value.strip():
|
||||
raise InvalidMessageText("поле text не может быть пустым или состоять из пробелов")
|
||||
if len(self.value) > MESSAGE_TEXT_MAX:
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient, Response
|
||||
|
||||
from conftest import PASSWORD, actor, basic, keyed, make_chat, new_user, register
|
||||
|
||||
NUL_TEXTS = ["\x00", "\x00abc", "abc\x00def", "abc\x00"]
|
||||
|
||||
|
||||
def rejected(response: Response, status: int, code: str) -> None:
|
||||
assert response.status_code == status, response.text
|
||||
assert response.headers["content-type"].startswith("application/json")
|
||||
assert response.headers["X-Instance-Id"]
|
||||
assert response.headers["X-Request-Id"]
|
||||
assert set(response.json()) == {"error"}
|
||||
error = response.json()["error"]
|
||||
assert set(error) == {"code", "message", "request_id"}
|
||||
assert error["code"] == code
|
||||
assert error["message"]
|
||||
assert error["request_id"] == response.headers["X-Request-Id"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("username", NUL_TEXTS)
|
||||
async def test_nul_basic_matches_wrong_password(client: AsyncClient, username: str) -> None:
|
||||
user = await register(client, "nul_login")
|
||||
responses = []
|
||||
for name, password in [(user["username"], "wrong-password"), (username, PASSWORD)]:
|
||||
response = await client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
headers={**basic(name, password), "X-Request-Id": "nul-login"},
|
||||
)
|
||||
rejected(response, 401, "unauthorized")
|
||||
assert response.headers["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"'
|
||||
responses.append(response.json())
|
||||
assert responses[0] == responses[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
async def test_nul_display_name_does_not_create_user(client: AsyncClient, raw: str) -> None:
|
||||
body = {**new_user("nul_display"), "display_name": raw}
|
||||
rejected(await client.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
response = await client.post("/api/v1/users", json={**body, "display_name": "Алиса 👋"})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["display_name"] == "Алиса 👋"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
async def test_nul_title_does_not_create_chat(client: AsyncClient, raw: str) -> None:
|
||||
user = await register(client, "nul_title")
|
||||
body = {"title": raw, "member_ids": [user["id"]]}
|
||||
rejected(
|
||||
await client.post("/api/v1/chats", json=body, headers=actor(user)), 400, "invalid_request"
|
||||
)
|
||||
chats = await client.get("/api/v1/chats", headers=actor(user))
|
||||
assert chats.status_code == 200
|
||||
assert chats.json()["items"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
async def test_nul_message_does_not_take_key(client: AsyncClient, raw: str) -> None:
|
||||
user = await register(client, "nul_message")
|
||||
chat = await make_chat(client, user)
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
headers = keyed(user)
|
||||
rejected(await client.post(path, json={"text": raw}, headers=headers), 400, "invalid_request")
|
||||
history = await client.get(path, headers=actor(user))
|
||||
assert history.status_code == 200
|
||||
assert history.json()["items"] == []
|
||||
text = "Исправлено\tбез потерь\n👋"
|
||||
first = await client.post(path, json={"text": text}, headers=headers)
|
||||
again = await client.post(path, json={"text": text}, headers=headers)
|
||||
assert first.status_code == again.status_code == 201
|
||||
assert first.json()["text"] == text
|
||||
assert first.json() == again.json()
|
||||
assert (await client.get(path, headers=actor(user))).json()["items"] == [first.json()]
|
||||
|
||||
|
||||
async def test_nul_message_does_not_disclose_chat(client: AsyncClient) -> None:
|
||||
owner = await register(client, "nul_owner")
|
||||
outsider = await register(client, "nul_outsider")
|
||||
chat = await make_chat(client, owner)
|
||||
responses = []
|
||||
for chat_id in [chat["id"], str(uuid4())]:
|
||||
response = await client.post(
|
||||
f"/api/v1/chats/{chat_id}/messages",
|
||||
json={"text": "abc\x00def"},
|
||||
headers={**keyed(outsider), "X-Request-Id": "nul-access"},
|
||||
)
|
||||
rejected(response, 404, "not_found")
|
||||
responses.append(response.json())
|
||||
assert responses[0] == responses[1]
|
||||
history = await client.get(f"/api/v1/chats/{chat['id']}/messages", headers=actor(owner))
|
||||
assert history.status_code == 200
|
||||
assert history.json()["items"] == []
|
||||
@@ -0,0 +1,95 @@
|
||||
from base64 import b64encode
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from starlette.types import Scope
|
||||
|
||||
from messenger.identity.application.queries import VerifyCredentials
|
||||
from messenger.identity.domain.errors import InvalidUserData
|
||||
from messenger.identity.domain.values import DisplayName
|
||||
from messenger.identity.entrypoints.authentication import (
|
||||
BASIC_CHALLENGE,
|
||||
LOGIN_PATH,
|
||||
basic_credentials,
|
||||
guard,
|
||||
)
|
||||
from messenger.messaging.application.commands import PostMessage
|
||||
from messenger.messaging.application.handlers import PostMessageHandler
|
||||
from messenger.messaging.application.ports import ChatDirectory, MessageLog, MessagingUnitOfWork
|
||||
from messenger.messaging.domain.errors import ChatNotFound, InvalidChatData, InvalidMessageText
|
||||
from messenger.messaging.domain.values import ChatTitle, MessageText
|
||||
from messenger.shared.application.ports import Clock, IdGenerator
|
||||
from messenger.shared.domain.errors import DomainError
|
||||
from messenger.shared.entrypoints.pipeline import Rejection
|
||||
|
||||
NUL_TEXTS = ["\x00", "\x00abc", "abc\x00def", "abc\x00"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("username", NUL_TEXTS)
|
||||
def test_basic_rejects_nul_username(username: str) -> None:
|
||||
raw = b64encode(f"{username}:synthetic-password".encode()).decode()
|
||||
assert basic_credentials(f"Basic {raw}") is None
|
||||
|
||||
|
||||
async def test_nul_username_is_rejected_before_credential_lookup() -> None:
|
||||
verify = AsyncMock(return_value=None)
|
||||
container = SimpleNamespace(get=AsyncMock(return_value=verify))
|
||||
scope: Scope = {
|
||||
"method": "POST",
|
||||
"path": LOGIN_PATH,
|
||||
"headers": [(b"authorization", b"Basic " + b64encode(b"abc\x00def:synthetic-password"))],
|
||||
"app": SimpleNamespace(state=SimpleNamespace(dishka_container=container)),
|
||||
}
|
||||
assert await guard(scope) == Rejection(
|
||||
401, "unauthorized", (("www-authenticate", BASIC_CHALLENGE),)
|
||||
)
|
||||
container.get.assert_awaited_once_with(VerifyCredentials)
|
||||
verify.assert_not_awaited()
|
||||
assert "user" not in scope["state"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NUL_TEXTS)
|
||||
@pytest.mark.parametrize(
|
||||
("kind", "error"),
|
||||
[
|
||||
(DisplayName, InvalidUserData),
|
||||
(ChatTitle, InvalidChatData),
|
||||
(MessageText, InvalidMessageText),
|
||||
],
|
||||
)
|
||||
def test_text_values_reject_nul(
|
||||
kind: type[DisplayName | ChatTitle | MessageText], error: type[DomainError], raw: str
|
||||
) -> None:
|
||||
with pytest.raises(error):
|
||||
kind(raw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", [DisplayName, ChatTitle, MessageText])
|
||||
def test_text_values_preserve_unicode_and_whitespace(
|
||||
kind: type[DisplayName | ChatTitle | MessageText],
|
||||
) -> None:
|
||||
raw = " Привет\tмир\n👋 "
|
||||
assert kind(raw).value == raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("member", [False, True])
|
||||
async def test_nul_message_checks_access_without_writing(member: bool) -> None:
|
||||
chats = AsyncMock(spec=ChatDirectory)
|
||||
chats.chat_for_member.return_value = Mock() if member else None
|
||||
log = AsyncMock(spec=MessageLog)
|
||||
log.post.return_value = None
|
||||
uow = Mock(spec=MessagingUnitOfWork)
|
||||
clock = Mock(spec=Clock)
|
||||
clock.now.return_value = datetime(2026, 1, 1, tzinfo=UTC)
|
||||
handler = PostMessageHandler(
|
||||
uow, log, chats, clock, Mock(spec=IdGenerator), ttl=timedelta(days=1)
|
||||
)
|
||||
command = PostMessage(uuid4(), uuid4(), "abc\x00def", "same-key", b"fingerprint")
|
||||
with pytest.raises(InvalidMessageText if member else ChatNotFound):
|
||||
await handler(command)
|
||||
chats.chat_for_member.assert_awaited_once_with(command.chat_id, command.sender_id)
|
||||
log.post.assert_not_awaited()
|
||||
uow.record.assert_not_called()
|
||||
Reference in New Issue
Block a user