token_verifier.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # (c) Nelen & Schuurmans
  2. import logging
  3. from typing import Dict
  4. from typing import FrozenSet
  5. from typing import List
  6. from typing import Optional
  7. import jwt
  8. from jwt import PyJWKClient
  9. from jwt.exceptions import PyJWTError
  10. from pydantic import AnyHttpUrl
  11. from pydantic import BaseModel
  12. from pydantic import ValidationError
  13. from clean_python import PermissionDenied
  14. from clean_python import Unauthorized
  15. from clean_python import User
  16. from .token import Token
  17. __all__ = [
  18. "BaseTokenVerifier",
  19. "TokenVerifier",
  20. "NoAuthTokenVerifier",
  21. "TokenVerifierSettings",
  22. "OAuth2SPAClientSettings",
  23. ]
  24. logger = logging.getLogger(__name__)
  25. class TokenVerifierSettings(BaseModel):
  26. issuer: str
  27. algorithms: List[str] = ["RS256"]
  28. # optional additional checks:
  29. scope: Optional[str] = None
  30. admin_users: Optional[List[str]] = None # 'sub' whitelist
  31. class OAuth2SPAClientSettings(BaseModel):
  32. client_id: str
  33. token_url: AnyHttpUrl
  34. authorization_url: AnyHttpUrl
  35. class BaseTokenVerifier:
  36. def __call__(self, authorization: Optional[str]) -> Token:
  37. raise NotImplementedError()
  38. class NoAuthTokenVerifier(BaseTokenVerifier):
  39. def __call__(self, authorization: Optional[str]) -> Token:
  40. return Token(claims={"sub": "DEV", "username": "dev", "scope": "superuser"})
  41. class TokenVerifier(BaseTokenVerifier):
  42. """A class for verifying OAuth2 Access Tokens from AWS Cognito
  43. The verification steps followed are documented here:
  44. https://docs.aws.amazon.com/cognito/latest/developerguide/amazon- ⏎
  45. cognito-user-pools-using-tokens-verifying-a-jwt.html
  46. """
  47. # allow 2 minutes leeway for verifying token expiry:
  48. LEEWAY = 120
  49. def __init__(
  50. self, settings: TokenVerifierSettings, logger: Optional[logging.Logger] = None
  51. ):
  52. self.settings = settings
  53. self.jwk_client = PyJWKClient(f"{settings.issuer}/.well-known/jwks.json")
  54. def __call__(self, authorization: Optional[str]) -> Token:
  55. # Step 0: retrieve the token from the Authorization header
  56. # See https://tools.ietf.org/html/rfc6750#section-2.1,
  57. # Bearer is case-sensitive and there is exactly 1 separator after.
  58. if authorization is None:
  59. logger.info("Missing Authorization header")
  60. raise Unauthorized()
  61. token = authorization[7:] if authorization.startswith("Bearer") else None
  62. if token is None:
  63. logger.info("Authorization does not start with 'Bearer '")
  64. raise Unauthorized()
  65. # Step 1: Confirm the structure of the JWT. This check is part of get_kid since
  66. # jwt.get_unverified_header will raise a JWTError if the structure is wrong.
  67. try:
  68. key = self.get_key(token) # JSON Web Key
  69. except PyJWTError as e:
  70. logger.info("Token is invalid: %s", e)
  71. raise Unauthorized()
  72. # Step 2: Validate the JWT signature and standard claims
  73. try:
  74. claims = jwt.decode(
  75. token,
  76. key.key,
  77. algorithms=self.settings.algorithms,
  78. issuer=self.settings.issuer,
  79. leeway=self.LEEWAY,
  80. options={
  81. "require": ["exp", "iss", "sub", "scope", "token_use"],
  82. },
  83. )
  84. except PyJWTError as e:
  85. logger.info("Token is invalid: %s", e)
  86. raise Unauthorized()
  87. # Step 3: Verify additional claims. At this point, we have passed
  88. # verification, so unverified claims may be used safely.
  89. self.verify_token_use(claims)
  90. try:
  91. token = Token(claims=claims)
  92. except ValidationError as e:
  93. logger.info("Token is invalid: %s", e)
  94. raise Unauthorized()
  95. self.verify_scope(token.scope)
  96. # Step 4: Authorization: verify user id ('sub' claim) against 'admin_users'
  97. self.authorize_user(token.user)
  98. return token
  99. def get_key(self, token) -> jwt.PyJWK:
  100. """Return the JSON Web KEY (JWK) corresponding to kid."""
  101. return self.jwk_client.get_signing_key_from_jwt(token)
  102. def verify_token_use(self, claims: Dict) -> None:
  103. """Check the token_use claim."""
  104. if claims["token_use"] != "access":
  105. logger.info("Token has invalid token_use claim: %s", claims["token_use"])
  106. raise Unauthorized()
  107. def verify_scope(self, claims_scope: FrozenSet[str]) -> None:
  108. """Parse scopes and optionally check scope claim."""
  109. if self.settings.scope is None:
  110. return
  111. if self.settings.scope not in claims_scope:
  112. logger.info("Token is missing '%s' scope", self.settings.scope)
  113. raise Unauthorized()
  114. def authorize_user(self, user: User) -> None:
  115. if self.settings.admin_users is None:
  116. return
  117. if user.id not in self.settings.admin_users:
  118. raise PermissionDenied()