feat: add password login and bearer sessions
- Argon2id password hashes, KDF in a thread with its own limit - POST /auth/sessions with Basic, DELETE /auth/sessions/current - Bearer sessions in PostgreSQL, X-User-Id ignored - migration drops lab 1 data without passwords - student-tests on tokens, sessions spec and synced specs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,51 +1,81 @@
|
||||
"""Спек `identification`: заголовок `X-User-Id` лабы 1.
|
||||
"""Спек `identification`: Bearer на защищённых эндпоинтах с лабы 2.
|
||||
|
||||
Единственный модуль, который собирает заголовок сам, а не через
|
||||
`Actor.headers()`: проверяется именно заголовок. На лабе 2 модуль
|
||||
переписывается вместе со спеком.
|
||||
Единственный модуль, который собирает `Authorization` и `X-User-Id`
|
||||
сам, а не через `Actor.headers()`: проверяются именно заголовки.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
import secrets
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from api_client import API, Actor, Api
|
||||
from contract import assert_error, assert_ok, contract
|
||||
from api_client import API, Actor, Api, basic_auth, bearer_auth
|
||||
from contract import (
|
||||
BEARER_CHALLENGE,
|
||||
assert_error,
|
||||
assert_ok,
|
||||
assert_unauthorized,
|
||||
contract,
|
||||
)
|
||||
|
||||
ME = f"{API}/users/me"
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Корректный заголовок")
|
||||
def test_valid_header(api: Api, alice: Actor) -> None:
|
||||
resp = api.request("GET", ME, headers={"X-User-Id": alice.id})
|
||||
@pytest.mark.spec("identification", "Действующий токен")
|
||||
def test_valid_token(api: Api, alice: Actor) -> None:
|
||||
resp = api.request("GET", ME, headers=bearer_auth(alice.token))
|
||||
assert assert_ok(resp, 200, "User") == alice.user
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Нет заголовка")
|
||||
def test_no_header(api: Api) -> None:
|
||||
assert_error(api.request("GET", ME), 401)
|
||||
assert_unauthorized(api.request("GET", ME), BEARER_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Не UUID")
|
||||
def test_not_uuid(api: Api) -> None:
|
||||
resp = api.request("GET", ME, headers={"X-User-Id": "not-a-uuid"})
|
||||
assert_error(resp, 401)
|
||||
@pytest.mark.spec("identification", "Неизвестный токен")
|
||||
def test_unknown_token(api: Api) -> None:
|
||||
for token in (secrets.token_urlsafe(32), "x"):
|
||||
resp = api.request("GET", ME, headers=bearer_auth(token))
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
# схема без токена — тот же ответ
|
||||
resp = api.request("GET", ME, headers={"Authorization": "Bearer"})
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Неизвестный пользователь")
|
||||
def test_unknown_user(api: Api) -> None:
|
||||
resp = api.request("GET", ME, headers={"X-User-Id": str(uuid.uuid4())})
|
||||
assert_error(resp, 401)
|
||||
@pytest.mark.spec("identification", "Basic на бизнес-эндпоинте")
|
||||
def test_basic_on_business_endpoint(api: Api, alice: Actor) -> None:
|
||||
resp = api.request(
|
||||
"GET",
|
||||
ME,
|
||||
headers=basic_auth(alice.username, alice.password),
|
||||
)
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Только X-User-Id")
|
||||
def test_only_user_id_header(api: Api, alice: Actor) -> None:
|
||||
resp = api.request("GET", ME, headers={"X-User-Id": alice.id})
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "X-User-Id не меняет владельца")
|
||||
def test_user_id_header_ignored(api: Api, alice: Actor, eve: Actor) -> None:
|
||||
resp = api.request(
|
||||
"GET",
|
||||
ME,
|
||||
headers={**bearer_auth(alice.token), "X-User-Id": eve.id},
|
||||
)
|
||||
assert assert_ok(resp, 200, "User") == alice.user
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Чужой чат без заголовка")
|
||||
def test_chat_without_header(api: Api, chat: dict[str, Any]) -> None:
|
||||
assert_error(api.request("GET", f"{API}/chats/{chat['id']}"), 401)
|
||||
def test_chat_without_token(api: Api, chat: dict[str, Any]) -> None:
|
||||
resp = api.request("GET", f"{API}/chats/{chat['id']}")
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Невалидное поле без заголовка")
|
||||
def test_invalid_field_without_header(
|
||||
def test_invalid_field_without_token(
|
||||
api: Api,
|
||||
alice: Actor,
|
||||
chat: dict[str, Any],
|
||||
@@ -55,16 +85,16 @@ def test_invalid_field_without_header(
|
||||
f"{API}/chats/{chat['id']}/messages",
|
||||
json={"text": ""},
|
||||
)
|
||||
assert_error(resp, 401)
|
||||
assert_unauthorized(resp, BEARER_CHALLENGE)
|
||||
assert api.all_messages(alice, chat["id"]) == []
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Битый JSON без заголовка")
|
||||
def test_malformed_json_without_header(
|
||||
def test_malformed_json_without_token(
|
||||
api: Api,
|
||||
chat: dict[str, Any],
|
||||
) -> None:
|
||||
# согласованное расхождение: битый JSON отклоняется до идентификации
|
||||
# согласованное расхождение: битый JSON отклоняется до аутентификации
|
||||
resp = api.request(
|
||||
"POST",
|
||||
f"{API}/chats/{chat['id']}/messages",
|
||||
@@ -75,12 +105,19 @@ def test_malformed_json_without_header(
|
||||
|
||||
|
||||
@pytest.mark.spec("identification", "Схема в openapi.json")
|
||||
def test_security_scheme_in_openapi(api: Api) -> None:
|
||||
def test_security_schemes_in_openapi(api: Api) -> None:
|
||||
resp = api.request("GET", "/openapi.json")
|
||||
assert resp.status_code == 200
|
||||
served = resp.json()
|
||||
expected = contract()["components"]["securitySchemes"]["devUser"]
|
||||
schemes = served["components"]["securitySchemes"]
|
||||
expected = contract()["components"]["securitySchemes"]
|
||||
|
||||
assert served["components"]["securitySchemes"]["devUser"] == expected
|
||||
assert served["paths"][ME]["get"]["security"] == [{"devUser": []}]
|
||||
assert not served["paths"][f"{API}/users"]["post"].get("security")
|
||||
assert schemes["bearerAuth"] == expected["bearerAuth"]
|
||||
assert schemes["basicAuth"] == expected["basicAuth"]
|
||||
assert "devUser" not in schemes
|
||||
paths = served["paths"]
|
||||
assert paths[ME]["get"]["security"] == [{"bearerAuth": []}]
|
||||
assert paths[f"{API}/auth/sessions"]["post"]["security"] == [
|
||||
{"basicAuth": []},
|
||||
]
|
||||
assert not paths[f"{API}/users"]["post"].get("security")
|
||||
|
||||
Reference in New Issue
Block a user