Harden login, sessions, and media access before the dev deploy.
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Successful in 47s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 5m43s
Deploy Development / deploy (push) Successful in 49s
Test Suite / pytest-backend (push) Successful in 47s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 15s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 5m43s
Limit brute-force attempts, require admin TOTP, and keep session tokens out of media URLs. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6c7c24e887
commit
32b28a93f3
31 files changed
+1146
-101
No files matched your search
+70
-4
@@ -12,6 +12,11 @@ from fastapi import Header, Query, HTTPException
|
||||
import bcrypt
|
||||
|
||||
from db import get_db, get_cursor
|
||||
from media_grant import profile_id_from_media_grant
|
||||
|
||||
# Fester bcrypt-Hash, damit ein unbekannter Login dieselbe Rechenzeit hat wie ein Treffer.
|
||||
_LOGIN_TIMING_HASH = "$2b$12$GYdnAmeiqaZg/.5J9E4f4.xhz70piViqXIpqKCY/FY609qj65sc9i"
|
||||
MAX_SESSION_DAYS = 30
|
||||
|
||||
|
||||
def hash_pin(pin: str) -> str:
|
||||
@@ -33,6 +38,34 @@ def verify_pin(pin: str, stored_hash: str) -> bool:
|
||||
return stored_hash == hashlib.sha256(pin.encode()).hexdigest()
|
||||
|
||||
|
||||
def verify_pin_for_login(pin: str, stored_hash: Optional[str]) -> bool:
|
||||
"""Immer ein bcrypt-Vergleich, auch wenn das Konto fehlt (kein Zeit-Orakel)."""
|
||||
if stored_hash and str(stored_hash).startswith("$2"):
|
||||
return verify_pin(pin, stored_hash)
|
||||
verify_pin(pin or "x", _LOGIN_TIMING_HASH)
|
||||
if not stored_hash:
|
||||
return False
|
||||
return verify_pin(pin, stored_hash)
|
||||
|
||||
|
||||
def session_lifetime_days(profile: Optional[dict]) -> int:
|
||||
raw = profile.get("session_days") if profile else None
|
||||
try:
|
||||
days = int(raw) if raw is not None else MAX_SESSION_DAYS
|
||||
except (TypeError, ValueError):
|
||||
days = MAX_SESSION_DAYS
|
||||
if days < 1:
|
||||
days = 1
|
||||
if days > MAX_SESSION_DAYS:
|
||||
days = MAX_SESSION_DAYS
|
||||
return days
|
||||
|
||||
|
||||
def revoke_profile_sessions(cur, profile_id: int) -> None:
|
||||
"""Alle Sitzungen eines Profils entfernen, inklusive Reset- und 2FA-Zwischentokens."""
|
||||
cur.execute("DELETE FROM sessions WHERE profile_id = %s", (profile_id,))
|
||||
|
||||
|
||||
def make_token() -> str:
|
||||
"""Generate a secure random token for sessions."""
|
||||
return secrets.token_urlsafe(32)
|
||||
@@ -51,12 +84,39 @@ def get_session(token: str):
|
||||
cur.execute(
|
||||
"SELECT s.*, p.role, p.name "
|
||||
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
||||
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP",
|
||||
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP "
|
||||
"AND COALESCE(s.purpose, 'full') = 'full'",
|
||||
(token,)
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def get_limited_session(token: str, purpose: str):
|
||||
"""Sitzung mit festem Zweck (totp_enroll, totp_challenge). Kein Fach-API-Zugriff."""
|
||||
if not token or purpose not in ("totp_enroll", "totp_challenge"):
|
||||
return None
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT s.*, p.role, p.name, p.email "
|
||||
"FROM sessions s JOIN profiles p ON s.profile_id=p.id "
|
||||
"WHERE s.token=%s AND s.expires_at > CURRENT_TIMESTAMP "
|
||||
"AND s.purpose = %s",
|
||||
(token, purpose),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def _profile_session_from_id(profile_id: int) -> Optional[dict]:
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT id AS profile_id, role, name FROM profiles WHERE id = %s",
|
||||
(profile_id,),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def require_auth(x_auth_token: Optional[str] = Header(default=None)):
|
||||
"""
|
||||
FastAPI dependency - requires valid authentication.
|
||||
@@ -80,8 +140,8 @@ def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), ss
|
||||
"""
|
||||
FastAPI dependency - auth via header OR query parameter.
|
||||
|
||||
Used for endpoints accessed by <img> tags and SSE connections that can't send headers.
|
||||
Query parameter is 'ssetoken' to avoid conflicts with endpoint 'token' parameters.
|
||||
Dateiabruf für <img>/<video>: Header-Sitzung oder kurzlebiges Medien-Token (?ssetoken).
|
||||
Ein Sitzungstoken in der Query-Zeichenfolge wird nicht akzeptiert.
|
||||
|
||||
Usage:
|
||||
@app.get("/api/photos/{id}")
|
||||
@@ -93,7 +153,13 @@ def require_auth_flexible(x_auth_token: Optional[str] = Header(default=None), ss
|
||||
Raises:
|
||||
HTTPException 401 if not authenticated
|
||||
"""
|
||||
session = get_session(x_auth_token or ssetoken)
|
||||
session = get_session(x_auth_token) if x_auth_token else None
|
||||
if session:
|
||||
return session
|
||||
profile_id = profile_id_from_media_grant(ssetoken)
|
||||
if profile_id is None:
|
||||
raise HTTPException(401, "Nicht eingeloggt")
|
||||
session = _profile_session_from_id(profile_id)
|
||||
if not session:
|
||||
raise HTTPException(401, "Nicht eingeloggt")
|
||||
return session
|
||||
|
||||
Reference in new issue
Block a user