service.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # (c) Nelen & Schuurmans
  2. import logging
  3. from typing import Any
  4. from typing import Callable
  5. from typing import List
  6. from typing import Optional
  7. from typing import Set
  8. from asgiref.sync import sync_to_async
  9. from fastapi import Depends
  10. from fastapi import FastAPI
  11. from fastapi import Request
  12. from fastapi.exceptions import RequestValidationError
  13. from fastapi.security import OAuth2AuthorizationCodeBearer
  14. from starlette.types import ASGIApp
  15. from clean_python import Conflict
  16. from clean_python import DoesNotExist
  17. from clean_python import Gateway
  18. from clean_python import PermissionDenied
  19. from clean_python import Unauthorized
  20. from clean_python.oauth2 import OAuth2SPAClientSettings
  21. from clean_python.oauth2 import TokenVerifier
  22. from clean_python.oauth2 import TokenVerifierSettings
  23. from .context import ctx
  24. from .context import RequestMiddleware
  25. from .error_responses import BadRequest
  26. from .error_responses import conflict_handler
  27. from .error_responses import DefaultErrorResponse
  28. from .error_responses import not_found_handler
  29. from .error_responses import not_implemented_handler
  30. from .error_responses import permission_denied_handler
  31. from .error_responses import unauthorized_handler
  32. from .error_responses import validation_error_handler
  33. from .error_responses import ValidationErrorResponse
  34. from .fastapi_access_logger import FastAPIAccessLogger
  35. from .resource import APIVersion
  36. from .resource import clean_resources
  37. from .resource import Resource
  38. logger = logging.getLogger(__name__)
  39. __all__ = ["Service"]
  40. class OAuth2WithClientDependable(OAuth2AuthorizationCodeBearer):
  41. """A fastapi 'dependable' configuring OAuth2.
  42. This does two things:
  43. - Verify the token in each request
  44. - (through FastAPI magic) add the scheme to the OpenAPI spec
  45. """
  46. def __init__(
  47. self, settings: TokenVerifierSettings, client: OAuth2SPAClientSettings
  48. ):
  49. self.verifier = sync_to_async(TokenVerifier(settings), thread_sensitive=False)
  50. super().__init__(
  51. authorizationUrl=str(client.authorization_url),
  52. tokenUrl=str(client.token_url),
  53. )
  54. async def __call__(self, request: Request) -> None:
  55. ctx.claims = await self.verifier(request.headers.get("Authorization"))
  56. class OAuth2WithoutClientDependable:
  57. """A fastapi 'dependable' configuring OAuth2.
  58. This does one thing:
  59. - Verify the token in each request
  60. """
  61. def __init__(self, settings: TokenVerifierSettings):
  62. self.verifier = sync_to_async(TokenVerifier(settings), thread_sensitive=False)
  63. async def __call__(self, request: Request) -> None:
  64. ctx.claims = await self.verifier(request.headers.get("Authorization"))
  65. def get_auth_kwargs(
  66. auth: Optional[TokenVerifierSettings],
  67. auth_client: Optional[OAuth2SPAClientSettings],
  68. ) -> None:
  69. if auth is None:
  70. return {}
  71. if auth_client is None:
  72. return {
  73. "dependencies": [Depends(OAuth2WithoutClientDependable(settings=auth))],
  74. }
  75. else:
  76. return {
  77. "dependencies": [
  78. Depends(OAuth2WithClientDependable(settings=auth, client=auth_client))
  79. ],
  80. "swagger_ui_init_oauth": {
  81. "clientId": auth_client.client_id,
  82. "usePkceWithAuthorizationCodeGrant": True,
  83. },
  84. }
  85. async def health_check():
  86. """Simple health check route"""
  87. return {"health": "OK"}
  88. class Service:
  89. resources: List[Resource]
  90. def __init__(self, *args: Resource):
  91. self.resources = clean_resources(args)
  92. @property
  93. def versions(self) -> Set[APIVersion]:
  94. return set([x.version for x in self.resources])
  95. def _create_root_app(
  96. self,
  97. title: str,
  98. description: str,
  99. hostname: str,
  100. on_startup: Optional[List[Callable[[], Any]]] = None,
  101. access_logger_gateway: Optional[Gateway] = None,
  102. ) -> FastAPI:
  103. app = FastAPI(
  104. title=title,
  105. description=description,
  106. on_startup=on_startup,
  107. servers=[
  108. {"url": f"{x.prefix}", "description": x.description}
  109. for x in self.versions
  110. ],
  111. root_path_in_servers=False,
  112. )
  113. app.middleware("http")(
  114. FastAPIAccessLogger(
  115. hostname=hostname, gateway_override=access_logger_gateway
  116. )
  117. )
  118. app.add_middleware(RequestMiddleware)
  119. app.get("/health", include_in_schema=False)(health_check)
  120. return app
  121. def _create_versioned_app(self, version: APIVersion, **kwargs) -> FastAPI:
  122. resources = [x for x in self.resources if x.version == version]
  123. app = FastAPI(
  124. version=version.prefix,
  125. tags=sorted(
  126. [x.get_openapi_tag().model_dump() for x in resources],
  127. key=lambda x: x["name"],
  128. ),
  129. **kwargs,
  130. )
  131. for resource in resources:
  132. app.include_router(
  133. resource.get_router(
  134. version,
  135. responses={
  136. "400": {"model": ValidationErrorResponse},
  137. "default": {"model": DefaultErrorResponse},
  138. },
  139. )
  140. )
  141. app.add_exception_handler(DoesNotExist, not_found_handler)
  142. app.add_exception_handler(Conflict, conflict_handler)
  143. app.add_exception_handler(RequestValidationError, validation_error_handler)
  144. app.add_exception_handler(BadRequest, validation_error_handler)
  145. app.add_exception_handler(NotImplementedError, not_implemented_handler)
  146. app.add_exception_handler(PermissionDenied, permission_denied_handler)
  147. app.add_exception_handler(Unauthorized, unauthorized_handler)
  148. return app
  149. def create_app(
  150. self,
  151. title: str,
  152. description: str,
  153. hostname: str,
  154. auth: Optional[TokenVerifierSettings] = None,
  155. auth_client: Optional[OAuth2SPAClientSettings] = None,
  156. on_startup: Optional[List[Callable[[], Any]]] = None,
  157. access_logger_gateway: Optional[Gateway] = None,
  158. ) -> ASGIApp:
  159. app = self._create_root_app(
  160. title=title,
  161. description=description,
  162. hostname=hostname,
  163. on_startup=on_startup,
  164. access_logger_gateway=access_logger_gateway,
  165. )
  166. kwargs = {
  167. "title": title,
  168. "description": description,
  169. **get_auth_kwargs(auth, auth_client),
  170. }
  171. versioned_apps = {
  172. v: self._create_versioned_app(v, **kwargs) for v in self.versions
  173. }
  174. for v, versioned_app in versioned_apps.items():
  175. app.mount("/" + v.prefix, versioned_app)
  176. return app