Files
mtusi2026lab3/student-tests/test_identification.py
T
ricoromaandClaude Opus 5.5 af4bca08c9 feat: carry lab 2 over and add X-Instance-Id and idempotency keys
- carry the lab 2 solution over and plan lab 3 (PLAN.md, OpenSpec
  change instance-id-idempotency)
- rename the compose project to mtusi-lab3 and the image to :lab3
- add X-Instance-Id to every response and instance_id to every log
  record ([app] instance_id, hostname by default)
- require Idempotency-Key on POST messages: keys table in Postgres,
  key and message in one transaction, replay returns the same 201,
  another body gets 409, TTL from [idempotency] ttl_seconds
- send the key from student-tests, k6 scenarios and the skill driver;
  add idempotency, X-Instance-Id, key race and fault tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 19:42:36 +03:00

121 lines
4.2 KiB
Python

"""Спек `identification`: Bearer на защищённых эндпоинтах с лабы 2.
Единственный модуль, который собирает `Authorization` и `X-User-Id`
сам, а не через `Actor.headers()`: проверяются именно заголовки.
"""
import secrets
from typing import Any
import pytest
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_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_unauthorized(api.request("GET", ME), BEARER_CHALLENGE)
@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", "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_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_token(
api: Api,
alice: Actor,
chat: dict[str, Any],
) -> None:
# с ключом: кроме токена в запросе неверно только поле
resp = api.post_message(None, chat["id"], json={"text": ""})
assert_unauthorized(resp, BEARER_CHALLENGE)
assert api.all_messages(alice, chat["id"]) == []
@pytest.mark.spec("identification", "Битый JSON без заголовка")
def test_malformed_json_without_token(
api: Api,
chat: dict[str, Any],
) -> None:
# согласованное расхождение: битый JSON отклоняется до аутентификации
resp = api.post_message(
None,
chat["id"],
headers={"Content-Type": "application/json"},
content=b"{bad",
)
assert_error(resp, 400)
@pytest.mark.spec("identification", "Схема в openapi.json")
def test_security_schemes_in_openapi(api: Api) -> None:
resp = api.request("GET", "/openapi.json")
assert resp.status_code == 200
served = resp.json()
schemes = served["components"]["securitySchemes"]
expected = contract()["components"]["securitySchemes"]
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")