выполнение лр2 на 4

This commit is contained in:
Ilya
2026-10-09 12:44:56 +03:00
parent e914e384fc
commit 13fa1852cb
30 changed files with 585 additions and 238 deletions
+3 -13
View File
@@ -1,4 +1,3 @@
"""Passwords (Argon2id), Basic login and opaque Bearer sessions."""
from __future__ import annotations
import asyncio
@@ -18,10 +17,8 @@ from app.cache import REVOKED, SessionCache
from app.errors import BASIC_CHALLENGE, unauthorized
from app.storage import Store, fmt_ts, user_row
# argon2-cffi defaults = RFC 9106 low-memory profile (Argon2id, t=3, m=64 MiB, p=4).
_hasher = PasswordHasher()
_hash_slots = asyncio.Semaphore(config.PASSWORD_HASH_CONCURRENCY)
# Verified when the username does not exist, so both failures cost the same time.
_DUMMY_HASH = _hasher.hash("dummy-password-for-timing")
@@ -42,8 +39,6 @@ async def verify_password(password_hash: str, password: str) -> bool:
def token_digest(token: str) -> bytes:
# A fast hash is enough here: the token already carries 256 random bits,
# unlike a human password that needs a slow KDF against guessing.
return hashlib.sha256(token.encode("ascii")).digest()
@@ -58,7 +53,7 @@ def parse_basic(header: Optional[str]) -> Tuple[str, str]:
decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
except (binascii.Error, UnicodeDecodeError):
raise bad from None
username, sep, password = decoded.partition(":") # the password may contain ':'
username, sep, password = decoded.partition(":")
if not sep or not username.isascii() or not 12 <= len(password) <= 128:
raise bad
return username, password
@@ -82,16 +77,12 @@ async def login(store: Store, header: Optional[str]) -> dict:
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
if not await verify_password(row["password_hash"], password):
raise unauthorized("invalid credentials", BASIC_CHALLENGE)
token = secrets.token_urlsafe(32) # 256 bits of entropy
token = secrets.token_urlsafe(32)
expires_at = await store.create_session(token_digest(token), row["id"], config.SESSION_TTL_SECONDS)
return {"token": token, "token_type": "Bearer", "expires_at": fmt_ts(expires_at), "user": user_row(row)}
async def authenticate(store: Store, cache: SessionCache, header: Optional[str]) -> dict:
"""Return the session's user or raise 401. Cache first, PostgreSQL on a miss.
If PostgreSQL is down and the cache has no answer the error propagates as 503:
an unverifiable token is never treated as authenticated."""
digest = token_digest(parse_bearer(header))
cached = await cache.get(digest)
if cached == REVOKED:
@@ -112,10 +103,9 @@ async def authenticate(store: Store, cache: SessionCache, header: Optional[str])
async def logout(store: Store, cache: SessionCache, header: Optional[str]) -> None:
# Authenticate first so an already revoked token gets 401, as the contract requires.
await authenticate(store, cache, header)
digest = token_digest(parse_bearer(header))
expires_at = await store.revoke_session(digest) # PostgreSQL first: it is the truth
expires_at = await store.revoke_session(digest)
if expires_at is None:
raise unauthorized("session expired or revoked")
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
-12
View File
@@ -1,10 +1,3 @@
"""Valkey session cache. Never the source of truth: every failure degrades to a miss.
Keys: session:<sha256(token) hex>
Value: JSON {"user": {...}, "expires_at": "..."} - a valid session
"revoked" - tombstone written by logout
Entry TTL = min(time left in the session, SESSION_CACHE_MAX_SECONDS).
"""
from __future__ import annotations
import json
@@ -45,7 +38,6 @@ class SessionCache:
return self._client is not None and time.monotonic() >= self._down_until
def _failed(self, op: str, exc: Exception) -> None:
# Circuit breaker: one slow failure, then skip the cache for a few seconds.
self._down_until = time.monotonic() + config.CACHE_RETRY_AFTER
logger.warning("cache %s failed (%s); bypassing cache for %.0fs", op, type(exc).__name__, config.CACHE_RETRY_AFTER)
@@ -69,7 +61,6 @@ class SessionCache:
return None
async def put(self, token_hash: bytes, entry: dict, ttl_seconds: int) -> None:
"""Fill after a PostgreSQL read. NX: never overwrite a logout tombstone."""
ttl = min(ttl_seconds, config.SESSION_CACHE_MAX_SECONDS)
if ttl <= 0 or not self._usable():
return
@@ -79,9 +70,6 @@ class SessionCache:
self._failed("set", exc)
async def revoke(self, token_hash: bytes, ttl_seconds: int) -> None:
"""Tombstone instead of DEL: a concurrent fill that read PostgreSQL before the
revoke cannot re-insert the session afterwards (its SET NX loses).
Tried even while the breaker is open: logout is rare and correctness matters more."""
if self._client is None:
return
try:
-5
View File
@@ -1,4 +1,3 @@
"""Runtime configuration from environment; secrets are read from *_FILE paths."""
from __future__ import annotations
import os
@@ -6,7 +5,6 @@ from typing import Optional
def _secret(name: str) -> Optional[str]:
"""NAME wins over NAME_FILE; NAME_FILE keeps the value out of `docker inspect`."""
value = os.environ.get(name)
if value:
return value.strip()
@@ -29,7 +27,6 @@ DATABASE_URL = _secret("DATABASE_URL")
CACHE_URL = _secret("CACHE_URL")
SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600)
# Upper bound for one cached session entry; PostgreSQL is re-checked after it.
SESSION_CACHE_MAX_SECONDS = _int("SESSION_CACHE_MAX_SECONDS", 300)
DB_POOL_MAX = _int("DB_POOL_MAX", 10)
@@ -39,8 +36,6 @@ DB_COMMAND_TIMEOUT = _float("DB_COMMAND_TIMEOUT", 5)
CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.3)
CACHE_POOL_MAX = _int("CACHE_POOL_MAX", 20)
# After a cache error, skip the cache for this long instead of paying the timeout per request.
CACHE_RETRY_AFTER = _float("CACHE_RETRY_AFTER", 5)
# Argon2id hashing is CPU/RAM heavy: bound how many run at once.
PASSWORD_HASH_CONCURRENCY = _int("PASSWORD_HASH_CONCURRENCY", 4)
-1
View File
@@ -1,4 +1,3 @@
"""API error type shared by all layers."""
from __future__ import annotations
from typing import Dict, Optional
+3 -34
View File
@@ -1,4 +1,3 @@
"""Lab 2: messenger API on PostgreSQL with Bearer sessions and a Valkey session cache."""
from __future__ import annotations
import logging
@@ -39,18 +38,13 @@ async def lifespan(_app: FastAPI):
app = FastAPI(title="MTUSI Messenger — lab2", lifespan=lifespan)
# ---------------------------------------------------------------------------
# Cross-cutting: request id + uniform error envelope
# ---------------------------------------------------------------------------
# PostgreSQL unreachable, restarting or pool exhausted -> bounded 503, never a hang.
DB_UNAVAILABLE = (
OSError, # includes ConnectionRefusedError and TimeoutError (pool acquire / connect)
OSError,
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.TooManyConnectionsError,
asyncpg.exceptions.OperatorInterventionError, # admin shutdown, cannot connect now
asyncpg.exceptions.QueryCanceledError, # statement timeout
asyncpg.exceptions.OperatorInterventionError,
asyncpg.exceptions.QueryCanceledError,
)
@@ -70,8 +64,6 @@ async def request_id_middleware(request: Request, call_next):
try:
response = await call_next(request)
except Exception:
# Unhandled errors must be answered here: Starlette's own 500 handler runs
# outside this middleware and would drop the X-Request-Id header.
logger.exception("unhandled error for request_id=%s", request_id)
response = JSONResponse(status_code=500, content=error_body("internal_error", "internal error", request_id))
response.headers["X-Request-Id"] = request_id
@@ -104,11 +96,6 @@ for _exc in DB_UNAVAILABLE:
app.add_exception_handler(_exc, db_unavailable_handler)
# ---------------------------------------------------------------------------
# Auth: Basic only on POST /auth/sessions, Bearer everywhere else.
# X-User-Id is ignored since lab2.
# ---------------------------------------------------------------------------
async def current_user(request: Request) -> dict:
return await auth.authenticate(store, cache, request.headers.get("Authorization"))
@@ -124,10 +111,6 @@ def not_found() -> ApiError:
return ApiError(404, "not_found", "chat not found")
# ---------------------------------------------------------------------------
# Health
# ---------------------------------------------------------------------------
@app.get("/health/live", response_model=Health)
async def liveness():
return Health()
@@ -135,7 +118,6 @@ async def liveness():
@app.get("/health/ready", response_model=Health)
async def readiness():
# PostgreSQL is critical; Valkey is not (the API bypasses the cache without it).
try:
await store.ping()
except DB_UNAVAILABLE:
@@ -143,10 +125,6 @@ async def readiness():
return Health()
# ---------------------------------------------------------------------------
# Users and sessions
# ---------------------------------------------------------------------------
@app.post("/api/v1/users", response_model=User, status_code=201)
async def register_user(body: CreateUser):
if not body.display_name.strip() or not body.password.strip():
@@ -171,10 +149,6 @@ async def delete_session(request: Request):
return Response(status_code=204)
# ---------------------------------------------------------------------------
# Chats
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
async def create_chat(body: CreateChat, user: dict = Depends(current_user)):
if not body.title.strip():
@@ -203,15 +177,10 @@ async def get_chat(chat_id: str, user: dict = Depends(current_user)):
return chat
# ---------------------------------------------------------------------------
# Messages
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
async def create_message(chat_id: str, body: CreateMessage, user: dict = Depends(current_user)):
chat_uuid = parse_uuid(chat_id, "chat_id")
if not body.text.strip():
# Access is checked before content: an outsider gets 404 even for a blank text.
if not await store.is_member(chat_uuid, uuid.UUID(user["id"])):
raise not_found()
raise ApiError(400, "invalid_request", "text must not be blank")
-5
View File
@@ -1,7 +1,3 @@
"""Apply versioned SQL migrations from migrations/; safe to run repeatedly and concurrently.
Usage: python -m app.migrate
"""
from __future__ import annotations
import asyncio
@@ -17,7 +13,6 @@ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(messag
logger = logging.getLogger("migrate")
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations"
# Arbitrary constant: serialises concurrent runners (e.g. several API replicas in lab3).
LOCK_ID = 2026_0002
-1
View File
@@ -1,4 +1,3 @@
"""Pydantic request/response schemas mirroring contracts/openapi.json."""
from __future__ import annotations
import uuid
+1 -25
View File
@@ -1,4 +1,3 @@
"""PostgreSQL repository. Every query is parameterised; PostgreSQL is the source of truth."""
from __future__ import annotations
import base64
@@ -14,7 +13,6 @@ from app.errors import ApiError
def fmt_ts(value: datetime) -> str:
# Always 6 fractional digits: exact round trip with PostgreSQL microseconds.
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
@@ -46,10 +44,6 @@ def message_row(row: asyncpg.Record) -> dict:
}
# ---------------------------------------------------------------------------
# Opaque keyset cursor bound to one resource
# ---------------------------------------------------------------------------
def encode_cursor(resource: str, created_at: str, item_id: str) -> str:
payload = json.dumps({"r": resource, "t": created_at, "i": item_id}, separators=(",", ":"))
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
@@ -65,12 +59,11 @@ def decode_cursor(resource: str, cursor: str) -> Tuple[datetime, uuid.UUID]:
if created_at.tzinfo is None:
raise ValueError("cursor time has no timezone")
return created_at, uuid.UUID(payload["i"])
except Exception as exc: # noqa: BLE001 - any malformed cursor is a 400
except Exception as exc:
raise ApiError(400, "invalid_request", "invalid cursor") from exc
def page_of(items: List[dict], resource: str, limit: int) -> dict:
"""Queries fetch limit+1 rows: the extra row only tells whether a next page exists."""
page = items[:limit]
next_cursor = None
if len(items) > limit:
@@ -79,17 +72,11 @@ def page_of(items: List[dict], resource: str, limit: int) -> dict:
return {"items": page, "next_cursor": next_cursor}
# ---------------------------------------------------------------------------
# Repository
# ---------------------------------------------------------------------------
class Store:
def __init__(self):
self.pool: Optional[asyncpg.Pool] = None
async def open(self) -> None:
# min_size=0: connections open on demand, so the API starts even while
# PostgreSQL is down and readiness reports 503 until it is back.
self.pool = await asyncpg.create_pool(
config.DATABASE_URL,
min_size=0,
@@ -110,7 +97,6 @@ class Store:
async with self.acquire() as conn:
return await conn.fetchval("SELECT 1") == 1
# -- users --------------------------------------------------------------
async def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
async with self.acquire() as conn:
@@ -124,7 +110,6 @@ class Store:
uuid.uuid4(), username, display_name, password_hash,
)
except asyncpg.UniqueViolationError:
# The UNIQUE constraint, not a prior SELECT, decides concurrent registrations.
raise ApiError(409, "conflict", "username already taken") from None
return user_row(row)
@@ -135,7 +120,6 @@ class Store:
username,
)
# -- sessions -----------------------------------------------------------
async def create_session(self, token_hash: bytes, user_id: uuid.UUID, ttl_seconds: int) -> datetime:
async with self.acquire() as conn:
@@ -149,7 +133,6 @@ class Store:
)
async def find_session(self, token_hash: bytes) -> Optional[asyncpg.Record]:
"""Only a live session: not revoked and not expired by the database clock."""
async with self.acquire() as conn:
return await conn.fetchrow(
"""
@@ -171,13 +154,8 @@ class Store:
token_hash,
)
# -- chats --------------------------------------------------------------
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
"""Chat and all memberships commit together or not at all.
Unknown members are detected by the foreign key inside the transaction, so a
failure after the chat row was inserted really exercises the rollback."""
chat_id = uuid.uuid4()
async with self.acquire() as conn:
try:
@@ -245,10 +223,8 @@ class Store:
chat_id, user_id,
))
# -- messages -----------------------------------------------------------
async def create_message(self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Optional[dict]:
"""Membership check and insert in one statement; None means "no such chat for you"."""
async with self.acquire() as conn:
row = await conn.fetchrow(
"""