Forward final lab3 session security and validation fixes
This commit is contained in:
@@ -1,12 +1,24 @@
|
||||
import json
|
||||
from base64 import b64encode
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
from starlette.types import Scope
|
||||
|
||||
from messenger.identity.application.queries import VerifyCredentials
|
||||
from messenger.identity.entrypoints.authentication import (
|
||||
BASIC_CHALLENGE,
|
||||
LOGIN_PATH,
|
||||
basic_credentials,
|
||||
bearer_token,
|
||||
challenge_for,
|
||||
guard,
|
||||
)
|
||||
from messenger.shared.application.ports import Logger
|
||||
from messenger.shared.entrypoints.pipeline import RequestPipeline
|
||||
|
||||
NON_ASCII_BASIC = [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]
|
||||
|
||||
|
||||
def encoded(raw: bytes) -> str:
|
||||
@@ -43,6 +55,46 @@ def test_basic_rejects_malformed(raw: str) -> None:
|
||||
assert basic_credentials(raw) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NON_ASCII_BASIC)
|
||||
def test_basic_rejects_non_ascii(raw: bytes) -> None:
|
||||
assert basic_credentials(raw.decode("latin-1")) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", NON_ASCII_BASIC)
|
||||
async def test_non_ascii_basic_returns_401_without_credential_lookup(raw: bytes) -> None:
|
||||
verify = AsyncMock(return_value=None)
|
||||
container = SimpleNamespace(get=AsyncMock(return_value=verify))
|
||||
scope: Scope = {
|
||||
"type": "http",
|
||||
"method": "POST",
|
||||
"path": LOGIN_PATH,
|
||||
"headers": [(b"authorization", raw), (b"x-request-id", b"non-ascii-basic")],
|
||||
"app": SimpleNamespace(state=SimpleNamespace(dishka_container=container)),
|
||||
}
|
||||
endpoint, send = AsyncMock(), AsyncMock()
|
||||
pipeline = RequestPipeline(endpoint, Mock(spec=Logger), 1024, 1, guard, "test-instance")
|
||||
await pipeline(scope, AsyncMock(), send)
|
||||
start, body = [call.args[0] for call in send.await_args_list]
|
||||
assert start["status"] == 401
|
||||
headers = dict(start["headers"])
|
||||
assert headers[b"www-authenticate"] == BASIC_CHALLENGE.encode()
|
||||
assert headers[b"x-instance-id"] == b"test-instance"
|
||||
assert headers[b"x-request-id"] == b"non-ascii-basic"
|
||||
assert headers[b"content-type"] == b"application/json"
|
||||
assert json.loads(body["body"]) == {
|
||||
"error": {
|
||||
"code": "unauthorized",
|
||||
"message": "Аутентификация не предоставлена или недействительна",
|
||||
"request_id": "non-ascii-basic",
|
||||
}
|
||||
}
|
||||
container.get.assert_awaited_once_with(VerifyCredentials)
|
||||
verify.assert_not_awaited()
|
||||
endpoint.assert_not_awaited()
|
||||
assert "user" not in scope["state"]
|
||||
assert scope["state"]["actor"] is None
|
||||
|
||||
|
||||
def test_bearer_accepts_token68() -> None:
|
||||
assert bearer_token("Bearer abc-DEF_123.~+/==") == "abc-DEF_123.~+/=="
|
||||
assert bearer_token("bearer token") == "token"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import json
|
||||
import shlex
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
CONFIG = Path(__file__).resolve().parents[2] / "infra/haproxy/haproxy.cfg"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [502, 503, 504])
|
||||
@pytest.mark.parametrize("request_id", ['a"b', "a\\b", "a\tb", "aÿb", "x" * 200])
|
||||
def test_error_templates_escape_json_without_changing_header(status: int, request_id: str) -> None:
|
||||
line = next(
|
||||
line.strip()
|
||||
for line in CONFIG.read_text().splitlines()
|
||||
if line.strip().startswith(f"http-error status {status} ")
|
||||
)
|
||||
tokens = shlex.split(line)
|
||||
header = tokens[tokens.index("hdr") + 1 : tokens.index("lf-string")]
|
||||
assert header == ["X-Request-Id", "%[var(txn.request_id)]"]
|
||||
template = tokens[tokens.index("lf-string") + 1]
|
||||
escaped = json.dumps(request_id, ensure_ascii=True)[1:-1]
|
||||
rendered = template.replace("%[var(txn.request_id),json(ascii)]", escaped)
|
||||
body = json.loads(rendered)
|
||||
assert body["error"]["request_id"] == request_id
|
||||
assert body["error"]["code"] == "unavailable"
|
||||
@@ -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()
|
||||
@@ -0,0 +1,161 @@
|
||||
import asyncio
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import cast
|
||||
from unittest.mock import AsyncMock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from redis.asyncio import Redis
|
||||
from redis.exceptions import ConnectionError as CacheConnectionError
|
||||
|
||||
from fakes import NullLogger
|
||||
from messenger.identity.domain.models import Session
|
||||
from messenger.identity.infrastructure.valkey import (
|
||||
FILL,
|
||||
REVOKE,
|
||||
REVOKED,
|
||||
CachedSessionDirectory,
|
||||
key_of,
|
||||
milliseconds,
|
||||
)
|
||||
|
||||
NOW = datetime(2030, 1, 1, tzinfo=UTC)
|
||||
|
||||
|
||||
class CacheModel:
|
||||
def __init__(self) -> None:
|
||||
self.values: dict[str, str] = {}
|
||||
self.expires: dict[str, int] = {}
|
||||
|
||||
async def get(self, key: str) -> str | None:
|
||||
return self.values.get(key)
|
||||
|
||||
async def set(self, key: str, value: str, *, pxat: int, nx: bool = False) -> bool:
|
||||
if nx and key in self.values:
|
||||
return False
|
||||
self.values[key], self.expires[key] = value, pxat
|
||||
return True
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
self.values.pop(key, None)
|
||||
self.expires.pop(key, None)
|
||||
|
||||
async def eval(self, script: str, count: int, key: str, marker: str, *args: str | int) -> bool:
|
||||
assert count == 2
|
||||
if script == REVOKE:
|
||||
value, until = args
|
||||
assert isinstance(value, str) and isinstance(until, int)
|
||||
await self.set(key, value, pxat=until)
|
||||
await self.delete(marker)
|
||||
return True
|
||||
assert script == FILL
|
||||
nonce, value, until = args
|
||||
assert isinstance(value, str) and isinstance(until, int)
|
||||
if await self.get(marker) != nonce:
|
||||
return False
|
||||
await self.delete(marker)
|
||||
return bool(value) and await self.set(key, value, pxat=until, nx=True)
|
||||
|
||||
|
||||
def directory(origin: AsyncMock, cache: CacheModel, ttl: int = 300) -> CachedSessionDirectory:
|
||||
return CachedSessionDirectory(
|
||||
origin, cast(Redis, cache), NullLogger(), limit=timedelta(seconds=ttl), cooldown=1
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session() -> Session:
|
||||
return Session.issue(user_id=uuid4(), issued_at=NOW, ttl=timedelta(seconds=30))[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ttl", [10, 300])
|
||||
async def test_cache_hit_keeps_absolute_ttl_without_reading_origin(
|
||||
session: Session, ttl: int
|
||||
) -> None:
|
||||
origin, cache = AsyncMock(), CacheModel()
|
||||
origin.find.return_value = session
|
||||
cached = directory(origin, cache, ttl)
|
||||
assert await cached.find(session.token_hash, NOW) == session
|
||||
assert await directory(origin, cache, ttl).find(session.token_hash, NOW) == session
|
||||
origin.find.assert_awaited_once()
|
||||
assert cache.expires == {
|
||||
key_of(session.token_hash): milliseconds(
|
||||
min(session.expires_at, NOW + timedelta(seconds=ttl))
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
|
||||
async def test_delayed_fill_cannot_revive_logged_out_session(session: Session, loss: str) -> None:
|
||||
origin, cache = AsyncMock(), CacheModel()
|
||||
origin.find.return_value = session
|
||||
entered, released = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def stale_find(token_hash: bytes, now: datetime) -> Session:
|
||||
entered.set()
|
||||
await released.wait()
|
||||
return session
|
||||
|
||||
slow = AsyncMock()
|
||||
slow.find.side_effect = stale_find
|
||||
async with asyncio.TaskGroup() as group:
|
||||
reader = group.create_task(directory(slow, cache).find(session.token_hash, NOW))
|
||||
await asyncio.wait_for(entered.wait(), 1)
|
||||
try:
|
||||
await directory(origin, cache).revoke(session)
|
||||
origin.find.return_value = None
|
||||
key = key_of(session.token_hash)
|
||||
if loss == "flushall":
|
||||
cache.values.clear()
|
||||
elif loss in {"evict", "replacement"}:
|
||||
await cache.delete(key)
|
||||
if loss == "replacement":
|
||||
await cache.set(f"{key}:fill", uuid4().hex, pxat=milliseconds(session.expires_at))
|
||||
finally:
|
||||
released.set()
|
||||
assert reader.result() == session
|
||||
assert await directory(origin, cache).find(session.token_hash, NOW) is None
|
||||
assert await cache.get(key) in {None, REVOKED}
|
||||
|
||||
|
||||
async def test_failed_reservation_never_fills_from_stale_database_result(session: Session) -> None:
|
||||
cache = CacheModel()
|
||||
origin = AsyncMock()
|
||||
key = key_of(session.token_hash)
|
||||
await cache.set(f"{key}:fill", "another-reader", pxat=milliseconds(session.expires_at))
|
||||
|
||||
async def find(token_hash: bytes, now: datetime) -> Session:
|
||||
cache.values.clear()
|
||||
return session
|
||||
|
||||
origin.find.side_effect = find
|
||||
assert await directory(origin, cache).find(session.token_hash, NOW) == session
|
||||
assert await cache.get(key) is None
|
||||
|
||||
|
||||
async def test_missing_session_releases_only_its_own_reservation(session: Session) -> None:
|
||||
origin, cache = AsyncMock(), CacheModel()
|
||||
origin.find.return_value = None
|
||||
assert await directory(origin, cache).find(session.token_hash, NOW) is None
|
||||
assert cache.values == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failed_operation", ["get", "set"])
|
||||
async def test_cache_recovery_during_database_read_does_not_allow_unreserved_fill(
|
||||
session: Session, failed_operation: str
|
||||
) -> None:
|
||||
origin, cache = AsyncMock(), AsyncMock()
|
||||
cache.get.return_value = None
|
||||
getattr(cache, failed_operation).side_effect = CacheConnectionError("offline")
|
||||
cached = CachedSessionDirectory(
|
||||
origin, cache, NullLogger(), limit=timedelta(seconds=300), cooldown=1
|
||||
)
|
||||
|
||||
async def find(token_hash: bytes, now: datetime) -> Session:
|
||||
cached._resume_at = 0.0
|
||||
return session
|
||||
|
||||
origin.find.side_effect = find
|
||||
assert await cached.find(session.token_hash, NOW) == session
|
||||
assert cache.set.await_count == (failed_operation == "set")
|
||||
cache.eval.assert_not_awaited()
|
||||
Reference in New Issue
Block a user