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:
2026-10-01 18:50:42 +03:00
co-authored by Claude Opus 5.5
parent ee2643d21e
commit ae4154eaf5
68 changed files with 2946 additions and 314 deletions
+39 -27
View File
@@ -15,10 +15,11 @@ FastAPI/uvicorn, данные в PostgreSQL из compose. Агент управ
Все пути — от корня репозитория. Проверено на macOS (arm64), uv 0.12,
Python 3.12 из `.python-version`, Docker Desktop 29.8.
До change `session-auth` API идентифицирует по `X-User-Id`, поэтому
публичный smoke лабы 2 падает на регистрации с `password` (400), а в
`student-tests` падает `test_security_scheme_in_openapi`: схемы `devUser`
нет в контракте lab2. Это ожидаемо (AGENTS.md, «Переходное состояние»).
Аутентификация лабы 2: регистрация с `password`, вход
`POST /api/v1/auth/sessions` по `Authorization: Basic`, дальше —
`Authorization: Bearer <token>`. `X-User-Id` доступа не даёт. Пароль —
Argon2id, около 30 мс на регистрацию и вход, поэтому `flow` и
`student-tests` идут дольше, чем на лабе 1.
## Setup
@@ -44,12 +45,14 @@ python3 $D all # start → flow → tests/smoke.py → student-tests → st
```bash
python3 $D start # make upgrade, затем фон; ждёт /health/ready до 30 с
python3 $D status # listeners: [pid reloader, pid worker], ready: True
python3 $D flow # ~35 проверок: регистрация, 409, /me, 401, чат, 5 сообщений,
# пагинация limit=2 по курсору, чужой → 404, 400-е, X-Request-Id
python3 $D req POST /api/v1/users --data '{"username":"zoe_demo","display_name":"Зоя"}'
python3 $D req GET /api/v1/users/me --user <uuid из ответа выше>
python3 $D flow # ~50 проверок: регистрация с паролем, вход, 409, неверный пароль,
# 401 с WWW-Authenticate, X-User-Id игнорируется, чат, 5 сообщений,
# пагинация limit=2 по курсору, чужой → 404, 400-е, logout
python3 $D req POST /api/v1/users --data '{"username":"zoe_demo","display_name":"Зоя","password":"Zoe-password-1"}'
python3 $D req POST /api/v1/auth/sessions --basic zoe_demo:Zoe-password-1
python3 $D req GET /api/v1/users/me --token <token из ответа выше>
python3 $D smoke # публичный tests/smoke.py против этого порта
python3 $D student # make student_test BASE_URL=http://localhost:<port> — 80 тестов, ~1,5 с
python3 $D student # make student_test BASE_URL=http://localhost:<port> — 99 тестов, ~11 с
python3 $D stop
```
@@ -57,8 +60,8 @@ python3 $D stop
|---|---|
| `start` | `make upgrade`, затем `APP__RUN_MODE=console APP__PORT=<port> uv run python -m src` в своей группе процессов |
| `status` | кто слушает порт, отвечает ли `/health/ready`; код 1, если никого |
| `flow` | сквозной сценарий; `[FAIL]` в строке и код 1 при провале; в конце печатает id alice/bob/eve/chat |
| `req METHOD PATH [--user UUID] [--data JSON]` | один запрос: статус, `x-request-id`, тело; код 2 при статусе ≥ 400 |
| `flow` | сквозной сценарий; `[FAIL]` в строке и код 1 при провале; в конце печатает id alice/bob/eve/chat и синтетический токен alice |
| `req METHOD PATH [--token T \| --basic USER:PASS] [--data JSON]` | один запрос: статус, `x-request-id`, `www-authenticate` у 401, тело; код 2 при статусе ≥ 400 |
| `smoke` | `tests/smoke.py --base-url http://localhost:<port>` |
| `student` | `make student_test BASE_URL=http://localhost:<port>` (pytest по `student-tests/`); код 1, если каталога нет |
| `stop` | SIGTERM всей группе; ждёт, пока порт освободится. Чужой сервер и контейнер не трогает |
@@ -82,7 +85,8 @@ make run_docker APP_OUT_PORT=18090 # build + up -d: postgres → migrat
docker compose ps -a --format '{{.Name}} {{.Ports}} {{.Status}}'
python3 $D --port 18090 flow # те же проверки против контейнера
docker compose logs --no-log-prefix api | tail -5 # JSON-строки, без -f
scripts/restart.sh # рестарт API и Postgres: данные и X-User-Id остаются
scripts/restart.sh # рестарт API и Postgres: данные и токены остаются
make test-persistence ACTION_SCRIPT=scripts/restart.sh # то же публичной проверкой
make down # удалить контейнеры, volume с данными остаётся
make wipe_data # удалить и данные: только после ввода yes
```
@@ -103,17 +107,20 @@ make upgrade
APP__LOG_LEVEL=WARNING uv run python - <<'EOF'
import asyncio
import uuid
from src.core.services import UserService
from src.core.services import SessionService, UserService
from src.infra.db.session import engine, session_factory
async def main():
async with session_factory() as db_session:
users = UserService(db_session=db_session)
user = await users.register(
username=f"alice_{uuid.uuid4().hex[:6]}",
username = f"alice_{uuid.uuid4().hex[:6]}"
await UserService(db_session=db_session).register(
username=username,
display_name="Alice",
password="Alice-password-1",
)
print(await users.identify(raw_user_id=str(user.id)))
sessions = SessionService(db_session=db_session)
issued = await sessions.login(username=username, password="Alice-password-1")
print(await sessions.authenticate(token=issued.token))
await engine.dispose()
asyncio.run(main())
@@ -123,8 +130,9 @@ EOF
`ChatService` и `MessageService` создаются так же (`db_session=...`),
все методы keyword-only, commit делает сам сервис. Ошибки — доменные
исключения из `src.core.exceptions` (базовый `DomainError`), не
HTTP-коды: `identify(raw_user_id="not-a-uuid")` бросает `Unidentified`.
Созданное так остаётся в рабочей базе.
HTTP-коды: `authenticate(token="x")` бросает `Unauthenticated`, неверный
пароль в `login` — `InvalidCredentials`. Созданное так остаётся в рабочей
базе.
## Run (human path)
@@ -143,11 +151,9 @@ python3 $D all # живой сервер + flow + s
make lint # ruff; затрагивает и driver.py
```
Ожидаемо до `session-auth`: `PASS: offline skeleton structure...`,
`FAILED: none` у `flow`, smoke — `FAIL: POST /api/v1/users: expected
[201], received 400`, student — `1 failed, 79 passed`
(`test_security_scheme_in_openapi`), `All checks passed!`. Поэтому
`all` и `test_isolated` пока выходят с ненулевым кодом.
Ожидаемо: `PASS: offline skeleton structure...`, `FAILED: none` у
`flow`, smoke — `PASS: lab2 public API scenario...`, student — все
прошли, `All checks passed!`; `all` и `test_isolated` — код 0.
## Gotchas
@@ -161,7 +167,7 @@ make lint # ruff; затрагивает и dr
стенд — `make wipe_data`.
- **Правка файла в `src/` перезапускает worker** (`WatchFiles detected
changes ... Reloading...`), задевает и `make run_dev` на 8080. Данные
в Postgres остаются, прежние `X-User-Id` работают.
и сессии в Postgres остаются, прежние токены работают.
- **`lsof` на порт показывает два PID** — reloader и worker делят один
сокет. Убивать по `lsof -t | xargs kill` бессмысленно: reloader
поднимет worker снова. Драйвер шлёт SIGTERM группе процессов; SIGTERM
@@ -183,8 +189,14 @@ make lint # ruff; затрагивает и dr
контейнера показывает один PID — процесс Docker Desktop, а не uvicorn.
- **`make logs` висит** (`logs -f`) — агенту нужен
`docker compose logs --no-log-prefix api` без `-f`.
- **`req` без `--user` на защищённом пути даёт 401 `unauthorized`** — это
не сломанный сервер, а контракт: идентификация раньше доступа.
- **`req` без `--token` на защищённом пути даёт 401 `unauthorized`** с
`www-authenticate: Bearer realm="messenger"` — это не сломанный
сервер, а контракт: аутентификация раньше доступа. Токен — из ответа
`req POST /api/v1/auth/sessions --basic USER:PASS` или последняя строка
`flow`.
- **Короткий срок сессии для проверки истечения** — окружением
`AUTH__SESSION_TTL_SECONDS=2 python3 $D start`: окружение важнее
`.env` и `config.toml`.
## Troubleshooting
+144 -37
View File
@@ -11,7 +11,8 @@
/health/ready; лог и pid — /tmp/mtusi-api-<port>.{log,pid}
status кто слушает порт и что отвечает /health/ready
flow сквозной сценарий по HTTP с проверками; код выхода 1 при провале
req один запрос: req METHOD PATH [--user UUID] [--data JSON]
req один запрос: req METHOD PATH [--token T | --basic USER:PASS]
[--data JSON]
smoke публичный tests/smoke.py против этого порта
student собственные тесты student-tests/ (make student_test) против
этого порта
@@ -26,6 +27,7 @@ student работают с любым сервером на порту, в то
"""
import argparse
import base64
import contextlib
import json
import os
@@ -42,6 +44,9 @@ ROOT = Path(__file__).resolve().parents[3]
DEFAULT_PORT = 18080
USERS = "/api/v1/users"
CHATS = "/api/v1/chats"
SESSIONS = "/api/v1/auth/sessions"
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
def paths(port: int) -> tuple[Path, Path]:
@@ -55,12 +60,20 @@ def base_url(port: int) -> str:
return f"http://127.0.0.1:{port}"
def basic(username: str, password: str) -> str:
"""Значение `Authorization: Basic` из username и пароля в UTF-8."""
raw = f"{username}:{password}".encode()
return "Basic " + base64.b64encode(raw).decode("ascii")
def call(
port: int,
method: str,
path: str,
*,
user: str | None = None,
token: str | None = None,
authorization: str | None = None,
extra: dict[str, str] | None = None,
body: object = None,
raw: bytes | None = None,
) -> tuple[int, dict[str, str], object]:
@@ -70,8 +83,11 @@ def call(
data = json.dumps(body).encode()
if data is not None:
headers["Content-Type"] = "application/json"
if user is not None:
headers["X-User-Id"] = user
if token is not None:
headers["Authorization"] = f"Bearer {token}"
if authorization is not None:
headers["Authorization"] = authorization
headers.update(extra or {})
request = urllib.request.Request(
base_url(port) + path,
data=data,
@@ -189,14 +205,21 @@ def cmd_status(port: int) -> int:
def cmd_req(port: int, args: argparse.Namespace) -> int:
body = json.loads(args.data) if args.data is not None else None
authorization = None
if args.basic is not None:
username, _, password = args.basic.partition(":")
authorization = basic(username, password)
status, hdrs, payload = call(
port,
args.method.upper(),
args.path,
user=args.user,
token=args.token,
authorization=authorization,
body=body,
)
print(status, "x-request-id:", hdrs.get("x-request-id"))
if "www-authenticate" in hdrs:
print("www-authenticate:", hdrs["www-authenticate"])
print(json.dumps(payload, ensure_ascii=False, indent=2))
return 0 if status < 400 else 2
@@ -218,9 +241,11 @@ class Flow:
method: str,
path: str,
status: int,
challenge: str | None = None,
**kwargs: object,
) -> object:
"""Запрос + проверка статуса, X-Request-Id и формата ошибки."""
"""Запрос + проверка статуса, X-Request-Id, формата ошибки и,
если задан, `WWW-Authenticate`."""
got, hdrs, payload = call(self.port, method, path, **kwargs)
request_id = hdrs.get("x-request-id")
ok = got == status and bool(request_id)
@@ -231,6 +256,9 @@ class Flow:
error = payload.get("error", {})
ok = ok and error.get("request_id") == request_id
detail = f"{got} {error.get('code')}"
if challenge is not None:
ok = ok and hdrs.get("www-authenticate") == challenge
detail += f" {hdrs.get('www-authenticate')}"
shown = path if len(path) <= 60 else path[:57] + "..."
self.check(f"{method} {shown} -> {status} ({label})", ok, detail)
return payload
@@ -242,42 +270,104 @@ def cmd_flow(port: int) -> int:
flow.expect("live", "GET", "/health/live", 200)
flow.expect("ready", "GET", "/health/ready", 200)
ids = {}
me_path = f"{USERS}/me"
ids, tokens, logins = {}, {}, {}
for name in ("alice", "bob", "eve"):
body = {"username": f"{name}_{tag}", "display_name": f"{name} ✨"}
ids[name] = flow.expect("register", "POST", USERS, 201, body=body)[
"id"
]
alice, bob, eve = ids["alice"], ids["bob"], ids["eve"]
dup = {"username": f"alice_{tag}", "display_name": "again"}
username, password = f"{name}_{tag}", f"Pw-{name}-{uuid.uuid4().hex}"
body = {
"username": username,
"display_name": f"{name} ✨",
"password": password,
}
user = flow.expect("register", "POST", USERS, 201, body=body)
flow.check("no password in User", "password" not in user)
session = flow.expect(
"login",
"POST",
SESSIONS,
201,
authorization=basic(username, password),
)
ids[name], tokens[name] = user["id"], session["token"]
logins[name] = (username, password)
alice, bob, eve = tokens["alice"], tokens["bob"], tokens["eve"]
dup = {
"username": f"alice_{tag}",
"display_name": "again",
"password": "Another-password-1",
}
flow.expect("duplicate username", "POST", USERS, 409, body=dup)
me = flow.expect("me", "GET", f"{USERS}/me", 200, user=alice)
flow.check("me.id == alice", me.get("id") == alice)
flow.expect("no X-User-Id", "GET", f"{USERS}/me", 401)
stranger = str(uuid.uuid4())
flow.expect("unknown user", "GET", f"{USERS}/me", 401, user=stranger)
no_password = {"username": f"nopw_{tag}", "display_name": "x"}
flow.expect("no password", "POST", USERS, 400, body=no_password)
body = {"title": "Проект 🚀", "member_ids": [alice, bob]}
chat = flow.expect("new chat", "POST", CHATS, 201, user=alice, body=body)
username, password = logins["alice"]
wrong = basic(username, "Wrong-password-1")
flow.expect(
"wrong password",
"POST",
SESSIONS,
401,
challenge=BASIC_CHALLENGE,
authorization=wrong,
)
me = flow.expect("me", "GET", me_path, 200, token=alice)
flow.check("me.id == alice", me.get("id") == ids["alice"])
flow.expect("no token", "GET", me_path, 401, challenge=BEARER_CHALLENGE)
flow.expect(
"Basic on business endpoint",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
authorization=basic(username, password),
)
flow.expect(
"only X-User-Id",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
extra={"X-User-Id": ids["alice"]},
)
spoofed = flow.expect(
"X-User-Id ignored",
"GET",
me_path,
200,
token=alice,
extra={"X-User-Id": ids["eve"]},
)
flow.check("still alice", spoofed.get("id") == ids["alice"])
flow.expect(
"unknown token",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
token=uuid.uuid4().hex * 2,
)
body = {"title": "Проект 🚀", "member_ids": [ids["alice"], ids["bob"]]}
chat = flow.expect("new chat", "POST", CHATS, 201, token=alice, body=body)
chat_path = f"{CHATS}/{chat['id']}"
msgs = f"{chat_path}/messages"
body = {"title": "x", "member_ids": [alice]}
flow.expect("not a member", "POST", CHATS, 400, user=eve, body=body)
body = {"title": "x", "member_ids": [ids["alice"]]}
flow.expect("not a member", "POST", CHATS, 400, token=eve, body=body)
texts = ["привет", "hi 👋", "третье", "четвёртое", "пятое"]
for index, text in enumerate(texts):
sender = alice if index % 2 == 0 else bob
body = {"text": text}
flow.expect("send", "POST", msgs, 201, user=sender, body=body)
flow.expect("send", "POST", msgs, 201, token=sender, body=body)
blank = {"text": " "}
flow.expect("blank text", "POST", msgs, 400, user=alice, body=blank)
spoof = {"text": "x", "sender_id": alice}
flow.expect("sender_id", "POST", msgs, 400, user=alice, body=spoof)
flow.expect("blank text", "POST", msgs, 400, token=alice, body=blank)
spoof = {"text": "x", "sender_id": ids["alice"]}
flow.expect("sender_id", "POST", msgs, 400, token=alice, body=spoof)
seen, cursor, pages = [], None, 0
while pages < 10:
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
page = flow.expect("page", "GET", msgs + query, 200, user=bob)
page = flow.expect("page", "GET", msgs + query, 200, token=bob)
seen += [item["text"] for item in page["items"]]
cursor, pages = page["next_cursor"], pages + 1
if cursor is None:
@@ -285,21 +375,36 @@ def cmd_flow(port: int) -> int:
flow.check("history order via cursor", seen == texts, f"{pages} pages")
flow.check("created_at ends with Z", chat["created_at"].endswith("Z"))
flow.expect("outsider reads chat", "GET", chat_path, 404, user=eve)
flow.expect("outsider reads history", "GET", msgs, 404, user=eve)
flow.expect("outsider reads chat", "GET", chat_path, 404, token=eve)
flow.expect("outsider reads history", "GET", msgs, 404, token=eve)
hi = {"text": "hi"}
flow.expect("outsider posts", "POST", msgs, 404, user=eve, body=hi)
flow.expect("no header beats 404", "GET", chat_path, 401)
flow.expect("limit=0", "GET", msgs + "?limit=0", 400, user=alice)
flow.expect("bad cursor", "GET", msgs + "?cursor=zzz", 400, user=alice)
flow.expect("chat_id not uuid", "GET", f"{CHATS}/nope", 400, user=alice)
flow.expect("outsider posts", "POST", msgs, 404, token=eve, body=hi)
flow.expect("no token beats 404", "GET", chat_path, 401)
flow.expect("limit=0", "GET", msgs + "?limit=0", 400, token=alice)
flow.expect("bad cursor", "GET", msgs + "?cursor=zzz", 400, token=alice)
flow.expect("chat_id not uuid", "GET", f"{CHATS}/nope", 400, token=alice)
flow.expect("malformed json", "POST", USERS, 400, raw=b"{not json")
flow.expect("unknown path", "GET", "/nope", 404)
chats = flow.expect("list chats", "GET", CHATS, 200, user=bob)
chats = flow.expect("list chats", "GET", CHATS, 200, token=bob)
listed = [item["id"] for item in chats["items"]]
flow.check("bob sees the chat", chat["id"] in listed)
print(f"\nalice={alice}\nbob={bob}\neve={eve}\nchat={chat['id']}")
flow.expect("logout", "DELETE", f"{SESSIONS}/current", 204, token=eve)
flow.expect(
"token after logout",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
token=eve,
)
print(
f"\nalice={ids['alice']}\nbob={ids['bob']}\neve={ids['eve']}"
f"\nchat={chat['id']}"
# синтетический токен локального стенда: для `req --token`
f"\nalice_token={alice}",
)
print("FAILED:", flow.failures or "none")
return 1 if flow.failures else 0
@@ -335,7 +440,9 @@ def main() -> int:
req = sub.add_parser("req")
req.add_argument("method")
req.add_argument("path")
req.add_argument("--user")
auth = req.add_mutually_exclusive_group()
auth.add_argument("--token", help="Bearer-токен сессии")
auth.add_argument("--basic", help="USER:PASS для POST /auth/sessions")
req.add_argument("--data")
args = parser.parse_args()
port = args.port