Files
mtusi2026lab2/student-tests/api/test_sessions.py
T
Artyom 8e4532f6f5 Forward-port lab3 SQLAlchemy and Alembic foundation
Carry source f591fa64e5 forward from 72a1e57. Preserve lab4 attachment transactions, reconciliation locks, quarantine, and existing schema data through verified legacy adoption. Keep report and evidence work in progress untouched.
2026-11-06 01:47:30 +03:00

176 lines
7.0 KiB
Python

import asyncio
from datetime import datetime, timedelta
from hashlib import sha256
from uuid import UUID
import pytest
from httpx import AsyncClient
from sqlalchemy import func, select
from conftest import (
PASSWORD,
actor,
basic,
bearer,
login,
make_chat,
new_user,
register,
running_app,
scalar,
)
from messenger.identity.infrastructure.postgres import SessionRow, UserRow
BASIC = 'Basic realm="messenger", charset="UTF-8"'
BEARER = 'Bearer realm="messenger"'
def challenged(response, challenge: str) -> None:
assert response.status_code == 401, response.text
assert response.headers["WWW-Authenticate"] == challenge
assert response.json()["error"]["code"] == "unauthorized"
assert response.json()["error"]["request_id"] == response.headers["X-Request-Id"]
async def test_login_returns_session_for_registered_user(client: AsyncClient) -> None:
body = new_user("alice")
user = (await client.post("/api/v1/users", json=body)).json()
session = await login(client, body["username"])
assert set(session) == {"token", "token_type", "expires_at", "user"}
assert session["token_type"] == "Bearer"
assert session["user"] == user
assert len(session["token"]) >= 43
assert body["username"] not in session["token"] and user["id"] not in session["token"]
assert session["expires_at"].endswith("Z")
expires = datetime.fromisoformat(session["expires_at"])
created = datetime.fromisoformat(user["created_at"])
assert timedelta(seconds=3500) < expires - created < timedelta(seconds=3700)
async def test_registration_response_hides_password(client: AsyncClient) -> None:
body = new_user("alice")
response = await client.post("/api/v1/users", json=body)
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
assert PASSWORD not in response.text
async def test_password_is_stored_as_argon2id(client: AsyncClient) -> None:
alice = await register(client, "alice")
stored = await scalar(select(UserRow.password_hash).where(UserRow.id == UUID(alice["id"])))
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
assert PASSWORD not in stored
async def test_session_stores_only_token_digest(client: AsyncClient) -> None:
alice = await register(client, "alice")
token = actor(alice)["Authorization"].split()[1]
rows = select(func.count()).select_from(SessionRow)
assert await scalar(rows.where(SessionRow.token_hash == sha256(token.encode()).digest())) == 1
assert await scalar(rows.where(SessionRow.token_hash == token.encode())) == 0
async def test_wrong_password_and_unknown_user_look_the_same(client: AsyncClient) -> None:
alice = await register(client, "alice")
wrong = await client.post("/api/v1/auth/sessions", headers=basic(alice["username"], "x" * 20))
unknown = await client.post("/api/v1/auth/sessions", headers=basic("u_ghost_000", PASSWORD))
challenged(wrong, BASIC)
challenged(unknown, BASIC)
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
@pytest.mark.parametrize(
"headers",
[{}, {"Authorization": "Basic !!!"}, {"Authorization": "Bearer abc"}, {"X-User-Id": "x"}],
)
async def test_login_without_valid_basic(client: AsyncClient, headers: dict) -> None:
challenged(await client.post("/api/v1/auth/sessions", headers=headers), BASIC)
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
assert (await login(client, body["username"], body["password"]))["token"]
async def test_login_with_body_is_rejected(client: AsyncClient) -> None:
body = new_user("body")
await client.post("/api/v1/users", json=body)
response = await client.post(
"/api/v1/auth/sessions", headers=basic(body["username"], PASSWORD), json={"x": 1}
)
assert response.status_code == 400
assert response.json()["error"]["code"] == "invalid_request"
async def test_basic_on_business_endpoint_gets_bearer_challenge(client: AsyncClient) -> None:
body = new_user("alice")
await client.post("/api/v1/users", json=body)
challenged(
await client.get("/api/v1/users/me", headers=basic(body["username"], PASSWORD)), BEARER
)
async def test_user_id_header_does_not_override_owner(client: AsyncClient) -> None:
alice = await register(client, "alice")
eve = await register(client, "eve")
response = await client.get(
"/api/v1/users/me", headers={**actor(alice), "X-User-Id": eve["id"]}
)
assert response.json() == alice
async def test_authentication_precedes_validation(client: AsyncClient) -> None:
response = await client.post(
"/api/v1/chats/not-a-uuid/messages",
content=b"{broken",
headers={"Content-Type": "application/json"},
)
challenged(response, BEARER)
async def test_logout_revokes_only_current_session(client: AsyncClient) -> None:
body = new_user("alice")
await client.post("/api/v1/users", json=body)
first = (await login(client, body["username"]))["token"]
second = (await login(client, body["username"]))["token"]
logout = await client.delete("/api/v1/auth/sessions/current", headers=bearer(first))
assert logout.status_code == 204
assert logout.content == b""
assert logout.headers["X-Request-Id"]
challenged(await client.get("/api/v1/users/me", headers=bearer(first)), BEARER)
challenged(await client.delete("/api/v1/auth/sessions/current", headers=bearer(first)), BEARER)
assert (await client.get("/api/v1/users/me", headers=bearer(second))).status_code == 200
async def test_short_ttl_session_expires() -> None:
async with running_app(session_ttl_seconds=1) as client:
alice = await register(client, "alice")
assert (await client.get("/api/v1/users/me", headers=actor(alice))).status_code == 200
await asyncio.sleep(1.2)
challenged(await client.get("/api/v1/users/me", headers=actor(alice)), BEARER)
async def test_expired_sessions_are_purged_on_next_login() -> None:
async with running_app(session_ttl_seconds=1) as client:
body = new_user("purge")
user = (await client.post("/api/v1/users", json=body)).json()
await login(client, body["username"])
await asyncio.sleep(1.2)
await login(client, body["username"])
sql = select(func.count()).select_from(SessionRow).where(SessionRow.user_id == UUID(user["id"]))
assert await scalar(sql) == 1
async def test_chat_routes_require_bearer(client: AsyncClient) -> None:
alice = await register(client, "alice")
chat = await make_chat(client, alice)
for method, path in [
("GET", "/api/v1/chats"),
("POST", "/api/v1/chats"),
("GET", f"/api/v1/chats/{chat['id']}"),
("GET", f"/api/v1/chats/{chat['id']}/messages"),
("POST", f"/api/v1/chats/{chat['id']}/messages"),
("DELETE", "/api/v1/auth/sessions/current"),
]:
challenged(await client.request(method, path, headers={"X-User-Id": alice["id"]}), BEARER)