import time from datetime import datetime from fastapi.testclient import TestClient from app.main import create_app from tests.helpers import ( PASSWORD, assert_request_id, basic_header, bearer, create_user, login, register, ) def test_login_returns_opaque_bearer_session(client: TestClient): user = register(client) response = client.post( "/api/v1/auth/sessions", headers=basic_header(user["username"], user["password"]), ) assert response.status_code == 201 body = response.json() assert set(body) == {"token", "token_type", "expires_at", "user"} assert body["token_type"] == "Bearer" assert len(body["token"]) >= 43 # 256 бит в base64url assert body["token"] not in (user["id"], user["username"]) assert body["user"]["id"] == user["id"] assert body["expires_at"].endswith("Z") assert datetime.fromisoformat(body["expires_at"].replace("Z", "+00:00")) assert_request_id(response) def test_each_login_issues_a_different_token(client: TestClient): user = register(client) first = login(client, user) second = login(client, user) assert first["token"] != second["token"] def test_password_with_colon_works(client: TestClient): user = register(client, password="pass:with:colons-123") assert login(client, user)["token"] def test_unicode_password_works(client: TestClient): user = register(client, password="Пароль-с-юникодом-🔑-123") assert login(client, user)["token"] def test_wrong_password_and_unknown_user_look_identical(client: TestClient): user = register(client) wrong_password = client.post( "/api/v1/auth/sessions", headers=basic_header(user["username"], "wrong-password-123"), ) unknown_user = client.post( "/api/v1/auth/sessions", headers=basic_header("no_such_user", "wrong-password-123"), ) for response in (wrong_password, unknown_user): assert response.status_code == 401 assert response.json()["error"]["code"] == "unauthorized" assert response.headers["WWW-Authenticate"].startswith('Basic realm="messenger"') assert_request_id(response) assert wrong_password.json()["error"]["message"] == unknown_user.json()["error"]["message"] def test_login_requires_basic_scheme(client: TestClient): user = register(client) session = login(client, user) for headers in ({}, bearer(session), {"Authorization": "Basic !!!not-base64"}): response = client.post("/api/v1/auth/sessions", headers=headers) assert response.status_code == 401 assert response.headers["WWW-Authenticate"].startswith("Basic") def test_business_endpoints_require_bearer(client: TestClient): user = register(client) for headers in ( {}, basic_header(user["username"], user["password"]), {"Authorization": "Bearer "}, {"Authorization": "Bearer unknown-token-value"}, {"X-User-Id": user["id"]}, ): response = client.get("/api/v1/users/me", headers=headers) assert response.status_code == 401, headers assert response.json()["error"]["code"] == "unauthorized" assert response.headers["WWW-Authenticate"].startswith('Bearer realm="messenger"') assert_request_id(response) def test_x_user_id_cannot_override_bearer_identity(client: TestClient): alice = create_user(client) eve = create_user(client) response = client.get( "/api/v1/users/me", headers={**bearer(alice), "X-User-Id": eve["id"]}, ) assert response.status_code == 200 assert response.json()["id"] == alice["id"] def test_logout_revokes_only_current_session(client: TestClient): user = register(client) first = login(client, user) second = login(client, user) assert client.delete("/api/v1/auth/sessions/current", headers=bearer(first)).status_code == 204 assert client.get("/api/v1/users/me", headers=bearer(first)).status_code == 401 assert client.get("/api/v1/users/me", headers=bearer(second)).status_code == 200 def test_logout_twice_returns_401(client: TestClient): session = create_user(client) first = client.delete("/api/v1/auth/sessions/current", headers=bearer(session)) again = client.delete("/api/v1/auth/sessions/current", headers=bearer(session)) assert first.status_code == 204 assert first.content == b"" assert again.status_code == 401 def test_session_expires_after_ttl(make_settings): app = create_app(make_settings(session_ttl_seconds=2)) with TestClient(app) as client: session = create_user(client) assert client.get("/api/v1/users/me", headers=bearer(session)).status_code == 200 time.sleep(3) response = client.get("/api/v1/users/me", headers=bearer(session)) assert response.status_code == 401 assert response.headers["WWW-Authenticate"].startswith("Bearer") def test_token_is_not_stored_in_plaintext(client: TestClient, db_engine): from sqlalchemy import text session = create_user(client) with db_engine.connect() as connection: stored = connection.execute(text("SELECT token_hash FROM sessions")).scalars().all() assert stored and session["token"] not in stored def test_password_is_not_stored_in_plaintext(client: TestClient, db_engine): from sqlalchemy import text register(client, username="hash_check") with db_engine.connect() as connection: stored = connection.execute( text("SELECT password_hash FROM users WHERE username = 'hash_check'") ).scalar_one() assert PASSWORD not in stored assert stored.startswith("$argon2id$")