forked from linkong/planet
316 lines
10 KiB
Python
316 lines
10 KiB
Python
"""API key lifecycle, scope evaluation, hashing, and rate-limited validation."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from collections import defaultdict, deque
|
|
from datetime import UTC, datetime, timedelta
|
|
import hashlib
|
|
import secrets
|
|
import time
|
|
from typing import Any
|
|
|
|
from fastapi import HTTPException, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.logging import get_logger
|
|
from app.core.security import REDIS_OP_TIMEOUT_SECONDS, _AsyncRedisClient
|
|
from app.core.time import to_iso8601_utc
|
|
from app.models.api_key import ApiKey
|
|
|
|
logger = get_logger(__name__, service="api_keys")
|
|
|
|
API_KEY_PREFIX = "plt_live_"
|
|
EARTH_ALL_READ_SCOPE = "earth:all_read"
|
|
|
|
EARTH_READ_SCOPES: frozenset[str] = frozenset(
|
|
{
|
|
"visualization:read",
|
|
"layers:read",
|
|
"vessels:read",
|
|
"news:read",
|
|
"data_products:read",
|
|
"situational:read",
|
|
"earth:read",
|
|
"interactables:read",
|
|
"tv:read",
|
|
"ws:connect",
|
|
}
|
|
)
|
|
|
|
VALID_API_KEY_SCOPES: frozenset[str] = frozenset({EARTH_ALL_READ_SCOPE, *EARTH_READ_SCOPES})
|
|
|
|
_LAST_USED_TOUCH_CACHE: dict[int, float] = {}
|
|
_LOCAL_KEY_RATE_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
|
|
_LAST_USED_MIN_INTERVAL_SECONDS = 60.0
|
|
|
|
|
|
def reset_api_key_runtime_caches() -> None:
|
|
"""Clear in-process caches (intended for deterministic tests)."""
|
|
_LAST_USED_TOUCH_CACHE.clear()
|
|
_LOCAL_KEY_RATE_WINDOWS.clear()
|
|
|
|
|
|
def hash_api_key(raw_key: str) -> str:
|
|
"""Compute SHA-256 hex digest of a raw API key."""
|
|
return hashlib.sha256(raw_key.strip().encode("utf-8")).hexdigest()
|
|
|
|
|
|
def mask_api_key_prefix(raw_key: str) -> str:
|
|
"""Return a short non-sensitive prefix for UI display and logging."""
|
|
cleaned = raw_key.strip()
|
|
return f"{cleaned[:16]}..." if len(cleaned) > 16 else f"{cleaned[:8]}..."
|
|
|
|
|
|
def normalize_api_key_scopes(scopes: list[str] | None) -> list[str]:
|
|
"""Validate and deduplicate requested API key scopes."""
|
|
if not scopes:
|
|
return [EARTH_ALL_READ_SCOPE]
|
|
normalized: list[str] = []
|
|
seen: set[str] = set()
|
|
invalid: list[str] = []
|
|
for raw in scopes:
|
|
scope = str(raw or "").strip()
|
|
if not scope:
|
|
continue
|
|
if scope not in VALID_API_KEY_SCOPES:
|
|
invalid.append(scope)
|
|
continue
|
|
if scope not in seen:
|
|
seen.add(scope)
|
|
normalized.append(scope)
|
|
if invalid:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail=f"Unsupported API key scope(s): {', '.join(invalid)}",
|
|
)
|
|
if not normalized:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="At least one valid scope is required",
|
|
)
|
|
return normalized
|
|
|
|
|
|
def api_key_allows_scope(key_scopes: list[str] | None, required_scope: str) -> bool:
|
|
"""Return True if the key scopes authorize `required_scope`."""
|
|
scopes = {str(item).strip() for item in (key_scopes or []) if item}
|
|
if required_scope in scopes:
|
|
return True
|
|
if EARTH_ALL_READ_SCOPE in scopes and required_scope in EARTH_READ_SCOPES:
|
|
return True
|
|
return False
|
|
|
|
|
|
def _ensure_utc(dt: datetime | None) -> datetime | None:
|
|
if dt is None:
|
|
return None
|
|
if dt.tzinfo is None:
|
|
return dt.replace(tzinfo=UTC)
|
|
return dt.astimezone(UTC)
|
|
|
|
|
|
def serialize_api_key(record: ApiKey) -> dict[str, Any]:
|
|
"""Serialize ApiKey metadata safely without exposing key_hash or raw secret."""
|
|
now = datetime.now(UTC)
|
|
expires_at = _ensure_utc(record.expires_at)
|
|
is_expired = bool(expires_at is not None and expires_at <= now)
|
|
status_label = "revoked" if not record.is_active else ("expired" if is_expired else "active")
|
|
return {
|
|
"id": record.id,
|
|
"name": record.name,
|
|
"key_prefix": record.key_prefix,
|
|
"scopes": list(record.scopes or []),
|
|
"rate_limit_per_minute": record.rate_limit_per_minute,
|
|
"expires_at": to_iso8601_utc(expires_at),
|
|
"is_active": bool(record.is_active),
|
|
"is_expired": is_expired,
|
|
"status": status_label,
|
|
"created_by_user_id": record.created_by_user_id,
|
|
"last_used_at": to_iso8601_utc(_ensure_utc(record.last_used_at)),
|
|
"revoked_at": to_iso8601_utc(_ensure_utc(record.revoked_at)),
|
|
"created_at": to_iso8601_utc(_ensure_utc(record.created_at)),
|
|
}
|
|
|
|
|
|
async def _enforce_api_key_rate_limit(key_id: int, limit_per_minute: int | None) -> None:
|
|
if limit_per_minute is None or int(limit_per_minute) <= 0:
|
|
return
|
|
limit = int(limit_per_minute)
|
|
window = 60
|
|
bucket = f"rate:api_key:{key_id}"
|
|
try:
|
|
client = _AsyncRedisClient.get_client()
|
|
current_count = await asyncio.wait_for(
|
|
client.incr(bucket),
|
|
timeout=REDIS_OP_TIMEOUT_SECONDS,
|
|
)
|
|
if int(current_count) == 1:
|
|
await asyncio.wait_for(client.expire(bucket, window), timeout=REDIS_OP_TIMEOUT_SECONDS)
|
|
if int(current_count) > limit:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
detail="API key rate limit exceeded",
|
|
)
|
|
return
|
|
except HTTPException:
|
|
raise
|
|
except Exception:
|
|
pass
|
|
|
|
now = time.monotonic()
|
|
dq = _LOCAL_KEY_RATE_WINDOWS[bucket]
|
|
cutoff = now - float(window)
|
|
while dq and dq[0] <= cutoff:
|
|
dq.popleft()
|
|
if len(dq) >= limit:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
detail="API key rate limit exceeded",
|
|
)
|
|
dq.append(now)
|
|
|
|
|
|
async def create_api_key(
|
|
db: AsyncSession,
|
|
*,
|
|
name: str,
|
|
scopes: list[str] | None,
|
|
rate_limit_per_minute: int | None,
|
|
expires_in_days: int | None,
|
|
created_by_user_id: int | None,
|
|
) -> tuple[ApiKey, str]:
|
|
"""Create and persist a new API key, returning `(record, raw_plaintext_once)`."""
|
|
cleaned_name = str(name or "").strip()
|
|
if not cleaned_name:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="API key name is required",
|
|
)
|
|
normalized_scopes = normalize_api_key_scopes(scopes)
|
|
normalized_limit = (
|
|
int(rate_limit_per_minute)
|
|
if rate_limit_per_minute is not None and int(rate_limit_per_minute) > 0
|
|
else None
|
|
)
|
|
expires_at: datetime | None = None
|
|
if expires_in_days is not None and int(expires_in_days) > 0:
|
|
expires_at = datetime.now(UTC) + timedelta(days=int(expires_in_days))
|
|
|
|
raw_key = f"{API_KEY_PREFIX}{secrets.token_urlsafe(32)}"
|
|
record = ApiKey(
|
|
name=cleaned_name[:120],
|
|
key_prefix=mask_api_key_prefix(raw_key),
|
|
key_hash=hash_api_key(raw_key),
|
|
scopes=normalized_scopes,
|
|
rate_limit_per_minute=normalized_limit,
|
|
expires_at=expires_at,
|
|
is_active=True,
|
|
created_by_user_id=created_by_user_id,
|
|
)
|
|
db.add(record)
|
|
await db.commit()
|
|
await db.refresh(record)
|
|
logger.info_event(
|
|
"Created API key",
|
|
event="api_key.created",
|
|
context={
|
|
"key_id": record.id,
|
|
"key_prefix": record.key_prefix,
|
|
"scopes": normalized_scopes,
|
|
"has_expiry": expires_at is not None,
|
|
"rate_limit_per_minute": normalized_limit,
|
|
"created_by_user_id": created_by_user_id,
|
|
},
|
|
)
|
|
return record, raw_key
|
|
|
|
|
|
async def list_api_keys(db: AsyncSession) -> list[ApiKey]:
|
|
result = await db.execute(select(ApiKey).order_by(ApiKey.created_at.desc(), ApiKey.id.desc()))
|
|
return list(result.scalars().all())
|
|
|
|
|
|
async def revoke_api_key(db: AsyncSession, key_id: int) -> ApiKey:
|
|
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
|
record = result.scalar_one_or_none()
|
|
if record is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
|
|
if record.is_active:
|
|
record.is_active = False
|
|
record.revoked_at = datetime.now(UTC)
|
|
await db.commit()
|
|
await db.refresh(record)
|
|
logger.info_event(
|
|
"Revoked API key",
|
|
event="api_key.revoked",
|
|
context={"key_id": record.id, "key_prefix": record.key_prefix},
|
|
)
|
|
return record
|
|
|
|
|
|
async def delete_api_key(db: AsyncSession, key_id: int) -> None:
|
|
result = await db.execute(select(ApiKey).where(ApiKey.id == key_id))
|
|
record = result.scalar_one_or_none()
|
|
if record is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="API key not found")
|
|
prefix = record.key_prefix
|
|
await db.delete(record)
|
|
await db.commit()
|
|
logger.info_event(
|
|
"Deleted API key",
|
|
event="api_key.deleted",
|
|
context={"key_id": key_id, "key_prefix": prefix},
|
|
)
|
|
|
|
|
|
async def authenticate_api_key(
|
|
db: AsyncSession,
|
|
raw_key: str,
|
|
required_scope: str,
|
|
) -> ApiKey:
|
|
"""Validate an incoming raw API key for active status, expiration, scope, and rate limit."""
|
|
cleaned = str(raw_key or "").strip()
|
|
if not cleaned:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid API key",
|
|
)
|
|
|
|
digest = hash_api_key(cleaned)
|
|
result = await db.execute(select(ApiKey).where(ApiKey.key_hash == digest))
|
|
record = result.scalar_one_or_none()
|
|
if record is None or not record.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or revoked API key",
|
|
)
|
|
|
|
expires_at = _ensure_utc(record.expires_at)
|
|
if expires_at is not None and expires_at <= datetime.now(UTC):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="API key has expired",
|
|
)
|
|
|
|
if not api_key_allows_scope(list(record.scopes or []), required_scope):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail=f"API key lacks required scope: {required_scope}",
|
|
)
|
|
|
|
await _enforce_api_key_rate_limit(int(record.id), record.rate_limit_per_minute)
|
|
|
|
now_mono = time.monotonic()
|
|
last_touched = _LAST_USED_TOUCH_CACHE.get(int(record.id), 0.0)
|
|
if now_mono - last_touched >= _LAST_USED_MIN_INTERVAL_SECONDS:
|
|
_LAST_USED_TOUCH_CACHE[int(record.id)] = now_mono
|
|
try:
|
|
record.last_used_at = datetime.now(UTC)
|
|
await db.commit()
|
|
except Exception:
|
|
await db.rollback()
|
|
|
|
return record
|