feat(enterprise): Phase 14 — API Key Management + SSO/SAML 2.0
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
- ApiKey model (SHA-256 hash, prefix, scopes, expiry) + Alembic migration (b040ent) - SsoConfig model for SAML 2.0 IdP settings (attribute mapping, auto-provision) - API key auth integrated into get_current_user (aegis_ prefix detection) - Routers: /api/v1/api-keys (full CRUD + revoke) and /api/v1/sso (metadata, login, callback, config) - python3-saml added to requirements; Dockerfile adds libxmlsec1-dev for SAML XML signing - QA script: 52 assertions covering key lifecycle, API key auth, SSO config Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
117
backend/app/routers/sso.py
Normal file
117
backend/app/routers/sso.py
Normal file
@@ -0,0 +1,117 @@
|
||||
"""Phase 14: SSO / SAML 2.0 router."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
|
||||
from fastapi.responses import RedirectResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.dependencies.auth import get_current_user, require_any_role
|
||||
from app import auth as auth_lib
|
||||
from app.schemas.sso_schema import (
|
||||
SsoConfigCreate, SsoConfigOut, SsoLoginInitResponse, SsoStatusResponse,
|
||||
)
|
||||
import app.services.sso_service as svc
|
||||
|
||||
router = APIRouter(prefix="/sso", tags=["SSO"])
|
||||
|
||||
_COOKIE_NAME = "aegis_token"
|
||||
_COOKIE_OPTS = {"httponly": True, "samesite": "lax", "secure": False}
|
||||
|
||||
|
||||
# ── Public ────────────────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/status", response_model=SsoStatusResponse)
|
||||
def sso_status(db: Session = Depends(get_db)):
|
||||
"""Return whether SSO is enabled and configured (public — for login page)."""
|
||||
return svc.get_status(db)
|
||||
|
||||
|
||||
@router.get("/metadata", response_model=None)
|
||||
def sp_metadata(db: Session = Depends(get_db)):
|
||||
"""
|
||||
Return the Service Provider SAML metadata XML.
|
||||
|
||||
Upload this XML to your IdP (Okta, Azure AD, etc.) to register Aegis.
|
||||
"""
|
||||
try:
|
||||
xml = svc.get_sp_metadata(db)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc))
|
||||
return Response(content=xml, media_type="application/xml")
|
||||
|
||||
|
||||
@router.get("/login")
|
||||
def sso_login(request: Request, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Initiate SAML login — redirects the browser to the IdP.
|
||||
|
||||
The IdP will POST the SAML Response to ``/sso/callback`` after authentication.
|
||||
"""
|
||||
request_data = {
|
||||
"https": request.url.scheme == "https",
|
||||
"http_host": request.url.hostname,
|
||||
"path": request.url.path,
|
||||
"port": str(request.url.port or (443 if request.url.scheme == "https" else 80)),
|
||||
"get_data": dict(request.query_params),
|
||||
"post_data": {},
|
||||
"query_string": str(request.url.query),
|
||||
}
|
||||
try:
|
||||
result = svc.initiate_login(db, request_data)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc))
|
||||
return RedirectResponse(url=result["redirect_url"])
|
||||
|
||||
|
||||
@router.post("/callback")
|
||||
async def sso_callback(request: Request, db: Session = Depends(get_db)):
|
||||
"""
|
||||
SAML Assertion Consumer Service (ACS) endpoint.
|
||||
|
||||
The IdP POSTs the SAML Response here. On success, sets the aegis_token
|
||||
cookie and redirects to the frontend.
|
||||
"""
|
||||
form = await request.form()
|
||||
request_data = {
|
||||
"https": request.url.scheme == "https",
|
||||
"http_host": request.url.hostname,
|
||||
"path": request.url.path,
|
||||
"port": str(request.url.port or (443 if request.url.scheme == "https" else 80)),
|
||||
"get_data": dict(request.query_params),
|
||||
"post_data": dict(form),
|
||||
"query_string": str(request.url.query),
|
||||
}
|
||||
try:
|
||||
user = svc.process_callback(db, request_data)
|
||||
except (ValueError, RuntimeError) as exc:
|
||||
raise HTTPException(status_code=401, detail=str(exc))
|
||||
|
||||
access_token = auth_lib.create_access_token({"sub": user.username})
|
||||
response = RedirectResponse(url="/", status_code=302)
|
||||
response.set_cookie(_COOKIE_NAME, access_token, **_COOKIE_OPTS)
|
||||
return response
|
||||
|
||||
|
||||
# ── Admin configuration ────────────────────────────────────────────────────────
|
||||
|
||||
@router.get("/config", response_model=SsoConfigOut)
|
||||
def get_sso_config(
|
||||
db: Session = Depends(get_db),
|
||||
_user=Depends(require_any_role("admin")),
|
||||
):
|
||||
"""Return the current SSO configuration (admin only)."""
|
||||
cfg = svc.get_config(db)
|
||||
if not cfg:
|
||||
raise HTTPException(status_code=404, detail="SSO not configured yet")
|
||||
return SsoConfigOut.model_validate(cfg)
|
||||
|
||||
|
||||
@router.put("/config", response_model=SsoConfigOut)
|
||||
def upsert_sso_config(
|
||||
body: SsoConfigCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_user=Depends(require_any_role("admin")),
|
||||
):
|
||||
"""Create or replace the SSO configuration (admin only)."""
|
||||
cfg = svc.upsert_config(db, **body.model_dump(exclude_unset=False))
|
||||
return SsoConfigOut.model_validate(cfg)
|
||||
Reference in New Issue
Block a user