Reject NUL input before authentication and text persistence

This commit is contained in:
Artyom
2026-11-06 02:05:09 +03:00
parent 5c561eac26
commit e66e2d7d68
6 changed files with 202 additions and 6 deletions
+95
View File
@@ -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"] == []
+95
View File
@@ -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()