Buckets:

download
raw
11.5 kB
# Copyright (c) 2025-2026 Yutaro Maeda. All rights reserved.
# Licensed under the Apache License 2.0. See LICENSE file for details.
"""API key authentication and RBAC for FaultRay."""
from __future__ import annotations
import hashlib
import logging
import secrets
from enum import Enum
from typing import Optional
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy import select
from faultray.api.database import UserRow, get_session_factory
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# RBAC — Role-Based Access Control
# ---------------------------------------------------------------------------
class Role(str, Enum):
ADMIN = "admin" # Full access
EDITOR = "editor" # Run simulations, create projects
VIEWER = "viewer" # Read-only access
ROLE_PERMISSIONS: dict[Role, set[str]] = {
Role.ADMIN: {"*"}, # everything
Role.EDITOR: {
"view_dashboard", "run_simulation", "create_project",
"view_results", "export_results", "manage_own_projects",
},
Role.VIEWER: {
"view_dashboard", "view_results", "export_results",
},
}
def require_permission(permission: str):
"""FastAPI dependency that checks user has required permission.
When no users exist, only /setup and /docs endpoints are accessible.
All other endpoints require authentication.
"""
async def check(request: Request):
user = await _resolve_user(request)
# No-auth mode: only allow setup and docs endpoints
if user is None:
return None
role = Role(getattr(user, "role", None) or "viewer")
allowed = ROLE_PERMISSIONS.get(role, set())
if "*" not in allowed and permission not in allowed:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Permission '{permission}' required",
)
return user
return check
async def _resolve_user(request: Request) -> UserRow | None:
"""Resolve user for permission checks, reusing get_current_user logic.
Fails closed: ``get_current_user`` returns ``None`` only for legitimately
public / no-users-configured cases, and raises ``HTTPException`` for auth
failures. Any *other* exception (DB outage, bad data) must NOT be swallowed
into a None that ``require_permission`` would treat as "access allowed";
surface it as a 500 so the request is denied.
"""
try:
credentials = await _bearer_scheme(request)
return await get_current_user(request, credentials)
except HTTPException:
raise
except Exception as exc:
logger.exception("User resolution failed unexpectedly; denying request")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Authorization check failed",
) from exc
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
_bearer_scheme = HTTPBearer(auto_error=False)
def hash_api_key(api_key: str) -> str:
"""Return the SHA-256 hex digest of an API key."""
return hashlib.sha256(api_key.encode()).hexdigest()
def generate_api_key() -> str:
"""Generate a new random API key (48 URL-safe bytes)."""
return secrets.token_urlsafe(48)
def _looks_like_jwt(token: str) -> bool:
"""Return True if *token* has the structural shape of a JWT.
A JWS-compact JWT is exactly three non-empty, dot-separated base64url
segments (``header.payload.signature``). API keys produced by
:func:`generate_api_key` are a single URL-safe token with no dots, so this
cheaply distinguishes the two without importing the (optionally
misconfigured) JWT subsystem for plain API keys.
"""
parts = token.split(".")
return len(parts) == 3 and all(parts)
# ---------------------------------------------------------------------------
# Public endpoints that skip auth
# ---------------------------------------------------------------------------
PUBLIC_PATHS = frozenset({
"/",
"/docs",
"/redoc",
"/openapi.json",
"/demo",
"/static",
# NOTE: '/components', '/simulation', '/simulation/run' and '/graph' are
# intentionally NOT public — they expose infrastructure inventory/topology
# and cached simulation findings (or execute simulations). Their routes
# carry _require_permission dependencies (routes/graph.py, routes/
# simulation.py). Dropping a path from this set alone does NOT enforce auth:
# _is_public only runs inside get_current_user, reached via an auth
# dependency, not by any global middleware.
# ADMIN-AUTH (#100): health / versioning / docs endpoints stay public
"/api/health",
"/api/versions",
"/api-docs",
})
# Paths allowed when no users are configured (setup mode)
SETUP_PATHS = frozenset({
"/setup",
"/docs",
"/redoc",
"/openapi.json",
})
def _is_public(path: str) -> bool:
"""Check whether *path* is a public (no-auth) endpoint."""
if path in PUBLIC_PATHS:
return True
# NOTE: /setup is intentionally NOT made unconditionally public here. It is
# allowed only in the no-users bootstrap branch of get_current_user (via
# SETUP_PATHS); once an admin exists, /setup requires authentication so the
# setup surface is not reachable unauthenticated after initial bootstrap.
# Allow static file sub-paths
if path.startswith("/static/"):
return True
# Allow OAuth login/callback paths
if path.startswith("/auth/"):
return True
# Allow v1 auth paths (OAuth2 login/callback)
if path.startswith("/api/v1/auth/"):
return True
# Allow Stripe webhook
if path == "/api/v1/billing/webhook":
return True
return False
# ---------------------------------------------------------------------------
# FastAPI dependency
# ---------------------------------------------------------------------------
async def get_current_user(
request: Request,
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer_scheme),
) -> UserRow | None:
"""Resolve the current user from Bearer token OR session cookie.
Behaviour:
* Public paths -> returns ``None`` (no auth required).
* If **no users** exist in the DB at all -> returns ``None``
(backward-compatible mode, acts as if auth is disabled).
* Protected paths without valid credentials -> 401.
Authentication order:
1. Bearer token (Authorization header) — existing API clients
2. Session cookie (set by OAuth callback) — Web UI browser sessions
"""
# Public endpoints never require auth
if _is_public(request.url.path):
return None
session_factory = get_session_factory()
async with session_factory() as session:
# Check if any users exist at all
count_result = await session.execute(
select(UserRow.id).limit(1)
)
has_users = count_result.scalar_one_or_none() is not None
if not has_users:
# No users registered yet -> only allow setup and docs endpoints
logger.warning(
"No users configured. Run setup to create admin user."
)
path = request.url.path
if path in SETUP_PATHS or path.startswith("/setup/"):
return None
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="No users configured. Access /setup to create an admin user.",
)
# --- Try session cookie first (Web UI OAuth flow) ---
session_user_id: int | None = None
try:
session_user_id = request.session.get("user_id") # type: ignore[attr-defined]
except (AssertionError, AttributeError):
# SessionMiddleware not installed, or test environment with a fake request
pass
if session_user_id is not None:
result = await session.execute(
select(UserRow).where(UserRow.id == int(session_user_id))
)
session_user = result.scalar_one_or_none()
if session_user is not None:
return session_user
# Users exist -> auth is required for /api/* paths
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing API key or JWT. Provide Authorization: Bearer <token>",
)
token = credentials.credentials
# Try JWT token first (OAuth2 sessions). A single Bearer token is tried
# as a JWT and then as an API key, so a token that is simply *not* a JWT
# (e.g. a raw API key) must fall through rather than error. decode_jwt
# already returns None for an invalid/expired/forged signature (it does
# not raise), so the only thing we guard here is a malformed 'sub'
# claim. We deliberately do NOT swallow unexpected errors (e.g. DB
# failures) — those propagate to _resolve_user and fail closed (deny),
# instead of silently masking them and falling through to API-key auth.
#
# Only treat the token as a JWT when it *looks* like one (three
# dot-separated segments). A raw API key never matches this shape, so we
# skip importing faultray.api.oauth for it entirely — that module raises
# at import time when FAULTRAY_ENV=production without a configured JWT
# secret, and a JWT *configuration/import* failure must not block
# API-key-only deployments. We catch such setup failures and fall
# through to the API-key path rather than 500-ing.
if _looks_like_jwt(token):
jwt_payload = None
try:
from faultray.api.oauth import decode_jwt
jwt_payload = decode_jwt(token)
except Exception:
# JWT subsystem misconfigured/unavailable (e.g. no secret in
# production, missing python-jose). Fall through to API-key auth
# instead of failing the whole request.
logger.warning(
"JWT decode unavailable; falling back to API-key auth.",
exc_info=True,
)
if jwt_payload and "sub" in jwt_payload:
try:
user_id = int(jwt_payload["sub"])
except (ValueError, TypeError):
user_id = None
if user_id is not None:
result = await session.execute(
select(UserRow).where(UserRow.id == user_id)
)
user = result.scalar_one_or_none()
if user is not None:
return user
# Fall back to API key authentication
key_hash = hash_api_key(token)
result = await session.execute(
select(UserRow).where(UserRow.api_key_hash == key_hash)
)
user = result.scalar_one_or_none()
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid API key or JWT token.",
)
return user

Xet Storage Details

Size:
11.5 kB
·
Xet hash:
ffd9b5a330e1079b931d687b0c6c088bf45dc4bfb2f8095edb26734dd7570112

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.