ЛР2: PostgreSQL, сессии (Basic + Bearer), Compose, миграции
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Отдельная тестовая база; задаётся до импорта приложения (настройки читаются при импорте).
|
||||
TEST_DB_NAME = "messenger_test"
|
||||
os.environ["APP_CONFIG__DB__NAME"] = TEST_DB_NAME
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from core.db import build_url, engine
|
||||
from main import app
|
||||
|
||||
APP_DIR = Path(__file__).resolve().parents[1] / "app"
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def test_database():
|
||||
# CREATE DATABASE нельзя выполнить в транзакции, поэтому AUTOCOMMIT.
|
||||
admin = create_engine(build_url().set(database="postgres"), isolation_level="AUTOCOMMIT")
|
||||
with admin.connect() as connection:
|
||||
exists = connection.scalar(text("SELECT 1 FROM pg_database WHERE datname = :name"), {"name": TEST_DB_NAME})
|
||||
if not exists:
|
||||
connection.execute(text(f'CREATE DATABASE "{TEST_DB_NAME}"'))
|
||||
admin.dispose()
|
||||
|
||||
command.upgrade(Config(str(APP_DIR / "alembic.ini")), "head")
|
||||
yield
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_database():
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("TRUNCATE users, sessions, chats, chat_members, messages"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return {"Authorization": "Basic " + credential}
|
||||
|
||||
|
||||
def login(client, username, password=PASSWORD):
|
||||
response = client.post("/api/v1/auth/sessions", headers=basic(username, password))
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
|
||||
def bearer(token):
|
||||
return {"Authorization": "Bearer " + token}
|
||||
|
||||
|
||||
def create_user(client, username):
|
||||
"""Регистрация + вход; заголовок авторизации — в поле "auth"."""
|
||||
response = client.post("/api/v1/users", json={"username": username, "display_name": "Имя " + username,
|
||||
"password": PASSWORD})
|
||||
assert response.status_code == 201
|
||||
user = response.json()
|
||||
user["token"] = login(client, username)["token"]
|
||||
user["auth"] = bearer(user["token"])
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def alice(client):
|
||||
return create_user(client, "alice")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bob(client):
|
||||
return create_user(client, "bob")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def eve(client):
|
||||
return create_user(client, "eve")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def chat(client, alice, bob):
|
||||
"""Чат alice и bob; eve в него не входит."""
|
||||
response = client.post("/api/v1/chats", headers=alice["auth"],
|
||||
json={"title": "Тестовый чат", "member_ids": [alice["id"], bob["id"]]})
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
|
||||
def assert_error(response, status_code, code):
|
||||
assert response.status_code == status_code
|
||||
body = response.json()
|
||||
assert body["error"]["code"] == code
|
||||
assert body["error"]["request_id"] == response.headers["X-Request-Id"]
|
||||
@@ -0,0 +1,92 @@
|
||||
import time
|
||||
|
||||
import jwt
|
||||
|
||||
from conftest import PASSWORD, assert_error, basic, bearer, login
|
||||
from core.config import settings
|
||||
|
||||
|
||||
def assert_challenge(response, scheme):
|
||||
assert response.headers["WWW-Authenticate"].startswith(scheme + ' realm="messenger"')
|
||||
|
||||
|
||||
def test_login_returns_session(client, alice):
|
||||
session = login(client, "alice")
|
||||
assert session["token_type"] == "Bearer"
|
||||
assert len(session["token"]) >= 32
|
||||
assert session["expires_at"].endswith("Z")
|
||||
assert session["user"]["id"] == alice["id"]
|
||||
assert "password" not in session["user"] and "password_hash" not in session["user"]
|
||||
assert login(client, "alice")["token"] != session["token"]
|
||||
|
||||
|
||||
def test_jwt_payload_contains_sub_exp_jti(client, alice):
|
||||
payload = jwt.decode(alice["token"], options={"verify_signature": False})
|
||||
assert payload["sub"] == alice["id"]
|
||||
assert payload["exp"] - payload["iat"] == settings.jwt.session_ttl_seconds
|
||||
assert len(payload["jti"]) >= 43
|
||||
|
||||
|
||||
def test_wrong_password_and_unknown_user_give_same_401(client, alice):
|
||||
wrong = client.post("/api/v1/auth/sessions", headers=basic("alice", "Wrong-password-1"))
|
||||
unknown = client.post("/api/v1/auth/sessions", headers=basic("nobody", PASSWORD))
|
||||
for response in (wrong, unknown):
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert_challenge(response, "Basic")
|
||||
assert 'charset="UTF-8"' in response.headers["WWW-Authenticate"]
|
||||
assert wrong.json()["error"]["message"] == unknown.json()["error"]["message"]
|
||||
|
||||
|
||||
def test_malformed_basic_returns_401(client):
|
||||
for header in ("", "Basic", "Basic !!!not-base64!!!", "Bearer abc", "Basic " + "YWxpY2U="): # последний — без ':'
|
||||
response = client.post("/api/v1/auth/sessions", headers={"Authorization": header})
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert_challenge(response, "Basic")
|
||||
|
||||
|
||||
def test_password_with_colon_and_unicode(client):
|
||||
password = "пароль:с:двоеточиями 👋"
|
||||
client.post("/api/v1/users", json={"username": "colon", "display_name": "C", "password": password})
|
||||
assert login(client, "colon", password)["user"]["username"] == "colon"
|
||||
|
||||
|
||||
def test_protected_endpoint_requires_bearer(client, alice):
|
||||
cases = [{}, basic("alice", PASSWORD), bearer("not-a-jwt"), {"Authorization": "Bearer"}]
|
||||
for headers in cases:
|
||||
response = client.get("/api/v1/users/me", headers=headers)
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert_challenge(response, "Bearer")
|
||||
|
||||
|
||||
def test_x_user_id_does_not_override_token(client, alice, eve):
|
||||
response = client.get("/api/v1/users/me", headers={**alice["auth"], "X-User-Id": eve["id"]})
|
||||
assert response.json()["id"] == alice["id"]
|
||||
|
||||
|
||||
def test_forged_token_is_rejected(client, alice):
|
||||
payload = jwt.decode(alice["token"], options={"verify_signature": False})
|
||||
forged = jwt.encode(payload, "attacker-key-attacker-key-attacker-key!!", algorithm="HS256")
|
||||
assert_error(client.get("/api/v1/users/me", headers=bearer(forged)), 401, "unauthorized")
|
||||
unsigned = jwt.encode(payload, None, algorithm="none")
|
||||
assert_error(client.get("/api/v1/users/me", headers=bearer(unsigned)), 401, "unauthorized")
|
||||
|
||||
|
||||
def test_logout_revokes_only_current_token(client, alice):
|
||||
second = login(client, "alice")["token"]
|
||||
response = client.delete("/api/v1/auth/sessions/current", headers=alice["auth"])
|
||||
assert response.status_code == 204
|
||||
assert response.content == b""
|
||||
assert_error(client.get("/api/v1/users/me", headers=alice["auth"]), 401, "unauthorized")
|
||||
assert_error(client.delete("/api/v1/auth/sessions/current", headers=alice["auth"]), 401, "unauthorized")
|
||||
# Другая сессия того же пользователя продолжает работать.
|
||||
assert client.get("/api/v1/users/me", headers=bearer(second)).status_code == 200
|
||||
|
||||
|
||||
def test_session_expires(client, alice, monkeypatch):
|
||||
monkeypatch.setattr(settings.jwt, "session_ttl_seconds", 1)
|
||||
token = login(client, "alice")["token"]
|
||||
assert client.get("/api/v1/users/me", headers=bearer(token)).status_code == 200
|
||||
time.sleep(2.1)
|
||||
response = client.get("/api/v1/users/me", headers=bearer(token))
|
||||
assert_error(response, 401, "unauthorized")
|
||||
assert_challenge(response, "Bearer")
|
||||
@@ -0,0 +1,54 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import assert_error
|
||||
from core.db import engine
|
||||
|
||||
|
||||
def count_rows(table):
|
||||
with engine.connect() as connection:
|
||||
return connection.scalar(text(f"SELECT count(*) FROM {table}"))
|
||||
|
||||
|
||||
def test_unknown_member_returns_400_and_nothing_is_saved(client, alice):
|
||||
response = client.post("/api/v1/chats", headers=alice["auth"],
|
||||
json={"title": "С призраком", "member_ids": [alice["id"], str(uuid.uuid4())]})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
assert count_rows("chats") == 0
|
||||
assert count_rows("chat_members") == 0
|
||||
|
||||
|
||||
def test_created_chat_is_stored_with_members(client, chat, alice, bob):
|
||||
assert sorted(chat["member_ids"]) == sorted([alice["id"], bob["id"]])
|
||||
assert count_rows("chats") == 1
|
||||
assert count_rows("chat_members") == 2
|
||||
again = client.get("/api/v1/chats/" + chat["id"], headers=bob["auth"]).json()
|
||||
assert again == chat
|
||||
|
||||
|
||||
def test_foreign_chat_returns_404(client, chat, eve):
|
||||
headers = eve["auth"]
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
|
||||
assert_error(client.get(path, headers=headers), 404, "not_found")
|
||||
assert_error(client.get(path + "/messages", headers=headers), 404, "not_found")
|
||||
assert_error(client.post(path + "/messages", headers=headers, json={"text": "чужое"}), 404, "not_found")
|
||||
assert client.get("/api/v1/chats", headers=headers).json()["items"] == []
|
||||
|
||||
|
||||
def test_member_sees_chat(client, chat, bob):
|
||||
response = client.get("/api/v1/chats", headers=bob["auth"])
|
||||
assert [c["id"] for c in response.json()["items"]] == [chat["id"]]
|
||||
|
||||
|
||||
def test_creator_must_be_member(client, alice, bob):
|
||||
response = client.post("/api/v1/chats", headers=alice["auth"],
|
||||
json={"title": "Без меня", "member_ids": [bob["id"]]})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_duplicate_members_return_400(client, alice):
|
||||
response = client.post("/api/v1/chats", headers=alice["auth"],
|
||||
json={"title": "Дубли", "member_ids": [alice["id"], alice["id"]]})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,66 @@
|
||||
from conftest import assert_error
|
||||
|
||||
|
||||
def test_empty_message_returns_400(client, chat, alice):
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
headers = alice["auth"]
|
||||
|
||||
assert_error(client.post(path, headers=headers, json={"text": ""}), 400, "invalid_request")
|
||||
assert_error(client.post(path, headers=headers, json={"text": " \n\t"}), 400, "invalid_request")
|
||||
|
||||
|
||||
def test_sender_is_taken_from_token(client, chat, alice, bob):
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
response = client.post(path, headers=bob["auth"], json={"text": "Привет 👋"})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["sender_id"] == bob["id"]
|
||||
assert response.json()["text"] == "Привет 👋"
|
||||
|
||||
spoof = client.post(path, headers=bob["auth"], json={"text": "x", "sender_id": alice["id"]})
|
||||
assert_error(spoof, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_pagination_over_several_pages(client, chat, alice):
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
headers = alice["auth"]
|
||||
sent = [client.post(path, headers=headers, json={"text": f"сообщение {i}"}).json() for i in range(7)]
|
||||
|
||||
received = []
|
||||
pages = 0
|
||||
cursor = None
|
||||
while True:
|
||||
params = {"limit": 3}
|
||||
if cursor:
|
||||
params["cursor"] = cursor
|
||||
page = client.get(path, headers=headers, params=params).json()
|
||||
received += page["items"]
|
||||
pages += 1
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
|
||||
assert pages == 3 # 3 + 3 + 1
|
||||
assert received == sent # тот же порядок, ничего не потеряно
|
||||
assert len({m["id"] for m in received}) == 7 # без повторов
|
||||
|
||||
|
||||
def test_cursor_from_another_chat_returns_400(client, chat, alice):
|
||||
headers = alice["auth"]
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
for i in range(2):
|
||||
client.post(path, headers=headers, json={"text": f"m{i}"})
|
||||
cursor = client.get(path, headers=headers, params={"limit": 1}).json()["next_cursor"]
|
||||
|
||||
other = client.post("/api/v1/chats", headers=headers, json={"title": "Другой", "member_ids": [alice["id"]]}).json()
|
||||
response = client.get("/api/v1/chats/" + other["id"] + "/messages", headers=headers, params={"cursor": cursor})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
response = client.get(path, headers=headers, params={"cursor": "мусор"})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_invalid_limit_returns_400(client, chat, alice):
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
for limit in (0, 101, "abc"):
|
||||
response = client.get(path, headers=alice["auth"], params={"limit": limit})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
@@ -0,0 +1,69 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import PASSWORD, assert_error
|
||||
from core.db import engine
|
||||
|
||||
|
||||
def test_invalid_json_returns_400(client):
|
||||
response = client.post("/api/v1/users", content=b'{"username": "bob",',
|
||||
headers={"Content-Type": "application/json"})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_extra_field_and_wrong_type_return_400(client):
|
||||
response = client.post("/api/v1/users", json={"username": "bob", "display_name": "Bob", "password": PASSWORD,
|
||||
"admin": True})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
response = client.post("/api/v1/users", json={"username": "bob", "display_name": 123, "password": PASSWORD})
|
||||
assert_error(response, 400, "invalid_request")
|
||||
|
||||
|
||||
def test_duplicate_username_returns_409(client, alice):
|
||||
response = client.post("/api/v1/users", json={"username": "alice", "display_name": "Другая Алиса",
|
||||
"password": PASSWORD})
|
||||
assert_error(response, 409, "conflict")
|
||||
|
||||
|
||||
def test_unicode_display_name_is_kept(client):
|
||||
response = client.post("/api/v1/users", json={"username": "uni", "display_name": "Алиса 👋",
|
||||
"password": PASSWORD})
|
||||
assert response.status_code == 201
|
||||
assert response.json()["display_name"] == "Алиса 👋"
|
||||
|
||||
|
||||
def test_password_is_required_and_length_checked(client):
|
||||
for password in (None, "short", "x" * 129):
|
||||
body = {"username": "pwd", "display_name": "P"}
|
||||
if password is not None:
|
||||
body["password"] = password
|
||||
assert_error(client.post("/api/v1/users", json=body), 400, "invalid_request")
|
||||
# 12 символов (не байт) — допустимо.
|
||||
response = client.post("/api/v1/users", json={"username": "pwd", "display_name": "P", "password": "пароль123456"})
|
||||
assert response.status_code == 201
|
||||
|
||||
|
||||
def test_password_is_hashed_and_never_returned(client, alice):
|
||||
assert "password" not in alice and "password_hash" not in alice
|
||||
with engine.connect() as connection:
|
||||
stored = connection.scalar(text("SELECT password_hash FROM users WHERE username = 'alice'"))
|
||||
assert stored.startswith("$argon2id$")
|
||||
assert PASSWORD not in stored
|
||||
|
||||
|
||||
def test_me_returns_current_user(client, alice):
|
||||
response = client.get("/api/v1/users/me", headers=alice["auth"])
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {key: alice[key] for key in ("id", "username", "display_name", "created_at")}
|
||||
|
||||
|
||||
def test_x_user_id_no_longer_authenticates(client, alice):
|
||||
assert_error(client.get("/api/v1/users/me", headers={"X-User-Id": alice["id"]}), 401, "unauthorized")
|
||||
assert_error(client.get("/api/v1/users/me", headers={"X-User-Id": str(uuid.uuid4())}), 401, "unauthorized")
|
||||
|
||||
|
||||
def test_every_response_has_request_id(client):
|
||||
assert client.get("/health/live").headers["X-Request-Id"]
|
||||
assert client.get("/health/ready").headers["X-Request-Id"]
|
||||
assert_error(client.get("/no/such/path"), 404, "not_found")
|
||||
Reference in New Issue
Block a user