Files
mtusi2026lab4/student-tests/api/test_sessions.py
T
ArtyomandClaude Opus 5.5 bf8e4e3cd1 Carry over the lab 3 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy and k6 configuration, migrations, hooks, evidence and level 4
scripts and the CI job from the lab 3 solution commit 61c0c28, merge
the lab 3 Makefile targets into the lab 4 skeleton Makefile without
touching its targets, and append the lab 3 solution variables to the
skeleton .env.example. The package and the application follow the
contract version 1.4.0, and the image and the throwaway test containers
are tagged lab4 so they do not collide with a lab 3 stand on the same
host.

This is the starting point of the lab 4 cycle: lint, own tests and the
offline skeleton check pass before any lab 4 change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 20:17:51 +03:00

173 lines
6.9 KiB
Python

import asyncio
from datetime import datetime, timedelta
import pytest
from httpx import AsyncClient
from conftest import (
PASSWORD,
actor,
basic,
bearer,
login,
make_chat,
new_user,
register,
running_app,
scalar,
)
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 password_hash FROM users WHERE id = $1::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]
sql = "SELECT count(*) FROM sessions WHERE token_hash = sha256(convert_to($1, 'UTF8'))"
assert await scalar(sql, token) == 1
raw = "SELECT count(*) FROM sessions WHERE encode(token_hash, 'escape') = $1"
assert await scalar(raw, token) == 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 count(*) FROM sessions WHERE user_id = $1::uuid"
assert await scalar(sql, user["id"]) == 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)