Buckets:

download
raw
37.8 kB
# Copyright (c) 2025-2026 Yutaro Maeda. All rights reserved.
# Licensed under the Apache License 2.0. See LICENSE file for details.
"""Admin, config, health, marketplace, calendar, chat, templates, agents,
supply chain, OAuth, billing, and miscellaneous endpoints."""
from __future__ import annotations
import asyncio
import logging
import os
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from faultray.api.routes._shared import (
get_graph,
get_model_path,
templates,
)
from faultray.api.routes._shared import _require_permission
logger = logging.getLogger(__name__)
router = APIRouter()
# Serializes first-admin creation within this process. The in-transaction
# has_users recheck below is not, on its own, atomic across concurrent
# requests: with SQLite (and without a portable SELECT ... FOR UPDATE / advisory
# lock) two concurrent first-run POSTs using *different* emails could each read
# an empty users table and each insert an admin row, since the unique-email
# constraint cannot catch distinct emails. This asyncio.Lock closes the
# realistic window — multiple coroutines interleaving on one event loop — so
# only one admin is created per process. Residual risk: separate processes
# (multi-worker deployments) do not share this lock; the unique-email backstop
# and the FAULTRAY_SETUP_TOKEN gate remain the cross-process mitigations.
_first_admin_lock = asyncio.Lock()
# ---------------------------------------------------------------------------
# ADMIN-AUTH (#100) — shared auth dependencies
#
# view_dashboard : viewer+ (HTML pages + read-only JSON listings)
# run_simulation : editor+ (POST/DELETE that install, schedule, chat, etc.)
#
# Routes left intentionally public (see auth.py PUBLIC_PATHS / _is_public):
# /api/health, /api/versions, /api-docs, /setup, /auth/*
# ---------------------------------------------------------------------------
_READ_ACCESS = Depends(_require_permission("view_dashboard"))
_WRITE_ACCESS = Depends(_require_permission("run_simulation"))
# ---------------------------------------------------------------------------
# Health, Versioning & API docs
# ---------------------------------------------------------------------------
@router.get("/api/health", response_class=JSONResponse)
async def health_check():
"""Return API health status."""
from faultray.api.api_versioning import health_checker
graph = get_graph()
component_count = len(graph.components) if graph else 0
return JSONResponse(health_checker.check(component_count))
@router.get("/api/versions", response_class=JSONResponse)
async def api_versions():
"""List available API versions."""
from faultray.api.api_versioning import list_versions
return JSONResponse({"versions": list_versions()})
@router.get("/api-docs", response_class=HTMLResponse)
async def api_docs_page(request: Request):
"""Interactive API documentation."""
return templates.TemplateResponse(request, "api_docs.html", {})
@router.get("/settings", response_class=HTMLResponse)
async def settings_page(request: Request, _user=_READ_ACCESS):
return templates.TemplateResponse(request, "settings.html", {
"has_data": True,
})
# ---------------------------------------------------------------------------
# Initial Setup — create the first admin user (C1 fix)
# ---------------------------------------------------------------------------
@router.get("/setup", response_class=HTMLResponse)
async def setup_page(request: Request):
"""Show initial setup form when no users exist; redirect to / otherwise."""
from faultray.api.database import UserRow, get_session_factory
from sqlalchemy import select
session_factory = get_session_factory()
async with session_factory() as session:
result = await session.execute(select(UserRow.id).limit(1))
has_users = result.scalar_one_or_none() is not None
if has_users:
return RedirectResponse(url="/", status_code=302)
return templates.TemplateResponse(request, "setup.html", {
"success": False,
"error": None,
})
@router.post("/setup", response_class=HTMLResponse)
async def setup_create_admin(request: Request):
"""Create the first admin user; redirect to setup GET with error on failure."""
from faultray.api.auth import generate_api_key, hash_api_key
from faultray.api.database import UserRow, get_session_factory
from sqlalchemy import select
# Block if users already exist
session_factory = get_session_factory()
async with session_factory() as session:
result = await session.execute(select(UserRow.id).limit(1))
has_users = result.scalar_one_or_none() is not None
if has_users:
return RedirectResponse(url="/", status_code=302)
form = await request.form()
# Optional bootstrap gate: when FAULTRAY_SETUP_TOKEN is configured, the very
# first-admin creation must present a matching token (form field or header).
# This closes the "race to takeover" on a fresh, internet-reachable instance
# (#140) while leaving the default first-run UX unchanged when unset.
import os as _os
setup_token = _os.environ.get("FAULTRAY_SETUP_TOKEN", "")
if setup_token:
import hmac as _hmac
provided = str(
form.get("setup_token") or request.headers.get("X-Setup-Token", "")
)
if not _hmac.compare_digest(provided, setup_token):
logger.warning("Rejected /setup attempt: missing/invalid setup token")
return templates.TemplateResponse(
request,
"setup.html",
{
"success": False,
"error": "A valid setup token is required to create the first admin.",
},
status_code=403,
)
name = str(form.get("name", "")).strip()
email = str(form.get("email", "")).strip()
if not name or not email:
return templates.TemplateResponse(
request,
"setup.html",
{
"success": False,
"error": "Name and email are required.",
"form_name": name,
"form_email": email,
},
status_code=422,
)
api_key = generate_api_key()
from sqlalchemy.exc import IntegrityError
try:
# Serialize the recheck-through-commit critical section so concurrent
# coroutines cannot both observe an empty users table and both insert an
# admin (the unique-email constraint does not catch distinct emails).
async with _first_admin_lock:
async with session_factory() as session:
# SEC (TOCTOU): re-check inside the SAME transaction as the
# insert (belt-and-braces with the lock above, and the only
# guard across processes that don't share the lock). The
# unique-email constraint is the final backstop: a colliding
# concurrent insert raises IntegrityError, treated as "setup
# already completed".
recheck = await session.execute(select(UserRow.id).limit(1))
if recheck.scalar_one_or_none() is not None:
return RedirectResponse(url="/", status_code=302)
user = UserRow(
email=email,
name=name,
api_key_hash=hash_api_key(api_key),
role="admin",
)
session.add(user)
await session.commit()
await session.refresh(user)
logger.info("Setup complete: admin user created (id=%s, email=%s)", user.id, email)
return templates.TemplateResponse(
request,
"setup.html",
{
"success": True,
"api_key": api_key,
},
)
except IntegrityError:
# A concurrent request won the race (duplicate email / first admin).
logger.warning("Setup race detected: admin already created concurrently")
return templates.TemplateResponse(
request,
"setup.html",
{
"success": False,
"error": "Setup has already been completed.",
"form_name": name,
"form_email": email,
},
status_code=409,
)
except Exception as exc:
# Log the detail server-side; never echo the raw exception to the client
# — a DB error here embeds the failing SQL and its parameters (which
# include the new user's api_key_hash) and would leak schema internals.
logger.warning("Setup failed: %s", exc)
return templates.TemplateResponse(
request,
"setup.html",
{
"success": False,
"error": "Failed to create user. Please check your details and try again.",
"form_name": name,
"form_email": email,
},
status_code=500,
)
# ---------------------------------------------------------------------------
# OAuth2 SSO
# ---------------------------------------------------------------------------
@router.get("/auth/login/{provider}")
async def oauth_login(provider: str):
"""Redirect to the OAuth provider's authorization page."""
import hashlib
import hmac
import secrets
from faultray.api.oauth import OAuthConfig, generate_oauth_url
config = OAuthConfig.from_env(provider)
if config is None:
return JSONResponse(
{"error": f"OAuth provider '{provider}' is not configured"},
status_code=400,
)
# Generate a random state token and sign it with the client secret
# so we can verify it in the callback without server-side session storage.
nonce = secrets.token_urlsafe(32)
signature = hmac.new(
config.client_secret.encode(), nonce.encode(), hashlib.sha256,
).hexdigest()
state = f"{nonce}.{signature}"
url = generate_oauth_url(config, state=state)
_is_https = os.environ.get("FAULTRAY_HTTPS", "").lower() in ("1", "true", "yes")
response = RedirectResponse(url=url)
response.set_cookie(
key="oauth_state",
value=state,
httponly=True,
samesite="lax",
max_age=600, # 10 minutes
secure=_is_https,
)
return response
@router.get("/auth/callback")
async def oauth_callback(request: Request, code: str = "", state: str = "", provider: str = "github"):
"""Handle the OAuth callback."""
import hashlib
import hmac
from faultray.api.oauth import OAuthConfig, exchange_code_for_token, get_user_profile
config = OAuthConfig.from_env(provider)
if config is None:
return JSONResponse(
{"error": f"OAuth provider '{provider}' is not configured"},
status_code=400,
)
if not code:
return JSONResponse({"error": "Missing authorization code"}, status_code=400)
# --- CSRF validation: verify the state parameter ---
stored_state = request.cookies.get("oauth_state", "")
if not state or not stored_state or state != stored_state:
logger.warning("OAuth CSRF check failed: state mismatch")
return JSONResponse({"error": "Invalid OAuth state parameter (CSRF check failed)"}, status_code=400)
# Verify the HMAC signature embedded in the state token
parts = state.split(".", 1)
if len(parts) != 2:
return JSONResponse({"error": "Malformed OAuth state token"}, status_code=400)
nonce, signature = parts
expected_sig = hmac.new(
config.client_secret.encode(), nonce.encode(), hashlib.sha256,
).hexdigest()
if not hmac.compare_digest(signature, expected_sig):
logger.warning("OAuth CSRF check failed: HMAC signature mismatch")
return JSONResponse({"error": "Invalid OAuth state signature"}, status_code=400)
try:
access_token = await exchange_code_for_token(config, code)
profile = await get_user_profile(config, access_token)
except Exception as exc:
# Detail to logs only: exc here can embed the provider's raw token-
# endpoint response, which must not be reflected back to the caller.
logger.warning("OAuth callback failed: %s", exc)
return JSONResponse({"error": "OAuth exchange failed"}, status_code=502)
try:
from faultray.api.auth import generate_api_key, hash_api_key
from faultray.api.database import UserRow, get_session_factory
from sqlalchemy import select
oauth_id = str(profile.get("id") or "").strip()
email = profile.get("email")
email_verified = bool(profile.get("email_verified"))
session_factory = get_session_factory()
async with session_factory() as session:
# SEC: match by the STABLE provider identity (provider, oauth_id)
# first — it can't be spoofed by asserting another user's email.
user = None
if oauth_id:
stmt = select(UserRow).where(
UserRow.oauth_provider == config.provider,
UserRow.oauth_id == oauth_id,
)
user = (await session.execute(stmt)).scalar_one_or_none()
if user is None:
# Fall back to email ONLY when the provider says it is verified, to
# link a pre-existing account on first OAuth sign-in. Without the
# verified gate, anyone who could get a provider to assert a
# victim's email could take over the account (and previously also
# rotate its API key).
email_user = None
if email and email_verified:
stmt = select(UserRow).where(UserRow.email == email)
email_user = (await session.execute(stmt)).scalar_one_or_none()
if email_user is not None:
if email_user.oauth_id and email_user.oauth_id != oauth_id:
logger.warning(
"OAuth link refused: email already bound to a different identity"
)
return JSONResponse(
{"error": "Account already linked to a different identity"},
status_code=409,
)
# Link the OAuth identity; do NOT rotate the API key.
user = email_user
user.oauth_provider = config.provider
if oauth_id:
user.oauth_id = oauth_id
user.name = profile.get("name") or user.name
else:
# Brand-new account. SEC: require a stable provider id AND a
# provider-verified, non-empty email before minting an
# account. Creating rows with an unverified or null email
# allows account-confusion/duplicate-email attacks and rows
# that bypass uniqueness assumptions.
if not oauth_id or not email or not email_verified:
logger.warning(
"OAuth account creation refused: missing oauth_id or "
"unverified/empty email (provider=%s)", config.provider,
)
return JSONResponse(
{"error": "A verified email is required to sign in."},
status_code=400,
)
api_key = generate_api_key()
user = UserRow(
email=email,
name=profile.get("name"),
api_key_hash=hash_api_key(api_key),
oauth_provider=config.provider,
oauth_id=oauth_id,
)
session.add(user)
else:
# Existing account matched by stable identity: refresh name + log
# in. Do NOT rotate api_key_hash on login — rotating it on every
# OAuth sign-in both broke the user's key and was the lever that
# made takeover impactful.
user.name = profile.get("name") or user.name
await session.commit()
await session.refresh(user)
# Establish session cookie for Web UI (C3 fix)
request.session["user_id"] = user.id # type: ignore[index]
request.session["user_email"] = user.email # type: ignore[index]
# Redirect to dashboard — browser will follow and carry the session cookie
from fastapi.responses import RedirectResponse as _RedirectResponse
response = _RedirectResponse(url="/", status_code=302)
return response
except Exception as exc:
# Detail to logs only: a DB error embeds the INSERT's SQL parameters
# (including the user's api_key_hash) — never echo it to the client.
logger.warning("OAuth user creation failed: %s", exc)
return JSONResponse({"error": "User creation failed"}, status_code=500)
# ---------------------------------------------------------------------------
# Marketplace
# ---------------------------------------------------------------------------
@router.get("/marketplace", response_class=HTMLResponse)
async def marketplace_page(request: Request, _user=_READ_ACCESS):
"""Marketplace HTML page."""
graph = get_graph()
has_data = bool(graph and graph.components)
return templates.TemplateResponse(request, "marketplace.html", {
"has_data": has_data,
"active_page": "marketplace",
})
@router.get("/api/marketplace/packages", response_class=JSONResponse)
async def list_marketplace_packages(
category: str | None = None,
provider: str | None = None,
_user=_READ_ACCESS,
):
"""List all marketplace packages."""
from faultray.marketplace import ScenarioMarketplace
mp = ScenarioMarketplace()
packages = mp.list_packages(category=category, provider=provider)
return JSONResponse({"packages": [p.to_dict() for p in packages]})
@router.get("/api/marketplace/packages/{package_id}", response_class=JSONResponse)
async def get_marketplace_package(package_id: str, _user=_READ_ACCESS):
"""Get a specific marketplace package by ID."""
from faultray.marketplace import ScenarioMarketplace
mp = ScenarioMarketplace()
try:
pkg = mp.get_package(package_id)
except KeyError:
raise HTTPException(status_code=404, detail=f"Package not found: {package_id}")
return JSONResponse(pkg.to_dict())
@router.post("/api/marketplace/install/{package_id}", response_class=JSONResponse)
async def install_marketplace_package(package_id: str, _user=_WRITE_ACCESS):
"""Install a marketplace package."""
from faultray.marketplace import ScenarioMarketplace
mp = ScenarioMarketplace()
try:
scenarios = mp.install_package(package_id)
except KeyError:
raise HTTPException(status_code=404, detail=f"Package not found: {package_id}")
return JSONResponse({
"installed": len(scenarios),
"package_id": package_id,
"scenarios": [
{
"id": s.id,
"name": s.name,
"description": s.description,
"fault_count": len(s.faults),
}
for s in scenarios
],
})
@router.get("/api/marketplace/featured", response_class=JSONResponse)
async def get_featured_packages(_user=_READ_ACCESS):
"""Get featured marketplace packages."""
from faultray.marketplace import ScenarioMarketplace
mp = ScenarioMarketplace()
featured = mp.get_featured()
return JSONResponse({"packages": [p.to_dict() for p in featured]})
@router.get("/api/marketplace/categories", response_class=JSONResponse)
async def get_marketplace_categories(_user=_READ_ACCESS):
"""Get all marketplace categories."""
from faultray.marketplace import ScenarioMarketplace
mp = ScenarioMarketplace()
categories = mp.get_categories()
return JSONResponse({"categories": [c.to_dict() for c in categories]})
@router.get("/api/marketplace/popular", response_class=JSONResponse)
async def get_popular_packages(_user=_READ_ACCESS):
"""Get most popular marketplace packages."""
from faultray.marketplace import ScenarioMarketplace
mp = ScenarioMarketplace()
popular = mp.get_popular()
return JSONResponse({"packages": [p.to_dict() for p in popular]})
@router.get("/api/marketplace/search", response_class=JSONResponse)
async def search_marketplace_packages(q: str = "", _user=_READ_ACCESS):
"""Search marketplace packages by query."""
from faultray.marketplace import ScenarioMarketplace
mp = ScenarioMarketplace()
results = mp.search(q)
return JSONResponse({"packages": [p.to_dict() for p in results]})
# ---------------------------------------------------------------------------
# Chaos Calendar
# ---------------------------------------------------------------------------
@router.get("/calendar", response_class=HTMLResponse)
async def calendar_page(request: Request, _user=_READ_ACCESS):
"""Chaos Calendar page."""
graph = get_graph()
return templates.TemplateResponse(request, "calendar.html", {
"has_data": len(graph.components) > 0,
"active_page": "calendar",
})
@router.get("/api/calendar", response_class=JSONResponse)
async def api_calendar_view(_user=_READ_ACCESS):
"""Return calendar view JSON."""
from faultray.scheduler.chaos_calendar import ChaosCalendar
cal = ChaosCalendar()
view = cal.get_calendar_view()
return JSONResponse({
"experiments": [exp.to_dict() for exp in view.experiments],
"upcoming": [exp.to_dict() for exp in view.upcoming],
"overdue": [exp.to_dict() for exp in view.overdue],
"history": [exp.to_dict() for exp in view.history],
"blackout_windows": [bw.to_dict() for bw in view.blackout_windows],
"coverage_score": view.coverage_score,
"experiment_frequency": view.experiment_frequency,
"streak": view.streak,
})
@router.post("/api/calendar/schedule", response_class=JSONResponse)
async def api_calendar_schedule(request: Request, _user=_WRITE_ACCESS):
"""Schedule a new chaos experiment."""
from faultray.scheduler.chaos_calendar import ChaosCalendar, ChaosExperiment
body = await request.json()
cal = ChaosCalendar()
experiment = ChaosExperiment(
id="",
name=body.get("name", "Untitled Experiment"),
description=body.get("description", ""),
scenario_ids=body.get("scenario_ids", []),
target_components=body.get("target_components", []),
owner=body.get("owner", ""),
tags=body.get("tags", []),
infrastructure_file=body.get("infrastructure_file", ""),
duration_estimate=body.get("duration_estimate", "30m"),
notes=body.get("notes", ""),
)
if "scheduled_time" in body:
from datetime import datetime
experiment.scheduled_time = datetime.fromisoformat(body["scheduled_time"])
if "recurrence" in body:
from faultray.scheduler.chaos_calendar import RecurrencePattern
experiment.recurrence = RecurrencePattern(body["recurrence"])
eid = cal.schedule(experiment)
return JSONResponse({"experiment_id": eid, "status": "scheduled"})
@router.delete("/api/calendar/{experiment_id}", response_class=JSONResponse)
async def api_calendar_cancel(experiment_id: str, _user=_WRITE_ACCESS):
"""Cancel a scheduled experiment."""
from faultray.scheduler.chaos_calendar import ChaosCalendar
cal = ChaosCalendar()
success = cal.cancel(experiment_id)
if not success:
raise HTTPException(status_code=404, detail=f"Experiment '{experiment_id}' not found")
return JSONResponse({"experiment_id": experiment_id, "status": "cancelled"})
@router.post("/api/calendar/auto-schedule", response_class=JSONResponse)
async def api_calendar_auto_schedule(_user=_WRITE_ACCESS):
"""Auto-schedule experiments for critical components."""
from faultray.scheduler.chaos_calendar import ChaosCalendar
graph = get_graph()
if not graph.components:
raise HTTPException(status_code=400, detail="No infrastructure loaded. Visit /demo first.")
cal = ChaosCalendar()
experiments = cal.auto_schedule(graph)
return JSONResponse({
"scheduled": len(experiments),
"experiments": [exp.to_dict() for exp in experiments],
})
@router.get("/api/calendar/ical")
async def api_calendar_ical(_user=_READ_ACCESS):
"""Download iCalendar (.ics) file."""
from faultray.scheduler.chaos_calendar import ChaosCalendar
cal = ChaosCalendar()
ical = cal.export_ical()
return Response(
content=ical,
media_type="text/calendar",
headers={"Content-Disposition": "attachment; filename=chaos-calendar.ics"},
)
# ---------------------------------------------------------------------------
# Chat
# ---------------------------------------------------------------------------
@router.get("/chat", response_class=HTMLResponse)
async def chat_page(request: Request, _user=_READ_ACCESS):
"""Chat interface page."""
from faultray.api.chat_engine import ChatEngine
graph = get_graph()
engine = ChatEngine()
suggestions = engine.get_suggestions(graph) if graph.components else [
"Load the demo infrastructure first",
]
return templates.TemplateResponse(request, "chat.html", {
"has_data": len(graph.components) > 0,
"suggestions": suggestions,
"active_page": "chat",
})
@router.post("/api/chat", response_class=JSONResponse)
async def chat_api(request: Request, _user=_WRITE_ACCESS):
"""Process a chat message about infrastructure."""
from faultray.api.chat_engine import ChatEngine
body = await request.json()
question = (body.get("question") or body.get("message") or "").strip()
if not question:
return JSONResponse(
{"error": "No question provided"},
status_code=400,
)
graph = get_graph()
engine = ChatEngine()
response = engine.ask(question, graph)
return JSONResponse({
"text": response.text,
"response": response.text,
"intent": response.intent.value,
"data": response.data,
"suggestions": response.suggestions,
"visualization": response.visualization,
})
# ---------------------------------------------------------------------------
# Slack Bot
# ---------------------------------------------------------------------------
def _verify_slack_signature(request: Request, body: bytes) -> bool:
"""Verify Slack request signature per https://api.slack.com/authentication/verifying-requests-from-slack.
Returns True if:
- SLACK_SIGNING_SECRET env var is set AND signature is valid AND timestamp is within 5 minutes
- SLACK_SIGNING_SECRET is NOT set AND FAULTRAY_ALLOW_UNSIGNED_SLACK=1
AND FAULTRAY_ENV != production (dev-only escape hatch)
Returns False otherwise (rejecting the request).
"""
import hashlib
import hmac
import time as _time
signing_secret = os.environ.get("SLACK_SIGNING_SECRET", "")
if not signing_secret:
# Dev escape hatch — explicitly disabled when FAULTRAY_ENV indicates
# production. This closes the self-review finding that a stray
# FAULTRAY_ALLOW_UNSIGNED_SLACK=1 in prod would silently open the
# endpoint to unauthenticated callers (#100 post-review).
env = os.environ.get("FAULTRAY_ENV", "").lower()
if env in ("production", "prod", "live"):
logger.warning(
"Slack: SLACK_SIGNING_SECRET missing in production — rejecting"
)
return False
return os.environ.get("FAULTRAY_ALLOW_UNSIGNED_SLACK", "").lower() in (
"1", "true", "yes"
)
ts = request.headers.get("x-slack-request-timestamp", "")
sig = request.headers.get("x-slack-signature", "")
if not ts or not sig:
return False
# Reject replay attacks (>5 min old)
try:
if abs(int(_time.time()) - int(ts)) > 60 * 5:
return False
except ValueError:
return False
basestring = b"v0:" + ts.encode() + b":" + body
expected = "v0=" + hmac.new(
signing_secret.encode(), basestring, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, sig)
@router.post("/api/slack/commands", response_class=JSONResponse)
async def slack_command_handler(request: Request):
"""Handle Slack slash commands.
Public endpoint (Slack has no Bearer token) but authenticated via
Slack signing-secret HMAC verification (ADMIN-AUTH #100).
"""
raw_body = await request.body()
if not _verify_slack_signature(request, raw_body):
logger.warning("Slack command rejected: invalid or missing signature")
return JSONResponse(
{"error": "Invalid Slack signature"}, status_code=401
)
try:
# Parse form from raw body bytes (body already read for signature verify).
from urllib.parse import parse_qs
try:
parsed = parse_qs(raw_body.decode(errors="replace"))
text = (parsed.get("text", ["help"]) or ["help"])[0]
user_id = (parsed.get("user_id", [""]) or [""])[0]
channel_id = (parsed.get("channel_id", [""]) or [""])[0]
except Exception:
import json as _json
try:
jbody = _json.loads(raw_body.decode(errors="replace") or "{}")
except Exception:
jbody = {}
text = jbody.get("text", "help")
user_id = jbody.get("user_id", "")
channel_id = jbody.get("channel_id", "")
from faultray.integrations.slack_bot import FaultRaySlackBot, parse_slack_command
model_path = get_model_path()
bot = FaultRaySlackBot(model_path=model_path)
command = parse_slack_command(str(text), user_id=str(user_id), channel_id=str(channel_id))
response = bot.handle_command(command)
return JSONResponse(response.to_dict())
except Exception as exc:
# Detail to logs only (full stack via exc_info); do not echo the raw
# exception into the Slack workspace response.
logger.error("Slack command handler error: %s", exc, exc_info=True)
return JSONResponse(
{"text": "Internal error. Please try again later.", "response_type": "ephemeral"},
status_code=500,
)
# ---------------------------------------------------------------------------
# Template Gallery
# ---------------------------------------------------------------------------
@router.get("/templates", response_class=HTMLResponse)
async def templates_page(request: Request, category: str | None = None, _user=_READ_ACCESS):
"""Render the Template Gallery page."""
from dataclasses import asdict
from faultray.templates.gallery import TemplateGallery, TemplateCategory
gallery = TemplateGallery()
gallery_templates = gallery.list_templates(category=category)
categories = [c.value for c in TemplateCategory]
template_data = [asdict(t) for t in gallery_templates]
for td in template_data:
td["category_value"] = td["category"]
return templates.TemplateResponse(request, "gallery.html", {
"has_data": True,
"gallery_templates": template_data,
"categories": categories,
"active_category": category,
})
@router.get("/api/templates", response_class=JSONResponse)
async def api_list_templates(category: str | None = None, _user=_READ_ACCESS):
"""List all gallery templates as JSON."""
from dataclasses import asdict
from faultray.templates.gallery import TemplateGallery
gallery = TemplateGallery()
gallery_templates = gallery.list_templates(category=category)
return JSONResponse([asdict(t) for t in gallery_templates])
@router.get("/api/templates/{template_id}", response_class=JSONResponse)
async def api_get_template(template_id: str, _user=_READ_ACCESS):
"""Get a specific template by ID."""
from dataclasses import asdict
from faultray.templates.gallery import TemplateGallery
gallery = TemplateGallery()
try:
t = gallery.get_template(template_id)
except KeyError:
raise HTTPException(status_code=404, detail=f"Template '{template_id}' not found")
return JSONResponse(asdict(t))
# ---------------------------------------------------------------------------
# Agent Assessment
# ---------------------------------------------------------------------------
@router.get("/agents", response_class=HTMLResponse)
async def agents_page(request: Request, _user=_READ_ACCESS):
"""AI Agent assessment page."""
graph = get_graph()
has_data = len(graph.components) > 0
assessment_data = None
monitoring_data = None
scenarios_data = None
if has_data:
import dataclasses
from faultray.simulator.adoption_engine import AdoptionEngine
from faultray.simulator.agent_monitor import AgentMonitorEngine
from faultray.simulator.agent_scenarios import generate_agent_scenarios
engine = AdoptionEngine(graph)
reports = engine.assess_all_agents()
assessment_data = [dataclasses.asdict(r) for r in reports]
monitor = AgentMonitorEngine(graph)
plan = monitor.generate_monitoring_plan()
monitoring_data = dataclasses.asdict(plan)
scenarios = generate_agent_scenarios(graph)
scenarios_data = [s.model_dump() for s in scenarios]
return templates.TemplateResponse(request, "agents.html", {
"has_data": has_data,
"active_page": "agents",
"assessments": assessment_data,
"monitoring": monitoring_data,
"scenarios": scenarios_data,
})
@router.post("/api/v1/agent/assess", response_class=JSONResponse)
async def agent_assess(request: Request, user=Depends(_require_permission("view_results"))):
"""Run agent adoption risk assessment."""
import dataclasses
graph = get_graph()
if not graph.components:
return JSONResponse(
{"error": "No infrastructure loaded. Visit /demo first."},
status_code=400,
)
from faultray.simulator.adoption_engine import AdoptionEngine
engine = AdoptionEngine(graph)
reports = engine.assess_all_agents()
return JSONResponse({"assessments": [dataclasses.asdict(r) for r in reports]})
@router.post("/api/v1/agent/monitor", response_class=JSONResponse)
async def agent_monitor(request: Request, user=Depends(_require_permission("view_results"))):
"""Generate agent monitoring plan."""
import dataclasses
graph = get_graph()
if not graph.components:
return JSONResponse(
{"error": "No infrastructure loaded. Visit /demo first."},
status_code=400,
)
from faultray.simulator.agent_monitor import AgentMonitorEngine
monitor = AgentMonitorEngine(graph)
plan = monitor.generate_monitoring_plan()
return JSONResponse(dataclasses.asdict(plan))
@router.post("/api/v1/agent/scenarios", response_class=JSONResponse)
async def agent_scenarios(request: Request, user=Depends(_require_permission("view_results"))):
"""List agent-specific scenarios."""
graph = get_graph()
if not graph.components:
return JSONResponse(
{"error": "No infrastructure loaded. Visit /demo first."},
status_code=400,
)
from faultray.simulator.agent_scenarios import generate_agent_scenarios
scenarios = generate_agent_scenarios(graph)
return JSONResponse({"scenarios": [s.model_dump() for s in scenarios]})
# ---------------------------------------------------------------------------
# Supply Chain Analysis
# ---------------------------------------------------------------------------
@router.get("/supply-chain", response_class=HTMLResponse)
async def supply_chain_page(request: Request, _user=_READ_ACCESS):
"""Supply chain attack analysis page."""
graph = get_graph()
has_data = len(graph.components) > 0
report_data = None
if has_data:
import dataclasses
from faultray.simulator.supply_chain_cascade import SupplyChainCascadeEngine
engine = SupplyChainCascadeEngine(graph)
report = engine.analyze_all_packages()
report_data = dataclasses.asdict(report)
return templates.TemplateResponse(request, "supply_chain.html", {
"has_data": has_data,
"active_page": "supply_chain",
"report": report_data,
})
@router.post("/api/v1/supply-chain/analyze", response_class=JSONResponse)
async def supply_chain_analyze(request: Request, user=Depends(_require_permission("view_results"))):
"""Run supply chain attack analysis."""
import dataclasses
graph = get_graph()
if not graph.components:
return JSONResponse(
{"error": "No infrastructure loaded. Visit /demo first."},
status_code=400,
)
from faultray.simulator.supply_chain_cascade import SupplyChainCascadeEngine
engine = SupplyChainCascadeEngine(graph)
report = engine.analyze_all_packages()
return JSONResponse(dataclasses.asdict(report))

Xet Storage Details

Size:
37.8 kB
·
Xet hash:
48d3d1674f5b355edc2bdcc6ff1d3565a1a1636f547d2f8744e4575a3e7e70b8

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