выполнение лр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