import asyncio from hashlib import sha256 import ipaddress import time from typing import Literal, Optional from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer, OAuth2PasswordRequestForm from pydantic import BaseModel, ConfigDict from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import text from app.core.access_gate import ( EARTH_SESSION_COOKIE, check_sliding_rate_limit, create_earth_session_token, verify_desktop_handshake, verify_turnstile_token, verify_web_same_origin, ) from app.core.config import settings from app.core.enums import OtpPurpose, UserRole from app.core.logging import get_logger from app.core.security import ( _AsyncRedisClient, create_access_token, create_refresh_token, get_current_user, get_current_user_refresh, get_password_hash, revoke_token, verify_password, ) from app.db.session import get_db from app.models.user import User from app.schemas.token import Token from app.schemas.user import ( ForgotPasswordRequest, ResendCodeRequest, ResetPasswordRequest, UserRegister, UserResponse, VerifyEmailRequest, ) from app.services import otp from app.services.email import ( EmailError, EmailNotConfiguredError, send_verification_email, ) logger = get_logger(__name__) router = APIRouter() optional_bearer = HTTPBearer(auto_error=False) _LOCAL_LOGIN_FAILURES: dict[str, tuple[int, float]] = {} _LOCAL_LOGIN_FAILURES_MAX = 10_000 class LogoutRequest(BaseModel): refresh_token: Optional[str] = None _TRUSTED_PROXY_NETWORKS = ( ipaddress.ip_network("127.0.0.0/8"), ipaddress.ip_network("10.0.0.0/8"), ipaddress.ip_network("172.16.0.0/12"), ipaddress.ip_network("192.168.0.0/16"), ipaddress.ip_network("169.254.0.0/16"), ipaddress.ip_network("100.64.0.0/10"), ipaddress.ip_network("::1/128"), ipaddress.ip_network("fc00::/7"), ipaddress.ip_network("fe80::/10"), ) def _is_trusted_proxy_peer(host: str) -> bool: cleaned = host.strip() if not cleaned: return False if cleaned in {"testclient", "localhost"}: return True try: parsed = ipaddress.ip_address(cleaned) except ValueError: return False if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None: parsed = parsed.ipv4_mapped return any(parsed in network for network in _TRUSTED_PROXY_NETWORKS) def _client_ip(request: Request) -> str: peer_host = request.client.host if (request.client and request.client.host) else "" if _is_trusted_proxy_peer(peer_host): real_ip = (request.headers.get("X-Real-IP") or "").strip() if real_ip: return real_ip forwarded = request.headers.get("X-Forwarded-For") or "" if forwarded: parts = [part.strip() for part in forwarded.split(",") if part.strip()] if parts: return parts[-1] if peer_host: return peer_host return "unknown" def _login_rate_key(client_ip: str, username: str) -> str: digest = sha256(f"{client_ip}:{username.strip().lower()}".encode("utf-8")).hexdigest() return f"auth:login_fail:{digest}" def _prune_local_login_failures(now: float) -> None: expired = [key for key, (_cnt, expires_at) in _LOCAL_LOGIN_FAILURES.items() if expires_at <= now] for key in expired: _LOCAL_LOGIN_FAILURES.pop(key, None) while len(_LOCAL_LOGIN_FAILURES) > _LOCAL_LOGIN_FAILURES_MAX: _LOCAL_LOGIN_FAILURES.pop(next(iter(_LOCAL_LOGIN_FAILURES)), None) async def check_login_rate_limit(client_ip: str, username: str) -> int: max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS) window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS)) if max_attempts <= 0: return 0 key = _login_rate_key(client_ip, username) try: client = _AsyncRedisClient.get_client() raw = await asyncio.wait_for(client.get(key), timeout=1.5) if raw is not None and int(raw) >= max_attempts: ttl = await asyncio.wait_for(client.ttl(key), timeout=1.5) return max(1, int(ttl) if isinstance(ttl, int) and ttl > 0 else window_seconds) return 0 except Exception: now = time.monotonic() _prune_local_login_failures(now) entry = _LOCAL_LOGIN_FAILURES.get(key) if entry and entry[1] > now and entry[0] >= max_attempts: return max(1, int(entry[1] - now)) return 0 async def record_login_failure(client_ip: str, username: str) -> None: max_attempts = int(settings.LOGIN_RATE_LIMIT_MAX_ATTEMPTS) window_seconds = max(1, int(settings.LOGIN_RATE_LIMIT_WINDOW_SECONDS)) if max_attempts <= 0: return key = _login_rate_key(client_ip, username) try: client = _AsyncRedisClient.get_client() count = await asyncio.wait_for(client.incr(key), timeout=1.5) if int(count) == 1: await asyncio.wait_for(client.expire(key, window_seconds), timeout=1.5) except Exception: now = time.monotonic() _prune_local_login_failures(now) count, expires_at = _LOCAL_LOGIN_FAILURES.get(key, (0, now + window_seconds)) if expires_at <= now: count = 0 expires_at = now + window_seconds _LOCAL_LOGIN_FAILURES[key] = (count + 1, expires_at) async def clear_login_failures(client_ip: str, username: str) -> None: key = _login_rate_key(client_ip, username) _LOCAL_LOGIN_FAILURES.pop(key, None) try: client = _AsyncRedisClient.get_client() await asyncio.wait_for(client.delete(key), timeout=1.5) except Exception: pass def _token_response(user: User) -> dict: access_token = create_access_token(data={"sub": user.id}) refresh = create_refresh_token(data={"sub": user.id}) expires_in = ( settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60 if settings.ACCESS_TOKEN_EXPIRE_MINUTES > 0 else None ) return { "access_token": access_token, "token_type": "bearer", "expires_in": expires_in, "refresh_token": refresh, "user": { "id": user.id, "username": user.username, "role": user.role, "gatekeeper_groups": user.gatekeeper_groups or [], }, } async def _load_user_by_email(db: AsyncSession, email: str) -> User | None: result = await db.execute( text( "SELECT id, username, email, password_hash, role, is_active, gatekeeper_groups, email_verified " "FROM users WHERE email = :email" ), {"email": email}, ) row = result.fetchone() if row is None: return None user = User() user.id = row[0] user.username = row[1] user.email = row[2] user.password_hash = row[3] user.role = row[4] user.is_active = row[5] user.gatekeeper_groups = row[6] or [] user.email_verified = bool(row[7]) return user @router.post("/login", response_model=Token) async def login( request: Request, form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db), ): client_ip = _client_ip(request) retry_after = await check_login_rate_limit(client_ip, form_data.username) if retry_after > 0: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, headers={"Retry-After": str(retry_after)}, detail={ "code": "RATE_LIMITED", "message": "Too many failed login attempts", "retry_after_seconds": retry_after, }, ) result = await db.execute( text( "SELECT id, username, email, password_hash, role, is_active, gatekeeper_groups, email_verified " "FROM users WHERE username = :username" ), {"username": form_data.username}, ) row = result.fetchone() if row is None: await record_login_failure(client_ip, form_data.username) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials", ) user = User() user.id = row[0] user.username = row[1] user.email = row[2] user.password_hash = row[3] user.role = row[4] user.is_active = row[5] user.gatekeeper_groups = row[6] or [] user.email_verified = bool(row[7]) if not verify_password(form_data.password, user.password_hash): await record_login_failure(client_ip, form_data.username) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials", ) if not user.is_active: await record_login_failure(client_ip, form_data.username) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User is inactive", ) if not user.email_verified: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail={"code": "EMAIL_NOT_VERIFIED", "email": user.email}, ) await clear_login_failures(client_ip, form_data.username) return _token_response(user) @router.post("/refresh", response_model=Token) async def refresh_token( current_user: User = Depends(get_current_user_refresh), ): return _token_response(current_user) @router.post("/logout") async def logout( credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer), body: LogoutRequest | None = Body(default=None), ): if credentials and credentials.credentials: await revoke_token(credentials.credentials) if body and body.refresh_token: await revoke_token(body.refresh_token) return {"message": "Successfully logged out"} @router.get("/me", response_model=UserResponse) async def get_me(current_user: User = Depends(get_current_user)): return { "id": current_user.id, "username": current_user.username, "email": current_user.email, "role": current_user.role, "gatekeeper_groups": current_user.gatekeeper_groups or [], "is_active": current_user.is_active, "email_verified": getattr(current_user, "email_verified", True), "created_at": current_user.created_at, } async def _send_code_or_raise(db: AsyncSession, email: str, code: str, purpose: OtpPurpose) -> None: try: await send_verification_email(db, to=email, code=code, purpose=purpose) except EmailNotConfiguredError as exc: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail={"code": exc.code, "message": str(exc)}, ) from exc except EmailError as exc: logger.warning_event( "SMTP send failed", event="auth.email.send_failed", context={"email": email, "purpose": purpose, "error": str(exc)}, ) raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, detail={"code": exc.code, "message": str(exc)}, ) from exc @router.post("/register", status_code=status.HTTP_201_CREATED) async def register(payload: UserRegister, db: AsyncSession = Depends(get_db)): existing = await db.execute( text("SELECT id, email_verified FROM users WHERE username = :u OR email = :e"), {"u": payload.username, "e": payload.email}, ) row = existing.fetchone() if row is not None: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail={"code": "USER_ALREADY_EXISTS", "message": "Username or email already in use"}, ) user = User( username=payload.username, email=payload.email, password_hash=get_password_hash(payload.password), role=UserRole.VIEWER.value, is_active=True, email_verified=False, ) db.add(user) await db.commit() try: code = otp.issue_code(payload.email, OtpPurpose.REGISTER) except otp.OtpResendRateLimited as exc: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail={"code": exc.code, "retry_after_seconds": exc.retry_after_seconds}, ) from exc await _send_code_or_raise(db, payload.email, code, OtpPurpose.REGISTER) return {"status": "pending_verification", "email": payload.email} @router.post("/verify-email", response_model=Token) async def verify_email(payload: VerifyEmailRequest, db: AsyncSession = Depends(get_db)): user = await _load_user_by_email(db, payload.email) if user is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail={"code": "USER_NOT_FOUND"}, ) try: otp.verify_code(payload.email, "register", payload.code) except otp.OtpExpired as exc: raise HTTPException( status_code=status.HTTP_410_GONE, detail={"code": exc.code, "message": str(exc)}, ) from exc except otp.OtpAttemptsExceeded as exc: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail={"code": exc.code, "message": str(exc)}, ) from exc except otp.OtpInvalid as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={"code": exc.code, "message": str(exc)}, ) from exc await db.execute( text("UPDATE users SET email_verified = TRUE WHERE id = :id"), {"id": user.id}, ) await db.commit() user.email_verified = True return _token_response(user) @router.post("/resend-code") async def resend_code(payload: ResendCodeRequest, db: AsyncSession = Depends(get_db)): user = await _load_user_by_email(db, payload.email) if user is None: # Avoid email enumeration; pretend success. return {"status": "ok"} if payload.purpose is OtpPurpose.REGISTER and user.email_verified: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail={"code": "ALREADY_VERIFIED"}, ) try: code = otp.issue_code(payload.email, payload.purpose) except otp.OtpResendRateLimited as exc: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail={"code": exc.code, "retry_after_seconds": exc.retry_after_seconds}, ) from exc await _send_code_or_raise(db, payload.email, code, payload.purpose) return {"status": "ok"} @router.post("/forgot-password") async def forgot_password(payload: ForgotPasswordRequest, db: AsyncSession = Depends(get_db)): user = await _load_user_by_email(db, payload.email) if user is None: # Don't leak whether an email is registered. return {"status": "ok"} try: code = otp.issue_code(payload.email, OtpPurpose.RESET_PASSWORD) except otp.OtpResendRateLimited: # Silently accept; the user can retry after the cooldown. return {"status": "ok"} try: await send_verification_email( db, to=payload.email, code=code, purpose=OtpPurpose.RESET_PASSWORD, ) except EmailNotConfiguredError as exc: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail={"code": exc.code, "message": str(exc)}, ) from exc except EmailError as exc: logger.warning_event( "SMTP send failed", event="auth.email.send_failed", context={ "email": payload.email, "purpose": OtpPurpose.RESET_PASSWORD.value, "error": str(exc), }, ) return {"status": "ok"} @router.post("/reset-password") async def reset_password(payload: ResetPasswordRequest, db: AsyncSession = Depends(get_db)): user = await _load_user_by_email(db, payload.email) if user is None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={"code": "OTP_INVALID"}, ) try: otp.verify_code(payload.email, OtpPurpose.RESET_PASSWORD, payload.code) except otp.OtpExpired as exc: raise HTTPException( status_code=status.HTTP_410_GONE, detail={"code": exc.code, "message": str(exc)}, ) from exc except otp.OtpAttemptsExceeded as exc: raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail={"code": exc.code, "message": str(exc)}, ) from exc except otp.OtpInvalid as exc: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail={"code": exc.code, "message": str(exc)}, ) from exc await db.execute( text("UPDATE users SET password_hash = :p, email_verified = TRUE WHERE id = :id"), {"p": get_password_hash(payload.new_password), "id": user.id}, ) await db.commit() return {"status": "ok"} class EarthSessionRequest(BaseModel): model_config = ConfigDict(extra="forbid") client_type: Literal["web", "desktop"] = "web" turnstile_token: Optional[str] = None def _is_https_request(request: Request) -> bool: forwarded_proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower() return forwarded_proto == "https" or request.url.scheme == "https" @router.post("/earth-session") async def create_earth_session( request: Request, response: Response, payload: EarthSessionRequest | None = Body(default=None), ): """Mint a short-lived Earth session credential for zero-login Web or Desktop Earth.""" body = payload or EarthSessionRequest() client_ip = _client_ip(request) if body.client_type == "desktop": await check_sliding_rate_limit( f"earth_session:desktop:{client_ip}", limit=120, window_seconds=3600, detail="Too many desktop Earth session requests", ) client_header = await verify_desktop_handshake(request) desktop_client_id = f"{client_ip}:{client_header}" token, ttl_seconds = create_earth_session_token("desktop", client_id=desktop_client_id) return { "token": token, "expires_in": ttl_seconds, "client_type": "desktop", } await check_sliding_rate_limit( f"earth_session:web:{client_ip}", limit=60, window_seconds=3600, detail="Too many web Earth session requests", ) verify_web_same_origin(request) await verify_turnstile_token(body.turnstile_token, client_ip) token, ttl_seconds = create_earth_session_token("web", client_id=client_ip) response.set_cookie( key=EARTH_SESSION_COOKIE, value=token, max_age=ttl_seconds, httponly=True, samesite="strict", secure=_is_https_request(request), path="/", ) return { "expires_in": ttl_seconds, "ws_token": token, "client_type": "web", "turnstile_required": bool(str(settings.TURNSTILE_SECRET_KEY or "").strip()), }