service.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import logging
  2. from typing import Any
  3. from typing import Callable
  4. from typing import Dict
  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 HTTPException
  13. from fastapi.exceptions import RequestValidationError
  14. from fastapi.security import OAuth2AuthorizationCodeBearer
  15. from starlette.status import HTTP_401_UNAUTHORIZED
  16. from starlette.status import HTTP_403_FORBIDDEN
  17. from starlette.types import ASGIApp
  18. from clean_python.base.domain.exceptions import Conflict
  19. from clean_python.base.domain.exceptions import DoesNotExist
  20. from clean_python.base.domain.exceptions import PermissionDenied
  21. from clean_python.base.domain.exceptions import Unauthorized
  22. from clean_python.base.infrastructure.gateway import Gateway
  23. from clean_python.oauth2.oauth2 import OAuth2AccessTokenVerifier
  24. from clean_python.oauth2.oauth2 import OAuth2Settings
  25. from .context import RequestMiddleware
  26. from .error_responses import BadRequest
  27. from .error_responses import conflict_handler
  28. from .error_responses import DefaultErrorResponse
  29. from .error_responses import not_found_handler
  30. from .error_responses import not_implemented_handler
  31. from .error_responses import permission_denied_handler
  32. from .error_responses import unauthorized_handler
  33. from .error_responses import validation_error_handler
  34. from .error_responses import ValidationErrorResponse
  35. from .fastapi_access_logger import FastAPIAccessLogger
  36. from .resource import APIVersion
  37. from .resource import clean_resources
  38. from .resource import Resource
  39. logger = logging.getLogger(__name__)
  40. class OAuth2Dependable(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__(self, scope, settings: OAuth2Settings):
  47. self.verifier = sync_to_async(
  48. OAuth2AccessTokenVerifier(
  49. scope,
  50. issuer=settings.issuer,
  51. resource_server_id=settings.resource_server_id,
  52. algorithms=settings.algorithms,
  53. admin_users=settings.admin_users,
  54. ),
  55. thread_sensitive=False,
  56. )
  57. super().__init__(
  58. authorizationUrl=settings.authorization_url,
  59. tokenUrl=settings.token_url,
  60. scopes={
  61. f"{settings.resource_server_id}*:readwrite": "Full read/write access"
  62. },
  63. )
  64. async def __call__(self, request: Request) -> None:
  65. token = await super().__call__(request)
  66. try:
  67. await self.verifier(token)
  68. except Unauthorized:
  69. raise HTTPException(status_code=HTTP_401_UNAUTHORIZED)
  70. except PermissionDenied:
  71. raise HTTPException(status_code=HTTP_403_FORBIDDEN)
  72. def fastapi_oauth_kwargs(auth: Optional[OAuth2Settings]) -> Dict:
  73. if auth is None:
  74. return {}
  75. return {
  76. "dependencies": [Depends(OAuth2Dependable(scope="*:readwrite", settings=auth))],
  77. "swagger_ui_init_oauth": {
  78. "clientId": auth.client_id,
  79. "usePkceWithAuthorizationCodeGrant": True,
  80. },
  81. }
  82. async def health_check():
  83. """Simple health check route"""
  84. return {"health": "OK"}
  85. class Service:
  86. resources: List[Resource]
  87. def __init__(self, *args: Resource):
  88. self.resources = clean_resources(args)
  89. @property
  90. def versions(self) -> Set[APIVersion]:
  91. return set([x.version for x in self.resources])
  92. def _create_root_app(
  93. self,
  94. title: str,
  95. description: str,
  96. hostname: str,
  97. on_startup: Optional[List[Callable[[], Any]]] = None,
  98. access_logger_gateway: Optional[Gateway] = None,
  99. ) -> FastAPI:
  100. app = FastAPI(
  101. title=title,
  102. description=description,
  103. on_startup=on_startup,
  104. servers=[
  105. {"url": f"{x.prefix}", "description": x.description}
  106. for x in self.versions
  107. ],
  108. root_path_in_servers=False,
  109. )
  110. app.middleware("http")(
  111. FastAPIAccessLogger(
  112. hostname=hostname, gateway_override=access_logger_gateway
  113. )
  114. )
  115. app.add_middleware(RequestMiddleware)
  116. app.get("/health", include_in_schema=False)(health_check)
  117. return app
  118. def _create_versioned_app(self, version: APIVersion, **kwargs) -> FastAPI:
  119. resources = [x for x in self.resources if x.version == version]
  120. app = FastAPI(
  121. version=version.prefix,
  122. tags=sorted(
  123. [x.get_openapi_tag().dict() for x in resources], key=lambda x: x["name"]
  124. ),
  125. **kwargs,
  126. )
  127. for resource in resources:
  128. app.include_router(
  129. resource.get_router(
  130. version,
  131. responses={
  132. "400": {"model": ValidationErrorResponse},
  133. "default": {"model": DefaultErrorResponse},
  134. },
  135. )
  136. )
  137. app.add_exception_handler(DoesNotExist, not_found_handler)
  138. app.add_exception_handler(Conflict, conflict_handler)
  139. app.add_exception_handler(RequestValidationError, validation_error_handler)
  140. app.add_exception_handler(BadRequest, validation_error_handler)
  141. app.add_exception_handler(NotImplementedError, not_implemented_handler)
  142. app.add_exception_handler(PermissionDenied, permission_denied_handler)
  143. app.add_exception_handler(Unauthorized, unauthorized_handler)
  144. return app
  145. def create_app(
  146. self,
  147. title: str,
  148. description: str,
  149. hostname: str,
  150. auth: Optional[OAuth2Settings] = None,
  151. on_startup: Optional[List[Callable[[], Any]]] = None,
  152. access_logger_gateway: Optional[Gateway] = None,
  153. ) -> ASGIApp:
  154. app = self._create_root_app(
  155. title=title,
  156. description=description,
  157. hostname=hostname,
  158. on_startup=on_startup,
  159. access_logger_gateway=access_logger_gateway,
  160. )
  161. kwargs = {
  162. "title": title,
  163. "description": description,
  164. **fastapi_oauth_kwargs(auth),
  165. }
  166. versioned_apps = {
  167. v: self._create_versioned_app(v, **kwargs) for v in self.versions
  168. }
  169. for v, versioned_app in versioned_apps.items():
  170. app.mount("/" + v.prefix, versioned_app)
  171. return app