|
| 1 | +# |
| 2 | +# Copyright (c) 2023 Airbyte, Inc., all rights reserved. |
| 3 | +# |
| 4 | + |
| 5 | +import base64 |
| 6 | +from dataclasses import InitVar, dataclass |
| 7 | +from datetime import datetime |
| 8 | +from typing import Any, Mapping, Optional, Union |
| 9 | + |
| 10 | +import jwt |
| 11 | +from airbyte_cdk.sources.declarative.auth.declarative_authenticator import DeclarativeAuthenticator |
| 12 | +from airbyte_cdk.sources.declarative.interpolation.interpolated_boolean import InterpolatedBoolean |
| 13 | +from airbyte_cdk.sources.declarative.interpolation.interpolated_mapping import InterpolatedMapping |
| 14 | +from airbyte_cdk.sources.declarative.interpolation.interpolated_string import InterpolatedString |
| 15 | + |
| 16 | + |
| 17 | +class JwtAlgorithm(str): |
| 18 | + """ |
| 19 | + Enum for supported JWT algorithms |
| 20 | + """ |
| 21 | + |
| 22 | + HS256 = "HS256" |
| 23 | + HS384 = "HS384" |
| 24 | + HS512 = "HS512" |
| 25 | + ES256 = "ES256" |
| 26 | + ES256K = "ES256K" |
| 27 | + ES384 = "ES384" |
| 28 | + ES512 = "ES512" |
| 29 | + RS256 = "RS256" |
| 30 | + RS384 = "RS384" |
| 31 | + RS512 = "RS512" |
| 32 | + PS256 = "PS256" |
| 33 | + PS384 = "PS384" |
| 34 | + PS512 = "PS512" |
| 35 | + EdDSA = "EdDSA" |
| 36 | + |
| 37 | + |
| 38 | +@dataclass |
| 39 | +class JwtAuthenticator(DeclarativeAuthenticator): |
| 40 | + """ |
| 41 | + Generates a JSON Web Token (JWT) based on a declarative connector configuration file. The generated token is attached to each request via the Authorization header. |
| 42 | +
|
| 43 | + Attributes: |
| 44 | + config (Mapping[str, Any]): The user-provided configuration as specified by the source's spec |
| 45 | + secret_key (Union[InterpolatedString, str]): The secret key used to sign the JWT |
| 46 | + algorithm (Union[str, JwtAlgorithm]): The algorithm used to sign the JWT |
| 47 | + token_duration (Optional[int]): The duration in seconds for which the token is valid |
| 48 | + base64_encode_secret_key (Optional[Union[InterpolatedBoolean, str, bool]]): Whether to base64 encode the secret key |
| 49 | + header_prefix (Optional[Union[InterpolatedString, str]]): The prefix to add to the Authorization header |
| 50 | + kid (Optional[Union[InterpolatedString, str]]): The key identifier to be included in the JWT header |
| 51 | + typ (Optional[Union[InterpolatedString, str]]): The type of the JWT. |
| 52 | + cty (Optional[Union[InterpolatedString, str]]): The content type of the JWT. |
| 53 | + iss (Optional[Union[InterpolatedString, str]]): The issuer of the JWT. |
| 54 | + sub (Optional[Union[InterpolatedString, str]]): The subject of the JWT. |
| 55 | + aud (Optional[Union[InterpolatedString, str]]): The audience of the JWT. |
| 56 | + additional_jwt_headers (Optional[Mapping[str, Any]]): Additional headers to include in the JWT. |
| 57 | + additional_jwt_payload (Optional[Mapping[str, Any]]): Additional payload to include in the JWT. |
| 58 | + """ |
| 59 | + |
| 60 | + config: Mapping[str, Any] |
| 61 | + parameters: InitVar[Mapping[str, Any]] |
| 62 | + secret_key: Union[InterpolatedString, str] |
| 63 | + algorithm: Union[str, JwtAlgorithm] |
| 64 | + token_duration: Optional[int] |
| 65 | + base64_encode_secret_key: Optional[Union[InterpolatedBoolean, str, bool]] = False |
| 66 | + header_prefix: Optional[Union[InterpolatedString, str]] = None |
| 67 | + kid: Optional[Union[InterpolatedString, str]] = None |
| 68 | + typ: Optional[Union[InterpolatedString, str]] = None |
| 69 | + cty: Optional[Union[InterpolatedString, str]] = None |
| 70 | + iss: Optional[Union[InterpolatedString, str]] = None |
| 71 | + sub: Optional[Union[InterpolatedString, str]] = None |
| 72 | + aud: Optional[Union[InterpolatedString, str]] = None |
| 73 | + additional_jwt_headers: Optional[Mapping[str, Any]] = None |
| 74 | + additional_jwt_payload: Optional[Mapping[str, Any]] = None |
| 75 | + |
| 76 | + def __post_init__(self, parameters: Mapping[str, Any]) -> None: |
| 77 | + self._secret_key = InterpolatedString.create(self.secret_key, parameters=parameters) |
| 78 | + self._algorithm = JwtAlgorithm(self.algorithm) if isinstance(self.algorithm, str) else self.algorithm |
| 79 | + self._base64_encode_secret_key = ( |
| 80 | + InterpolatedBoolean(self.base64_encode_secret_key, parameters=parameters) |
| 81 | + if isinstance(self.base64_encode_secret_key, str) |
| 82 | + else self.base64_encode_secret_key |
| 83 | + ) |
| 84 | + self._token_duration = self.token_duration |
| 85 | + self._header_prefix = InterpolatedString.create(self.header_prefix, parameters=parameters) if self.header_prefix else None |
| 86 | + self._kid = InterpolatedString.create(self.kid, parameters=parameters) if self.kid else None |
| 87 | + self._typ = InterpolatedString.create(self.typ, parameters=parameters) if self.typ else None |
| 88 | + self._cty = InterpolatedString.create(self.cty, parameters=parameters) if self.cty else None |
| 89 | + self._iss = InterpolatedString.create(self.iss, parameters=parameters) if self.iss else None |
| 90 | + self._sub = InterpolatedString.create(self.sub, parameters=parameters) if self.sub else None |
| 91 | + self._aud = InterpolatedString.create(self.aud, parameters=parameters) if self.aud else None |
| 92 | + self._additional_jwt_headers = InterpolatedMapping(self.additional_jwt_headers or {}, parameters=parameters) |
| 93 | + self._additional_jwt_payload = InterpolatedMapping(self.additional_jwt_payload or {}, parameters=parameters) |
| 94 | + |
| 95 | + def _get_jwt_headers(self) -> dict[str, Any]: |
| 96 | + """ " |
| 97 | + Builds and returns the headers used when signing the JWT. |
| 98 | + """ |
| 99 | + headers = self._additional_jwt_headers.eval(self.config) |
| 100 | + if any(prop in headers for prop in ["kid", "alg", "typ", "cty"]): |
| 101 | + raise ValueError("'kid', 'alg', 'typ', 'cty' are reserved headers and should not be set as part of 'additional_jwt_headers'") |
| 102 | + |
| 103 | + if self._kid: |
| 104 | + headers["kid"] = self._kid.eval(self.config) |
| 105 | + if self._typ: |
| 106 | + headers["typ"] = self._typ.eval(self.config) |
| 107 | + if self._cty: |
| 108 | + headers["cty"] = self._cty.eval(self.config) |
| 109 | + headers["alg"] = self._algorithm |
| 110 | + return headers |
| 111 | + |
| 112 | + def _get_jwt_payload(self) -> dict[str, Any]: |
| 113 | + """ |
| 114 | + Builds and returns the payload used when signing the JWT. |
| 115 | + """ |
| 116 | + now = int(datetime.now().timestamp()) |
| 117 | + exp = now + self._token_duration if isinstance(self._token_duration, int) else now |
| 118 | + nbf = now |
| 119 | + |
| 120 | + payload = self._additional_jwt_payload.eval(self.config) |
| 121 | + if any(prop in payload for prop in ["iss", "sub", "aud", "iat", "exp", "nbf"]): |
| 122 | + raise ValueError( |
| 123 | + "'iss', 'sub', 'aud', 'iat', 'exp', 'nbf' are reserved properties and should not be set as part of 'additional_jwt_payload'" |
| 124 | + ) |
| 125 | + |
| 126 | + if self._iss: |
| 127 | + payload["iss"] = self._iss.eval(self.config) |
| 128 | + if self._sub: |
| 129 | + payload["sub"] = self._sub.eval(self.config) |
| 130 | + if self._aud: |
| 131 | + payload["aud"] = self._aud.eval(self.config) |
| 132 | + payload["iat"] = now |
| 133 | + payload["exp"] = exp |
| 134 | + payload["nbf"] = nbf |
| 135 | + return payload |
| 136 | + |
| 137 | + def _get_secret_key(self) -> str: |
| 138 | + """ |
| 139 | + Returns the secret key used to sign the JWT. |
| 140 | + """ |
| 141 | + secret_key: str = self._secret_key.eval(self.config) |
| 142 | + return base64.b64encode(secret_key.encode()).decode() if self._base64_encode_secret_key else secret_key |
| 143 | + |
| 144 | + def _get_signed_token(self) -> Union[str, Any]: |
| 145 | + """ |
| 146 | + Signed the JWT using the provided secret key and algorithm and the generated headers and payload. For additional information on PyJWT see: https://pyjwt.readthedocs.io/en/stable/ |
| 147 | + """ |
| 148 | + try: |
| 149 | + return jwt.encode( |
| 150 | + payload=self._get_jwt_payload(), |
| 151 | + key=self._get_secret_key(), |
| 152 | + algorithm=self._algorithm, |
| 153 | + headers=self._get_jwt_headers(), |
| 154 | + ) |
| 155 | + except Exception as e: |
| 156 | + raise ValueError(f"Failed to sign token: {e}") |
| 157 | + |
| 158 | + def _get_header_prefix(self) -> Union[str, None]: |
| 159 | + """ |
| 160 | + Returns the header prefix to be used when attaching the token to the request. |
| 161 | + """ |
| 162 | + return self._header_prefix.eval(self.config) if self._header_prefix else None |
| 163 | + |
| 164 | + @property |
| 165 | + def auth_header(self) -> str: |
| 166 | + return "Authorization" |
| 167 | + |
| 168 | + @property |
| 169 | + def token(self) -> str: |
| 170 | + return f"{self._get_header_prefix()} {self._get_signed_token()}" if self._get_header_prefix() else self._get_signed_token() |
0 commit comments