diff --git a/.github/workflows/kms_encryption_integration_tests.yml b/.github/workflows/kms_encryption_integration_tests.yml new file mode 100644 index 000000000..70d92e99f --- /dev/null +++ b/.github/workflows/kms_encryption_integration_tests.yml @@ -0,0 +1,264 @@ +name: KMS Encryption Integration Tests + +# The LocalStack job needs no AWS account and no secrets, so it also runs on pull requests from forks. +# The real-key and Aurora jobs read the key ARN, its region and the roles from repository variables, +# which an administrator sets up once; CI never creates or changes KMS keys. +# On a push to main they run only when the variables they need are set, so main stays green until then; +# a manual run of either fails when KMS_KEY_ARN is missing. + +on: + pull_request: + paths: + - 'aws_advanced_python_wrapper/**' + - 'tests/integration/**' + - 'pyproject.toml' + - 'poetry.lock' + - '.github/workflows/kms_encryption_integration_tests.yml' + push: + branches: [ main ] + paths: + - 'aws_advanced_python_wrapper/**' + - 'tests/integration/**' + - 'pyproject.toml' + - 'poetry.lock' + - '.github/workflows/kms_encryption_integration_tests.yml' + workflow_dispatch: + inputs: + lane: + description: 'Which KMS environment to run' + type: choice + options: [ localstack, real-kms, aurora ] + default: localstack + +permissions: + contents: read + +concurrency: + # Each push has its own group, so a long Aurora job never holds back or cancels a later push's other jobs. + group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.lane }}-${{ github.event_name == 'push' && github.sha || '' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + kms-localstack: + name: Run KMS Encryption Tests with LocalStack + if: github.event_name != 'workflow_dispatch' || inputs.lane == 'localstack' + runs-on: ubuntu-latest + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: + - { engine: pg, skip: mysql } + - { engine: mysql, skip: pg } + + steps: + - name: 'Clone repository' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + + - name: 'Set up JDK 8' + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 + with: + distribution: 'corretto' + java-version: 8 + + - name: 'Set up Python 3.12' + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install poetry + shell: bash + run: | + pipx install poetry==1.8.2 + poetry config virtualenvs.prefer-active-python true + + - name: Install dependencies + run: poetry install + + - name: 'Run the KMS tests on Docker with LocalStack' + run: | + DB_PASSWORD="$(openssl rand -hex 16)" + echo "::add-mask::${DB_PASSWORD}" + export DB_PASSWORD DB_USERNAME=test_user DB_DATABASE_NAME=test_db + ./gradlew --no-parallel --no-daemon test-kms-encryption-docker \ + -Dexclude-${{ matrix.skip }}-engine=true -Dexclude-${{ matrix.skip }}-driver=true + + # pytest exits 0 when every test is skipped, so count the KMS test cases that ran. + - name: 'Fail when no KMS test ran' + run: | + python3 -c 'import glob,sys,xml.etree.ElementTree as E; c=[t for f in glob.glob("tests/integration/container/reports/*.xml") for t in E.parse(f).iter("testcase") if "kms_encryption" in t.get("classname","") and t.find("skipped") is None]; print("KMS tests run:", len(c)); sys.exit(0 if c else 1)' + + - name: 'Archive results' + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: kms-localstack-${{ matrix.engine }} + path: ./tests/integration/container/reports + retention-days: 5 + + kms-real-key: + name: Run KMS Encryption Tests with a real KMS key + if: >- + (github.event_name == 'push' && github.ref == 'refs/heads/main' + && vars.KMS_KEY_ARN != '' && vars.KMS_REGION != '' && vars.KMS_DECRYPT_ONLY_ROLE_ARN != '' && vars.KMS_IT_ROLE_ARN != '') + || inputs.lane == 'real-kms' + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + id-token: write # This is required for requesting the JWT + contents: read # This is required for actions/checkout + strategy: + fail-fast: false + matrix: + include: + - { engine: pg, skip: mysql } + - { engine: mysql, skip: pg } + + steps: + - name: 'Clone repository' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + + - name: 'Set up JDK 8' + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 + with: + distribution: 'corretto' + java-version: 8 + + - name: 'Set up Python 3.12' + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install poetry + shell: bash + run: | + pipx install poetry==1.8.2 + poetry config virtualenvs.prefer-active-python true + + - name: Install dependencies + run: poetry install + + - name: 'Configure AWS Credentials' + uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6 + with: + role-to-assume: ${{ vars.KMS_IT_ROLE_ARN }} + role-session-name: python_kms_integration_tests + role-duration-seconds: 3600 + aws-region: ${{ vars.KMS_REGION }} + + - name: 'Run the KMS tests on Docker with a real KMS key' + run: | + test -n "${KMS_KEY_ARN}" || { echo "::error::Set the KMS_KEY_ARN repository variable: CI uses the administrator's key and never makes one."; exit 1; } + DB_PASSWORD="$(openssl rand -hex 16)" + echo "::add-mask::${DB_PASSWORD}" + export DB_PASSWORD DB_USERNAME=test_user DB_DATABASE_NAME=test_db + ./gradlew --no-parallel --no-daemon test-kms-encryption-docker-kms \ + -Dexclude-${{ matrix.skip }}-engine=true -Dexclude-${{ matrix.skip }}-driver=true + env: + KMS_KEY_ARN: ${{ vars.KMS_KEY_ARN }} + KMS_REGION: ${{ vars.KMS_REGION }} + KMS_DECRYPT_ONLY_ROLE_ARN: ${{ vars.KMS_DECRYPT_ONLY_ROLE_ARN }} + + - name: 'Fail when no KMS test ran' + run: | + python3 -c 'import glob,sys,xml.etree.ElementTree as E; c=[t for f in glob.glob("tests/integration/container/reports/*.xml") for t in E.parse(f).iter("testcase") if "kms_encryption" in t.get("classname","") and t.find("skipped") is None]; print("KMS tests run:", len(c)); sys.exit(0 if c else 1)' + + - name: 'Archive results' + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: kms-real-key-${{ matrix.engine }} + path: ./tests/integration/container/reports + retention-days: 5 + + kms-aurora: + name: Run KMS Encryption Tests on Aurora + if: >- + (github.event_name == 'push' && github.ref == 'refs/heads/main' && vars.KMS_KEY_ARN != '' && vars.KMS_REGION != '') + || inputs.lane == 'aurora' + runs-on: ubuntu-latest + timeout-minutes: 150 + permissions: + id-token: write # This is required for requesting the JWT + contents: read # This is required for actions/checkout + strategy: + fail-fast: false + matrix: + include: + - { engine: pg, skip: mysql } + - { engine: mysql, skip: pg } + concurrency: + group: kms-aurora-${{ matrix.engine }} + cancel-in-progress: false + env: + # The harness doesn't delete its cluster when a run is cancelled, so the last step deletes this one by name. + RDS_DB_NAME: kms-it-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.engine }} + + steps: + - name: 'Clone repository' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + + - name: 'Set up JDK 8' + uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5 + with: + distribution: 'corretto' + java-version: 8 + + - name: 'Set up Python 3.12' + uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + + - name: Install poetry + shell: bash + run: | + pipx install poetry==1.8.2 + poetry config virtualenvs.prefer-active-python true + + - name: Install dependencies + run: poetry install + + - name: 'Configure AWS Credentials' + uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6 + with: + role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/${{ secrets.AWS_DEPLOY_ROLE }} + role-session-name: python_integration_tests + role-duration-seconds: 21600 + aws-region: ${{ secrets.AWS_DEFAULT_REGION }} + + - name: 'Run the KMS tests on Aurora' + run: | + test -n "${KMS_KEY_ARN}" || { echo "::error::Set the KMS_KEY_ARN repository variable: CI uses the administrator's key and never makes one."; exit 1; } + DB_PASSWORD="$(openssl rand -hex 16)" + echo "::add-mask::${DB_PASSWORD}" + export DB_PASSWORD DB_USERNAME=test_user DB_DATABASE_NAME=test_db + ./gradlew --no-parallel --no-daemon test-kms-encryption-aurora \ + -Dexclude-${{ matrix.skip }}-engine=true -Dexclude-${{ matrix.skip }}-driver=true + env: + NUM_INSTANCES: 2 + RDS_DB_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + KMS_KEY_ARN: ${{ vars.KMS_KEY_ARN }} + KMS_REGION: ${{ vars.KMS_REGION }} + + - name: 'Fail when no KMS test ran' + run: | + python3 -c 'import glob,sys,xml.etree.ElementTree as E; c=[t for f in glob.glob("tests/integration/container/reports/*.xml") for t in E.parse(f).iter("testcase") if "kms_encryption" in t.get("classname","") and t.find("skipped") is None]; print("KMS tests run:", len(c)); sys.exit(0 if c else 1)' + + - name: 'Archive results' + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: kms-aurora-${{ matrix.engine }} + path: ./tests/integration/container/reports + retention-days: 5 + + # Deletes the cluster named RDS_DB_NAME and its member instances, never clusters matched by a name prefix. + - name: 'Delete the cluster of this run' + if: always() + run: | + instances="$(aws rds describe-db-clusters --db-cluster-identifier "${RDS_DB_NAME}" \ + --query 'DBClusters[0].DBClusterMembers[].DBInstanceIdentifier' --output text 2>/dev/null)" || exit 0 + for instance in ${instances}; do + aws rds delete-db-instance --db-instance-identifier "${instance}" --skip-final-snapshot > /dev/null || true + done + aws rds delete-db-cluster --db-cluster-identifier "${RDS_DB_NAME}" --skip-final-snapshot > /dev/null || true diff --git a/CHANGELOG.md b/CHANGELOG.md index c311cb515..001c4b3ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### :magic_wand: Added * The `connection_lifetime` plugin, bounding how long a physical connection is used. Once `connection_lifetime_ms` has elapsed, the next network-bound call either closes the connection or reconnects through the host the application originally supplied, depending on `connection_lifetime_action`. Expiration is deferred while a transaction is open, and reports through `ConnectionLifetimeSuccessError`, `ConnectionLifetimeExpiredError` or `ConnectionLifetimeFailedError` so a connection pool can tell a usable connection from a dead one. With an internal connection pool, the plugin evicts an expired connection so the pool closes it instead of handing it out again. Available in both the synchronous and asynchronous wrapper. See [Connection Lifetime Plugin](./docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md). +* Synchronous plugins can replace the arguments that `Cursor.execute` and `Cursor.executemany` pass to the plugins after them and to the target driver, without modifying the caller's objects, by assigning new `args` and `kwargs` to the plugin service's `current_call_context`. See [The Call Context](./docs/development-guide/PluginService.md#the-call-context). ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) * The `failover` and `failover_v2` plugins currently rewraps all errors to an AwsWrapperError even when the errors do not trigger failover. Set the `preserve_driver_exception_type` configuration parameter to `True` to re-raise the target driver errors as-is for the failover plugins. Failover errors are unaffected and are still raised as `FailoverSuccessError`, `FailoverFailedError` or `TransactionResolutionUnknownError`. This is useful for ORMs to properly classify the errors. ([Issue #1275](https://github.com/aws/aws-advanced-python-wrapper/issues/1275)) +* KMS Encryption Plugin (`kms_encryption`), which encrypts the values an application binds for columns configured in the database's encryption metadata before the driver sends them, and decrypts them on read, with each column's data key protected by an AWS KMS master key. Install it with `pip install "aws-advanced-python-wrapper[encryption]"`, and add a database-side trigger to every encrypted column with the trigger SQL that ships in `aws_advanced_python_wrapper/encryption/sql`. The plugin works with the synchronous wrapper only. See [KMS Encryption Plugin](./docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md). ([PR #1331](https://github.com/aws/aws-advanced-python-wrapper/pull/1331)) + +### :bug: Fixed +* With psycopg's synchronous cursor, a fetch chained onto `cursor.execute()` (`cursor.execute(query).fetchone()`) skipped every plugin, the failover and host monitoring plugins included, because `execute()` returned the driver's cursor. It now returns the wrapper's cursor, so `isinstance(cursor.execute(query), psycopg.Cursor)` is now `False`. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) +* `next(cursor)` on a synchronous cursor raised `TypeError`. It now returns the next row through the plugins subscribed to `Cursor.__next__`. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) +* Loops over a synchronous cursor (`for row in cursor`) skipped every plugin. A loop now calls the plugins subscribed to `Cursor.__iter__`, and those subscribed to every method, such as `execute_time`, once per loop, not once per row. A loop over a cursor whose connection is no longer the current one now raises `AwsWrapperError` where `fetchone` does. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) ## [3.1.0] - 2026-08-24 ### :magic_wand: Added diff --git a/aws_advanced_python_wrapper/driver_dialect.py b/aws_advanced_python_wrapper/driver_dialect.py index c667316b5..03fa09304 100644 --- a/aws_advanced_python_wrapper/driver_dialect.py +++ b/aws_advanced_python_wrapper/driver_dialect.py @@ -131,7 +131,9 @@ def execute( exec_timeout: Optional[float] = None, conn: Optional[Connection] = None, **kwargs: Any) -> Cursor: - if DbApiMethod.ALL.method_name not in self.network_bound_methods and method_name not in self.network_bound_methods: + # Cursor.__iter__ only creates the driver's iterator; the rows are fetched outside this call. + if method_name == DbApiMethod.CURSOR_ITER.method_name or ( + DbApiMethod.ALL.method_name not in self.network_bound_methods and method_name not in self.network_bound_methods): return exec_func() if exec_timeout is None: diff --git a/aws_advanced_python_wrapper/driver_dialect_manager.py b/aws_advanced_python_wrapper/driver_dialect_manager.py index dd71de40b..a7a2e3257 100644 --- a/aws_advanced_python_wrapper/driver_dialect_manager.py +++ b/aws_advanced_python_wrapper/driver_dialect_manager.py @@ -14,7 +14,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Callable, Dict, Optional, Protocol, Union +from typing import (TYPE_CHECKING, Any, Callable, Dict, Optional, Protocol, + Union) if TYPE_CHECKING: from aws_advanced_python_wrapper.connection_provider import ConnectionProvider @@ -75,21 +76,9 @@ def get_dialect(self, conn_func: Callable, props: Properties) -> DriverDialect: else: logger.warning("DriverDialectManager.CustomDialectNotSupported") - result: Optional[str] dialect_code: Optional[str] = WrapperProperties.DRIVER_DIALECT.get(props) if dialect_code: - result = DriverDialectManager.known_dialects_by_code.get(dialect_code) - if result is None: - raise AwsWrapperError(Messages.get_formatted( - "DriverDialectManager.UnknownDialectCode", - dialect_code)) - self._log_dialect(dialect_code, result) - dialect = Utils.initialize_class(result, props) - if dialect is None: - raise AwsWrapperError(Messages.get_formatted( - "DriverDialectManager.InitializationError", - dialect_code)) - return dialect + return self._get_dialect_by_code(dialect_code, props) for key, value in DriverDialectManager.known_dialects_by_code.items(): dialect = Utils.initialize_class(value, props) @@ -100,6 +89,41 @@ def get_dialect(self, conn_func: Callable, props: Properties) -> DriverDialect: self._log_dialect(DriverDialectCodes.GENERIC, "generic") return DriverDialect(props) + def get_dialect_for_connection(self, conn: Any, props: Properties) -> Optional[DriverDialect]: + """ + Returns the driver dialect for a connection that the wrapper didn't open. + It doesn't use a custom dialect, because that dialect keeps its own properties and ``props`` can't bound its statements. + + :param conn: the driver connection, or an object that holds one. + :param props: the properties; their ``wrapper_driver_dialect`` code always wins over detection. + :return: the dialect of the ``wrapper_driver_dialect`` code, else the first known dialect that finds + a connection in ``conn``, or None. + """ + dialect_code: Optional[str] = WrapperProperties.DRIVER_DIALECT.get(props) + if dialect_code: + return self._get_dialect_by_code(dialect_code, props) + + for key, value in DriverDialectManager.known_dialects_by_code.items(): + dialect = Utils.initialize_class(value, props) + if dialect is not None and dialect.get_connection_from_obj(conn) is not None: + self._log_dialect(key, value) + return dialect + return None + + def _get_dialect_by_code(self, dialect_code: str, props: Properties) -> DriverDialect: + result = DriverDialectManager.known_dialects_by_code.get(dialect_code) + if result is None: + raise AwsWrapperError(Messages.get_formatted( + "DriverDialectManager.UnknownDialectCode", + dialect_code)) + self._log_dialect(dialect_code, result) + dialect = Utils.initialize_class(result, props) + if dialect is None: + raise AwsWrapperError(Messages.get_formatted( + "DriverDialectManager.InitializationError", + dialect_code)) + return dialect + @staticmethod def _log_dialect(dialect_code: str, driver_dialect: Union[DriverDialect, str]): logger.debug( diff --git a/aws_advanced_python_wrapper/encryption/__init__.py b/aws_advanced_python_wrapper/encryption/__init__.py new file mode 100644 index 000000000..bd4acb2bf --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/__init__.py @@ -0,0 +1,13 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/aws_advanced_python_wrapper/encryption/algorithm.py b/aws_advanced_python_wrapper/encryption/algorithm.py new file mode 100644 index 000000000..c3ae42fcb --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/algorithm.py @@ -0,0 +1,68 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Dict, Optional, Tuple + +from aws_advanced_python_wrapper.errors import InvalidAlgorithmError + + +class EncryptionAlgorithm: + """The symmetric algorithms the plugin can use to encrypt column values. + + These names are stored in the ``encryption_metadata.encryption_algorithm`` + column of the metadata tables. + """ + + AES_256_GCM: str = "AES-256-GCM" + AES_128_GCM: str = "AES-128-GCM" + DEFAULT: str = AES_256_GCM + + # Expected data key length in bytes for each algorithm. + _KEY_LENGTHS: Dict[str, int] = { + AES_256_GCM: 32, + AES_128_GCM: 16, + } + + ALL: Tuple[str, ...] = tuple(_KEY_LENGTHS.keys()) + + @classmethod + def data_key_spec(cls, name: str) -> str: + """Return the KMS ``GenerateDataKey`` key spec (``AES_256`` / + ``AES_128``) that yields a data key of the right length for ``name``. + This is also the value stored in ``key_storage.key_spec``.""" + return f"AES_{cls.key_length(name) * 8}" + + @classmethod + def key_length(cls, name: str) -> int: + """Return the required data key length in bytes for ``name``.""" + try: + return cls._KEY_LENGTHS[name] + except KeyError: + # ``from None`` drops the KeyError from the dict lookup; + # unsupported() already explains the failure. + raise cls.unsupported(name) from None + + @classmethod + def is_supported(cls, name: Optional[str]) -> bool: + return name in cls._KEY_LENGTHS + + @classmethod + def unsupported(cls, name: Optional[str]) -> InvalidAlgorithmError: + return InvalidAlgorithmError( + f"Unsupported kms_encryption algorithm: {name!r}. " + f"Supported algorithms: {', '.join(cls.ALL)}", + algorithm=name, + ) diff --git a/aws_advanced_python_wrapper/encryption/buffers.py b/aws_advanced_python_wrapper/encryption/buffers.py new file mode 100644 index 000000000..f7f4d7b48 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/buffers.py @@ -0,0 +1,34 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helpers for buffers holding key material. + +Kept free of third-party imports, so the key and metadata layer can be +imported without the ``encryption`` extra (``cryptography``) installed. +""" + +from __future__ import annotations + +from typing import Union + +BytesLike = Union[bytes, bytearray, memoryview] + + +def wipe(buffer: bytearray) -> None: + """Overwrite a mutable ``bytearray`` with zeros, in place. Best effort: + immutable ``bytes`` cannot be zeroed, so hold key material in + ``bytearray`` where wiping matters. CPython may still leave copies + elsewhere.""" + if isinstance(buffer, bytearray): + buffer[:] = bytes(len(buffer)) diff --git a/aws_advanced_python_wrapper/encryption/config.py b/aws_advanced_python_wrapper/encryption/config.py new file mode 100644 index 000000000..13af175b9 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/config.py @@ -0,0 +1,223 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +import re +from dataclasses import dataclass +from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Set, + Type, TypeVar) + +from aws_advanced_python_wrapper.errors import EncryptionConfigError +from aws_advanced_python_wrapper.utils.concurrent import ConcurrentSet +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import (WrapperProperties, + WrapperProperty) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.utils.properties import Properties + +# Schema names cannot be bound as statement parameters, so they are +# interpolated into the plugin's own SQL. Only plain identifiers are accepted, +# which rules out quoting, whitespace, comments, and statement separators. +_SCHEMA_NAME_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + +# The region of a KMS key or alias ARN. An alias name (alias/...) or a bare key id names no region. +_KMS_ARN_REGION = re.compile(r"arn:[^:]+:kms:([^:]+):") + +logger = Logger(__name__) + +# The configuration is built for every connection, so each region mismatch is warned about once. +_warned_region_mismatches: ConcurrentSet[str] = ConcurrentSet() + +# The longest name the key management utility puts in its re-encryption SQL; MySQL's limit for most identifiers. +_MAX_IDENTIFIER_LENGTH = 64 + +T = TypeVar("T", int, float) + + +def validate_schema_name(name: Any) -> str: + """Return ``name`` if it is a plain SQL identifier, else raise + :class:`EncryptionConfigError`.""" + if not isinstance(name, str) or not _SCHEMA_NAME_PATTERN.fullmatch(name): + raise EncryptionConfigError( + Messages.get_formatted("EncryptionConfig.InvalidSchemaName", repr(name))) + return name + + +def is_valid_identifier(name: Any) -> bool: + return isinstance(name, str) and len(name) <= _MAX_IDENTIFIER_LENGTH and bool(_SCHEMA_NAME_PATTERN.fullmatch(name)) + + +def _normalize_arns(value: Any) -> FrozenSet[str]: + """Accept ``None``, a comma-separated string, or an iterable of strings.""" + if value is None: + return frozenset() + entries: Iterable[Any] = value.split(",") if isinstance(value, str) else value + return frozenset(s for s in (str(e).strip() for e in entries) if s) + + +@dataclass(frozen=True) +class EncryptionConfig: + """The plugin's configuration, resolved once from the connection + properties. Build it with :meth:`from_props`; the constructor validates.""" + + kms_region: str + allowed_master_key_arns: FrozenSet[str] + kms_endpoint: Optional[str] + metadata_schema: str + metadata_cache_enabled: bool + metadata_cache_expiration_sec: float + metadata_cache_refresh_interval_sec: float + data_key_cache_enabled: bool + data_key_cache_max_size: int + data_key_cache_expiration_sec: float + key_management_max_retries: int + key_management_retry_backoff_base_sec: float + audit_logging_enabled: bool + return_unverified_data: bool + fail_on_unmapped_parameter: bool = True + + def __post_init__(self) -> None: + if not self.kms_region or not self.kms_region.strip(): + raise EncryptionConfigError(Messages.get_formatted( + "EncryptionConfig.MissingRegion", WrapperProperties.ENCRYPTION_KMS_REGION.name, + WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)) + # Normalize here too, so a directly constructed config gets the same + # exact-match semantics as one built from properties. + object.__setattr__(self, "allowed_master_key_arns", _normalize_arns(self.allowed_master_key_arns)) + validate_schema_name(self.metadata_schema) + + wp = WrapperProperties + # Durations must be finite: an infinite interval or TTL reaches + # Event.wait(), which rejects it and kills the background thread, and + # an infinite expiry or backoff is never what was meant. + self._require(_finite(self.metadata_cache_expiration_sec) and self.metadata_cache_expiration_sec > 0, + wp.ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC, "a finite number > 0") + self._require(_finite(self.metadata_cache_refresh_interval_sec) and self.metadata_cache_refresh_interval_sec >= 0, + wp.ENCRYPTION_METADATA_CACHE_REFRESH_INTERVAL_SEC, "a finite number >= 0") + self._require(self.data_key_cache_max_size > 0, wp.ENCRYPTION_DATA_KEY_CACHE_MAX_SIZE, "> 0") + self._require(_finite(self.data_key_cache_expiration_sec) and self.data_key_cache_expiration_sec > 0, + wp.ENCRYPTION_DATA_KEY_CACHE_EXPIRATION_SEC, "a finite number > 0") + self._require(self.key_management_max_retries >= 0, wp.ENCRYPTION_KEY_MANAGEMENT_MAX_RETRIES, ">= 0") + self._require(_finite(self.key_management_retry_backoff_base_sec) + and self.key_management_retry_backoff_base_sec > 0, + wp.ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC, "a finite number > 0") + + @classmethod + def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = True) -> EncryptionConfig: + """Build the configuration from connection properties. + + :param require_allowed_master_keys: the plugin refuses to run without + ``encryption_allowed_master_key_arns``. Only administrative setup + code that builds a config for :class:`KeyManagementUtility` should + pass ``False``, so a new master key can be created and used in the + same setup script. + :raises EncryptionConfigError: if a value is missing or out of range. + """ + wp = WrapperProperties + # Read directly: the value may be a list, which WrapperProperty.get + # (typed Optional[str]) does not model. + allowed_master_key_arns = _normalize_arns(props.get(wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)) + config = cls( + kms_region=_kms_region(_stripped(wp.ENCRYPTION_KMS_REGION.get(props)), allowed_master_key_arns), + kms_endpoint=wp.ENCRYPTION_KMS_ENDPOINT.get(props), + allowed_master_key_arns=allowed_master_key_arns, + metadata_schema=wp.ENCRYPTION_METADATA_SCHEMA.get(props) or "", + metadata_cache_enabled=wp.ENCRYPTION_METADATA_CACHE_ENABLED.get_bool(props), + metadata_cache_expiration_sec=_number(wp.ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC, props, float), + metadata_cache_refresh_interval_sec=_number(wp.ENCRYPTION_METADATA_CACHE_REFRESH_INTERVAL_SEC, props, float), + data_key_cache_enabled=wp.ENCRYPTION_DATA_KEY_CACHE_ENABLED.get_bool(props), + data_key_cache_max_size=_number(wp.ENCRYPTION_DATA_KEY_CACHE_MAX_SIZE, props, int), + data_key_cache_expiration_sec=_number(wp.ENCRYPTION_DATA_KEY_CACHE_EXPIRATION_SEC, props, float), + key_management_max_retries=_number(wp.ENCRYPTION_KEY_MANAGEMENT_MAX_RETRIES, props, int), + key_management_retry_backoff_base_sec=_number( + wp.ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC, props, float), + audit_logging_enabled=wp.ENCRYPTION_AUDIT_LOGGING_ENABLED.get_bool(props), + return_unverified_data=wp.ENCRYPTION_RETURN_UNVERIFIED_DATA.get_bool(props), + fail_on_unmapped_parameter=wp.ENCRYPTION_FAIL_ON_UNMAPPED_PARAMETER.get_bool(props), + ) + + if require_allowed_master_keys and not config.restricts_master_keys: + raise EncryptionConfigError( + Messages.get_formatted("EncryptionConfig.MissingAllowedMasterKeys", + wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)) + return config + + @property + def restricts_master_keys(self) -> bool: + """``True`` when only the listed master keys may be used.""" + return bool(self.allowed_master_key_arns) + + @property + def background_refresh_enabled(self) -> bool: + return self.metadata_cache_enabled and self.metadata_cache_refresh_interval_sec > 0 + + def is_master_key_allowed(self, master_key_arn: Optional[str]) -> bool: + """Exact-match check against the allow-list. With no allow-list + configured (administrative use only) every key is allowed.""" + if not self.restricts_master_keys: + return True + return master_key_arn is not None and master_key_arn in self.allowed_master_key_arns + + @staticmethod + def _require(condition: bool, prop: WrapperProperty, requirement: str) -> None: + if not condition: + raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.OutOfRange", prop.name, requirement)) + + +def _kms_region(region: str, allowed_master_key_arns: FrozenSet[str]) -> str: + """``region`` when it is set, else the one region of the KMS key and alias ARNs in the allow-list.""" + arn_regions: Set[str] = set() + for arn in allowed_master_key_arns: + match = _KMS_ARN_REGION.match(arn) + if match is not None: + arn_regions.add(match[1]) + wp = WrapperProperties + if region: + others = ", ".join(sorted(arn_regions - {region})) + # Reported, not refused: an unused leftover, or a multi-region key's replica listed for a deployment in + # another region, doesn't stop this one from working. + if others and f"{region} {others}" not in _warned_region_mismatches: + _warned_region_mismatches.add(f"{region} {others}") + logger.warning("EncryptionConfig.RegionMismatch", wp.ENCRYPTION_KMS_REGION.name, region, + wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name, others, region) + return region + if len(arn_regions) > 1: + raise EncryptionConfigError(Messages.get_formatted( + "EncryptionConfig.AmbiguousRegion", wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name, wp.ENCRYPTION_KMS_REGION.name)) + return next(iter(arn_regions), "") + + +def _stripped(value: Optional[str]) -> str: + return (value or "").strip() + + +def _finite(value: float) -> bool: + return isinstance(value, (int, float)) and math.isfinite(value) + + +def _number(prop: WrapperProperty, props: Properties, kind: Type[T]) -> T: + """Read a numeric property, naming it if the value is not a number. + Property values are configuration, not secrets, so chaining is fine.""" + value = props.get(prop.name) + # int() drops the fraction, so 1.5 would become 1 without an error. + if kind is int and isinstance(value, float) and not value.is_integer(): + raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.InvalidValue", prop.name, value)) + try: + return prop.get_type(props, kind) + except (TypeError, ValueError) as e: + raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.InvalidValue", prop.name, e)) from e diff --git a/aws_advanced_python_wrapper/encryption/connection_source.py b/aws_advanced_python_wrapper/encryption/connection_source.py new file mode 100644 index 000000000..7d783e08f --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/connection_source.py @@ -0,0 +1,187 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""How the key and metadata layer gets a connection and runs its SQL through the driver dialect.""" + +from __future__ import annotations + +from contextlib import closing, contextmanager +from threading import local +from typing import (TYPE_CHECKING, Any, ContextManager, Dict, Iterator, List, + Mapping, Optional, Protocol, Sequence, cast) + +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.utils.decorators import \ + is_connection_abandoned +from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.retry_util import RetryUtil + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + from aws_advanced_python_wrapper.pep249 import Connection + from aws_advanced_python_wrapper.plugin import Plugin + from aws_advanced_python_wrapper.plugin_service import PluginService + + +class ConnectionSource(Protocol): + def connection(self) -> ContextManager[Any]: + """Return a context manager that yields a DB-API connection.""" + ... + + +class CallerConnectionSource: + """Runs every operation on a connection the caller owns. + + The connection is never closed, committed, or rolled back here, so a + multi-step administrative operation stays inside the caller's transaction. + """ + + def __init__(self, conn: Any): + self._conn = conn + + @contextmanager + def connection(self) -> Iterator[Any]: + yield self._conn + + +class PluginConnectionSource: + """Opens a short-lived connection through the wrapper's connect pipeline + and closes it: one per :meth:`connection` call, or one per + :meth:`statement` scope on the thread. + + Metadata and key reads therefore never use the application's connection, + and cannot block on or join the application's transaction. The connection + runs in autocommit mode so a read never leaves a session idle in a + transaction and a ``last_used_at`` update is not lost on close. + """ + + def __init__(self, plugin_service: PluginService, plugin_to_skip: Optional[Plugin] = None): + self._plugin_service = plugin_service + self._plugin_to_skip = plugin_to_skip + self._scope = local() + + @contextmanager + def statement(self) -> Iterator[None]: + """Share one connection among the lookups of one statement on this thread. + + The connection opens at the first lookup inside the scope and closes when + the outermost scope ends, also when a lookup fails, so a statement uses at + most one short-lived connection. A connection that a timed-out statement + still runs on stays open, and that statement's worker frees it when it + finishes. A scope that looks nothing up opens nothing. + """ + depth = getattr(self._scope, "depth", 0) + self._scope.depth = depth + 1 + if depth == 0: + self._scope.conn = None + try: + yield + finally: + self._scope.depth = depth + if depth == 0: + conn, self._scope.conn = self._scope.conn, None + # A statement that timed out can leave its worker on the connection; closing it then would crash the + # process, so the worker frees it when it finishes. + if conn is not None and not is_connection_abandoned(conn): + RetryUtil.close_connection(self._plugin_service, conn) + + @contextmanager + def connection(self) -> Iterator[Any]: + if getattr(self._scope, "depth", 0): + if self._scope.conn is None: + self._scope.conn = self._open() + yield self._scope.conn + return + conn = self._open() + try: + yield conn + finally: + # A statement that timed out can leave its worker on the connection; closing it then would crash the + # process, so the worker frees it when it finishes. + if not is_connection_abandoned(conn): + RetryUtil.close_connection(self._plugin_service, conn) + + def _open(self) -> Any: + service = self._plugin_service + conn = service.force_connect( + service.current_host_info, Properties(service.props.copy()), self._plugin_to_skip) + try: + service.driver_dialect.set_autocommit(conn, True) + except BaseException: # noqa: BLE001 - close the half-opened connection, then re-raise it as is + RetryUtil.close_connection(service, conn) + raise + return conn + + +def fetch_rows(dialect: DriverDialect, conn: Connection, sql: str, params: Sequence[Any] = ()) -> List[Dict[str, Any]]: + """ + Runs a query and returns its rows as dicts keyed by the lower-cased column name. + MySQL reports ``information_schema`` names in upper case on some versions, so callers never depend on the case + of a result key. + Rows can come back as tuples or, on a connection opened with a dict-like row factory (for example psycopg's + ``row_factory=dict_row``), as mappings; both are handled. + Each cursor call runs through the dialect's :meth:`DriverDialect.execute`, so the ``socket_timeout`` of the + dialect's properties applies, and a timeout raises ``QueryTimeoutError``. + + :param dialect: the driver dialect whose ``execute`` runs each cursor call. + :param conn: the connection to run the query on. + :param sql: the query. + :param params: the query's parameters. + :return: the rows, each a dict keyed by the lower-cased column name. + """ + with closing(conn.cursor()) as cursor: + dialect.execute(DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(sql, params), sql, conn=conn) + if cursor.description is None: + return [] + names = [_lower(d[0]) for d in cursor.description] + rows = cast("List[Any]", dialect.execute(DbApiMethod.CURSOR_FETCHALL.method_name, lambda: cursor.fetchall(), conn=conn)) + return [{_lower(k): v for k, v in row.items()} if isinstance(row, Mapping) else dict(zip(names, row, strict=False)) + for row in rows] + + +def _lower(name: Any) -> Any: + return name.lower() if isinstance(name, str) else name + + +def describe_failure(error: Exception) -> str: + """ + Describes a failed statement by the exception type and any SQLSTATE or errno the driver reports. + Neither carries statement text or row values, unlike the driver's error message. + + :param error: the error the statement raised. + :return: the type name, followed by the SQLSTATE and errno when the error has them. + """ + details = [type(error).__name__] + for attribute in ("sqlstate", "errno"): + value = getattr(error, attribute, None) + if isinstance(value, (str, int)) and not isinstance(value, bool): + details.append(f"{attribute} {value}") + return ", ".join(details) + + +def run_statement(dialect: DriverDialect, conn: Connection, sql: str, params: Sequence[Any] = ()) -> int: + """ + Runs a statement and returns the number of rows it affected. + The cursor call runs through the dialect's :meth:`DriverDialect.execute`, so the ``socket_timeout`` of the + dialect's properties applies, and a timeout raises ``QueryTimeoutError``. + + :param dialect: the driver dialect whose ``execute`` runs each cursor call. + :param conn: the connection to run the statement on. + :param sql: the statement. + :param params: the statement's parameters. + :return: the number of rows the statement affected, 0 when the driver doesn't report it. + """ + with closing(conn.cursor()) as cursor: + dialect.execute(DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(sql, params), sql, conn=conn) + return max(cursor.rowcount, 0) diff --git a/aws_advanced_python_wrapper/encryption/data_key_cache.py b/aws_advanced_python_wrapper/encryption/data_key_cache.py new file mode 100644 index 000000000..76ef470cd --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/data_key_cache.py @@ -0,0 +1,201 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import weakref +from dataclasses import dataclass +from threading import Event, Lock, Thread, current_thread +from typing import List, Optional + +from aws_advanced_python_wrapper.encryption.buffers import BytesLike, wipe +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.storage.expiration_tracking_cache import \ + ExpirationTrackingCache + +logger = Logger(__name__) + + +@dataclass(frozen=True) +class DataKeyCacheStats: + size: int + hits: int + misses: int + evictions: int + + @property + def hit_rate(self) -> float: + """Percentage of lookups served from the cache.""" + total = self.hits + self.misses + return 100.0 * self.hits / total if total else 0.0 + + +class DataKeyCache: + """An in-memory cache of plaintext data keys, so reading an encrypted + column does not need a KMS ``Decrypt`` call per statement. + + The keys are held in an ``ExpirationTrackingCache``, which fixes each + key's expiry when it is stored; a cache hit does not extend it. This class + adds a size bound with oldest-first eviction, and zeroes a key's bytes when + it leaves the cache. Each ``get`` returns a fresh ``bytearray`` copy, so a + caller wiping its copy cannot corrupt the cached one. An expired entry is + never returned, even before the cleanup thread removes it. + + Call :meth:`close` when done with the cache. After ``close`` the cache + stores nothing. A cache dropped without ``close`` still stops its cleanup + thread and wipes its keys once it is garbage-collected, because the thread + holds only a weak reference to it. + + Wiping is best effort: CPython may hold other copies of the key bytes. + """ + + MIN_CLEANUP_INTERVAL_SEC = 30.0 + SHUTDOWN_TIMEOUT_SEC = 5.0 + + def __init__(self, max_size: int, ttl_sec: float, enabled: bool = True, + *, start_cleanup_thread: bool = True): + self._max_size = max_size + self._ttl_sec = ttl_sec + self._enabled = enabled + self._entries: ExpirationTrackingCache[str, bytearray] = ExpirationTrackingCache( + int(ttl_sec * 1_000_000_000)) + self._lock = Lock() + self._hits = 0 + self._misses = 0 + self._evictions = 0 + self._closed = False + self._stop = Event() + self._cleanup_thread: Optional[Thread] = None + # Holds the cleanup thread for the finalizer, which must not refer to + # self, or the cache would never be collected. + self._thread_holder: List[Optional[Thread]] = [None] + # Runs at close() or when the cache is collected, whichever is first. + self._finalizer = weakref.finalize( + self, DataKeyCache._release, self._entries, self._lock, self._stop, self._thread_holder) + if enabled and start_cleanup_thread: + self._cleanup_thread = Thread( + target=DataKeyCache._cleanup_loop, args=(weakref.ref(self), self._stop, self.cleanup_interval_sec), + name="kms-encryption-data-key-cache-cleanup", daemon=True) + self._thread_holder[0] = self._cleanup_thread + self._cleanup_thread.start() + + @property + def cleanup_interval_sec(self) -> float: + return max(self._ttl_sec / 4, self.MIN_CLEANUP_INTERVAL_SEC) + + def get(self, key: str) -> Optional[bytearray]: + """Return a copy of the cached data key, or ``None`` on a miss. The + caller owns the copy and should wipe it once used.""" + if not self._enabled: + return None + with self._lock: + if self._closed: + return None + data_key = self._entries.get(key) + if data_key is None: + # The store keeps an expired key until it is removed. + self._discard(key) + self._misses += 1 + return None + self._hits += 1 + return bytearray(data_key) + + def put(self, key: str, data_key: BytesLike) -> None: + """Store a copy of ``data_key``, evicting the oldest entry when full. + The caller keeps ownership of the buffer it passed in. A closed cache + stores nothing.""" + if not self._enabled: + return + copy = bytearray(data_key) + with self._lock: + if self._closed: + wipe(copy) + return + self._discard(key) + while len(self._entries) >= self._max_size: + oldest, _ = self._entries.items()[0] + self._discard(oldest) + self._evictions += 1 + self._entries.put(key, copy) + + def remove_expired(self) -> int: + """Drop every expired entry. Returns the number removed.""" + removed = 0 + with self._lock: + for key, _ in self._entries.items(): + data_key = self._entries.remove_expired_if(key, lambda _: True) + if data_key is not None: + wipe(data_key) + removed += 1 + return removed + + def stats(self) -> DataKeyCacheStats: + with self._lock: + return DataKeyCacheStats(len(self._entries), self._hits, self._misses, self._evictions) + + def __len__(self) -> int: + with self._lock: + return len(self._entries) + + def close(self) -> None: + """Stop the cleanup thread and zero every cached key. Later ``put`` + calls store nothing. Idempotent. + + Call it from ordinary code, not from a finalizer or ``__del__``: a + garbage collection on the cleanup thread can run inside its wait, where + stopping the thread would deadlock. + """ + with self._lock: + self._closed = True + self._stop.set() + self._finalizer() + thread = self._cleanup_thread + if thread is not None and thread is not current_thread(): + thread.join(self.SHUTDOWN_TIMEOUT_SEC) + self._cleanup_thread = None + + def _discard(self, key: str) -> None: + # Callers hold the lock. + data_key = self._entries.remove(key) + if data_key is not None: + wipe(data_key) + + @staticmethod + def _release(entries: ExpirationTrackingCache[str, bytearray], lock: Lock, stop: Event, + thread_holder: List[Optional[Thread]]) -> None: + # Runs at close() or when an unclosed cache is collected. Wipe first, + # so the keys are zeroed whatever happens next. A collection can run + # on the cleanup thread itself, inside Event.wait while it holds the + # event's lock, where stop.set() would deadlock; that thread exits on + # its own, finding the cache gone as soon as wait returns. + with lock: + for data_key in entries.clear(): + wipe(data_key) + if thread_holder[0] is not current_thread(): + stop.set() + + @staticmethod + def _cleanup_loop(cache_ref: weakref.ref[DataKeyCache], stop: Event, interval_sec: float) -> None: + # Holds the cache only weakly between runs, so an unclosed cache can + # still be collected. Event.wait returns as soon as close() (or the + # finalizer) sets the event, so shutdown does not wait out an interval. + while not stop.wait(interval_sec): + cache = cache_ref() + if cache is None: + return + try: + cache.remove_expired() + except Exception as e: + logger.debug("DataKeyCache.CleanupFailed", type(e).__name__) + del cache diff --git a/aws_advanced_python_wrapper/encryption/encryption_service.py b/aws_advanced_python_wrapper/encryption/encryption_service.py new file mode 100644 index 000000000..0417db880 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/encryption_service.py @@ -0,0 +1,542 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import hashlib +import hmac +import operator +import os +import struct +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal, InvalidOperation +from typing import TYPE_CHECKING, Any, Optional, Union + +from aws_advanced_python_wrapper.utils.messages import Messages + +try: + from cryptography.exceptions import InvalidTag + from cryptography.hazmat.primitives.ciphers.aead import AESGCM +except ModuleNotFoundError as e: + # Only a missing package gets the install hint. An installed but broken + # cryptography raises its own ImportError, which is clearer as it is. + if (e.name or "").partition(".")[0] != "cryptography": + raise + raise ImportError(Messages.get("EncryptionService.CryptographyMissing")) from e + +from aws_advanced_python_wrapper.encryption import buffers +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker +from aws_advanced_python_wrapper.errors import (DecryptionError, + EncryptionFailedError, + IntegrityCheckError, + InvalidKeyError, + TypeConversionError) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.buffers import BytesLike + +_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) +_MICROSECOND = timedelta(microseconds=1) +_MILLISECOND = timedelta(milliseconds=1) +# The epoch-millis range a datetime can be read back into. +_MIN_EPOCH_MS = -((_EPOCH - datetime.min.replace(tzinfo=timezone.utc)) // _MILLISECOND) +_MAX_EPOCH_MS = (datetime.max.replace(tzinfo=timezone.utc) - _EPOCH) // _MILLISECOND + + +class EncryptionService: + """Encrypts and decrypts single column values with AES-GCM, signed with a + separate HMAC-SHA256 key. + + The payload has this layout. The database-side trigger checks its minimum + length and its HMAC tag:: + + [ HMAC-SHA256 tag : 32 ][ key id : 4 ][ type marker : 1 ][ GCM IV : 12 ][ ciphertext ][ GCM tag : 16 ] + + The HMAC covers everything after itself, so the database can detect a + tampered payload (the ``verify_encrypted_data_hmac`` SQL function) without + holding the data key. The key id is the ``key_storage`` row the value was + encrypted with, which keeps the value decryptable after its column's data + key is rotated. It sits inside the HMAC-covered region, so tampering with + it is detected too. The type marker records how the plaintext was + serialized, so the original Python type can be restored on read. + + Errors never quote plaintext. Several standard-library failures do quote + their input (``UnicodeEncodeError.object``, ``int("...")``, + ``datetime.fromisoformat``), and an exception raised inside an ``except`` + block keeps the caught one as ``__context__`` even with ``from None``. So + where such a failure is caught, the wrapper error is raised after the + ``except`` block, with nothing chained. + """ + + HMAC_TAG_LENGTH = 32 + KEY_ID_LENGTH = 4 + TYPE_MARKER_LENGTH = 1 + GCM_IV_LENGTH = 12 + GCM_TAG_LENGTH = 16 + MIN_ENCRYPTED_LENGTH = ( + HMAC_TAG_LENGTH + KEY_ID_LENGTH + TYPE_MARKER_LENGTH + GCM_IV_LENGTH + GCM_TAG_LENGTH + ) + + #: Zero a ``bytearray`` in place; see :func:`buffers.wipe`. + wipe = staticmethod(buffers.wipe) + + @classmethod + def encrypt(cls, value: Any, data_key: BytesLike, hmac_key: BytesLike, + algorithm: str = EncryptionAlgorithm.DEFAULT, *, key_id: int) -> Optional[bytes]: + """Encrypt a single value. + + :param value: the plaintext value; ``None`` is returned unchanged. + :param data_key: the plaintext data key, binary. + :param hmac_key: the HMAC-SHA256 key, binary. + :param algorithm: an :class:`EncryptionAlgorithm` name. + :param key_id: the ``key_storage`` id of the data key, recorded in the + payload so the value stays decryptable after the column's key is + rotated. + :return: the binary payload to store, or ``None`` when value is ``None``. + :raises EncryptionError: if the key, algorithm, or key id is unusable, + or the value cannot be serialized. + """ + if value is None: + return None + + cls._validate_key(data_key, algorithm) + cls._validate_hmac_key(hmac_key) + cls._validate_key_id(key_id) + + marker = TypeMarker.from_object(value) + # The buffer handed to AES-GCM is the one wiped afterwards. + plaintext = bytearray(cls.serialize_value(value, marker)) + try: + # body = [ key id : 4 ][ type marker : 1 ][ IV : 12 ][ ciphertext ][ GCM tag : 16 ] + body = struct.pack(">I", key_id) + cls._seal(plaintext, marker, data_key, algorithm) + tag = hmac.new(cls._hmac_key(hmac_key), body, hashlib.sha256).digest() + return tag + body + finally: + cls.wipe(plaintext) + + @classmethod + def key_id_from_payload(cls, encrypted: Optional[BytesLike]) -> Optional[int]: + """Read the key id recorded in a payload, without verifying or + decrypting it. A payload with no key id (too short) yields ``None``. + """ + if encrypted is None: + return None + data = cls._to_bytes(encrypted) + if len(data) < cls.HMAC_TAG_LENGTH + cls.KEY_ID_LENGTH: + return None + return struct.unpack(">I", data[cls.HMAC_TAG_LENGTH:cls.HMAC_TAG_LENGTH + cls.KEY_ID_LENGTH])[0] + + @classmethod + def decrypt(cls, encrypted: Optional[BytesLike], data_key: BytesLike, hmac_key: BytesLike, + algorithm: str = EncryptionAlgorithm.DEFAULT, *, target_type: Optional[type] = None) -> Any: + """Decrypt a payload produced by :meth:`encrypt`. + + :param target_type: the type to coerce the result to; defaults to the + type recorded by the payload's marker. + :raises IntegrityCheckError: if the payload is too short or its HMAC + does not verify: it was modified, was never encrypted, or was + signed with a different HMAC key. + :raises EncryptionError: if the payload cannot be decrypted with the + given key or its value cannot be restored. + """ + if encrypted is None: + return None + + data = cls._to_bytes(encrypted) + if len(data) < cls.MIN_ENCRYPTED_LENGTH: + raise IntegrityCheckError( + Messages.get_formatted("EncryptionService.DataTooShort", len(data), cls.MIN_ENCRYPTED_LENGTH), + algorithm=algorithm, + ) + + cls._validate_key(data_key, algorithm) + cls._validate_hmac_key(hmac_key) + + # The HMAC covers the key id and everything after it. + body = data[cls.HMAC_TAG_LENGTH:] + expected = data[:cls.HMAC_TAG_LENGTH] + actual = hmac.new(cls._hmac_key(hmac_key), body, hashlib.sha256).digest() + if not hmac.compare_digest(expected, actual): + raise IntegrityCheckError(Messages.get("EncryptionService.IntegrityCheckFailed"), algorithm=algorithm) + + payload = body[cls.KEY_ID_LENGTH:] + marker = cls._read_marker(payload) + # The recovered value is returned to the caller as a Python object, so + # there is no buffer here worth wiping. + plaintext = cls._unseal(payload, data_key, algorithm, marker) + return cls._convert_to_target_type(cls.deserialize_value(plaintext, marker), target_type) + + @classmethod + def verify(cls, encrypted: BytesLike, hmac_key: BytesLike) -> bool: + """Check a payload's HMAC tag against ``hmac_key`` in constant time. + + :return: ``True`` when ``encrypted`` is long enough for a payload and its tag verifies. + """ + data = cls._to_bytes(encrypted) + if len(data) < cls.MIN_ENCRYPTED_LENGTH: + return False + actual = hmac.new(cls._hmac_key(hmac_key), data[cls.HMAC_TAG_LENGTH:], hashlib.sha256).digest() + return hmac.compare_digest(data[:cls.HMAC_TAG_LENGTH], actual) + + @classmethod + def reencrypt(cls, encrypted: BytesLike, data_key: BytesLike, hmac_key: BytesLike, new_data_key: BytesLike, + new_hmac_key: BytesLike, algorithm: str, *, new_key_id: int) -> bytes: + """Seal a payload's plaintext again under another data key, with a new IV and the same type marker. The + plaintext bytes are never converted to a Python value. + + :param new_key_id: the ``key_storage`` id of ``new_data_key``, recorded in the new payload. + :return: the new payload. + :raises IntegrityCheckError: if the payload's HMAC doesn't verify with ``hmac_key``. + :raises EncryptionError: if a key is unusable or the payload can't be decrypted with ``data_key``. + """ + if not cls.verify(encrypted, hmac_key): + raise IntegrityCheckError(Messages.get("EncryptionService.IntegrityCheckFailed"), algorithm=algorithm) + cls._validate_key(data_key, algorithm) + cls._validate_key(new_data_key, algorithm) + cls._validate_hmac_key(new_hmac_key) + cls._validate_key_id(new_key_id) + payload = cls._to_bytes(encrypted)[cls.HMAC_TAG_LENGTH + cls.KEY_ID_LENGTH:] + marker = cls._read_marker(payload) + # AESGCM.decrypt returns immutable bytes, which can't be wiped, so plaintext wiping is best effort. + plaintext = bytearray(cls._unseal(payload, data_key, algorithm, marker)) + try: + body = struct.pack(">I", new_key_id) + cls._seal(plaintext, marker, new_data_key, algorithm) + finally: + cls.wipe(plaintext) + return hmac.new(cls._hmac_key(new_hmac_key), body, hashlib.sha256).digest() + body + + @classmethod + def serialize_value(cls, value: Any, marker: Optional[int] = None) -> bytes: + """Serialize a value to the bytes that get encrypted. + + :param marker: the marker to write; defaults to the one + :meth:`TypeMarker.from_object` picks for ``value``. + :raises EncryptionFailedError: if ``value`` cannot be written with + that marker. + """ + if marker is None: + marker = TypeMarker.from_object(value) + if not TypeMarker.is_known(marker): + raise EncryptionFailedError(Messages.get_formatted("EncryptionService.UnsupportedTypeMarker", marker)) + try: + return cls._serialize(value, marker) + except (TypeError, ValueError, AttributeError, ArithmeticError, struct.error): + # Mostly a value that does not fit an explicitly requested marker + # (or a GENERIC value whose __str__ fails). The caught message may + # quote the value, so it is not chained, and the error is raised + # below, outside the handler. ArithmeticError covers OverflowError + # and decimal.InvalidOperation. + pass + raise EncryptionFailedError( + Messages.get_formatted("EncryptionService.CannotWriteType", type(value).__name__, TypeMarker.name_for(marker)), + data_type=TypeMarker.name_for(marker)) + + @classmethod + def _serialize(cls, value: Any, marker: int) -> bytes: + if marker == TypeMarker.STRING and issubclass(type(value), str): + # Store the string's own text: str() of a (str, Enum) member is + # 'Color.RED', and a subclass may override __str__. The check is + # on type(), not isinstance(), because str.__str__ needs a real + # str and proxies can fake __class__. + return cls._utf8_bytes(str.__str__(value)) + if marker in (TypeMarker.STRING, TypeMarker.GENERIC): + return cls._utf8_bytes(str(value)) + if marker == TypeMarker.LOCAL_TIME: + # LOCAL_TIME is ISO text on the wire; TIME is the epoch-millis form. + if isinstance(value, time): + cls._require_naive(value, "LOCAL_TIME") + return cls._utf8_bytes(value.isoformat()) + return cls._utf8_bytes(str(value)) + if marker == TypeMarker.BYTE_ARRAY: + # bytes(7) would be seven zero bytes, so only bytes-like values. + if not isinstance(value, (bytes, bytearray, memoryview)): + raise TypeError(Messages.get("EncryptionService.NeedsBytes")) + return cls._to_bytes(value) + if marker == TypeMarker.INTEGER: + return struct.pack(">i", value) + if marker == TypeMarker.LONG: + # Every Python int but bool defaults to LONG, so an out-of-range + # one gets its own message rather than the generic one. + # operator.index accepts what INTEGER's struct packing accepts + # (int, bool, other integer types) and raises TypeError for a + # float or Decimal. + value = operator.index(value) + if not (-(2 ** 63) <= value <= 2 ** 63 - 1): + raise EncryptionFailedError(Messages.get("EncryptionService.LongOutOfRange"), data_type="LONG") + return struct.pack(">q", value) + if marker == TypeMarker.DOUBLE: + return struct.pack(">d", value) + if marker == TypeMarker.FLOAT: + return struct.pack(">f", value) + if marker == TypeMarker.BOOLEAN: + # Not truthiness: "false" must not be written as True. + if not isinstance(value, bool): + raise TypeError(Messages.get("EncryptionService.NeedsBool")) + return b"\x01" if value else b"\x00" + if marker == TypeMarker.BIG_DECIMAL: + # Plain (non-scientific) notation, so Decimal("1E+2") and + # Decimal("100") give the same bytes. The scale is kept: + # Decimal("1.0") is written as "1.0". + if not value.is_finite(): + raise EncryptionFailedError(Messages.get("EncryptionService.NonFiniteDecimal"), data_type="BIG_DECIMAL") + return cls._utf8_bytes(format(value, "f")) + if marker in (TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP): + return struct.pack(">q", cls._to_millis(value, TypeMarker.name_for(marker) or "")) + if marker == TypeMarker.LOCAL_DATE: + # isoformat always writes a 4-digit year; strftime("%Y") does not + # on every platform. A datetime is cut to its own (wall-clock) + # date, as a local date has no offset to keep. + return cls._utf8_bytes(date(value.year, value.month, value.day).isoformat()) + if marker == TypeMarker.LOCAL_DATE_TIME: + if not isinstance(value, datetime): + raise EncryptionFailedError( + Messages.get_formatted("EncryptionService.CannotWriteType", type(value).__name__, "LOCAL_DATE_TIME"), + data_type="LOCAL_DATE_TIME") + cls._require_naive(value, "LOCAL_DATE_TIME") + return cls._utf8_bytes(value.isoformat()) + raise EncryptionFailedError(Messages.get_formatted("EncryptionService.UnsupportedTypeMarker", marker)) + + @classmethod + def deserialize_value(cls, data: bytes, marker: int) -> Any: + """Turn decrypted bytes back into a Python value.""" + try: + if marker in (TypeMarker.STRING, TypeMarker.GENERIC, TypeMarker.LOCAL_TIME): + return cls._utf8(data) + if marker == TypeMarker.BYTE_ARRAY: + return bytes(data) + if marker == TypeMarker.INTEGER: + return struct.unpack(">i", cls._expect_length(data, 4, marker))[0] + if marker == TypeMarker.LONG: + return struct.unpack(">q", cls._expect_length(data, 8, marker))[0] + if marker == TypeMarker.DOUBLE: + return struct.unpack(">d", cls._expect_length(data, 8, marker))[0] + if marker == TypeMarker.FLOAT: + return struct.unpack(">f", cls._expect_length(data, 4, marker))[0] + if marker == TypeMarker.BOOLEAN: + return cls._expect_length(data, 1, marker)[0] != 0 + if marker == TypeMarker.BIG_DECIMAL: + return Decimal(cls._utf8(data)) + if marker == TypeMarker.DATE: + return cls._from_millis(struct.unpack(">q", cls._expect_length(data, 8, marker))[0]).date() + if marker in (TypeMarker.TIME, TypeMarker.TIMESTAMP): + return cls._from_millis(struct.unpack(">q", cls._expect_length(data, 8, marker))[0]) + if marker == TypeMarker.LOCAL_DATE: + return date.fromisoformat(cls._utf8(data)) + if marker == TypeMarker.LOCAL_DATE_TIME: + return cls._parse_local_datetime(cls._utf8(data)) + except (ValueError, struct.error, InvalidOperation, OverflowError): + # The text markers' parse errors quote the decrypted plaintext, so + # the error reports only the marker and is raised below, outside + # the handler (see the class docstring). + failed_marker = marker + else: + raise DecryptionError( + Messages.get_formatted("EncryptionService.UnsupportedTypeMarker", marker), data_type=str(marker)) + raise TypeConversionError( + Messages.get_formatted("EncryptionService.DeserializeFailed", TypeMarker.name_for(failed_marker) or failed_marker), + data_type=TypeMarker.name_for(failed_marker), + ) + + @classmethod + def _seal(cls, plaintext: BytesLike, marker: int, data_key: BytesLike, algorithm: str) -> bytes: + try: + iv = os.urandom(cls.GCM_IV_LENGTH) + # AESGCM appends the 16-byte tag to the ciphertext, giving the + # [ciphertext][GCM tag] tail the wire format expects. AESGCM keeps + # its own copy of the key, which wiping the caller's bytearray + # doesn't reach, so key wiping is best effort. + sealed = AESGCM(data_key).encrypt(iv, plaintext, None) + return bytes([marker]) + iv + sealed + except Exception as e: + raise EncryptionFailedError( + Messages.get_formatted("EncryptionService.EncryptFailed", type(e).__name__), + algorithm=algorithm, data_type=TypeMarker.name_for(marker), + ) from e + + @classmethod + def _unseal(cls, payload: bytes, data_key: BytesLike, algorithm: str, marker: int) -> bytes: + iv = payload[cls.TYPE_MARKER_LENGTH:cls.TYPE_MARKER_LENGTH + cls.GCM_IV_LENGTH] + sealed = payload[cls.TYPE_MARKER_LENGTH + cls.GCM_IV_LENGTH:] + try: + return AESGCM(data_key).decrypt(iv, sealed, None) + except InvalidTag as e: + # The HMAC has already been checked, so a GCM failure here means the + # data key is wrong rather than the data being corrupt. + raise DecryptionError( + Messages.get("EncryptionService.TagMismatch"), algorithm=algorithm, data_type=TypeMarker.name_for(marker), + ) from e + + @classmethod + def _convert_to_target_type(cls, value: Any, target_type: Optional[type]) -> Any: + if target_type is None or value is None or isinstance(value, target_type): + return value + source_name = type(value).__name__ + try: + if target_type is str: + return str(value) + if target_type is int: + return int(value) + if target_type is float: + return float(value) + if target_type is Decimal: + return Decimal(str(value)) + if target_type is bool: + return cls._truthy(value) + except (ValueError, TypeError, ArithmeticError): + # `value` is the recovered plaintext and int()/float()/Decimal() + # quote their input, so nothing is interpolated or chained, and the + # error is raised below, outside the handler (see the class + # docstring). ArithmeticError covers OverflowError (int of an + # infinite float or Decimal) and decimal.InvalidOperation. + pass + # Reached after a caught conversion failure, or when target_type + # matched no branch above. + raise TypeConversionError( + Messages.get_formatted("EncryptionService.CannotConvert", source_name, target_type), + data_type=str(target_type), + ) + + @classmethod + def _read_marker(cls, payload: bytes) -> int: + try: + return TypeMarker.from_value(payload[0]) + except ValueError as e: + raise DecryptionError(str(e)) from e + + @classmethod + def _validate_key(cls, data_key: BytesLike, algorithm: str) -> None: + expected = EncryptionAlgorithm.key_length(algorithm) + if not isinstance(data_key, (bytes, bytearray, memoryview)) or len(data_key) != expected: + got = len(data_key) if isinstance(data_key, (bytes, bytearray, memoryview)) else None + raise InvalidKeyError( + Messages.get_formatted("EncryptionService.WrongKeyLength", expected, algorithm, got), algorithm=algorithm) + + @classmethod + def _validate_hmac_key(cls, hmac_key: BytesLike) -> None: + if not isinstance(hmac_key, (bytes, bytearray, memoryview)) or not hmac_key: + raise InvalidKeyError(Messages.get("EncryptionService.MissingHmacKey")) + + @classmethod + def _validate_key_id(cls, key_id: int) -> None: + # Packed as an unsigned 32-bit integer. bool is excluded (it is an int subclass). + if isinstance(key_id, bool) or not isinstance(key_id, int) or not (0 <= key_id <= 0xFFFFFFFF): + raise EncryptionFailedError(Messages.get_formatted("EncryptionService.InvalidKeyId", key_id)) + + @staticmethod + def _require_naive(value: Any, marker_name: str) -> None: + # A local date-time or time of day has no UTC offset on the wire, so an + # aware value would silently lose it. Aware datetimes are written as + # TIMESTAMP instead (see TypeMarker.from_object). + if isinstance(value, (datetime, time)) and value.utcoffset() is not None: + raise EncryptionFailedError( + Messages.get_formatted("EncryptionService.TimezoneAware", marker_name), data_type=marker_name) + + @classmethod + def _expect_length(cls, data: bytes, length: int, marker: int) -> bytes: + if len(data) != length: + raise TypeConversionError( + Messages.get_formatted("EncryptionService.WrongValueLength", length, TypeMarker.name_for(marker), len(data)), + data_type=TypeMarker.name_for(marker), + ) + return data + + @staticmethod + def _hmac_key(key: BytesLike) -> Union[bytes, bytearray]: + # hmac takes bytes or bytearray but not memoryview, so a memoryview key + # is copied to bytes (which cannot be wiped). A bytearray key is passed + # as is, so no immutable copy of it is made. + return key if isinstance(key, (bytes, bytearray)) else bytes(key) + + @staticmethod + def _to_bytes(value: BytesLike) -> bytes: + return value if isinstance(value, bytes) else bytes(value) + + @staticmethod + def _utf8(data: bytes) -> str: + return bytes(data).decode("utf-8") + + @classmethod + def _utf8_bytes(cls, string: str) -> bytes: + """Encode the string as UTF-8. A str with no UTF-8 form (lone + surrogates) is refused, and the error does not quote the offending + character, since that character is plaintext.""" + try: + return string.encode("utf-8") + except UnicodeEncodeError: + # UnicodeEncodeError holds the full plaintext in `.object`; raised + # below, outside the handler (see the class docstring). + pass + raise EncryptionFailedError(Messages.get("EncryptionService.NoUtf8Form"), data_type="str") + + @classmethod + def _to_millis(cls, value: Any, marker_name: str) -> int: + """Milliseconds since the Unix epoch, rounded half away from zero, + except at the very end of the datetime range, which keeps its last + millisecond rather than rounding past it. + + Integer arithmetic, so the result is exact for any datetime; a float + ``timestamp()`` loses microseconds far from the epoch. + """ + if isinstance(value, datetime): + dt = value if value.utcoffset() is not None else value.replace(tzinfo=timezone.utc) + elif isinstance(value, date): + dt = datetime(value.year, value.month, value.day, tzinfo=timezone.utc) + else: + raise TypeError(Messages.get_formatted("EncryptionService.NeedsDate", marker_name)) + micros = (dt - _EPOCH) // _MICROSECOND + millis, remainder = divmod(abs(micros), 1000) + if remainder >= 500: + millis += 1 + millis = millis if micros >= 0 else -millis + if micros // 1000 == _MAX_EPOCH_MS: + # Rounding up past the last representable millisecond (for example + # an aware datetime.max, a common "never" value) keeps that + # millisecond. + millis = _MAX_EPOCH_MS + if not _MIN_EPOCH_MS <= millis <= _MAX_EPOCH_MS: + # A UTC offset put the instant outside what a datetime can hold, + # so it could not be read back. + raise EncryptionFailedError(Messages.get("EncryptionService.OutsideDatetimeRange"), data_type=marker_name) + return millis + + @classmethod + def _from_millis(cls, millis: int) -> datetime: + return _EPOCH + millis * _MILLISECOND + + @staticmethod + def _parse_local_datetime(text: str) -> datetime: + """Parse an ISO-8601 local date-time. + + This wrapper writes ``YYYY-MM-DDTHH:MM:SS``, with 6 fractional digits + when the microseconds aren't 0. It also accepts a time without seconds + (``...THH:MM``) and with 3, 6, or 9 fractional digits. + ``datetime.fromisoformat`` accepts the no-seconds, 3-digit, and + 6-digit forms, but on Python 3.10 (the support floor) it rejects 9 + digits, so the fraction is cut to microseconds, the finest unit + ``datetime`` can hold. Anything after the digits is kept as is. + """ + head, dot, rest = text.partition(".") + if dot: + digits = len(rest) - len(rest.lstrip("0123456789")) + if digits > 6: + text = f"{head}.{rest[:6]}{rest[digits:]}" + return datetime.fromisoformat(text) + + @staticmethod + def _truthy(value: Any) -> bool: + if isinstance(value, bool): + return value + return str(value).strip().lower() in ("t", "true", "y", "yes", "1") diff --git a/aws_advanced_python_wrapper/encryption/key_management_utility.py b/aws_advanced_python_wrapper/encryption/key_management_utility.py new file mode 100644 index 000000000..384f5df8c --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/key_management_utility.py @@ -0,0 +1,739 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import time +from contextlib import closing +from typing import (TYPE_CHECKING, Any, Dict, List, Mapping, NamedTuple, + Optional, Sequence, Set, Tuple, Type, cast) + +from aws_advanced_python_wrapper.driver_dialect_manager import \ + DriverDialectManager +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.buffers import wipe +from aws_advanced_python_wrapper.encryption.config import is_valid_identifier +from aws_advanced_python_wrapper.encryption.connection_source import ( + CallerConnectionSource, describe_failure, fetch_rows, run_statement) +from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache +from aws_advanced_python_wrapper.encryption.key_manager import ( + KeyManager, describe_kms_failure) +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, DataKeyReencryptionResult, KeyMetadata, + KeyOperation, mask_arn, replace_control_characters) +from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect +from aws_advanced_python_wrapper.errors import (AwsWrapperError, + EncryptionConfigError, + InvalidAlgorithmError, + KeyManagementError) +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) +from aws_advanced_python_wrapper.wrapper import AwsWrapperConnection + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService + +logger = Logger(__name__) + +_MAX_REPORTED_UNMATCHED_KEYS = 100 +_METADATA_COLUMNS = ("table_name", "column_name", "encryption_algorithm", "key_id", "created_at", "updated_at") +_KEY_STORAGE_COLUMNS = ("id", "key_id", "name", "master_key_arn", "encrypted_data_key", "hmac_key", "key_spec", + "created_at", "last_used_at") + + +def _stored_bytes(value: Any) -> Optional[bytes]: + """A stored value as ``bytes``, or None for a value of another type, such as text, which can't be a payload.""" + if isinstance(value, (bytes, bytearray, memoryview)): + return bytes(value) + return None + + +class _Target(NamedTuple): + """The column a re-encryption converts: the names as given, and the table and columns quoted for its SQL.""" + + table_name: str + column_name: str + primary_key_column: str + table: str + column: str + primary_key: str + + +class KeyManagementUtility: + """Administrative operations for the kms_encryption plugin: create master + keys, turn encryption on or off for a column, and rotate data keys. + + Nothing here runs during normal query execution. Call it from a migration + or setup script on a plain psycopg / mysql-connector connection (or an + ``AwsWrapperConnection``) that you own:: + + import boto3 + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.key_management_utility import KeyManagementUtility + from aws_advanced_python_wrapper.encryption.key_manager import KeyManager + + config = EncryptionConfig.from_props( + {"encryption_kms_region": "us-east-1"}, require_allowed_master_keys=False) + # create_kms_client turns off botocore's own retries, which would + # otherwise multiply with the utility's. + kms = KeyManager.create_kms_client(boto3.Session(), config) + utility = KeyManagementUtility(conn, kms, config) + arn = utility.create_master_key("users.ssn encryption") + utility.initialize_encryption_for_column("users", "ssn", arn) + conn.commit() + + The connection is never closed, committed, or rolled back here, except by + :meth:`rotate_data_key_and_reencrypt` and :meth:`reencrypt_remaining_rows`, + which commit as they go and refuse an ``AwsWrapperConnection``. Each other + operation's statements run inside your transaction, so a failed setup can + be rolled back as a unit, and nothing is stored until you commit. A KMS + master key created before a rollback is not deleted. A statement that runs + longer than ``socket_timeout`` raises ``KeyManagementError`` or + ``MetadataError``, and the connection can't be used again. + + Unlike the plugin, the utility works without + ``encryption_allowed_master_key_arns``. When the allow-list is configured, + it gates every data-key operation here too (not :meth:`create_master_key` + or :meth:`is_master_key_valid`). Add every master key a column uses to the + application's allow-list, or the plugin refuses that column. + + After a change here, running applications pick it up at their next + metadata refresh, or once their cached metadata expires if that comes + first (``encryption_metadata_cache_refresh_interval_sec``, + ``encryption_metadata_cache_expiration_sec``). + + This does not create the database-side HMAC-validation trigger, which is + required on every encrypted column. + """ + + ALIAS_PREFIX = "alias/python-kms-encryption-" + DEFAULT_REENCRYPTION_BATCH_SIZE = 1000 + MAX_REENCRYPTION_BATCH_SIZE = 100_000 + + def __init__(self, connection: Any, kms_client: Any, config: EncryptionConfig, + *, props: Optional[Dict[str, Any]] = None): + """ + :param props: properties for the utility's own statements. + ``wrapper_driver_dialect`` (``psycopg`` or ``mysql-connector-python``) + picks the driver dialect and always wins over detection from + ``connection``; pass it for a connection the utility doesn't + recognize, such as mysql-connector's ``PooledMySQLConnection``. An + unknown code, or a driver that isn't installed, raises + ``AwsWrapperError``, and an unsupported connection raises + ``EncryptionConfigError``. ``socket_timeout`` bounds each statement + only when ``connection`` is a psycopg or mysql-connector connection + itself. On mysql-connector's C extension it can't stop a statement: + the error comes after up to twice ``socket_timeout``, and the + connection must stay open until the statement ends; use + ``use_pure=True`` or leave ``socket_timeout`` unset. + """ + if connection is None or kms_client is None or config is None: + raise ValueError(Messages.get("KeyManagementUtility.MissingArgument")) + driver_props = Properties(props or {}) + target = connection.target_connection if isinstance(connection, AwsWrapperConnection) else connection + dialect = DriverDialectManager().get_dialect_for_connection(target, driver_props) + # The None check comes first so mypy narrows to a dialect that has both bases. + if dialect is None or not isinstance(dialect, EncryptionDriverDialect): + raise EncryptionConfigError( + Messages.get_formatted("KeyManagementUtility.UnsupportedDriver", type(target).__name__)) + if dialect.get_connection_from_obj(connection) is not connection: + # props' socket_timeout applies only to the driver's own connection, because that is the only connection this dialect can abort. + # On any other object only its own settings limit a statement, such as the socket_timeout an AwsWrapperConnection was opened with. + driver_props.pop(WrapperProperties.SOCKET_TIMEOUT_SEC.name, None) + self._driver_dialect: DriverDialect = dialect + self._encryption_dialect: EncryptionDriverDialect = dialect + self._connection = connection + self._connections = CallerConnectionSource(connection) + self._kms = kms_client + self._config = config + # Interpolated into every statement below. + self._schema = config.metadata_schema + # The utility never decrypts a data key, so there is nothing to cache. + self._key_manager = KeyManager(kms_client, self._connections, self._driver_dialect, self._encryption_dialect, config, + DataKeyCache(1, 1.0, enabled=False)) + # Never started, so every lookup reads the database through the + # caller's connection and sees this transaction's own changes. + self._metadata = MetadataManager(self._connections, self._driver_dialect, self._encryption_dialect, config) + + def create_master_key(self, description: str, *, policy: Optional[str] = None, + create_alias: bool = True) -> str: + """Create a symmetric KMS master key and return its ARN. A failure to + create the alias is logged, not raised: the key works by ARN.""" + if description is None: + raise ValueError(Messages.get_formatted("KeyManagementUtility.RequiredArgument", "description")) + arn = self._key_manager.create_master_key(description, policy=policy) + if create_alias: + alias = f"{self.ALIAS_PREFIX}{int(time.time() * 1000)}" + try: + self._kms.create_alias(AliasName=alias, TargetKeyId=arn) + except Exception as e: + logger.warning("KeyManagementUtility.CreateAliasFailed", mask_arn(arn), describe_kms_failure(e)) + logger.info("KeyManagementUtility.CreatedMasterKey", mask_arn(arn)) + return arn + + def initialize_encryption_for_column(self, table_name: str, column_name: str, master_key_arn: str, + algorithm: str = EncryptionAlgorithm.DEFAULT) -> int: + """Set up encryption for a column that is not encrypted yet. + + :return: the ``key_storage.id`` of the new data key. + :raises KeyManagementError: if the column is already encrypted or the + setup fails. + """ + self._require(table_name=table_name, column_name=column_name, master_key_arn=master_key_arn) + if self._metadata.is_column_encrypted(table_name, column_name): + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.AlreadyEncrypted", table_name, column_name), + operation=KeyOperation.INITIALIZE_COLUMN.value) + return self.generate_and_store_data_key(table_name, column_name, master_key_arn, algorithm) + + def generate_and_store_data_key(self, table_name: str, column_name: str, master_key_arn: str, + algorithm: str = EncryptionAlgorithm.DEFAULT) -> int: + """Generate a data key for a column and record it, replacing any + configuration the column already has (an upsert, so a setup script can + be re-run). + + :return: the ``key_storage.id`` of the new data key. + """ + self._require(table_name=table_name, column_name=column_name, master_key_arn=master_key_arn) + algorithm = algorithm or EncryptionAlgorithm.DEFAULT + # The plugin still reads and writes an AES-128-GCM column set up before. + if algorithm != EncryptionAlgorithm.AES_256_GCM: + raise InvalidAlgorithmError( + Messages.get_formatted("KeyManagementUtility.UnsupportedAlgorithm", replace_control_characters(algorithm)), + algorithm=algorithm) + + key_storage_id = self._store_new_data_key(table_name, column_name, master_key_arn, algorithm) + sql = (f"INSERT INTO {self._schema}.encryption_metadata " + "(table_name, column_name, encryption_algorithm, key_id) VALUES (%s, %s, %s, %s) " + + self._encryption_dialect.upsert_clause(("table_name", "column_name"), ("encryption_algorithm", "key_id"), + extra_assignments=("updated_at = CURRENT_TIMESTAMP",))) + self._run(KeyOperation.STORE_ENCRYPTION_METADATA, sql, (table_name, column_name, algorithm, key_storage_id)) + logger.info("KeyManagementUtility.StoredDataKey", table_name, column_name, key_storage_id) + return key_storage_id + + def rotate_data_key(self, table_name: str, column_name: str, new_master_key_arn: Optional[str] = None) -> int: + """Give an encrypted column that holds no value a new data key. A + column with a value raises ``KeyManagementError`` before any change, + because its values would stay under the data key the rotation means + to retire: use :meth:`rotate_data_key_and_reencrypt` for it. + + Omitting ``new_master_key_arn`` keeps the master key recorded in + ``key_storage``. That is only allowed with an allow-list configured to + check it against, since otherwise a row repointed at another key would + be trusted. + + :return: the ``key_storage.id`` of the new data key. + """ + self._require(table_name=table_name, column_name=column_name) + table, column = self._quoted_table(table_name), self._quoted_name(column_name, "column") + self._require_target_master_key(new_master_key_arn) + + current = self._metadata.column_config(table_name, column_name) + if current is None: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NotEncrypted", table_name, column_name), + operation=KeyOperation.ROTATE_DATA_KEY.value) + if current.algorithm != EncryptionAlgorithm.AES_256_GCM: + raise InvalidAlgorithmError( + Messages.get_formatted("KeyManagementUtility.RotateUnsupportedAlgorithm", table_name, column_name, + replace_control_characters(current.algorithm)), + algorithm=current.algorithm) + if self._fetch(KeyOperation.ROTATE_DATA_KEY, f"SELECT 1 FROM {table} WHERE {column} IS NOT NULL LIMIT 1"): + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.RotateColumnHasData", table_name, column_name), + operation=KeyOperation.ROTATE_DATA_KEY.value) + master_key_arn = new_master_key_arn or (current.key_metadata.master_key_arn if current.key_metadata else None) + if not master_key_arn: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NoCurrentMasterKey", table_name, column_name), + operation=KeyOperation.ROTATE_DATA_KEY.value) + + key_storage_id = self._store_new_data_key(table_name, column_name, master_key_arn, current.algorithm) + sql = (f"UPDATE {self._schema}.encryption_metadata SET key_id = %s, updated_at = CURRENT_TIMESTAMP " + f"WHERE table_name {self._encryption_dialect.equals_operator} %s AND column_name {self._encryption_dialect.equals_operator} %s") + if self._run(KeyOperation.UPDATE_ENCRYPTION_METADATA, sql, (key_storage_id, table_name, column_name)) == 0: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NotEncrypted", table_name, column_name), + operation=KeyOperation.ROTATE_DATA_KEY.value) + logger.info("KeyManagementUtility.RotatedDataKey", table_name, column_name, current.key_id, key_storage_id) + return key_storage_id + + def rotate_data_key_and_reencrypt(self, table_name: str, column_name: str, primary_key_column: str, + new_master_key_arn: Optional[str] = None, + batch_size: int = DEFAULT_REENCRYPTION_BATCH_SIZE) -> DataKeyReencryptionResult: + """Give an encrypted column a new data key and re-encrypt its values under it, in primary key order, + ``batch_size`` rows per transaction. + + Before any change, every value must be under the column's current key, and the table and both columns must + exist. Then the new key row is stored, the column is switched to it and that is committed. A failure before + that commit rolls everything back. After it, each batch commits on its own: a failed batch is rolled back, + the committed ones stay, and the error names the earlier key id to finish with + :meth:`reencrypt_remaining_rows`. The earlier key row and its KMS key are never deleted. + + Run it on the driver's own connection, not on an ``AwsWrapperConnection``, with no open transaction. It + changes the connection's autocommit setting and sets it back at the end. + + :param table_name: the table, optionally as ``schema.table``. The metadata is looked up by the table alone. + :param column_name: the encrypted column. + :param primary_key_column: a unique, ``NOT NULL`` column to page through the table by. + :param new_master_key_arn: the master key for the new data key; ``None`` keeps the current one, which needs + ``encryption_allowed_master_key_arns``. + :param batch_size: the rows per transaction, 1 to 100000. + :return: the counts of re-encrypted, already current and unmatched values. + :raises ValueError: for a name that isn't a plain identifier, a bad ``batch_size``, or no master key to check. + :raises KeyManagementError: if the connection is an ``AwsWrapperConnection``, a value isn't under the current + key, a master key isn't allowed, or a statement or KMS call fails. + """ + target = self._reencryption_target(table_name, column_name, primary_key_column, batch_size) + self._require_target_master_key(new_master_key_arn) + if new_master_key_arn is not None: + self._key_manager.authorize_master_key(new_master_key_arn) + conn = self._connection + autocommit = self._driver_dialect.get_autocommit(conn) + self._driver_dialect.set_autocommit(conn, False) + try: + switched = False + try: + current = self._current_column(target) + old_key = cast("KeyMetadata", current.key_metadata) + self._check_target(target) + self._precheck(target, old_key, batch_size) + master_key_arn = new_master_key_arn or cast("str", old_key.master_key_arn) + new_id = self._store_new_data_key(current.table_name, current.column_name, master_key_arn, + current.algorithm) + eq = self._encryption_dialect.equals_operator + sql = (f"UPDATE {self._schema}.encryption_metadata SET key_id = %s, updated_at = CURRENT_TIMESTAMP " + f"WHERE table_name {eq} %s AND column_name {eq} %s AND key_id {eq} %s") + params = (new_id, current.table_name, current.column_name, old_key.id) + if self._run(KeyOperation.UPDATE_ENCRYPTION_METADATA, sql, params) == 0: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.RotationSwitchConflict", table_name, column_name, + old_key.id, new_id), + operation=KeyOperation.ROTATE_DATA_KEY.value) + self._commit(conn) + switched = True + finally: + if not switched: + self._rollback(conn) + logger.info("KeyManagementUtility.RotationKeySwitched", table_name, column_name, new_id, old_key.id, + old_key.id) + new_key = self._key_row(new_id) + return self._reencrypt_rows(conn, target, current.algorithm, new_key, [old_key], batch_size) + finally: + self._driver_dialect.set_autocommit(conn, autocommit) + + def reencrypt_remaining_rows(self, table_name: str, column_name: str, primary_key_column: str, + old_key_ids: Sequence[int], + batch_size: int = DEFAULT_REENCRYPTION_BATCH_SIZE) -> DataKeyReencryptionResult: + """Re-encrypt the values still under one of ``old_key_ids`` into the column's current key, as + :meth:`rotate_data_key_and_reencrypt` does after its switch. Values already under the current key are + skipped, and values under no listed key are counted and left as they are, so it can run again. Use it to + finish a failed re-encryption, or to convert the values that connections wrote with the earlier key before + their metadata refreshed. Run it on the driver's own connection, with no open transaction. + + :param old_key_ids: the ``key_storage`` ids of the earlier keys; the current key id isn't allowed. + :return: the counts of re-encrypted, already current and unmatched values. + :raises ValueError: for a name that isn't a plain identifier, a bad ``batch_size``, no + ``encryption_allowed_master_key_arns``, or an empty ``old_key_ids``. + :raises KeyManagementError: if the connection is an ``AwsWrapperConnection``, a key id is the current one or + isn't in ``key_storage``, a master key isn't allowed, or a statement or KMS call fails. + """ + target = self._reencryption_target(table_name, column_name, primary_key_column, batch_size) + if not self._config.restricts_master_keys: + raise ValueError(Messages.get_formatted( + "KeyManagementUtility.ReencryptNeedsAllowList", WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)) + if not old_key_ids or any(key_id is None for key_id in old_key_ids): + raise ValueError(Messages.get("KeyManagementUtility.OldKeyIdsRequired")) + conn = self._connection + autocommit = self._driver_dialect.get_autocommit(conn) + self._driver_dialect.set_autocommit(conn, False) + try: + try: + current = self._current_column(target) + current_key = cast("KeyMetadata", current.key_metadata) + old_keys = [] + for key_id in dict.fromkeys(old_key_ids): + if key_id == current_key.id: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.OldKeyIsCurrent", key_id, table_name, column_name), + operation=KeyOperation.REENCRYPT_COLUMN.value) + old_keys.append(self._key_row(key_id)) + for key in old_keys: + self._key_manager.authorize_master_key(key.master_key_arn) + self._check_target(target) + finally: + self._rollback(conn) + return self._reencrypt_rows(conn, target, current.algorithm, current_key, old_keys, batch_size) + finally: + self._driver_dialect.set_autocommit(conn, autocommit) + + def remove_encryption_for_column(self, table_name: str, column_name: str) -> bool: + """Stop encrypting a column by deleting its ``encryption_metadata`` + row. The key stays in ``key_storage`` so values already written can + still be decrypted. + + :return: ``True`` when a configuration row was removed. + """ + self._require(table_name=table_name, column_name=column_name) + sql = (f"DELETE FROM {self._schema}.encryption_metadata " + f"WHERE table_name {self._encryption_dialect.equals_operator} %s AND column_name {self._encryption_dialect.equals_operator} %s") + removed = self._run(KeyOperation.DELETE_ENCRYPTION_METADATA, sql, (table_name, column_name)) > 0 + if not removed: + logger.warning("KeyManagementUtility.NothingToRemove", table_name, column_name) + return removed + + def columns_using_key(self, key_storage_id: int) -> List[str]: + """The ``"table.column"`` names that use a ``key_storage.id``, to see + what rotating or retiring that key would affect.""" + sql = (f"SELECT table_name, column_name FROM {self._schema}.encryption_metadata " + f"WHERE key_id {self._encryption_dialect.equals_operator} %s ORDER BY table_name, column_name") + try: + with self._connections.connection() as conn: + rows = fetch_rows(self._driver_dialect, conn, sql, (key_storage_id,)) + except Exception as e: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", + KeyOperation.SELECT_COLUMNS_USING_KEY.value, e), + operation=KeyOperation.SELECT_COLUMNS_USING_KEY.value) from e + return [f"{r['table_name']}.{r['column_name']}" for r in rows] + + def validate_schema(self) -> List[str]: + """Check the metadata tables in ``encryption_metadata_schema``: that both exist with their columns, that + ``encryption_metadata`` has a primary key or unique constraint on ``(table_name, column_name)``, that + ``key_storage`` has its primary key on ``id`` and, when nothing else is wrong, that + ``encryption_metadata.key_id`` has a foreign key to ``key_storage.id``. Nothing calls it on its own. It reads + only the catalog, so a user with ``SELECT`` on the schema can run it. + + :return: one message per problem found, or an empty list when the schema is sound. + :raises KeyManagementError: if a catalog query fails. + """ + dialect = self._encryption_dialect + schema = self._schema.lower() + problems: List[str] = [] + for table, required in (("encryption_metadata", _METADATA_COLUMNS), ("key_storage", _KEY_STORAGE_COLUMNS)): + if not self._fetch(KeyOperation.VALIDATE_SCHEMA, dialect.schema_table_sql, (schema, table)): + problems.append(Messages.get_formatted("KeyManagementUtility.SchemaMissingTable", self._schema, table)) + continue + found = {str(row["column_name"]).lower() + for row in self._fetch(KeyOperation.VALIDATE_SCHEMA, dialect.schema_columns_sql, (schema, table))} + problems.extend(Messages.get_formatted("KeyManagementUtility.SchemaMissingColumn", self._schema, table, column) + for column in required if column not in found) + if table == "encryption_metadata": + if not self._has_key(schema, table, ("PRIMARY KEY", "UNIQUE"), {"table_name", "column_name"}): + problems.append(Messages.get_formatted("KeyManagementUtility.SchemaMissingUniqueKey", self._schema)) + elif not self._has_key(schema, table, ("PRIMARY KEY",), {"id"}): + problems.append(Messages.get_formatted("KeyManagementUtility.SchemaMissingPrimaryKey", self._schema)) + if problems: + return problems + foreign_keys = self._fetch(KeyOperation.VALIDATE_SCHEMA, dialect.schema_foreign_keys_sql, + (schema, "encryption_metadata")) + if not any((str(row["column_name"]).lower(), str(row["referenced_table"]).lower(), + str(row["referenced_column"]).lower()) == ("key_id", "key_storage", "id") for row in foreign_keys): + problems.append(Messages.get_formatted("KeyManagementUtility.SchemaMissingForeignKey", self._schema, + self._schema)) + return problems + + def is_master_key_valid(self, master_key_arn: str) -> bool: + """``True`` when the master key exists, is enabled, and can encrypt + and decrypt. ``False`` also covers "could not check"; see + :meth:`KeyManager.is_master_key_valid`.""" + self._require(master_key_arn=master_key_arn) + return self._key_manager.is_master_key_valid(master_key_arn) + + def _store_new_data_key(self, table_name: str, column_name: str, master_key_arn: str, + algorithm: str) -> int: + """Generate a data key, store it, and return its ``key_storage.id``.""" + generated = self._key_manager.generate_data_key(master_key_arn, algorithm) + try: + # Nothing here encrypts with the plaintext key; only its + # KMS-encrypted form is stored. + stored = self._key_manager.store_key_metadata(KeyMetadata( + key_name=f"key-{table_name}-{column_name}-{int(time.time() * 1000)}", + master_key_arn=master_key_arn, + encrypted_data_key=generated.encrypted_data_key, + hmac_key=generated.hmac_key, + key_spec=generated.key_spec, + )) + return cast("int", stored.id) + finally: + wipe(generated.plaintext) + + def _run(self, operation: KeyOperation, sql: str, params: Any) -> int: + try: + with self._connections.connection() as conn: + return run_statement(self._driver_dialect, conn, sql, params) + except Exception as e: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", operation.value, e), + operation=operation.value) from e + + def _has_key(self, schema: str, table: str, kinds: Tuple[str, ...], columns: Set[str]) -> bool: + constraints: Dict[Any, Set[str]] = {} + for row in self._fetch(KeyOperation.VALIDATE_SCHEMA, self._encryption_dialect.schema_key_constraints_sql, + (schema, table)): + if str(row["constraint_type"]).upper() in kinds: + constraints.setdefault(row["constraint_name"], set()).add(str(row["column_name"]).lower()) + return columns in constraints.values() + + def _reencryption_target(self, table_name: str, column_name: str, primary_key_column: str, + batch_size: int) -> _Target: + if isinstance(self._connection, AwsWrapperConnection): + # The plugin on that connection would encrypt the payloads the utility writes a second time. + raise KeyManagementError(Messages.get("KeyManagementUtility.PluginConnectionNotAllowed"), + operation=KeyOperation.REENCRYPT_COLUMN.value) + self._require(table_name=table_name, column_name=column_name, primary_key_column=primary_key_column) + table = self._quoted_table(table_name) + column = self._quoted_name(column_name, "column") + primary_key = self._quoted_name(primary_key_column, "primary key column") + if primary_key_column.lower() == column_name.lower(): + raise ValueError(Messages.get_formatted("KeyManagementUtility.PrimaryKeySameAsColumn", primary_key_column)) + if isinstance(batch_size, bool) or not isinstance(batch_size, int) or not ( + 1 <= batch_size <= self.MAX_REENCRYPTION_BATCH_SIZE): + raise ValueError(Messages.get_formatted( + "KeyManagementUtility.InvalidBatchSize", self.MAX_REENCRYPTION_BATCH_SIZE, batch_size)) + return _Target(table_name.rpartition(".")[2], column_name, primary_key_column, table, column, primary_key) + + def _quoted_table(self, table_name: str) -> str: + parts = table_name.split(".") + if len(parts) > 2 or not all(is_valid_identifier(part) for part in parts): + raise ValueError(Messages.get_formatted( + "KeyManagementUtility.InvalidName", replace_control_characters(table_name), "table")) + return ".".join(self._encryption_dialect.quote_identifier(part) for part in parts) + + def _quoted_name(self, name: str, kind: str) -> str: + if not is_valid_identifier(name): + raise ValueError(Messages.get_formatted( + "KeyManagementUtility.InvalidName", replace_control_characters(str(name)), kind)) + return self._encryption_dialect.quote_identifier(name) + + def _require_target_master_key(self, new_master_key_arn: Optional[str]) -> None: + if new_master_key_arn is None and not self._config.restricts_master_keys: + raise ValueError(Messages.get_formatted( + "KeyManagementUtility.RotateNeedsMasterKey", WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)) + + def _current_column(self, target: _Target) -> ColumnEncryptionConfig: + """The column's configuration, refused unless it is AES-256-GCM with a usable key row under an allowed master + key.""" + current = self._metadata.column_config(target.table_name, target.column_name) + if current is None: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NotEncrypted", target.table_name, target.column_name), + operation=KeyOperation.REENCRYPT_COLUMN.value) + if current.algorithm != EncryptionAlgorithm.AES_256_GCM: + raise InvalidAlgorithmError( + Messages.get_formatted("KeyManagementUtility.RotateUnsupportedAlgorithm", target.table_name, + target.column_name, replace_control_characters(current.algorithm)), + algorithm=current.algorithm) + key = current.key_metadata + if key is None or key.id is None or not key.is_usable: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.KeyRowUnusable", current.key_id), + operation=KeyOperation.REENCRYPT_COLUMN.value) + self._key_manager.authorize_master_key(key.master_key_arn) + return current + + def _key_row(self, key_id: int) -> KeyMetadata: + key = self._key_manager.key_metadata_by_id(key_id) + if key is None: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.OldKeyNotFound", key_id), + operation=KeyOperation.REENCRYPT_COLUMN.value) + if key.id is None or not key.is_usable: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.KeyRowUnusable", key_id), + operation=KeyOperation.REENCRYPT_COLUMN.value) + return key + + def _check_target(self, target: _Target) -> None: + """Refuse a table or column that doesn't exist and, where the engine needs it, a primary key column whose + type isn't built in, before any change.""" + sql = f"SELECT {target.primary_key}, {target.column} FROM {target.table} WHERE FALSE" + failure: Optional[str] = None + try: + with self._connections.connection() as conn: + fetch_rows(self._driver_dialect, conn, sql) + except Exception as e: + failure = describe_failure(e) + if failure is not None: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.RelationCheckFailed", target.table_name, + target.column_name, target.primary_key_column, failure), + operation=KeyOperation.REENCRYPT_COLUMN.value) + type_sql = self._encryption_dialect.key_column_type_sql + if type_sql is None: + return + rows = self._fetch(KeyOperation.REENCRYPT_COLUMN, type_sql, (target.table, target.primary_key_column)) + if not rows or not rows[0]["built_in"]: + type_name = rows[0]["type_name"] if rows else "unknown" + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.UnsupportedPrimaryKeyType", target.table_name, + target.primary_key_column, type_name), + operation=KeyOperation.REENCRYPT_COLUMN.value) + + def _page_sql(self, target: _Target, after: Any, batch_size: int, for_update: bool) -> Tuple[str, Tuple[Any, ...]]: + sql = (f"SELECT {target.primary_key}, {target.column} FROM {target.table} WHERE {target.column} IS NOT NULL " + f"AND {target.primary_key} IS NOT NULL") + params: Tuple[Any, ...] = (batch_size,) + if after is not None: + sql += f" AND {target.primary_key} {self._encryption_dialect.greater_than_operator} %s" + params = (after, batch_size) + sql += f" ORDER BY {target.primary_key} LIMIT %s" + return (sql + " FOR UPDATE" if for_update else sql), params + + def _precheck(self, target: _Target, key: KeyMetadata, batch_size: int) -> None: + from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService + mismatched = 0 + after = None + while True: + sql, params = self._page_sql(target, after, batch_size, False) + rows = [tuple(row.values()) for row in self._fetch(KeyOperation.REENCRYPT_COLUMN, sql, params)] + for _, value in rows: + stored = _stored_bytes(value) + if stored is None or not self._is_under(EncryptionService, stored, key): + mismatched += 1 + if len(rows) < batch_size: + break + after = rows[-1][0] + if mismatched: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.RotationPrecheckFailed", target.table_name, + target.column_name, mismatched, key.id), + operation=KeyOperation.ROTATE_DATA_KEY.value) + + def _reencrypt_rows(self, conn: Any, target: _Target, algorithm: str, key: KeyMetadata, + old_keys: List[KeyMetadata], batch_size: int) -> DataKeyReencryptionResult: + """A value under no listed key is never sent to KMS; each value's key id picks the key row its HMAC is checked + against.""" + # Imported here, as the plugin does, so the utility imports without the encryption extra. + from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService + old_by_id = {old.id: old for old in old_keys} + old_ids = tuple(cast("int", old.id) for old in old_keys) + listed = ", ".join(str(key_id) for key_id in old_ids) + eq = self._encryption_dialect.equals_operator + data_keys: Dict[Optional[int], bytearray] = {} + reencrypted = already_current = unmatched = batches = batch = 0 + unmatched_keys: List[Any] = [] + after = None + logger.info("KeyManagementUtility.ReencryptStarting", target.table_name, target.column_name, key.id, listed, + batch_size) + try: + while True: + batch += 1 + converted = current = 0 + skipped: List[Any] = [] + rows: List[Tuple[Any, ...]] = [] + failure: Optional[str] = None + try: + with closing(conn.cursor()) as cursor: + sql, params = self._page_sql(target, after, batch_size, True) + self._execute(conn, cursor, sql, params) + fetched = self._driver_dialect.execute( + DbApiMethod.CURSOR_FETCHALL.method_name, lambda: cursor.fetchall(), conn=conn) + rows = [tuple(row.values()) if isinstance(row, Mapping) else tuple(row) for row in fetched] + prefix = self._encryption_dialect.binary_placeholder_prefix(cursor) or "" + update_sql = (f"UPDATE {target.table} SET {target.column} = {prefix}%s WHERE {target.primary_key} " + f"{eq} %s AND {target.column} {eq} {prefix}%s") + for primary_key, value in rows: + stored = _stored_bytes(value) + if stored is not None and self._is_under(EncryptionService, stored, key): + current += 1 + continue + old = None if stored is None else old_by_id.get(EncryptionService.key_id_from_payload(stored)) + if stored is None or old is None or not self._is_under(EncryptionService, stored, old): + skipped.append(primary_key) + continue + sealed = EncryptionService.reencrypt( + stored, self._data_key(old, data_keys), cast("bytes", old.hmac_key), + self._data_key(key, data_keys), cast("bytes", key.hmac_key), algorithm, + new_key_id=cast("int", key.id)) + self._execute(conn, cursor, update_sql, (sealed, primary_key, stored)) + if cursor.rowcount != 1: + raise KeyManagementError(Messages.get("KeyManagementUtility.RowUpdateMissed"), + operation=KeyOperation.REENCRYPT_COLUMN.value) + converted += 1 + self._commit(conn) + except Exception as e: + # A driver error can quote the payloads; keep only its type and codes, and chain nothing. + failure = str(e) if isinstance(e, AwsWrapperError) else describe_failure(e) + if failure is not None: + self._rollback(conn) + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.ReencryptFailed", target.table_name, + target.column_name, batch, reencrypted, failure, key.id, listed), + operation=KeyOperation.REENCRYPT_COLUMN.value) + if rows: + batches += 1 + reencrypted += converted + already_current += current + unmatched += len(skipped) + unmatched_keys.extend(skipped[:_MAX_REPORTED_UNMATCHED_KEYS - len(unmatched_keys)]) + if len(rows) < batch_size: + break + after = rows[-1][0] + finally: + for data_key in data_keys.values(): + wipe(data_key) + if unmatched: + logger.warning("KeyManagementUtility.UnmatchedRows", target.table_name, target.column_name, unmatched, + key.id, listed) + logger.info("KeyManagementUtility.ReencryptCompleted", target.table_name, target.column_name, reencrypted, + already_current, unmatched, batches) + return DataKeyReencryptionResult(target.table_name, target.column_name, cast("int", key.id), old_ids, + reencrypted, already_current, unmatched, batches, tuple(unmatched_keys)) + + @staticmethod + def _is_under(crypto: Type[EncryptionService], stored: bytes, key: KeyMetadata) -> bool: + return crypto.key_id_from_payload(stored) == key.id and crypto.verify(stored, cast("bytes", key.hmac_key)) + + def _data_key(self, key: KeyMetadata, data_keys: Dict[Optional[int], bytearray]) -> bytearray: + if key.id not in data_keys: + data_keys[key.id] = self._key_manager.decrypt_data_key(key.encrypted_data_key, key.master_key_arn) + return data_keys[key.id] + + def _execute(self, conn: Any, cursor: Any, sql: str, params: Sequence[Any]) -> None: + self._driver_dialect.execute(DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(sql, params), sql, + conn=conn) + + def _commit(self, conn: Any) -> None: + self._driver_dialect.execute(DbApiMethod.CONNECTION_COMMIT.method_name, lambda: conn.commit(), conn=conn) + + def _rollback(self, conn: Any) -> None: + try: + self._driver_dialect.execute(DbApiMethod.CONNECTION_ROLLBACK.method_name, lambda: conn.rollback(), conn=conn) + except Exception as e: + logger.warning("KeyManagementUtility.RollbackFailed", describe_failure(e)) + + def _fetch(self, operation: KeyOperation, sql: str, params: Sequence[Any] = ()) -> List[Dict[str, Any]]: + failure: Optional[str] = None + try: + with self._connections.connection() as conn: + return fetch_rows(self._driver_dialect, conn, sql, params) + except Exception as e: + # A driver error can quote the row's values; keep only its type and codes, and chain nothing. + failure = describe_failure(e) + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", operation.value, failure), + operation=operation.value) + + @staticmethod + def _require(**arguments: Any) -> None: + for name, value in arguments.items(): + if value is None or (isinstance(value, str) and not value.strip()): + raise ValueError(Messages.get_formatted("KeyManagementUtility.RequiredArgument", name)) diff --git a/aws_advanced_python_wrapper/encryption/key_manager.py b/aws_advanced_python_wrapper/encryption/key_manager.py new file mode 100644 index 000000000..704721d32 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/key_manager.py @@ -0,0 +1,459 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import base64 +import hashlib +import logging +import os +import random +import threading +import time +import uuid +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar + +from botocore.config import Config +from botocore.exceptions import ClientError +from botocore.exceptions import ConnectionError as BotoConnectionError +from botocore.exceptions import (ConnectTimeoutError, EndpointConnectionError, + HTTPClientError) + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.buffers import wipe +from aws_advanced_python_wrapper.encryption.connection_source import ( + describe_failure, fetch_rows, run_statement) +from aws_advanced_python_wrapper.encryption.models import (DEFAULT_KEY_SPEC, + KeyMetadata, + KeyOperation, + mask_arn, + mask_error_text, + mask_key_id) +from aws_advanced_python_wrapper.errors import (InvalidKeyMetadataError, + KeyManagementError, + UnauthorizedMasterKeyError) +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import WrapperProperties + +if TYPE_CHECKING: + from boto3 import Session + + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.connection_source import \ + ConnectionSource + from aws_advanced_python_wrapper.encryption.data_key_cache import \ + DataKeyCache + from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect + +logger = Logger(__name__) + +T = TypeVar("T") + + +class _NoKmsPlaintext(logging.Filter): + """Drops botocore's DEBUG records of a response body that holds the + bytes ``"Plaintext"``, as every KMS response with a plaintext data key + does. Another service's response body that holds them is dropped too.""" + + def filter(self, record: logging.LogRecord) -> bool: + args = record.args if isinstance(record.args, tuple) else () + return not any(isinstance(a, (bytes, bytearray)) and b'"Plaintext"' in a for a in args) + + +class _NoKmsRequestCredentials(logging.Filter): + """Drops botocore's DEBUG records of each signed KMS request, which + carry its access key id, session token and signature. ``TrentService.`` is + the target prefix of every KMS operation, so other services' signed + requests keep these records. The separate signature record is dropped for + every service: it doesn't name its service, and other services' sent + requests keep their signatures in their other request records.""" + + def filter(self, record: logging.LogRecord) -> bool: + try: + message = record.getMessage() + except Exception: # noqa: BLE001 - a filter must never raise; a record that can't be formatted passes unchanged + return True + if message.startswith("Signature:\n"): + return False + if "TrentService." not in message: + return True + lowered = message.lower() + return "authorization" not in lowered and "x-amz-security-token" not in lowered + + +# A logger's filters don't see its children's records, so each filter goes on +# the logger that emits the records. KeyManager.__init__ and create_kms_client +# install them once per process, so a filter that was removed on purpose stays +# removed. +_FILTER_LOCK = threading.Lock() +_filters_installed = False + + +def _install_botocore_filters() -> None: + global _filters_installed + with _FILTER_LOCK: + if _filters_installed: + return + logging.getLogger("botocore.parsers").addFilter(_NoKmsPlaintext()) + request_filter = _NoKmsRequestCredentials() + logging.getLogger("botocore.endpoint").addFilter(request_filter) + logging.getLogger("botocore.auth").addFilter(request_filter) + _filters_installed = True + + +def describe_kms_failure(error: Exception) -> str: + """Summarize a failed KMS call for a log record or an error message. + KMS's own text can name the master key and the caller's role session, so + an AWS error keeps only its class, error code and HTTP status, and any + other error keeps its class and its text masked by :func:`mask_error_text`.""" + name = type(error).__name__ + if isinstance(error, ClientError): + code = error.response.get("Error", {}).get("Code") or "unknown" + status = error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") or "unknown" + return f"{name}, error code {mask_error_text(str(code))}, HTTP status {status}" + text = mask_error_text(str(error)) + if text: + return f"{name}: {text}" + return name + + +@dataclass(frozen=True, eq=False) +class GeneratedDataKey: + """A data key fresh from KMS. ``plaintext`` is a ``bytearray`` so the + caller can wipe it once used; ``repr`` never shows key material.""" + + plaintext: bytearray = field(repr=False) + encrypted_data_key: str = field(repr=False) + hmac_key: bytes = field(repr=False) + key_spec: str = DEFAULT_KEY_SPEC + + +class KeyManager: + """Owns the data keys: generates them through KMS, stores them in + ``key_storage``, and decrypts them again, caching the plaintext keys. + + The data-key operations (``GenerateDataKey`` and ``Decrypt``) are gated on + ``encryption_allowed_master_key_arns`` before KMS is contacted, including + on a data-key cache hit. :meth:`create_master_key` and + :meth:`is_master_key_valid` are not gated: they use no data key. Plaintext + data keys never reach the database. + + Building a ``KeyManager`` turns on the log filters that + :meth:`create_kms_client` describes, whichever KMS client it is given. + """ + + HMAC_KEY_LENGTH = 32 + MASTER_KEY_SPEC = "SYMMETRIC_DEFAULT" + KEY_USAGE = "ENCRYPT_DECRYPT" + MAX_BACKOFF_SEC = 20.0 + JITTER_RATIO = 0.25 + # botocore defaults both to 60 s. A KMS call normally takes milliseconds, + # so an unreachable or hung endpoint fails an attempt in seconds rather + # than a minute. + CONNECT_TIMEOUT_SEC = 5.0 + READ_TIMEOUT_SEC = 10.0 + _CACHE_KEY_PREFIX = "datakey_" + + # KMS error codes worth retrying, in addition to any 5xx or 429 response. + RETRYABLE_ERROR_CODES = frozenset({ + "ThrottlingException", + "LimitExceededException", + "KMSInternalException", + "KeyUnavailableException", + "DependencyTimeoutException", + "RequestTimeout", + "ServiceUnavailable", + "InternalFailure", + }) + + # Errors that mean KMS did not act on the request, so even a call that is + # not idempotent (CreateKey) can be retried without creating a duplicate. + NOT_PROCESSED_ERROR_CODES = frozenset({"ThrottlingException"}) + + def __init__(self, kms_client: Any, connection_source: ConnectionSource, driver_dialect: DriverDialect, + encryption_dialect: EncryptionDriverDialect, config: EncryptionConfig, data_key_cache: DataKeyCache, + *, sleep: Callable[[float], None] = time.sleep): + self._kms = kms_client + self._connections = connection_source + self._driver_dialect = driver_dialect + self._encryption_dialect = encryption_dialect + self._config = config + self._cache = data_key_cache + self._sleep = sleep + _install_botocore_filters() + + @staticmethod + def create_kms_client(session: Session, config: EncryptionConfig) -> Any: + """Build a KMS client for ``config``. + + botocore's own retries are turned off because :class:`KeyManager` + retries itself. botocore cannot be given the configured backoff base + (``encryption_key_management_retry_backoff_base_sec``), and leaving + both on would multiply the attempt count. Connect and read timeouts + are short, so an unreachable KMS endpoint fails in seconds rather than + minutes. + + The first call in a process also filters botocore's DEBUG records of + KMS calls, which would otherwise carry the data keys in response + bodies and the access key id, session token and signature of each + request. It changes no logger's level, handlers or propagation, and no + formatter. The filters it installs also drop, for every AWS service, + botocore's separate record of each request's signature and any + response body that holds the bytes ``"Plaintext"``. + """ + _install_botocore_filters() + client_config = Config(region_name=config.kms_region, retries={"total_max_attempts": 1}, + connect_timeout=KeyManager.CONNECT_TIMEOUT_SEC, + read_timeout=KeyManager.READ_TIMEOUT_SEC) + if config.kms_endpoint: + return session.client("kms", endpoint_url=config.kms_endpoint, config=client_config) + return session.client("kms", config=client_config) + + def decrypt_data_key(self, encrypted_data_key: Optional[str], master_key_arn: Optional[str]) -> bytearray: + """Return the plaintext of a stored data key, from the cache when + possible. The caller owns the returned buffer and should wipe it. + + :raises UnauthorizedMasterKeyError: the master key is not allowed; + KMS is not called. + :raises InvalidKeyMetadataError: there is no usable encrypted data key. + :raises KeyManagementError: KMS rejected the request. + """ + self.authorize_master_key(master_key_arn) + if encrypted_data_key is None or not encrypted_data_key.strip(): + raise InvalidKeyMetadataError( + Messages.get("KeyManager.MissingEncryptedDataKey"), operation=KeyOperation.DECRYPT_DATA_KEY.value) + + cache_key = self.data_key_cache_key(encrypted_data_key) + cached = self._cache.get(cache_key) + if cached is not None: + return cached + + try: + ciphertext = base64.b64decode("".join(encrypted_data_key.split()), validate=True) + except ValueError: + # Catches binascii.Error (bad base64) and the plain ValueError + # b64decode raises for a non-ASCII string, as in a hand-edited row. + ciphertext = None + if not ciphertext: + raise InvalidKeyMetadataError( + Messages.get("KeyManager.MalformedEncryptedDataKey"), operation=KeyOperation.DECRYPT_DATA_KEY.value) + + # KeyId is passed as defense in depth: a data key wrapped under a + # different master key than its row names fails inside KMS too. With + # no ARN (only possible without an allow-list), KMS reads the key from + # the ciphertext. + request: Dict[str, Any] = {"CiphertextBlob": ciphertext} + if master_key_arn: + request["KeyId"] = master_key_arn + response = self._call_kms(KeyOperation.DECRYPT_DATA_KEY, lambda: self._kms.decrypt(**request)) + plaintext = bytearray(response["Plaintext"]) + self._cache.put(cache_key, plaintext) + return plaintext + + def generate_data_key(self, master_key_arn: str, + algorithm: str = EncryptionAlgorithm.DEFAULT) -> GeneratedDataKey: + """Ask KMS for a new data key sized for ``algorithm``, plus a random + HMAC key. + + :raises UnauthorizedMasterKeyError: the master key is not allowed. + :raises KeyManagementError: KMS rejected the request. + """ + self.authorize_master_key(master_key_arn) + key_spec = EncryptionAlgorithm.data_key_spec(algorithm) + response = self._call_kms( + KeyOperation.GENERATE_DATA_KEY, lambda: self._kms.generate_data_key(KeyId=master_key_arn, KeySpec=key_spec)) + plaintext = bytearray(response["Plaintext"]) + if len(plaintext) != EncryptionAlgorithm.key_length(algorithm): + # Catch a mis-sized key now, at setup, rather than on the first + # write to the column. (Some KMS emulators ignore KeySpec.) + length = len(plaintext) + wipe(plaintext) + raise KeyManagementError( + Messages.get_formatted("KeyManager.WrongDataKeyLength", length, key_spec, algorithm), + operation=KeyOperation.GENERATE_DATA_KEY.value) + return GeneratedDataKey( + plaintext=plaintext, + encrypted_data_key=base64.b64encode(response["CiphertextBlob"]).decode("ascii"), + hmac_key=os.urandom(self.HMAC_KEY_LENGTH), + key_spec=key_spec, + ) + + @classmethod + def data_key_cache_key(cls, encrypted_data_key: str) -> str: + """Hash the encrypted data key so it never appears as a cache key.""" + digest = hashlib.sha256(encrypted_data_key.encode("utf-8")).digest() + return cls._CACHE_KEY_PREFIX + base64.b64encode(digest).decode("ascii") + + def create_master_key(self, description: str, *, policy: Optional[str] = None) -> str: + """Create a symmetric KMS key and return its ARN. Not gated on the + allow-list: the new key cannot be listed before it exists. + + Only failures that mean KMS did not act are retried: throttling, and + a connection that was never made. After a timeout or a server error + the key may already exist, and a retry would create a second one. + """ + request = {"Description": description, "KeyUsage": self.KEY_USAGE, "KeySpec": self.MASTER_KEY_SPEC} + if policy and policy.strip(): + request["Policy"] = policy + response = self._call_kms(KeyOperation.CREATE_MASTER_KEY, lambda: self._kms.create_key(**request), + retryable=self._is_not_processed) + return response["KeyMetadata"]["Arn"] + + def is_master_key_valid(self, master_key_arn: str) -> bool: + """``True`` when the key exists, is enabled, and can encrypt/decrypt. + + ``False`` also covers "could not check" (no ``kms:DescribeKey`` + permission, KMS unreachable); the reason is logged as a warning. + """ + try: + metadata = self._call_kms( + KeyOperation.DESCRIBE_MASTER_KEY, lambda: self._kms.describe_key(KeyId=master_key_arn))["KeyMetadata"] + except KeyManagementError as e: + logger.warning("KeyManager.MasterKeyValidationFailed", mask_arn(master_key_arn), e) + return False + return (bool(metadata.get("Enabled")) and metadata.get("KeyState") == "Enabled" + and metadata.get("KeyUsage") == self.KEY_USAGE) + + def store_key_metadata(self, key_metadata: KeyMetadata) -> KeyMetadata: + """Insert a ``key_storage`` row and return it with ``id`` (and a + generated ``key_id`` UUID, if none was given) filled in. + + Timestamps come from the database's ``CURRENT_TIMESTAMP`` defaults, so + the stored values follow the database's own time zone handling. + """ + if not key_metadata.is_usable: + raise InvalidKeyMetadataError( + Messages.get("KeyManager.RefusingUnusableKeyMetadata"), operation=KeyOperation.STORE_KEY_METADATA.value) + + to_store = key_metadata if key_metadata.key_id else replace(key_metadata, key_id=str(uuid.uuid4())) + sql = (f"INSERT INTO {self._config.metadata_schema}.key_storage " + "(key_id, name, master_key_arn, encrypted_data_key, hmac_key, key_spec) " + "VALUES (%s, %s, %s, %s, %s, %s)") + params = (to_store.key_id, to_store.key_name, to_store.master_key_arn, + to_store.encrypted_data_key, to_store.hmac_key, to_store.key_spec) + + failure: Optional[str] = None + try: + with self._connections.connection() as conn: + new_id = self._encryption_dialect.insert_returning_id(conn, sql, params) + except Exception as e: + # The bound HMAC key is a secret, and some driver errors quote the + # interpolated statement. Keep only the exception type and the + # driver's error codes, and raise outside this block so the driver + # error is not even chained as __context__. + failure = describe_failure(e) + if failure is not None: + raise KeyManagementError( + Messages.get_formatted("KeyManager.StoreKeyMetadataFailed", failure), + operation=KeyOperation.STORE_KEY_METADATA.value) + return replace(to_store, id=new_id) + + def key_metadata_by_id(self, key_storage_id: int) -> Optional[KeyMetadata]: + """Read one ``key_storage`` row by its integer ``id``.""" + sql = ("SELECT id, key_id, name, master_key_arn, encrypted_data_key, hmac_key, key_spec, " + f"created_at, last_used_at FROM {self._config.metadata_schema}.key_storage WHERE id {self._encryption_dialect.equals_operator} %s") + failure: Optional[str] = None + try: + with self._connections.connection() as conn: + rows = fetch_rows(self._driver_dialect, conn, sql, (key_storage_id,)) + except Exception as e: + # A driver error can quote the row's bytes. Keep only its type and + # codes, and raise outside this block so it isn't chained. + failure = describe_failure(e) + if failure is not None: + raise KeyManagementError( + Messages.get_formatted("KeyManager.ReadKeyMetadataFailed", failure), + operation=KeyOperation.GET_KEY_METADATA.value) + return KeyMetadata.from_row(rows[0]) if rows else None + + def touch_key(self, key_uuid: str) -> None: + """Stamp ``last_used_at``. Bookkeeping only: failures are logged.""" + sql = (f"UPDATE {self._config.metadata_schema}.key_storage SET last_used_at = CURRENT_TIMESTAMP " + f"WHERE key_id {self._encryption_dialect.equals_operator} %s") + try: + with self._connections.connection() as conn: + run_statement(self._driver_dialect, conn, sql, (key_uuid,)) + except Exception as e: + logger.debug("KeyManager.TouchKeyFailed", mask_key_id(key_uuid), describe_failure(e)) + + def authorize_master_key(self, master_key_arn: Optional[str]) -> None: + """Raise :class:`UnauthorizedMasterKeyError` unless the allow-list allows ``master_key_arn``.""" + if not self._config.is_master_key_allowed(master_key_arn): + raise UnauthorizedMasterKeyError( + Messages.get_formatted("KeyManager.UnauthorizedMasterKey", mask_arn(master_key_arn), + WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name), + operation=KeyOperation.AUTHORIZE_MASTER_KEY.value) + + def _call_kms(self, operation: KeyOperation, call: Callable[[], T], + retryable: Optional[Callable[[Exception], bool]] = None) -> T: + """Run a KMS call, retrying throttling and transient failures with + exponential backoff and jitter. ``retryable`` decides which failures + are retried; it defaults to :meth:`_is_retryable`.""" + is_retryable = retryable or self._is_retryable + max_retries = self._config.key_management_max_retries + attempt = 0 + while True: + try: + return call() + except Exception as e: + # Keep only the summary, and raise outside this block, so the + # SDK's error and its text aren't chained as __context__. + failure = describe_kms_failure(e) + retry = attempt < max_retries and is_retryable(e) + if not retry: + raise KeyManagementError( + Messages.get_formatted("KeyManager.KmsCallFailed", operation.value, attempt + 1, failure), + operation=operation.value) + delay = self._backoff_sec(attempt) + logger.debug("KeyManager.Retrying", operation.value, attempt + 1, max_retries + 1, round(delay, 3), failure) + self._sleep(delay) + attempt += 1 + + @classmethod + def _is_retryable(cls, error: Exception) -> bool: + if isinstance(error, (BotoConnectionError, HTTPClientError)): + return True + if isinstance(error, ClientError): + status = error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") + if status is not None and (status >= 500 or status == 429): + return True + return error.response.get("Error", {}).get("Code") in cls.RETRYABLE_ERROR_CODES + return False + + @classmethod + def _is_not_processed(cls, error: Exception) -> bool: + # EndpointConnectionError and ConnectTimeoutError are raised before the + # request is sent. + if isinstance(error, (EndpointConnectionError, ConnectTimeoutError)): + return True + if isinstance(error, ClientError): + status = error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") + code = error.response.get("Error", {}).get("Code") + return status == 429 or code in cls.NOT_PROCESSED_ERROR_CODES + return False + + def _backoff_sec(self, attempt: int) -> float: + """``base * 2**attempt`` +/- 25%, at least ``base``, at most 20 s. + + The cap wins over the floor when the configured base exceeds it. + """ + base = self._config.key_management_retry_backoff_base_sec + exponential = base * (2 ** attempt) + jitter = exponential * self.JITTER_RATIO * random.uniform(-1.0, 1.0) + return min(max(exponential + jitter, base), self.MAX_BACKOFF_SEC) diff --git a/aws_advanced_python_wrapper/encryption/kms_encryption_plugin.py b/aws_advanced_python_wrapper/encryption/kms_encryption_plugin.py new file mode 100644 index 000000000..c130499b0 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/kms_encryption_plugin.py @@ -0,0 +1,847 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import threading +from contextlib import nullcontext +from enum import Enum +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List, + Mapping, Optional, Sequence, Set, Tuple, Union) +from weakref import WeakKeyDictionary + +from aws_advanced_python_wrapper.aws_credentials_manager import \ + AwsCredentialsManager +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +from aws_advanced_python_wrapper.encryption.connection_source import \ + PluginConnectionSource +from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache +from aws_advanced_python_wrapper.encryption.key_manager import KeyManager +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker +from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect +from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + EncryptionFailedError, + IntegrityCheckError, + InvalidAlgorithmError, + InvalidKeyMetadataError, + MetadataError) +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.plugin import (CanReleaseResources, Plugin, + PluginFactory) +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata) + from aws_advanced_python_wrapper.encryption.sql_analyzer import \ + StatementAnalysis + from aws_advanced_python_wrapper.encryption.sql_tokenizer import ColumnRef + from aws_advanced_python_wrapper.plugin_service import PluginService + from aws_advanced_python_wrapper.utils.properties import Properties + +logger = Logger(__name__) + +_EXECUTE = DbApiMethod.CURSOR_EXECUTE.method_name +_EXECUTEMANY = DbApiMethod.CURSOR_EXECUTEMANY.method_name +_FETCHONE = DbApiMethod.CURSOR_FETCHONE.method_name +_ITER = DbApiMethod.CURSOR_ITER.method_name +_NEXT = DbApiMethod.CURSOR_NEXT.method_name +_NEXTSET = DbApiMethod.CURSOR_NEXTSET.method_name +_COPY = DbApiMethod.CURSOR_COPY.method_name +_CALLPROC = DbApiMethod.CURSOR_CALLPROC.method_name +# Driver methods whose rows don't pass through the plugin's fetch, so it can't decrypt them. +_UNWRAPPED_RESULTS = frozenset(m.method_name for m in ( + DbApiMethod.CURSOR_STREAM, DbApiMethod.CURSOR_RESULTS, DbApiMethod.CURSOR_SET_RESULT, DbApiMethod.CURSOR_FETCHSETS, + DbApiMethod.CURSOR_STORED_RESULTS)) +_EXECUTES = frozenset({_EXECUTE, _EXECUTEMANY}) +_ONE_ROW = frozenset({_FETCHONE, _NEXT}) +# Bounds the warnings recorded on one connection: statement shapes can come from user SQL. +_MAX_WARNING_KEYS = 256 +_SQL_NAMES = ("query", "operation") +_COPY_SQL_NAMES = ("statement",) +_PARAM_NAMES = ("params", "params_seq", "seq_params") +# With the data-key cache off, one call's data keys by encrypted data key and master key, zeroed when the call ends. +_CallKeys = Dict[Tuple[Optional[str], Optional[str]], bytearray] + + +class _Pending(Enum): + """The type of ``_NOT_READY``: a one-member enum, so mypy narrows on ``is _NOT_READY``.""" + + NOT_READY = 0 + + +# _decoder's answer while the driver has no description for the result, as in psycopg's pipeline mode until a fetch +# receives the result. Nothing is cached then, so the decoder is built from the description that arrives. +_NOT_READY = _Pending.NOT_READY + + +class _Result: + """The analysis of a cursor's last statement, the encrypted columns its tables had when it ran, and the row decoder + built from those. ``many`` is set for an ``executemany``: ``nextset()`` keeps its result, and the decoder is built + again from each set's description.""" + + def __init__(self, analysis: StatementAnalysis, configs: Dict[str, Sequence[ColumnEncryptionConfig]], many: bool): + self.analysis = analysis + # By the metadata key of each table, as the snapshot keys them: a fetch looks nothing up. + self.configs = configs + self.many = many + # _Result itself: not built yet; None: no encrypted column to decode. + self.decode: Any = _Result + # A result set after the first of a multi-statement string. + self.later = False + + def __repr__(self) -> str: + return f"_Result({list(self.configs)})" + + +class KmsEncryptionPlugin(Plugin, CanReleaseResources): + """Encrypts and decrypts the configured columns of one connection. Its metadata, data-key cache and KMS client + are built at the first statement the plugin analyzes; ``release_resources``, which each close of the connection + calls, closes the metadata manager, the cache and the KMS client.""" + + _SUBSCRIBED_METHODS: Set[str] = {_EXECUTE, _EXECUTEMANY, _FETCHONE, DbApiMethod.CURSOR_FETCHMANY.method_name, + DbApiMethod.CURSOR_FETCHALL.method_name, _ITER, _NEXT, _NEXTSET, _COPY, + _CALLPROC, *_UNWRAPPED_RESULTS} + + def __init__(self, plugin_service: PluginService, props: Properties): + self._plugin_service = plugin_service + self._props = props + self._config = EncryptionConfig.from_props(props) + driver_dialect = plugin_service.driver_dialect + # Before any connection opens: the plugins are built after the driver dialect is chosen. + if not isinstance(driver_dialect, EncryptionDriverDialect): + raise EncryptionConfigError( + Messages.get_formatted("KmsEncryptionPlugin.UnsupportedDriver", driver_dialect.driver_name)) + # Under the internal pool, the service's dialect turns generic after connect. + self._driver_dialect: DriverDialect = driver_dialect + self._encryption_dialect: EncryptionDriverDialect = driver_dialect + # Imported here so the wrapper imports without the encryption extra; a missing extra fails at connect. + from aws_advanced_python_wrapper.encryption import (encryption_service, + sql_analyzer) + self._crypto = encryption_service.EncryptionService + self._analyze = sql_analyzer.analyze + self._gaps = sql_analyzer.AnalysisGap + self._lock = threading.Lock() + # Built here, not with the metadata: _execute scopes a statement's lookups before the first build runs. + self._source = PluginConnectionSource(plugin_service) + self._metadata: Optional[MetadataManager] = None + self._cache: Optional[DataKeyCache] = None + self._keys: Optional[KeyManager] = None + self._kms_client: Any = None + # Set by release_resources(); a closed plugin builds nothing and looks nothing up. + self._closed = False + # Threads may use different cursors of one connection, so the three below share a lock of their own: _lock + # is held across the first statement's metadata load. + self._state_lock = threading.Lock() + # By driver cursor: none outlives its cursor. + self._results: WeakKeyDictionary[Any, _Result] = WeakKeyDictionary() + # Key_storage rows of rotated-out keys, by id. + self._old_keys: Dict[int, KeyMetadata] = {} + self._warned: Set[Any] = set() + if self._config.audit_logging_enabled: + logger.warning("KmsEncryptionPlugin.AuditNotWritten") + + @property + def subscribed_methods(self) -> Set[str]: + return self._SUBSCRIBED_METHODS + + # Any, not the base's type: target is the driver's cursor, whose attributes the plugin reads. + def execute(self, target: Any, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + if method_name in _UNWRAPPED_RESULTS: + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.ResultMethodNotSupported", method_name)) + if method_name == _NEXTSET: + return self._next_set(target, execute_func) + if method_name == _CALLPROC: + self._refuse_callproc(target, args, kwargs) + return execute_func() + + if method_name in _EXECUTES: + return self._execute(target, method_name, execute_func, args, kwargs) + if method_name == _COPY: + scope = nullcontext() if self._config.metadata_cache_enabled else self._source.statement() + with scope: + self._refuse_copy(target, args, kwargs) + return execute_func() + # Before the driver call, so a refused row factory reads no row (see _decoder_after_fetch). + decode = self._decoder(target) + result = execute_func() + if method_name == _ITER: + with self._state_lock: + started = self._results.get(target) + return self._loop(target, result, decode, started) + if decode is None or result is None: + return result + # The description arrives with the rows: at this fetch, or at a loop's first row. + if decode is _NOT_READY: + if method_name not in _ONE_ROW and not result: + return result + # Once: this fetch has received the result, and with it the description. + decode = self._decoder_after_fetch(target) + if decode is None: + return result + data_keys = self._call_keys() + try: + return decode(result, data_keys) if method_name in _ONE_ROW else [decode(row, data_keys) for row in result] + finally: + self._wipe(data_keys) + + def release_resources(self) -> None: + # First, and without _lock, so a close never waits on a metadata load; a build re-checks it. + self._closed = True + with self._state_lock: + # Rotated-out key rows: their HMAC keys are bytes, which can't be wiped, only dropped. + self._old_keys.clear() + # The KMS client's close() frees its pooled connections to KMS, which otherwise stay open until a garbage collection. + for resource in (self._metadata, self._cache, self._kms_client): + if resource is not None: + try: + resource.close() + except Exception as e: # noqa: BLE001 - one failed release step must not stop the others or raise from close() + logger.warning("KmsEncryptionPlugin.ReleaseFailed", type(resource).__name__, type(e).__name__) + + def _execute(self, target: Any, method_name: str, execute_func: Callable, args: Tuple[Any, ...], + kwargs: Dict[str, Any]) -> Any: + # The metadata snapshot answers the lookups; without it, the statement's lookups share one connection, closed + # before the driver call. + scope = nullcontext() if self._config.metadata_cache_enabled else self._source.statement() + with scope: + new_args, new_kwargs = self._encrypted_call(target, method_name, args, kwargs) + if new_args is not args or new_kwargs is not kwargs: + context = self._plugin_service.current_call_context + if context is None or not context.holds(args, kwargs): + # Nothing would hand the copies to the driver, or this would change another statement's arguments. + raise EncryptionFailedError(Messages.get("KmsEncryptionPlugin.ArgumentsChanged")) + # Undone by the plugin manager when this returns. + context.args, context.kwargs = new_args, new_kwargs + return execute_func() + + def _encrypted_call(self, target: Any, method_name: str, args: Tuple[Any, ...], + kwargs: Dict[str, Any]) -> Tuple[Tuple[Any, ...], Dict[str, Any]]: + self._remember(target, None) + sql_at = 0 if args else _keyword(kwargs, _SQL_NAMES) + params_at = 1 if len(args) > 1 else _keyword(kwargs, _PARAM_NAMES) + sql = _argument(args, kwargs, sql_at) + params = _argument(args, kwargs, params_at) + many = method_name == _EXECUTEMANY + if many and params is not None: + if not isinstance(params, (list, tuple)): + params = list(params) + args, kwargs = _replace(args, kwargs, params_at, params) + # An empty batch has no value to encrypt, and the driver sends nothing. + if not params: + return args, kwargs + text, codec = self._encryption_dialect.analyzable_sql(sql, target) + # Other SQL objects, and bytes the driver dialect rejects, can't be analyzed, so the plugin can't tell which + # values they write or compare. + if text is None: + if self._config.fail_on_unmapped_parameter and self._components().has_encrypted_columns(): + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.NotAnalysedRefused", type(sql).__name__)) + if self._new_warning(type(sql)): + logger.warning("KmsEncryptionPlugin.NotAnalysed", type(sql).__name__) + return args, kwargs + metadata = self._components() + analysis = self._analyze(text, type(self._encryption_dialect), params[0] if many and params else params) + tables: List[str] = [] + configs: Dict[str, Sequence[ColumnEncryptionConfig]] = {} + for table in analysis.tables: + found = metadata.table_configs(table.name) + if found: + tables.append(table.name) + configs[self._encryption_dialect.metadata_key(table.name)] = found + self._refuse_shadowing_cte(analysis, metadata) + if tables and analysis.gap is self._gaps.HIDDEN_PLACEHOLDER: + # The driver binds a hidden placeholder too, so the analysis can't tell which value lands in an encrypted column. + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.HiddenPlaceholder", ", ".join(tables))) + if tables and analysis.gap is self._gaps.EXECUTABLE_COMMENT: + # MySQL runs the comment's body, which can name another table or move a value to another column. + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.ExecutableComment", ", ".join(tables))) + targets: Dict[Any, ColumnEncryptionConfig] = {} + if tables: + only = analysis.tables[0].name if len(analysis.tables) == 1 else None + # First, so a refused statement leaves no result. + self._refuse_unsafe_comparisons(analysis, metadata, tables, only) + if (params and analysis.gap is not None and analysis.gap is not self._gaps.DRIVER_ERROR + and self._config.fail_on_unmapped_parameter): + # The values would reach the server as given, a compared value included. + raise MetadataError(Messages.get_formatted( + "KmsEncryptionPlugin.UnmappedParameters", ", ".join(tables), analysis.gap.value)) + self._remember(target, _Result(analysis, configs, many)) + for column in analysis.unbound_writes: + config = metadata.column_config(column.table or only, column.column) + if config is not None: + raise MetadataError( + Messages.get_formatted("KmsEncryptionPlugin.UnboundWrite", config.column_identifier), + table_name=config.table_name, column_name=config.column_name) + if analysis.gap is not None and analysis.writes: + # Passed through; the trigger must reject plaintext. + self._warn_once(analysis, tables) + else: + targets = self._targets(analysis, metadata, tables, only) + if targets and params: + data_keys = self._call_keys() + try: + params = ([self._encrypt(p, targets, data_keys) for p in params] if many + else self._encrypt(params, targets, data_keys)) + finally: + self._wipe(data_keys) + args, kwargs = _replace(args, kwargs, params_at, params) + prefix = self._encryption_dialect.binary_placeholder_prefix(target) + if prefix is not None: + # Every parameter set shares one SQL text, so a key that is None in any set gets no prefix. + keys = {k for k in targets if all(_bound(p, k) is not None for p in (params if many else [params]))} + prefixed = _binary_prefix(text, analysis, keys, prefix) + if prefixed != text: + args, kwargs = _replace(args, kwargs, sql_at, prefixed if codec is None else prefixed.encode(codec)) + return args, kwargs + + def _refuse_copy(self, target: Any, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> None: + """Raise for a ``COPY ... FROM`` that names an encrypted column, and for a ``COPY`` that the plugin can't parse + and that can write a table with encrypted columns: its rows reach the server as the application writes them, and + no annotation can change that. A ``COPY ... FROM`` without a column list on such a table runs with a warning, and + the database trigger must reject plaintext. Also raise for a CTE that has the name of such a table, and for a + ``COPY`` with parameters on such a table while ``encryption_fail_on_unmapped_parameter`` is on, because the + plugin doesn't encrypt them. A ``COPY`` the plugin can't analyze raises while any column is encrypted.""" + self._remember(target, None) + sql = _argument(args, kwargs, 0 if args else _keyword(kwargs, _COPY_SQL_NAMES)) + text, _ = self._encryption_dialect.analyzable_sql(sql, target) + if text is None: + if self._components().has_encrypted_columns(): + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.CopyNotAnalysed", type(sql).__name__)) + if self._new_warning(type(sql)): + logger.warning("KmsEncryptionPlugin.NotAnalysed", type(sql).__name__) + return + metadata = self._components() + params = _argument(args, kwargs, 1 if len(args) > 1 else _keyword(kwargs, _PARAM_NAMES)) + analysis = self._analyze(text, type(self._encryption_dialect), params) + self._refuse_shadowing_cte(analysis, metadata) + tables = [table.name for table in analysis.tables if metadata.table_configs(table.name)] + only = analysis.tables[0].name if len(analysis.tables) == 1 else None + for column in analysis.unbound_writes: + config = metadata.column_config(column.table or only, column.column) + if config is not None: + raise MetadataError( + Messages.get_formatted("KmsEncryptionPlugin.CopyRefused", config.column_identifier), + table_name=config.table_name, column_name=config.column_name) + if tables and analysis.writes and analysis.gap is not None and analysis.gap is not self._gaps.NO_COLUMN_LIST: + raise MetadataError(Messages.get_formatted( + "KmsEncryptionPlugin.CopyUnread", ", ".join(tables), analysis.gap.value)) + if tables and params and self._config.fail_on_unmapped_parameter: + # The plugin never changes a COPY's arguments, so a compared value would reach the server unencrypted. + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.CopyParameters", ", ".join(tables))) + if tables and analysis.writes and analysis.gap is self._gaps.NO_COLUMN_LIST: + self._warn_once(analysis, tables) + + def _refuse_shadowing_cte(self, analysis: StatementAnalysis, metadata: MetadataManager) -> None: + # The analysis reads the name as the CTE, but the database can read or write the table of that name. + for name in analysis.cte_names: + if metadata.table_configs(name): + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.CteShadowsTable", name)) + + def _refuse_unsafe_comparisons(self, analysis: StatementAnalysis, metadata: MetadataManager, tables: List[str], + only: Optional[str]) -> None: + """Raise for a comparison of a value with an encrypted column where a comparison that never matches would still + select rows: an encrypted value equals no stored value. The column the value is bound to, annotations included, + and the column it is compared with are both checked, also in a write that would otherwise be passed through. + Among several tables, a compared column without a table isn't looked up by name when the value's annotation + names a table the statement uses, as ``_refuse_unmapped`` trusts it.""" + # Built only for a statement with an unsafe comparison. + columns: Optional[Dict[int, ColumnRef]] = None + trusted: Set[int] = set() + for use in analysis.comparisons: + if use.safe: + continue + if columns is None: + columns = analysis.parameter_columns() + trusted = {u.ordinal for u in analysis.annotations if self._names_a_table_used(analysis, u.column)} + for column in (columns[use.ordinal], use.column): + # Among several tables, by name, as _refuse_unmapped finds it. + if column.table is None and only is None: + if use.ordinal in trusted: + # The value's annotation names its column, as _refuse_unmapped trusts it. + continue + config = _encrypted_column_by_name(metadata, tables, column.column) + else: + config = metadata.column_config(column.table or only, column.column) + if config is not None: + raise MetadataError( + Messages.get_formatted("KmsEncryptionPlugin.UnsafeComparison", config.column_identifier), + table_name=config.table_name, column_name=config.column_name) + + def _targets(self, analysis: StatementAnalysis, metadata: MetadataManager, tables: List[str], + only: Optional[str]) -> Dict[Any, ColumnEncryptionConfig]: + """The encrypted column of each placeholder key. Raises for a value that may belong to an encrypted column + the analysis can't tie it to.""" + annotated = {use.ordinal for use in analysis.annotations} + # The columns the analysis infers before annotations override them, merged as the analysis merges them. + inferred = {use.ordinal: use.column for use in (*analysis.comparisons, *analysis.assignments)} + targets: Dict[Any, ColumnEncryptionConfig] = {} + # The ordinals bound for an encrypted column. + encrypted: Set[int] = set() + for ordinal, column in sorted(analysis.parameter_columns().items()): + config = metadata.column_config(column.table or only, column.column) + if config is not None: + # A %(name)s used for several encrypted columns is encrypted once, with the first one's key. + targets.setdefault(analysis.placeholders[ordinal].key, config) + encrypted.add(ordinal) + else: + self._refuse_unmapped(analysis, metadata, tables, only, column, ordinal in annotated, + inferred.get(ordinal)) + for placeholder in analysis.placeholders: + # One mapping entry can't hold both the payload and the plaintext a %(name)s's other use needs. + config = targets.get(placeholder.key) + if config is not None and placeholder.ordinal not in encrypted: + raise MetadataError( + Messages.get_formatted("KmsEncryptionPlugin.SharedParameter", placeholder.key, config.column_identifier), + table_name=config.table_name, column_name=config.column_name) + return targets + + def _refuse_unmapped(self, analysis: StatementAnalysis, metadata: MetadataManager, tables: List[str], + only: Optional[str], column: ColumnRef, annotated: bool, inferred: Optional[ColumnRef]) -> None: + """Raise for a value whose column has no encryption metadata but whose value may still be an encrypted + column's: the analysis infers an encrypted column for an annotated value, or the column has no table and + the statement reads an encrypted column of that name.""" + checked: Optional[ColumnRef] = column + if annotated: + found = None if inferred is None else metadata.column_config(inferred.table or only, inferred.column) + if found is not None: + raise MetadataError( + Messages.get_formatted("KmsEncryptionPlugin.AnnotationNotEncrypted", found.column_identifier), + table_name=found.table_name, column_name=found.column_name) + if self._names_a_table_used(analysis, column): + # Trusted: it names a table the statement uses. + return + # Any other annotation counts as none. + checked = inferred + if checked is None or checked.table is not None: + return + found = _encrypted_column_by_name(metadata, tables, checked.column) + if found is not None: + raise MetadataError( + Messages.get_formatted("KmsEncryptionPlugin.UnknownColumnTable", found.column_identifier), + table_name=found.table_name, column_name=found.column_name) + + def _names_a_table_used(self, analysis: StatementAnalysis, column: ColumnRef) -> bool: + """Whether an annotated value's column names a table the statement uses, read or written, which makes the + annotation trusted.""" + key = self._encryption_dialect.metadata_key + return column.table is not None and any(key(column.table) == key(t.name) for t in analysis.tables) + + def _encrypt(self, params: Any, targets: Dict[Any, ColumnEncryptionConfig], keys: Optional[_CallKeys]) -> Any: + mapping = isinstance(params, Mapping) + out = dict(params) if mapping else list(params) + for key, config in targets.items(): + if (key in out) if mapping else key < len(out): + out[key] = self._seal(out[key], config, key, keys) + if isinstance(params, tuple): + return tuple(out) + return out + + def _seal(self, value: Any, config: ColumnEncryptionConfig, parameter: Union[int, str], + keys: Optional[_CallKeys]) -> Any: + if value is None: + return None + # It would be stored as str(value) and read back as text. + if TypeMarker.from_object(value) == TypeMarker.GENERIC: + # A position counts from 1 in the message. + position = parameter + 1 if isinstance(parameter, int) else parameter + raise EncryptionFailedError( + Messages.get_formatted("KmsEncryptionPlugin.NoExactForm", position, type(value).__name__, + config.column_identifier), + data_type="GENERIC") + key = config.key_metadata + if key is None or key.hmac_key is None or config.key_id is None or not config.is_usable: + raise self._unusable(config) + data_key = self._data_key(key, keys) + # This call's copy, wiped below (best effort: the key row keeps its own bytes). + hmac_key = bytearray(key.hmac_key) + try: + return self._crypto.encrypt(value, data_key, hmac_key, config.algorithm, key_id=config.key_id) + finally: + if keys is None: + self._crypto.wipe(data_key) + self._crypto.wipe(hmac_key) + + def _call_keys(self) -> Optional[_CallKeys]: + """A new holder for one call's data keys when the data-key cache is off, so each key is decrypted once per + call; None when it is on.""" + return None if self._config.data_key_cache_enabled else {} + + def _data_key(self, key: KeyMetadata, keys: Optional[_CallKeys]) -> bytearray: + """The key row's data key, from ``keys`` when the call holds it. A key kept in ``keys`` is zeroed with them; any + other is the caller's to zero.""" + if self._keys is None: + raise MetadataError(Messages.get("KmsEncryptionPlugin.MetadataNotLoaded")) + if keys is None: + return self._keys.decrypt_data_key(key.encrypted_data_key, key.master_key_arn) + name = (key.encrypted_data_key, key.master_key_arn) + data_key = keys.get(name) + if data_key is None: + data_key = self._keys.decrypt_data_key(key.encrypted_data_key, key.master_key_arn) + keys[name] = data_key + return data_key + + def _wipe(self, keys: Optional[_CallKeys]) -> None: + if keys is not None: + for data_key in keys.values(): + self._crypto.wipe(data_key) + + def _warn_once(self, analysis: StatementAnalysis, tables: List[str]) -> None: + # Bounded: shapes can come from user SQL. + if self._new_warning((analysis.kind, analysis.gap, tuple(tables)), bounded=True): + # Without a detail, the gap's fixed text. + reason = analysis.detail or (analysis.gap.value if analysis.gap is not None else "") + logger.warning("KmsEncryptionPlugin.PassedThrough", ", ".join(tables), reason) + + def _new_warning(self, key: Any, bounded: bool = False) -> bool: + """Whether a warning for ``key`` is still to be logged on this connection; records it. With ``bounded``, only + while fewer than ``_MAX_WARNING_KEYS`` keys are recorded.""" + with self._state_lock: + if key in self._warned or (bounded and len(self._warned) >= _MAX_WARNING_KEYS): + return False + self._warned.add(key) + return True + + def _refuse_callproc(self, target: Any, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> None: + """Raise for a ``callproc()`` with arguments while ``encryption_fail_on_unmapped_parameter`` is on and a column is + encrypted: the plugin can't tell where the routine writes them, and mysql-connector sends them as SQL text.""" + self._remember(target, None) + # mysql-connector's callproc(procname, args=()); psycopg's cursor has no callproc. + params = _argument(args, kwargs, 1 if len(args) > 1 else _keyword(kwargs, ("args",))) + if not params or not self._config.fail_on_unmapped_parameter: + return + scope = nullcontext() if self._config.metadata_cache_enabled else self._source.statement() + with scope: + if self._components().has_encrypted_columns(): + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.CallprocRefused", _CALLPROC)) + + def _remember(self, target: Any, state: Optional[_Result]) -> None: + """Set or clear the state of the driver cursor's last statement.""" + with self._state_lock: + if state is None: + self._results.pop(target, None) + else: + self._results[target] = state + + def _next_set(self, target: Any, execute_func: Callable) -> Any: + """Call the driver's ``nextset()``, and once the driver has moved to another result set, build the decoder + again from the new set's description at the next fetch. After the first set of a multi-statement string, the + plugin can't tell which statement produced a set, so a fetch raises when a column's name is that of an + encrypted column of the string's tables. For an ``executemany``, every set comes from the one statement: on + mysql-connector, the sets of a multi-statement string differ. Returns the driver's result as it is.""" + # First: a nextset() that raises, or returns None at the last set, hasn't moved. + result = execute_func() + if result: + with self._state_lock: + state = self._results.get(target) + if state is not None: + # Not built: the next fetch builds it from this set's description. + state.decode = _Result + state.later = not state.many + return result + + def _decoder(self, target: Any) -> Union[Callable[..., Any], None, _Pending]: + """The row decoder of the cursor's last statement, None when it has no encrypted column to decode, or + ``_NOT_READY`` while the driver has no description for its result.""" + with self._state_lock: + state = self._results.get(target) + if state is None or state.decode is None: + return None + # Before the driver reads a row; a decoder built before the close would read key rows and call KMS. + if self._closed: + raise MetadataError(Messages.get("KmsEncryptionPlugin.Closed")) + if state.decode is not _Result: + return state.decode + description = target.description + if description is None: + return _NOT_READY + key = self._encryption_dialect.metadata_key + names = [d[0] for d in description] + # So a name repeated in another letter case counts as a repeat. + lowered = [str(n).lower() for n in names] + known = state.analysis.result_columns + only = state.analysis.tables[0].name if len(state.analysis.tables) == 1 else None + # A column whose table has none isn't encrypted. + configs = state.configs + positions: Dict[int, ColumnEncryptionConfig] = {} + for i, _ in enumerate(names): + ref = known[i] if known is not None and i < len(known) and not state.later else None + if ref is not None: + config = _column_config(configs, ref.table or only, ref.column, key) + else: + config = self._config_by_name(state, names[i], lowered, i) + if config is not None: + positions[i] = config + # Checked before any row is built, except through _decoder_after_fetch. + if positions: + factory = self._encryption_dialect.unsupported_row_factory(target) + if factory is not None: + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.RowFactory", factory)) + # A dict row keeps only the last column of each name, so it is decoded with that column's configuration. + last = {name: i for i, name in enumerate(names)} + by_name = {name: positions[i] for name, i in last.items() if i in positions} + state.decode = (lambda row, keys=None: self._decode_row(row, positions, by_name, keys)) if positions else None + return state.decode + + def _config_by_name(self, state: _Result, name: Any, lowered: List[str], i: int) -> Optional[ColumnEncryptionConfig]: + """The configuration of result column ``i``, which the analysis couldn't place by position, by its name in + any letter case. A name the analysis traced to one table column decides by that column. When that column is + plain, the name is in :attr:`StatementAnalysis.shared_names` and an encrypted column has that name, it raises, + because a USING or NATURAL join can merge the encrypted column into the result. Otherwise a unique encrypted + column of that name, named once in the result, decrypts. A name that can hold an encrypted column that the + plugin can't tell apart from another raises.""" + configs, key = state.configs, self._encryption_dialect.metadata_key + found = [c for table_configs in configs.values() for c in table_configs if c.column_name.lower() == lowered[i]] + # A later result set may come from any statement of the string. + traced = [] if state.later else [ref for out, ref in state.analysis.named_columns if out.lower() == lowered[i]] + sources = {ref for ref in traced if ref is not None} + encrypted = [c for c in (_column_config(configs, ref.table, ref.column, key) for ref in sources) if c is not None] + if (found or encrypted) and lowered.count(lowered[i]) > 1: + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", name)) + if len(sources) == 1 and None not in traced: + if encrypted: + return encrypted[0] + # A USING or NATURAL join can merge in another source's column of that name. + if found and any(out.lower() == lowered[i] for out in state.analysis.shared_names): + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", name)) + return None + if encrypted or (found and (state.later or len(found) > 1)): + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", name)) + return found[0] if found else None + + def _decoder_after_fetch(self, target: Any) -> Optional[Callable[..., Any]]: + """The row decoder of a result whose rows have arrived but which had no description when the read began: + psycopg's pipeline mode fills it in when a fetch, or a loop's first row, receives the result. So an unsupported + row factory is refused only after the driver has built rows with it, from the stored payloads.""" + # Built at the first rows, then cached on the result. + decode = self._decoder(target) + # Rows of a result with encrypted columns, and still no description to place them. + if decode is _NOT_READY: + raise MetadataError(Messages.get("KmsEncryptionPlugin.NoResultDescription")) + return decode + + def _loop(self, target: Any, rows: Iterator[Any], decode: Union[Callable[..., Any], None, _Pending], + started: Optional[_Result]) -> Iterator[Any]: + """The rows of a loop over the driver cursor's result, decoded. The driver's iterator reads whatever result the + cursor holds, so once the cursor has run another statement, the next row raises instead of returning a row + of that statement undecoded.""" + for row in rows: + if self._results.get(target) is not started: + raise MetadataError(Messages.get("KmsEncryptionPlugin.LoopOutlivedStatement")) + if decode is None: + yield row + elif decode is _NOT_READY: + # The loop began before the result had a description. + yield self._decode_late(target, row) + else: + yield decode(row) + + def _decode_late(self, target: Any, row: Any) -> Any: + """Decode a row of a loop that began before its result had a description (see _decoder_after_fetch).""" + decode = self._decoder_after_fetch(target) + return row if decode is None else decode(row) + + def _decode_row(self, row: Any, positions: Dict[int, ColumnEncryptionConfig], + by_name: Dict[Any, ColumnEncryptionConfig], keys: Optional[_CallKeys]) -> Any: + if isinstance(row, dict): + out = dict(row) + for name, config in by_name.items(): + out[name] = self._open(out[name], config, keys) + return out + values = list(row) + for i, config in positions.items(): + values[i] = self._open(values[i], config, keys) + if hasattr(row, "_make"): + return type(row)._make(values) + return tuple(values) if isinstance(row, tuple) else values + + def _open(self, value: Any, config: ColumnEncryptionConfig, keys: Optional[_CallKeys]) -> Any: + if value is None: + return None + # Text from a text column, say: not a payload. + if not isinstance(value, (bytes, bytearray, memoryview)): + return self._unverified(value, config, "KmsEncryptionPlugin.NotAPayload") + # A loop that began before the close decodes lazily and never reaches _decoder again. + if self._closed: + raise MetadataError(Messages.get("KmsEncryptionPlugin.Closed")) + if self._keys is None: + raise MetadataError(Messages.get("KmsEncryptionPlugin.MetadataNotLoaded")) + key_id = self._crypto.key_id_from_payload(value) + # The column's own key row. + if key_id is None or key_id == config.key_id: + key = config.key_metadata + if key is None or key.hmac_key is None or not config.is_usable: + raise self._unusable(config) + else: + # A value written before the column's key was rotated, or a value that isn't a payload. + # Before the lookup: no earlier key row makes it usable. repr quotes the name and keeps a trailing space or + # a control character visible. + if not EncryptionAlgorithm.is_supported(config.algorithm): + raise InvalidAlgorithmError( + Messages.get_formatted("KmsEncryptionPlugin.UnsupportedAlgorithm", config.column_identifier, + repr(config.algorithm), ", ".join(EncryptionAlgorithm.ALL)), + algorithm=config.algorithm) + with self._state_lock: + kept = self._old_keys.get(key_id) + key = kept or self._keys.key_metadata_by_id(key_id) + if key is None or not key.is_usable or key.hmac_key is None: + # Never retried with the column's current key. The message leaves out the id: for a stored value + # that isn't a payload, it is four bytes of that value. + return self._unverified(value, config, "KmsEncryptionPlugin.UnknownKey") + with self._state_lock: + # Closed during the lookup: the close cleared _old_keys under this lock, so don't refill it. + if self._closed: + raise MetadataError(Messages.get("KmsEncryptionPlugin.Closed")) + self._old_keys[key_id] = key + data_key = self._data_key(key, keys) + hmac_key = bytearray(key.hmac_key) + try: + return self._crypto.decrypt(value, data_key, hmac_key, config.algorithm) + except IntegrityCheckError: + if not self._config.return_unverified_data: + raise + finally: + if keys is None: + self._crypto.wipe(data_key) + self._crypto.wipe(hmac_key) + return value + + def _unverified(self, value: Any, config: ColumnEncryptionConfig, message_key: str) -> Any: + if self._config.return_unverified_data: + # Lenient mode: the driver's value, nothing logged. + return value + raise IntegrityCheckError(Messages.get_formatted(message_key, config.column_identifier), + algorithm=config.algorithm) + + @staticmethod + def _unusable(config: ColumnEncryptionConfig) -> Union[InvalidAlgorithmError, InvalidKeyMetadataError]: + """The error for a column that can't be written or read: its algorithm when that is unsupported, else its key row.""" + if not EncryptionAlgorithm.is_supported(config.algorithm): + # repr quotes the name and keeps a trailing space or a control character visible. + return InvalidAlgorithmError( + Messages.get_formatted("KmsEncryptionPlugin.UnsupportedAlgorithm", config.column_identifier, + repr(config.algorithm), ", ".join(EncryptionAlgorithm.ALL)), + algorithm=config.algorithm) + return InvalidKeyMetadataError(Messages.get_formatted("KmsEncryptionPlugin.UnusableColumn", config.column_identifier)) + + def _components(self) -> MetadataManager: + if self._closed: + raise MetadataError(Messages.get("KmsEncryptionPlugin.Closed")) + if self._metadata is None: + with self._lock: + # Closed while this thread waited for another thread's build. + if self._closed: + raise MetadataError(Messages.get("KmsEncryptionPlugin.Closed")) + if self._metadata is None: + config = self._config + session = AwsCredentialsManager.get_session(self._plugin_service.current_host_info, self._props, + config.kms_region) + client = KeyManager.create_kms_client(session, config) + metadata = MetadataManager(self._source, self._driver_dialect, self._encryption_dialect, config) + metadata.start() + # The cache's constructor starts its cleanup thread, so it comes after every step that can + # fail; if that thread can't start, stop the refresh thread start() began. + try: + cache = DataKeyCache(config.data_key_cache_max_size, config.data_key_cache_expiration_sec, + enabled=config.data_key_cache_enabled) + except BaseException: # noqa: BLE001 - release the started manager, then re-raise the error as is + metadata.close() + raise + self._cache, self._kms_client = cache, client + self._keys = KeyManager(client, self._source, self._driver_dialect, self._encryption_dialect, config, cache) + # Last: the check outside the lock reads it. + self._metadata = metadata + # Closed during this build: release what it started, which that close couldn't see. + if self._closed: + self.release_resources() + raise MetadataError(Messages.get("KmsEncryptionPlugin.Closed")) + return self._metadata + + +def _column_config(configs: Dict[str, Sequence[ColumnEncryptionConfig]], table: Optional[str], column: str, + key: Callable[[str], str]) -> Optional[ColumnEncryptionConfig]: + """The configuration of ``table.column`` among ``configs``, or None when it isn't encrypted.""" + if table is None: + return None + for config in configs.get(key(table), ()): + if key(config.column_name) == key(column): + return config + return None + + +def _keyword(kwargs: Dict[str, Any], names: Tuple[str, ...]) -> Optional[str]: + """The first of ``names`` that ``kwargs`` holds, or None.""" + for name in names: + if name in kwargs: + return name + return None + + +def _argument(args: Tuple[Any, ...], kwargs: Dict[str, Any], at: Union[int, str, None]) -> Any: + """The argument at position or keyword ``at``, or None when ``at`` is None.""" + if at is None: + return None + if isinstance(at, int): + return args[at] + return kwargs[at] + + +def _replace(args: Tuple[Any, ...], kwargs: Dict[str, Any], at: Any, value: Any) -> Tuple[Tuple[Any, ...], Dict[str, Any]]: + if isinstance(at, int): + return (*args[:at], value, *args[at + 1:]), kwargs + return args, {**kwargs, at: value} + + +def _bound(params: Any, key: Any) -> Any: + """The value one parameter set binds to ``key``, or None if it binds none.""" + if isinstance(params, Mapping): + return params.get(key) + return params[key] if isinstance(key, int) and key < len(params) else None + + +def _encrypted_column_by_name(metadata: MetadataManager, tables: List[str], name: str) -> Optional[ColumnEncryptionConfig]: + """The first encrypted column called ``name`` in any of ``tables``, for a column named without its table.""" + for table in tables: + config = metadata.column_config(table, name) + if config is not None: + return config + return None + + +def _binary_prefix(sql: str, analysis: StatementAnalysis, encrypted_keys: Set[Any], prefix: str) -> str: + """Insert ``prefix`` before every placeholder bound for an encrypted column, so the server reads the payload as + binary data. No prefix is added where a charset introducer, such as ``_binary``, is already directly before the + placeholder, or for a key whose value is ``None`` (in any parameter set, for ``executemany``).""" + starts = sorted({p.start for p in analysis.placeholders + if p.key in encrypted_keys and p.introducer is None and not p.hidden}) + # Joined once: splicing at each placeholder copies the whole SQL each time, quadratic in a bulk INSERT. + parts: List[str] = [] + previous = 0 + for start in starts: + parts += (sql[previous:start], prefix) + previous = start + parts.append(sql[previous:]) + return "".join(parts) + + +class KmsEncryptionPluginFactory(PluginFactory): + @staticmethod + def get_instance(plugin_service: PluginService, props: Properties) -> Plugin: + return KmsEncryptionPlugin(plugin_service, props) diff --git a/aws_advanced_python_wrapper/encryption/metadata_manager.py b/aws_advanced_python_wrapper/encryption/metadata_manager.py new file mode 100644 index 000000000..a8b1db55a --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -0,0 +1,338 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import time +import weakref +from threading import Event, Lock, Thread, current_thread +from types import MappingProxyType +from typing import (TYPE_CHECKING, Any, Dict, List, Mapping, NamedTuple, + Optional, Sequence, Tuple) + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.connection_source import ( + describe_failure, fetch_rows) +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata) +from aws_advanced_python_wrapper.errors import MetadataError +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.connection_source import \ + ConnectionSource + from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect + +logger = Logger(__name__) + +_KS_PREFIX = "ks_" + + +class _Snapshot(NamedTuple): + # Keyed by EncryptionDriverDialect.metadata_key of the names. + columns: Mapping[Tuple[str, str], ColumnEncryptionConfig] + by_table: Mapping[str, Tuple[ColumnEncryptionConfig, ...]] + loaded_at: float # time.monotonic() + + +class MetadataManager: + """Reads ``encryption_metadata`` (joined to ``key_storage``) and caches + which columns are encrypted. + + The cache is one immutable snapshot of the whole table, replaced + atomically on each refresh, so a lookup never sees a half-loaded state. It + is loaded by :meth:`start`, refreshed on a background thread every + ``encryption_metadata_cache_refresh_interval_sec``, and answers lookups + only while younger than ``encryption_metadata_cache_expiration_sec``. + The first lookup after expiry reloads it, whether or not the background + refresh is on. Before :meth:`start`, after :meth:`close`, or with the cache + disabled, each lookup queries the database. + + Lookups compare names the way the engine does + (:meth:`EncryptionDriverDialect.metadata_key`): exactly on PostgreSQL, where names are + stored as the catalog has them (``users`` for an unquoted ``Users``), and + case-insensitively on MySQL. That matches what the uncached query's + ``WHERE`` does, given the default (case-insensitive) MySQL collations. + + Call :meth:`close` when done. The refresh thread holds the manager only + weakly, so a manager dropped without ``close`` still stops its thread once + it is garbage-collected. + + The wrapper's shared storage service is not used: its entries are not + checked for expiry on read, and it caches per key rather than one + consistent snapshot. + """ + + SHUTDOWN_TIMEOUT_SEC = 5.0 + + def __init__(self, connection_source: ConnectionSource, driver_dialect: DriverDialect, + encryption_dialect: EncryptionDriverDialect, config: EncryptionConfig): + self._connections = connection_source + self._driver_dialect = driver_dialect + self._encryption_dialect = encryption_dialect + self._config = config + self._snapshot: Optional[_Snapshot] = None + self._started = False + # Guards _started, _snapshot publication and the thread handle against + # close(). Never held across a database call. + self._lifecycle_lock = Lock() + # Serializes refreshes, so an older load cannot overwrite a newer one. + self._refresh_lock = Lock() + self._stop = Event() + self._refresh_thread: Optional[Thread] = None + # Holds the refresh thread for the finalizer, which must not refer to + # self, or the manager would never be collected. + self._thread_holder: List[Optional[Thread]] = [None] + weakref.finalize(self, MetadataManager._finalize, self._stop, self._thread_holder) + + def start(self) -> None: + """Load the cache and start the background refresh, as configured. + + :raises MetadataError: if the initial load fails. + """ + with self._lifecycle_lock: + if self._stop.is_set(): + return + self._started = True + if self._config.metadata_cache_enabled: + self.refresh() + if not self._config.background_refresh_enabled: + return + with self._lifecycle_lock: + if self._refresh_thread is None and not self._stop.is_set(): + self._refresh_thread = Thread( + target=MetadataManager._refresh_loop, + args=(weakref.ref(self), self._stop, self._config.metadata_cache_refresh_interval_sec), + name="kms-encryption-metadata-refresh", daemon=True) + self._thread_holder[0] = self._refresh_thread + self._refresh_thread.start() + + def close(self) -> None: + """Stop the background refresh and drop the cache. A refresh still + running is discarded when it finishes. Idempotent. + + Call it from ordinary code, not from a finalizer or ``__del__``: a + garbage collection on the refresh thread can run inside its wait, where + stopping the thread would deadlock. + """ + with self._lifecycle_lock: + self._stop.set() + thread, self._refresh_thread = self._refresh_thread, None + self._snapshot = None + # Joining the current thread raises; close() can run on the refresh + # thread if a caller releases the manager from inside a refresh. + if thread is not None and thread is not current_thread(): + thread.join(self.SHUTDOWN_TIMEOUT_SEC) + + def refresh(self) -> int: + """Reload every column configuration and replace the cache. After + :meth:`close` the result is not cached. + + :return: the number of encrypted columns. + :raises MetadataError: if the load fails; the previous snapshot is kept. + """ + with self._refresh_lock: + return self._load_snapshot() + + def load_metadata(self) -> Dict[Tuple[str, str], ColumnEncryptionConfig]: + """Read every column configuration from the database, bypassing the + cache. Keyed by ``(table_name, column_name)``.""" + return self._load_all() + + def is_column_encrypted(self, table_name: Optional[str], column_name: Optional[str]) -> bool: + if table_name is None or column_name is None: + return False + return self.column_config(table_name, column_name) is not None + + def column_config(self, table_name: Optional[str], column_name: Optional[str]) -> Optional[ColumnEncryptionConfig]: + """The column's configuration, or ``None`` when it is not encrypted. + + A configured column whose ``key_storage`` row is missing is still + returned, with ``key_metadata=None``, so the caller fails closed. + """ + if table_name is None or column_name is None: + return None + snapshot = self._usable_snapshot(table_name, column_name) + key = self._encryption_dialect.metadata_key + if snapshot is not None: + return snapshot.columns.get((key(table_name), key(column_name))) + equals = self._encryption_dialect.equals_operator + rows = self._query( + f"{self._joined_sql()} WHERE em.table_name {equals} %s AND em.column_name {equals} %s", + (table_name, column_name), table_name=table_name, column_name=column_name) + return self._to_column_config(rows[0]) if rows else None + + def table_configs(self, table_name: Optional[str]) -> Sequence[ColumnEncryptionConfig]: + """Every encrypted column of one table; empty when there are none.""" + if table_name is None: + return () + snapshot = self._usable_snapshot(table_name) + if snapshot is not None: + return snapshot.by_table.get(self._encryption_dialect.metadata_key(table_name), ()) + rows = self._query(f"{self._joined_sql()} WHERE em.table_name {self._encryption_dialect.equals_operator} %s", + (table_name,), table_name=table_name) + return tuple(self._to_column_config(row) for row in rows) + + def has_encrypted_columns(self) -> bool: + """``True`` when any column is encrypted. The cached snapshot answers + while it is usable; otherwise the metadata tables are read.""" + snapshot = self._usable_snapshot() + if snapshot is not None: + return bool(snapshot.columns) + return bool(self._load_all()) + + @property + def cache_size(self) -> int: + snapshot = self._snapshot + return 0 if snapshot is None else len(snapshot.columns) + + @property + def is_cache_loaded(self) -> bool: + return self._snapshot is not None + + def _usable_snapshot(self, table_name: Optional[str] = None, + column_name: Optional[str] = None) -> Optional[_Snapshot]: + if not self._config.metadata_cache_enabled: + return None + snapshot = self._fresh(self._snapshot) + if snapshot is None and self._started and not self._stop.is_set(): + # An expired snapshot is reloaded here, whether or not the + # background refresh is on, so a statement reads the tables once + # instead of at every lookup. Lookups that find it expired at the + # same time wait for one reload; if that reload fails, each of them + # then tries its own, one at a time. + with self._refresh_lock: + if not self._stop.is_set() and self._fresh(self._snapshot) is None: + self._load_snapshot(table_name=table_name, column_name=column_name) + snapshot = self._fresh(self._snapshot) + return snapshot + + def _load_snapshot(self, *, table_name: Optional[str] = None, column_name: Optional[str] = None) -> int: + # Callers hold _refresh_lock. Stamped before the query, so expiry + # counts from when the data was read rather than when the query + # returned. + loaded_at = time.monotonic() + columns = self._load_all(table_name=table_name, column_name=column_name) + key = self._encryption_dialect.metadata_key + by_table: Dict[str, List[ColumnEncryptionConfig]] = {} + for config in columns.values(): + by_table.setdefault(key(config.table_name), []).append(config) + snapshot = _Snapshot( + MappingProxyType({(key(c.table_name), key(c.column_name)): c for c in columns.values()}), + MappingProxyType({t: tuple(c) for t, c in by_table.items()}), + loaded_at) + with self._lifecycle_lock: + if not self._stop.is_set(): + self._snapshot = snapshot + logger.debug("MetadataManager.Refreshed", len(columns)) + return len(columns) + + def _load_all(self, *, table_name: Optional[str] = None, + column_name: Optional[str] = None) -> Dict[Tuple[str, str], ColumnEncryptionConfig]: + # table_name / column_name only label a failure: the lookup that + # triggered a reload. + rows = self._query(f"{self._joined_sql()} ORDER BY em.table_name, em.column_name", (), + table_name=table_name, column_name=column_name) + configs = (self._to_column_config(row) for row in rows) + return {(c.table_name, c.column_name): c for c in configs} + + def _fresh(self, snapshot: Optional[_Snapshot]) -> Optional[_Snapshot]: + if snapshot is None or time.monotonic() - snapshot.loaded_at >= self._config.metadata_cache_expiration_sec: + return None + return snapshot + + def _query(self, sql: str, params: Sequence[Any], *, table_name: Optional[str] = None, + column_name: Optional[str] = None) -> List[Dict[str, Any]]: + try: + with self._connections.connection() as conn: + return fetch_rows(self._driver_dialect, conn, sql, params) + except Exception as e: + # A driver error can quote the row's bytes. Keep only its type and + # codes, and raise outside this block so it isn't chained. + failure = describe_failure(e) + raise MetadataError(Messages.get_formatted("MetadataManager.LoadFailed", failure), + table_name=table_name, column_name=column_name) + + def _joined_sql(self) -> str: + # A LEFT join, so a column whose key_storage row is missing still reads + # as encrypted (with no key) and a write to it fails instead of storing + # plaintext. An inner join would make it look like an ordinary column. + # em.key_id is the integer FK to ks.id; ks.key_id is the key's UUID. + schema = self._config.metadata_schema + p = _KS_PREFIX + return ("SELECT em.table_name, em.column_name, em.encryption_algorithm, em.key_id, " + "em.created_at, em.updated_at, " + f"ks.id AS {p}id, ks.key_id AS {p}key_id, ks.name AS {p}name, " + f"ks.master_key_arn AS {p}master_key_arn, ks.encrypted_data_key AS {p}encrypted_data_key, " + f"ks.hmac_key AS {p}hmac_key, ks.key_spec AS {p}key_spec, " + f"ks.created_at AS {p}created_at, ks.last_used_at AS {p}last_used_at " + f"FROM {schema}.encryption_metadata em " + f"LEFT JOIN {schema}.key_storage ks ON em.key_id {self._encryption_dialect.equals_operator} ks.id") + + @staticmethod + def _to_column_config(row: Mapping[str, Any]) -> ColumnEncryptionConfig: + key_metadata = None if row.get(f"{_KS_PREFIX}id") is None else KeyMetadata.from_row(row, _KS_PREFIX) + return ColumnEncryptionConfig( + table_name=MetadataManager._name(row, "table_name"), + column_name=MetadataManager._name(row, "column_name"), + algorithm=row.get("encryption_algorithm") or EncryptionAlgorithm.DEFAULT, + key_id=None if row.get("key_id") is None else int(row["key_id"]), + key_metadata=key_metadata, + created_at=row.get("created_at"), + updated_at=row.get("updated_at"), + ) + + @staticmethod + def _name(row: Mapping[str, Any], field: str) -> str: + # A driver can return text as bytes (psycopg on a SQL_ASCII database, + # Connector/Python with use_unicode=False). Such a name would never + # match the str names parsed from SQL, so an encrypted column would + # look like an ordinary one: decode it, and refuse anything else. + value = row[field] + if isinstance(value, str): + return value + if isinstance(value, (bytes, bytearray, memoryview)): + try: + return bytes(value).decode("utf-8") + except UnicodeDecodeError: + pass + raise MetadataError(Messages.get_formatted("MetadataManager.InvalidName", field, type(value).__name__)) + + @staticmethod + def _finalize(stop: Event, thread_holder: List[Optional[Thread]]) -> None: + # Runs when an unclosed manager is collected. The collection can happen + # on the refresh thread itself, inside Event.wait while it holds the + # event's lock, where stop.set() would deadlock. That thread exits on + # its own anyway: it finds the manager gone as soon as wait returns. + if thread_holder[0] is not current_thread(): + stop.set() + + @staticmethod + def _refresh_loop(manager_ref: weakref.ref[MetadataManager], stop: Event, interval_sec: float) -> None: + # Holds the manager only weakly between runs, so an unclosed manager + # can still be collected. + while not stop.wait(interval_sec): + manager = manager_ref() + if manager is None: + return + try: + manager.refresh() + except Exception as e: + logger.warning("MetadataManager.RefreshFailed", e) + del manager diff --git a/aws_advanced_python_wrapper/encryption/models.py b/aws_advanced_python_wrapper/encryption/models.py new file mode 100644 index 000000000..6d6710b0e --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/models.py @@ -0,0 +1,247 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Value objects for rows of the ``key_storage`` and ``encryption_metadata`` +tables. Their ``repr`` never shows key material, so they are safe to log.""" + +from __future__ import annotations + +import re +import unicodedata +from dataclasses import dataclass, field +from enum import Enum +from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Tuple, cast + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.utils.properties import PropertiesUtils + +if TYPE_CHECKING: + from datetime import datetime + +REDACTED = "[REDACTED]" +DEFAULT_KEY_SPEC = "AES_256" + + +class KeyOperation(Enum): + """The key or metadata operation a ``KeyManagementError`` names.""" + + AUTHORIZE_MASTER_KEY = "AUTHORIZE_MASTER_KEY" + CREATE_MASTER_KEY = "CREATE_MASTER_KEY" + DECRYPT_DATA_KEY = "DECRYPT_DATA_KEY" + DELETE_ENCRYPTION_METADATA = "DELETE_ENCRYPTION_METADATA" + DESCRIBE_MASTER_KEY = "DESCRIBE_MASTER_KEY" + GENERATE_DATA_KEY = "GENERATE_DATA_KEY" + GET_KEY_METADATA = "GET_KEY_METADATA" + INITIALIZE_COLUMN = "INITIALIZE_COLUMN" + REENCRYPT_COLUMN = "REENCRYPT_COLUMN" + ROTATE_DATA_KEY = "ROTATE_DATA_KEY" + SELECT_COLUMNS_USING_KEY = "SELECT_COLUMNS_USING_KEY" + STORE_ENCRYPTION_METADATA = "STORE_ENCRYPTION_METADATA" + STORE_KEY_METADATA = "STORE_KEY_METADATA" + UPDATE_ENCRYPTION_METADATA = "UPDATE_ENCRYPTION_METADATA" + VALIDATE_SCHEMA = "VALIDATE_SCHEMA" + + +# An ARN as AWS quotes it in an error message, in any partition. It must name +# an account, so text that is already masked doesn't match. Punctuation that +# ends a sentence or a list is left out of the match; inside the ARN (a role +# session name can hold '.' and ',') it is kept. +_ARN_IN_TEXT = re.compile( + r"arn:(?Paws(?:-[a-z]+)*):(?P[a-z0-9-]+):[a-z0-9-]*:\d{12}:" + r"(?P[^\s'\"]*[^\s'\".,;:!?)\]])") +# A URL's user info runs to the last '@' before whitespace, '?' or '#'. A +# password with a raw '/' looks like a path, so the match can also take part +# of the host, which keeps such a password out of the text. +_URL_USER_INFO = re.compile(r"://[^\s?#]*@") +# The name of a name=value pair. The lookbehind starts each match at the start of its name, so a long name isn't +# scanned again from every one of its characters. +_PAIR_NAME = re.compile(r"(? Optional[str]: + """Keep the first and last four characters of an identifier; one of 8 + characters or fewer becomes ``***``. Control characters in the kept part + become ``?``.""" + if value is None: + return None + if len(value) > 8: + return replace_control_characters(f"{value[:4]}***{value[-4:]}") + return "***" + + +def mask_arn(value: Optional[str]) -> Optional[str]: + """Mask the region and account of a KMS key ARN, and the middle of its key + id, for the wrapper's own log and error messages. An alias, as an ARN or + as an ``alias/`` name, is masked whole, because people choose its name. + Control characters in the kept part become ``?``.""" + if value is None: + return None + lower = value.strip().lower() + if lower.startswith("alias/") or ":alias/" in lower: + return "arn:aws:kms:***:***:alias/***" + _, sep, key = value.rpartition("/") + return f"arn:aws:kms:***:***:key/{mask_key_id(key) if sep and key else '***'}" + + +def mask_error_text(text: str) -> str: + """Mask an error's text in this order: each ARN that names an account (a + KMS key ARN as :func:`mask_arn` does, any other ARN down to its partition + and service), the user info of each URL, the value of each ``name=value`` + pair whose name :meth:`PropertiesUtils.is_secret_property` takes for a + secret or ends in ``key`` (a quoted value to its closing quote, any other + value to the next ASCII whitespace), and control characters, which become + ``?``. Text longer than 200 characters keeps its first 197, followed by + ``...``.""" + masked = _URL_USER_INFO.sub("://***@", _ARN_IN_TEXT.sub(_mask_matched_arn, text)) + masked = replace_control_characters(_mask_secret_pairs(masked)) + if len(masked) > _MAX_ERROR_TEXT_LENGTH: + return masked[:_MAX_ERROR_TEXT_LENGTH - len(_CUT_MARK)] + _CUT_MARK + return masked + + +def _mask_secret_pairs(text: str) -> str: + parts: List[str] = [] + copied = 0 + for name in _PAIR_NAME.finditer(text): + # A name inside a value that was just masked isn't a pair of its own. A name that ends in "key", such as + # api_key, is a secret here, though property logging doesn't mask it. + if name.start() < copied or not (PropertiesUtils.is_secret_property(name[1]) or name[1].lower().endswith("key")): + continue + value = _PAIR_VALUE.match(text, name.end()) + if value is None: + continue + parts.extend((text[copied:name.end()], "***")) + copied = value.end() + parts.append(text[copied:]) + return "".join(parts) + + +def replace_control_characters(text: str) -> str: + return "".join("?" if unicodedata.category(c) in _CONTROL_CATEGORIES else c for c in text) + + +def _mask_matched_arn(match: re.Match[str]) -> str: + if match["service"] == "kms" and match["resource"].startswith("key/"): + return cast("str", mask_arn(match[0])) + return f"arn:{match['partition']}:{match['service']}:***:***:***" + + +def _blank(value: Optional[str]) -> bool: + return value is None or not value.strip() + + +@dataclass(frozen=True) +class KeyMetadata: + """One ``key_storage`` row. + + ``id`` is the integer surrogate key, which encrypted payloads record and + ``encryption_metadata.key_id`` references. ``key_id`` is a separate UUID + string. ``encrypted_data_key`` is the base64 text of the KMS ciphertext + blob; ``hmac_key`` is raw bytes. The plaintext data key is never held here. + """ + + id: Optional[int] = None + key_id: Optional[str] = None + key_name: Optional[str] = None + master_key_arn: Optional[str] = None + encrypted_data_key: Optional[str] = field(default=None, repr=False) + hmac_key: Optional[bytes] = field(default=None, repr=False) + key_spec: str = DEFAULT_KEY_SPEC + created_at: Optional[datetime] = None + last_used_at: Optional[datetime] = None + + @property + def is_usable(self) -> bool: + """``True`` once the row names a master key and carries an encrypted + data key, an HMAC key, and a key spec.""" + return (not _blank(self.master_key_arn) and not _blank(self.encrypted_data_key) + and bool(self.hmac_key) and not _blank(self.key_spec)) + + @classmethod + def from_row(cls, row: Mapping[str, Any], prefix: str = "") -> KeyMetadata: + """Build from a ``key_storage`` row whose columns may carry ``prefix``.""" + hmac_key = row.get(f"{prefix}hmac_key") + return cls( + id=None if row.get(f"{prefix}id") is None else int(row[f"{prefix}id"]), + key_id=row.get(f"{prefix}key_id"), + key_name=row.get(f"{prefix}name"), + master_key_arn=row.get(f"{prefix}master_key_arn"), + encrypted_data_key=row.get(f"{prefix}encrypted_data_key"), + hmac_key=None if hmac_key is None else bytes(hmac_key), + key_spec=row.get(f"{prefix}key_spec") or DEFAULT_KEY_SPEC, + created_at=row.get(f"{prefix}created_at"), + last_used_at=row.get(f"{prefix}last_used_at"), + ) + + def __repr__(self) -> str: + return (f"KeyMetadata(id={self.id!r}, key_id={self.key_id!r}, key_name={self.key_name!r}, " + f"master_key_arn={mask_arn(self.master_key_arn)!r}, encrypted_data_key={REDACTED!r}, " + f"hmac_key={None if self.hmac_key is None else REDACTED!r}, key_spec={self.key_spec!r}, " + f"created_at={self.created_at!r}, last_used_at={self.last_used_at!r})") + + __str__ = __repr__ + + +@dataclass(frozen=True) +class ColumnEncryptionConfig: + """One ``encryption_metadata`` row joined to the key it references. + + ``key_metadata`` is ``None`` when the referenced ``key_storage`` row is + missing. The column still counts as encrypted, so a write fails closed + instead of storing plaintext. + """ + + table_name: str + column_name: str + algorithm: str = EncryptionAlgorithm.DEFAULT + key_id: Optional[int] = None + key_metadata: Optional[KeyMetadata] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + + @property + def column_identifier(self) -> str: + """``table.column`` for a message. The names come from the metadata table, so control characters become ``?``.""" + return replace_control_characters(f"{self.table_name}.{self.column_name}") + + @property + def is_usable(self) -> bool: + """``True`` when the algorithm is supported and the key row is usable.""" + return (EncryptionAlgorithm.is_supported(self.algorithm) + and self.key_metadata is not None and self.key_metadata.is_usable) + + +@dataclass(frozen=True) +class DataKeyReencryptionResult: + """What a re-encryption of a column did. ``unmatched_primary_keys`` holds the primary keys of the first 100 + values that matched neither ``key_id`` nor one of ``old_key_ids``.""" + + table_name: str + column_name: str + key_id: int + old_key_ids: Tuple[int, ...] + reencrypted_count: int + already_current_count: int + unmatched_count: int + batch_count: int + unmatched_primary_keys: Tuple[Any, ...] = () diff --git a/aws_advanced_python_wrapper/encryption/sql/trigger_mysql.sql b/aws_advanced_python_wrapper/encryption/sql/trigger_mysql.sql new file mode 100644 index 000000000..fff020a1b --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql/trigger_mysql.sql @@ -0,0 +1,125 @@ +DELIMITER $$ + +-- Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +-- +-- Licensed under the Apache License, Version 2.0 (the "License"). +-- You may not use this file except in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. + +-- Trigger SQL of the kms_encryption plugin. See "Enforce encryption in the database" in +-- docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md. + +-- HMAC-SHA256 built from SHA2(), which MySQL has no native HMAC for. +DROP FUNCTION IF EXISTS hmac_sha256$$ +CREATE FUNCTION hmac_sha256( + message VARBINARY(65535), + key_data VARBINARY(64) +) +RETURNS VARBINARY(32) +DETERMINISTIC +NO SQL +BEGIN + DECLARE block_size INT DEFAULT 64; -- SHA-256 block size + DECLARE key_padded VARBINARY(64); + DECLARE ipad VARBINARY(64); + DECLARE opad VARBINARY(64); + DECLARE i INT DEFAULT 1; + DECLARE key_byte INT; + + -- Reduce an over-long key to its hash, then zero-pad the key to the block size. + IF LENGTH(key_data) > block_size THEN + SET key_padded = CONCAT(UNHEX(SHA2(key_data, 256)), REPEAT(X'00', block_size - 32)); + ELSE + SET key_padded = CONCAT(key_data, REPEAT(X'00', block_size - LENGTH(key_data))); + END IF; + + -- ipad = key XOR 0x36 per byte, opad = key XOR 0x5C per byte, one raw byte at a time. + SET ipad = X''; + SET opad = X''; + WHILE i <= block_size DO + SET key_byte = ASCII(SUBSTRING(key_padded, i, 1)); + SET ipad = CONCAT(ipad, UNHEX(LPAD(HEX(key_byte ^ 0x36), 2, '0'))); + SET opad = CONCAT(opad, UNHEX(LPAD(HEX(key_byte ^ 0x5C), 2, '0'))); + SET i = i + 1; + END WHILE; + + RETURN UNHEX(SHA2(CONCAT(opad, UNHEX(SHA2(CONCAT(ipad, message), 256))), 256)); +END$$ + +-- Verifies that a stored value carries a valid HMAC for the given HMAC key. +DROP FUNCTION IF EXISTS verify_encrypted_data_hmac$$ +CREATE FUNCTION verify_encrypted_data_hmac( + data VARBINARY(65535), + hmac_key VARBINARY(32) +) +RETURNS BOOLEAN +DETERMINISTIC +NO SQL +BEGIN + -- Minimum payload: 32 (HMAC) + 4 (key id) + 1 (type) + 12 (IV) + 0 (ciphertext) + 16 (GCM tag) = 65. + IF data IS NULL OR LENGTH(data) < 65 THEN + RETURN FALSE; + END IF; + + RETURN SUBSTRING(data, 1, 32) = hmac_sha256(SUBSTRING(data, 33), hmac_key); +END$$ + +-- Called from a BEFORE INSERT trigger (and by the BEFORE UPDATE procedure) to reject a value that is +-- not a valid kms_encryption payload. Replace SCHEMA_NAME with encryption_metadata_schema. +-- The COMMENT records which version of this SQL is installed. Check it with: +-- SELECT ROUTINE_COMMENT FROM information_schema.ROUTINES +-- WHERE ROUTINE_SCHEMA = DATABASE() AND ROUTINE_NAME = 'validate_encrypted_data_hmac_before_insert'; +DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_insert$$ +CREATE PROCEDURE validate_encrypted_data_hmac_before_insert( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN column_value VARBINARY(65535) +) +COMMENT 'aws-advanced-python-wrapper kms_encryption trigger v1' +BEGIN + DECLARE v_hmac_key VARBINARY(32); + + IF column_value IS NOT NULL THEN + SELECT ks.hmac_key INTO v_hmac_key + FROM SCHEMA_NAME.encryption_metadata em + JOIN SCHEMA_NAME.key_storage ks ON em.key_id = ks.id + WHERE em.table_name = p_table_name + AND em.column_name = p_column_name + LIMIT 1; + + IF v_hmac_key IS NULL THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'No HMAC key is configured for the encrypted column'; + END IF; + + IF NOT verify_encrypted_data_hmac(column_value, v_hmac_key) THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Column does not carry a valid HMAC tag (plaintext or tampered value)'; + END IF; + END IF; +END$$ + +-- Called from a BEFORE UPDATE trigger. An UPDATE that leaves the value as it was is not +-- re-checked; see "Updates after a key rotation" in the guide. +DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_update$$ +CREATE PROCEDURE validate_encrypted_data_hmac_before_update( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN new_value VARBINARY(65535), + IN old_value VARBINARY(65535) +) +BEGIN + IF NOT (new_value <=> old_value) THEN + CALL validate_encrypted_data_hmac_before_insert(p_table_name, p_column_name, new_value); + END IF; +END$$ + +DELIMITER ; diff --git a/aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql b/aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql new file mode 100644 index 000000000..cd3050a35 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql @@ -0,0 +1,73 @@ +-- Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +-- +-- Licensed under the Apache License, Version 2.0 (the "License"). +-- You may not use this file except in compliance with the License. +-- You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +-- See the License for the specific language governing permissions and +-- limitations under the License. + +-- Trigger SQL of the kms_encryption plugin. See "Enforce encryption in the database" in +-- docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md. + +-- pgcrypto provides hmac(). If it is already installed in a schema other than public, +-- replace public in public.hmac below with that schema. +CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; + +-- Replace SCHEMA_NAME below with encryption_metadata_schema (encrypt by default). Replace that +-- token only: a plain search for "encrypt" also matches enforce_encrypted_column, +-- encryption_metadata and kms_encryption. +-- A trigger runs with the search_path of the session that fires it. Pinning it to pg_catalog +-- stops a session from putting its own functions or operators, such as hmac() or <>, ahead of +-- the built-in ones to get a plaintext value past this check. +CREATE OR REPLACE FUNCTION enforce_encrypted_column() RETURNS trigger +SET search_path = pg_catalog, pg_temp +AS $$ +DECLARE + col_name text := TG_ARGV[0]; + col_value bytea; + hmac_key bytea; + unchanged boolean; +BEGIN + -- An UPDATE that leaves the encrypted value as it was is not re-checked; see + -- "Updates after a key rotation" in the guide. + IF TG_OP = 'UPDATE' THEN + EXECUTE format('SELECT ($1).%I IS NOT DISTINCT FROM ($2).%I', col_name, col_name) + INTO unchanged USING NEW, OLD; + IF unchanged THEN + RETURN NEW; + END IF; + END IF; + + EXECUTE format('SELECT ($1).%I', col_name) INTO col_value USING NEW; + IF col_value IS NULL THEN + RETURN NEW; + END IF; + + -- Read the column's current HMAC key from key_storage. + SELECT ks.hmac_key INTO hmac_key + FROM SCHEMA_NAME.encryption_metadata em + JOIN SCHEMA_NAME.key_storage ks ON em.key_id = ks.id + WHERE em.table_name = TG_TABLE_NAME AND em.column_name = col_name; + + IF hmac_key IS NULL THEN + RAISE EXCEPTION 'No HMAC key is configured for %.%', TG_TABLE_NAME, col_name; + END IF; + + IF length(col_value) < 65 + OR substring(col_value from 1 for 32) <> public.hmac(substring(col_value from 33), hmac_key, 'sha256'::text) THEN + RAISE EXCEPTION 'Column %.% does not carry a valid HMAC tag (plaintext or tampered value)', TG_TABLE_NAME, col_name; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Records which version of this SQL is installed. Check it with: +-- SELECT obj_description('enforce_encrypted_column'::regproc, 'pg_proc'); +COMMENT ON FUNCTION enforce_encrypted_column() IS 'aws-advanced-python-wrapper kms_encryption trigger v2'; diff --git a/aws_advanced_python_wrapper/encryption/sql_analyzer.py b/aws_advanced_python_wrapper/encryption/sql_analyzer.py new file mode 100644 index 000000000..f0f043917 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_analyzer.py @@ -0,0 +1,1618 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Works out which bind parameter of a statement fills or is compared with +which column, so values bound for an encrypted column can be encrypted. + +:func:`analyze` finds the placeholders the way the driver does +(:mod:`.sql_tokenizer`), parses the statement with ``sqlglot``, and pairs each +placeholder with a column by its position, which the normalized SQL carries in +the placeholder's name. It knows nothing about encryption metadata: the +plugin looks the reported columns up. + +The analysis is best effort, and reports where it fell short: +:attr:`StatementAnalysis.gap` is ``None`` only when every column the statement +itself writes (not one written by a routine, ``CALL`` or ``DO`` it runs) was +established, either as filled by a placeholder +(:attr:`~StatementAnalysis.assignments`) or by something else +(:attr:`~StatementAnalysis.unbound_writes`). A statement that could not be +parsed is never mistaken for one that writes nothing. +""" + +from __future__ import annotations + +import logging +import re +import threading +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from functools import lru_cache +from typing import (TYPE_CHECKING, Any, Callable, Dict, FrozenSet, Iterator, + List, Optional, Sequence, Set, Tuple, Type) + +from aws_advanced_python_wrapper.errors import EncryptionPluginError +from aws_advanced_python_wrapper.utils.messages import Messages + +try: + import sqlglot + from sqlglot import exp +except ModuleNotFoundError as e: + # Only a missing package gets the install hint; a broken install raises + # its own error. + if (e.name or "").partition(".")[0] != "sqlglot": + raise + raise ImportError(Messages.get("SqlAnalyzer.SqlglotMissing")) from e + +from aws_advanced_python_wrapper.encryption.sql_tokenizer import ( + ColumnRef, ParamStyle, Placeholder, TokenizedSql, normalized_ordinal, + tokenize) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect + + +class StatementKind(Enum): + """What the (first) statement is.""" + + SELECT = "SELECT" + INSERT = "INSERT" # also MySQL REPLACE + UPDATE = "UPDATE" + DELETE = "DELETE" + MERGE = "MERGE" + COPY_FROM = "COPY_FROM" + COPY_TO = "COPY_TO" + #: Recognized but not one the analysis reads (DDL, SET, CALL...). + OTHER = "OTHER" + #: Not established: the statement could not be parsed, was not parsed + #: (see :attr:`StatementAnalysis.gap`), or its parse was not trusted. + UNKNOWN = "UNKNOWN" + + +class AnalysisGap(Enum): + """Why a statement's parameters or written columns could not all be + established. The values are fixed text, safe to log.""" + + #: The SQL could not be parsed (or ran out inside a quote or comment). + UNPARSEABLE = "the statement could not be parsed" + #: A placeholder sits inside a quoted literal, quoted identifier or + #: comment, where the driver still binds it. The tables the statement + #: names are still listed, but no placeholder's column is inferred. + HIDDEN_PLACEHOLDER = "a placeholder is inside a quoted literal, quoted identifier or comment" + #: The driver will reject the statement's placeholders. + DRIVER_ERROR = "the driver will reject the placeholders" + #: The parsed statement does not have exactly the placeholders the driver + #: binds, so the parse can't be trusted. + PLACEHOLDER_MISMATCH = "the parsed statement does not match its placeholders" + #: MySQL runs the body of a ``/*! ... */`` comment, which the analysis + #: can't read as SQL. + EXECUTABLE_COMMENT = "the statement has a MySQL executable comment" + #: The statement may write but is not a form the analysis reads + #: (``EXPLAIN ANALYZE INSERT``, ``EXECUTE``, ``LOAD DATA``, ...). + UNSUPPORTED_STATEMENT = "the statement is not a form the analysis reads" + #: A ``PREPARE``: its ``$n`` parameters are bound by a later ``EXECUTE``, + #: which the analysis does not see. + PREPARED_PARAMETERS = "the prepared statement's parameters arrive with a later EXECUTE" + #: An ``INSERT`` (or ``MERGE ... INSERT``, ``COPY ... FROM``) with no column + #: list, or ``DEFAULT VALUES``. + NO_COLUMN_LIST = "the statement does not name the columns it writes" + #: ``INSERT ... SELECT`` and similar: the rows come from a query, so which + #: value fills which column is not read. + VALUES_FROM_QUERY = "the values come from a query" + #: A ``VALUES`` row with more or fewer values than columns. + ROW_LENGTH_MISMATCH = "a VALUES row does not match the column list" + #: An ``UPDATE`` of several tables assigns a column whose table can't be + #: told. + AMBIGUOUS_TABLE = "an assignment's table can't be established" + + +@dataclass(frozen=True, slots=True) +class TableRef: + """A table a statement names.""" + + name: str + schema: Optional[str] = None + + def __str__(self) -> str: + return self.name if self.schema is None else f"{self.schema}.{self.name}" + + +@dataclass(frozen=True, slots=True) +class ParameterUse: + """A placeholder whose value fills, or is compared with, a column.""" + + placeholder: Placeholder + column: ColumnRef + #: Types the value is cast to, outermost first (``%s::text::bytea`` -> + #: ``("VARBINARY", "TEXT")``), as ``sqlglot`` names them. + casts: Tuple[str, ...] = () + #: Compared with ``= ANY(...)``, ``ALL(...)`` or ``SOME(...)``: the value + #: is a list. + array: bool = False + #: For a comparison: when it never matches, it can only remove rows from + #: what the statement reads or changes. Always true for an assignment or + #: an annotation. + safe: bool = True + + @property + def ordinal(self) -> int: + return self.placeholder.ordinal + + +@dataclass(frozen=True, slots=True) +class StatementAnalysis: + """What :func:`analyze` established about one SQL string.""" + + kind: StatementKind + #: The string stores values: an INSERT, UPDATE, MERGE, COPY ... FROM, a + #: data-modifying CTE, a PREPARE of one of those, or (when it could not + #: be read) a statement whose keywords say it may write. + writes: bool + placeholders: Tuple[Placeholder, ...] + #: Every table the string names, without duplicates and excluding CTE + #: names (outer queries first, not in text order). When the string can't + #: be read (see :attr:`gap`), also every other name that could be a table. + tables: Tuple[TableRef, ...] = () + #: The tables it writes. + written_tables: Tuple[TableRef, ...] = () + #: Placeholders written into a column. + assignments: Tuple[ParameterUse, ...] = () + #: Placeholders compared with a column (``WHERE``, ``ON``, ``HAVING``...). + comparisons: Tuple[ParameterUse, ...] = () + #: Placeholders annotated with ``/*@encrypt:...*/``. These take precedence + #: over the rest. Once the statement is parsed and its placeholders + #: matched, a qualifier is resolved through the aliases in scope at the + #: placeholder, and a bare column gets a table only when the statement + #: says which: the table the value is written to, or else the only table + #: the query around it reads. Otherwise the annotation is kept as + #: written, only folded. + annotations: Tuple[ParameterUse, ...] = () + #: Columns written with something other than a placeholder (a literal, an + #: expression, ``DEFAULT``, another column, a ``COPY`` stream). ``NULL`` + #: and copying a conflicting row's own value for the same column + #: (``EXCLUDED.c`` / ``VALUES(c)`` / a row alias) are not listed. + unbound_writes: Tuple[ColumnRef, ...] = () + #: The source column of each result column, by position, when the result + #: is a plain select list or ``RETURNING`` list: an entry is ``None`` for an + #: expression, a column of a subquery or CTE, or one whose table can't be + #: told. ``None`` altogether when unknown (``*``, set operations, + #: ``VALUES``, ``PREPARE``, several statements, no result). + result_columns: Optional[Tuple[Optional[ColumnRef], ...]] = None + #: Output names for name matching to look up first, each with the table + #: column it comes from (``None`` when unknown): every item beside a ``*`` + #: in the select list, and each item of a derived table or CTE that a + #: result column reads, through a ``*`` that reads that source or as a + #: select list column of that name. Empty when there are none or the + #: result is unknown. + named_columns: Tuple[Tuple[str, Optional[ColumnRef]], ...] = () + #: The names in :attr:`named_columns` that an unqualified ``*`` or column + #: takes from a derived table or CTE while another source of the query's + #: FROM or JOIN has columns the analysis can't list: a table, a set + #: operation, or a derived table or CTE with a ``*``, a column list over a + #: ``*`` or an item with no name. A ``USING`` or ``NATURAL`` join can give + #: the result that source's column instead. + shared_names: Tuple[str, ...] = () + #: Why the analysis is incomplete: for a statement that writes, why its + #: written columns could not all be established; for any statement, a + #: placeholder or parse problem that makes its parameters untrustworthy. + #: ``None`` when complete. + gap: Optional[AnalysisGap] = None + #: ``/*@encrypt:...*/`` comments that annotate nothing or can't be read. + stray_annotations: Tuple[str, ...] = () + #: Diagnostic detail for :attr:`gap`, safe to log: it never quotes the SQL. + detail: Optional[str] = field(default=None, compare=False) + #: The names the string gives its CTEs, in the form names are compared in + #: (see :meth:`EncryptionDriverDialect.metadata_key`). + cte_names: FrozenSet[str] = frozenset() + + @property + def complete(self) -> bool: + return self.gap is None + + def parameter_columns(self) -> Dict[int, ColumnRef]: + """The column each placeholder belongs to, by ordinal: comparisons, + then assignments, then annotations, each overriding the last.""" + result: Dict[int, ColumnRef] = {} + for use in (*self.comparisons, *self.assignments, *self.annotations): + result[use.ordinal] = use.column + return result + + +#: Only short statements with few ``%`` signs (an upper bound on their +#: placeholders) are cached, as psycopg does with its own query cache. Bulk +#: INSERTs differ in their row count and rarely repeat, so caching them would +#: only make the cache large. +CACHEABLE_SQL_LENGTH = 4096 +CACHEABLE_PERCENT_SIGNS = 64 + + +def _is_star(item: exp.Expression) -> bool: + inner = item.this if isinstance(item, exp.Alias) else item + return isinstance(inner, exp.Star) or (isinstance(inner, exp.Column) and isinstance(inner.this, exp.Star)) + + +def analyze(sql: str, dialect: Type[EncryptionDriverDialect], params: Any = None) -> StatementAnalysis: + """Analyze ``sql`` as the driver for ``dialect`` runs it with ``params`` + (the second argument of ``execute``; for ``executemany``, one of its + parameter sets). Only the kind of ``params`` matters (none, a sequence, a + mapping, and on MySQL whether it is empty), not its values. The result is + immutable and may be shared. + + :raises TypeError: if ``sql`` is not a ``str``. + """ + style = ParamStyle.of(params, dialect) + if isinstance(sql, str) and len(sql) <= CACHEABLE_SQL_LENGTH and sql.count("%") <= CACHEABLE_PERCENT_SIGNS: + try: + return _cached_analysis(sql, dialect, style) + except _Uncacheable as e: + return e.analysis + return _analysis(sql, dialect, style) + + +class _Uncacheable(Exception): + """Carries an analysis that must not be cached (lru_cache does not cache + exceptions).""" + + def __init__(self, analysis: StatementAnalysis): + super().__init__() + self.analysis = analysis + + +@lru_cache(maxsize=1024) +def _cached_analysis(sql: str, dialect: Type[EncryptionDriverDialect], style: ParamStyle) -> StatementAnalysis: + result = _analysis(sql, dialect, style) + if result.detail == RecursionError.__name__: + # Depends on how deep the calling thread's stack already is; another + # caller may parse the same SQL. + raise _Uncacheable(result) + return result + + +_WRITE_LEADING = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT", "LOAD", "EXECUTE"}) +_WRITE_WORDS = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT"}) +_KINDS = {"SELECT": StatementKind.SELECT, "WITH": StatementKind.SELECT, "VALUES": StatementKind.SELECT, + "TABLE": StatementKind.SELECT, "INSERT": StatementKind.INSERT, "REPLACE": StatementKind.INSERT, + "UPDATE": StatementKind.UPDATE, "DELETE": StatementKind.DELETE, "MERGE": StatementKind.MERGE} + +# Whitespace and comments, one character or one whole comment per repetition, +# with a line comment running through its newline. If the pattern could split +# the same text two ways, a failed match would backtrack exponentially. +_GAP = r"(?:\s|--[^\n]*(?:\n|\Z)|/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)*" + +# PREPARE name [(type, ...)] AS , on the normalized SQL. +_PREPARE = re.compile(rf""" + \A{_GAP} + PREPARE{_GAP}(?:"(?:[^"]|"")+"|[^\W\d][\w$]*){_GAP} + (?:\((?:[^()]|\([^()]*\))*\){_GAP})? + AS\b +""", re.IGNORECASE | re.VERBOSE) + +# MySQL: sqlglot rejects a qualified INSERT column list ("INSERT INTO t (t.a)"); +# a qualifier there can only name the target (the server rejects any other). +_MYSQL_NAME = r"(?:`(?:[^`]|``)+`|[\w$]+)" +_MYSQL_INSERT_COLUMNS = re.compile(rf""" + \A(?P{_GAP}INSERT{_GAP}(?:INTO{_GAP})?{_MYSQL_NAME}(?:\s*\.\s*{_MYSQL_NAME})*\s*\() + (?P[^()]*)\) +""", re.IGNORECASE | re.VERBOSE) +# One name of the column list, and the dot after it when it is a qualifier. +# A back-quoted name is one token, dots and all. +_MYSQL_COLUMN_PART = re.compile(rf"(?P{_MYSQL_NAME})(?P\s*\.\s*)?") + + +class _QuietWhileAnalyzing(logging.Filter): + """Drops sqlglot's records while this module parses on the current thread. + sqlglot logs the statement text (literals included) when it falls back to + an opaque command or reports an unsupported construct; the application's + own sqlglot logging is untouched.""" + + def __init__(self) -> None: + super().__init__() + self._local = threading.local() + + def filter(self, record: logging.LogRecord) -> bool: + return not getattr(self._local, "active", False) + + @contextmanager + def active(self) -> Iterator[None]: + previous = getattr(self._local, "active", False) + self._local.active = True + try: + yield + finally: + self._local.active = previous + + +_QUIET = _QuietWhileAnalyzing() +logging.getLogger("sqlglot").addFilter(_QUIET) + + +def _analysis(sql: str, dialect: Type[EncryptionDriverDialect], style: ParamStyle) -> StatementAnalysis: + tokens = tokenize(sql, dialect, style) + annotations = tuple(ParameterUse(p, p.annotation) for p in tokens.placeholders if p.annotation is not None) + + def result(**kwargs: Any) -> StatementAnalysis: + kwargs.setdefault("annotations", annotations) + return StatementAnalysis(placeholders=tokens.placeholders, stray_annotations=tokens.stray_annotations, + **kwargs) + + early: Optional[AnalysisGap] = None + if tokens.unterminated: + early = AnalysisGap.UNPARSEABLE + elif tokens.driver_error: + early = AnalysisGap.DRIVER_ERROR + elif tokens.has_hidden_placeholders: + early = AnalysisGap.HIDDEN_PLACEHOLDER + elif tokens.executable_comment: + early = AnalysisGap.EXECUTABLE_COMMENT + if early is not None: + # The tables are still listed, so a caller can refuse the statement + # when one of them has encrypted columns. + tables = _unread_tables(tokens, dialect, annotations) if early is not AnalysisGap.DRIVER_ERROR else () + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), gap=early, detail=tokens.driver_error, + tables=tables) + + if not tokens.leading_words: + return result(kind=StatementKind.OTHER, writes=False) + # sqlglot falls back to an opaque "command" for a statement it doesn't + # support, and logs it, so only the dialect's analyzed statements are parsed. + if any(w not in dialect.analyzed_statements for w in tokens.leading_words): + writes = _may_write(tokens) + kind = _KINDS.get(tokens.leading_words[0], StatementKind.OTHER) if len(tokens.leading_words) == 1 \ + else StatementKind.OTHER + return result(kind=kind, writes=writes, gap=AnalysisGap.UNSUPPORTED_STATEMENT if writes else None) + + parsed = _parse_statement(tokens, dialect) + if parsed is None: + writes = _may_write(tokens) + return result(kind=StatementKind.OTHER, writes=writes, + gap=AnalysisGap.UNSUPPORTED_STATEMENT if writes else None) + trees, failure = parsed + if trees is None: + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), gap=AnalysisGap.UNPARSEABLE, + detail=failure, tables=_unread_tables(tokens, dialect, annotations)) + + mismatch = _placeholder_mismatch(trees, tokens) + if (mismatch is not None or not trees or any(isinstance(t, exp.Command) for t in trees) + or any(_removes_from_parenthesized_table(t) for t in trees)): + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), + gap=AnalysisGap.PLACEHOLDER_MISMATCH if mismatch else AnalysisGap.UNPARSEABLE, detail=mismatch, + tables=_unread_tables(tokens, dialect, annotations)) + + walker = _Walker(dialect, tokens, prepared=tokens.leading_words == ("PREPARE",)) + for tree in trees: + walker.statement(tree) + return walker.result(trees, annotations, result) + + +def _parse(text: str, dialect: Type[EncryptionDriverDialect]) -> Tuple[Optional[List[exp.Expression]], Optional[str]]: + try: + with _QUIET.active(): + parsed = sqlglot.parse(text, read=dialect.sqlglot_dialect) + except Exception as e: + # sqlglot raises ParseError/TokenError, but must never break a statement. + # sqlglot's tokenizer re-raises a RecursionError as a TokenError. + cause: Optional[BaseException] = e + seen: Set[int] = set() + while cause is not None and id(cause) not in seen: + if isinstance(cause, RecursionError): + return None, RecursionError.__name__ + seen.add(id(cause)) + cause = cause.__cause__ or cause.__context__ + return None, type(e).__name__ + return [t for t in parsed if isinstance(t, exp.Expression)], None + + +def _parse_statement(tokens: TokenizedSql, dialect: Type[EncryptionDriverDialect]) -> Optional[Tuple[Optional[List[exp.Expression]], Optional[str]]]: + """Parses the normalized SQL the way the analysis reads it. A PostgreSQL + ``PREPARE name AS`` prefix is left out, and an INSERT or REPLACE that + doesn't parse is tried again without its column qualifiers when the + dialect accepts qualified insert columns. ``None`` when a PREPARE has no + such prefix.""" + text = tokens.normalized + if tokens.leading_words == ("PREPARE",): + m = _PREPARE.match(text) + if m is None: + return None + text = text[m.end():] + + trees, failure = _parse(text, dialect) + if trees is None and dialect.qualified_insert_columns and tokens.leading_words in (("INSERT",), ("REPLACE",)): + unqualified = _without_insert_column_qualifiers(text) + if unqualified is not None: + trees, failure = _parse(unqualified, dialect) + return trees, failure + + +def _named_tables(tokens: TokenizedSql, dialect: Type[EncryptionDriverDialect]) -> Tuple[TableRef, ...]: + """The tables the statement names, read from the text the analysis + parses; none when it doesn't parse.""" + parsed = _parse_statement(tokens, dialect) + trees = parsed[0] if parsed is not None else None + if not trees: + return () + walker = _Walker(dialect, tokens) + for tree in trees: + walker.collect_tables(tree) + return walker.tables + + +def _unread_tables(tokens: TokenizedSql, dialect: Type[EncryptionDriverDialect], + annotations: Tuple[ParameterUse, ...]) -> Tuple[TableRef, ...]: + """The tables a statement the analysis can't read may use: those its + parse names, every name in its text (see :attr:`TokenizedSql.names`) and + the tables its annotations name, one per metadata key.""" + found: Dict[str, TableRef] = {} + for table in _named_tables(tokens, dialect): + found.setdefault(dialect.metadata_key(table.name), table) + for name, quoted in tokens.names: + folded = dialect.fold_identifier(name, quoted=quoted) + found.setdefault(dialect.metadata_key(folded), TableRef(folded)) + for use in annotations: + if use.column.table is not None: + found.setdefault(dialect.metadata_key(use.column.table), TableRef(use.column.table)) + return tuple(found.values()) + + +def _removes_from_parenthesized_table(tree: exp.Expression) -> bool: + # sqlglot reads MySQL's "DELETE u FROM (users u) ..." as a removal from a + # subquery, so the alias u is taken for a table of its own. + return isinstance(tree, exp.Delete) and isinstance(tree.this, exp.Subquery) + + +def _without_insert_column_qualifiers(text: str) -> Optional[str]: + m = _MYSQL_INSERT_COLUMNS.match(text) + if m is None or "." not in m.group("columns"): + return None + columns = _MYSQL_COLUMN_PART.sub(lambda part: "" if part.group("dot") else part.group(0), m.group("columns")) + return f"{m.group('head')}{columns}){text[m.end():]}" + + +def _may_write(tokens: TokenizedSql) -> bool: + # Keywords only: what a statement that could not be read may be doing. + words = tokens.keywords + for leading, copies_query in zip(tokens.leading_words, tokens.copy_queries, strict=False): + if leading in _WRITE_LEADING: + return True + if leading in ("WITH", "EXPLAIN", "PREPARE", "COPY") and words & _WRITE_WORDS: + return True + if leading == "COPY" and "FROM" in words and not copies_query: + # PostgreSQL takes a query only in COPY ( query ) TO, so the FROM + # of that query doesn't make it a COPY ... FROM. + return True + if leading == "EXPLAIN" and "EXECUTE" in words: + # EXPLAIN ANALYZE EXECUTE runs the prepared statement. + return True + # A MySQL executable comment can turn any statement into a write. + return tokens.executable_comment and bool(words & (_WRITE_WORDS | _WRITE_LEADING)) + + +def _placeholder_mismatch(trees: List[exp.Expression], tokens: TokenizedSql) -> Optional[str]: + seen: Set[int] = set() + for tree in trees: + for node in tree.find_all(exp.Placeholder): + ordinal = normalized_ordinal(node.name) + if ordinal is None: + # A "?" or ":name" the driver does not bind. + continue + if ordinal in seen or ordinal >= len(tokens.placeholders): + return "a placeholder appears more than once" + seen.add(ordinal) + if len(seen) != len(tokens.placeholders): + return f"{len(tokens.placeholders) - len(seen)} placeholder(s) missing from the parse" + return None + + +def _by_ordinal(use: ParameterUse) -> int: + return use.ordinal + + +#: What an alias or table name in scope names: a table, or ``None`` for a +#: subquery, CTE or function. +_Source = Optional[TableRef] +#: Maps an assignment's qualifier (if any) to the table it writes. +_TableOf = Callable[[Optional[str]], Optional[str]] +#: For a same-row copy in an upsert: qualifier key -> {source column key -> +#: the insert column key it carries}; ``None`` maps a column to itself. +_SameRow = Dict[str, Optional[Dict[str, str]]] + +_COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.NullSafeEQ, exp.NullSafeNEQ, + exp.Like, exp.ILike) +# Operators under which a value that never matches leaves the comparison false, +# unless negated (sqlglot reads NOT LIKE as a negated Like, with no NOT node) +# or applied over ALL(...). +_SAFE_OPERATORS = (exp.EQ, exp.NullSafeEQ, exp.In, exp.Like, exp.ILike) +# Join kinds that keep only the rows that match. +_INNER_JOIN_KINDS = frozenset({"", "INNER", "CROSS", "STRAIGHT_JOIN"}) +# What makes a SELECT aggregate: an aggregate or window function, or a +# function sqlglot doesn't know, which may be an aggregate (PostgreSQL's +# jsonb_agg, MySQL's JSON_ARRAYAGG, any user-defined one). Each entry of a +# WINDOW clause is a Window, so any WINDOW clause matches. +_AGGREGATING = (exp.AggFunc, exp.Window, exp.Anonymous) +_QUERIES = (exp.Select, exp.Update, exp.Delete, exp.Merge, exp.Insert) +_ARRAY_FUNCTIONS = frozenset({"ALL", "SOME", "ANY"}) +_WRITES = (exp.Insert, exp.Update, exp.Merge) +# Operators that test a value rather than produce one. Most of them are +# Predicates only from sqlglot 30.16, and MATCH ... AGAINST is not one in any +# version, so they are listed by name as well. +_TESTS = (exp.Predicate, exp.RegexpLike, exp.RegexpILike, exp.RegexpFullMatch, exp.ArrayOverlaps, exp.ArrayContains, + exp.ArrayContainsAll, exp.ArrayContainedBy, exp.JSONBContains, exp.JSONBContainsAnyTopKeys, + exp.JSONBContainsAllTopKeys, exp.Overlaps, exp.Adjacent, exp.ExtendsLeft, exp.ExtendsRight, + exp.MatchAgainst) +# Slots of a query whose values are not written: conditions, grouping +# (including a window's PARTITION BY), sorting, limits and RETURNING. A value +# bound there feeds no column of the write above. +_NOT_WRITTEN_ARGS = frozenset({"where", "having", "on", "condition", "group", "partition_by", "order", "limit", + "offset", "qualify", "returning"}) +# Slots of a query that hold its sources (CTEs, FROM, JOIN, LATERAL, USING). A +# value bound in a source may feed the write, or may only be compared with +# another table's column, so the table it is written to can't be told. +_SOURCE_ARGS = frozenset({"with_", "from_", "joins", "laterals", "using"}) +# The Select args a "SELECT p0, p1 FROM (VALUES ...) AS v(p0, p1)" may set and +# still be read as plain rows (ORDER BY changes no row's values). +_PLAIN_SELECT_ARGS = frozenset({"expressions", "from_", "order"}) + +# How many derived tables or CTEs a result column is followed through. +_MAX_DEPTH = 8 + + +class _Walker: + """Collects what one or more parsed statements write, compare and read.""" + + def __init__(self, dialect: Type[EncryptionDriverDialect], tokens: TokenizedSql, prepared: bool = False): + self._dialect = dialect + self._tokens = tokens + # The body of a PREPARE: its $n parameters are bound later. + self._prepared = prepared + self._kind: Optional[StatementKind] = None + self._writes = False + self._tables: Dict[TableRef, None] = {} + self._written: Dict[TableRef, None] = {} + self._assignments: List[ParameterUse] = [] + self._comparisons: List[ParameterUse] = [] + self._unbound: List[ColumnRef] = [] + self._gap: Optional[AnalysisGap] = None + self._cte_names: Set[str] = set() + # Ids of the SET and ON CONFLICT assignments (EQ nodes), which are + # neither comparisons nor tests. + self._assignment_nodes: Set[int] = set() + self._scopes: Dict[int, Dict[str, _Source]] = {} + # Nearest enclosing query of a node, memoized so a long AND/OR chain + # is resolved in linear time. + self._nearest: Dict[int, Optional[exp.Expression]] = {} + # The query that decides whether a condition under a node (AND, OR, + # parentheses) is in a safe position, or None when it can't be (see + # _deciding_query), memoized so a long AND/OR chain is resolved in + # linear time; and whether each query's own position is safe. + self._deciders: Dict[int, Optional[exp.Expression]] = {} + self._safe: Dict[int, bool] = {} + # Per statement, its tables without a schema by name: where its CTEs + # are read. + self._tables_by_name: Dict[int, Dict[str, List[exp.Table]]] = {} + self._placeholder_nodes: Dict[int, exp.Expression] = {} + # Tables each write node (INSERT, UPDATE, MERGE) writes. + self._written_by: Dict[int, List[TableRef]] = {} + + def statement(self, tree: exp.Expression) -> None: + self.collect_tables(tree) + for found in tree.find_all(exp.Placeholder): + ordinal = normalized_ordinal(found.name) + if ordinal is not None: + self._placeholder_nodes[ordinal] = found + + kind = self._statement_kind(tree) + if self._kind is None: + self._kind = kind + + # Every write, wherever it sits: the statement itself or a + # data-modifying CTE. MERGE's own WHEN ... INSERT/UPDATE are read by + # the MERGE. + for node in tree.walk(): + if isinstance(node, exp.Insert) and not isinstance(node.parent, exp.When): + self._insert(node) + elif isinstance(node, exp.Update) and not isinstance(node.parent, exp.When): + self._update(node) + elif isinstance(node, exp.Merge): + self._merge(node) + elif isinstance(node, exp.Copy): + self._copy(node) + self._collect_comparisons(tree) + + def collect_tables(self, tree: exp.Expression) -> None: + """Adds the tables ``tree`` names, leaving out its CTE names.""" + for cte in tree.find_all(exp.CTE): + alias = cte.args.get("alias") + if isinstance(alias, exp.TableAlias): + self._cte_names.add(self._key(alias.this)) + for table in tree.find_all(exp.Table): + ref = self._table_ref(table) + if ref is not None: + self._tables.setdefault(ref, None) + + @property + def tables(self) -> Tuple[TableRef, ...]: + return tuple(self._tables) + + def result(self, trees: List[exp.Expression], annotations: Tuple[ParameterUse, ...], + build: Callable[..., StatementAnalysis]) -> StatementAnalysis: + assignments = tuple(sorted(self._assignments, key=_by_ordinal)) + comparisons = tuple(sorted(self._comparisons, key=_by_ordinal)) + inferred = {use.ordinal: use.column for use in (*comparisons, *assignments)} + resolved = tuple(ParameterUse(a.placeholder, self._resolve_annotation(a.placeholder, a.column, inferred)) + for a in annotations) + if self._prepared: + self._note(AnalysisGap.PREPARED_PARAMETERS) + named, shared = self._named_columns(trees[0]) if len(trees) == 1 and not self._prepared else ((), ()) + return build( + kind=self._kind or StatementKind.OTHER, + writes=self._writes, + tables=tuple(self._tables), + written_tables=tuple(self._written), + assignments=assignments, + comparisons=comparisons, + annotations=resolved, + unbound_writes=tuple(self._unbound), + result_columns=self._result_columns(trees[0]) if len(trees) == 1 and not self._prepared else None, + named_columns=named, + shared_names=shared, + gap=self._gap if self._writes else None, + cte_names=frozenset(self._cte_names)) + + def _statement_kind(self, tree: exp.Expression) -> StatementKind: + if isinstance(tree, exp.Copy): + return StatementKind.COPY_FROM if tree.args.get("kind") else StatementKind.COPY_TO + for cls, kind in ((exp.Insert, StatementKind.INSERT), (exp.Update, StatementKind.UPDATE), + (exp.Delete, StatementKind.DELETE), (exp.Merge, StatementKind.MERGE), + (exp.Query, StatementKind.SELECT), (exp.Values, StatementKind.SELECT)): + if isinstance(tree, cls): + return kind + return StatementKind.OTHER + + def _insert(self, node: exp.Insert) -> None: + self._writes = True + target = node.this + columns: Optional[List[Optional[str]]] = None + if isinstance(target, exp.Schema): + table = target.this + columns = [self._identifier(i) for i in target.expressions] + else: + table = target + # sqlglot attaches the column list of "INSERT INTO t AS a (c)" to + # the alias. + alias = table.args.get("alias") if isinstance(table, exp.Table) else None + if alias is not None and alias.columns: + columns = [self._identifier(i) for i in alias.columns] + ref = self._written_table(table, node) + name = None if ref is None else ref.name + if ref is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + if columns is not None and any(c is None for c in columns): + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + columns = None + + source = node.expression + if columns is None: + self._note(AnalysisGap.NO_COLUMN_LIST) + elif isinstance(source, exp.Values): + self._insert_rows(columns, name, source.expressions) + elif source is None: + self._note(AnalysisGap.NO_COLUMN_LIST) # DEFAULT VALUES + elif not self._insert_from_values(columns, name, source): + self._note(AnalysisGap.VALUES_FROM_QUERY) + + conflict = node.args.get("conflict") + if isinstance(conflict, exp.OnConflict): + self._upsert(conflict, name, columns, source) + + def _insert_rows(self, columns: List[Optional[str]], table: Optional[str], rows: List[exp.Expression], + positions: Optional[List[Tuple[int, Tuple[str, ...]]]] = None) -> None: + # positions: for each insert column, the position in the row that + # fills it and the casts on the way (default: the same position). + for row in rows: + values = self._row_values(row) + width = len(columns) if positions is None else max(p for p, _ in positions) + 1 + if values is None or (len(values) != width if positions is None else len(values) < width): + self._note(AnalysisGap.ROW_LENGTH_MISMATCH) + if values is None: + continue + for i, column in enumerate(columns): + position, casts = (i, ()) if positions is None else positions[i] + if position < len(values) and column is not None: + self._write(ColumnRef(column, table), values[position], casts) + + def _insert_from_values(self, columns: List[Optional[str]], table: Optional[str], + source: exp.Expression) -> bool: + """``INSERT INTO t (a, b) SELECT x, y FROM (VALUES (...), ...) AS v(x, y)``, + the form SQLAlchemy uses for a multi-row ORM insert. When each insert + column is filled by a different column of the VALUES list (possibly + cast), it is read like an ordinary multi-row VALUES. An ORDER BY is + allowed. A join, a filter, an expression other than a cast, or one + VALUES column filling two insert columns is not.""" + if not isinstance(source, exp.Select) or len(source.expressions) != len(columns): + return False + if any(value for key, value in source.args.items() if key not in _PLAIN_SELECT_ARGS): + # A join, a filter, a limit, ... (or an arg this code does not know) + return False + from_ = source.args.get("from_") + values = from_.this if isinstance(from_, exp.From) else None + alias = values.args.get("alias") if isinstance(values, exp.Values) else None + if not isinstance(alias, exp.TableAlias) or not alias.columns: + return False + names = {self._key(c): i for i, c in enumerate(alias.columns)} + alias_key = self._key(alias.this) + positions: List[Tuple[int, Tuple[str, ...]]] = [] + for item in source.expressions: + inner, casts = self._unwrap_casts(item) + qualifier = inner.args.get("table") if isinstance(inner, exp.Column) else None + if not isinstance(inner, exp.Column) or not isinstance(inner.this, exp.Identifier) \ + or (qualifier is not None and self._key(qualifier) != alias_key) \ + or self._key(inner.this) not in names: + return False + positions.append((names[self._key(inner.this)], casts)) + if len({position for position, _ in positions}) != len(positions): + # One value would fill two columns. + return False + if not isinstance(values, exp.Values): + raise EncryptionPluginError(Messages.get("SqlAnalyzer.InsertSourceNotValues")) + self._insert_rows(columns, table, values.expressions, positions) + return True + + def _upsert(self, conflict: exp.OnConflict, table: Optional[str], columns: Optional[List[Optional[str]]], + source: Optional[exp.Expression]) -> None: + same_row: _SameRow = {} + if self._dialect.upsert_row_alias is not None: + same_row[self._key(self._dialect.upsert_row_alias)] = None + row_alias = source.args.get("alias") if isinstance(source, exp.Values) else None + if isinstance(row_alias, exp.TableAlias): + renamed: Optional[Dict[str, str]] = None + if row_alias.columns: + # AS new(c1, c2) renames the inserted columns by position. + renamed = {} + for alias_column, column in zip(row_alias.columns, columns or (), strict=False): + if column is not None: + renamed[self._key(alias_column)] = self._dialect.metadata_key(column) + same_row[self._key(row_alias.this)] = renamed + for assignment in conflict.expressions: + self._assign(assignment, lambda _q: table, same_row=same_row) + + def _update(self, node: exp.Update) -> None: + self._writes = True + target = node.this + joins = (target.args.get("joins") or []) if isinstance(target, exp.Table) else [] + targets = [target] + [j.this for j in joins] + scope = self._scope(node) + ref = self._written_table(target, node) + if ref is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + for extra in targets[1:]: + self._written_table(extra, node) + + def table_of(qualifier: Optional[str]) -> Optional[str]: + if len(targets) == 1: + # One table to write: a qualifier can only mean it. + # PostgreSQL's FROM adds tables to read, not to write. + return None if ref is None else ref.name + source = scope.get(self._dialect.metadata_key(qualifier)) if qualifier else None + if source is None: + self._note(AnalysisGap.AMBIGUOUS_TABLE) + return None + return source.name + + for assignment in node.expressions: + self._assign(assignment, table_of) + + def _merge(self, node: exp.Merge) -> None: + self._writes = True + ref = self._written_table(node.this, node) + name = None if ref is None else ref.name + whens = node.args.get("whens") + for when in (whens.expressions if whens is not None else ()): + then = when.args.get("then") + if isinstance(then, exp.Update): + for assignment in then.expressions: + self._assign(assignment, lambda _q: name) + elif isinstance(then, exp.Insert): + columns = [self._identifier(c) for c in then.this.expressions] \ + if isinstance(then.this, exp.Tuple) else None + if columns is None or any(c is None for c in columns): + self._note(AnalysisGap.NO_COLUMN_LIST if columns is None else AnalysisGap.UNSUPPORTED_STATEMENT) + continue + self._insert_rows(columns, name, [then.expression]) + + def _copy(self, node: exp.Copy) -> None: + if not node.args.get("kind"): + return # COPY ... TO reads + self._writes = True + target = node.this + table = target.this if isinstance(target, exp.Schema) else target + ref = self._written_table(table) + name = None if ref is None else ref.name + if not isinstance(target, exp.Schema) or not target.expressions: + self._note(AnalysisGap.NO_COLUMN_LIST) + return + # The rows arrive as a stream, never as bind parameters. + for identifier in target.expressions: + column = self._identifier(identifier) + if column is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + else: + self._unbound.append(ColumnRef(column, name)) + + def _assign(self, assignment: exp.Expression, table_of: _TableOf, same_row: Optional[_SameRow] = None) -> None: + self._assignment_nodes.add(id(assignment)) + if not isinstance(assignment, exp.EQ): + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + return + target, value = assignment.this, assignment.expression + if isinstance(target, exp.Tuple): + # SET (a, b) = (v1, v2) / ROW(v1, v2); a subquery fills them all. + values = self._row_values(value) + if values is None or len(values) != len(target.expressions): + for column in target.expressions: + name = self._identifier(column) if isinstance(column, exp.Column) else None + if name is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + continue + self._unbound.append(ColumnRef(name, table_of(self._fold(column.args.get("table"))))) + return + pairs = list(zip(target.expressions, values, strict=False)) + else: + pairs = [(target, value)] + for column, v in pairs: + name = self._identifier(column) if isinstance(column, exp.Column) else None + if name is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + continue + if same_row is not None and self._copies_same_column(v, name, same_row): + continue + self._write(ColumnRef(name, table_of(self._fold(column.args.get("table")))), v) + + def _write(self, column: ColumnRef, value: exp.Expression, outer_casts: Tuple[str, ...] = ()) -> None: + param = self._param(value) + if param is not None: + ordinal, casts, _ = param + self._assignments.append(ParameterUse(self._tokens.placeholders[ordinal], column, outer_casts + casts)) + elif self._prepared and self._server_parameter(value): + # Bound by a later EXECUTE; the statement's gap says so. + pass + elif not isinstance(value, exp.Null): + self._unbound.append(column) + + @staticmethod + def _server_parameter(value: exp.Expression) -> bool: + while isinstance(value, (exp.Paren, exp.Cast, exp.TryCast)): + value = value.this + return isinstance(value, exp.Parameter) + + def _copies_same_column(self, value: exp.Expression, column: str, same_row: _SameRow) -> bool: + # The incoming row's own value for this column, already encrypted (or + # refused) where the row was written: EXCLUDED.c, VALUES(c) on MySQL, + # or alias.c with a MySQL row alias (by position when the alias names + # its columns). + key = self._dialect.metadata_key(column) + qualifier = value.args.get("table") if isinstance(value, exp.Column) else None + if qualifier is not None: + qualifier_key = self._key(qualifier) + if qualifier_key not in same_row: + return False + renamed = same_row[qualifier_key] + source = self._key(value.this) + return (renamed.get(source) if renamed is not None else source) == key + if self._dialect.upsert_values_function and isinstance(value, exp.Anonymous) \ + and str(value.this).upper() == "VALUES" and len(value.expressions) == 1: + inner = value.expressions[0] + if isinstance(inner, exp.Column) and inner.args.get("table") is None: + inner = inner.this + return isinstance(inner, exp.Identifier) and self._key(inner) == key + return False + + def _row_values(self, row: Optional[exp.Expression]) -> Optional[List[exp.Expression]]: + if isinstance(row, exp.Paren): + return [row.this] + if isinstance(row, exp.Tuple): + items = list(row.expressions) + # MySQL's VALUES ROW(...) comes back as a one-item tuple. + if len(items) == 1 and self._is_row(items[0]): + return list(items[0].expressions) + return items + if row is not None and self._is_row(row): + return list(row.expressions) + return None + + @staticmethod + def _is_row(node: exp.Expression) -> bool: + return isinstance(node, exp.Anonymous) and str(node.this).upper() == "ROW" + + def _collect_comparisons(self, tree: exp.Expression) -> None: + for node in tree.walk(): + if id(node) in self._assignment_nodes: + continue + if isinstance(node, _COMPARISONS): + self._compare(node, node.this, node.expression) + self._compare(node, node.expression, node.this) + elif isinstance(node, exp.In): + for item in node.expressions: + self._compare(node, node.this, item) + # %s IN (SELECT ssn FROM users) + self._compare(node, node.args.get("query"), node.this) + elif isinstance(node, exp.Between): + self._compare(node, node.this, node.args.get("low")) + self._compare(node, node.this, node.args.get("high")) + + def _compare(self, node: exp.Expression, column: Optional[exp.Expression], + value: Optional[exp.Expression]) -> None: + column, every = self._compared_column(column) + if not isinstance(column, exp.Column) or not isinstance(column.this, exp.Identifier) or value is None: + return + param = self._param(value) + if param is None: + return + ordinal, casts, function = param + # A sub-select's column is resolved in the sub-select. + ref = self._column_ref(column, column) + if ref is not None: + safe = isinstance(node, _SAFE_OPERATORS) and not node.args.get("negate") and function != "ALL" and not every + if safe: + decider = self._deciding_query(node) + safe = decider is not None and self._query_safe(decider) + self._comparisons.append( + ParameterUse(self._tokens.placeholders[ordinal], ref, casts, function is not None, safe)) + + @staticmethod + def _compared_column(side: Optional[exp.Expression]) -> Tuple[Optional[exp.Expression], bool]: + """What one side of a comparison compares a value with, and whether + it does so under ALL. A column in parentheses is the column + (``(ssn) = %s``). A sub-select whose select list is one column, under + any alias, is that column, because its rows hold that column's + values: ``%s IN (SELECT ssn FROM users)``, ``%s = ANY (SELECT ...)``, + ``%s <> ALL (SELECT ...)`` and ``%s = (SELECT ...)``, in any number of + parentheses and with an ORDER BY or LIMIT between them + (``%s <> ALL ((SELECT ...) LIMIT 5)``). Any other side comes back with + the parentheses, aliases, ALL, SOME or ANY over a sub-select with its + ORDER BY or LIMIT, and one-item select list around it removed, for + the caller to reject.""" + every = False + if isinstance(side, (exp.Any, exp.All)) and isinstance(side.this, (exp.Subquery, exp.Select)): + # sqlglot reads ALL (SELECT ...) and SOME (SELECT ...) without a Subquery. + every, side = isinstance(side, exp.All), side.this + elif isinstance(side, exp.Anonymous) and str(side.this).upper() in _ARRAY_FUNCTIONS \ + and len(side.expressions) == 1: + # sqlglot reads ALL ((SELECT ...)) and SOME ((SELECT ...)) as functions, and an ORDER BY or LIMIT + # between the parentheses as a node over the Subquery. + query = side.expressions[0] + while isinstance(query, (exp.Order, exp.Limit)): + query = query.this + if isinstance(query, exp.Subquery): + every, side = str(side.this).upper() == "ALL", query + while True: + if isinstance(side, (exp.Paren, exp.Subquery, exp.Alias)): + side = side.this + elif isinstance(side, exp.Select) and len(side.expressions) == 1: + side = side.expressions[0] + else: + return side, every + + def _deciding_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The query whose own position (:meth:`_query_safe`) decides whether + a condition at ``node`` that never holds can only remove rows from + what the statement reads or changes; ``None`` when the condition's + place makes it unsafe in any query. The place is safe when AND, OR + and parentheses alone join the condition to the WHERE of a SELECT, + UPDATE or DELETE, the HAVING of a SELECT, or the ON of an inner join + in a query with no outer join. Anything else around it (NOT, IS, a + function, CASE, a select list, a SET value, a MERGE ...) is not.""" + path: List[int] = [] + child, parent = node, node.parent + while isinstance(parent, (exp.Paren, exp.And, exp.Or)) \ + or (isinstance(parent, exp.Escape) and child.arg_key == "this"): + if id(parent) in self._deciders: + decider = self._deciders[id(parent)] + break + path.append(id(parent)) + child, parent = parent, parent.parent + else: + # Reached without a memo hit: the clause the condition is in decides. + query = parent.parent if parent is not None else None + if (isinstance(parent, exp.Where) and isinstance(query, (exp.Select, exp.Update, exp.Delete))) \ + or (isinstance(parent, exp.Having) and isinstance(query, exp.Select)): + decider = query + elif isinstance(parent, exp.Join) and child.arg_key == "on" and not parent.side \ + and parent.kind in _INNER_JOIN_KINDS: + decider = self._joining_query(parent) + else: + decider = None + for key in path: + self._deciders[key] = decider + return decider + + def _query_safe(self, query: exp.Expression) -> bool: + """Whether a condition of ``query`` that never holds can only remove + rows from what the statement reads or changes, memoized. Worked out + with a stack rather than by recursion, because a chain of CTEs is as + deep as it is long. A query counts as unsafe while it is worked out, + so a recursive CTE's reference to itself ends unsafe.""" + needs: Dict[int, List[exp.Expression]] = {} + todo = [query] + while todo: + top = todo[-1] + if id(top) in needs: + self._safe[id(top)] = all(self._safe[id(n)] for n in needs.pop(id(top))) + todo.pop() + elif id(top) in self._safe: + todo.pop() + else: + required = self._requirements(top) + self._safe[id(top)] = required == [] + if required: + needs[id(top)] = required + todo.extend(n for n in required if id(n) not in self._safe) + else: + todo.pop() + return self._safe[id(query)] + + def _requirements(self, query: exp.Expression) -> Optional[List[exp.Expression]]: + """The queries whose positions must all be safe for the position of + ``query`` to be, or ``None`` when it is unsafe whatever they are. What + reads its rows must only lose rows when it loses some: the statement + itself; a sub-select that doesn't group, aggregate or have a WINDOW + clause (an aggregate or window function in its select list, ORDER BY + or DISTINCT ON, where a function sqlglot doesn't know counts as an + aggregate), read (through either side of UNION or INTERSECT, the left + of EXCEPT, and an ORDER BY or LIMIT written after its parentheses) by + IN, EXISTS, a scalar ``=`` or ``= ANY`` in a safe position, or as a + FROM or JOIN source of a query with no outer join; a + CTE read only that way; or the rows of the statement's INSERT.""" + child, parent = query, query.parent + if parent is None: + return [] + if isinstance(query, exp.Select) and (query.args.get("group") or query.args.get("having") or any( + e.find(*_AGGREGATING) for e in (*query.expressions, *(query.args.get("windows") or ()), + query.args.get("order"), query.args.get("distinct")) if e)): + # It may return rows for no input row, such as a count of 0. + return None + while isinstance(parent, (exp.Subquery, exp.Paren, exp.Union, exp.Intersect)) \ + or (isinstance(parent, (exp.Except, exp.Order, exp.Limit)) and child.arg_key == "this"): + child, parent = parent, parent.parent + if parent is None: + # A set operation or a parenthesized query that is the statement. + return [] + if isinstance(parent, exp.Insert): + # INSERT ... SELECT: a filter that never holds only inserts fewer rows. + return [] if child.arg_key == "expression" and parent.parent is None else None + if isinstance(parent, exp.CTE): + return self._cte_readers(parent) + decider: Optional[exp.Expression] = None + if isinstance(parent, exp.Exists) or (isinstance(parent, exp.In) and child.arg_key == "query") \ + or (isinstance(parent, exp.EQ) and isinstance(child, exp.Subquery)): + decider = self._deciding_query(parent) + elif (isinstance(parent, exp.Any) or (isinstance(parent, exp.Anonymous) and str(parent.this).upper() == "SOME")) \ + and isinstance(parent.parent, exp.EQ): + # sqlglot reads SOME ((SELECT ...)) as a function. + decider = self._deciding_query(parent.parent) + elif isinstance(parent, (exp.From, exp.Join)) and child.arg_key == "this": + decider = self._joining_query(parent) + return None if decider is None else [decider] + + def _cte_readers(self, cte: exp.Expression) -> Optional[List[exp.Expression]]: + """The queries that read ``cte``, each as a FROM or JOIN source with no + outer join, or ``None`` when something reads it otherwise. It is read + wherever a table without a schema has its name in the statement (as + :attr:`_cte_names` is scoped), its own body included.""" + root = cte.root() + named = self._tables_by_name.get(id(root)) + if named is None: + named = self._tables_by_name[id(root)] = {} + for table in root.find_all(exp.Table): + if table.args.get("db") is None and isinstance(table.this, exp.Identifier): + named.setdefault(self._key(table.this), []).append(table) + readers: List[exp.Expression] = [] + for table in named.get(self._key(cte.args["alias"].this), ()): + reader = self._joining_query(table.parent) \ + if isinstance(table.parent, (exp.From, exp.Join)) and table.arg_key == "this" else None + if reader is None: + return None + readers.append(reader) + return readers + + def _joining_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The query that owns ``node`` (a JOIN, or the FROM or JOIN of a + derived table or CTE) when it has no outer join, else ``None``. Joins + are evaluated left to right, so a later RIGHT or FULL join keeps the + rows of its side when an earlier one matches none.""" + owner = self._nearest_query(node) + return owner if owner is not None and not self._has_outer_join(owner) else None + + @staticmethod + def _has_outer_join(query: exp.Expression) -> bool: + """Whether ``query`` has a join with a side (LEFT, RIGHT, FULL), read + from its own joins and from the tables and ``Subquery`` nodes its FROM, + its USING and the table it writes start from, at any depth of + parentheses: sqlglot puts a multi-table UPDATE's or DELETE's joins + under a table, and the joins that follow a derived table or a + parenthesized join under its ``Subquery``. A derived table's joins are + its own query's.""" + using = query.args.get("using") + sources: List[Any] = [query.args.get("this"), query.args.get("from_"), *(query.args.get("joins") or ()), + *(using if isinstance(using, list) else [using])] + while sources: + source = sources.pop() + if isinstance(source, exp.Join): + if source.side: + return True + sources.append(source.this) + elif isinstance(source, (exp.From, exp.Subquery)): + # A Subquery around a Table is a parenthesized join. sqlglot + # hangs the joins that follow a derived table or a + # parenthesized join on its Subquery. + sources.append(source.this) + sources.extend(source.args.get("joins") or ()) + elif isinstance(source, exp.Table): + sources.extend(source.args.get("joins") or ()) + return False + + @staticmethod + def _unwrap_casts(value: exp.Expression) -> Tuple[exp.Expression, Tuple[str, ...]]: + casts: List[str] = [] + while True: + if isinstance(value, exp.Paren): + value = value.this + elif isinstance(value, (exp.Cast, exp.TryCast)): + to = value.args.get("to") + casts.append(to.this.name if isinstance(to, exp.DataType) else str(to)) + value = value.this + else: + return value, tuple(casts) + + def _param(self, value: exp.Expression) -> Optional[Tuple[int, Tuple[str, ...], Optional[str]]]: + """(ordinal, casts, array function) when ``value`` is a placeholder, + possibly in parentheses, casts, or ANY/ALL/SOME. The array function + is ``"ANY"``, ``"ALL"`` or ``"SOME"``, or ``None`` outside them.""" + value, casts = self._unwrap_casts(value) + function: Optional[str] = None + if isinstance(value, (exp.Any, exp.All)): + function, (value, more) = "ALL" if isinstance(value, exp.All) else "ANY", self._unwrap_casts(value.this) + casts += more + elif isinstance(value, exp.Anonymous) and str(value.this).upper() in _ARRAY_FUNCTIONS \ + and len(value.expressions) == 1: + # sqlglot reads PostgreSQL's ALL(...) and SOME(...) as functions. + function, (value, more) = str(value.this).upper(), self._unwrap_casts(value.expressions[0]) + casts += more + if isinstance(value, exp.Placeholder): + ordinal = normalized_ordinal(value.name) + if ordinal is not None: + return ordinal, casts, function + return None + + def _fold(self, name: Any) -> Optional[str]: + """The name an identifier resolves to, folded as the engine folds it; + ``None`` when ``name`` is not an identifier.""" + if isinstance(name, exp.Identifier): + return self._dialect.fold_identifier(name.this, quoted=bool(name.args.get("quoted"))) + if isinstance(name, str) and name: + return self._dialect.fold_identifier(name, quoted=False) + return None + + def _identifier(self, node: Any) -> Optional[str]: + """The column a node names, or ``None`` when it is not a plain name + (a subscript, a field of a composite, ...).""" + if isinstance(node, exp.Column): + node = node.this + return self._fold(node) if isinstance(node, exp.Identifier) else None + + def _key(self, name: Any) -> str: + """The form names are compared in (case-insensitive on MySQL).""" + return self._dialect.metadata_key(self._fold(name) or "") + + def _table_ref(self, table: exp.Table) -> Optional[TableRef]: + if not isinstance(table.this, exp.Identifier): + # A function or a subquery. + return None + name = self._fold(table.this) + if name is None: + raise EncryptionPluginError(Messages.get("SqlAnalyzer.UnnamedTable")) + schema = self._fold(table.args.get("db")) + if schema is None and self._dialect.metadata_key(name) in self._cte_names: + return None + return TableRef(name, schema) + + def _written_table(self, table: Optional[exp.Expression], + write: Optional[exp.Expression] = None) -> Optional[TableRef]: + ref = self._table_ref(table) if isinstance(table, exp.Table) else None + if ref is not None: + self._written.setdefault(ref, None) + if write is not None: + self._written_by.setdefault(id(write), []).append(ref) + return ref + + def _write_targets(self, node: exp.Expression) -> Optional[Sequence[TableRef]]: + """The tables written by the INSERT, UPDATE or MERGE that the value at + ``node`` feeds. + + Returns ``None`` when the value is not written. That is the case when, + on the way up, it is compared or otherwise tested (:data:`_TESTS`), is + the condition or operand of a ``CASE`` or ``IF``, or sits in one of + :data:`_NOT_WRITTEN_ARGS`, and when it reaches no write at all. + + Returns an empty sequence when the table can't be told: the value + reaches the write through one of :data:`_SOURCE_ARGS` (a CTE, or a + ``FROM``, ``JOIN``, ``LATERAL`` or ``USING`` source), or the write's + target is not a plain table.""" + child: Any = node + parent: Any = node.parent + through_source = False + while parent is not None: + key = child.arg_key + if key in _NOT_WRITTEN_ARGS: + return None + # A SET or ON CONFLICT "c = value" is an assignment, not a test. + if isinstance(parent, _TESTS) and id(parent) not in self._assignment_nodes: + return None + if isinstance(parent, (exp.If, exp.Case)) and key == "this": + return None + through_source = through_source or key in _SOURCE_ARGS + # A MERGE's WHEN ... UPDATE / INSERT belongs to the MERGE. + if isinstance(parent, _WRITES) and not isinstance(parent.parent, exp.When): + return () if through_source else self._written_by.get(id(parent), ()) + child, parent = parent, parent.parent + return None + + def _scope(self, query: exp.Expression) -> Dict[str, _Source]: + """Alias or table name -> what it names, for the sources one query + reads directly.""" + cached = self._scopes.get(id(query)) + if cached is not None: + return cached + sources: Dict[str, _Source] = {} + + def add(node: Any) -> None: + if isinstance(node, list): + for item in node: + add(item) + return + if not isinstance(node, exp.Expression): + # An absent arg can be None or False. + return + if isinstance(node, (exp.From, exp.Join)): + add(node.this) + return + alias = node.args.get("alias") + alias_name = alias.this if isinstance(alias, exp.TableAlias) else None + ref = self._table_ref(node) if isinstance(node, exp.Table) else None + if alias_name is not None: + sources[self._key(alias_name)] = ref + if ref is not None: + sources.setdefault(self._dialect.metadata_key(ref.name), ref) + elif isinstance(node, exp.Table) and alias_name is None: + sources[self._key(node.this)] = None # a CTE named directly + if isinstance(node, exp.Table): + add(node.args.get("joins")) + + if isinstance(query, exp.Insert): + add(query.this.this if isinstance(query.this, exp.Schema) else query.this) + else: + if isinstance(query, (exp.Update, exp.Delete, exp.Merge)): + add(query.args.get("this")) + add(query.args.get("from_")) + add(query.args.get("joins")) + # A list for DELETE ... USING. + add(query.args.get("using")) + add(query.args.get("tables")) + self._scopes[id(query)] = sources + return sources + + def _nearest_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The innermost query around ``node`` (excluding ``node`` itself).""" + path: List[int] = [] + parent = node.parent + found: Optional[exp.Expression] = None + while parent is not None: + if id(parent) in self._nearest: + found = self._nearest[id(parent)] + break + if isinstance(parent, _QUERIES): + found = parent + break + path.append(id(parent)) + parent = parent.parent + for key in path: + self._nearest[key] = found + return found + + def _enclosing_queries(self, node: exp.Expression) -> Iterator[exp.Expression]: + query = self._nearest_query(node) + while query is not None: + yield query + query = self._nearest_query(query) + + def _column_ref(self, column: exp.Column, at: exp.Expression) -> Optional[ColumnRef]: + name = self._identifier(column) + if name is None: + return None + qualifier = self._fold(column.args.get("table")) + if qualifier is not None: + key = self._dialect.metadata_key(qualifier) + for query in self._enclosing_queries(at): + scope = self._scope(query) + if key in scope: + source = scope[key] + return ColumnRef(name, None if source is None else source.name) + # Not an alias in sight: taken as a table name. + return ColumnRef(name, qualifier) + nearest = self._nearest_query(at) + if nearest is not None: + sources = set(self._scope(nearest).values()) + if len(sources) == 1: + only = next(iter(sources)) + return ColumnRef(name, None if only is None else only.name) + return ColumnRef(name) + + def _resolve_annotation(self, placeholder: Placeholder, ref: ColumnRef, + inferred: Dict[int, ColumnRef]) -> ColumnRef: + """Resolve an annotation's qualifier through the aliases in scope at + its placeholder, nearest query first. A qualifier that names nothing + in scope, or names a subquery or CTE, is kept as a table name. + + A bare column gets a table only when the statement says which: + + 1. the table the analysis found for that placeholder, if it is the + same column; + 2. otherwise, for a written value (a VALUES row, a SET value, or the + select list of a query feeding an INSERT, UPDATE or MERGE; see + :meth:`_write_targets`), the table that write writes. With several + written tables, or when the value reaches the write through a CTE + or a FROM, JOIN, LATERAL or USING source, it stays bare; + 3. otherwise, for a compared or read value, the only table its + nearest query reads. + + In every other case it stays bare.""" + node = self._placeholder_nodes.get(placeholder.ordinal) + if ref.table is not None: + key = self._dialect.metadata_key(ref.table) + for query in (self._enclosing_queries(node) if node is not None else ()): + scope = self._scope(query) + if key in scope: + source = scope[key] + return ColumnRef(ref.column, ref.table if source is None else source.name) + return ref + found = inferred.get(placeholder.ordinal) + if found is not None and found.table is not None \ + and self._dialect.metadata_key(found.column) == self._dialect.metadata_key(ref.column): + return ColumnRef(ref.column, found.table) + if node is None: + return ref + targets = self._write_targets(node) + if targets is not None: + tables = {t.name: None for t in targets} + return ColumnRef(ref.column, next(iter(tables))) if len(tables) == 1 else ref + nearest = self._nearest_query(node) + if nearest is not None: + sources = set(self._scope(nearest).values()) + if len(sources) == 1: + only = next(iter(sources)) + if only is not None: + return ColumnRef(ref.column, only.name) + return ref + + def _result_columns(self, tree: exp.Expression) -> Optional[Tuple[Optional[ColumnRef], ...]]: + if isinstance(tree, exp.Select): + items = tree.expressions + else: + returning = tree.args.get("returning") if isinstance(tree, (exp.Insert, exp.Update, exp.Delete)) else None + if not isinstance(returning, exp.Returning): + return None + items = returning.expressions + result: List[Optional[ColumnRef]] = [] + for item in items: + if _is_star(item): + return None + result.append(self._source_column(item, tree)) + return tuple(result) + + def _named_columns(self, tree: exp.Expression) -> Tuple[Tuple[Tuple[str, Optional[ColumnRef]], ...], Tuple[str, ...]]: + """The :attr:`StatementAnalysis.named_columns` and + :attr:`StatementAnalysis.shared_names` of ``tree``. An item of a + derived table or CTE counts only for a result column that reads it: a + ``*`` that reads that source (``*`` or ``.*``), or a select + list column of that name, unqualified or qualified by the source's + name, with or without an alias. A literal or an expression never takes + a derived item's source, and neither does a column that a ``*`` reads + from another source. A derived table or CTE lists its columns only when + every item of its select list has a name; a table, a set operation, a + ``*`` or an item with no name leaves them unlisted. A name read from a + derived table or CTE is shared when another source of the FROM or JOIN + leaves its columns unlisted.""" + if not isinstance(tree, exp.Select): + return (), () + named: List[Tuple[str, Optional[ColumnRef]]] = [] + shared: List[str] = [] + outer = self._output_items(tree.expressions, ()) or [] + stars = [item.this if isinstance(item, exp.Alias) else item for item in tree.expressions if _is_star(item)] + every_source = any(star.args.get("table") is None for star in stars) + star_sources = {self._key(star.args.get("table")) for star in stars if star.args.get("table") is not None} + if stars: + for name, item in outer: + if name is not None: + named.append((name, self._source_column(item, tree))) + derived: List[Tuple[Optional[str], exp.Expression, List[Tuple[Optional[str], exp.Expression]], bool]] = [] + for qualifier in self._source_names(tree): + found = self._derived_query(qualifier, tree) + if found is not None and isinstance(found[0], exp.Select): + items = self._output_items(found[0].expressions, found[1]) or [] + listed = bool(items) and all(name is not None for name, _ in items) + derived.append((qualifier, found[0], items, listed)) + from_ = tree.args.get("from_") + # A source whose columns aren't all listed, such as a table, may give a result column of the same name. + unlisted = (from_ is not None) + len(tree.args.get("joins") or []) - sum(listed for *_, listed in derived) + for qualifier, inner, items, listed in derived: + # A source's own unlisted columns can't merge into its own items, so only the other sources count. + merges = unlisted - (0 if listed else 1) > 0 + if every_source or qualifier in star_sources: + for name, item in items: + if name is not None: + named.append((name, self._source_column(item, inner))) + if every_source and merges: + shared.append(name) + for out, outer_item in outer: + column = outer_item.this if isinstance(outer_item, exp.Alias) else outer_item + read = self._identifier(column) if isinstance(column, exp.Column) else None + table = column.args.get("table") + if out is None or read is None or (table is not None and self._key(table) != qualifier): + continue + for name, item in items: + if name is not None and self._dialect.metadata_key(name) == self._dialect.metadata_key(read): + named.append((out, self._source_column(item, inner))) + if table is None and merges: + shared.append(out) + return tuple(named), tuple(shared) + + def _source_column(self, item: exp.Expression, query: exp.Expression) -> Optional[ColumnRef]: + """The table column a select list item of ``query`` comes from, or + ``None`` for an expression or a column whose table can't be told.""" + inner = item.this if isinstance(item, exp.Alias) else item + ref = self._column_ref(inner, inner) if isinstance(inner, exp.Column) else None + if (ref is None or ref.table is None) and isinstance(query, exp.Select): + # Read through a derived table or CTE: follow it to its table. + ref = self._trace(inner, query, 0) + return ref if ref is not None and ref.table is not None else None + + def _source_names(self, query: exp.Expression) -> List[Optional[str]]: + """The name ``query`` reads each of its sources by, in the form + :meth:`_derived_query` takes; ``None`` for an unnamed only source.""" + nodes: List[exp.Expression] = [] + from_ = query.args.get("from_") + if from_ is not None: + nodes.append(from_.this) + nodes.extend(j.this for j in query.args.get("joins") or []) + names: List[Optional[str]] = [] + for node in nodes: + alias = node.args.get("alias") + alias_name = self._fold(alias.this) if isinstance(alias, exp.TableAlias) else None + if alias_name is not None: + names.append(self._dialect.metadata_key(alias_name)) + elif isinstance(node, exp.Table) and isinstance(node.this, exp.Identifier): + names.append(self._key(node.this)) + elif len(nodes) == 1: + names.append(None) + return names + + def _output_items(self, items: List[exp.Expression], + listed: Tuple[str, ...]) -> Optional[List[Tuple[Optional[str], exp.Expression]]]: + """Each select list item with the name a reader sees it by: a listed + name by position, and past the list, its alias or column name. With a + list, ``None`` when the list is longer than the items or the items + hold a ``*``, because the positions can't be told then.""" + if listed and (len(listed) > len(items) or any(_is_star(item) for item in items)): + return None + named: List[Tuple[Optional[str], exp.Expression]] = [] + for position, item in enumerate(items): + if position < len(listed): + named.append((listed[position], item)) + elif isinstance(item, exp.Alias): + # The alias is folded from its Identifier, so quoting counts. + named.append((self._fold(item.args.get("alias")), item)) + else: + named.append((self._identifier(item), item)) + return named + + def _trace(self, node: exp.Expression, query: exp.Expression, depth: int) -> Optional[ColumnRef]: + """The table column a result column of ``query`` comes from, followed + through derived tables and CTEs, a column list by position; ``None`` + past a set operation, ``*``, an expression or :data:`_MAX_DEPTH` levels.""" + if depth > _MAX_DEPTH or not isinstance(node, exp.Column): + return None + ref = self._column_ref(node, node) + if ref is not None and ref.table is not None: + return ref + name = self._identifier(node) + if name is None: + return None + qualifier = self._fold(node.args.get("table")) + found = self._derived_query(None if qualifier is None else self._dialect.metadata_key(qualifier), query) + if found is None or not isinstance(found[0], exp.Select): + return None + inner, listed = found + key = self._dialect.metadata_key(name) + for out, item in self._output_items(inner.expressions, listed) or (): + if out is not None and self._dialect.metadata_key(out) == key: + return self._trace(item.this if isinstance(item, exp.Alias) else item, inner, depth + 1) + return None + + def _derived_query(self, qualifier: Optional[str], + query: exp.Expression) -> Optional[Tuple[exp.Expression, Tuple[str, ...]]]: + """The query behind the derived table or CTE that ``query`` reads as + ``qualifier``, or behind its only source when there is no qualifier, + with the column names its alias or CTE lists (empty when none). A CTE + that lists names and is read under an alias that lists names too is + not followed. A CTE sees only the CTEs written before it, as the + engines resolve a non-recursive ``WITH``. In a ``RECURSIVE`` list, a + source name no earlier CTE defines leaves the column unknown.""" + nodes: List[exp.Expression] = [] + from_ = query.args.get("from_") + if from_ is not None: + nodes.append(from_.this) + nodes.extend(j.this for j in query.args.get("joins") or []) + if qualifier is None and len(nodes) != 1: + return None + for node in nodes: + alias = node.args.get("alias") + alias_name = self._fold(alias.this) if isinstance(alias, exp.TableAlias) else None + renamed = self._column_list(alias) + if isinstance(node, exp.Subquery): + if qualifier is None or (alias_name is not None and self._dialect.metadata_key(alias_name) == qualifier): + return None if renamed is None else (node.this, renamed) + elif isinstance(node, exp.Table) and isinstance(node.this, exp.Identifier): + key = self._key(node.this) + seen = key if alias_name is None else self._dialect.metadata_key(alias_name) + if qualifier is not None and seen != qualifier: + continue + if renamed is None: + return None + outer: Optional[exp.Expression] = query + inside: Any = None + while outer is not None: + with_ = outer.args.get("with_") + recursive = with_ is not None and bool(with_.args.get("recursive")) + for cte in (with_.expressions if with_ is not None else ()): + if cte is inside: + if recursive: + # PostgreSQL lets a RECURSIVE list read later CTEs. + return None + # A CTE sees only the CTEs before it. + break + cte_alias = cte.args.get("alias") + if isinstance(cte_alias, exp.TableAlias) and self._key(cte_alias.this) == key: + listed = self._column_list(cte_alias) + if listed is None or (listed and renamed): + return None + return cte.this, renamed or listed + inside = outer.parent + outer = self._nearest_query(outer) + return None + return None + + def _column_list(self, alias: Any) -> Optional[Tuple[str, ...]]: + """The column names a table alias or CTE lists, folded: empty when + it lists none, ``None`` when one of them isn't a plain name.""" + columns = alias.args.get("columns") if isinstance(alias, exp.TableAlias) else None + names: List[str] = [] + for column in columns or (): + name = self._fold(column) + if name is None: + return None + names.append(name) + return tuple(names) + + def _note(self, gap: AnalysisGap) -> None: + if self._gap is None: + self._gap = gap diff --git a/aws_advanced_python_wrapper/encryption/sql_tokenizer.py b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py new file mode 100644 index 000000000..af479844d --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py @@ -0,0 +1,584 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Finds a statement's bind parameters the way its driver does. + +Both supported drivers use the ``pyformat`` paramstyle, but they do not find +placeholders the same way, and neither skips quoted literals or comments: + +* psycopg, when given parameters (even an empty sequence), treats every ``%`` + as the start of a placeholder: ``%s``/``%b``/``%t``, ``%(name)s`` (or ``b`` + / ``t``), or ``%%`` for a literal percent sign. Anything else after a ``%`` + is a ``ProgrammingError``, and positional and named placeholders cannot be + mixed. Given ``None`` it substitutes nothing. +* MySQL Connector/Python, given a non-empty list or tuple, replaces every + ``%s`` substring and nothing else (``%%`` is left alone). Given a non-empty + dict, it replaces ``%(name)s`` and turns ``%(name)%`` into ``%``. Given an + empty value it substitutes nothing, and given any other type it raises + ``ProgrammingError``. + +So the n-th placeholder found here is the n-th value the driver binds, even +when it sits inside a quoted literal or a comment. Such a placeholder is +reported as hidden: the statement's structure says nothing about which column +it fills, and the statement is almost certainly broken anyway. + +The SQL is also lexed (quotes, comments, statement separators) for what the +driver doesn't need: spotting hidden placeholders, reading +``/*@encrypt:table.column*/`` annotations, and producing a copy of the SQL a +structural parser can read, with each placeholder replaced by a named +placeholder that carries its position. + +The lexer assumes server defaults: ``standard_conforming_strings=on`` on +PostgreSQL, and backslash escapes on and ``ANSI_QUOTES`` off on MySQL. Under +other settings a literal may end somewhere else on the server. MySQL runs the +body of an executable comment (``/*! ... */``), so a statement with one is +flagged (:attr:`TokenizedSql.executable_comment`) rather than read as if the +comment were not there. The database-side HMAC trigger, not this module, +guarantees an encrypted column never holds plaintext. + +The placeholder rules are the drivers' (psycopg, MySQL Connector/Python), not +the engines': another driver for the same engine needs its own. + +This module has no third-party dependencies. +""" + +from __future__ import annotations + +import re +from bisect import bisect_right +from collections.abc import Mapping +from dataclasses import dataclass, field, replace +from enum import Enum +from typing import (TYPE_CHECKING, Any, FrozenSet, List, Optional, Tuple, Type, + Union) + +from aws_advanced_python_wrapper.errors import (EncryptionPluginError, + UnsupportedOperationError) +from aws_advanced_python_wrapper.utils.messages import Messages + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect + +#: Prefix of the named placeholders written into :attr:`TokenizedSql.normalized`: +#: ``:_kms_p3`` stands for the placeholder whose ordinal is 3. +NORMALIZED_PLACEHOLDER_PREFIX = "_kms_p" + + +class ParamStyle(Enum): + """How a statement's parameters were passed, which decides what its driver + treats as a placeholder.""" + + #: No parameters, or (MySQL) a type the driver refuses: nothing is + #: substituted. + NONE = "none" + #: A sequence: ``%s`` placeholders, bound by position. + POSITIONAL = "positional" + #: A mapping: ``%(name)s`` placeholders, bound by name. + NAMED = "named" + + @classmethod + def of(cls, params: Any, dialect: Type[EncryptionDriverDialect]) -> ParamStyle: + """The style the driver for ``dialect`` applies to ``params``, the + second argument of ``execute``.""" + if not dialect.binds_parameters(params): + return cls.NONE + return cls.NAMED if isinstance(params, Mapping) else cls.POSITIONAL + + +@dataclass(frozen=True, slots=True) +class ColumnRef: + """A column a statement names, with names folded the way the engine folds + them (see :meth:`EncryptionDriverDialect.fold_identifier`).""" + + column: str + #: The table, without any schema; ``None`` when the statement does not say + #: which of its tables the column belongs to. + table: Optional[str] = None + + def __str__(self) -> str: + return self.column if self.table is None else f"{self.table}.{self.column}" + + +@dataclass(frozen=True, slots=True) +class Placeholder: + """One bind parameter, in the order the driver binds them.""" + + #: Position among the statement's placeholders, from 0. + ordinal: int + #: What the driver binds here: the index into the parameter sequence, or + #: the key in the parameter mapping. A key may be used more than once. + key: Union[int, str] + #: Span of the placeholder in the original SQL. + start: int + end: int + #: Overlaps a quoted literal (including a dollar-quoted one), a quoted + #: identifier, or a comment. + hidden: bool = False + #: The column a ``/*@encrypt:...*/`` annotation directly before it names, + #: folded like any identifier. Its qualifier is not resolved yet: see + #: :attr:`StatementAnalysis.annotations` for what the analyzer makes of it. + annotation: Optional[ColumnRef] = None + #: A MySQL charset introducer written directly before it (``_binary`` in + #: ``_binary %s``, as Django renders binary values), lower-cased. Anything + #: in between, an annotation included, hides the introducer. + introducer: Optional[str] = None + + +@dataclass(frozen=True) +class TokenizedSql: + """What :func:`tokenize` found.""" + + style: ParamStyle + placeholders: Tuple[Placeholder, ...] + #: The SQL with every placeholder replaced by ``:_kms_p``, the + #: driver's ``%`` escapes resolved, and on MySQL ``REPLACE`` read as + #: ``INSERT``, statement modifiers such as ``LOW_PRIORITY`` dropped, and + #: charset introducers before a placeholder removed (see + #: :attr:`Placeholder.introducer`). Only for a structural parser; never + #: sent to the database. + normalized: str + #: The first word of each statement, upper-cased. + leading_words: Tuple[str, ...] + #: For each statement, in the order of :attr:`leading_words`, whether it + #: is a ``COPY`` whose next token is ``(``, as in ``COPY ( query ) TO``. + copy_queries: Tuple[bool, ...] + #: Which of the keywords that matter for spotting a write (``INSERT``, + #: ``UPDATE``, ``REPLACE``, ``MERGE``, ``UPSERT``, ``COPY``, ``FROM``, + #: ``EXECUTE``, ``LOAD``) appear outside literals, comments and + #: placeholders, or inside a MySQL executable comment. + keywords: FrozenSet[str] + #: A quoted literal, quoted identifier, or comment runs to the end of the + #: text. + unterminated: bool = False + #: MySQL only: a ``/*! ... */`` (or MariaDB ``/*M! ... */``) comment, whose + #: body the server runs. + executable_comment: bool = False + #: Why the driver will reject the placeholders (an unknown ``%`` sequence, + #: positional and named placeholders mixed, or a style the parameters + #: don't have); ``None`` when it won't. + driver_error: Optional[str] = None + #: ``/*@encrypt:...*/`` comments that annotate no placeholder or can't be + #: read, as written. A caller may want to warn about them. + stray_annotations: Tuple[str, ...] = () + #: Each name that could be a table, as written and without duplicates, + #: with whether it was quoted: the words outside literals, comments and + #: placeholders, the words inside MySQL executable comments, and quoted + #: identifiers without their quotes. Only for a statement the analysis + #: can't read. + names: Tuple[Tuple[str, bool], ...] = () + + @property + def has_hidden_placeholders(self) -> bool: + return any(p.hidden for p in self.placeholders) + + +_KEYWORDS = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT", "COPY", "FROM", "EXECUTE", "LOAD"}) + +_QUOTED_KINDS = frozenset({"estring", "string", "dqstring", "ident"}) + +# A block comment that is an annotation: /*@encrypt:*/, with no space +# after the opening delimiter. is dot-separated parts, table.column or a +# bare column; leading parts (a schema) are ignored. A part is word characters, +# or a name quoted with the dialect's identifier quote. Every [\w.]+ reference +# that ends in a column is accepted, empty parts included: ".c" is the bare +# column c and "t..c" is t.c. A reference that ends in "." names no column and +# is reported as stray. +_ANNOTATION = re.compile(r"/\*@encrypt:(?P.*?)\*/\Z", re.DOTALL) +_REF_PARTS = { + '"': re.compile(r'(?P\w+)|"(?P(?:[^"]|"")+)"'), + "`": re.compile(r"(?P\w+)|`(?P(?:[^`]|``)+)`"), +} + +# A charset introducer (_binary, _utf8mb4, ...) and the space after it, +# directly before a placeholder. +_INTRODUCER = re.compile(r"(?[A-Za-z0-9]+)\s*\Z") +_WORD = re.compile(r"[^\W\d][\w$]*") +_COMMENT_DELIMITER = re.compile(r"/\*|\*/") + +# The drivers' own placeholder patterns. +# No DOTALL, as in psycopg. +_PSYCOPG_PLACEHOLDER = re.compile(r"%(?:\(([^)]+)\).|.)") +_MYSQL_POSITIONAL = re.compile(r"%s") +_MYSQL_NAMED = re.compile(r"%\((?P[^)]+)\)(?P[diouxXeEfFgGcrs%])") + +_Edit = Tuple[int, int, str] +_FAR = 1 << 62 # past any string offset + + +@dataclass +class _Lexed: + # Literals, quoted identifiers, comments; sorted. + hidden_spans: List[Tuple[int, int]] + block_comments: List[Tuple[int, int]] + # (UPPER word, start, end); "" stands for any other significant token, so + # that two words with something between them are not taken as adjacent. + words: List[Tuple[str, int, int]] + # Offsets of the ";" between statements. + separators: List[int] + unterminated: bool = False + executable_comment: bool = False + # Words inside MySQL executable comments, which the server runs, as written. + executable_words: List[str] = field(default_factory=list) + # Quoted identifiers without their quotes, doubled quotes undone. + quoted_names: List[str] = field(default_factory=list) + + +def tokenize(sql: str, dialect: Type[EncryptionDriverDialect], style: ParamStyle) -> TokenizedSql: + """Find the placeholders in ``sql`` as the driver for ``dialect`` does when + given parameters of ``style``. + + :raises TypeError: if ``sql`` is not a ``str``. + """ + if not isinstance(sql, str): + raise TypeError(Messages.get_formatted("SqlTokenizer.SqlNotStr", type(sql).__name__)) + lexed = _lex(sql, dialect) + + edits: List[_Edit] = [] + if dialect.strict_placeholders: + placeholders, driver_error = _psycopg_placeholders(sql, style, lexed, edits) + else: + placeholders, driver_error = _mysql_placeholders(sql, style, lexed, edits) + if dialect.charset_introducers: + placeholders = _attach_introducers(sql, dialect.charset_introducers, lexed, placeholders, edits) + + stray: List[str] = [] + if "@encrypt:" in sql: + placeholders = _attach_annotations(sql, dialect, lexed, placeholders, stray) + + # A word inside a placeholder (the s of %s, a %(name)s key) is not SQL. + words = _outside(lexed.words, placeholders) + bounds = _statement_bounds(words, lexed.separators) + edits.extend(_modifier_rewrites(words, bounds, dialect.statement_modifiers)) + edits.extend(_copy_option_rewrites(sql, words, bounds)) + + keywords = {w for w, _, _ in words if w in _KEYWORDS} + keywords.update(w.upper() for w in lexed.executable_words if w.upper() in _KEYWORDS) + names = dict.fromkeys((sql[start:end], False) for word, start, end in words if word) + names.update(dict.fromkeys((word, False) for word in lexed.executable_words)) + names.update(dict.fromkeys((name, True) for name in lexed.quoted_names)) + return TokenizedSql( + style=style, + placeholders=tuple(placeholders), + normalized=_apply(sql, edits), + leading_words=_leading_words(words, bounds), + copy_queries=tuple(_copies_query(sql, words[begin:end]) for begin, end in bounds), + keywords=frozenset(keywords), + unterminated=lexed.unterminated, + executable_comment=lexed.executable_comment, + driver_error=driver_error, + stray_annotations=tuple(stray), + names=tuple(names), + ) + + +def normalized_ordinal(name: Optional[str]) -> Optional[int]: + """The ordinal of a placeholder in the normalized SQL, from the name a + parser reports for it (``_kms_p3`` -> 3); ``None`` for any other name.""" + if not name or not name.startswith(NORMALIZED_PLACEHOLDER_PREFIX): + return None + digits = name[len(NORMALIZED_PLACEHOLDER_PREFIX):] + return int(digits) if digits.isascii() and digits.isdigit() else None + + +# The error texts never quote the SQL: a rejected "%(...)x" sequence can sit +# inside a literal holding a value. + +def _psycopg_placeholders(sql: str, style: ParamStyle, lexed: _Lexed, + edits: List[_Edit]) -> Tuple[List[Placeholder], Optional[str]]: + if style is ParamStyle.NONE: + return [], None + found: List[Placeholder] = [] + error: Optional[str] = None + named = positional = False + for m in _PSYCOPG_PLACEHOLDER.finditer(sql): + text = m.group(0) + if text == "%%": + edits.append((m.start(), m.end(), "%")) + continue + if text == "%(" or text[-1] not in "sbt": + error = error or f"psycopg rejects the % sequence at offset {m.start()}" + continue + name = m.group(1) + named, positional = named or name is not None, positional or name is None + ordinal = len(found) + found.append(_placeholder(ordinal, ordinal if name is None else name, m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + if named and positional: + error = error or "positional and named placeholders are mixed" + elif (named or positional) and named != (style is ParamStyle.NAMED): + error = error or f"the placeholders don't match {style.value} parameters" + return found, error + + +def _mysql_placeholders(sql: str, style: ParamStyle, lexed: _Lexed, + edits: List[_Edit]) -> Tuple[List[Placeholder], Optional[str]]: + found: List[Placeholder] = [] + error: Optional[str] = None + if style is ParamStyle.POSITIONAL: + for m in _MYSQL_POSITIONAL.finditer(sql): + ordinal = len(found) + found.append(_placeholder(ordinal, ordinal, m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + elif style is ParamStyle.NAMED: + for m in _MYSQL_NAMED.finditer(sql): + conv = m.group("conv") + if conv == "%": + edits.append((m.start(), m.end(), "%")) + elif conv != "s": + error = error or f"MySQL Connector/Python rejects the %(...) conversion at offset {m.start()}" + else: + ordinal = len(found) + found.append(_placeholder(ordinal, m.group("key"), m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + return found, error + + +def _placeholder(ordinal: int, key: Union[int, str], m: re.Match, lexed: _Lexed) -> Placeholder: + return Placeholder(ordinal=ordinal, key=key, start=m.start(), end=m.end(), + hidden=_overlaps(lexed.hidden_spans, m.start(), m.end())) + + +def _placeholder_edit(ordinal: int, m: re.Match) -> _Edit: + # Padded so the placeholder cannot fuse with a neighboring token. + return m.start(), m.end(), f" :{NORMALIZED_PLACEHOLDER_PREFIX}{ordinal} " + + +def _overlaps(spans: List[Tuple[int, int]], start: int, end: int) -> bool: + i = bisect_right(spans, (start, _FAR)) - 1 + if i >= 0 and spans[i][1] > start: + return True + return i + 1 < len(spans) and spans[i + 1][0] < end + + +def _attach_introducers(sql: str, charsets: FrozenSet[str], lexed: _Lexed, placeholders: List[Placeholder], + edits: List[_Edit]) -> List[Placeholder]: + # "_binary %s" binds the value as a binary string, which is what a + # ciphertext is. The parser misreads the pair (as an alias, or not at all), + # so the introducer is recorded on the placeholder and removed from the + # normalized copy. Only whitespace may separate the two. + if "_" not in sql: + return placeholders + result = list(placeholders) + for i, p in enumerate(placeholders): + if p.hidden: + continue + m = _INTRODUCER.search(sql, max(0, p.start - 64), p.start) + if m is None or m.group("charset").lower() not in charsets \ + or _overlaps(lexed.hidden_spans, m.start(), m.end()): + continue + result[i] = replace(p, introducer=f"_{m.group('charset').lower()}") + edits.append((m.start(), m.end(), " ")) + return result + + +def _attach_annotations(sql: str, dialect: Type[EncryptionDriverDialect], lexed: _Lexed, + placeholders: List[Placeholder], stray: List[str]) -> List[Placeholder]: + by_start = {p.start: i for i, p in enumerate(placeholders)} + result = list(placeholders) + for start, end in lexed.block_comments: + if not sql.startswith("/*@encrypt:", start): + continue + m = _ANNOTATION.match(sql, start, end) + ref = None if m is None else _annotation_ref(m.group("ref"), dialect) + nxt = end + while nxt < len(sql) and sql[nxt].isspace(): + nxt += 1 + index = by_start.get(nxt) + if ref is None or index is None or result[index].hidden: + stray.append(sql[start:end]) + else: + result[index] = replace(result[index], annotation=ref) + return result + + +def _annotation_ref(text: str, dialect: Type[EncryptionDriverDialect]) -> Optional[ColumnRef]: + quote = dialect.identifier_quote + part_re = _REF_PARTS[quote] + parts: List[str] = [] + pos = 0 + while pos <= len(text): + if text.startswith(".", pos) or pos == len(text): + # An empty part, as in ".c" or "t..c". + parts.append("") + else: + m = part_re.match(text, pos) + if m is None: + return None + if m.group("word") is not None: + parts.append(dialect.fold_identifier(m.group("word"), quoted=False)) + else: + parts.append(dialect.fold_identifier(m.group("quoted").replace(quote * 2, quote), quoted=True)) + pos = m.end() + if pos < len(text) and text[pos] != ".": + return None + pos += 1 + if not parts[-1]: + return None # no column ("t.") + # The metadata has no schema: the table is the nearest named part before + # the column, and anything before that is ignored. + for part in reversed(parts[:-1]): + if part: + return ColumnRef(column=parts[-1], table=part) + return ColumnRef(column=parts[-1], table=None) + + +def _lex(sql: str, dialect: Type[EncryptionDriverDialect]) -> _Lexed: + token_re = dialect.sql_token_pattern + if token_re is None: + raise UnsupportedOperationError(Messages.get_formatted("SqlTokenizer.NoTokenPattern", dialect.__name__)) + lexed = _Lexed([], [], [], []) + pos, n = 0, len(sql) + while pos < n: + m = token_re.match(sql, pos) + # The "other" group matches any character. + if m is None: + raise EncryptionPluginError(Messages.get("SqlTokenizer.NoToken")) + kind, end = m.lastgroup, m.end() + if kind == "block_comment": + if dialect.nested_block_comments: + end = _nested_comment_end(sql, pos) + elif not m.group("block_comment_end"): + lexed.unterminated = True + if end < 0: + end, lexed.unterminated = n, True + if dialect.executable_comments and (sql.startswith("/*!", pos) or sql.startswith("/*M!", pos)): + lexed.executable_comment = True + lexed.executable_words.extend(_WORD.findall(sql, pos, end)) + lexed.block_comments.append((pos, end)) + lexed.hidden_spans.append((pos, end)) + elif kind == "dollar": + close = sql.find(m.group(0), end) + if close < 0: + end, lexed.unterminated = n, True + else: + end = close + len(m.group(0)) + lexed.hidden_spans.append((pos, end)) + elif kind in _QUOTED_KINDS: + if not m.group(f"{kind}_end"): + lexed.unterminated = True + elif kind == "ident": + quote = sql[pos] + lexed.quoted_names.append(sql[pos + 1:end - 1].replace(quote * 2, quote)) + lexed.hidden_spans.append((pos, end)) + elif kind == "line_comment": + lexed.hidden_spans.append((pos, end)) + elif kind == "word": + lexed.words.append((m.group(0).upper(), pos, end)) + elif kind == "semicolon": + lexed.separators.append(pos) + elif kind != "space": + lexed.words.append(("", pos, end)) + pos = end + return lexed + + +def _nested_comment_end(sql: str, start: int) -> int: + # PostgreSQL block comments nest. Returns -1 when unterminated. One pass + # over the delimiters, so deep nesting stays linear. + depth = 0 + for m in _COMMENT_DELIMITER.finditer(sql, start): + depth += 1 if m.group(0) == "/*" else -1 + if depth == 0: + return m.end() + return -1 + + +def _outside(words: List[Tuple[str, int, int]], placeholders: List[Placeholder]) -> List[Tuple[str, int, int]]: + if not placeholders: + return words + spans = [(p.start, p.end) for p in placeholders] + return [w for w in words if not _overlaps(spans, w[1], w[2])] + + +def _statement_bounds(words: List[Tuple[str, int, int]], separators: List[int]) -> List[Tuple[int, int]]: + """(begin, end) indexes into ``words`` of each non-empty statement.""" + bounds: List[Tuple[int, int]] = [] + begin = 0 + for separator in separators + [_FAR]: + end = begin + while end < len(words) and words[end][1] < separator: + end += 1 + if end > begin: + bounds.append((begin, end)) + begin = end + return bounds + + +def _leading_words(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> Tuple[str, ...]: + # A statement's first word, skipping leading punctuation such as "("; "" + # when it has no word at all. + return tuple(_first_word(words[begin:end]) for begin, end in bounds) + + +def _first_word(words: List[Tuple[str, int, int]]) -> str: + for word, _, _ in words: + if word: + return word + return "" + + +def _copies_query(sql: str, words: List[Tuple[str, int, int]]) -> bool: + for i, (word, _, _) in enumerate(words): + if word: + return word == "COPY" and i + 1 < len(words) and sql[words[i + 1][1]] == "(" + return False + + +def _copy_option_rewrites(sql: str, words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> List[_Edit]: + # PostgreSQL takes COPY's option list with or without WITH; the parser + # reads only the WITH form. + edits: List[_Edit] = [] + for begin, end in bounds: + if _first_word(words[begin:end]) != "COPY": + continue + for (word, _, _), (_, start, _) in zip(words[begin:end - 1], words[begin + 1:end], strict=False): + if word in ("STDIN", "STDOUT") and sql[start] == "(": + edits.append((start, start, "WITH ")) + return edits + + +def _modifier_rewrites(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]], + statement_modifiers: Mapping[str, FrozenSet[str]]) -> List[_Edit]: + # The statement modifiers are dropped from the normalized copy, which the + # structural parser reads. + leading = {begin for begin, _ in bounds} + edits: List[_Edit] = [] + for i, (word, start, end) in enumerate(words): + modifiers = statement_modifiers.get(word) + if modifiers is None: + continue + if word == "REPLACE": + # Only the statement keyword, not the REPLACE() string function. + if i not in leading: + continue + edits.append((start, end, "INSERT")) + j = i + 1 + while j < len(words) and words[j][0] in modifiers: + edits.append((words[j][1], words[j][2], " ")) + j += 1 + return edits + + +def _apply(sql: str, edits: List[_Edit]) -> str: + if not edits: + return sql + out: List[str] = [] + pos = 0 + for start, end, text in sorted(edits): + out.append(sql[pos:start]) + out.append(text) + pos = end + out.append(sql[pos:]) + return "".join(out) diff --git a/aws_advanced_python_wrapper/encryption/type_marker.py b/aws_advanced_python_wrapper/encryption/type_marker.py new file mode 100644 index 000000000..34d080914 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/type_marker.py @@ -0,0 +1,115 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from datetime import date, datetime, time +from decimal import Decimal +from typing import Any, Dict, Optional + +from aws_advanced_python_wrapper.utils.messages import Messages + + +class TypeMarker: + """The single byte written ahead of the ciphertext recording how the + plaintext was serialized, so a decrypted payload can be turned back into a + Python value. + + The marker numbers are stored in every payload, so they can't change + without breaking values already written. Python has a single unbounded + ``int`` type, so integers are always written as :data:`LONG` (8 bytes, + big-endian); :data:`INTEGER` (4 bytes) is still understood on read. + """ + + STRING = 1 + INTEGER = 2 + LONG = 3 + DOUBLE = 4 + FLOAT = 5 + BOOLEAN = 6 + BIG_DECIMAL = 7 + DATE = 8 + TIME = 9 + TIMESTAMP = 10 + LOCAL_DATE = 11 + LOCAL_TIME = 12 + LOCAL_DATE_TIME = 13 + BYTE_ARRAY = 14 + GENERIC = 99 + + _NAMES: Dict[int, str] = { + STRING: "STRING", + INTEGER: "INTEGER", + LONG: "LONG", + DOUBLE: "DOUBLE", + FLOAT: "FLOAT", + BOOLEAN: "BOOLEAN", + BIG_DECIMAL: "BIG_DECIMAL", + DATE: "DATE", + TIME: "TIME", + TIMESTAMP: "TIMESTAMP", + LOCAL_DATE: "LOCAL_DATE", + LOCAL_TIME: "LOCAL_TIME", + LOCAL_DATE_TIME: "LOCAL_DATE_TIME", + BYTE_ARRAY: "BYTE_ARRAY", + GENERIC: "GENERIC", + } + + @classmethod + def from_value(cls, value: int) -> int: + """Validate a marker byte read from a payload and return it unchanged.""" + if value not in cls._NAMES: + raise ValueError(Messages.get_formatted("TypeMarker.UnknownMarker", value)) + return value + + @classmethod + def from_object(cls, value: Any) -> int: + """Pick the marker used to serialize a Python value. + + Unknown types fall back to :data:`GENERIC`, serialized through ``str``. + Order matters: ``bool`` is a subclass of ``int`` and ``datetime`` a + subclass of ``date``, so the narrower types are checked first. + + A naive ``datetime`` is a local date-time (:data:`LOCAL_DATE_TIME`, + ISO text). A timezone-aware one names an instant, so it is written as + :data:`TIMESTAMP` (epoch milliseconds), which keeps the instant and + reads back as an aware UTC ``datetime``. + """ + if isinstance(value, (bytes, bytearray, memoryview)): + return cls.BYTE_ARRAY + if isinstance(value, str): + return cls.STRING + if isinstance(value, bool): + return cls.BOOLEAN + if isinstance(value, int): + return cls.LONG + if isinstance(value, float): + return cls.DOUBLE + if isinstance(value, Decimal): + return cls.BIG_DECIMAL + if isinstance(value, datetime): + return cls.LOCAL_DATE_TIME if value.utcoffset() is None else cls.TIMESTAMP + if isinstance(value, date): + return cls.LOCAL_DATE + if isinstance(value, time): + return cls.LOCAL_TIME + return cls.GENERIC + + @classmethod + def name_for(cls, marker: int) -> Optional[str]: + return cls._NAMES.get(marker) + + @classmethod + def is_known(cls, marker: int) -> bool: + return marker in cls._NAMES diff --git a/aws_advanced_python_wrapper/encryption_driver_dialect.py b/aws_advanced_python_wrapper/encryption_driver_dialect.py new file mode 100644 index 000000000..1123ba9a2 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption_driver_dialect.py @@ -0,0 +1,204 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import (TYPE_CHECKING, Any, ClassVar, FrozenSet, Mapping, Optional, + Sequence, Tuple) + +if TYPE_CHECKING: + from re import Pattern + + from aws_advanced_python_wrapper.pep249 import Connection, Cursor + +from abc import ABC, abstractmethod + + +class EncryptionDriverDialect(ABC): + """ + The members the KMS Encryption Plugin needs from a driver dialect, mixed into the driver dialects that support it. + The KMS Encryption Plugin and KeyManagementUtility refuse a driver dialect that does not include it. + """ + + # The equality operator the encryption plugin writes in its own statements. + equals_operator: ClassVar[str] = "=" + # The leading words of the statements the encryption plugin parses; it reports any other statement without parsing it. + analyzed_statements: ClassVar[FrozenSet[str]] = frozenset() + # The sqlglot dialect the encryption plugin parses statements with. + sqlglot_dialect: ClassVar[str] = "" + # Whether the engine accepts a qualified column (t.c) in an INSERT column list, which the parser rejects. + qualified_insert_columns: ClassVar[bool] = False + # The name upsert_clause gives the incoming row (EXCLUDED.c), or None when the clause names no row. + upsert_row_alias: ClassVar[Optional[str]] = None + # Whether upsert_clause reads the incoming row through the VALUES(c) function. + upsert_values_function: ClassVar[bool] = False + # The character that quotes an identifier. + identifier_quote: ClassVar[str] = '"' + # The greater-than operator the key management utility pages a table with. + greater_than_operator: ClassVar[str] = ">" + # A query for the type of a table's column, with the table and the column as parameters, which returns its type + # name and whether that type is built in; None when the engine needs no check. + key_column_type_sql: ClassVar[Optional[str]] = None + # The catalog queries of KeyManagementUtility.validate_schema, each with the schema and the table in lower case as + # parameters: a row when the table exists; its column names (column_name); its primary key and unique constraint + # columns (constraint_name, constraint_type as PRIMARY KEY or UNIQUE, column_name); and its foreign key columns + # into a table of the same schema (column_name, referenced_table, referenced_column). + schema_table_sql: ClassVar[str] + schema_columns_sql: ClassVar[str] + schema_key_constraints_sql: ClassVar[str] + schema_foreign_keys_sql: ClassVar[str] + # The modifiers that can follow a statement keyword and change how the statement runs, not what it writes. + statement_modifiers: ClassVar[Mapping[str, FrozenSet[str]]] = {} + # The character sets whose introducer (_binary) can come directly before a placeholder. + charset_introducers: ClassVar[FrozenSet[str]] = frozenset() + # The SQL token pattern, tried in order at each token boundary, or None when the encryption plugin can't lex SQL. + # Its groups: line_comment, block_comment (with block_comment_end when comments don't nest), string, estring, + # dqstring and ident (each with _end, empty when the text ends first), dollar, param, word, number, + # semicolon, space and other, which matches any character. + sql_token_pattern: ClassVar[Optional[Pattern[str]]] = None + # Whether block comments nest. + nested_block_comments: ClassVar[bool] = False + # Whether the server runs the body of a /*! ... */ comment. + executable_comments: ClassVar[bool] = False + # Whether the driver reads every % as a placeholder or %%, and rejects the rest, when it gets parameters. + strict_placeholders: ClassVar[bool] = False + _ASCII: ClassVar[bytes] = bytes(range(0x80)) + + @classmethod + def binds_parameters(cls, params: Any) -> bool: + """ + Returns whether the driver substitutes the placeholders of a statement when ``execute`` gets ``params``. + + :param params: the second argument of ``execute``. + :return: True when the driver substitutes the placeholders. + """ + return params is not None + + @classmethod + def fold_identifier(cls, name: str, quoted: bool) -> str: + """ + Returns the name the server resolves an identifier written in SQL to. + + :param name: the identifier without its quotes, with doubled quotes undone. + :param quoted: whether the identifier was quoted. + :return: the name the server resolves the identifier to. + """ + return name + + @classmethod + def metadata_key(cls, name: str) -> str: + """ + Returns the form in which a table or column name is compared when the encryption plugin looks it up in + ``encryption_metadata``. + Names with the same key share encryption metadata. + + :param name: the table or column name. + :return: the key the name is compared by. + """ + return name + + @classmethod + def quote_identifier(cls, name: str) -> str: + """ + Returns ``name`` quoted with :attr:`identifier_quote`, a quote character in it doubled. + + :param name: the identifier. + :return: the quoted identifier. + """ + quote = cls.identifier_quote + return quote + name.replace(quote, quote * 2) + quote + + @abstractmethod + def upsert_clause( + self, conflict_columns: Sequence[str], update_columns: Sequence[str], extra_assignments: Sequence[str] = ()) -> str: + """ + Returns the trailing upsert clause for an ``INSERT``. + On a conflict over ``conflict_columns``, the clause overwrites ``update_columns`` from the incoming row and + applies each of ``extra_assignments``. + + :param conflict_columns: the columns of the unique key the clause matches on. + :param update_columns: the columns the clause overwrites from the incoming row. + :param extra_assignments: literal assignments the clause also applies. + :return: the upsert clause. + """ + ... + + @abstractmethod + def insert_returning_id(self, conn: Connection, sql: str, params: Sequence[Any]) -> int: + """ + Runs an ``INSERT`` written without ``RETURNING`` and returns the generated ``id``. + + :param conn: the connection to run the statement on. + :param sql: the ``INSERT`` statement. + :param params: the statement's parameters. + :return: the generated ``id``. + """ + ... + + def analyzable_sql(self, sql: Any, cursor: Cursor) -> Tuple[Optional[str], Optional[str]]: + """ + Returns the text the encryption plugin analyzes for ``sql``, and the codec of the connection's client encoding + when ``sql`` is ``bytes``. + + :param sql: the SQL the application passed to the cursor. + :param cursor: the driver cursor the SQL runs on. + :return: the text to analyze, or None when the SQL runs unanalyzed, and the codec ``bytes`` SQL was decoded + with, or None. + """ + if isinstance(sql, str): + return sql, None + return None, None + + def binary_placeholder_prefix(self, cursor: Cursor) -> Optional[str]: + """ + Returns the text the encryption plugin puts before each placeholder whose value it encrypts, so the server + reads the payload as binary data. + + :param cursor: the driver cursor the statement runs on. + :return: the prefix, or None when the server already reads a bound ``bytes`` value as binary data. + """ + return None + + def unsupported_row_factory(self, cursor: Cursor) -> Optional[Any]: + """ + Returns the cursor's row factory when the encryption plugin can't decode the rows it builds. + + :param cursor: the driver cursor the rows come from. + :return: the unsupported row factory, or None. + """ + return None + + @staticmethod + def _decode_sql(sql: bytes, codec: Optional[str]) -> Optional[str]: + """ + Returns the text the encryption plugin analyzes in ``bytes`` SQL. + + :param sql: the SQL the application passed to the cursor. + :param codec: the codec of the connection's client encoding, or None when the connection is unknown. + :return: the text, or None when ``codec`` is None, reads an ASCII byte as another character, can't decode + ``sql``, or doesn't encode the text back to ``sql``. + """ + if codec is None: + return None + try: + # A codec that reads an ASCII byte as another character (shift_jis_2004 reads 0x5C and 0x7E as a yen sign + # and an overline), or text that doesn't encode back to the same bytes, would show the analysis another + # statement. + if EncryptionDriverDialect._ASCII.decode(codec) != EncryptionDriverDialect._ASCII.decode("ascii"): + return None + text = sql.decode(codec) + return text if text.encode(codec) == sql else None + # Their .object is the whole statement: keep nothing of it. + except (UnicodeDecodeError, UnicodeEncodeError): + return None diff --git a/aws_advanced_python_wrapper/errors.py b/aws_advanced_python_wrapper/errors.py index 3f31e961a..89fe7dcc5 100644 --- a/aws_advanced_python_wrapper/errors.py +++ b/aws_advanced_python_wrapper/errors.py @@ -14,7 +14,8 @@ from typing import Optional -from .pep249 import Error, InterfaceError, NotSupportedError, OperationalError +from .pep249 import (Error, IntegrityError, InterfaceError, NotSupportedError, + OperationalError) class AwsWrapperError(Error): @@ -98,3 +99,119 @@ class ReadWriteSplittingError(AwsWrapperError, InterfaceError): class AwsConnectError(AwsWrapperError, OperationalError): __module__ = "aws_advanced_python_wrapper" + + +# -- KMS encryption plugin errors -- +# +# Callers branch on the exception type. For example, the read path's lenient +# ``encryption_return_unverified_data`` mode will catch ``IntegrityCheckError`` +# and let every other failure propagate. +# +# Each class derives from ``AwsWrapperError`` for the wrapper's own error +# handling and mixes in a PEP 249 type, which is what SQLAlchemy uses to +# classify errors at the DB-API boundary. SQLAlchemy picks the first PEP 249 +# class in the MRO, so a class whose mix-in should win lists it first. Django +# does not translate these errors: its backends look error classes up on the +# native driver module, which these do not derive from, so they reach Django +# code as raised. The optional ``algorithm`` and ``data_type`` attributes help +# with diagnostics. +# +# The class hierarchy is specific to this wrapper. + +class EncryptionPluginError(AwsWrapperError): + __module__ = "aws_advanced_python_wrapper" + + +class EncryptionError(EncryptionPluginError, OperationalError): + __module__ = "aws_advanced_python_wrapper" + + def __init__(self, message: str = "", *, algorithm: Optional[str] = None, + data_type: Optional[str] = None): + super().__init__(message) + self.algorithm = algorithm + self.data_type = data_type + + +class IntegrityCheckError(IntegrityError, EncryptionError): + """The payload is not a valid encrypted value: too short to hold the + framing, or its HMAC tag does not match. + + ``IntegrityError`` is listed first so SQLAlchemy classifies it as an + integrity error rather than through ``EncryptionError``'s + ``OperationalError``. Lenient mode (``encryption_return_unverified_data``) + will swallow this read-side failure and no other. A value that verifies + but will not decrypt raises ``DecryptionError``, which lenient mode always + lets through. + """ + __module__ = "aws_advanced_python_wrapper" + + +class DecryptionError(EncryptionError): + """A verified payload could not be decrypted, usually because the data key + is wrong (the GCM authentication tag does not match) or the marker is bad. + """ + __module__ = "aws_advanced_python_wrapper" + + +class EncryptionFailedError(EncryptionError): + """A value could not be encrypted or serialized.""" + __module__ = "aws_advanced_python_wrapper" + + +class InvalidKeyError(EncryptionError): + """A data key or HMAC key is missing or the wrong length.""" + __module__ = "aws_advanced_python_wrapper" + + +class InvalidAlgorithmError(EncryptionError): + """An unsupported encryption algorithm was requested.""" + __module__ = "aws_advanced_python_wrapper" + + +class TypeConversionError(EncryptionError): + """A decrypted value could not be coerced to its declared or requested type.""" + __module__ = "aws_advanced_python_wrapper" + + +class EncryptionConfigError(EncryptionPluginError, InterfaceError): + """The ``encryption_*`` connection properties are missing or invalid.""" + __module__ = "aws_advanced_python_wrapper" + + +class KeyManagementError(EncryptionPluginError, OperationalError): + """A data key or master key could not be created, read, decrypted, or + stored. + + ``operation`` names the failing step (for example ``"DECRYPT_DATA_KEY"``) + for diagnostics. It is not part of any cross-wrapper contract. + """ + __module__ = "aws_advanced_python_wrapper" + + def __init__(self, message: str = "", *, operation: Optional[str] = None): + super().__init__(message) + self.operation = operation + + +class UnauthorizedMasterKeyError(KeyManagementError): + """The master key named by a ``key_storage`` row is not listed in + ``encryption_allowed_master_key_arns``. Raised before KMS is called. + """ + __module__ = "aws_advanced_python_wrapper" + + +class InvalidKeyMetadataError(KeyManagementError): + """A ``key_storage`` row is unusable: it names no master key, or its + encrypted data key, HMAC key, or key spec is missing or malformed. + """ + __module__ = "aws_advanced_python_wrapper" + + +class MetadataError(EncryptionPluginError, OperationalError): + """The ``encryption_metadata`` / ``key_storage`` tables could not be read.""" + __module__ = "aws_advanced_python_wrapper" + + def __init__(self, message: str = "", *, table_name: Optional[str] = None, + column_name: Optional[str] = None): + super().__init__(message) + self.table_name = table_name + self.column_name = column_name diff --git a/aws_advanced_python_wrapper/mysql_driver_dialect.py b/aws_advanced_python_wrapper/mysql_driver_dialect.py index 4b6f28215..f36ccc89b 100644 --- a/aws_advanced_python_wrapper/mysql_driver_dialect.py +++ b/aws_advanced_python_wrapper/mysql_driver_dialect.py @@ -14,17 +14,24 @@ from __future__ import annotations +import re import socket -from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, Set +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, FrozenSet, Mapping, + Optional, Sequence, Set, Tuple) if TYPE_CHECKING: + from re import Pattern + from aws_advanced_python_wrapper.hostinfo import HostInfo - from aws_advanced_python_wrapper.pep249 import Connection + from aws_advanced_python_wrapper.pep249 import Connection, Cursor +from contextlib import closing from inspect import signature from aws_advanced_python_wrapper.driver_dialect import DriverDialect from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes +from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect from aws_advanced_python_wrapper.errors import UnsupportedOperationError from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.utils.messages import Messages @@ -36,10 +43,12 @@ from mysql.connector import MySQLConnection # noqa: E402 from mysql.connector.cursor import MySQLCursor # noqa: E402 +from mysql.connector.cursor import MySQLCursorPrepared # noqa: E402 try: from mysql.connector import CMySQLConnection # noqa: E402 from mysql.connector.cursor_cext import CMySQLCursor # noqa: E402 + from mysql.connector.cursor_cext import CMySQLCursorPrepared # noqa: E402 CMYSQL_ENABLED = True @@ -48,7 +57,7 @@ pass -class MySQLDriverDialect(DriverDialect): +class MySQLDriverDialect(DriverDialect, EncryptionDriverDialect): _driver_name = "MySQL Connector Python" TARGET_DRIVER_CODE = "MySQL" AUTH_PLUGIN_PARAM = "auth_plugin" @@ -57,6 +66,63 @@ class MySQLDriverDialect(DriverDialect): _executor_name: ClassVar[str] = "MySQLDriverDialectExecutor" + # equals_operator keeps the base's "=": MySQL has no user-defined operators. + # fold_identifier keeps the base's names as written. + analyzed_statements: ClassVar[FrozenSet[str]] = frozenset({"SELECT", "WITH", "INSERT", "REPLACE", "UPDATE", "DELETE", "VALUES"}) + sqlglot_dialect: ClassVar[str] = "mysql" + qualified_insert_columns: ClassVar[bool] = True + upsert_values_function: ClassVar[bool] = True + identifier_quote: ClassVar[str] = "`" + schema_table_sql: ClassVar[str] = ( + "SELECT 1 AS found FROM information_schema.tables WHERE LOWER(table_schema) = %s AND LOWER(table_name) = %s") + schema_columns_sql: ClassVar[str] = ( + "SELECT column_name AS column_name FROM information_schema.columns " + "WHERE LOWER(table_schema) = %s AND LOWER(table_name) = %s") + schema_key_constraints_sql: ClassVar[str] = ( + "SELECT tc.constraint_name AS constraint_name, tc.constraint_type AS constraint_type, " + "kcu.column_name AS column_name " + "FROM information_schema.table_constraints tc " + "JOIN information_schema.key_column_usage kcu ON kcu.constraint_schema = tc.constraint_schema " + "AND kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema " + "AND kcu.table_name = tc.table_name " + "WHERE tc.constraint_type IN ('PRIMARY KEY', 'UNIQUE') " + "AND LOWER(tc.table_schema) = %s AND LOWER(tc.table_name) = %s " + "ORDER BY tc.constraint_name, kcu.ordinal_position") + # key_column_usage names the referenced table and column itself, so no join on constraint names is needed: every + # primary key is named PRIMARY. + schema_foreign_keys_sql: ClassVar[str] = ( + "SELECT column_name AS column_name, referenced_table_name AS referenced_table, " + "referenced_column_name AS referenced_column FROM information_schema.key_column_usage " + "WHERE LOWER(table_schema) = %s AND LOWER(table_name) = %s " + "AND referenced_table_name IS NOT NULL AND referenced_table_schema = table_schema") + # The structural parser reads "UPDATE LOW_PRIORITY users" as a table named LOW_PRIORITY aliased users. All are + # reserved words except QUICK, which can only follow DELETE. + statement_modifiers: ClassVar[Mapping[str, FrozenSet[str]]] = { + "INSERT": frozenset({"LOW_PRIORITY", "HIGH_PRIORITY", "DELAYED", "IGNORE"}), + "REPLACE": frozenset({"LOW_PRIORITY", "DELAYED"}), + "UPDATE": frozenset({"LOW_PRIORITY", "IGNORE"}), + "DELETE": frozenset({"LOW_PRIORITY", "QUICK", "IGNORE"}), + } + charset_introducers: ClassVar[FrozenSet[str]] = frozenset({ + "armscii8", "ascii", "big5", "binary", "cp1250", "cp1251", "cp1256", "cp1257", "cp850", "cp852", "cp866", + "cp932", "dec8", "eucjpms", "euckr", "gb18030", "gb2312", "gbk", "geostd8", "greek", "hebrew", "hp8", + "keybcs2", "koi8r", "koi8u", "latin1", "latin2", "latin5", "latin7", "macce", "macroman", "sjis", "swe7", + "tis620", "ucs2", "ujis", "utf16", "utf16le", "utf32", "utf8", "utf8mb3", "utf8mb4", + }) + sql_token_pattern: ClassVar[Optional[Pattern[str]]] = re.compile(r""" + (?P(?:\#|--(?=\s|\Z))[^\n]*) + | (?P/\*.*?(?P\*/|\Z)) + | (?P'(?:[^'\\]|\\.|'')*(?P'?)) + | (?P"(?:[^"\\]|\\.|"")*(?P"?)) + | (?P`(?:[^`]|``)*(?P`?)) + | (?P[^\W\d][\w$]*) + | (?P\d[\w.]*) + | (?P;) + | (?P\s+) + | (?P[^\w\s'"`;/\-\#]+|.) + """, re.VERBOSE | re.DOTALL) + executable_comments: ClassVar[bool] = True + _dialect_code: str = DriverDialectCodes.MYSQL_CONNECTOR_PYTHON _network_bound_methods: Set[str] = { DbApiMethod.CONNECTION_COMMIT.method_name, @@ -69,6 +135,7 @@ class MySQLDriverDialect(DriverDialect): DbApiMethod.CURSOR_CLOSE.method_name, DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_FETCHONE.method_name, + DbApiMethod.CURSOR_NEXT.method_name, DbApiMethod.CURSOR_FETCHMANY.method_name, DbApiMethod.CURSOR_FETCHALL.method_name } @@ -223,6 +290,80 @@ def get_connection_from_obj(self, obj: object) -> Any: return None + @classmethod + def binds_parameters(cls, params: Any) -> bool: + # Connector/Python substitutes only for a non-empty dict, list or tuple. + return bool(params) and isinstance(params, (dict, list, tuple)) + + @classmethod + def metadata_key(cls, name: str) -> str: + # Column names are case-insensitive in MySQL, and table names are too unless lower_case_table_names=0 on a + # case-sensitive file system, where two tables differing only in case would share encryption metadata. This + # agrees with the uncached lookup under the default (case-insensitive) collations; metadata tables created with + # a _bin or _cs collation would compare case-sensitively there. + return name.lower() + + def upsert_clause( + self, conflict_columns: Sequence[str], update_columns: Sequence[str], extra_assignments: Sequence[str] = ()) -> str: + # VALUES(col) rather than a row alias, which needs MySQL 8.0.19+. + assignments = ", ".join([f"{c} = VALUES({c})" for c in update_columns] + list(extra_assignments)) + return f"ON DUPLICATE KEY UPDATE {assignments}" + + def insert_returning_id(self, conn: Connection, sql: str, params: Sequence[Any]) -> int: + """ + Runs an ``INSERT`` and returns the generated ``id``. + The cursor call runs through :meth:`execute`, so the ``socket_timeout`` of this dialect's properties applies, + and a timeout raises ``QueryTimeoutError``. + + :param conn: the connection to run the statement on. + :param sql: the ``INSERT`` statement. + :param params: the statement's parameters. + :return: the generated ``id``. + """ + with closing(conn.cursor()) as cursor: + self.execute(DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(sql, params), sql, conn=conn) + return int(cursor.lastrowid) # type: ignore[attr-defined] + + def analyzable_sql(self, sql: Any, cursor: Cursor) -> Tuple[Optional[str], Optional[str]]: + """ + Returns the text the encryption plugin analyzes for ``sql``, and the codec of the connection's client encoding + when ``sql`` is ``bytes``. + ``bytes`` SQL is analyzed as text when every byte is ASCII, the connection's character set reads each ASCII + byte as itself, and the text encodes back to the same bytes. + A character set Python has no codec for raises ``LookupError``. + + :param sql: the SQL the application passed to the cursor. + :param cursor: the driver cursor the SQL runs on. + :return: the text to analyze, or None when the SQL runs unanalyzed, and the codec ``bytes`` SQL was decoded + with, or None. + """ + if not isinstance(sql, bytes): + return super().analyzable_sql(sql, cursor) + conn = self.get_connection_from_obj(cursor) + # Not conn.charset: utf8mb4 is no Python codec. + codec = None if conn is None else conn.python_charset + text = self._decode_sql(sql, codec) + # mysql-connector keeps reporting the character set it negotiated (python_charset) when SQL changes the + # session's, and every client character set MySQL accepts, except swe7, reads ASCII bytes as ASCII, so only + # all-ASCII bytes SQL is analyzed. swe7 has no Python codec, so a connection reporting it raises above; a + # session switched to swe7 in SQL is a documented limit. + if not sql.isascii(): + return None, codec + return text, codec + + def binary_placeholder_prefix(self, cursor: Cursor) -> Optional[str]: + """ + Returns ``_binary``, which makes MySQL read a payload sent as text as binary data rather than as characters + (Warning 1300). + A prepared cursor sends a ``bytes`` value as binary data, so it needs no prefix. + + :param cursor: the driver cursor the statement runs on. + :return: ``"_binary "``, or None on a prepared cursor. + """ + if isinstance(cursor, MySQLCursorPrepared) or (CMYSQL_ENABLED and isinstance(cursor, CMySQLCursorPrepared)): + return None + return "_binary " + def transfer_session_state(self, from_conn: Connection, to_conn: Connection): if MySQLDriverDialect._is_mysql_connection(from_conn) and MySQLDriverDialect._is_mysql_connection(to_conn): to_conn.autocommit = from_conn.autocommit # type: ignore[attr-defined] diff --git a/aws_advanced_python_wrapper/pep249_methods.py b/aws_advanced_python_wrapper/pep249_methods.py index 0406c1d43..0d64bf0ed 100644 --- a/aws_advanced_python_wrapper/pep249_methods.py +++ b/aws_advanced_python_wrapper/pep249_methods.py @@ -56,24 +56,31 @@ class DbApiMethod(Enum): CURSOR_COPY_FROM = (25, "Cursor.copy_from", False) CURSOR_COPY_TO = (26, "Cursor.copy_to", False) CURSOR_COPY_EXPERT = (27, "Cursor.copy_expert", False) + CURSOR_COPY = (40, "Cursor.copy", False) + CURSOR_STREAM = (41, "Cursor.stream", False) + CURSOR_RESULTS = (42, "Cursor.results", False) + CURSOR_SET_RESULT = (43, "Cursor.set_result", False) + CURSOR_FETCHSETS = (44, "Cursor.fetchsets", False) + CURSOR_STORED_RESULTS = (45, "Cursor.stored_results", False) # Cursor properties and attributes CURSOR_CONNECTION = (28, "Cursor.connection", False) CURSOR_ROWNUMBER = (29, "Cursor.rownumber", False) CURSOR_NEXT = (30, "Cursor.__next__", False) - CURSOR_LASTROWID = (31, "Cursor.lastrowid", False) + CURSOR_ITER = (31, "Cursor.__iter__", False) + CURSOR_LASTROWID = (32, "Cursor.lastrowid", False) # AWS Advanced Python Wrapper Methods for the execution pipelines. - CONNECT = (32, "connect", True) - FORCE_CONNECT = (33, "force_connect", True) - INIT_HOST_PROVIDER = (34, "init_host_provider", True) - NOTIFY_CONNECTION_CHANGED = (35, "notify_connection_changed", True) - NOTIFY_HOST_LIST_CHANGED = (36, "notify_host_list_changed", True) - GET_HOST_INFO_BY_STRATEGY = (37, "get_host_info_by_strategy", True) - ACCEPTS_STRATEGY = (38, "accepts_strategy", True) + CONNECT = (33, "connect", True) + FORCE_CONNECT = (34, "force_connect", True) + INIT_HOST_PROVIDER = (35, "init_host_provider", True) + NOTIFY_CONNECTION_CHANGED = (36, "notify_connection_changed", True) + NOTIFY_HOST_LIST_CHANGED = (37, "notify_host_list_changed", True) + GET_HOST_INFO_BY_STRATEGY = (38, "get_host_info_by_strategy", True) + ACCEPTS_STRATEGY = (39, "accepts_strategy", True) # Special marker for all methods - ALL = (39, "*", False) + ALL = (46, "*", False) def __init__(self, id: int, method_name: str, always_use_pipeline: bool): self.id = id diff --git a/aws_advanced_python_wrapper/pg_driver_dialect.py b/aws_advanced_python_wrapper/pg_driver_dialect.py index 415011344..e8957e8a3 100644 --- a/aws_advanced_python_wrapper/pg_driver_dialect.py +++ b/aws_advanced_python_wrapper/pg_driver_dialect.py @@ -14,19 +14,29 @@ from __future__ import annotations +import re import socket -from typing import TYPE_CHECKING, Any, Callable, Set +import string +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, FrozenSet, Mapping, + Optional, Sequence, Set, Tuple, cast) import psycopg +from psycopg import rows +from psycopg import sql as psycopg_sql if TYPE_CHECKING: + from re import Pattern + from aws_advanced_python_wrapper.hostinfo import HostInfo - from aws_advanced_python_wrapper.pep249 import Connection + from aws_advanced_python_wrapper.pep249 import Connection, Cursor +from contextlib import closing from inspect import signature from aws_advanced_python_wrapper.driver_dialect import DriverDialect from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes +from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect from aws_advanced_python_wrapper.errors import UnsupportedOperationError from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.utils.log import Logger @@ -37,14 +47,93 @@ logger = Logger(__name__) +_ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase) + -class PgDriverDialect(DriverDialect): +class PgDriverDialect(DriverDialect, EncryptionDriverDialect): _driver_name: str = "Psycopg" TARGET_DRIVER_CODE: str = "psycopg" # https://www.psycopg.org/psycopg3/docs/api/pq.html#psycopg.pq.TransactionStatus PSYCOPG_IDLE_TRANSACTION_STATUS = 0 + # metadata_key keeps the base's exact match: catalog names are case-sensitive, so "Users" and users are two tables. + # An unqualified operator resolves through search_path, where a user-defined "=" with a closer type match would + # win. Pin the built-in. + equals_operator: ClassVar[str] = "OPERATOR(pg_catalog.=)" + greater_than_operator: ClassVar[str] = "OPERATOR(pg_catalog.>)" + # The key management utility compares the primary key with the built-in operators, so it needs a built-in type, + # or a domain over one. + key_column_type_sql: ClassVar[Optional[str]] = ( + "SELECT pg_catalog.format_type(a.atttypid, a.atttypmod) AS type_name, " + "(CASE WHEN t.typtype OPERATOR(pg_catalog.=) 'd' THEN bt.typnamespace ELSE t.typnamespace END) " + "OPERATOR(pg_catalog.=) 'pg_catalog'::pg_catalog.regnamespace::pg_catalog.oid AS built_in " + "FROM pg_catalog.pg_attribute a " + "JOIN pg_catalog.pg_type t ON t.oid OPERATOR(pg_catalog.=) a.atttypid " + "LEFT JOIN pg_catalog.pg_type bt ON bt.oid OPERATOR(pg_catalog.=) t.typbasetype " + "WHERE a.attrelid OPERATOR(pg_catalog.=) pg_catalog.to_regclass(%s::pg_catalog.text)::pg_catalog.oid " + "AND a.attname OPERATOR(pg_catalog.=) %s::pg_catalog.name AND NOT a.attisdropped") + schema_table_sql: ClassVar[str] = ( + "SELECT 1 AS found FROM information_schema.tables " + "WHERE pg_catalog.lower(table_schema) OPERATOR(pg_catalog.=) %s::pg_catalog.text " + "AND pg_catalog.lower(table_name) OPERATOR(pg_catalog.=) %s::pg_catalog.text") + schema_columns_sql: ClassVar[str] = ( + "SELECT column_name FROM information_schema.columns " + "WHERE pg_catalog.lower(table_schema) OPERATOR(pg_catalog.=) %s::pg_catalog.text " + "AND pg_catalog.lower(table_name) OPERATOR(pg_catalog.=) %s::pg_catalog.text") + # pg_catalog, not information_schema: its constraint views hide the tables a SELECT-only role can read. + schema_key_constraints_sql: ClassVar[str] = ( + "SELECT c.conname AS constraint_name, " + "CASE WHEN c.contype OPERATOR(pg_catalog.=) 'p'::pg_catalog.\"char\" THEN 'PRIMARY KEY' ELSE 'UNIQUE' END " + "AS constraint_type, a.attname AS column_name " + "FROM pg_catalog.pg_constraint c " + "JOIN pg_catalog.pg_class t ON t.oid OPERATOR(pg_catalog.=) c.conrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid OPERATOR(pg_catalog.=) t.relnamespace " + "CROSS JOIN LATERAL pg_catalog.unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord) " + "JOIN pg_catalog.pg_attribute a ON a.attrelid OPERATOR(pg_catalog.=) t.oid " + "AND a.attnum OPERATOR(pg_catalog.=) k.attnum " + "WHERE (c.contype OPERATOR(pg_catalog.=) 'p'::pg_catalog.\"char\" " + "OR c.contype OPERATOR(pg_catalog.=) 'u'::pg_catalog.\"char\") " + "AND pg_catalog.lower(n.nspname) OPERATOR(pg_catalog.=) %s::pg_catalog.text " + "AND pg_catalog.lower(t.relname) OPERATOR(pg_catalog.=) %s::pg_catalog.text " + "ORDER BY c.conname, k.ord") + # ROWS FROM zips the two key arrays: the two-argument unnest shorthand works only unqualified. + schema_foreign_keys_sql: ClassVar[str] = ( + "SELECT a.attname AS column_name, rt.relname AS referenced_table, ra.attname AS referenced_column " + "FROM pg_catalog.pg_constraint c " + "JOIN pg_catalog.pg_class t ON t.oid OPERATOR(pg_catalog.=) c.conrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid OPERATOR(pg_catalog.=) t.relnamespace " + "JOIN pg_catalog.pg_class rt ON rt.oid OPERATOR(pg_catalog.=) c.confrelid " + "CROSS JOIN LATERAL ROWS FROM (pg_catalog.unnest(c.conkey), pg_catalog.unnest(c.confkey)) AS k(attnum, refnum) " + "JOIN pg_catalog.pg_attribute a ON a.attrelid OPERATOR(pg_catalog.=) t.oid " + "AND a.attnum OPERATOR(pg_catalog.=) k.attnum " + "JOIN pg_catalog.pg_attribute ra ON ra.attrelid OPERATOR(pg_catalog.=) rt.oid " + "AND ra.attnum OPERATOR(pg_catalog.=) k.refnum " + "WHERE c.contype OPERATOR(pg_catalog.=) 'f'::pg_catalog.\"char\" " + "AND rt.relnamespace OPERATOR(pg_catalog.=) t.relnamespace " + "AND pg_catalog.lower(n.nspname) OPERATOR(pg_catalog.=) %s::pg_catalog.text " + "AND pg_catalog.lower(t.relname) OPERATOR(pg_catalog.=) %s::pg_catalog.text") + analyzed_statements: ClassVar[FrozenSet[str]] = frozenset( + {"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "COPY", "VALUES", "PREPARE"}) + sqlglot_dialect: ClassVar[str] = "postgres" + upsert_row_alias: ClassVar[Optional[str]] = "excluded" + sql_token_pattern: ClassVar[Optional[Pattern[str]]] = re.compile(r""" + (?P--[^\n]*) + | (?P/\*) + | (?P[Ee]'(?:[^'\\]|\\.|'')*(?P'?)) + | (?P'(?:[^']|'')*(?P'?)) + | (?P"(?:[^"]|"")*(?P"?)) + | (?P\$\d+) + | (?P\$(?:[^\W\d]\w*)?\$) + | (?P[^\W\d][\w$]*) + | (?P\d[\w.]*) + | (?P;) + | (?P\s+) + | (?P[^\w\s'"$;/\-]+|.) + """, re.VERBOSE | re.DOTALL) + nested_block_comments: ClassVar[bool] = True + strict_placeholders: ClassVar[bool] = True + _dialect_code: str = DriverDialectCodes.PSYCOPG _network_bound_methods: Set[str] = { DbApiMethod.CONNECTION_COMMIT.method_name, @@ -59,6 +148,7 @@ class PgDriverDialect(DriverDialect): DbApiMethod.CURSOR_CALLPROC.method_name, DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_FETCHONE.method_name, + DbApiMethod.CURSOR_NEXT.method_name, DbApiMethod.CURSOR_FETCHMANY.method_name, DbApiMethod.CURSOR_FETCHALL.method_name } @@ -178,6 +268,67 @@ def get_connection_from_obj(self, obj: object) -> Any: if isinstance(obj, psycopg.Cursor): return obj.connection + @classmethod + def fold_identifier(cls, name: str, quoted: bool) -> str: + # PostgreSQL folds an unquoted identifier to lower case, ASCII letters only in a multibyte (e.g. UTF-8) + # database; a quoted one keeps its case. The result is the name in the system catalog, apart from PostgreSQL's + # truncation of names longer than 63 bytes. + return name if quoted else name.translate(_ASCII_LOWER) + + def upsert_clause( + self, conflict_columns: Sequence[str], update_columns: Sequence[str], extra_assignments: Sequence[str] = ()) -> str: + assignments = ", ".join([f"{c} = EXCLUDED.{c}" for c in update_columns] + list(extra_assignments)) + return f"ON CONFLICT ({', '.join(conflict_columns)}) DO UPDATE SET {assignments}" + + def insert_returning_id(self, conn: Connection, sql: str, params: Sequence[Any]) -> int: + """ + Runs an ``INSERT`` written without ``RETURNING`` and returns the generated ``id``. + Each cursor call runs through :meth:`execute`, so the ``socket_timeout`` of this dialect's properties applies, and + a timeout raises ``QueryTimeoutError``. + + :param conn: the connection to run the statement on. + :param sql: the ``INSERT`` statement. + :param params: the statement's parameters. + :return: the generated ``id``. + """ + returning_sql = f"{sql} RETURNING id" + with closing(conn.cursor()) as cursor: + self.execute( + DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(returning_sql, params), returning_sql, conn=conn) + row = cast("Any", self.execute(DbApiMethod.CURSOR_FETCHONE.method_name, lambda: cursor.fetchone(), conn=conn)) + # A connection opened with a dict-like row factory returns a mapping. + if isinstance(row, Mapping): + return int(next(iter(row.values()))) + return int(row[0]) + + def analyzable_sql(self, sql: Any, cursor: Cursor) -> Tuple[Optional[str], Optional[str]]: + """ + Returns the text the encryption plugin analyzes for ``sql``, and the codec of the connection's client encoding + when ``sql`` is ``bytes``. + A psycopg ``Composable`` is analyzed as text and sent as the object. + ``bytes`` SQL is analyzed as text in the connection's client encoding when that encoding reads each ASCII byte + as itself and the text encodes back to the same bytes. + psycopg raises ``NotSupportedError`` for an encoding Python has no codec for. + + :param sql: the SQL the application passed to the cursor. + :param cursor: the driver cursor the SQL runs on. + :return: the text to analyze, or None when the SQL runs unanalyzed, and the codec ``bytes`` SQL was decoded + with, or None. + """ + if isinstance(sql, psycopg_sql.Composable): + return sql.as_string(cast("Any", cursor)), None + if isinstance(sql, bytes): + conn = self.get_connection_from_obj(cursor) + codec = None if conn is None else conn.info.encoding + return self._decode_sql(sql, codec), codec + return super().analyzable_sql(sql, cursor) + + def unsupported_row_factory(self, cursor: Cursor) -> Optional[Any]: + if isinstance(cursor, psycopg.Cursor) and \ + cursor.row_factory not in (rows.tuple_row, rows.dict_row, rows.namedtuple_row): + return cursor.row_factory + return None + def prepare_connect_info(self, host_info: HostInfo, original_props: Properties) -> Properties: driver_props: Properties = Properties(original_props.copy()) PropertiesUtils.remove_wrapper_props(driver_props) diff --git a/aws_advanced_python_wrapper/plugin.py b/aws_advanced_python_wrapper/plugin.py index 7706364c5..feefb08ee 100644 --- a/aws_advanced_python_wrapper/plugin.py +++ b/aws_advanced_python_wrapper/plugin.py @@ -93,6 +93,18 @@ def force_connect( return force_connect_func() def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + """ + Handles a call to a method this plugin subscribes to, such as `Cursor.execute`. Calling `execute_func` runs the plugins after this one, + then the target driver method. To send different `Cursor.execute` or `Cursor.executemany` arguments to them, assign a new tuple to the + `args` and a new mapping to the `kwargs` of :py:attr:`PluginService.current_call_context` before calling `execute_func`. + + :param target: the target driver object the method is called on, such as the driver's cursor or connection. + :param method_name: the name of the method, such as `Cursor.execute`. + :param execute_func: the function to call to continue the call down the pipeline. + :param args: the method's positional arguments, as they are when this plugin's turn comes. + :param kwargs: the method's keyword arguments, as they are when this plugin's turn comes. + :return: the result of the call, usually the value `execute_func` returns. + """ return execute_func() def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index 2d8268813..82f029b57 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -23,6 +23,8 @@ BlueGreenPluginFactory from aws_advanced_python_wrapper.custom_endpoint_plugin import \ CustomEndpointPluginFactory +from aws_advanced_python_wrapper.encryption.kms_encryption_plugin import \ + KmsEncryptionPluginFactory from aws_advanced_python_wrapper.failover_v2_plugin import \ FailoverV2PluginFactory from aws_advanced_python_wrapper.fastest_response_strategy_plugin import \ @@ -45,7 +47,10 @@ from abc import abstractmethod from concurrent.futures import TimeoutError -from typing import Any, Callable, Dict, Optional, Protocol, Set, Tuple +from contextvars import ContextVar +from functools import partial +from typing import (Any, Callable, Dict, FrozenSet, Mapping, Optional, + Protocol, Set, Tuple) from aws_advanced_python_wrapper.allowed_and_blocked_hosts import \ AllowedAndBlockedHosts @@ -243,6 +248,23 @@ def network_bound_methods(self) -> Set[str]: def props(self) -> Properties: ... + @property + @abstractmethod + def current_call_context(self) -> Optional[PluginCallContext]: + """ + The context of the ``Cursor.execute`` or ``Cursor.executemany`` call this thread is running through the plugins. + + Read it only while handling one of those two methods. Each of those calls has its own context, a call made + from inside a plugin included, and the enclosing one is current again once it returns. Other methods get no + context of their own, so while one of them runs inside such a call, this still returns the enclosing call's + context. ``None`` when no such call is running on this thread. + + The value belongs to the calling thread, not to this connection's plugin service. Another thread sees it only + through a copy of this thread's context taken during the call (``contextvars.copy_context()``, or a thread + that inherits its creator's context), and such a copy holds no arguments once the call has returned. + """ + ... + def is_network_bound_method(self, method_name: str) -> bool: ... @@ -575,6 +597,10 @@ def network_bound_methods(self) -> Set[str]: def props(self) -> Properties: return self._props + @property + def current_call_context(self) -> Optional[PluginCallContext]: + return _CURRENT_CALL_CONTEXT.get() + def update_in_transaction(self, is_in_transaction: Optional[bool] = None): if is_in_transaction is not None: self._is_in_transaction = is_in_transaction @@ -860,6 +886,48 @@ def get_status(self, clazz: Type[StatusType], key: str) -> Optional[StatusType]: return status +class PluginCallContext: + """The arguments of the ``Cursor.execute`` or ``Cursor.executemany`` call the plugins are handling. + + Each plugin's ``execute`` receives the arguments as they are when its turn comes. A plugin that needs to hand + different ones to the plugins after it and to the target driver method assigns a new tuple to ``args`` and a new + mapping to ``kwargs`` before it calls its ``execute_func``. Before it assigns, a plugin can call :py:meth:`holds` to + check that the context holds the argument objects it was handed. Changing either object in place is not allowed, and + the caller's own objects must never be modified. The target driver method receives exactly what is assigned, even + when it is empty. A replacement lasts until the plugin that made it returns, so a plugin before it that calls its + ``execute_func`` again starts from the arguments it saw. + + Reached through :py:attr:`PluginService.current_call_context`. + """ + + __slots__ = ("args", "kwargs") + + def __init__(self, args: Tuple[Any, ...], kwargs: Mapping[str, Any]): + self.args = args + self.kwargs = kwargs + + def holds(self, args: Tuple[Any, ...], kwargs: Mapping[str, Any]) -> bool: + """Whether this context holds the argument objects a plugin was handed, so it is that call's context. + + :param args: The positional arguments the plugin's ``execute`` received. + :param kwargs: The keyword arguments the plugin's ``execute`` received. + :return: True when each positional argument and each keyword value is the context's own object (compared + with ``is``). + """ + return (len(self.args) == len(args) and all(a is b for a, b in zip(self.args, args, strict=False)) + and self.kwargs.keys() == kwargs.keys() and all(self.kwargs[k] is v for k, v in kwargs.items())) + + +# The methods whose call gets a PluginCallContext. Their target driver functions (in AwsWrapperCursor) take the +# context's arguments. +_CALL_CONTEXT_METHODS: FrozenSet[DbApiMethod] = frozenset({DbApiMethod.CURSOR_EXECUTE, DbApiMethod.CURSOR_EXECUTEMANY}) + +# The current call's context belongs to the calling thread, not to a plugin service, so it is a ContextVar. Resetting +# its token in PluginManager.execute makes the enclosing call's context current again after a nested call. +_CURRENT_CALL_CONTEXT: ContextVar[Optional[PluginCallContext]] = ContextVar( + "aws_advanced_python_wrapper_plugin_call_context", default=None) + + class PluginChainCallableInfo: """Container for plugin chain callable and subscription information.""" def __init__(self, func: Callable, is_subscribed: bool): @@ -891,7 +959,8 @@ class PluginManager(CanReleaseResources): "okta": OktaAuthPluginFactory, "initial_connection": AuroraInitialConnectionStrategyPluginFactory, "limitless": LimitlessPluginFactory, - "bg": BlueGreenPluginFactory + "bg": BlueGreenPluginFactory, + "kms_encryption": KmsEncryptionPluginFactory } WEIGHT_RELATIVE_TO_PRIOR_PLUGIN = -1 @@ -908,6 +977,7 @@ class PluginManager(CanReleaseResources): ReadWriteSplittingPluginFactory: 300, SimpleReadWriteSplittingPluginFactory: 310, GdbReadWriteSplittingPluginFactory: 320, + KmsEncryptionPluginFactory: 390, FailoverPluginFactory: 400, FailoverV2PluginFactory: 410, GdbFailoverPluginFactory: 420, @@ -1068,13 +1138,18 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla if context is not None: context.set_attribute("python_call", method.method_name) + call_context = PluginCallContext(args, kwargs) if method in _CALL_CONTEXT_METHODS else None + token = None if call_context is None else _CURRENT_CALL_CONTEXT.set(call_context) try: - result = self._execute_with_subscribed_plugins( - method, - # next_plugin_func is defined later in make_pipeline - lambda plugin, next_plugin_func: plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs), - target_driver_func, - None) + if call_context is None: + result = self._execute_with_subscribed_plugins( + method, + # next_plugin_func is defined later in make_pipeline + lambda plugin, next_plugin_func: plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs), + target_driver_func, + None) + else: + result = self._execute_with_call_context(target, method, target_driver_func, call_context) if context is not None: context.set_success(True) @@ -1084,9 +1159,47 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla context.set_success(False) raise e finally: + if token is not None: + _CURRENT_CALL_CONTEXT.reset(token) + if call_context is not None: + # A copy of this thread's context taken during the call (one a plugin passes to a thread it starts, say) + # still holds this object, so it must not keep the call's arguments once the call has returned. + call_context.args, call_context.kwargs = (), {} if context is not None: context.close_context() + def _execute_with_call_context( + self, target: Any, method: DbApiMethod, target_driver_func: Callable, call_context: PluginCallContext) -> Any: + # The target driver function is always called with the context's arguments, so a replacement reaches the + # driver as written: an empty one fails there instead of running the caller's arguments. + return self._execute_with_subscribed_plugins( + method, + lambda plugin, next_plugin_func: PluginManager._execute_plugin( + plugin, target, method.method_name, next_plugin_func, call_context, target_driver_func), + lambda: target_driver_func(*call_context.args, **call_context.kwargs), + None) + + @staticmethod + def _execute_plugin( + plugin: Plugin, + target: Any, + method_name: str, + next_plugin_func: Callable, + call_context: PluginCallContext, + target_driver_func: Callable) -> Any: + # Each plugin gets the arguments as they are when its turn comes, so a replacement made before it is honoured. + # A replacement lasts until the plugin that made it returns: a plugin before it that calls its execute_func + # again starts from the arguments it saw, so nothing is replaced twice. + args, kwargs = call_context.args, call_context.kwargs + if isinstance(plugin, DefaultPlugin): + # DefaultPlugin may run the driver call on a socket_timeout worker that starts only after this call has + # timed out and every replacement has been undone, so the driver function gets these arguments bound now. + next_plugin_func = partial(target_driver_func, *args, **kwargs) + try: + return plugin.execute(target, method_name, next_plugin_func, *args, **kwargs) + finally: + call_context.args, call_context.kwargs = args, kwargs + def _execute_with_telemetry(self, plugin_name: str, func: Callable): context = self._telemetry_factory.open_telemetry_context(plugin_name, TelemetryTraceLevel.NESTED) try: diff --git a/aws_advanced_python_wrapper/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/read_write_splitting_plugin.py index 88b7d13ab..c2540cda6 100644 --- a/aws_advanced_python_wrapper/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/read_write_splitting_plugin.py @@ -60,6 +60,7 @@ class AbstractReadWriteSplittingPlugin(Plugin): DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_FETCHONE.method_name, + DbApiMethod.CURSOR_NEXT.method_name, DbApiMethod.CURSOR_FETCHMANY.method_name, DbApiMethod.CURSOR_FETCHALL.method_name } diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index 8672e7810..f03e3a89b 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -563,3 +563,129 @@ MonitorService.ErrorDisposingMonitor=[MonitorService] Error disposing monitor: { MonitorService.ErrorPropagatingEvent=[MonitorService] Error propagating event: {} MonitorService.StuckMonitorDetected=[MonitorService] Stuck monitor detected for type '{}' with key '{}'. MonitorService.ErrorDuringCleanup=[MonitorService] Error during cleanup: {} + +DataKeyCache.CleanupFailed=[DataKeyCache] Removing expired data keys failed: {} +EncryptionConfig.AmbiguousRegion=[EncryptionConfig] The KMS key ARNs in {} are in more than one region: set {} to the region of the keys the plugin uses. +EncryptionConfig.InvalidSchemaName=[EncryptionConfig] Invalid encryption_metadata_schema {}: a schema name must start with a letter or underscore and contain only letters, digits, and underscores. +EncryptionConfig.InvalidValue=[EncryptionConfig] Invalid value for {}: {} +EncryptionConfig.MissingAllowedMasterKeys=[EncryptionConfig] {} is required: list the KMS master key ARNs the kms_encryption plugin may use. +EncryptionConfig.MissingRegion=[EncryptionConfig] No KMS region configured: set {} to the region of your KMS keys, or list a KMS key ARN in {} to take the region from. Alias names (alias/...) and bare key ids name no region. +EncryptionConfig.RegionMismatch=[EncryptionConfig] {} is '{}', but {} lists a KMS key or alias ARN in {}. KMS calls with such a key fail, because the KMS client serves only '{}'. +EncryptionConfig.OutOfRange=[EncryptionConfig] The value of {} is out of range: it must be {}. +EncryptionService.CannotConvert=[EncryptionService] Cannot convert {} to {}. +EncryptionService.CannotWriteType=[EncryptionService] Cannot write a value of type '{}' as {}. +EncryptionService.CryptographyMissing=[EncryptionService] The KMS encryption plugin needs the 'cryptography' package. Run pip install 'aws-advanced-python-wrapper[encryption]' to install it. +EncryptionService.DataTooShort=[EncryptionService] Encrypted data is too short: {} bytes, expected at least {}. +EncryptionService.DeserializeFailed=[EncryptionService] Failed to deserialize {}. +EncryptionService.EncryptFailed=[EncryptionService] Failed to encrypt value: {} +EncryptionService.IntegrityCheckFailed=[EncryptionService] Integrity check failed: the value was modified, was never encrypted, or was signed with a different HMAC key. +EncryptionService.InvalidKeyId=[EncryptionService] A valid key id is required to tag an encrypted value, got '{}'. +EncryptionService.LongOutOfRange=[EncryptionService] Integer value exceeds the signed 64-bit range. +EncryptionService.MissingHmacKey=[EncryptionService] An HMAC key is required to protect encrypted values. +EncryptionService.NeedsBool=[EncryptionService] BOOLEAN needs a bool. +EncryptionService.NeedsBytes=[EncryptionService] BYTE_ARRAY needs a bytes-like value. +EncryptionService.NeedsDate=[EncryptionService] {} needs a date or datetime. +EncryptionService.NonFiniteDecimal=[EncryptionService] Cannot encrypt a non-finite Decimal. +EncryptionService.NoUtf8Form=[EncryptionService] Cannot encrypt a string with no UTF-8 form. +EncryptionService.OutsideDatetimeRange=[EncryptionService] In UTC, the value is outside the range a datetime can represent. +EncryptionService.TagMismatch=[EncryptionService] Failed to decrypt value: the authentication tag does not match this data key. +EncryptionService.TimezoneAware=[EncryptionService] Cannot write a timezone-aware value as {}. +EncryptionService.UnsupportedTypeMarker=[EncryptionService] Unsupported type marker: '{}'. +EncryptionService.WrongKeyLength=[EncryptionService] Data key must be {} bytes for {}, got {}. +EncryptionService.WrongValueLength=[EncryptionService] Expected {} bytes for {}, got {}. +KeyManagementUtility.AlreadyEncrypted=[KeyManagementUtility] Column {}.{} is already encrypted. +KeyManagementUtility.CreateAliasFailed=[KeyManagementUtility] Created master key {} but could not create an alias for it: {} +KeyManagementUtility.CreatedMasterKey=[KeyManagementUtility] Created KMS master key {}. +KeyManagementUtility.InvalidBatchSize=[KeyManagementUtility] batch_size must be an integer from 1 to {}, not '{}'. +KeyManagementUtility.InvalidName=[KeyManagementUtility] '{}' is not a valid {} name. Use letters, digits and underscores, starting with a letter or an underscore, at most 64 characters; a table name can have one schema prefix, as schema.table. +KeyManagementUtility.KeyRowUnusable=[KeyManagementUtility] Key id {} in key_storage has no master key ARN, encrypted data key or HMAC key, so its values can't be checked. Nothing was changed. +KeyManagementUtility.MissingArgument=[KeyManagementUtility] The connection, kms_client and config arguments are required. +KeyManagementUtility.NoCurrentMasterKey=[KeyManagementUtility] Column {}.{} has no current master key to rotate onto; pass new_master_key_arn. +KeyManagementUtility.NotEncrypted=[KeyManagementUtility] No kms_encryption configuration exists for {}.{}. +KeyManagementUtility.NothingToRemove=[KeyManagementUtility] No kms_encryption configuration existed for {}.{}. +KeyManagementUtility.OldKeyIdsRequired=[KeyManagementUtility] old_key_ids needs at least one earlier key id, and can't hold None. +KeyManagementUtility.OldKeyIsCurrent=[KeyManagementUtility] Key id {} is the current key of {}.{}. Pass only earlier key ids in old_key_ids. +KeyManagementUtility.OldKeyNotFound=[KeyManagementUtility] Key id {} is not in key_storage. +KeyManagementUtility.PluginConnectionNotAllowed=[KeyManagementUtility] Re-encryption runs only on the driver's own connection, not on an AwsWrapperConnection: the KMS Encryption Plugin would encrypt the stored values a second time. +KeyManagementUtility.PrimaryKeySameAsColumn=[KeyManagementUtility] The primary key column '{}' can't be the encrypted column. +KeyManagementUtility.ReencryptCompleted=[KeyManagementUtility] Re-encryption of {}.{} finished: {} re-encrypted, {} already current, {} unmatched, in {} batch(es). +KeyManagementUtility.ReencryptFailed=[KeyManagementUtility] Re-encryption of {}.{} failed in batch {} after {} committed value(s): {}. The committed batches stay, and the failed batch was rolled back. The column uses key id {}; run reencrypt_remaining_rows with old key id(s) {} to finish. +KeyManagementUtility.ReencryptNeedsAllowList=[KeyManagementUtility] Configure {} to re-encrypt the remaining rows, so the master key of the column's current data key can be checked. +KeyManagementUtility.ReencryptStarting=[KeyManagementUtility] Re-encrypting {}.{} into key id {} from key id(s) {}, {} rows per batch. +KeyManagementUtility.RelationCheckFailed=[KeyManagementUtility] Can't read table {}, column {} and primary key column {}: {}. Check that they exist and are spelled as in the database. Nothing was changed. +KeyManagementUtility.RequiredArgument=[KeyManagementUtility] {} is required. +KeyManagementUtility.RollbackFailed=[KeyManagementUtility] The rollback failed: {} +KeyManagementUtility.RotateColumnHasData=[KeyManagementUtility] Can't rotate the data key of {}.{} with rotate_data_key: the column holds data, which would stay under the data key the rotation means to retire. Nothing was changed. Use rotate_data_key_and_reencrypt instead. +KeyManagementUtility.RotatedDataKey=[KeyManagementUtility] Rotated the data key for {}.{} from key {} to {}. +KeyManagementUtility.RotateNeedsMasterKey=[KeyManagementUtility] Pass the master key ARN to rotate onto, or configure {} so the current one can be checked. +KeyManagementUtility.RotateUnsupportedAlgorithm=[KeyManagementUtility] Can't rotate the data key of {}.{}: the column uses encryption algorithm '{}', and the utility creates only AES-256-GCM data keys. Nothing was changed. +KeyManagementUtility.RotationKeySwitched=[KeyManagementUtility] {}.{} now uses key id {} (earlier key id {}). Keep key id {} and its KMS key while any value or backup uses it. +KeyManagementUtility.RotationPrecheckFailed=[KeyManagementUtility] The rotation of {}.{} stopped before any change: {} value(s) aren't under the current key id {}. Move them with reencrypt_remaining_rows and their earlier key id, then try again. +KeyManagementUtility.RotationSwitchConflict=[KeyManagementUtility] The encryption metadata of {}.{} no longer names key id {}, so another rotation may be running. The new key id {} wasn't used, and nothing was changed. +KeyManagementUtility.RowUpdateMissed=[KeyManagementUtility] A row changed during its re-encryption, so it wasn't updated. +KeyManagementUtility.SchemaMissingColumn=[KeyManagementUtility] Table '{}.{}' has no column '{}'. +KeyManagementUtility.SchemaMissingForeignKey=[KeyManagementUtility] There is no foreign key from '{}.encryption_metadata.key_id' to '{}.key_storage.id'. +KeyManagementUtility.SchemaMissingPrimaryKey=[KeyManagementUtility] Table '{}.key_storage' has no primary key on 'id'. +KeyManagementUtility.SchemaMissingTable=[KeyManagementUtility] Table '{}.{}' does not exist. +KeyManagementUtility.SchemaMissingUniqueKey=[KeyManagementUtility] Table '{}.encryption_metadata' has no primary key or unique constraint on (table_name, column_name). +KeyManagementUtility.StatementFailed=[KeyManagementUtility] {} failed: {} +KeyManagementUtility.StoredDataKey=[KeyManagementUtility] Stored a data key for {}.{} as key_storage id {}. +KeyManagementUtility.UnmatchedRows=[KeyManagementUtility] {}.{}: {} value(s) are under neither the current key id {} nor the old key id(s) {}, and were left as they are. +KeyManagementUtility.UnsupportedAlgorithm=[KeyManagementUtility] The utility creates only AES-256-GCM data keys, so it can't set up a column with encryption algorithm '{}'. Nothing was changed. +KeyManagementUtility.UnsupportedDriver=[KeyManagementUtility] The key management utility does not support '{}'. Use a psycopg or mysql-connector-python connection, or pass props with wrapper_driver_dialect set to 'psycopg' or 'mysql-connector-python', with that driver installed. +KeyManagementUtility.UnsupportedPrimaryKeyType=[KeyManagementUtility] Can't re-encrypt table {}: its primary key column {} has type '{}', and it needs a built-in type or a domain over one. Nothing was changed. +KeyManager.KmsCallFailed=[KeyManager] KMS {} failed after {} attempt(s): {} +KeyManager.MalformedEncryptedDataKey=[KeyManager] The stored encrypted data key is not valid base64. +KeyManager.MasterKeyValidationFailed=[KeyManager] Could not validate master key {}: {} +KeyManager.MissingEncryptedDataKey=[KeyManager] The stored key metadata has no encrypted data key. +KeyManager.ReadKeyMetadataFailed=[KeyManager] Failed to read a key_storage row: {} +KeyManager.RefusingUnusableKeyMetadata=[KeyManager] Refusing to store key metadata that names no master key or lacks an encrypted data key, HMAC key, or key spec. +KeyManager.Retrying=[KeyManager] KMS {} failed (attempt {}/{}), retrying in {}s: {} +KeyManager.StoreKeyMetadataFailed=[KeyManager] Failed to store key metadata ({}). +KeyManager.TouchKeyFailed=[KeyManager] Failed to update last_used_at for key {}: {} +KeyManager.UnauthorizedMasterKey=[KeyManager] Master key {} is not listed in {}; refusing to use it. +KeyManager.WrongDataKeyLength=[KeyManager] KMS returned a {}-byte data key for key spec {}, which {} cannot use. +KmsEncryptionPlugin.AnnotationNotEncrypted=[KmsEncryptionPlugin] Refusing a statement that annotates a value for encrypted column '{}' with a column that has no encryption metadata. +KmsEncryptionPlugin.ArgumentsChanged=[KmsEncryptionPlugin] The driver call would not receive the arguments the plugin analyzed; refusing to run it. +KmsEncryptionPlugin.AuditNotWritten=[KmsEncryptionPlugin] encryption_audit_logging_enabled is True, but this release writes no audit records. +KmsEncryptionPlugin.CallprocRefused=[KmsEncryptionPlugin] Refusing '{}' with arguments while a column is encrypted: the plugin can't tell which columns the routine writes them to, so they could reach the server unencrypted. Write encrypted columns with execute, or set encryption_fail_on_unmapped_parameter to False to pass the arguments unchanged. +KmsEncryptionPlugin.Closed=[KmsEncryptionPlugin] The connection is closed, so the plugin refuses to analyze statements or results on it. +KmsEncryptionPlugin.CopyNotAnalysed=[KmsEncryptionPlugin] Refusing a COPY of type '{}', which the plugin can't analyze, while a column is encrypted: its rows could reach an encrypted column unencrypted. Pass the COPY statement as a str. +KmsEncryptionPlugin.CopyParameters=[KmsEncryptionPlugin] Refusing a COPY with parameters on table(s) '{}' with encrypted columns: the plugin doesn't encrypt a COPY's parameters, so they would reach the server unencrypted. Set encryption_fail_on_unmapped_parameter to False to run such statements unchanged. +KmsEncryptionPlugin.CopyRefused=[KmsEncryptionPlugin] Refusing a COPY ... FROM that writes encrypted column '{}': its rows would reach the server unencrypted. Write the rows with INSERT instead. +KmsEncryptionPlugin.CopyUnread=[KmsEncryptionPlugin] Refusing a COPY that can write table(s) '{}' with encrypted columns: {}, so the plugin can't tell which columns it writes. Write the rows with execute or executemany instead. +KmsEncryptionPlugin.CteShadowsTable=[KmsEncryptionPlugin] Refusing a statement whose CTE '{}' has the name of a table with encrypted columns: a reference to that name can read or write the table instead of the CTE, and the table's values would be neither encrypted nor decrypted. Rename the CTE. +KmsEncryptionPlugin.ExecutableComment=[KmsEncryptionPlugin] Refusing a statement on table(s) '{}' with encrypted columns: MySQL runs the body of its /*! ... */ comment, which the plugin can't analyze. +KmsEncryptionPlugin.HiddenPlaceholder=[KmsEncryptionPlugin] Refusing a statement on table(s) '{}' with encrypted columns: a placeholder is inside a quoted literal, quoted identifier or comment, so its values can't be paired with their columns. +KmsEncryptionPlugin.LoopOutlivedStatement=[KmsEncryptionPlugin] The cursor ran another statement during this loop, so the loop's next row would come from that statement. Start a new loop after each execute, or use one cursor per statement. +KmsEncryptionPlugin.MetadataNotLoaded=[KmsEncryptionPlugin] The plugin's key manager isn't loaded, so it can't read or write encrypted values. +KmsEncryptionPlugin.NoExactForm=[KmsEncryptionPlugin] The value of parameter '{}', of type '{}', has no exact stored form; convert it before writing it to or comparing it with encrypted column '{}'. +KmsEncryptionPlugin.NoResultDescription=[KmsEncryptionPlugin] A result from a table with encrypted columns arrived without a column description, so its values can't be decrypted. +KmsEncryptionPlugin.NotAnalysed=[KmsEncryptionPlugin] SQL of type '{}' is not analyzed; it runs unchanged and the database trigger must reject any plaintext. +KmsEncryptionPlugin.NotAnalysedRefused=[KmsEncryptionPlugin] Refusing SQL of type '{}', which the plugin can't analyze, while a column is encrypted: its values could reach the server unencrypted. Pass the SQL as a str, or set encryption_fail_on_unmapped_parameter to False to run such SQL unchanged. +KmsEncryptionPlugin.NotAPayload=[KmsEncryptionPlugin] Encrypted column '{}' returned a value that is not binary, so it is not an encrypted payload. +KmsEncryptionPlugin.PassedThrough=[KmsEncryptionPlugin] A statement writing table(s) '{}' with encrypted columns could not be fully analyzed ({}); it runs unchanged and the database trigger must reject any plaintext. +KmsEncryptionPlugin.ReleaseFailed=[KmsEncryptionPlugin] Closing the connection couldn't release its '{}', which raised '{}'; the plugin goes on to release its other resources. +KmsEncryptionPlugin.ResultMethodNotSupported=[KmsEncryptionPlugin] Refusing '{}' while the kms_encryption plugin is on: its rows don't pass through the plugin, so it can't decrypt them. To read the results of several statements, run one statement per execute and read it with fetchone, fetchmany or fetchall; on psycopg, use a named cursor to read a large result in pages. +KmsEncryptionPlugin.RowFactory=[KmsEncryptionPlugin] The cursor's row factory '{}' is not supported on results with encrypted columns: use the default, dict_row or namedtuple_row. +KmsEncryptionPlugin.SharedParameter=[KmsEncryptionPlugin] Refusing a statement that binds parameter '{}' both to encrypted column '{}' and to a use that isn't encrypted; give each use its own parameter. +KmsEncryptionPlugin.UnboundWrite=[KmsEncryptionPlugin] Refusing a statement that writes encrypted column '{}' with something other than a bind parameter. +KmsEncryptionPlugin.UnknownColumnTable=[KmsEncryptionPlugin] Refusing a statement that binds a value for a column whose table can't be determined and whose name matches encrypted column '{}'. Annotate the value with the column's table and name. +KmsEncryptionPlugin.UnknownKey=[KmsEncryptionPlugin] A value in encrypted column '{}' names a key that has no usable key_storage row. +KmsEncryptionPlugin.UnmappedParameters=[KmsEncryptionPlugin] Refusing a statement on table(s) '{}' with encrypted columns: {}, so its parameters can't be paired with their columns. Set encryption_fail_on_unmapped_parameter to False to run such statements unchanged. +KmsEncryptionPlugin.UnplacedColumn=[KmsEncryptionPlugin] Result column '{}' has the name of an encrypted column, but the plugin can't tell which column it holds, so it can't decrypt it. List the columns instead of *, and run one SELECT per execute when it reads encrypted columns. +KmsEncryptionPlugin.UnsafeComparison=[KmsEncryptionPlugin] Refusing a statement that compares encrypted column '{}' with a parameter where a comparison that never matches would still select rows, for example with <>, <, BETWEEN, NOT IN, NOT LIKE or NOT, or in an outer join's ON. An encrypted parameter never equals a stored value, so the statement would match every row or arbitrary rows. Compare the column only by =, IN or LIKE, joined to the rest of the condition by AND or OR. +KmsEncryptionPlugin.UnsupportedAlgorithm=[KmsEncryptionPlugin] Encrypted column '{}' names algorithm {}, which the plugin doesn't support. Supported algorithms: {}. +KmsEncryptionPlugin.UnsupportedDriver=[KmsEncryptionPlugin] The kms_encryption plugin does not support driver '{}'; use psycopg or mysql-connector-python. +KmsEncryptionPlugin.UnusableColumn=[KmsEncryptionPlugin] Encrypted column '{}' has no usable key_storage row. +MetadataManager.InvalidName=[MetadataManager] encryption_metadata.{} must be UTF-8 text; the driver returned a value of type {} that is not. +MetadataManager.LoadFailed=[MetadataManager] Failed to read the kms_encryption metadata: {} +MetadataManager.RefreshFailed=[MetadataManager] Failed to refresh the kms_encryption metadata cache: {} +MetadataManager.Refreshed=[MetadataManager] Refreshed the kms_encryption metadata cache with {} column configuration(s). +SqlAnalyzer.InsertSourceNotValues=[SqlAnalyzer] The source of the INSERT is not a VALUES list. +SqlAnalyzer.SqlglotMissing=[SqlAnalyzer] The KMS encryption plugin needs the 'sqlglot' package. Run pip install 'aws-advanced-python-wrapper[encryption]' to install it. +SqlAnalyzer.UnnamedTable=[SqlAnalyzer] The parsed table has no name. +SqlTokenizer.NoToken=[SqlTokenizer] The SQL token pattern matched no token. +SqlTokenizer.NoTokenPattern=[SqlTokenizer] The driver dialect '{}' has no SQL token pattern, so the kms_encryption plugin can't read its statements. +SqlTokenizer.SqlNotStr=[SqlTokenizer] The SQL must be a str, not '{}'. +TypeMarker.UnknownMarker=[TypeMarker] Unknown type marker: '{}'. diff --git a/aws_advanced_python_wrapper/utils/properties.py b/aws_advanced_python_wrapper/utils/properties.py index 7787e729f..dd7c04a71 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -218,6 +218,88 @@ class WrapperProperties: 60 * 60 * 24 * 365, ) + # KMS encryption plugin. + ENCRYPTION_KMS_REGION = WrapperProperty( + "encryption_kms_region", + "AWS region for KMS calls made by the kms_encryption plugin. Falls back to the AWS_REGION, then " + "AWS_DEFAULT_REGION environment variable; the connection is rejected if none is set.", + ) + ENCRYPTION_KMS_ENDPOINT = WrapperProperty( + "encryption_kms_endpoint", "Endpoint URL override for KMS." + ) + ENCRYPTION_ALLOWED_MASTER_KEY_ARNS = WrapperProperty( + "encryption_allowed_master_key_arns", + "The KMS master keys the kms_encryption plugin may use, as a comma-separated string or a list. Required by " + "the plugin. Each entry must match a key_storage.master_key_arn value exactly; a data key naming any other " + "master key, or none, is refused before KMS is called.", + ) + ENCRYPTION_METADATA_SCHEMA = WrapperProperty( + "encryption_metadata_schema", + "Schema (database, on MySQL) holding the encryption_metadata and key_storage tables.", + "encrypt", + ) + ENCRYPTION_METADATA_CACHE_ENABLED = WrapperProperty( + "encryption_metadata_cache_enabled", + "Cache the kms_encryption metadata in memory instead of querying it per statement.", + True, + ) + ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC = WrapperProperty( + "encryption_metadata_cache_expiration_sec", + "How long cached kms_encryption metadata stays valid, in seconds.", + 3600.0, + ) + ENCRYPTION_METADATA_CACHE_REFRESH_INTERVAL_SEC = WrapperProperty( + "encryption_metadata_cache_refresh_interval_sec", + "How often the kms_encryption metadata is refreshed in the background, in seconds. 0 disables it.", + 300.0, + ) + ENCRYPTION_DATA_KEY_CACHE_ENABLED = WrapperProperty( + "encryption_data_key_cache_enabled", + "Cache decrypted data keys in memory to avoid a KMS Decrypt call for every encrypted value written or read.", + True, + ) + ENCRYPTION_DATA_KEY_CACHE_MAX_SIZE = WrapperProperty( + "encryption_data_key_cache_max_size", + "Maximum number of decrypted data keys held in memory.", + 1000, + ) + ENCRYPTION_DATA_KEY_CACHE_EXPIRATION_SEC = WrapperProperty( + "encryption_data_key_cache_expiration_sec", + "How long a decrypted data key stays cached, in seconds.", + 300.0, + ) + ENCRYPTION_KEY_MANAGEMENT_MAX_RETRIES = WrapperProperty( + "encryption_key_management_max_retries", + "Maximum number of retries for throttled or failed KMS calls. Creating a master key is retried only " + "when KMS did not act on the request.", + 3, + ) + ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC = WrapperProperty( + "encryption_key_management_retry_backoff_base_sec", + "Base delay in seconds for the exponential backoff between KMS retries.", + 0.1, + ) + ENCRYPTION_AUDIT_LOGGING_ENABLED = WrapperProperty( + "encryption_audit_logging_enabled", + "Accepted by the kms_encryption plugin, which writes no audit records; when True, the plugin logs one " + "warning per connection saying so.", + False, + ) + ENCRYPTION_RETURN_UNVERIFIED_DATA = WrapperProperty( + "encryption_return_unverified_data", + "Do not enable in production. On read, return a value as stored instead of raising when it cannot be " + "confirmed to be this column's encrypted data: too short to be a payload, or a failed HMAC. Intended " + "only for reading data written before the column was encrypted (used by the kms_encryption plugin).", + False, + ) + ENCRYPTION_FAIL_ON_UNMAPPED_PARAMETER = WrapperProperty( + "encryption_fail_on_unmapped_parameter", + "Refuse a statement with parameters on a table with encrypted columns when the kms_encryption plugin can't pair " + "each parameter with its column, such as an INSERT without a column list. False runs it unchanged, with a " + "warning when it writes; a COPY the plugin can't parse that can write the table is still refused.", + True, + ) + DIALECT = WrapperProperty( "wrapper_dialect", "A unique identifier for the supported database dialect." ) @@ -936,18 +1018,21 @@ def log_properties(props: Properties): return f"\n{props}" - _SECRET_NAME_MARKERS = ("password", "passwd") + _SECRET_NAME_MARKERS = ("password", "passwd", "pwd", "secret", "token", "credential") @staticmethod - def _is_secret_property(key: str) -> bool: + def is_secret_property(key: str) -> bool: lowered = key.lower() + # The allowed key ARNs name the AWS account. + if lowered in ("key", WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name): + return True return any(marker in lowered for marker in PropertiesUtils._SECRET_NAME_MARKERS) @staticmethod def mask_properties(props: Properties) -> Properties: masked_properties = Properties(props.copy()) for key in masked_properties: - if PropertiesUtils._is_secret_property(key): + if PropertiesUtils.is_secret_property(key): masked_properties[key] = "***" return masked_properties diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 07fc9722f..e16bf33bc 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -15,7 +15,7 @@ from __future__ import annotations from typing import (TYPE_CHECKING, Any, Callable, Iterator, List, Optional, - Type, TypeVar, Union) + Type, TypeVar, Union, cast) from aws_advanced_python_wrapper.plugin_service import ( PluginManager, PluginServiceImpl, PluginServiceManagerContainer) @@ -400,15 +400,20 @@ def close(self) -> None: def callproc(self, *args: Any, **kwargs: Any): return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_CALLPROC, - lambda: self.target_cursor.callproc(**kwargs), *args, **kwargs) + lambda: self.target_cursor.callproc(*args, **kwargs), *args, **kwargs) def execute( self, *args: Any, **kwargs: Any ) -> AwsWrapperCursor: - return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTE, - lambda: self.target_cursor.execute(*args, **kwargs), *args, **kwargs) + # The plugin manager calls the driver with the statement's arguments, + # which a plugin may have replaced. + result = self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: self.target_cursor.execute(*a, **kw), *args, **kwargs) + # psycopg returns the driver cursor itself; return this cursor instead, + # so a chained fetch goes through the plugins. + return self if result is self.target_cursor else result def executemany( self, @@ -416,9 +421,39 @@ def executemany( **kwargs: Any ) -> None: self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTEMANY, - lambda: self.target_cursor.executemany(*args, **kwargs), + lambda *a, **kw: self.target_cursor.executemany(*a, **kw), *args, **kwargs) + def copy(self, *args: Any, **kwargs: Any) -> Any: + # psycopg's copy() returns a context manager, which sends nothing before it is entered. + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_COPY, + lambda: self.target_cursor.copy(*args, **kwargs), # type: ignore[attr-defined] + *args, **kwargs) + + # psycopg's stream(), results() and set_result(), and mysql-connector's fetchsets() and stored_results(). As with + # copy(), the plugins wrap only the call that returns the generator or cursor; reads from it go to the driver. + def stream(self, *args: Any, **kwargs: Any) -> Any: + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_STREAM, + lambda: self.target_cursor.stream(*args, **kwargs), # type: ignore[attr-defined] + *args, **kwargs) + + def results(self) -> Any: + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_RESULTS, + lambda: self.target_cursor.results()) # type: ignore[attr-defined] + + def set_result(self, index: int) -> Any: + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_SET_RESULT, + lambda: self.target_cursor.set_result(index), # type: ignore[attr-defined] + index) + + def fetchsets(self) -> Any: + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_FETCHSETS, + lambda: self.target_cursor.fetchsets()) # type: ignore[attr-defined] + + def stored_results(self) -> Any: + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_STORED_RESULTS, + lambda: self.target_cursor.stored_results()) # type: ignore[attr-defined] + def nextset(self) -> bool: return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_NEXTSET, lambda: self.target_cursor.nextset()) @@ -436,7 +471,44 @@ def fetchall(self) -> List[Any]: lambda: self.target_cursor.fetchall()) def __iter__(self) -> Iterator[Any]: - return self.target_cursor.__iter__() + # The plugins subscribed to Cursor.__iter__ run once per loop, not once + # per row: such a plugin returns an iterator over the driver's (one that + # changes each row, say). The driver's iterator still fetches the rows, + # so a server-side cursor keeps fetching a page at a time. + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_ITER, + lambda: iter(self.target_cursor)) + + def __next__(self) -> Any: + # A loop doesn't call this method: __iter__ returns the driver's iterator. + # The plugins subscribed to Cursor.__next__ run for each row. A driver cursor + # that is its own iterator (psycopg 3.3 and later) gives the row with its own + # next(), so a server-side cursor continues the page a loop read ahead; any + # other driver cursor gives it with fetchone. + target = self.target_cursor + rows = iter(target) + if cast("object", rows) is not target: + row = self._plugin_manager.execute(target, DbApiMethod.CURSOR_NEXT, lambda: target.fetchone()) + if row is None: + raise StopIteration + return row + # A row can itself be None (psycopg's scalar_row on a NULL), so the rows end + # only when the driver's next() ends them or a plugin returns None without + # reading a row. The plugins see the end as None, as from fetchone. + read = False + + def next_row() -> Any: + nonlocal read + try: + row = next(rows) + except StopIteration: + return None + read = True + return row + + row = self._plugin_manager.execute(target, DbApiMethod.CURSOR_NEXT, next_row) + if row is None and not read: + raise StopIteration + return row def setinputsizes(self, sizes: Any) -> None: return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_SETINPUTSIZES, diff --git a/docs/README.md b/docs/README.md index 63ed2edaa..40027d502 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,6 +28,7 @@ - [Simple Read Write Splitting Plugin](using-the-python-wrapper/using-plugins/UsingTheSimpleReadWriteSplittingPlugin.md) - [Fastest Response Strategy Plugin](using-the-python-wrapper/using-plugins/UsingTheFastestResponseStrategyPlugin.md) - [Connection Lifetime Plugin](using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md) + - [KMS Encryption Plugin](using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md) - [Host Availability Strategy](using-the-python-wrapper/HostAvailabilityStrategy.md) - [Development Guide](./development-guide/DevelopmentGuide.md) - [Setup](./development-guide/DevelopmentGuide.md#setup) diff --git a/docs/development-guide/IntegrationTests.md b/docs/development-guide/IntegrationTests.md index 3e018297b..52779c4e4 100644 --- a/docs/development-guide/IntegrationTests.md +++ b/docs/development-guide/IntegrationTests.md @@ -64,9 +64,36 @@ unset FILTER # Done testing the IAM tests, unset FILTER 6. In the git bash terminal, navigate to the project root directory and execute a gradle integration test task, e.g.: `./gradlew test-pg-aurora`. Other tasks are defined in `tests/integration/host/build.gradle.kts`. +### Existing clusters and leftovers + +When `REUSE_RDS_DB` isn't `true` and `RDS_DB_NAME` names a cluster that exists, an Aurora run fails before it adds the rule for the runner's IP or makes a cluster. +Then set `REUSE_RDS_DB=true` to use that cluster, or set `RDS_DB_NAME` to a new name. +An Aurora run adds an all-traffic rule for the runner's IP to the `default` security group, described `Test run at