This commit is contained in:
+122
@@ -0,0 +1,122 @@
|
||||
"""Passwords (Argon2id), Basic login and opaque Bearer sessions."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app import config
|
||||
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")
|
||||
|
||||
|
||||
async def hash_password(password: str) -> str:
|
||||
async with _hash_slots:
|
||||
return await run_in_threadpool(_hasher.hash, password)
|
||||
|
||||
|
||||
async def verify_password(password_hash: str, password: str) -> bool:
|
||||
def verify() -> bool:
|
||||
try:
|
||||
return _hasher.verify(password_hash, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
async with _hash_slots:
|
||||
return await run_in_threadpool(verify)
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
def parse_basic(header: Optional[str]) -> Tuple[str, str]:
|
||||
bad = unauthorized("invalid credentials", BASIC_CHALLENGE)
|
||||
if not header:
|
||||
raise bad
|
||||
scheme, _, value = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not value.strip():
|
||||
raise bad
|
||||
try:
|
||||
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 ':'
|
||||
if not sep or not username.isascii() or not 12 <= len(password) <= 128:
|
||||
raise bad
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(header: Optional[str]) -> str:
|
||||
if not header:
|
||||
raise unauthorized("bearer token required")
|
||||
scheme, _, token = header.partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token or not token.isascii() or len(token) > 256:
|
||||
raise unauthorized("bearer token required")
|
||||
return token
|
||||
|
||||
|
||||
async def login(store: Store, header: Optional[str]) -> dict:
|
||||
username, password = parse_basic(header)
|
||||
row = await store.get_credentials(username)
|
||||
if row is None:
|
||||
await verify_password(_DUMMY_HASH, password)
|
||||
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
|
||||
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:
|
||||
raise unauthorized("session expired or revoked")
|
||||
if isinstance(cached, dict):
|
||||
expires_at = datetime.fromisoformat(cached["expires_at"].replace("Z", "+00:00"))
|
||||
if expires_at > datetime.now(timezone.utc):
|
||||
return cached["user"]
|
||||
raise unauthorized("session expired or revoked")
|
||||
|
||||
row = await store.find_session(digest)
|
||||
if row is None:
|
||||
raise unauthorized("session expired or revoked")
|
||||
user = user_row(row)
|
||||
remaining = int((row["expires_at"] - datetime.now(timezone.utc)).total_seconds())
|
||||
await cache.put(digest, {"user": user, "expires_at": fmt_ts(row["expires_at"])}, remaining)
|
||||
return user
|
||||
|
||||
|
||||
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
|
||||
if expires_at is None:
|
||||
raise unauthorized("session expired or revoked")
|
||||
remaining = int((expires_at - datetime.now(timezone.utc)).total_seconds()) + 1
|
||||
await cache.revoke(digest, remaining)
|
||||
Reference in New Issue
Block a user