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