forked from mtusi2026/mtusi2026lab3
Исходная точка lab3: код из solution/bvt2302-bodanyuk лабы 2, коммит ef44e48 (PR mtusi2026/mtusi2026lab2#42 принят). README, COURSE, contracts/ и tests/ преподавателя не тронуты; к Makefile дописан студенческий раздел lab2, .env.example — версия lab2. Исследование трека 2 lab2 (bench/track2) не переносилось. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
135 lines
6.0 KiB
Python
135 lines
6.0 KiB
Python
"""Pure functions, no services: validation, cursor, Authorization parsing, Argon2id, config."""
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import base64
|
||
import datetime as dt
|
||
|
||
import pytest
|
||
|
||
from messenger import authhdr, cursor, passwords, validation
|
||
from messenger.config import ConfigError, Settings
|
||
from messenger.errors import InvalidRequest, Unauthorized
|
||
from messenger.timefmt import UTC, from_us, rfc3339, to_us
|
||
|
||
|
||
def b64(raw: bytes) -> str:
|
||
return base64.b64encode(raw).decode()
|
||
|
||
|
||
# ------------------------------------------------------------------ password rules
|
||
@pytest.mark.parametrize("password", ["Twelve-chars", "я" * 128, "пароль:с:двоеточиями", "😀" * 12, "a b c d e f g"])
|
||
def test_valid_passwords(password):
|
||
assert validation.password_field({"password": password}) == password
|
||
|
||
|
||
@pytest.mark.parametrize("password", ["short-11ch", "я" * 129, " " * 12, "\t\n " * 5, "\ud800" * 12, None, 123456789012])
|
||
def test_invalid_passwords(password):
|
||
with pytest.raises(InvalidRequest):
|
||
validation.password_field({"password": password})
|
||
|
||
|
||
def test_text_may_contain_nul_but_not_lone_surrogates():
|
||
assert validation.text_field({"t": "a\u0000b"}, "t", 10) == "a\u0000b"
|
||
with pytest.raises(InvalidRequest):
|
||
validation.text_field({"t": "a\ud800"}, "t", 10)
|
||
|
||
|
||
# ------------------------------------------------------------------ cursor
|
||
CHAT = "3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11"
|
||
|
||
|
||
def test_cursor_roundtrip_and_binding():
|
||
key = (to_us(dt.datetime(2026, 10, 12, 12, 0, 0, 123456, tzinfo=UTC)), "11111111-1111-4111-8111-111111111111")
|
||
token = cursor.encode(cursor.MESSAGES, CHAT, key)
|
||
assert cursor.decode(token, cursor.MESSAGES, CHAT) == key
|
||
with pytest.raises(InvalidRequest):
|
||
cursor.decode(token, cursor.MESSAGES, "00000000-0000-4000-8000-000000000000") # other chat
|
||
with pytest.raises(InvalidRequest):
|
||
cursor.decode(token, cursor.CHATS, CHAT) # other resource
|
||
|
||
|
||
@pytest.mark.parametrize("payload", [
|
||
b"v1|m|" + CHAT.encode() + b"|253402300800000000|11111111-1111-4111-8111-111111111111", # 1 us after 9999-12-31
|
||
b"v1|m|" + CHAT.encode() + b"|9999999999999999999|11111111-1111-4111-8111-111111111111", # int64 edge
|
||
b"v1|m|" + CHAT.encode() + b"|-1|11111111-1111-4111-8111-111111111111",
|
||
b"v1|m|" + CHAT.encode() + b"|1|not-a-uuid",
|
||
b"v1|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-11111111111G",
|
||
b"v2|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-111111111111",
|
||
])
|
||
def test_broken_cursors_are_400_not_500(payload):
|
||
token = base64.urlsafe_b64encode(payload).rstrip(b"=").decode()
|
||
with pytest.raises(InvalidRequest):
|
||
cursor.decode(token, cursor.MESSAGES, CHAT)
|
||
|
||
|
||
def test_time_helpers_are_exact():
|
||
moment = dt.datetime(2026, 2, 28, 23, 59, 59, 999999, tzinfo=UTC)
|
||
assert from_us(to_us(moment)) == moment
|
||
assert rfc3339(moment) == "2026-02-28T23:59:59.999999Z"
|
||
assert from_us(cursor.MAX_TS_US).year == 9999
|
||
|
||
|
||
# ------------------------------------------------------------------ Authorization header
|
||
def test_basic_is_parsed_and_password_may_contain_colons():
|
||
assert authhdr.parse_basic("Basic " + b64("alice:pa:ss:wörd".encode())) == ("alice", "pa:ss:wörd")
|
||
assert authhdr.parse_basic("basic " + b64(b"bob_1:x" * 1)) == ("bob_1", "x")
|
||
|
||
|
||
@pytest.mark.parametrize("header", [
|
||
None, "", "Basic", "Basic é", "Basic !!!!", "Basic " + b64(b"no-colon"), "Basic " + b64(b"\xff\xfe:pw"),
|
||
"Basic " + b64(b":password"), "Basic " + b64(b"alice:"), "Basic " + b64("Алиса:pw".encode()),
|
||
"Bearer " + "a" * 43, "Basic " + "A" * 2000,
|
||
])
|
||
def test_bad_basic_is_401_with_basic_challenge(header):
|
||
with pytest.raises(Unauthorized) as info:
|
||
authhdr.parse_basic(header)
|
||
assert info.value.headers["WWW-Authenticate"].startswith("Basic realm=\"messenger\"")
|
||
|
||
|
||
@pytest.mark.parametrize("header", [None, "", "Bearer", "Bearer short", "Bearer " + "a" * 43 + "!",
|
||
"Basic " + b64(b"alice:password-123"), "Token " + "a" * 43, "Bearer " + "é" * 43])
|
||
def test_bad_bearer_is_401_with_bearer_challenge(header):
|
||
with pytest.raises(Unauthorized) as info:
|
||
authhdr.parse_bearer(header)
|
||
assert info.value.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
|
||
|
||
|
||
def test_bearer_ok():
|
||
token = "A_b-" + "x" * 39
|
||
assert authhdr.parse_bearer("Bearer " + token) == token
|
||
|
||
|
||
# ------------------------------------------------------------------ Argon2id
|
||
def test_argon2id_hash_and_verify():
|
||
async def scenario():
|
||
stored = await passwords.hash_password("я" * 128)
|
||
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||
assert await passwords.verify_password(stored, "я" * 128)
|
||
assert not await passwords.verify_password(stored, "я" * 127)
|
||
assert not await passwords.verify_password(None, "anything") # unknown user, dummy hash
|
||
assert not await passwords.verify_password("not-a-hash", "anything")
|
||
assert await passwords.hash_password("same password!") != await passwords.hash_password("same password!") # salt
|
||
asyncio.run(scenario())
|
||
|
||
|
||
# ------------------------------------------------------------------ config
|
||
def test_settings_read_secret_files_and_contract_names(tmp_path, monkeypatch):
|
||
url_file = tmp_path / "database_url"
|
||
url_file.write_text("postgresql://u:p@db/x\n", encoding="utf-8")
|
||
monkeypatch.setenv("DATABASE_URL_FILE", str(url_file))
|
||
monkeypatch.setenv("SESSION_STORE", "redis")
|
||
monkeypatch.setenv("CACHE_URL", "redis://:p@valkey:6379/0")
|
||
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
|
||
settings = Settings.from_env()
|
||
assert settings.database_url == "postgresql://u:p@db/x"
|
||
assert settings.session_store == "valkey" and settings.session_ttl_seconds == 2
|
||
monkeypatch.setenv("SESSION_TTL_SECONDS", "0")
|
||
with pytest.raises(ConfigError):
|
||
Settings.from_env()
|
||
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
|
||
monkeypatch.setenv("DATABASE_URL_FILE", str(tmp_path / "missing"))
|
||
with pytest.raises(ConfigError) as info:
|
||
Settings.from_env()
|
||
assert "u:p" not in str(info.value)
|