from datetime import UTC, datetime from uuid import uuid4 import pytest from messenger.messaging.domain.errors import InvalidPageRequest from messenger.messaging.infrastructure.cursor import SignedCursorCodec KEY = (datetime(2026, 5, 17, 12, 30, 45, 123456, tzinfo=UTC), uuid4().int) def codec(secret: bytes = b"secret-for-tests") -> SignedCursorCodec: return SignedCursorCodec(secret) def test_roundtrip_preserves_key() -> None: subject = codec() assert subject.decode("messages:a", subject.encode("messages:a", KEY)) == KEY def test_cursor_is_opaque() -> None: encoded = codec().encode("messages:a", KEY) assert "2026" not in encoded assert str(KEY[1]) not in encoded def test_cursor_from_another_scope_is_rejected() -> None: subject = codec() encoded = subject.encode("messages:chat-one", KEY) with pytest.raises(InvalidPageRequest): subject.decode("messages:chat-two", encoded) def test_forged_cursor_is_rejected() -> None: encoded = codec(b"one-secret").encode("messages:a", KEY) with pytest.raises(InvalidPageRequest): codec(b"another-secret").decode("messages:a", encoded) @pytest.mark.parametrize( "raw", ["", "garbage", "1.2.3", "2.1.2.3", "1.notanumber.ff.AAAA", "1.1.zz.AAAA"], ) def test_broken_cursor_is_rejected(raw: str) -> None: with pytest.raises(InvalidPageRequest): codec().decode("messages:a", raw) def test_tampered_payload_is_rejected() -> None: subject = codec() encoded = subject.encode("messages:a", KEY) head, _, signature = encoded.rpartition(".") version, micros, identifier = head.split(".") tampered = f"{version}.{int(micros) + 1}.{identifier}.{signature}" with pytest.raises(InvalidPageRequest): subject.decode("messages:a", tampered)