import hashlib import json import re import time from concurrent.futures import ThreadPoolExecutor from uuid import uuid4 import psycopg import pytest from conftest import PASSWORD, ROOT, basic from fastapi.testclient import TestClient from messenger.app import create_app from messenger.auth import basic_credentials from messenger.migrate import migrate def headers(actor): return {"Authorization": "Bearer " + actor["token"], "Idempotency-Key": uuid4().hex} def error(response, status, code): assert response.status_code == status, response.text body = response.json()["error"] assert set(body) == {"code", "message", "request_id"} assert body["code"] == code assert body["request_id"] == response.headers["X-Request-Id"] assert len(response.headers.get_list("X-Request-Id")) == 1 if status == 401: assert response.headers["WWW-Authenticate"].startswith(("Basic", "Bearer")) @pytest.mark.parametrize("body", ["{", "null", "[]", '"text"', '{"username":']) def test_malformed_json(client, body): error( client.post("/api/v1/users", content=body, headers={"Content-Type": "application/json"}), 400, "invalid_request", ) @pytest.mark.parametrize( "change", [ {"username": "ab"}, {"username": "a" * 33}, {"username": "Upper"}, {"username": "кириллица"}, {"username": "valid\n"}, {"username": 123}, {"username": True}, {"display_name": 123}, {"display_name": None}, {"display_name": " \n\t"}, {"display_name": "😀" * 101}, {"display_name": "\ud800"}, {"password": "short"}, {"password": "😀" * 129}, {"password": 123}, {"password": " " * 12}, {"password": "\ud800" * 12}, {"extra": True}, ], ) def test_strict_registration(client, change): data = {"username": "valid", "display_name": "Имя", "password": PASSWORD, **change} response = client.post( "/api/v1/users", content=json.dumps(data), headers={"Content-Type": "application/json"} ) error(response, 400, "invalid_request") def test_unicode_password_hash_and_authentication(client, settings, actors): for u in actors: assert "password" not in u and "password_hash" not in u assert re.fullmatch(r"[A-Za-z0-9_-]{43}", u["token"]) with psycopg.connect(settings.database_url) as conn: encoded = conn.execute("SELECT password_hash FROM users WHERE username='alice'").fetchone()[ 0 ] assert encoded.startswith("$argon2id$") and PASSWORD not in encoded assert ( conn.execute("SELECT octet_length(token_hash) FROM sessions LIMIT 1").fetchone()[0] == 32 ) bad = client.post("/api/v1/auth/sessions", headers=basic("alice", "wrong-password")) absent = client.post("/api/v1/auth/sessions", headers=basic("unknown", "wrong-password")) error(bad, 401, "unauthorized") error(absent, 401, "unauthorized") assert bad.json()["error"]["message"] == absent.json()["error"]["message"] assert bad.headers["WWW-Authenticate"] == 'Basic realm="messenger", charset="UTF-8"' for value in ( {}, basic("alice"), {"X-User-Id": actors[0]["id"]}, {"Authorization": "Bearer unknown"}, ): error(client.get("/api/v1/users/me", headers=value), 401, "unauthorized") actual = client.get( "/api/v1/users/me", headers={**headers(actors[0]), "X-User-Id": actors[2]["id"]} ).json() assert actual["id"] == actors[0]["id"] error( client.post("/api/v1/auth/sessions", headers=basic("alice"), json={}), 400, "invalid_request", ) @pytest.mark.parametrize("value", [None, "Bearer a", "Basic !", "Basic YWxpY2U=", "Basic /w=="]) def test_invalid_basic(value): with pytest.raises(Exception) as caught: basic_credentials(value) assert caught.value.status == 401 def test_registration_race(client, settings): def register(_): return client.post( "/api/v1/users", json={"username": "same", "display_name": "Алиса", "password": PASSWORD}, ).status_code with ThreadPoolExecutor(max_workers=2) as pool: assert sorted(pool.map(register, range(10))) == [201] + [409] * 9 with psycopg.connect(settings.database_url) as conn: assert conn.execute("SELECT count(*) FROM users WHERE username='same'").fetchone()[0] == 1 def test_acl_validation_and_transaction_rollback(client, actors, room, settings): path = "/api/v1/chats/" + room["id"] for suffix in ("", "/messages"): error(client.get(path + suffix, headers=headers(actors[2])), 404, "not_found") error(client.get("/api/v1/chats/not-a-uuid"), 401, "unauthorized") error( client.get("/api/v1/chats/not-a-uuid", headers=headers(actors[0])), 400, "invalid_request" ) with psycopg.connect(settings.database_url) as conn: before = conn.execute("SELECT count(*) FROM chats").fetchone()[0] for members in ([actors[0]["id"], str(uuid4())], [actors[0]["id"]] * 2, [actors[1]["id"]], []): error( client.post( "/api/v1/chats", headers=headers(actors[0]), json={"title": "rollback", "member_ids": members}, ), 400, "invalid_request", ) with psycopg.connect(settings.database_url) as conn: assert conn.execute("SELECT count(*) FROM chats").fetchone()[0] == before assert conn.execute("SELECT count(*) FROM chat_members").fetchone()[0] == 2 for body in ( {"text": ""}, {"text": " \t"}, {"text": "😀" * 4001}, {"text": 123}, {"text": None}, {"text": "ok", "sender_id": actors[1]["id"]}, ): error( client.post(path + "/messages", headers=headers(actors[0]), json=body), 400, "invalid_request", ) for query in ( "limit=0", "limit=101", "limit=true", "limit=1.0", "limit=1&limit=2", "cursor=", "cursor=bad!", "cursor=e30", "cursor=x&cursor=y", ): error( client.get(path + "/messages?" + query, headers=headers(actors[0])), 400, "invalid_request", ) def test_concurrent_messages_and_keyset_ties(client, actors, room, settings): path = f"/api/v1/chats/{room['id']}/messages" def send(i): r = client.post(path, headers=headers(actors[i % 2]), json={"text": f"m{i} 😀"}) assert r.status_code == 201 return r.json() with ThreadPoolExecutor(max_workers=10) as pool: sent = list(pool.map(send, range(100))) with psycopg.connect(settings.database_url) as conn: conn.execute( "UPDATE messages SET created_at='2026-10-17T12:00:00Z' WHERE chat_id=%s", (room["id"],) ) for m in sent: m["created_at"] = "2026-10-17T12:00:00.000000Z" found, cursor = [], None while True: query = {"limit": 17 if cursor else 1} if cursor: query["cursor"] = cursor response = client.get(path, params=query, headers=headers(actors[1])) assert response.status_code == 200 page = response.json() found.extend(page["items"]) cursor = page["next_cursor"] if not cursor: break assert len(found) == len({x["id"] for x in found}) == 100 assert found == sorted(sent, key=lambda x: (x["created_at"], x["id"])) first_cursor = client.get(path + "?limit=1", headers=headers(actors[0])).json()["next_cursor"] error( client.get("/api/v1/chats", params={"cursor": first_cursor}, headers=headers(actors[0])), 400, "invalid_request", ) def test_cache_hit_flush_and_revocation(client, actors, monkeypatch): user = actors[0] url = "/api/v1/users/me" assert client.get(url, headers=headers(user)).status_code == 200 repository = client.app.state.repository original = repository.get_user def must_be_cached(*args): raise AssertionError("cache hit should avoid fetching immutable user again") monkeypatch.setattr(repository, "get_user", must_be_cached) assert client.get(url, headers=headers(user)).status_code == 200 monkeypatch.setattr(repository, "get_user", original) cache = client.app.state.cache.client digest = hashlib.sha256(user["token"].encode()).digest() key = client.app.state.cache.key(digest) assert 0 < cache.ttl(key) <= 3600 stale = cache.get(key) cache.flushdb() assert client.get(url, headers=headers(user)).status_code == 200 assert client.delete("/api/v1/auth/sessions/current", headers=headers(user)).status_code == 204 cache.set(key, stale, ex=3600) # A resurrected stale cache entry must not resurrect a session. error(client.get(url, headers=headers(user)), 401, "unauthorized") error( client.delete("/api/v1/auth/sessions/current", headers=headers(user)), 401, "unauthorized" ) def test_expiry_and_api_restart(client, actors, settings, monkeypatch, tmp_path): database_file, cache_file = tmp_path / "database_url", tmp_path / "cache_url" database_file.write_text(settings.database_url) cache_file.write_text(settings.cache_url) monkeypatch.setenv("DATABASE_URL_FILE", str(database_file)) monkeypatch.setenv("CACHE_URL_FILE", str(cache_file)) monkeypatch.setenv("SESSION_TTL_SECONDS", "2") with TestClient(create_app()) as short: response = short.post("/api/v1/auth/sessions", headers=basic("alice")) assert response.status_code == 201 token = {"Authorization": "Bearer " + response.json()["token"]} assert short.get("/api/v1/users/me", headers=token).status_code == 200 with TestClient(create_app(settings)) as restarted: assert restarted.get("/api/v1/users/me", headers=token).status_code == 200 time.sleep(2.1) error(restarted.get("/api/v1/users/me", headers=token), 401, "unauthorized") def test_migrations_idempotent_and_detect_change(client, settings, tmp_path): migrate(settings.database_url, ROOT / "migrations") modified = tmp_path / "001_initial.sql" modified.write_text((ROOT / "migrations/001_initial.sql").read_text() + "\n-- changed") with pytest.raises(RuntimeError, match="checksum changed"): migrate(settings.database_url, tmp_path) def test_logs_and_safe_errors(client, monkeypatch, caplog): canary = "PRIVATE_BODY_CANARY_123" with caplog.at_level("INFO", logger="messenger"): r = client.post( "/api/v1/users", json={"username": "logging", "display_name": canary, "password": PASSWORD}, ) assert r.status_code == 201 assert canary not in caplog.text and PASSWORD not in caplog.text def broken(*args): raise RuntimeError(canary) monkeypatch.setattr(client.app.state.authentication, "register", broken) response = client.post( "/api/v1/users", json={"username": "broken", "display_name": "x", "password": PASSWORD} ) error(response, 500, "internal_error") assert canary not in response.text and canary not in caplog.text error( client.post("/api/v1/users", content="{}", headers={"Content-Type": "text/plain"}), 415, "unsupported_media_type", )