"""JWT authentication — single user from env vars.""" import hmac import logging import os import time from jose import jwt logger = logging.getLogger(__name__) # #1 CRITICAL: no fallback — fail loudly if not set SECRET = os.environ.get("SESSION_SECRET", "") if not SECRET: logger.warning("SESSION_SECRET not set! Auth will reject all tokens.") ALGORITHM = "HS256" TOKEN_EXPIRE = 86400 # 24 hours (was 7 days — #11) VALID_USER = os.environ.get("SMETA_USER", "") VALID_PASS = os.environ.get("SMETA_PASS", "") # Login rate limiting (#5) _login_attempts: dict[str, list[float]] = {} MAX_ATTEMPTS = 5 LOCKOUT_SECONDS = 300 def _is_locked(ip: str) -> bool: now = time.time() attempts = _login_attempts.get(ip, []) # Remove old attempts attempts = [t for t in attempts if now - t < LOCKOUT_SECONDS] _login_attempts[ip] = attempts return len(attempts) >= MAX_ATTEMPTS def _record_attempt(ip: str): _login_attempts.setdefault(ip, []).append(time.time()) def authenticate(username: str, password: str, client_ip: str = "") -> str | None: """Return JWT token if credentials are valid, else None.""" if not SECRET or not VALID_PASS or not VALID_USER: return None if client_ip and _is_locked(client_ip): return None # #4 HIGH: constant-time comparison user_ok = hmac.compare_digest(username, VALID_USER) pass_ok = hmac.compare_digest(password, VALID_PASS) if user_ok and pass_ok: payload = {"sub": username, "exp": int(time.time()) + TOKEN_EXPIRE} return jwt.encode(payload, SECRET, algorithm=ALGORITHM) if client_ip: _record_attempt(client_ip) return None def verify_token(token: str) -> str | None: """Return username if token is valid, else None.""" if not SECRET: return None try: payload = jwt.decode(token, SECRET, algorithms=[ALGORITHM]) return payload.get("sub") except Exception: return None