Files
planet/backend/app/core/access_gate.py
T
linkong b3d2d9e9f1
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.81.0
2026-11-30 19:39:29 +08:00

493 lines
17 KiB
Python

"""Unified access gate for first-party Earth sessions, API keys, and authorized JWT callers."""
from __future__ import annotations
import asyncio
from collections import defaultdict, deque
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
import hashlib
import hmac
import secrets
import time
from typing import Any, Literal
from urllib.parse import urlsplit
from uuid import uuid4
from fastapi import Depends, HTTPException, Request, WebSocket, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
import httpx
from jose import JWTError, jwt
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import (
REDIS_OP_TIMEOUT_SECONDS,
_AsyncRedisClient,
_load_active_user,
decode_token,
get_current_user,
is_token_blacklisted,
)
from app.db.session import get_db
from app.models.user import User
from app.services.api_keys import authenticate_api_key
logger = get_logger(__name__, service="access_gate")
EARTH_SESSION_COOKIE = "planet_earth_session"
EARTH_TOKEN_HEADER = "X-Planet-Earth-Token"
API_KEY_HEADER = "X-API-Key"
API_ACCESS_GROUP = "api_access"
DESKTOP_CLIENT_PREFIX = "planet-earth-desktop/"
TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
_EARTH_SESSION_TOKEN_TYPE = "earth_session"
_MAX_DESKTOP_CLOCK_SKEW_SECONDS = 300
_EARTH_SESSION_RATE_LIMIT_PER_MIN = 600
_LOCAL_SLIDING_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
_LOCAL_NONCES: dict[str, float] = {}
_MAX_LOCAL_ENTRIES = 20_000
optional_bearer = HTTPBearer(auto_error=False)
@dataclass(frozen=True, slots=True)
class EarthAccessContext:
"""Resolved caller identity for Earth data and external API routes."""
channel: Literal["api_key", "jwt", "earth_web", "earth_desktop", "dev_open"]
actor_key: str
user: User | None = None
api_key_id: int | None = None
def reset_access_gate_caches() -> None:
"""Clear in-process rate-limit and nonce caches (used by tests)."""
_LOCAL_SLIDING_WINDOWS.clear()
_LOCAL_NONCES.clear()
def _prune_local_nonces(now: float) -> None:
expired = [key for key, exp in _LOCAL_NONCES.items() if exp <= now]
for key in expired:
_LOCAL_NONCES.pop(key, None)
while len(_LOCAL_NONCES) > _MAX_LOCAL_ENTRIES:
_LOCAL_NONCES.pop(next(iter(_LOCAL_NONCES)), None)
async def check_sliding_rate_limit(
bucket: str,
*,
limit: int,
window_seconds: int,
detail: str = "Rate limit exceeded",
) -> None:
"""Enforce a bounded sliding/fixed window limit via Redis with local fallback."""
if limit <= 0 or window_seconds <= 0:
return
redis_key = f"access_gate:{bucket}"
try:
client = _AsyncRedisClient.get_client()
count = await asyncio.wait_for(
client.incr(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) == 1:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) > limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=detail,
)
return
except HTTPException:
raise
except Exception:
pass
now = time.monotonic()
dq = _LOCAL_SLIDING_WINDOWS[bucket]
cutoff = now - float(window_seconds)
while dq and dq[0] <= cutoff:
dq.popleft()
if len(dq) >= limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=detail,
)
dq.append(now)
if len(_LOCAL_SLIDING_WINDOWS) > _MAX_LOCAL_ENTRIES:
_LOCAL_SLIDING_WINDOWS.pop(next(iter(_LOCAL_SLIDING_WINDOWS)), None)
async def _register_nonce_once(nonce: str, ttl_seconds: int) -> bool:
key = f"earth_nonce:{hashlib.sha256(nonce.encode('utf-8')).hexdigest()}"
try:
client = _AsyncRedisClient.get_client()
stored = await asyncio.wait_for(
client.set(key, "1", ex=ttl_seconds, nx=True),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
return bool(stored)
except Exception:
pass
now = time.monotonic()
_prune_local_nonces(now)
if key in _LOCAL_NONCES and _LOCAL_NONCES[key] > now:
return False
_LOCAL_NONCES[key] = now + float(ttl_seconds)
return True
def create_earth_session_token(
channel: Literal["web", "desktop"],
client_id: str | None = None,
) -> tuple[str, int]:
"""Mint a short-lived signed JWT for Web Earth or Desktop Earth zero-login access."""
ttl_minutes = max(5, int(settings.EARTH_SESSION_TTL_MINUTES or 30))
ttl_seconds = ttl_minutes * 60
expire = datetime.now(UTC) + timedelta(seconds=ttl_seconds)
cid = (client_id or uuid4().hex[:16]).strip()[:64]
payload = {
"type": _EARTH_SESSION_TOKEN_TYPE,
"channel": channel,
"cid": cid,
"jti": uuid4().hex,
"exp": expire,
}
token = jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return token, ttl_seconds
def verify_earth_session_token(token: str) -> dict[str, Any] | None:
"""Verify a signed Earth session token and return its claims or None."""
cleaned = str(token or "").strip()
if not cleaned:
return None
try:
payload = jwt.decode(cleaned, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
except JWTError:
return None
if payload.get("type") != _EARTH_SESSION_TOKEN_TYPE:
return None
if payload.get("channel") not in {"web", "desktop"}:
return None
return payload
def _extract_host_port(raw_url_or_host: str) -> str:
value = str(raw_url_or_host or "").strip()
if not value:
return ""
if "://" in value:
parsed = urlsplit(value)
return (parsed.netloc or "").lower()
return value.lower()
def _allowed_web_origins(request: Request) -> set[str]:
allowed: set[str] = set()
req_host = _extract_host_port(request.headers.get("host") or request.url.netloc or "")
if req_host:
allowed.add(req_host)
for raw in [*(settings.EARTH_WEB_ALLOWED_ORIGINS or []), *(settings.CORS_ORIGINS or [])]:
host = _extract_host_port(str(raw))
if host and host != "*":
allowed.add(host)
return allowed
def verify_web_same_origin(request: Request) -> None:
"""Require first-party browser same-origin / allowed-origin headers for web session minting."""
sec_fetch_site = (request.headers.get("sec-fetch-site") or "").strip().lower()
if sec_fetch_site in {"cross-site"}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Cross-site Earth session requests are forbidden",
)
origin_host = _extract_host_port(request.headers.get("origin") or "")
referer_host = _extract_host_port(request.headers.get("referer") or "")
allowed = _allowed_web_origins(request)
if origin_host:
if origin_host not in allowed:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Origin not permitted for Earth web session",
)
return
if referer_host:
if referer_host not in allowed:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Referer not permitted for Earth web session",
)
return
if sec_fetch_site in {"same-origin", "same-site"}:
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Same-origin browser headers required for Earth web session",
)
async def verify_turnstile_token(token: str | None, remote_ip: str) -> None:
"""Verify Cloudflare Turnstile token when `TURNSTILE_SECRET_KEY` is configured."""
secret = str(settings.TURNSTILE_SECRET_KEY or "").strip()
if not secret:
return
cleaned = str(token or "").strip()
if not cleaned:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Turnstile verification token is required",
)
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.post(
TURNSTILE_VERIFY_URL,
data={
"secret": secret,
"response": cleaned,
"remoteip": remote_ip,
},
)
resp.raise_for_status()
body = resp.json()
except httpx.HTTPError as exc:
logger.warning_event(
"Turnstile verification request failed",
event="access_gate.turnstile.error",
context={"error": str(exc)},
)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Human verification service temporarily unavailable",
) from exc
if not bool(body.get("success")):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Turnstile verification failed",
)
async def verify_desktop_handshake(request: Request) -> str:
"""Verify Planet Earth Desktop client identity and optional HMAC handshake."""
client_header = (request.headers.get("X-Planet-Client") or "").strip()
if not client_header.startswith(DESKTOP_CLIENT_PREFIX) or len(client_header) <= len(
DESKTOP_CLIENT_PREFIX
):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Desktop client header is required",
)
secret = str(settings.EARTH_DESKTOP_HANDSHAKE_SECRET or "").strip()
if not secret:
return client_header
ts_raw = (request.headers.get("X-Planet-Client-Timestamp") or "").strip()
nonce = (request.headers.get("X-Planet-Client-Nonce") or "").strip()
signature = (request.headers.get("X-Planet-Client-Signature") or "").strip().lower()
if not ts_raw or not nonce or not signature or len(nonce) > 128:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Desktop handshake signature headers required",
)
try:
ts_val = int(ts_raw)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid desktop handshake timestamp",
) from exc
now_ts = int(time.time())
if abs(now_ts - ts_val) > _MAX_DESKTOP_CLOCK_SKEW_SECONDS:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Desktop handshake timestamp expired",
)
expected = hmac.new(
secret.encode("utf-8"),
f"{ts_raw}.{nonce}.{client_header}".encode("utf-8"),
hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid desktop handshake signature",
)
fresh = await _register_nonce_once(nonce, _MAX_DESKTOP_CLOCK_SKEW_SECONDS)
if not fresh:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Replay desktop handshake nonce rejected",
)
return client_header
def user_has_api_access(user: User) -> bool:
"""Return True if the authenticated user is allowed to call Earth/external APIs."""
role = user.role.value if hasattr(user.role, "value") else str(user.role or "")
if role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
return True
groups = {str(g).strip() for g in (user.gatekeeper_groups or []) if g}
return API_ACCESS_GROUP in groups
async def require_admin_user(current_user: User = Depends(get_current_user)) -> User:
"""FastAPI dependency requiring `admin` or `super_admin` role."""
role = current_user.role.value if hasattr(current_user.role, "value") else str(current_user.role or "")
if role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Administrator privileges required",
)
return current_user
async def _validate_bearer_api_user(
token: str,
db: AsyncSession,
) -> User:
if await is_token_blacklisted(token):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has been revoked",
)
payload = decode_token(token)
if payload is None or payload.get("type") != "access" or payload.get("sub") is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
)
user = await _load_active_user(str(payload["sub"]), db)
if not user_has_api_access(user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account lacks api_access permission",
)
return user
def require_earth_or_api_access(
scope: str,
*,
allow_query_api_key: bool = False,
):
"""Build a FastAPI dependency allowing API Keys, authorized JWT users, or Earth sessions."""
async def _dependency(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
db: AsyncSession = Depends(get_db),
) -> EarthAccessContext:
raw_api_key = (request.headers.get(API_KEY_HEADER) or "").strip()
if not raw_api_key and allow_query_api_key:
raw_api_key = (request.query_params.get("api_key") or "").strip()
if raw_api_key:
record = await authenticate_api_key(db, raw_api_key, scope)
return EarthAccessContext(
channel="api_key",
actor_key=f"api_key:{record.id}",
api_key_id=int(record.id),
)
if credentials is not None and credentials.credentials:
user = await _validate_bearer_api_user(credentials.credentials, db)
return EarthAccessContext(
channel="jwt",
actor_key=f"user:{user.id}",
user=user,
)
earth_header = (request.headers.get(EARTH_TOKEN_HEADER) or "").strip()
earth_cookie = (request.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
earth_token = earth_header or earth_cookie
if earth_token:
claims = verify_earth_session_token(earth_token)
if claims is not None:
channel = "earth_desktop" if claims.get("channel") == "desktop" else "earth_web"
cid = str(claims.get("cid") or "anon")
await check_sliding_rate_limit(
f"earth:{channel}:{cid}",
limit=_EARTH_SESSION_RATE_LIMIT_PER_MIN,
window_seconds=60,
detail="Earth session rate limit exceeded",
)
return EarthAccessContext(
channel=channel,
actor_key=f"{channel}:{cid}",
)
if settings.effective_earth_api_auth_mode == "enforce":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired Earth session",
)
if settings.effective_earth_api_auth_mode == "enforce":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
)
return EarthAccessContext(channel="dev_open", actor_key="dev:open")
return _dependency
async def authenticate_ws_earth_or_api_key(
websocket: WebSocket,
*,
api_key_query: str | None,
earth_token_query: str | None,
db: AsyncSession,
) -> tuple[bool, str | None]:
"""Authenticate non-JWT WebSocket connections via API key or Earth session token.
Returns `(authenticated, actor_id)`. Raises HTTPException on explicit invalid credentials.
"""
raw_api_key = (
(websocket.headers.get(API_KEY_HEADER) or "").strip()
or (api_key_query or "").strip()
)
if raw_api_key:
record = await authenticate_api_key(db, raw_api_key, "ws:connect")
return True, f"api_key:{record.id}"
raw_earth_token = (
(websocket.headers.get(EARTH_TOKEN_HEADER) or "").strip()
or (earth_token_query or "").strip()
or (websocket.cookies.get(EARTH_SESSION_COOKIE) or "").strip()
)
if raw_earth_token:
claims = verify_earth_session_token(raw_earth_token)
if claims is None:
if settings.effective_earth_api_auth_mode == "enforce":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or expired Earth WebSocket session",
)
return False, None
channel = str(claims.get("channel") or "web")
cid = str(claims.get("cid") or secrets.token_hex(4))
return True, f"earth_{channel}:{cid}"
return False, None