Buckets:

download
raw
10.7 kB
#!/usr/bin/env python3
"""
Security check script to verify FastAPI routes are properly secured with authentication.
Analyzes routes in FastAPI backends to identify endpoints missing authentication dependencies.
"""
import inspect
import os
import sys
from pathlib import Path
from typing import Dict, List, Set, Optional
import importlib
import asyncio
def setup_backend_environment(backend_dir: Path) -> Path:
"""Setup environment to import the FastAPI app."""
config_dir = backend_dir / "config"
# --- Flexible App Directory Discovery ---
# We check for these two paths in order
app_dir_options = [
backend_dir / "agentic_backend",
backend_dir / "knowledge_flow_backend",
backend_dir / "control_plane_backend",
]
app_dir = None
for current_app_dir in app_dir_options:
if current_app_dir.exists() and (current_app_dir / "main.py").exists():
app_dir = current_app_dir
print(f"โœ… Found application main code in: {app_dir}")
break
# If neither structure is found, raise the final error
if not app_dir:
checked = ", ".join(str(p) for p in app_dir_options)
raise FileNotFoundError(
f"Could not find app/main.py in expected locations within {backend_dir}. "
f"Checked: {checked}"
)
# --- End Flexible App Directory Discovery ---
# Validate backend directory structure
if not app_dir.exists() or not (app_dir / "main.py").exists():
raise FileNotFoundError(f"Could not find main.py in {backend_dir}")
if not config_dir.exists() or not (config_dir / "configuration.yaml").exists():
raise FileNotFoundError(f"Could not find config/configuration.yaml in {backend_dir}")
# Add the app directory to Python path
sys.path.insert(0, str(app_dir))
# Set required environment variables.
# This is static route analysis: the app is imported but never connects to any
# backend, so dummy secrets are enough to satisfy the fail-fast config validators
# (OpenSearch / Postgres passwords) that otherwise refuse to start.
os.environ.setdefault("ENV_FILE", str(config_dir / ".env"))
os.environ.setdefault("CONFIG_FILE", str(config_dir / "configuration.yaml"))
os.environ.setdefault("OPENAI_API_KEY", "sk-dummy-key-for-static-analysis")
os.environ.setdefault("OPENSEARCH_PASSWORD", "dummy-password-for-static-analysis") # pragma: allowlist secret
os.environ.setdefault("FRED_POSTGRES_PASSWORD", "dummy-password-for-static-analysis") # pragma: allowlist secret
return app_dir
def shutdown_app_context(app_dir: Path) -> None:
"""
Best-effort shutdown of ApplicationContext resources (thread pools, executors)
to avoid hanging processes after static inspection.
"""
try:
module_name = f"{app_dir.name}.application_context"
ctx_module = sys.modules.get(module_name)
if ctx_module is None:
ctx_module = importlib.import_module(module_name)
get_ctx = getattr(ctx_module, "get_app_context", None)
if get_ctx:
ctx = get_ctx()
if hasattr(ctx, "shutdown"):
try:
asyncio.run(ctx.shutdown())
except RuntimeError:
# Event loop already running; ignore
pass
elif hasattr(ctx, "shutdown_io_executor"):
ctx.shutdown_io_executor()
except Exception:
# Best-effort cleanup only; a failed shutdown must not fail the security check.
pass
def get_route_function_info(app, path: str, method: str) -> Optional[tuple[str, int]]:
"""Get the file and line number for a route's handler function."""
try:
# Find the route in FastAPI app
for route in app.routes:
if hasattr(route, 'path') and hasattr(route, 'methods'):
if route.path == path and method.upper() in route.methods:
# Get the endpoint function
endpoint = route.endpoint
if endpoint:
# Get source file and line number
source_file = inspect.getfile(endpoint)
line_number = inspect.getsourcelines(endpoint)[1]
# Convert to relative path from backend directory
backend_dir = Path.cwd()
try:
rel_path = Path(source_file).relative_to(backend_dir)
return str(rel_path), line_number
except ValueError:
# If we can't make it relative, return absolute path
return source_file, line_number
except Exception:
# Route introspection is best-effort; fall through to "unknown" below.
pass
return None
def has_auth_dependency(app, path: str, method: str) -> bool:
"""Check if a route has authentication dependency by inspecting the function signature."""
try:
for route in app.routes:
if hasattr(route, 'path') and hasattr(route, 'methods'):
if route.path == path and method.upper() in route.methods:
# Check if route has security dependencies
if hasattr(route, 'dependencies') and route.dependencies:
# Look for get_current_user in dependencies
for dep in route.dependencies:
if hasattr(dep, 'dependency'):
dep_str = str(dep.dependency)
if 'get_current_user' in dep_str:
return True
# Also check function signature for auth parameters
if route.endpoint:
sig = inspect.signature(route.endpoint)
for param_name, param in sig.parameters.items():
if param.annotation and 'KeycloakUser' in str(param.annotation):
return True
if param.default and 'get_current_user' in str(param.default):
return True
except Exception:
# Signature/dependency introspection is best-effort; treat failures as "no auth found" below.
pass
return False
def get_exempt_routes() -> Set[str]:
"""Return set of routes that are exempt from authentication requirements."""
return {
# FastAPI auto routes
"/docs",
"/docs/oauth2-redirect",
"/redoc",
"/openapi.json",
# Kubernetes monitoring routes
"/healthz",
"/ready",
# Agentic specific routes
"/config/frontend_settings",
"/schemas/echo",
# Prometheus scraping route
"/metrics",
# Public pre-auth frontend config (user_auth from security.user
"/frontend/config",
}
def check_route_security(backend_dir: Path) -> tuple[bool, List[Dict]]:
"""
Check route security for a backend by introspecting the FastAPI app.
Returns:
tuple: (is_secure, unsecured_routes)
"""
app_dir: Optional[Path] = None
try:
app_dir = setup_backend_environment(backend_dir)
# Import and create the FastAPI app
from main import create_app
app = create_app()
exempt_routes = get_exempt_routes()
unsecured_routes = []
# Inspect all routes in the app
for route in app.routes:
if hasattr(route, 'path') and hasattr(route, 'methods'):
for method in route.methods:
if method.upper() in ["GET", "POST", "PUT", "DELETE", "PATCH"]:
path = route.path
# Skip exempt routes
if any(path.endswith(exempt) or path == exempt for exempt in exempt_routes):
continue
# Check if route is secured
if not has_auth_dependency(app, path, method):
# Get file and line information
file_info = get_route_function_info(app, path, method)
route_dict = {
"path": path,
"method": method.upper(),
"summary": getattr(route, 'summary', '') or '',
"tags": getattr(route, 'tags', []) or []
}
if file_info:
route_dict["controller_file"], route_dict["line_number"] = file_info
else:
route_dict["controller_file"] = None
route_dict["line_number"] = None
unsecured_routes.append(route_dict)
return len(unsecured_routes) == 0, unsecured_routes
except Exception as e:
print(f"โŒ Error checking route security for {backend_dir.name}: {e}")
import traceback
traceback.print_exc()
return False, []
finally:
if app_dir:
shutdown_app_context(app_dir)
def main():
"""Main entry point for route security check."""
backend_dir = Path.cwd()
backend_name = backend_dir.name
print(f"๐Ÿ”’ Checking route security for {backend_name}...")
is_secure, unsecured_routes = check_route_security(backend_dir)
if is_secure:
print(f"โœ… All routes in {backend_name} are properly secured!")
return 0
else:
print(f"โŒ Found {len(unsecured_routes)} unsecured route(s) in {backend_name}:")
for route in unsecured_routes:
print(f" - {route['method']} {route['path']}")
if route.get('summary'):
print(f" Summary: {route['summary']}")
if route.get('controller_file') and route.get('line_number'):
print(f" File: {route['controller_file']}:{route['line_number']}")
else:
print(" File: <location not found>")
print("")
print("\nTo secure these routes, add: user: KeycloakUser = Depends(get_current_user)")
return 1
if __name__ == "__main__":
sys.exit(main())

Xet Storage Details

Size:
10.7 kB
ยท
Xet hash:
97be0c7b3f7f9c8108b313e0782b4fd27c6669ee3b1e8da7f4ecd9d248bb9566

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