forked from mtusi2026/mtusi2026lab6
Implement lab6 observability with OpenTelemetry and Grafana
This commit is contained in:
+104
@@ -0,0 +1,104 @@
|
||||
"""HTTP Basic only on login; bearer sessions shared by all API replicas."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError
|
||||
from fastapi import Request
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from .core import APIError, SESSION_TTL, iso
|
||||
from .storage import cache, db
|
||||
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
PASSWORD_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
def public_user(row: dict):
|
||||
return {"id": str(row["id"]), "username": row["username"], "display_name": bytes(row["display_name"]).decode("utf-8"), "created_at": iso(row["created_at"])}
|
||||
|
||||
|
||||
def unauthorized() -> APIError:
|
||||
return APIError(401, "unauthorized", "Unauthorized")
|
||||
|
||||
|
||||
def challenge(req: Request) -> str:
|
||||
return 'Basic realm="messenger", charset="UTF-8"' if req.url.path == "/api/v1/auth/sessions" else 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def bearer_token(req: Request) -> str:
|
||||
value = req.headers.get("Authorization", "")
|
||||
if not value.startswith("Bearer ") or len(value) <= 7 or " " in value[7:] or len(value) > 512:
|
||||
raise unauthorized()
|
||||
try:
|
||||
value[7:].encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
raise unauthorized() from None
|
||||
return value[7:]
|
||||
|
||||
|
||||
def session_key(token: str) -> str:
|
||||
return "session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def current_user(req: Request) -> dict:
|
||||
token = bearer_token(req)
|
||||
try:
|
||||
raw = cache().get(session_key(token))
|
||||
except (RedisError, UnicodeError) as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
if not raw:
|
||||
raise unauthorized()
|
||||
try:
|
||||
ident = str(uuid.UUID(raw))
|
||||
except (ValueError, TypeError):
|
||||
try:
|
||||
cache().delete(session_key(token))
|
||||
except RedisError as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
raise unauthorized() from None
|
||||
with db() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE id = %s", (ident,)).fetchone()
|
||||
if row is None:
|
||||
raise unauthorized()
|
||||
return public_user(row)
|
||||
|
||||
|
||||
def login(req: Request):
|
||||
auth = req.headers.get("Authorization", "")
|
||||
if not auth.startswith("Basic "):
|
||||
raise unauthorized()
|
||||
try:
|
||||
decoded = base64.b64decode(auth[6:].encode("ascii"), validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
if not PASSWORD_RE.fullmatch(username):
|
||||
raise ValueError()
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
raise unauthorized() from None
|
||||
with db() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
|
||||
if not row:
|
||||
raise unauthorized()
|
||||
try:
|
||||
hasher.verify(row["password_hash"], password)
|
||||
except (VerifyMismatchError, VerificationError):
|
||||
raise unauthorized() from None
|
||||
token = secrets.token_urlsafe(32)
|
||||
try:
|
||||
cache().set(session_key(token), str(row["id"]), ex=SESSION_TTL)
|
||||
except RedisError as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": iso(datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)), "user": public_user(row)}
|
||||
|
||||
|
||||
def logout(req: Request):
|
||||
current_user(req)
|
||||
try:
|
||||
cache().delete(session_key(bearer_token(req)))
|
||||
except RedisError as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
Reference in New Issue
Block a user