|
| 1 | +from dataclasses import dataclass |
| 2 | +import logging |
| 3 | + |
| 4 | +from fastapi import Request, Response |
| 5 | +from fastapi.routing import APIRoute |
| 6 | + |
| 7 | +from .proxy import ReverseProxy |
| 8 | +from .utils import safe_headers |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class OpenApiSpecHandler: |
| 15 | + proxy: ReverseProxy |
| 16 | + oidc_config_url: str |
| 17 | + auth_scheme_name: str = "oidcAuth" |
| 18 | + |
| 19 | + async def dispatch(self, req: Request, res: Response): |
| 20 | + """ |
| 21 | + Proxy the OpenAPI spec from the upstream STAC API, updating it with OIDC security |
| 22 | + requirements. |
| 23 | + """ |
| 24 | + oidc_spec_response = await self.proxy.proxy_request(req) |
| 25 | + openapi_spec = oidc_spec_response.json() |
| 26 | + |
| 27 | + # Pass along the response headers |
| 28 | + res.headers.update(safe_headers(oidc_spec_response.headers)) |
| 29 | + |
| 30 | + # Add the OIDC security scheme to the components |
| 31 | + openapi_spec.setdefault("components", {}).setdefault("securitySchemes", {})[ |
| 32 | + self.auth_scheme_name |
| 33 | + ] = { |
| 34 | + "type": "openIdConnect", |
| 35 | + "openIdConnectUrl": self.oidc_config_url, |
| 36 | + } |
| 37 | + |
| 38 | + proxy_auth_routes = [ |
| 39 | + r |
| 40 | + for r in req.app.routes |
| 41 | + # Ignore non-APIRoutes (we can't check their security dependencies) |
| 42 | + if isinstance(r, APIRoute) |
| 43 | + # Ignore routes that don't have security requirements |
| 44 | + and ( |
| 45 | + r.dependant.security_requirements |
| 46 | + or any(d.security_requirements for d in r.dependant.dependencies) |
| 47 | + ) |
| 48 | + ] |
| 49 | + |
| 50 | + # Update the paths with the specified security requirements |
| 51 | + for path, method_config in openapi_spec["paths"].items(): |
| 52 | + for method, config in method_config.items(): |
| 53 | + for route in proxy_auth_routes: |
| 54 | + match, _ = route.matches( |
| 55 | + {"type": "http", "method": method.upper(), "path": path} |
| 56 | + ) |
| 57 | + if match.name != "FULL": |
| 58 | + continue |
| 59 | + # Add the OIDC security requirement |
| 60 | + config.setdefault("security", []).append( |
| 61 | + [{self.auth_scheme_name: []}] |
| 62 | + ) |
| 63 | + break |
| 64 | + |
| 65 | + return openapi_spec |
0 commit comments