forked from mtusi2026/mtusi2026lab2
Реализовать лабораторную 2: API мессенджера с PostgreSQL и кэшем сессий
FastAPI-сервис с opaque-сессиями (Argon2id, SHA-256 фингерпринт), PostgreSQL как источником истины, Valkey как кэшем сессий, keyset-пагинацией, пулом соединений и таймаутами. Добавлены миграции, compose-стенд, скрипт рестарта, студенческие проверки и evidence.
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
# Студенческие проверки (lab 2)
|
||||
|
||||
Дополняют публичный `tests/smoke.py`, не ослабляя его. Только стандартная библиотека.
|
||||
|
||||
```sh
|
||||
# негативные и конкурентные проверки на работающем стенде
|
||||
python student-tests/test_lab2.py --base-url http://localhost:8080
|
||||
|
||||
# проверка истечения сессии при коротком TTL (см. compose.expiry.yaml)
|
||||
docker compose -f compose.yaml -f compose.expiry.yaml up -d --no-deps api
|
||||
python student-tests/test_lab2.py --base-url http://localhost:8081 --expiry
|
||||
docker compose up -d --no-deps api # вернуть обычный TTL
|
||||
|
||||
# обход кэша при недоступности Valkey (останавливает/запускает valkey)
|
||||
python student-tests/test_lab2.py --base-url http://localhost:8080 --cache-check
|
||||
```
|
||||
|
||||
Что проверяется:
|
||||
|
||||
- неверный пароль → одинаковый `401` и `WWW-Authenticate: Basic`;
|
||||
- `X-User-Id` сам по себе не аутентифицирует и не подменяет владельца Bearer-сессии;
|
||||
- logout отзывает токен (`204`, затем `401` с `WWW-Authenticate: Bearer`);
|
||||
- гонка регистрации одного username: ровно один `201`, остальные `409`;
|
||||
- истечение сессии по короткому `SESSION_TTL_SECONDS` (`--expiry`);
|
||||
- недоступность Valkey не ломает аутентификацию, источник истины — PostgreSQL (`--cache-check`).
|
||||
|
||||
`perf_explain.sql` наполняет один чат 10 000 синтетических сообщений и печатает
|
||||
`EXPLAIN (ANALYZE, BUFFERS)` для keyset-пагинации:
|
||||
|
||||
```sh
|
||||
Get-Content -Raw student-tests/perf_explain.sql | docker compose exec -T postgres psql -U messenger -d messenger
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ('00000000-0000-4000-8000-000000000001', 'perf_user_1', 'Perf One', 'synthetic'),
|
||||
('00000000-0000-4000-8000-000000000002', 'perf_user_2', 'Perf Two', 'synthetic')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
INSERT INTO chats (id, title)
|
||||
VALUES ('00000000-0000-4000-8000-0000000000aa', 'Perf chat')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES ('00000000-0000-4000-8000-0000000000aa', '00000000-0000-4000-8000-000000000001')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(),
|
||||
'00000000-0000-4000-8000-0000000000aa',
|
||||
'00000000-0000-4000-8000-000000000001',
|
||||
'perf message ' || g,
|
||||
now() - (g || ' seconds')::interval
|
||||
FROM generate_series(1, 10000) AS g;
|
||||
|
||||
ANALYZE messages;
|
||||
|
||||
\echo === message count ===
|
||||
SELECT count(*) AS messages FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-0000000000aa';
|
||||
|
||||
\echo === EXPLAIN (ANALYZE, BUFFERS): keyset page in the middle of history ===
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-0000000000aa'
|
||||
AND (created_at, id) > (now() - interval '5000 seconds',
|
||||
'00000000-0000-4000-8000-000000000000'::uuid)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT 50;
|
||||
|
||||
\echo === EXPLAIN (ANALYZE, BUFFERS): first page (no cursor) ===
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-0000000000aa'
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT 50;
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
class Failure(AssertionError):
|
||||
pass
|
||||
|
||||
|
||||
def check(condition, message):
|
||||
if not condition:
|
||||
raise Failure(message)
|
||||
|
||||
|
||||
def call(base, method, path, body=None, token=None, basic=None, headers=None):
|
||||
h = {"Accept": "application/json"}
|
||||
if token:
|
||||
h["Authorization"] = "Bearer " + token
|
||||
if basic:
|
||||
h["Authorization"] = "Basic " + base64.b64encode(basic.encode("utf-8")).decode("ascii")
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
h["Content-Type"] = "application/json"
|
||||
h.update(headers or {})
|
||||
request = urllib.request.Request(base + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=10)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
raw = response.read()
|
||||
return response.code, response.headers, raw
|
||||
|
||||
|
||||
def register(base, username, password):
|
||||
return call(base, "POST", "/api/v1/users", body={
|
||||
"username": username, "display_name": "Студент " + username, "password": password})
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--expiry", action="store_true", help="expect a short SESSION_TTL_SECONDS")
|
||||
parser.add_argument("--cache-check", action="store_true", help="stop Valkey via docker compose")
|
||||
parser.add_argument("--compose-dir", default=".")
|
||||
args = parser.parse_args()
|
||||
base = args.base_url.rstrip("/")
|
||||
tag = uuid.uuid4().hex[:10]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
|
||||
status, _, raw = register(base, "u_neg_" + tag, password)
|
||||
check(status == 201, "registration failed: %d" % status)
|
||||
user = json.loads(raw)
|
||||
status, headers, _ = call(base, "POST", "/api/v1/auth/sessions",
|
||||
basic="u_neg_%s:%s" % (tag, "wrong-password-123"))
|
||||
check(status == 401, "wrong password must be 401, got %d" % status)
|
||||
check(headers.get("WWW-Authenticate", "").lower().startswith("basic"), "missing Basic challenge")
|
||||
print("PASS: wrong password -> 401 with Basic challenge")
|
||||
|
||||
status, _, raw = call(base, "POST", "/api/v1/auth/sessions",
|
||||
basic="u_neg_%s:%s" % (tag, password))
|
||||
check(status == 201, "login failed: %d" % status)
|
||||
token = json.loads(raw)["token"]
|
||||
|
||||
status, _, _ = call(base, "GET", "/api/v1/users/me", headers={"X-User-Id": user["id"]})
|
||||
check(status == 401, "X-User-Id must not authenticate, got %d" % status)
|
||||
other = json.loads(register(base, "u_neg2_" + tag, password)[2])
|
||||
status, _, raw = call(base, "GET", "/api/v1/users/me", token=token, headers={"X-User-Id": other["id"]})
|
||||
check(status == 200 and json.loads(raw)["id"] == user["id"], "X-User-Id overrode bearer identity")
|
||||
print("PASS: X-User-Id ignored for authentication")
|
||||
|
||||
status, _, raw = call(base, "DELETE", "/api/v1/auth/sessions/current", token=token)
|
||||
check(status == 204 and not raw, "logout must be 204 without body, got %d" % status)
|
||||
status, headers, _ = call(base, "GET", "/api/v1/users/me", token=token)
|
||||
check(status == 401, "revoked token must be 401, got %d" % status)
|
||||
check(headers.get("WWW-Authenticate", "").lower().startswith("bearer"), "missing Bearer challenge")
|
||||
print("PASS: logout revokes the session")
|
||||
|
||||
race_username = "u_race_" + tag
|
||||
results = []
|
||||
lock = threading.Lock()
|
||||
barrier = threading.Barrier(8)
|
||||
|
||||
def attempt():
|
||||
barrier.wait()
|
||||
code, _, _ = register(base, race_username, password)
|
||||
with lock:
|
||||
results.append(code)
|
||||
|
||||
threads = [threading.Thread(target=attempt) for _ in range(8)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
check(results.count(201) == 1, "exactly one registration must succeed: %s" % sorted(results))
|
||||
check(results.count(409) == 7, "losers must get 409: %s" % sorted(results))
|
||||
print("PASS: concurrent registration -> one 201 and seven 409")
|
||||
|
||||
if args.expiry:
|
||||
status, _, raw = call(base, "POST", "/api/v1/auth/sessions",
|
||||
basic="u_neg_%s:%s" % (tag, password))
|
||||
check(status == 201, "login failed: %d" % status)
|
||||
short = json.loads(raw)
|
||||
expires = short["expires_at"]
|
||||
from datetime import datetime, timezone
|
||||
ttl = (datetime.fromisoformat(expires.replace("Z", "+00:00")) - datetime.now(timezone.utc)).total_seconds()
|
||||
check(ttl < 60, "run this with a short SESSION_TTL_SECONDS (ttl=%.1fs)" % ttl)
|
||||
time.sleep(max(0.0, ttl) + 1.5)
|
||||
status, _, _ = call(base, "GET", "/api/v1/users/me", token=short["token"])
|
||||
check(status == 401, "expired session must be 401, got %d" % status)
|
||||
print("PASS: session expired after %.0fs TTL" % ttl)
|
||||
|
||||
if args.cache_check:
|
||||
status, _, raw = call(base, "POST", "/api/v1/auth/sessions",
|
||||
basic="u_neg_%s:%s" % (tag, password))
|
||||
token = json.loads(raw)["token"]
|
||||
subprocess.run(["docker", "compose", "stop", "valkey"], cwd=args.compose_dir, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
status, _, _ = call(base, "GET", "/api/v1/users/me", token=token)
|
||||
check(status == 200, "auth must keep working without the cache, got %d" % status)
|
||||
print("PASS: authentication survives a cache outage")
|
||||
finally:
|
||||
subprocess.run(["docker", "compose", "start", "valkey"], cwd=args.compose_dir, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
print("PASS: student lab2 checks completed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Failure as error:
|
||||
print("FAIL:", error)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user