airbyte_cdk.sources.declarative.parsers.custom_code_compiler

Contains functions to compile custom code from text.

  1"""Contains functions to compile custom code from text."""
  2
  3import hashlib
  4import os
  5import sys
  6from collections.abc import Mapping
  7from types import ModuleType
  8from typing import Any, Literal, cast
  9
 10ChecksumType = Literal["md5", "sha256"]
 11CHECKSUM_FUNCTIONS = {
 12    "md5": hashlib.md5,
 13    "sha256": hashlib.sha256,
 14}
 15COMPONENTS_MODULE_NAME = "components"
 16SDM_COMPONENTS_MODULE_NAME = "source_declarative_manifest.components"
 17INJECTED_MANIFEST = "__injected_declarative_manifest"
 18INJECTED_COMPONENTS_PY = "__injected_components_py"
 19INJECTED_COMPONENTS_PY_CHECKSUMS = "__injected_components_py_checksums"
 20ENV_VAR_ALLOW_CUSTOM_CODE = "AIRBYTE_ENABLE_UNSAFE_CODE"
 21
 22
 23class AirbyteCodeTamperedError(Exception):
 24    """Raised when the connector's components module does not match its checksum.
 25
 26    This is a fatal error, as it can be a sign of code tampering.
 27    """
 28
 29
 30class AirbyteCustomCodeNotPermittedError(Exception):
 31    """Raised when custom code is attempted to be run in an environment that does not support it."""
 32
 33    def __init__(self) -> None:
 34        super().__init__(
 35            "Custom connector code is not permitted in this environment. "
 36            "If you need to run custom code, please ask your administrator to set the `AIRBYTE_ENABLE_UNSAFE_CODE` "
 37            "environment variable to 'true' in your Airbyte environment. "
 38            "If you see this message in Airbyte Cloud, your workspace does not allow executing "
 39            "custom connector code."
 40        )
 41
 42
 43def _hash_text(input_text: str, hash_type: str = "md5") -> str:
 44    """Return the hash of the input text using the specified hash type."""
 45    if not input_text:
 46        raise ValueError("Hash input text cannot be empty.")
 47
 48    hash_object = CHECKSUM_FUNCTIONS[hash_type]()
 49    hash_object.update(input_text.encode())
 50    return hash_object.hexdigest()
 51
 52
 53def custom_code_execution_permitted() -> bool:
 54    """Return `True` if custom code execution is permitted, otherwise `False`.
 55
 56    Custom code execution is permitted if the `AIRBYTE_ENABLE_UNSAFE_CODE` environment variable is set to 'true'.
 57    """
 58    return os.environ.get(ENV_VAR_ALLOW_CUSTOM_CODE, "").lower() == "true"
 59
 60
 61def validate_python_code(
 62    code_text: str,
 63    checksums: dict[str, str] | None,
 64) -> None:
 65    """Validate the provided Python code text against the provided checksums.
 66
 67    Currently we fail if no checksums are provided, although this may change in the future.
 68    """
 69    if not code_text:
 70        # No code provided, nothing to validate.
 71        return
 72
 73    if not checksums:
 74        raise ValueError(f"A checksum is required to validate the code. Received: {checksums}")
 75
 76    for checksum_type, checksum in checksums.items():
 77        if checksum_type not in CHECKSUM_FUNCTIONS:
 78            raise ValueError(
 79                f"Unsupported checksum type: {checksum_type}. Supported checksum types are: {CHECKSUM_FUNCTIONS.keys()}"
 80            )
 81
 82        calculated_checksum = _hash_text(code_text, checksum_type)
 83        if calculated_checksum != checksum:
 84            raise AirbyteCodeTamperedError(
 85                f"{checksum_type} checksum does not match."
 86                + str(
 87                    {
 88                        "expected_checksum": checksum,
 89                        "actual_checksum": calculated_checksum,
 90                    }
 91                ),
 92            )
 93
 94
 95def get_registered_components_module(
 96    config: Mapping[str, Any] | None,
 97) -> ModuleType | None:
 98    """Get a components module object based on the provided config.
 99
100    If custom python components is provided, this will be loaded. Otherwise, we will
101    attempt to load from the `components` module already imported/registered in sys.modules.
102
103    If custom `components.py` text is provided in config, it will be registered with sys.modules
104    so that it can be later imported by manifest declarations which reference the provided classes.
105
106    Returns `None` if no components is provided and the `components` module is not found.
107    """
108    if config and config.get(INJECTED_COMPONENTS_PY, None):
109        if not custom_code_execution_permitted():
110            raise AirbyteCustomCodeNotPermittedError
111
112        # Create a new module object and execute the provided Python code text within it
113        python_text: str = config[INJECTED_COMPONENTS_PY]
114        return register_components_module_from_string(
115            components_py_text=python_text,
116            checksums=config.get(INJECTED_COMPONENTS_PY_CHECKSUMS, None),
117        )
118
119    # Check for `components` or `source_declarative_manifest.components`.
120    if SDM_COMPONENTS_MODULE_NAME in sys.modules:
121        return cast(ModuleType, sys.modules.get(SDM_COMPONENTS_MODULE_NAME))
122
123    if COMPONENTS_MODULE_NAME in sys.modules:
124        return cast(ModuleType, sys.modules.get(COMPONENTS_MODULE_NAME))
125
126    # Could not find module 'components' in `sys.modules`
127    # and INJECTED_COMPONENTS_PY was not provided in config.
128    return None
129
130
131def register_components_module_from_string(
132    components_py_text: str,
133    checksums: dict[str, Any] | None,
134) -> ModuleType:
135    """Load and return the components module from a provided string containing the python code."""
136    # First validate the code
137    validate_python_code(
138        code_text=components_py_text,
139        checksums=checksums,
140    )
141
142    # Create a new module object
143    components_module = ModuleType(name=COMPONENTS_MODULE_NAME)
144
145    # Execute the module text in the module's namespace
146    exec(components_py_text, components_module.__dict__)
147
148    # Register the module in `sys.modules`` so it can be imported as
149    # `source_declarative_manifest.components` and/or `components`.
150    sys.modules[SDM_COMPONENTS_MODULE_NAME] = components_module
151    sys.modules[COMPONENTS_MODULE_NAME] = components_module
152
153    # Now you can import and use the module
154    return components_module
ChecksumType = typing.Literal['md5', 'sha256']
CHECKSUM_FUNCTIONS = {'md5': <built-in function openssl_md5>, 'sha256': <built-in function openssl_sha256>}
COMPONENTS_MODULE_NAME = 'components'
SDM_COMPONENTS_MODULE_NAME = 'source_declarative_manifest.components'
INJECTED_MANIFEST = '__injected_declarative_manifest'
INJECTED_COMPONENTS_PY = '__injected_components_py'
INJECTED_COMPONENTS_PY_CHECKSUMS = '__injected_components_py_checksums'
ENV_VAR_ALLOW_CUSTOM_CODE = 'AIRBYTE_ENABLE_UNSAFE_CODE'
class AirbyteCodeTamperedError(builtins.Exception):
24class AirbyteCodeTamperedError(Exception):
25    """Raised when the connector's components module does not match its checksum.
26
27    This is a fatal error, as it can be a sign of code tampering.
28    """

Raised when the connector's components module does not match its checksum.

This is a fatal error, as it can be a sign of code tampering.

class AirbyteCustomCodeNotPermittedError(builtins.Exception):
31class AirbyteCustomCodeNotPermittedError(Exception):
32    """Raised when custom code is attempted to be run in an environment that does not support it."""
33
34    def __init__(self) -> None:
35        super().__init__(
36            "Custom connector code is not permitted in this environment. "
37            "If you need to run custom code, please ask your administrator to set the `AIRBYTE_ENABLE_UNSAFE_CODE` "
38            "environment variable to 'true' in your Airbyte environment. "
39            "If you see this message in Airbyte Cloud, your workspace does not allow executing "
40            "custom connector code."
41        )

Raised when custom code is attempted to be run in an environment that does not support it.

def custom_code_execution_permitted() -> bool:
54def custom_code_execution_permitted() -> bool:
55    """Return `True` if custom code execution is permitted, otherwise `False`.
56
57    Custom code execution is permitted if the `AIRBYTE_ENABLE_UNSAFE_CODE` environment variable is set to 'true'.
58    """
59    return os.environ.get(ENV_VAR_ALLOW_CUSTOM_CODE, "").lower() == "true"

Return True if custom code execution is permitted, otherwise False.

Custom code execution is permitted if the AIRBYTE_ENABLE_UNSAFE_CODE environment variable is set to 'true'.

def validate_python_code(code_text: str, checksums: dict[str, str] | None) -> None:
62def validate_python_code(
63    code_text: str,
64    checksums: dict[str, str] | None,
65) -> None:
66    """Validate the provided Python code text against the provided checksums.
67
68    Currently we fail if no checksums are provided, although this may change in the future.
69    """
70    if not code_text:
71        # No code provided, nothing to validate.
72        return
73
74    if not checksums:
75        raise ValueError(f"A checksum is required to validate the code. Received: {checksums}")
76
77    for checksum_type, checksum in checksums.items():
78        if checksum_type not in CHECKSUM_FUNCTIONS:
79            raise ValueError(
80                f"Unsupported checksum type: {checksum_type}. Supported checksum types are: {CHECKSUM_FUNCTIONS.keys()}"
81            )
82
83        calculated_checksum = _hash_text(code_text, checksum_type)
84        if calculated_checksum != checksum:
85            raise AirbyteCodeTamperedError(
86                f"{checksum_type} checksum does not match."
87                + str(
88                    {
89                        "expected_checksum": checksum,
90                        "actual_checksum": calculated_checksum,
91                    }
92                ),
93            )

Validate the provided Python code text against the provided checksums.

Currently we fail if no checksums are provided, although this may change in the future.

def get_registered_components_module(config: Mapping[str, typing.Any] | None) -> module | None:
 96def get_registered_components_module(
 97    config: Mapping[str, Any] | None,
 98) -> ModuleType | None:
 99    """Get a components module object based on the provided config.
100
101    If custom python components is provided, this will be loaded. Otherwise, we will
102    attempt to load from the `components` module already imported/registered in sys.modules.
103
104    If custom `components.py` text is provided in config, it will be registered with sys.modules
105    so that it can be later imported by manifest declarations which reference the provided classes.
106
107    Returns `None` if no components is provided and the `components` module is not found.
108    """
109    if config and config.get(INJECTED_COMPONENTS_PY, None):
110        if not custom_code_execution_permitted():
111            raise AirbyteCustomCodeNotPermittedError
112
113        # Create a new module object and execute the provided Python code text within it
114        python_text: str = config[INJECTED_COMPONENTS_PY]
115        return register_components_module_from_string(
116            components_py_text=python_text,
117            checksums=config.get(INJECTED_COMPONENTS_PY_CHECKSUMS, None),
118        )
119
120    # Check for `components` or `source_declarative_manifest.components`.
121    if SDM_COMPONENTS_MODULE_NAME in sys.modules:
122        return cast(ModuleType, sys.modules.get(SDM_COMPONENTS_MODULE_NAME))
123
124    if COMPONENTS_MODULE_NAME in sys.modules:
125        return cast(ModuleType, sys.modules.get(COMPONENTS_MODULE_NAME))
126
127    # Could not find module 'components' in `sys.modules`
128    # and INJECTED_COMPONENTS_PY was not provided in config.
129    return None

Get a components module object based on the provided config.

If custom python components is provided, this will be loaded. Otherwise, we will attempt to load from the components module already imported/registered in sys.modules.

If custom components.py text is provided in config, it will be registered with sys.modules so that it can be later imported by manifest declarations which reference the provided classes.

Returns None if no components is provided and the components module is not found.

def register_components_module_from_string( components_py_text: str, checksums: dict[str, typing.Any] | None) -> module:
132def register_components_module_from_string(
133    components_py_text: str,
134    checksums: dict[str, Any] | None,
135) -> ModuleType:
136    """Load and return the components module from a provided string containing the python code."""
137    # First validate the code
138    validate_python_code(
139        code_text=components_py_text,
140        checksums=checksums,
141    )
142
143    # Create a new module object
144    components_module = ModuleType(name=COMPONENTS_MODULE_NAME)
145
146    # Execute the module text in the module's namespace
147    exec(components_py_text, components_module.__dict__)
148
149    # Register the module in `sys.modules`` so it can be imported as
150    # `source_declarative_manifest.components` and/or `components`.
151    sys.modules[SDM_COMPONENTS_MODULE_NAME] = components_module
152    sys.modules[COMPONENTS_MODULE_NAME] = components_module
153
154    # Now you can import and use the module
155    return components_module

Load and return the components module from a provided string containing the python code.