Forward final lab3 session security and validation fixes

This commit is contained in:
Artyom
2026-11-06 12:07:00 +03:00
parent f0fc084fbb
commit 75b93bbba5
41 changed files with 2864 additions and 28 deletions
+91 -14
View File
@@ -11,7 +11,12 @@ from sqlalchemy import select
from conftest import actor, bearer, keyed, make_chat, register, resolve, running_app, scalar
from messenger.identity.application.ports import SessionDirectory
from messenger.identity.domain.models import Session
from messenger.identity.infrastructure.postgres import PostgresSessionRepository, SessionRow
from messenger.identity.infrastructure.postgres import (
PostgresIdentityUnitOfWork,
PostgresSessionDirectory,
PostgresSessionRepository,
SessionRow,
)
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.shared.application.errors import Unavailable
@@ -44,7 +49,7 @@ async def test_second_check_is_served_from_cache(valkey: dict[str, str]) -> None
await cache.aclose()
async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -> None:
async def test_logout_leaves_tombstone_after_commit(valkey: dict[str, str]) -> None:
cache = Redis.from_url(valkey["url"])
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
@@ -59,19 +64,26 @@ async def test_logout_writes_tombstone_before_database(valkey: dict[str, str]) -
await cache.aclose()
@pytest.mark.parametrize("failure", ["remove", "commit"])
async def test_logout_rejected_by_database_changes_nothing(
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, failure: str
) -> None:
async def broken(self: PostgresSessionRepository, token_hash: bytes) -> None:
raise Unavailable("PostgreSQL недоступен")
async def broken_commit(self: PostgresIdentityUnitOfWork) -> None:
raise Unavailable("PostgreSQL недоступен")
cache = Redis.from_url(valkey["url"])
logout = "/api/v1/auth/sessions/current"
async with running_app(cache_url=valkey["url"]) as http:
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
with monkeypatch.context() as patch:
patch.setattr(PostgresSessionRepository, "remove", broken)
if failure == "remove":
patch.setattr(PostgresSessionRepository, "remove", broken)
else:
patch.setattr(PostgresIdentityUnitOfWork, "commit", broken_commit)
failed = await http.delete(logout, headers=actor(alice))
assert failed.status_code == 503
assert failed.json()["error"]["code"] == "unavailable"
@@ -82,8 +94,14 @@ async def test_logout_rejected_by_database_changes_nothing(
await cache.aclose()
async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, str]) -> None:
async with running_app(cache_url=valkey["url"]) as http:
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
async def test_fill_racing_with_logout_does_not_revive_token(
valkey: dict[str, str], loss: str
) -> None:
async with (
Redis.from_url(valkey["url"]) as cache,
running_app(cache_url=valkey["url"]) as http,
):
alice = await register(http, "alice")
directory = await resolve(http, SessionDirectory)
assert isinstance(directory, CachedSessionDirectory)
@@ -99,14 +117,73 @@ async def test_fill_racing_with_logout_does_not_revive_token(valkey: dict[str, s
return stale[-1]
directory._origin = SlowOrigin()
reader = asyncio.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await entered.wait()
directory._origin = origin
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
released.set()
assert (await reader).status_code == 200
async with asyncio.TaskGroup() as group:
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
try:
await asyncio.wait_for(entered.wait(), 5)
directory._origin = origin
assert (
await http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
).status_code == 204
key = key_of(token_of(alice))
assert await cache.get(f"{key}:fill") is None
if loss == "flushall":
await cache.flushall()
elif loss in {"evict", "replacement"}:
await cache.delete(key)
if loss == "replacement":
await cache.set(f"{key}:fill", "another-reader", px=1000)
finally:
released.set()
assert reader.result().status_code == 200
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
@pytest.mark.parametrize("loss", ["flushall", "evict"])
async def test_cache_loss_before_logout_commit_cannot_refill_deleted_session(
valkey: dict[str, str], monkeypatch: pytest.MonkeyPatch, loss: str
) -> None:
revoked, release_commit, reading = asyncio.Event(), asyncio.Event(), asyncio.Event()
revoke = CachedSessionDirectory.revoke
find = PostgresSessionDirectory.find
async def paused_revoke(self: CachedSessionDirectory, session: Session) -> None:
await revoke(self, session)
revoked.set()
await release_commit.wait()
async def observed_find(
self: PostgresSessionDirectory, token_hash: bytes, now: datetime
) -> Session | None:
reading.set()
return await find(self, token_hash, now)
async with (
Redis.from_url(valkey["url"]) as cache,
running_app(cache_url=valkey["url"]) as http,
):
alice = await register(http, "alice")
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
monkeypatch.setattr(CachedSessionDirectory, "revoke", paused_revoke)
async with asyncio.TaskGroup() as group:
logout = group.create_task(
http.delete("/api/v1/auth/sessions/current", headers=actor(alice))
)
try:
await asyncio.wait_for(revoked.wait(), 5)
if loss == "flushall":
await cache.flushall()
else:
await cache.delete(key_of(token_of(alice)))
monkeypatch.setattr(PostgresSessionDirectory, "find", observed_find)
reader = group.create_task(http.get("/api/v1/users/me", headers=actor(alice)))
await asyncio.wait_for(reading.wait(), 5)
done, _ = await asyncio.wait({reader}, timeout=0.1)
assert not done
finally:
release_commit.set()
assert logout.result().status_code == 204
assert reader.result().status_code == 401
assert (await http.get("/api/v1/users/me", headers=actor(alice))).status_code == 401
+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"] == []
+28
View File
@@ -86,6 +86,34 @@ async def test_login_without_valid_basic(client: AsyncClient, headers: dict) ->
challenged(await client.post("/api/v1/auth/sessions", headers=headers), BASIC)
@pytest.mark.parametrize(
"raw", [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]
)
async def test_non_ascii_basic_matches_wrong_password(client: AsyncClient, raw: bytes) -> None:
alice = await register(client, "non_ascii_basic")
count = (
select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(alice["id"]))
)
before = await scalar(count)
wrong = await client.post(
"/api/v1/auth/sessions",
headers={**basic(alice["username"], "wrong-password"), "X-Request-Id": "non-ascii-basic"},
)
invalid = await client.post(
"/api/v1/auth/sessions",
headers={b"Authorization": raw, b"X-Request-Id": b"non-ascii-basic"},
)
for response in [wrong, invalid]:
challenged(response, BASIC)
assert response.headers["X-Instance-Id"]
assert response.headers["content-type"].startswith("application/json")
assert set(response.json()) == {"error"}
assert set(response.json()["error"]) == {"code", "message", "request_id"}
assert response.json()["error"]["message"]
assert wrong.json() == invalid.json()
assert await scalar(count) == before
async def test_password_with_colon_logs_in(client: AsyncClient) -> None:
body = new_user("colon", password="пароль:с:двоеточием")
assert (await client.post("/api/v1/users", json=body)).status_code == 201