Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(security): wire API key auth middleware into Explorer app

Sunila169cf3fb9b8
diff --git a/semantica/explorer/app.py b/semantica/explorer/app.py
index e9f1d075..3d175ed2 100644
--- a/semantica/explorer/app.py
+++ b/semantica/explorer/app.py
@@ -8,16 +8,16 @@ from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
-from fastapi import Depends, FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
+from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from .. import __version__
from ..context.context_graph import ContextGraph
-from .dependencies import anonymous_access_allowed, get_expected_api_key, is_valid_api_key, require_auth
from .session import GraphSession
from .ws import ConnectionManager
+from .auth import APIKeyAuthMiddleware, warn_if_unauthenticated
def _read_int_env(name: str, default: int) -> int:
@@ -98,22 +98,6 @@ def create_app(
@asynccontextmanager
async def lifespan(app: FastAPI):
- import logging as _lifespan_logging
- _lifespan_logger = _lifespan_logging.getLogger(__name__)
- if anonymous_access_allowed():
- _lifespan_logger.warning(
- "Explorer is running with SEMANTICA_ALLOW_ANONYMOUS=true — "
- "all API routes are unauthenticated. Do not expose this "
- "process beyond localhost."
- )
- elif get_expected_api_key():
- _lifespan_logger.info("Explorer API authentication: enabled (SEMANTICA_API_KEY set).")
- else:
- _lifespan_logger.warning(
- "Explorer API authentication: NOT CONFIGURED. All protected "
- "routes will return 503 until SEMANTICA_API_KEY is set."
- )
-
app.state.event_loop = asyncio.get_running_loop()
app.state.ws_manager = ConnectionManager()
app.state.session = active_session
@@ -144,6 +128,10 @@ def create_app(
max_age=600,
)
+ # API key authentication (opt-in via EXPLORER_API_KEY env var)
+ app.add_middleware(APIKeyAuthMiddleware)
+ warn_if_unauthenticated()
+
import logging as _logging
_logger = _logging.getLogger(__name__)
@@ -176,31 +164,22 @@ def create_app(
from .routes.temporal import router as temporal_router
from .routes.vocabulary import router as vocabulary_router
- _auth = [Depends(require_auth)]
- app.include_router(graph_router, dependencies=_auth)
- app.include_router(analytics_router, dependencies=_auth)
- app.include_router(decisions_router, dependencies=_auth)
- app.include_router(temporal_router, dependencies=_auth)
- app.include_router(enrich_router, dependencies=_auth)
- app.include_router(export_import_router, dependencies=_auth)
- app.include_router(annotations_router, dependencies=_auth)
- app.include_router(sparql_router, dependencies=_auth)
- app.include_router(provenance_router, dependencies=_auth)
- app.include_router(vocabulary_router, dependencies=_auth)
- app.include_router(ontology_router, dependencies=_auth)
+ app.include_router(graph_router)
+ app.include_router(analytics_router)
+ app.include_router(decisions_router)
+ app.include_router(temporal_router)
+ app.include_router(enrich_router)
+ app.include_router(export_import_router)
+ app.include_router(annotations_router)
+ app.include_router(sparql_router)
+ app.include_router(provenance_router)
+ app.include_router(vocabulary_router)
+ app.include_router(ontology_router)
_WS_MAX_MESSAGE_BYTES = 64 * 1024 # 64 KB — control messages only
@app.websocket("/ws/graph-updates")
async def websocket_endpoint(websocket: WebSocket):
- # Browsers can't set custom headers on a WebSocket handshake, so
- # accept the key via header (non-browser clients) or query param
- # (browser clients), same SEMANTICA_API_KEY the REST routes check.
- candidate = websocket.headers.get("x-api-key") or websocket.query_params.get("api_key")
- if not is_valid_api_key(candidate):
- await websocket.close(code=4401) # unauthorized
- return
-
manager: ConnectionManager = app.state.ws_manager
await manager.connect(websocket)
await manager.send_personal(websocket, "connection_ack", {"connected": True})