Files
next-tjwater-server/app/auth/keycloak_dependencies.py
T
jiang be6317eb48 feat(server): integrate MCP queries and investigation messaging
Add project-bound OAuth MCP queries and controlled analysis with scoped evidence,
limits, timeouts and a nearby-model spatial query using EPSG:4326 inputs.
Default nearby searches to 200 meters and five results.

Integrate investigation messaging/presentation, health/readiness and typed history;
remove duplicate web search and fix online simulation and compressed baseline writes.
Include project migrations 023-025; keep local credentials and demo seeding excluded.

Validation: 319 focused pytest checks; real PostGIS temporary-table regression;
read-only Jinqian bridge radius comparison; cross-language MCP discovery/calls.
2026-10-19 18:46:58 +08:00

111 lines
3.4 KiB
Python

import time
from uuid import UUID
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from app.core.config import settings
from app.mcp.config import McpSettings
mcp_resource_settings = McpSettings()
oauth2_optional = OAuth2PasswordBearer(
tokenUrl="keycloak", auto_error=False
)
# logger = logging.getLogger(__name__)
def _decode_keycloak_token(token: str) -> dict:
if not settings.KEYCLOAK_PUBLIC_KEY:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Keycloak public key is not configured",
)
key = settings.KEYCLOAK_PUBLIC_KEY.replace("\\n", "\n")
payload = jwt.decode(
token,
key,
algorithms=[settings.KEYCLOAK_ALGORITHM],
audience=settings.KEYCLOAK_AUDIENCE or None,
)
# A resource-bound MCP token must never authorize product REST APIs,
# including when another audience overlaps the configured API audience.
audience = payload.get("aud", [])
audiences = [audience] if isinstance(audience, str) else audience
if (isinstance(audiences, list) and mcp_resource_settings.audience in audiences
or payload.get("azp") == mcp_resource_settings.host_client_id):
raise JWTError("MCP resource tokens cannot authorize product REST APIs")
if settings.KEYCLOAK_ACCESS_TOKEN_MAX_AGE_SECONDS <= 0:
return payload
issued_at = payload.get("iat")
if not isinstance(issued_at, (int, float)) or (
time.time() >= issued_at + settings.KEYCLOAK_ACCESS_TOKEN_MAX_AGE_SECONDS
):
raise JWTError("Keycloak access token is older than the allowed maximum age")
return payload
async def get_current_keycloak_payload(
token: str | None = Depends(oauth2_optional),
) -> dict:
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
try:
return _decode_keycloak_token(token)
except JWTError as exc:
# logger.warning("Keycloak token validation failed: %s", exc)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"},
) from exc
async def get_current_keycloak_sub(
payload: dict = Depends(get_current_keycloak_payload),
) -> UUID:
sub = payload.get("sub")
if not sub:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing subject claim",
headers={"WWW-Authenticate": "Bearer"},
)
try:
return UUID(sub)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid subject claim",
headers={"WWW-Authenticate": "Bearer"},
) from exc
def get_keycloak_preferred_username(payload: dict) -> str:
username = payload.get("preferred_username")
if not username:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing preferred_username claim",
headers={"WWW-Authenticate": "Bearer"},
)
return str(username)
async def get_current_keycloak_username(
payload: dict = Depends(get_current_keycloak_payload),
) -> str:
return get_keycloak_preferred_username(payload)