feat: реализация второй лабы по тз

This commit is contained in:
Enterxx2
2026-10-11 18:14:20 +03:00
parent a6c74c9bb0
commit ea2b432a22
100 changed files with 3416 additions and 428 deletions
+21 -8
View File
@@ -5,7 +5,7 @@ from pathlib import Path
import httpx
import pytest
from helpers import auth, unique_username
from helpers import auth, basic, unique_password, unique_username
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_BASE_URL = json.loads((ROOT / "lab.json").read_text())["default_base_url"]
@@ -24,16 +24,29 @@ def api(base_url: str) -> Iterator[httpx.Client]:
yield client
def register_and_login(
client: httpx.Client, label: str, display_name: str | None = None
) -> dict:
"""Регистрация и вход; в словаре User плюс token и password для тестов"""
username = unique_username(label)
password = unique_password()
body = {
"username": username,
"display_name": display_name or f"Студент {label}",
"password": password,
}
response = client.post("/api/v1/users", json=body)
assert response.status_code == 201, response.text
user = response.json()
session = client.post("/api/v1/auth/sessions", headers=basic(username, password))
assert session.status_code == 201, session.text
return {**user, "token": session.json()["token"], "password": password}
@pytest.fixture
def make_user(api: httpx.Client) -> Callable[..., dict]:
def create(label: str = "user", display_name: str | None = None) -> dict:
body = {
"username": unique_username(label),
"display_name": display_name or f"Студент {label}",
}
response = api.post("/api/v1/users", json=body)
assert response.status_code == 201, response.text
return response.json()
return register_and_login(api, label, display_name)
return create
+56 -1
View File
@@ -1,16 +1,38 @@
"""Общие проверки для собственных black-box тестов"""
import base64
import subprocess
import uuid
from pathlib import Path
import httpx
ROOT = Path(__file__).resolve().parents[1]
USER_FIELDS = ("id", "username", "display_name", "created_at")
def unique_username(label: str) -> str:
return f"st_{label}_{uuid.uuid4().hex[:12]}"
def unique_password() -> str:
return f"Pw-{uuid.uuid4().hex}"
def basic(username: str, password: str) -> dict[str, str]:
"""Authorization: Basic; пароль кодируется в UTF-8"""
raw = f"{username}:{password}".encode()
return {"Authorization": "Basic " + base64.b64encode(raw).decode()}
def auth(user: dict) -> dict[str, str]:
return {"X-User-Id": user["id"]}
return {"Authorization": f"Bearer {user['token']}"}
def public_user(user: dict) -> dict:
"""User из ответа API без тестовых полей token/password"""
return {field: user[field] for field in USER_FIELDS}
def assert_error(response: httpx.Response, status: int, code: str) -> None:
@@ -23,6 +45,12 @@ def assert_error(response: httpx.Response, status: int, code: str) -> None:
assert error["request_id"] == response.headers["X-Request-Id"]
def assert_unauthorized(response: httpx.Response, scheme: str = "Bearer") -> None:
"""401 с challenge нужной схемы"""
assert_error(response, 401, "unauthorized")
assert response.headers["WWW-Authenticate"].startswith(scheme)
def read_all_messages(
api: httpx.Client, user: dict, chat_id: str, limit: int
) -> tuple[list[dict], int]:
@@ -41,3 +69,30 @@ def read_all_messages(
if page["next_cursor"] is None:
return items, pages
params = {"limit": limit, "cursor": page["next_cursor"]}
def compose(*args: str, stdin: str | None = None) -> str:
"""docker compose из корня репозитория; вывод не печатается (может быть секретен)"""
result = subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
input=stdin,
capture_output=True,
text=True,
timeout=120,
check=True,
)
return result.stdout
def psql(sql: str) -> str:
"""Запрос в PostgreSQL стенда изнутри контейнера; порт БД наружу не открыт"""
return compose(
"exec",
"-T",
"postgres",
"sh",
"-c",
'psql -X -q -tA -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
stdin=sql,
).strip()
+131
View File
@@ -0,0 +1,131 @@
"""Вход по Basic, opaque Bearer-сессия, неверный пароль и logout"""
import base64
from datetime import UTC, datetime
import httpx
import pytest
from helpers import (
assert_unauthorized,
auth,
basic,
psql,
public_user,
unique_username,
)
SESSIONS_PATH = "/api/v1/auth/sessions"
CURRENT_SESSION_PATH = "/api/v1/auth/sessions/current"
def test_login_returns_opaque_bearer_session(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
response = api.post(
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
)
assert response.status_code == 201, response.text
session = response.json()
assert set(session) == {"token", "token_type", "expires_at", "user"}
assert session["token_type"] == "Bearer"
assert session["user"] == public_user(alice)
assert len(session["token"]) >= 43 # 32 байта в base64url
assert alice["id"] not in session["token"]
assert alice["username"] not in session["token"]
assert session["token"] != alice["token"]
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
assert expires_at > datetime.now(UTC)
def test_wrong_password_and_unknown_user_are_indistinguishable(
api: httpx.Client, make_user
) -> None:
alice = make_user("alice")
wrong = api.post(SESSIONS_PATH, headers=basic(alice["username"], "Wrong-pass-123"))
unknown = api.post(
SESSIONS_PATH, headers=basic(unique_username("ghost"), "Wrong-pass-123")
)
for response in (wrong, unknown):
assert_unauthorized(response, scheme="Basic")
assert 'realm="messenger"' in response.headers["WWW-Authenticate"]
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
@pytest.mark.parametrize(
"authorization",
[
None,
"",
"Basic",
"Basic !!!not-base64!!!",
"Basic " + base64.b64encode(b"no-colon-here").decode(),
"Basic " + base64.b64encode(b"\xff\xfe:password").decode(),
"Bearer some-token",
],
)
def test_malformed_basic_is_unauthorized(
api: httpx.Client, authorization: str | None
) -> None:
headers = {} if authorization is None else {"Authorization": authorization}
assert_unauthorized(api.post(SESSIONS_PATH, headers=headers), scheme="Basic")
def test_utf8_password_with_colon(api: httpx.Client) -> None:
username = unique_username("utf")
password = "пароль:с:двоеточием 🔐"
body = {"username": username, "display_name": "x", "password": password}
assert api.post("/api/v1/users", json=body).status_code == 201
assert api.post(SESSIONS_PATH, headers=basic(username, password)).status_code == 201
assert_unauthorized(
api.post(SESSIONS_PATH, headers=basic(username, "пароль:с:двоеточием")),
scheme="Basic",
)
def test_basic_is_rejected_on_business_endpoints(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
headers = basic(alice["username"], alice["password"])
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
def test_logout_revokes_only_current_session(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
second = api.post(
SESSIONS_PATH, headers=basic(alice["username"], alice["password"])
)
other_session = {**alice, "token": second.json()["token"]}
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
response = api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
assert response.status_code == 204
assert response.content == b""
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
assert_unauthorized(api.delete(CURRENT_SESSION_PATH, headers=auth(alice)))
assert api.get("/api/v1/users/me", headers=auth(other_session)).status_code == 200
def test_logout_without_token(api: httpx.Client) -> None:
assert_unauthorized(api.delete(CURRENT_SESSION_PATH))
assert_unauthorized(
api.delete(CURRENT_SESSION_PATH, headers={"Authorization": "Bearer unknown"})
)
def test_relogin_after_logout(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
api.delete(CURRENT_SESSION_PATH, headers=auth(alice))
again = api.post(SESSIONS_PATH, headers=basic(alice["username"], alice["password"]))
assert again.status_code == 201
renewed = {**alice, "token": again.json()["token"]}
assert api.get("/api/v1/users/me", headers=auth(renewed)).status_code == 200
def test_password_is_not_stored_in_plaintext(make_user) -> None:
"""Проверка в БД стенда: в users лежит PHC-строка Argon2id, а не пароль"""
alice = make_user("alice")
stored = psql(
f"SELECT password_hash FROM users WHERE username = '{alice['username']}';"
)
assert stored.startswith("$argon2id$")
assert alice["password"] not in stored
+2 -2
View File
@@ -5,7 +5,7 @@ import json
import time
import httpx
from helpers import read_all_messages
from helpers import auth, read_all_messages
CLIENTS = 10
MESSAGES_PER_CLIENT = 10
@@ -21,7 +21,7 @@ async def _send_concurrently(
async def client_worker(user: dict) -> list[int]:
async with httpx.AsyncClient(
base_url=base_url, headers={"X-User-Id": user["id"]}, timeout=30
base_url=base_url, headers=auth(user), timeout=30
) as client:
await start.wait()
responses = await asyncio.gather(
+129
View File
@@ -0,0 +1,129 @@
"""
Отказы зависимостей: Valkey и PostgreSQL останавливаются через docker compose.
Тесты меняют состояние стенда (stop/start контейнеров, volumes сохраняются),
поэтому запускаются только явно: make test-failures (RUN_FAILURE_TESTS=1).
"""
import os
import time
from collections.abc import Iterator
import httpx
import pytest
from helpers import assert_error, assert_unauthorized, auth, basic, compose
pytestmark = pytest.mark.skipif(
os.environ.get("RUN_FAILURE_TESTS") != "1",
reason="останавливает контейнеры стенда: запускайте через make test-failures",
)
READY_TIMEOUT_SEC = 60
# Ответ при упавшей зависимости должен быть быстрым, а не висеть до таймаута клиента
BOUNDED_RESPONSE_SEC = 3
def wait_ready(api: httpx.Client) -> None:
deadline = time.monotonic() + READY_TIMEOUT_SEC
while time.monotonic() < deadline:
try:
if api.get("/health/ready").status_code == 200:
return
except httpx.TransportError:
pass
time.sleep(0.5)
raise AssertionError("API не стал готов после восстановления зависимости")
@pytest.fixture
def valkey_stopped(api: httpx.Client) -> Iterator[None]:
compose("stop", "valkey")
try:
yield
finally:
compose("start", "valkey")
compose("up", "-d", "--wait", "valkey")
wait_ready(api)
@pytest.fixture
def postgres_stopped(api: httpx.Client) -> Iterator[None]:
compose("stop", "postgres")
try:
yield
finally:
compose("start", "postgres")
compose("up", "-d", "--wait", "postgres")
wait_ready(api)
def test_valkey_down_cache_is_bypassed(
api: httpx.Client, make_user, make_chat, send_message, valkey_stopped
) -> None:
"""Без Valkey всё работает через PostgreSQL: вход, Bearer, запись, logout"""
alice = make_user("alice")
started = time.monotonic()
me = api.get("/api/v1/users/me", headers=auth(alice))
assert me.status_code == 200, me.text
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
chat = make_chat(alice, [alice])
send_message(alice, chat, "без кэша")
assert api.get("/health/ready").status_code == 200
assert (
api.delete("/api/v1/auth/sessions/current", headers=auth(alice)).status_code
== 204
)
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
assert_unauthorized(api.get("/api/v1/users/me"))
def test_logout_during_valkey_outage_is_not_resurrected(
api: httpx.Client, make_user
) -> None:
"""
Сессия попала в кэш, затем Valkey упал и пользователь вышел. После подъёма
Valkey (без persistence — пустой) отозванный токен не принимается.
"""
alice = make_user("alice")
assert api.get("/api/v1/users/me", headers=auth(alice)).status_code == 200
compose("stop", "valkey")
try:
response = api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
assert response.status_code == 204
finally:
compose("start", "valkey")
compose("up", "-d", "--wait", "valkey")
wait_ready(api)
assert_unauthorized(api.get("/api/v1/users/me", headers=auth(alice)))
def test_postgres_down_returns_bounded_503_and_no_anonymous_access(
api: httpx.Client, make_user, postgres_stopped
) -> None:
alice_token_unused = {"token": "x" * 43}
started = time.monotonic()
ready = api.get("/health/ready")
assert_error(ready, 503, "unavailable")
assert time.monotonic() - started < BOUNDED_RESPONSE_SEC
# Анонимный запрос остаётся 401, неизвестный токен не принимается как доверенный
assert_unauthorized(api.get("/api/v1/users/me"))
unknown = api.get("/api/v1/users/me", headers=auth(alice_token_unused))
assert_error(unknown, 503, "unavailable")
assert "asyncpg" not in unknown.text and "postgres" not in unknown.text.lower()
body = {"username": "st_pg_down", "display_name": "x", "password": "P" * 12}
assert_error(api.post("/api/v1/users", json=body), 503, "unavailable")
login = api.post("/api/v1/auth/sessions", headers=basic("st_pg_down", "P" * 12))
assert_error(login, 503, "unavailable")
def test_session_survives_postgres_restart(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
compose("restart", "postgres")
wait_ready(api)
chats = api.get("/api/v1/chats", headers=auth(alice))
assert chats.status_code == 200, chats.text
+55
View File
@@ -0,0 +1,55 @@
"""
Истечение сессии при коротком SESSION_TTL_SECONDS.
Нужен отдельный API с SESSION_TTL_SECONDS=2: make test-expiry поднимает
api-short-ttl на :8081 поверх тех же PostgreSQL и Valkey.
"""
import os
import time
from datetime import UTC, datetime
import httpx
import pytest
from conftest import register_and_login
from helpers import assert_unauthorized, auth, basic
EXPIRY_BASE_URL = os.environ.get("EXPIRY_BASE_URL")
SHORT_TTL_SEC = 2
pytestmark = pytest.mark.skipif(
not EXPIRY_BASE_URL, reason="EXPIRY_BASE_URL не задан: запустите make test-expiry"
)
@pytest.fixture
def short_api() -> httpx.Client:
assert EXPIRY_BASE_URL is not None
with httpx.Client(base_url=EXPIRY_BASE_URL, timeout=10) as client:
yield client
def test_session_expires_after_short_ttl(short_api: httpx.Client) -> None:
alice = register_and_login(short_api, "ttl")
me = short_api.get("/api/v1/users/me", headers=auth(alice))
assert me.status_code == 200, me.text
time.sleep(SHORT_TTL_SEC + 1)
# Сессия уже лежала в кэше после первого запроса: истечь должна и там
assert_unauthorized(short_api.get("/api/v1/users/me", headers=auth(alice)))
assert_unauthorized(short_api.get("/api/v1/chats", headers=auth(alice)))
assert_unauthorized(
short_api.delete("/api/v1/auth/sessions/current", headers=auth(alice))
)
def test_expires_at_matches_short_ttl(short_api: httpx.Client) -> None:
before = datetime.now(UTC)
alice = register_and_login(short_api, "ttl")
session = short_api.post(
"/api/v1/auth/sessions", headers=basic(alice["username"], alice["password"])
).json()
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
lifetime = (expires_at - before).total_seconds()
assert 0 < lifetime <= SHORT_TTL_SEC + 1
+16 -8
View File
@@ -4,6 +4,8 @@ import httpx
import pytest
from helpers import assert_error, auth
PASSWORD = "Valid-password-123"
MALFORMED_BODIES = [
b'{"username": "abc",',
b"not json at all",
@@ -42,14 +44,20 @@ def test_malformed_json_on_create_chat_and_message(
[
[],
"alice",
{"username": "valid_name"},
{"username": 123, "display_name": "x"},
{"username": "valid_name", "display_name": None},
{"username": "valid_name", "display_name": "x", "is_admin": True},
{"username": "Upper_Case", "display_name": "x"},
{"username": "ab", "display_name": "x"},
{"username": "valid_name", "display_name": " "},
{"username": "valid_name", "display_name": "я" * 101},
{"username": "valid_name", "password": PASSWORD},
{"username": 123, "display_name": "x", "password": PASSWORD},
{"username": "valid_name", "display_name": None, "password": PASSWORD},
{
"username": "valid_name",
"display_name": "x",
"password": PASSWORD,
"is_admin": True,
},
{"username": "Upper_Case", "display_name": "x", "password": PASSWORD},
{"username": "ab", "display_name": "x", "password": PASSWORD},
{"username": "valid_name", "display_name": " ", "password": PASSWORD},
{"username": "valid_name", "display_name": "я" * 101, "password": PASSWORD},
{"username": "valid_name", "display_name": "a\u0000b", "password": PASSWORD},
],
)
def test_invalid_user_payload(api: httpx.Client, body: object) -> None:
+20 -2
View File
@@ -42,14 +42,32 @@ def test_unicode_is_preserved(
assert alice["display_name"] == name
chat = make_chat(alice, [alice], title="Чат 🚀 中文")
assert chat["title"] == "Чат 🚀 中文"
text = "Привет, мир 👋 — «кавычки» \u0000 и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
text = "Привет, мир 👋 — «кавычки» \t\n и 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"
message = send_message(alice, chat, text)
assert message["text"] == text
page = api.get(f"/api/v1/chats/{chat['id']}/messages", headers=auth(alice)).json()
assert page["items"][0]["text"] == text
def test_sender_is_taken_from_x_user_id(make_user, make_chat, send_message) -> None:
def test_nul_character_is_rejected(api: httpx.Client, make_user, make_chat) -> None:
"""PostgreSQL text не хранит U+0000: отказ 400 до записи, а не 500"""
alice = make_user("alice")
chat = make_chat(alice, [alice])
response = api.post(
f"/api/v1/chats/{chat['id']}/messages",
json={"text": "до\u0000после"},
headers=auth(alice),
)
assert_error(response, 400, "invalid_request")
response = api.post(
"/api/v1/chats",
json={"title": "a\u0000b", "member_ids": [alice["id"]]},
headers=auth(alice),
)
assert_error(response, 400, "invalid_request")
def test_sender_is_taken_from_session(make_user, make_chat, send_message) -> None:
alice = make_user("alice")
bob = make_user("bob")
chat = make_chat(alice, [alice, bob])
+95
View File
@@ -0,0 +1,95 @@
"""Гонка регистрации одинакового username и rollback создания чата"""
import asyncio
import json
import uuid
import httpx
from helpers import assert_error, auth, psql, unique_password, unique_username
PARALLEL_REGISTRATIONS = 20
async def _register_concurrently(base_url: str, username: str) -> list[int]:
"""Все запросы стартуют по одному сигналу, у каждого свой пароль"""
start = asyncio.Event()
async def register(client: httpx.AsyncClient) -> int:
await start.wait()
body = {
"username": username,
"display_name": "Гонка",
"password": unique_password(),
}
response = await client.post("/api/v1/users", json=body)
return response.status_code
limits = httpx.Limits(max_connections=PARALLEL_REGISTRATIONS)
async with httpx.AsyncClient(
base_url=base_url, timeout=30, limits=limits
) as client:
tasks = [
asyncio.create_task(register(client)) for _ in range(PARALLEL_REGISTRATIONS)
]
await asyncio.sleep(0)
start.set()
return list(await asyncio.gather(*tasks))
def test_same_username_race_creates_exactly_one_user(base_url: str) -> None:
username = unique_username("race")
statuses = asyncio.run(_register_concurrently(base_url, username))
stored = psql(f"SELECT count(*) FROM users WHERE username = '{username}';")
print(
"\nREGISTRATION RACE:",
json.dumps(
{
"requests": len(statuses),
"status_201": statuses.count(201),
"status_409": statuses.count(409),
"rows_in_db": int(stored),
}
),
)
assert statuses.count(201) == 1
assert statuses.count(409) == PARALLEL_REGISTRATIONS - 1
assert stored == "1"
def test_failed_chat_creation_is_rolled_back(api: httpx.Client, make_user) -> None:
"""
Строка chats вставляется первой, затем участники нарушают FK (неизвестный
пользователь в конце списка). После 400 в БД не должно остаться ни чата
с этим title, ни его участников: откатилась вся транзакция.
"""
alice = make_user("alice")
bob = make_user("bob")
title = f"rollback-{uuid.uuid4().hex}"
body = {"title": title, "member_ids": [alice["id"], bob["id"], str(uuid.uuid4())]}
response = api.post("/api/v1/chats", json=body, headers=auth(alice))
assert_error(response, 400, "invalid_request")
assert psql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0"
orphan_members = psql(
"SELECT count(*) FROM chat_members m "
"LEFT JOIN chats c ON c.id = m.chat_id WHERE c.id IS NULL;"
)
assert orphan_members == "0"
listed = api.get("/api/v1/chats", params={"limit": 100}, headers=auth(alice))
assert all(chat["title"] != title for chat in listed.json()["items"])
def test_successful_chat_creation_commits_all_members(
api: httpx.Client, make_user
) -> None:
alice = make_user("alice")
bob = make_user("bob")
title = f"commit-{uuid.uuid4().hex}"
body = {"title": title, "member_ids": [bob["id"], alice["id"]]}
chat = api.post("/api/v1/chats", json=body, headers=auth(alice)).json()
assert chat["member_ids"] == [bob["id"], alice["id"]]
members = psql(f"SELECT count(*) FROM chat_members WHERE chat_id = '{chat['id']}';")
assert members == "2"
again = api.get(f"/api/v1/chats/{chat['id']}", headers=auth(bob)).json()
assert again == chat
+73 -18
View File
@@ -1,40 +1,95 @@
"""Дубликат username и идентификация через X-User-Id"""
"""Регистрация, дубликат username и идентификация только через Bearer"""
import uuid
import httpx
import pytest
from helpers import assert_error, unique_username
from helpers import (
assert_error,
assert_unauthorized,
auth,
public_user,
unique_password,
unique_username,
)
def test_duplicate_username_is_conflict(api: httpx.Client) -> None:
username = unique_username("dup")
first = api.post("/api/v1/users", json={"username": username, "display_name": "A"})
assert first.status_code == 201
second = api.post("/api/v1/users", json={"username": username, "display_name": "B"})
assert_error(second, 409, "conflict")
me = api.get("/api/v1/users/me", headers={"X-User-Id": first.json()["id"]})
assert me.json()["display_name"] == "A"
def test_duplicate_username_is_conflict(api: httpx.Client, make_user) -> None:
alice = make_user("dup")
body = {
"username": alice["username"],
"display_name": "B",
"password": unique_password(),
}
assert_error(api.post("/api/v1/users", json=body), 409, "conflict")
me = api.get("/api/v1/users/me", headers=auth(alice))
assert me.json()["display_name"] == alice["display_name"]
def test_registration_never_returns_password(api: httpx.Client) -> None:
password = unique_password()
body = {
"username": unique_username("pw"),
"display_name": "x",
"password": password,
}
response = api.post("/api/v1/users", json=body)
assert response.status_code == 201
assert set(response.json()) == {"id", "username", "display_name", "created_at"}
assert password not in response.text
@pytest.mark.parametrize(
"password",
[None, "", "короткий", "x" * 11, "x" * 129, 123456789012],
)
def test_invalid_password_is_rejected(api: httpx.Client, password: object) -> None:
body: dict[str, object] = {"username": unique_username("pw"), "display_name": "x"}
if password is not None:
body["password"] = password
assert_error(api.post("/api/v1/users", json=body), 400, "invalid_request")
def test_password_length_is_counted_in_code_points(api: httpx.Client) -> None:
for password in ("😀" * 12, "😀" * 128):
body = {
"username": unique_username("pw"),
"display_name": "x",
"password": password,
}
assert api.post("/api/v1/users", json=body).status_code == 201
@pytest.mark.parametrize(
"headers",
[
{},
{"X-User-Id": ""},
{"X-User-Id": "not-a-uuid"},
{"X-User-Id": str(uuid.uuid4())},
{"Authorization": ""},
{"Authorization": "Bearer"},
{"Authorization": "Bearer not-a-real-token"},
{"Authorization": "Bearer " + "x" * 5000},
{"Authorization": "Token abc"},
],
)
def test_missing_or_unknown_user_is_unauthorized(
def test_missing_or_unknown_token_is_unauthorized(
api: httpx.Client, headers: dict
) -> None:
assert_error(api.get("/api/v1/users/me", headers=headers), 401, "unauthorized")
assert_error(api.get("/api/v1/chats", headers=headers), 401, "unauthorized")
assert_unauthorized(api.get("/api/v1/users/me", headers=headers))
assert_unauthorized(api.get("/api/v1/chats", headers=headers))
def test_x_user_id_gives_no_access(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
eve = make_user("eve")
assert_unauthorized(api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}))
me = api.get("/api/v1/users/me", headers={**auth(alice), "X-User-Id": eve["id"]})
assert me.json()["id"] == alice["id"]
unknown = {"X-User-Id": str(uuid.uuid4())}
assert_unauthorized(api.get("/api/v1/chats", headers=unknown))
def test_current_user(api: httpx.Client, make_user) -> None:
alice = make_user("alice")
me = api.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]})
me = api.get("/api/v1/users/me", headers=auth(alice))
assert me.status_code == 200
assert me.json() == alice
assert me.json() == public_user(alice)