feat(auth): implement API key authentication and management

Introduce a new API key authentication mechanism to support service-to-service
communication (e.g., Airflow, CI/CD) without browser-based JWT login.

- Add `APIKey` model and `APIKeyPrincipal` dependency for RBAC.
- Implement `require_api_key_or_jwt` dependency with environment scoping.
- Add admin CRUD endpoints for API key lifecycle management.
- Add API key management UI in System Settings.
- Update maintenance API to support explicit `environment_id` and API key auth.
- Add i18n support for API keys and connection settings.
- Include Python and Bash usage examples in the `examples/` directory.
- Update technical specifications and documentation.
This commit is contained in:
2026-05-25 11:35:27 +03:00
parent 31680a1bc9
commit 320f82ab95
39 changed files with 3359 additions and 707 deletions

View File

@@ -1,4 +1,4 @@
# #region AppDependencies [C:3] [TYPE Module] [SEMANTICS fastapi, schedule]
# #region AppDependencies [C:4] [TYPE Module] [SEMANTICS fastapi, schedule, auth, api_key]
# @BRIEF Manages creation and provision of shared application dependencies, such as PluginLoader and TaskManager, to avoid circular imports.
# @LAYER: Core
# @RELATION Used by main app and API routers to get access to shared instances.
@@ -9,12 +9,18 @@
# @RELATION CALLS -> [TaskManager]
# @RELATION CALLS -> [get_all_plugin_configs]
# @RELATION CALLS -> [get_db]
# @RELATION CALLS -> [APIKeyPrincipal]
# @RELATION CALLS -> [get_api_key_principal]
# @RELATION CALLS -> [info]
# @RELATION CALLS -> [init_db]
import json
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
from fastapi import Depends, HTTPException, status
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError
@@ -26,6 +32,7 @@ from .core.logger import logger
from .core.plugin_loader import PluginLoader
from .core.scheduler import SchedulerService
from .core.task_manager import TaskManager
from .models.api_key import APIKey
from .models.auth import User
from .services.clean_release.facade import CleanReleaseFacade
from .services.clean_release.repositories import (
@@ -201,12 +208,295 @@ def get_clean_release_facade(db=Depends(get_db)) -> CleanReleaseFacade:
# #endregion get_clean_release_facade
# #region APIKeyPrincipal [C:1] [TYPE Class]
# @BRIEF Dataclass representing an authenticated API key principal for service-to-service auth.
@dataclass
class APIKeyPrincipal:
name: str
api_key_id: str
environment_id: Optional[str] = None
permissions: list[str] = field(default_factory=list)
# #endregion APIKeyPrincipal
# #region require_api_key_or_jwt [C:4] [TYPE Function]
# @BRIEF Factory: creates a dependency that accepts either a valid API key (with permission check)
# OR a JWT (with standard has_permission check). Returns the authenticated user/principal name.
# JWT takes precedence when both auth methods are present.
# When API key is used, its environment_id scope is enforced against the caller's environment_id.
# @PRE required_api_permission is a dot-separated string e.g. "maintenance:start".
# required_jwt_resource and required_jwt_action are the JWT permission to check.
# environment_id is the target environment for the operation (may be None for cross-env ops).
# @POST Returns str (username or api key name). Raises 400/401/403 if auth fails or scope mismatch.
# @SIDE_EFFECT Updates APIKey.last_used_at on successful API key auth.
# @RELATION DEPENDS_ON -> [APIKeyModel]
# @RELATION DEPENDS_ON -> [hash_api_key]
# @RELATION DEPENDS_ON -> [AuthRepository]
# @RELATION DEPENDS_ON -> [decode_token]
def require_api_key_or_jwt(
required_api_permission: str,
required_jwt_resource: str,
required_jwt_action: str,
environment_id: str | None = None,
):
"""Factory: creates a combined API-key-or-JWT auth dependency with environment scoping.
JWT takes precedence when both Authorization: Bearer and X-API-Key are present.
When API key auth is used, the key's environment_id scope is enforced:
- If key.environment_id differs from environment_id → 400
- If environment_id is None, the key's scope is used as default (auto-scope).
Args:
required_api_permission: Permission string to check against API key (e.g. 'maintenance:start').
required_jwt_resource: JWT resource for has_permission fallback.
required_jwt_action: JWT action for has_permission fallback.
environment_id: Target environment for the operation. Pass None for cross-env operations.
"""
async def _auth_dependency(
request: Request,
db=Depends(get_db),
auth_db=Depends(get_auth_db),
token: str | None = Depends(oauth2_scheme_optional),
) -> str:
from .core.auth.api_key import hash_api_key
# Resolve effective environment_id: factory parameter > request body > None
effective_env_id = environment_id
if effective_env_id is None:
try:
body = await request.json()
effective_env_id = body.get("environment_id")
except (json.JSONDecodeError, KeyError, AttributeError):
pass
# ── Try JWT auth first (JWT takes precedence over API key) ──
if token:
try:
payload = decode_token(token)
username_value = payload.get("sub")
if not isinstance(username_value, str) or not username_value:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
username = username_value
except Exception:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
repo = AuthRepository(auth_db)
user = repo.get_user_by_username(username)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found",
)
# Check JWT permission (Admin has full access)
has_perm = any(
role.name == "Admin"
for role in user.roles
)
if not has_perm:
for role in user.roles:
for perm in role.permissions:
if perm.resource == required_jwt_resource and perm.action == required_jwt_action:
has_perm = True
break
if has_perm:
break
if not has_perm:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission denied for {required_jwt_resource}:{required_jwt_action}",
)
logger.info(f"JWT auth: {user.username}")
return f"jwt:{user.username}"
# ── Try API key auth ──
raw_key = request.headers.get("X-API-Key")
if raw_key:
key_hash = hash_api_key(raw_key)
api_key = db.query(APIKey).filter(APIKey.key_hash == key_hash).first()
if not api_key:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API key",
)
if not api_key.active:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="API key has been revoked",
)
if api_key.expires_at:
expires_at = api_key.expires_at
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=timezone.utc)
if expires_at < datetime.now(timezone.utc):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="API key has expired",
)
# Check API key has required permission
api_permissions = list(api_key.permissions or [])
if required_api_permission not in api_permissions:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"API key lacks permission '{required_api_permission}'",
)
# Environment scoping check: key's scope vs effective operation env
key_env = api_key.environment_id
if key_env is not None and effective_env_id is not None and key_env != effective_env_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"API key is restricted to environment '{key_env}'",
)
# Update last_used_at (best-effort, non-blocking)
api_key.last_used_at = datetime.now(timezone.utc)
db.flush()
logger.info(f"API key auth: {api_key.name} ({api_key.prefix}...)")
return f"api_key:{api_key.name}"
# ── Neither JWT nor API key provided ──
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required (API key or JWT)",
)
return _auth_dependency
# #endregion require_api_key_or_jwt
# #region check_api_key_environment_scope [C:1] [TYPE Function]
# @BRIEF Check the request's API key environment scope against a target env_id. Raises 400 if mismatch.
# @RELATION DEPENDS_ON -> [APIKeyModel]
# @RELATION DEPENDS_ON -> [hash_api_key]
async def check_api_key_environment_scope(request: Request, db, target_env_id: str) -> None:
"""Check the request's API key environment scope against a target environment_id.
If the API key has an environment_id set and it differs from target_env_id,
raises HTTP 400. This is used in route handlers where the target env_id
is only known at request time (e.g., loaded from DB in end_maintenance).
Args:
request: FastAPI request object (to extract X-API-Key header).
db: Database session.
target_env_id: The target environment to validate against.
"""
from .core.auth.api_key import hash_api_key
raw_key = request.headers.get("X-API-Key")
if not raw_key:
return
key_hash = hash_api_key(raw_key)
api_key = db.query(APIKey).filter(APIKey.key_hash == key_hash).first()
if api_key is None:
return
key_env = api_key.environment_id
if key_env is not None and key_env != target_env_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"API key is restricted to environment '{key_env}'",
)
# #endregion check_api_key_environment_scope
# #region get_api_key_principal [C:3] [TYPE Function]
# @BRIEF FastAPI dependency that reads X-API-Key header and returns APIKeyPrincipal or None.
# @PRE X-API-Key header may be present in the request.
# @POST If valid key: returns APIKeyPrincipal; if no header: returns None; if invalid: raises 401.
# @SIDE_EFFECT Updates last_used_at on the APIKey row (non-blocking flush).
# @RELATION DEPENDS_ON -> [APIKeyModel]
# @RELATION DEPENDS_ON -> [hash_api_key]
async def get_api_key_principal(
request: Request,
db=Depends(get_db),
) -> Optional[APIKeyPrincipal]:
"""Extract and validate API key from X-API-Key header.
If no header is present, returns None (fall through to JWT auth).
If header is present but invalid, raises 401.
Returns:
APIKeyPrincipal | None: Principal if valid API key, None if no header.
"""
from .core.auth.api_key import hash_api_key
raw_key = request.headers.get("X-API-Key")
if not raw_key:
return None
key_hash = hash_api_key(raw_key)
api_key = db.query(APIKey).filter(APIKey.key_hash == key_hash).first()
if not api_key:
logger.warning(f"API key auth failed: key not found (hash prefix: {raw_key[:11]}...)")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API key",
)
if not api_key.active:
logger.warning(f"API key auth failed: key revoked (id: {api_key.id}, name: {api_key.name})")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="API key has been revoked",
)
if api_key.expires_at:
expires_at = api_key.expires_at
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=timezone.utc)
if expires_at < datetime.now(timezone.utc):
logger.warning(f"API key auth failed: key expired (id: {api_key.id}, name: {api_key.name})")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="API key has expired",
)
# Update last_used_at (non-blocking, best-effort)
api_key.last_used_at = datetime.now(timezone.utc)
db.flush()
logger.info(f"API key auth success: {api_key.name} ({api_key.prefix}...)")
return APIKeyPrincipal(
name=api_key.name,
api_key_id=api_key.id,
environment_id=api_key.environment_id,
permissions=list(api_key.permissions or []),
)
# #endregion get_api_key_principal
# #region oauth2_scheme [C:1] [TYPE Variable]
# @RELATION DEPENDS_ON -> OAuth2PasswordBearer
# @BRIEF OAuth2 password bearer scheme for token extraction.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
# @BRIEF OAuth2 password bearer scheme for token extraction (raises 401 on missing token).
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=True)
# #endregion oauth2_scheme
# #region oauth2_scheme_optional [C:1] [TYPE Variable]
# @RELATION DEPENDS_ON -> OAuth2PasswordBearer
# @BRIEF Optional OAuth2 scheme — returns None instead of raising 401 when no token.
# @RATIONALE Used in dual-auth routes (API key OR JWT) where JWT may be absent.
oauth2_scheme_optional = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
# #endregion oauth2_scheme_optional
# #region get_current_user [C:3] [TYPE Function]
# @RELATION CALLS -> AuthRepository