airbyte_cdk.sources.declarative.auth.jwt

  1#
  2# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
  3#
  4
  5import base64
  6import json
  7from dataclasses import InitVar, dataclass
  8from datetime import datetime
  9from typing import Any, Mapping, MutableMapping, Optional, Union, cast
 10
 11import jwt
 12from cryptography.hazmat.primitives import serialization
 13from cryptography.hazmat.primitives.asymmetric.ec import (
 14    EllipticCurvePrivateKey,
 15    EllipticCurvePublicKey,
 16)
 17from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey, Ed448PublicKey
 18from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
 19from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
 20
 21from airbyte_cdk.models import FailureType
 22from airbyte_cdk.sources.declarative.auth.declarative_authenticator import DeclarativeAuthenticator
 23from airbyte_cdk.sources.declarative.interpolation.interpolated_boolean import InterpolatedBoolean
 24from airbyte_cdk.sources.declarative.interpolation.interpolated_mapping import InterpolatedMapping
 25from airbyte_cdk.sources.declarative.interpolation.interpolated_string import InterpolatedString
 26from airbyte_cdk.sources.declarative.requesters.request_option import (
 27    RequestOption,
 28    RequestOptionType,
 29)
 30from airbyte_cdk.utils.traced_exception import AirbyteTracedException
 31
 32# Type alias for keys that JWT library accepts
 33JwtKeyTypes = Union[
 34    RSAPrivateKey, EllipticCurvePrivateKey, Ed25519PrivateKey, Ed448PrivateKey, str, bytes
 35]
 36
 37
 38_PUBLIC_KEY_TYPES = (RSAPublicKey, EllipticCurvePublicKey, Ed25519PublicKey, Ed448PublicKey)
 39_UNUSABLE_KEY_MESSAGE = (
 40    "The key used to sign the JWT could not be used with the {algorithm} algorithm. {hint}"
 41)
 42_UNUSABLE_SECRET_HINT = "Check that the secret is set and complete."
 43_UNUSABLE_PRIVATE_KEY_HINT = (
 44    "Check that it is the complete private key of the expected type, including its BEGIN and END "
 45    "lines and its line breaks, and, if the key is encrypted, its passphrase."
 46)
 47
 48
 49class JwtAlgorithm(str):
 50    """
 51    Enum for supported JWT algorithms
 52    """
 53
 54    HS256 = "HS256"
 55    HS384 = "HS384"
 56    HS512 = "HS512"
 57    ES256 = "ES256"
 58    ES256K = "ES256K"
 59    ES384 = "ES384"
 60    ES512 = "ES512"
 61    RS256 = "RS256"
 62    RS384 = "RS384"
 63    RS512 = "RS512"
 64    PS256 = "PS256"
 65    PS384 = "PS384"
 66    PS512 = "PS512"
 67    EdDSA = "EdDSA"
 68
 69
 70@dataclass
 71class JwtAuthenticator(DeclarativeAuthenticator):
 72    """
 73    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.
 74
 75    Attributes:
 76        config (Mapping[str, Any]): The user-provided configuration as specified by the source's spec
 77        secret_key (Union[InterpolatedString, str]): The secret key used to sign the JWT
 78        algorithm (Union[str, JwtAlgorithm]): The algorithm used to sign the JWT
 79        token_duration (Optional[int]): The duration in seconds for which the token is valid
 80        iat_backdate_seconds (int): Seconds to move `iat` and `nbf` into the past to tolerate clock drift; `exp` is unaffected
 81        base64_encode_secret_key (Optional[Union[InterpolatedBoolean, str, bool]]): Whether to base64 encode the secret key
 82        header_prefix (Optional[Union[InterpolatedString, str]]): The prefix to add to the Authorization header
 83        kid (Optional[Union[InterpolatedString, str]]): The key identifier to be included in the JWT header
 84        typ (Optional[Union[InterpolatedString, str]]): The type of the JWT.
 85        cty (Optional[Union[InterpolatedString, str]]): The content type of the JWT.
 86        iss (Optional[Union[InterpolatedString, str]]): The issuer of the JWT.
 87        sub (Optional[Union[InterpolatedString, str]]): The subject of the JWT.
 88        aud (Optional[Union[InterpolatedString, str]]): The audience of the JWT.
 89        additional_jwt_headers (Optional[Mapping[str, Any]]): Additional headers to include in the JWT.
 90        additional_jwt_payload (Optional[Mapping[str, Any]]): Additional payload to include in the JWT.
 91    """
 92
 93    config: Mapping[str, Any]
 94    parameters: InitVar[Mapping[str, Any]]
 95    secret_key: Union[InterpolatedString, str]
 96    algorithm: Union[str, JwtAlgorithm]
 97    token_duration: Optional[int]
 98    base64_encode_secret_key: Optional[Union[InterpolatedBoolean, str, bool]] = False
 99    header_prefix: Optional[Union[InterpolatedString, str]] = None
100    kid: Optional[Union[InterpolatedString, str]] = None
101    typ: Optional[Union[InterpolatedString, str]] = None
102    cty: Optional[Union[InterpolatedString, str]] = None
103    iss: Optional[Union[InterpolatedString, str]] = None
104    sub: Optional[Union[InterpolatedString, str]] = None
105    aud: Optional[Union[InterpolatedString, str]] = None
106    additional_jwt_headers: Optional[Mapping[str, Any]] = None
107    additional_jwt_payload: Optional[Mapping[str, Any]] = None
108    passphrase: Optional[Union[InterpolatedString, str]] = None
109    request_option: Optional[RequestOption] = None
110    iat_backdate_seconds: int = 0
111
112    def __post_init__(self, parameters: Mapping[str, Any]) -> None:
113        self.iat_backdate_seconds = self.iat_backdate_seconds or 0
114        if self.iat_backdate_seconds < 0:
115            raise ValueError(
116                f"iat_backdate_seconds must be zero or positive, got {self.iat_backdate_seconds}"
117            )
118        self._secret_key = InterpolatedString.create(self.secret_key, parameters=parameters)
119        self._algorithm = (
120            JwtAlgorithm(self.algorithm) if isinstance(self.algorithm, str) else self.algorithm
121        )
122        self._base64_encode_secret_key = (
123            InterpolatedBoolean(self.base64_encode_secret_key, parameters=parameters)
124            if isinstance(self.base64_encode_secret_key, str)
125            else self.base64_encode_secret_key
126        )
127        self._token_duration = self.token_duration
128        self._header_prefix = (
129            InterpolatedString.create(self.header_prefix, parameters=parameters)
130            if self.header_prefix
131            else None
132        )
133        self._kid = InterpolatedString.create(self.kid, parameters=parameters) if self.kid else None
134        self._typ = InterpolatedString.create(self.typ, parameters=parameters) if self.typ else None
135        self._cty = InterpolatedString.create(self.cty, parameters=parameters) if self.cty else None
136        self._iss = InterpolatedString.create(self.iss, parameters=parameters) if self.iss else None
137        self._sub = InterpolatedString.create(self.sub, parameters=parameters) if self.sub else None
138        self._aud = InterpolatedString.create(self.aud, parameters=parameters) if self.aud else None
139        self._additional_jwt_headers = InterpolatedMapping(
140            self.additional_jwt_headers or {}, parameters=parameters
141        )
142        self._additional_jwt_payload = InterpolatedMapping(
143            self.additional_jwt_payload or {}, parameters=parameters
144        )
145        self._passphrase = (
146            InterpolatedString.create(self.passphrase, parameters=parameters)
147            if self.passphrase
148            else None
149        )
150
151        # When we first implemented the JWT authenticator, we assumed that the signed token was always supposed
152        # to be loaded into the request headers under the `Authorization` key. This is not always the case, but
153        # this default option allows for backwards compatibility to be retained for existing connectors
154        self._request_option = self.request_option or RequestOption(
155            inject_into=RequestOptionType.header, field_name="Authorization", parameters=parameters
156        )
157
158    def _get_jwt_headers(self) -> dict[str, Any]:
159        """
160        Builds and returns the headers used when signing the JWT.
161        """
162        headers = self._additional_jwt_headers.eval(self.config, json_loads=json.loads)
163        if any(prop in headers for prop in ["kid", "alg", "typ", "cty"]):
164            raise ValueError(
165                "'kid', 'alg', 'typ', 'cty' are reserved headers and should not be set as part of 'additional_jwt_headers'"
166            )
167
168        kid = self._eval_string(self._kid)
169        if kid is not None:
170            headers["kid"] = kid
171        if self._typ:
172            headers["typ"] = self._typ.eval(self.config, json_loads=json.loads)
173        if self._cty:
174            headers["cty"] = self._cty.eval(self.config, json_loads=json.loads)
175        headers["alg"] = self._algorithm
176        return headers
177
178    def _get_jwt_payload(self) -> dict[str, Any]:
179        """
180        Builds and returns the payload used when signing the JWT.
181        """
182        now = int(datetime.now().timestamp())
183        exp = now + self._token_duration if isinstance(self._token_duration, int) else now
184        issued_at = now - self.iat_backdate_seconds
185
186        payload = self._additional_jwt_payload.eval(self.config, json_loads=json.loads)
187        if any(prop in payload for prop in ["iss", "sub", "aud", "iat", "exp", "nbf"]):
188            raise ValueError(
189                "'iss', 'sub', 'aud', 'iat', 'exp', 'nbf' are reserved properties and should not be set as part of 'additional_jwt_payload'"
190            )
191
192        iss = self._eval_string(self._iss)
193        if iss is not None:
194            payload["iss"] = iss
195        sub = self._eval_string(self._sub)
196        if sub is not None:
197            payload["sub"] = sub
198        if self._aud:
199            payload["aud"] = self._aud.eval(self.config, json_loads=json.loads)
200
201        payload["iat"] = issued_at
202        payload["exp"] = exp
203        payload["nbf"] = issued_at
204        return payload
205
206    def _eval_string(self, value: Optional[InterpolatedString]) -> Optional[str]:
207        """
208        Evaluates a value that must stay a string: the `iss`, `sub` and `kid` claims, which RFC 7519
209        and RFC 7515 define as strings, and the secret key and passphrase.
210
211        Interpolation would turn a value that only looks numeric (an application, account or key ID,
212        or an all-digit secret or passphrase) into an int or float. PyJWT refuses a non-string key
213        and `kid`, and from 2.11 a non-string `iss`; older versions emit `iss` and `sub` as JSON
214        numbers. A missing config value renders as "None" (`config.get(...)`, or a null value) or as
215        an empty string (`config['...']` on a missing key), and both are returned as `None`.
216        """
217        if value is None:
218            return None
219        evaluated = value.eval(self.config, json_loads=json.loads, valid_types=(str,))
220        return None if evaluated in ("None", "") else cast(Optional[str], evaluated)
221
222    def _get_secret_key(self) -> JwtKeyTypes:
223        """
224        Returns the secret key used to sign the JWT.
225        """
226        secret_key = self._eval_string(self._secret_key)
227        if not secret_key:
228            raise AirbyteTracedException(
229                message=self._unusable_key_message(),
230                internal_message="Failed to sign token: the secret key is not set",
231                failure_type=FailureType.config_error,
232            )
233
234        if self._passphrase:
235            passphrase_value = self._eval_string(self._passphrase)
236            if passphrase_value:
237                try:
238                    private_key = serialization.load_pem_private_key(
239                        secret_key.encode(),
240                        password=passphrase_value.encode(),
241                    )
242                except (ValueError, TypeError) as e:
243                    raise AirbyteTracedException(
244                        message=self._unusable_key_message(),
245                        internal_message=f"Failed to load the private key: {e}",
246                        failure_type=FailureType.config_error,
247                    ) from e
248                return cast(JwtKeyTypes, private_key)
249
250        return (
251            base64.b64encode(secret_key.encode()).decode()
252            if self._base64_encode_secret_key
253            else secret_key
254        )
255
256    def _get_signed_token(self) -> Union[str, Any]:
257        """
258        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/
259        """
260        try:
261            return jwt.encode(
262                payload=self._get_jwt_payload(),
263                key=self._prepare_signing_key(self._get_secret_key()),
264                algorithm=self._algorithm,
265                headers=self._get_jwt_headers(),
266            )
267        except AirbyteTracedException:
268            raise
269        except Exception as e:
270            raise ValueError(f"Failed to sign token: {e}")
271
272    def _prepare_signing_key(self, key: JwtKeyTypes) -> Any:
273        """
274        Parses the key the way PyJWT would, so an unusable key is reported as a config error whichever
275        algorithm family it belongs to. PyJWT raises `InvalidKeyError` for an unparseable RSA key but
276        lets cryptography's `ValueError` through for EC and EdDSA keys. Before 2.11 it also accepts a
277        private key of the wrong family when parsing a PEM, and only rejects it, with a `TypeError`,
278        when it prepares the loaded key object again inside `jwt.encode`.
279        """
280        try:
281            algorithm = jwt.get_algorithm_by_name(self._algorithm)
282        except NotImplementedError:
283            # An unsupported algorithm is a manifest problem; `jwt.encode` reports it.
284            return key
285        try:
286            prepared = algorithm.prepare_key(key)
287            # Preparing the loaded key object runs the type check that PyJWT < 2.11 skips for PEM input.
288            algorithm.prepare_key(prepared)
289            # PyJWT accepts a public key, which can only verify, and fails later inside `jwt.encode`.
290            if isinstance(prepared, _PUBLIC_KEY_TYPES):
291                raise TypeError("a public key cannot sign a token")
292            return prepared
293        except (jwt.exceptions.InvalidKeyError, ValueError, TypeError) as e:
294            # PyJWT's messages talk about a "public key" even for a private one, so they stay internal.
295            raise AirbyteTracedException(
296                message=self._unusable_key_message(),
297                internal_message=f"Failed to sign token: {e}",
298                failure_type=FailureType.config_error,
299            ) from e
300
301    def _unusable_key_message(self) -> str:
302        """Returns the user-facing message for an unusable key, with a hint for the algorithm family."""
303        hint = (
304            _UNUSABLE_SECRET_HINT
305            if str(self._algorithm).startswith("HS")
306            else _UNUSABLE_PRIVATE_KEY_HINT
307        )
308        return _UNUSABLE_KEY_MESSAGE.format(algorithm=self._algorithm, hint=hint)
309
310    def _get_header_prefix(self) -> Union[str, None]:
311        """
312        Returns the header prefix to be used when attaching the token to the request.
313        """
314        return (
315            self._header_prefix.eval(self.config, json_loads=json.loads)
316            if self._header_prefix
317            else None
318        )
319
320    @property
321    def auth_header(self) -> str:
322        options = self._get_request_options(RequestOptionType.header)
323        return next(iter(options.keys()), "")
324
325    @property
326    def token(self) -> str:
327        return (
328            f"{self._get_header_prefix()} {self._get_signed_token()}"
329            if self._get_header_prefix()
330            else self._get_signed_token()
331        )
332
333    def get_request_params(self) -> Mapping[str, Any]:
334        return self._get_request_options(RequestOptionType.request_parameter)
335
336    def get_request_body_data(self) -> Union[Mapping[str, Any], str]:
337        return self._get_request_options(RequestOptionType.body_data)
338
339    def get_request_body_json(self) -> Mapping[str, Any]:
340        return self._get_request_options(RequestOptionType.body_json)
341
342    def _get_request_options(self, option_type: RequestOptionType) -> Mapping[str, Any]:
343        options: MutableMapping[str, Any] = {}
344        if self._request_option.inject_into == option_type:
345            self._request_option.inject_into_request(options, self.token, self.config)
346        return options
JwtKeyTypes = typing.Union[cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey, cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey, str, bytes]
class JwtAlgorithm(builtins.str):
50class JwtAlgorithm(str):
51    """
52    Enum for supported JWT algorithms
53    """
54
55    HS256 = "HS256"
56    HS384 = "HS384"
57    HS512 = "HS512"
58    ES256 = "ES256"
59    ES256K = "ES256K"
60    ES384 = "ES384"
61    ES512 = "ES512"
62    RS256 = "RS256"
63    RS384 = "RS384"
64    RS512 = "RS512"
65    PS256 = "PS256"
66    PS384 = "PS384"
67    PS512 = "PS512"
68    EdDSA = "EdDSA"

Enum for supported JWT algorithms

HS256 = 'HS256'
HS384 = 'HS384'
HS512 = 'HS512'
ES256 = 'ES256'
ES256K = 'ES256K'
ES384 = 'ES384'
ES512 = 'ES512'
RS256 = 'RS256'
RS384 = 'RS384'
RS512 = 'RS512'
PS256 = 'PS256'
PS384 = 'PS384'
PS512 = 'PS512'
EdDSA = 'EdDSA'
 71@dataclass
 72class JwtAuthenticator(DeclarativeAuthenticator):
 73    """
 74    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.
 75
 76    Attributes:
 77        config (Mapping[str, Any]): The user-provided configuration as specified by the source's spec
 78        secret_key (Union[InterpolatedString, str]): The secret key used to sign the JWT
 79        algorithm (Union[str, JwtAlgorithm]): The algorithm used to sign the JWT
 80        token_duration (Optional[int]): The duration in seconds for which the token is valid
 81        iat_backdate_seconds (int): Seconds to move `iat` and `nbf` into the past to tolerate clock drift; `exp` is unaffected
 82        base64_encode_secret_key (Optional[Union[InterpolatedBoolean, str, bool]]): Whether to base64 encode the secret key
 83        header_prefix (Optional[Union[InterpolatedString, str]]): The prefix to add to the Authorization header
 84        kid (Optional[Union[InterpolatedString, str]]): The key identifier to be included in the JWT header
 85        typ (Optional[Union[InterpolatedString, str]]): The type of the JWT.
 86        cty (Optional[Union[InterpolatedString, str]]): The content type of the JWT.
 87        iss (Optional[Union[InterpolatedString, str]]): The issuer of the JWT.
 88        sub (Optional[Union[InterpolatedString, str]]): The subject of the JWT.
 89        aud (Optional[Union[InterpolatedString, str]]): The audience of the JWT.
 90        additional_jwt_headers (Optional[Mapping[str, Any]]): Additional headers to include in the JWT.
 91        additional_jwt_payload (Optional[Mapping[str, Any]]): Additional payload to include in the JWT.
 92    """
 93
 94    config: Mapping[str, Any]
 95    parameters: InitVar[Mapping[str, Any]]
 96    secret_key: Union[InterpolatedString, str]
 97    algorithm: Union[str, JwtAlgorithm]
 98    token_duration: Optional[int]
 99    base64_encode_secret_key: Optional[Union[InterpolatedBoolean, str, bool]] = False
100    header_prefix: Optional[Union[InterpolatedString, str]] = None
101    kid: Optional[Union[InterpolatedString, str]] = None
102    typ: Optional[Union[InterpolatedString, str]] = None
103    cty: Optional[Union[InterpolatedString, str]] = None
104    iss: Optional[Union[InterpolatedString, str]] = None
105    sub: Optional[Union[InterpolatedString, str]] = None
106    aud: Optional[Union[InterpolatedString, str]] = None
107    additional_jwt_headers: Optional[Mapping[str, Any]] = None
108    additional_jwt_payload: Optional[Mapping[str, Any]] = None
109    passphrase: Optional[Union[InterpolatedString, str]] = None
110    request_option: Optional[RequestOption] = None
111    iat_backdate_seconds: int = 0
112
113    def __post_init__(self, parameters: Mapping[str, Any]) -> None:
114        self.iat_backdate_seconds = self.iat_backdate_seconds or 0
115        if self.iat_backdate_seconds < 0:
116            raise ValueError(
117                f"iat_backdate_seconds must be zero or positive, got {self.iat_backdate_seconds}"
118            )
119        self._secret_key = InterpolatedString.create(self.secret_key, parameters=parameters)
120        self._algorithm = (
121            JwtAlgorithm(self.algorithm) if isinstance(self.algorithm, str) else self.algorithm
122        )
123        self._base64_encode_secret_key = (
124            InterpolatedBoolean(self.base64_encode_secret_key, parameters=parameters)
125            if isinstance(self.base64_encode_secret_key, str)
126            else self.base64_encode_secret_key
127        )
128        self._token_duration = self.token_duration
129        self._header_prefix = (
130            InterpolatedString.create(self.header_prefix, parameters=parameters)
131            if self.header_prefix
132            else None
133        )
134        self._kid = InterpolatedString.create(self.kid, parameters=parameters) if self.kid else None
135        self._typ = InterpolatedString.create(self.typ, parameters=parameters) if self.typ else None
136        self._cty = InterpolatedString.create(self.cty, parameters=parameters) if self.cty else None
137        self._iss = InterpolatedString.create(self.iss, parameters=parameters) if self.iss else None
138        self._sub = InterpolatedString.create(self.sub, parameters=parameters) if self.sub else None
139        self._aud = InterpolatedString.create(self.aud, parameters=parameters) if self.aud else None
140        self._additional_jwt_headers = InterpolatedMapping(
141            self.additional_jwt_headers or {}, parameters=parameters
142        )
143        self._additional_jwt_payload = InterpolatedMapping(
144            self.additional_jwt_payload or {}, parameters=parameters
145        )
146        self._passphrase = (
147            InterpolatedString.create(self.passphrase, parameters=parameters)
148            if self.passphrase
149            else None
150        )
151
152        # When we first implemented the JWT authenticator, we assumed that the signed token was always supposed
153        # to be loaded into the request headers under the `Authorization` key. This is not always the case, but
154        # this default option allows for backwards compatibility to be retained for existing connectors
155        self._request_option = self.request_option or RequestOption(
156            inject_into=RequestOptionType.header, field_name="Authorization", parameters=parameters
157        )
158
159    def _get_jwt_headers(self) -> dict[str, Any]:
160        """
161        Builds and returns the headers used when signing the JWT.
162        """
163        headers = self._additional_jwt_headers.eval(self.config, json_loads=json.loads)
164        if any(prop in headers for prop in ["kid", "alg", "typ", "cty"]):
165            raise ValueError(
166                "'kid', 'alg', 'typ', 'cty' are reserved headers and should not be set as part of 'additional_jwt_headers'"
167            )
168
169        kid = self._eval_string(self._kid)
170        if kid is not None:
171            headers["kid"] = kid
172        if self._typ:
173            headers["typ"] = self._typ.eval(self.config, json_loads=json.loads)
174        if self._cty:
175            headers["cty"] = self._cty.eval(self.config, json_loads=json.loads)
176        headers["alg"] = self._algorithm
177        return headers
178
179    def _get_jwt_payload(self) -> dict[str, Any]:
180        """
181        Builds and returns the payload used when signing the JWT.
182        """
183        now = int(datetime.now().timestamp())
184        exp = now + self._token_duration if isinstance(self._token_duration, int) else now
185        issued_at = now - self.iat_backdate_seconds
186
187        payload = self._additional_jwt_payload.eval(self.config, json_loads=json.loads)
188        if any(prop in payload for prop in ["iss", "sub", "aud", "iat", "exp", "nbf"]):
189            raise ValueError(
190                "'iss', 'sub', 'aud', 'iat', 'exp', 'nbf' are reserved properties and should not be set as part of 'additional_jwt_payload'"
191            )
192
193        iss = self._eval_string(self._iss)
194        if iss is not None:
195            payload["iss"] = iss
196        sub = self._eval_string(self._sub)
197        if sub is not None:
198            payload["sub"] = sub
199        if self._aud:
200            payload["aud"] = self._aud.eval(self.config, json_loads=json.loads)
201
202        payload["iat"] = issued_at
203        payload["exp"] = exp
204        payload["nbf"] = issued_at
205        return payload
206
207    def _eval_string(self, value: Optional[InterpolatedString]) -> Optional[str]:
208        """
209        Evaluates a value that must stay a string: the `iss`, `sub` and `kid` claims, which RFC 7519
210        and RFC 7515 define as strings, and the secret key and passphrase.
211
212        Interpolation would turn a value that only looks numeric (an application, account or key ID,
213        or an all-digit secret or passphrase) into an int or float. PyJWT refuses a non-string key
214        and `kid`, and from 2.11 a non-string `iss`; older versions emit `iss` and `sub` as JSON
215        numbers. A missing config value renders as "None" (`config.get(...)`, or a null value) or as
216        an empty string (`config['...']` on a missing key), and both are returned as `None`.
217        """
218        if value is None:
219            return None
220        evaluated = value.eval(self.config, json_loads=json.loads, valid_types=(str,))
221        return None if evaluated in ("None", "") else cast(Optional[str], evaluated)
222
223    def _get_secret_key(self) -> JwtKeyTypes:
224        """
225        Returns the secret key used to sign the JWT.
226        """
227        secret_key = self._eval_string(self._secret_key)
228        if not secret_key:
229            raise AirbyteTracedException(
230                message=self._unusable_key_message(),
231                internal_message="Failed to sign token: the secret key is not set",
232                failure_type=FailureType.config_error,
233            )
234
235        if self._passphrase:
236            passphrase_value = self._eval_string(self._passphrase)
237            if passphrase_value:
238                try:
239                    private_key = serialization.load_pem_private_key(
240                        secret_key.encode(),
241                        password=passphrase_value.encode(),
242                    )
243                except (ValueError, TypeError) as e:
244                    raise AirbyteTracedException(
245                        message=self._unusable_key_message(),
246                        internal_message=f"Failed to load the private key: {e}",
247                        failure_type=FailureType.config_error,
248                    ) from e
249                return cast(JwtKeyTypes, private_key)
250
251        return (
252            base64.b64encode(secret_key.encode()).decode()
253            if self._base64_encode_secret_key
254            else secret_key
255        )
256
257    def _get_signed_token(self) -> Union[str, Any]:
258        """
259        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/
260        """
261        try:
262            return jwt.encode(
263                payload=self._get_jwt_payload(),
264                key=self._prepare_signing_key(self._get_secret_key()),
265                algorithm=self._algorithm,
266                headers=self._get_jwt_headers(),
267            )
268        except AirbyteTracedException:
269            raise
270        except Exception as e:
271            raise ValueError(f"Failed to sign token: {e}")
272
273    def _prepare_signing_key(self, key: JwtKeyTypes) -> Any:
274        """
275        Parses the key the way PyJWT would, so an unusable key is reported as a config error whichever
276        algorithm family it belongs to. PyJWT raises `InvalidKeyError` for an unparseable RSA key but
277        lets cryptography's `ValueError` through for EC and EdDSA keys. Before 2.11 it also accepts a
278        private key of the wrong family when parsing a PEM, and only rejects it, with a `TypeError`,
279        when it prepares the loaded key object again inside `jwt.encode`.
280        """
281        try:
282            algorithm = jwt.get_algorithm_by_name(self._algorithm)
283        except NotImplementedError:
284            # An unsupported algorithm is a manifest problem; `jwt.encode` reports it.
285            return key
286        try:
287            prepared = algorithm.prepare_key(key)
288            # Preparing the loaded key object runs the type check that PyJWT < 2.11 skips for PEM input.
289            algorithm.prepare_key(prepared)
290            # PyJWT accepts a public key, which can only verify, and fails later inside `jwt.encode`.
291            if isinstance(prepared, _PUBLIC_KEY_TYPES):
292                raise TypeError("a public key cannot sign a token")
293            return prepared
294        except (jwt.exceptions.InvalidKeyError, ValueError, TypeError) as e:
295            # PyJWT's messages talk about a "public key" even for a private one, so they stay internal.
296            raise AirbyteTracedException(
297                message=self._unusable_key_message(),
298                internal_message=f"Failed to sign token: {e}",
299                failure_type=FailureType.config_error,
300            ) from e
301
302    def _unusable_key_message(self) -> str:
303        """Returns the user-facing message for an unusable key, with a hint for the algorithm family."""
304        hint = (
305            _UNUSABLE_SECRET_HINT
306            if str(self._algorithm).startswith("HS")
307            else _UNUSABLE_PRIVATE_KEY_HINT
308        )
309        return _UNUSABLE_KEY_MESSAGE.format(algorithm=self._algorithm, hint=hint)
310
311    def _get_header_prefix(self) -> Union[str, None]:
312        """
313        Returns the header prefix to be used when attaching the token to the request.
314        """
315        return (
316            self._header_prefix.eval(self.config, json_loads=json.loads)
317            if self._header_prefix
318            else None
319        )
320
321    @property
322    def auth_header(self) -> str:
323        options = self._get_request_options(RequestOptionType.header)
324        return next(iter(options.keys()), "")
325
326    @property
327    def token(self) -> str:
328        return (
329            f"{self._get_header_prefix()} {self._get_signed_token()}"
330            if self._get_header_prefix()
331            else self._get_signed_token()
332        )
333
334    def get_request_params(self) -> Mapping[str, Any]:
335        return self._get_request_options(RequestOptionType.request_parameter)
336
337    def get_request_body_data(self) -> Union[Mapping[str, Any], str]:
338        return self._get_request_options(RequestOptionType.body_data)
339
340    def get_request_body_json(self) -> Mapping[str, Any]:
341        return self._get_request_options(RequestOptionType.body_json)
342
343    def _get_request_options(self, option_type: RequestOptionType) -> Mapping[str, Any]:
344        options: MutableMapping[str, Any] = {}
345        if self._request_option.inject_into == option_type:
346            self._request_option.inject_into_request(options, self.token, self.config)
347        return options

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.

Attributes:
  • config (Mapping[str, Any]): The user-provided configuration as specified by the source's spec
  • secret_key (Union[InterpolatedString, str]): The secret key used to sign the JWT
  • algorithm (Union[str, JwtAlgorithm]): The algorithm used to sign the JWT
  • token_duration (Optional[int]): The duration in seconds for which the token is valid
  • iat_backdate_seconds (int): Seconds to move iat and nbf into the past to tolerate clock drift; exp is unaffected
  • base64_encode_secret_key (Optional[Union[InterpolatedBoolean, str, bool]]): Whether to base64 encode the secret key
  • header_prefix (Optional[Union[InterpolatedString, str]]): The prefix to add to the Authorization header
  • kid (Optional[Union[InterpolatedString, str]]): The key identifier to be included in the JWT header
  • typ (Optional[Union[InterpolatedString, str]]): The type of the JWT.
  • cty (Optional[Union[InterpolatedString, str]]): The content type of the JWT.
  • iss (Optional[Union[InterpolatedString, str]]): The issuer of the JWT.
  • sub (Optional[Union[InterpolatedString, str]]): The subject of the JWT.
  • aud (Optional[Union[InterpolatedString, str]]): The audience of the JWT.
  • additional_jwt_headers (Optional[Mapping[str, Any]]): Additional headers to include in the JWT.
  • additional_jwt_payload (Optional[Mapping[str, Any]]): Additional payload to include in the JWT.
JwtAuthenticator( config: Mapping[str, Any], parameters: dataclasses.InitVar[typing.Mapping[str, typing.Any]], secret_key: Union[airbyte_cdk.InterpolatedString, str], algorithm: Union[str, JwtAlgorithm], token_duration: Optional[int], base64_encode_secret_key: Union[airbyte_cdk.InterpolatedBoolean, str, bool, NoneType] = False, header_prefix: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, kid: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, typ: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, cty: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, iss: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, sub: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, aud: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, additional_jwt_headers: Optional[Mapping[str, Any]] = None, additional_jwt_payload: Optional[Mapping[str, Any]] = None, passphrase: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None, request_option: Optional[airbyte_cdk.RequestOption] = None, iat_backdate_seconds: int = 0)
config: Mapping[str, Any]
parameters: dataclasses.InitVar[typing.Mapping[str, typing.Any]]
secret_key: Union[airbyte_cdk.InterpolatedString, str]
algorithm: Union[str, JwtAlgorithm]
token_duration: Optional[int]
base64_encode_secret_key: Union[airbyte_cdk.InterpolatedBoolean, str, bool, NoneType] = False
header_prefix: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
kid: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
typ: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
cty: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
iss: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
sub: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
aud: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
additional_jwt_headers: Optional[Mapping[str, Any]] = None
additional_jwt_payload: Optional[Mapping[str, Any]] = None
passphrase: Union[airbyte_cdk.InterpolatedString, str, NoneType] = None
request_option: Optional[airbyte_cdk.RequestOption] = None
iat_backdate_seconds: int = 0
auth_header: str
321    @property
322    def auth_header(self) -> str:
323        options = self._get_request_options(RequestOptionType.header)
324        return next(iter(options.keys()), "")

HTTP header to set on the requests

token: str
326    @property
327    def token(self) -> str:
328        return (
329            f"{self._get_header_prefix()} {self._get_signed_token()}"
330            if self._get_header_prefix()
331            else self._get_signed_token()
332        )

The header value to set on outgoing HTTP requests

def get_request_params(self) -> Mapping[str, Any]:
334    def get_request_params(self) -> Mapping[str, Any]:
335        return self._get_request_options(RequestOptionType.request_parameter)

HTTP request parameter to add to the requests

def get_request_body_data(self) -> Union[Mapping[str, Any], str]:
337    def get_request_body_data(self) -> Union[Mapping[str, Any], str]:
338        return self._get_request_options(RequestOptionType.body_data)

Form-encoded body data to set on the requests

def get_request_body_json(self) -> Mapping[str, Any]:
340    def get_request_body_json(self) -> Mapping[str, Any]:
341        return self._get_request_options(RequestOptionType.body_json)

JSON-encoded body data to set on the requests