"""Password hashing, session cookies and CSRF.""" from __future__ import annotations import hashlib import secrets from datetime import timedelta from functools import lru_cache import bcrypt from fastapi import Request, Response from app.core.settings import Settings from app.core.timeutil import utcnow HOST_COOKIE = "__Host-jinkendo-session" PLAIN_COOKIE = "jinkendo-session" def hash_password(password: str) -> str: return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8") def verify_password(password: str, password_hash: str) -> bool: try: return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8")) except ValueError: return False @lru_cache def _dummy_hash() -> str: return hash_password("kein-konto-nur-zeitausgleich") def verify_unknown_account(password: str) -> None: """Spend the same time as a real check so the answer time does not reveal an account.""" verify_password(password, _dummy_hash()) def login_bucket(host: str, email: str) -> str: """Rate-limit key. The address is never stored in the clear.""" return hashlib.sha256(f"{host}|{email}".encode("utf-8")).hexdigest() _BROWSERS = (("Edg/", "Edge"), ("OPR/", "Opera"), ("Firefox/", "Firefox"), ("Chrome/", "Chrome"), ("Safari/", "Safari")) _SYSTEMS = (("Windows", "Windows"), ("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"), ("Mac OS", "macOS"), ("Linux", "Linux")) def device_label(user_agent: str | None) -> str: """A short, readable hint for the session list. The full user agent is not kept.""" agent = user_agent or "" browser = next((name for marker, name in _BROWSERS if marker in agent), "Browser") system = next((name for marker, name in _SYSTEMS if marker in agent), "") return f"{browser} auf {system}" if system else browser def new_secret() -> str: return secrets.token_urlsafe(32) def hash_secret(secret: str) -> str: return hashlib.sha256(secret.encode("utf-8")).hexdigest() def cookie_name_and_secure(request: Request, settings: Settings) -> tuple[str, bool]: # __Host- cookies require Secure. Production is only published behind HTTPS. # Development also serves the documented plain HTTP LAN addresses, which cannot store them. if settings.tsumugu_env == "production": return HOST_COOKIE, True forwarded = request.headers.get("x-forwarded-proto", request.url.scheme) if forwarded == "https": return HOST_COOKIE, True return PLAIN_COOKIE, False def read_session_token(request: Request) -> str | None: return request.cookies.get(HOST_COOKIE) or request.cookies.get(PLAIN_COOKIE) def set_session_cookie(response: Response, request: Request, settings: Settings, token: str) -> None: name, secure = cookie_name_and_secure(request, settings) response.set_cookie( key=name, value=token, httponly=True, secure=secure, samesite="lax", path="/", max_age=settings.session_ttl_hours * 3600, ) def clear_session_cookie(response: Response, request: Request, settings: Settings) -> None: name, secure = cookie_name_and_secure(request, settings) response.delete_cookie(key=name, path="/", secure=secure, httponly=True, samesite="lax") if name != PLAIN_COOKIE: response.delete_cookie(key=PLAIN_COOKIE, path="/", httponly=True, samesite="lax") def session_expiry(settings: Settings): return utcnow() + timedelta(hours=settings.session_ttl_hours)