|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +"""FastAPI router for OAuth 2.1 endpoints.""" |
| 4 | + |
| 5 | +import logging |
| 6 | + |
| 7 | +from fastapi import APIRouter, FastAPI, Request |
| 8 | +from fastapi.responses import JSONResponse |
| 9 | + |
| 10 | +from airlock.oauth.discovery import build_discovery_metadata, build_jwks |
| 11 | +from airlock.oauth.introspection import introspect_token |
| 12 | +from airlock.oauth.models import TokenRequest |
| 13 | +from airlock.oauth.registration import RegistrationError, RegistrationRequest, register_client |
| 14 | +from airlock.oauth.server import OAuthError, handle_token_request |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | +oauth_router = APIRouter(tags=["oauth"]) |
| 19 | + |
| 20 | + |
| 21 | +@oauth_router.post("/oauth/token") |
| 22 | +async def token_endpoint(request: Request) -> JSONResponse: |
| 23 | + """OAuth 2.1 token endpoint supporting client_credentials and token_exchange.""" |
| 24 | + form = await request.form() |
| 25 | + token_request = TokenRequest( |
| 26 | + grant_type=str(form.get("grant_type", "")), |
| 27 | + client_assertion=str(form.get("client_assertion", "")) or None, |
| 28 | + client_assertion_type=str(form.get("client_assertion_type", "")) or None, |
| 29 | + scope=str(form.get("scope", "")) or None, |
| 30 | + subject_token=str(form.get("subject_token", "")) or None, |
| 31 | + subject_token_type=str(form.get("subject_token_type", "")) or None, |
| 32 | + ) |
| 33 | + |
| 34 | + kp = request.app.state.airlock_kp |
| 35 | + cfg = request.app.state.config |
| 36 | + oauth_store = request.app.state.oauth_store |
| 37 | + |
| 38 | + base_url = (cfg.public_base_url or cfg.default_gateway_url).rstrip("/") |
| 39 | + token_endpoint_url = f"{base_url}/oauth/token" |
| 40 | + |
| 41 | + # Trust score lookup from reputation store |
| 42 | + def _trust_lookup(did: str) -> tuple[float, int]: |
| 43 | + reputation = getattr(request.app.state, "reputation", None) |
| 44 | + if reputation is None: |
| 45 | + return 0.0, 0 |
| 46 | + record = reputation.get(did) |
| 47 | + if record is None: |
| 48 | + return 0.0, 0 |
| 49 | + return record.score, record.tier |
| 50 | + |
| 51 | + try: |
| 52 | + response = handle_token_request( |
| 53 | + token_request, |
| 54 | + oauth_store=oauth_store, |
| 55 | + signing_key=kp.signing_key, |
| 56 | + verify_key=kp.verify_key, |
| 57 | + issuer_did=kp.did, |
| 58 | + token_endpoint=token_endpoint_url, |
| 59 | + ttl_seconds=cfg.oauth_token_ttl_seconds, |
| 60 | + max_delegation_depth=cfg.oauth_max_delegation_depth, |
| 61 | + allowed_scopes=cfg.oauth_allowed_scopes, |
| 62 | + trust_score_lookup=_trust_lookup, |
| 63 | + ) |
| 64 | + except OAuthError as exc: |
| 65 | + return JSONResponse( |
| 66 | + status_code=exc.status_code, |
| 67 | + content={"error": exc.error, "error_description": exc.description}, |
| 68 | + ) |
| 69 | + |
| 70 | + return JSONResponse( |
| 71 | + status_code=200, |
| 72 | + content=response.model_dump(), |
| 73 | + headers={"Cache-Control": "no-store", "Pragma": "no-cache"}, |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +@oauth_router.post("/oauth/register") |
| 78 | +async def registration_endpoint(body: RegistrationRequest, request: Request) -> JSONResponse: |
| 79 | + """Dynamic client registration (RFC 7591).""" |
| 80 | + cfg = request.app.state.config |
| 81 | + |
| 82 | + if not cfg.oauth_dynamic_registration: |
| 83 | + return JSONResponse( |
| 84 | + status_code=403, |
| 85 | + content={"error": "registration_disabled", "error_description": "Dynamic registration is disabled"}, |
| 86 | + ) |
| 87 | + |
| 88 | + oauth_store = request.app.state.oauth_store |
| 89 | + |
| 90 | + try: |
| 91 | + response = register_client( |
| 92 | + body, |
| 93 | + oauth_store=oauth_store, |
| 94 | + allowed_scopes=cfg.oauth_allowed_scopes, |
| 95 | + ) |
| 96 | + except RegistrationError as exc: |
| 97 | + return JSONResponse( |
| 98 | + status_code=400, |
| 99 | + content={"error": exc.error, "error_description": exc.description}, |
| 100 | + ) |
| 101 | + |
| 102 | + return JSONResponse(status_code=201, content=response.model_dump(mode="json")) |
| 103 | + |
| 104 | + |
| 105 | +@oauth_router.post("/oauth/introspect") |
| 106 | +async def introspection_endpoint(request: Request) -> JSONResponse: |
| 107 | + """RFC 7662 token introspection.""" |
| 108 | + form = await request.form() |
| 109 | + token_str = str(form.get("token", "")) |
| 110 | + |
| 111 | + if not token_str: |
| 112 | + return JSONResponse( |
| 113 | + status_code=400, |
| 114 | + content={"error": "invalid_request", "error_description": "token parameter is required"}, |
| 115 | + ) |
| 116 | + |
| 117 | + kp = request.app.state.airlock_kp |
| 118 | + oauth_store = request.app.state.oauth_store |
| 119 | + |
| 120 | + def _trust_lookup(did: str) -> tuple[float, int]: |
| 121 | + reputation = getattr(request.app.state, "reputation", None) |
| 122 | + if reputation is None: |
| 123 | + return 0.0, 0 |
| 124 | + record = reputation.get(did) |
| 125 | + if record is None: |
| 126 | + return 0.0, 0 |
| 127 | + return record.score, record.tier |
| 128 | + |
| 129 | + response = introspect_token( |
| 130 | + token_str, |
| 131 | + verify_key=kp.verify_key, |
| 132 | + issuer_did=kp.did, |
| 133 | + oauth_store=oauth_store, |
| 134 | + trust_score_lookup=_trust_lookup, |
| 135 | + ) |
| 136 | + |
| 137 | + return JSONResponse( |
| 138 | + status_code=200, |
| 139 | + content=response.model_dump(by_alias=True, exclude_none=True), |
| 140 | + ) |
| 141 | + |
| 142 | + |
| 143 | +@oauth_router.post("/oauth/revoke") |
| 144 | +async def revocation_endpoint(request: Request) -> JSONResponse: |
| 145 | + """Token revocation endpoint.""" |
| 146 | + form = await request.form() |
| 147 | + token_str = str(form.get("token", "")) |
| 148 | + |
| 149 | + if not token_str: |
| 150 | + return JSONResponse( |
| 151 | + status_code=400, |
| 152 | + content={"error": "invalid_request", "error_description": "token parameter is required"}, |
| 153 | + ) |
| 154 | + |
| 155 | + kp = request.app.state.airlock_kp |
| 156 | + oauth_store = request.app.state.oauth_store |
| 157 | + |
| 158 | + # Try to decode and revoke |
| 159 | + from airlock.oauth.token_validator import validate_access_token |
| 160 | + |
| 161 | + try: |
| 162 | + payload = validate_access_token( |
| 163 | + token_str, |
| 164 | + verify_key=kp.verify_key, |
| 165 | + expected_issuer=kp.did, |
| 166 | + ) |
| 167 | + jti = payload.get("jti", "") |
| 168 | + if jti: |
| 169 | + oauth_store.revoke_cascade(jti) |
| 170 | + except Exception: |
| 171 | + # Per RFC 7009, always return 200 even if token is invalid |
| 172 | + pass |
| 173 | + |
| 174 | + return JSONResponse(status_code=200, content={}) |
| 175 | + |
| 176 | + |
| 177 | +@oauth_router.get("/.well-known/openid-configuration") |
| 178 | +async def openid_configuration(request: Request) -> JSONResponse: |
| 179 | + """OIDC discovery metadata endpoint.""" |
| 180 | + cfg = request.app.state.config |
| 181 | + kp = request.app.state.airlock_kp |
| 182 | + base_url = (cfg.public_base_url or cfg.default_gateway_url).rstrip("/") |
| 183 | + |
| 184 | + metadata = build_discovery_metadata( |
| 185 | + base_url=base_url, |
| 186 | + issuer_did=kp.did, |
| 187 | + ) |
| 188 | + |
| 189 | + return JSONResponse(status_code=200, content=metadata) |
| 190 | + |
| 191 | + |
| 192 | +@oauth_router.get("/.well-known/jwks.json") |
| 193 | +async def jwks_endpoint(request: Request) -> JSONResponse: |
| 194 | + """JWKS endpoint exposing the gateway's Ed25519 public key.""" |
| 195 | + kp = request.app.state.airlock_kp |
| 196 | + |
| 197 | + jwks = build_jwks(verify_key=kp.verify_key) |
| 198 | + |
| 199 | + return JSONResponse( |
| 200 | + status_code=200, |
| 201 | + content=jwks, |
| 202 | + headers={"Cache-Control": "public, max-age=3600"}, |
| 203 | + ) |
| 204 | + |
| 205 | + |
| 206 | +def register_oauth_routes(app: FastAPI) -> None: |
| 207 | + """Mount all OAuth routes onto the FastAPI application.""" |
| 208 | + app.include_router(oauth_router) |
| 209 | + logger.info("OAuth 2.1 routes registered") |
0 commit comments