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
+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