From 80d9a0ac734bcd949ec6683d5fbef77da278be24 Mon Sep 17 00:00:00 2001 From: JuanLeee Date: Thu, 12 Nov 2026 03:04:06 -0700 Subject: [PATCH 1/6] feat: plugin call context for cursor execute arguments (#1330) --- CHANGELOG.md | 6 + aws_advanced_python_wrapper/driver_dialect.py | 4 +- .../encryption/__init__.py | 13 + .../encryption/algorithm.py | 68 ++ .../encryption/buffers.py | 34 + .../encryption/config.py | 179 ++++ .../encryption/connection_source.py | 113 +++ .../encryption/data_key_cache.py | 228 +++++ .../encryption/encryption_service.py | 529 +++++++++++ .../encryption/key_management_utility.py | 270 ++++++ .../encryption/key_manager.py | 445 +++++++++ .../encryption/metadata_manager.py | 302 ++++++ .../encryption/models.py | 158 ++++ .../encryption/sql_dialect.py | 162 ++++ .../encryption/type_marker.py | 113 +++ aws_advanced_python_wrapper/errors.py | 119 ++- .../mysql_driver_dialect.py | 1 + aws_advanced_python_wrapper/pep249_methods.py | 19 +- .../pg_driver_dialect.py | 1 + aws_advanced_python_wrapper/plugin.py | 12 + aws_advanced_python_wrapper/plugin_service.py | 111 ++- .../read_write_splitting_plugin.py | 1 + ...dvanced_python_wrapper_messages.properties | 34 + .../utils/properties.py | 75 ++ aws_advanced_python_wrapper/wrapper.py | 50 +- docs/development-guide/LoadablePlugins.md | 12 + docs/development-guide/PluginService.md | 38 + poetry.lock | 222 ++++- pyproject.toml | 13 + .../encryption/conformance_vectors.json | 122 +++ .../generate_conformance_vectors.py | 123 +++ tests/unit/test_connection.py | 375 +++++++- tests/unit/test_connection_source.py | 154 ++++ tests/unit/test_data_key_cache.py | 275 ++++++ tests/unit/test_encryption_config.py | 253 +++++ tests/unit/test_encryption_conformance.py | 126 +++ tests/unit/test_encryption_import_guard.py | 132 +++ tests/unit/test_encryption_service.py | 864 ++++++++++++++++++ tests/unit/test_key_management_utility.py | 320 +++++++ tests/unit/test_key_manager.py | 847 +++++++++++++++++ tests/unit/test_metadata_manager.py | 517 +++++++++++ tests/unit/test_plugin_manager.py | 387 +++++++- .../unit/test_psycopg3_parity_passthroughs.py | 5 +- tests/unit/test_sql_alchemy_driver_dialect.py | 27 + tests/unit/test_type_marker.py | 72 ++ 45 files changed, 7902 insertions(+), 29 deletions(-) create mode 100644 aws_advanced_python_wrapper/encryption/__init__.py create mode 100644 aws_advanced_python_wrapper/encryption/algorithm.py create mode 100644 aws_advanced_python_wrapper/encryption/buffers.py create mode 100644 aws_advanced_python_wrapper/encryption/config.py create mode 100644 aws_advanced_python_wrapper/encryption/connection_source.py create mode 100644 aws_advanced_python_wrapper/encryption/data_key_cache.py create mode 100644 aws_advanced_python_wrapper/encryption/encryption_service.py create mode 100644 aws_advanced_python_wrapper/encryption/key_management_utility.py create mode 100644 aws_advanced_python_wrapper/encryption/key_manager.py create mode 100644 aws_advanced_python_wrapper/encryption/metadata_manager.py create mode 100644 aws_advanced_python_wrapper/encryption/models.py create mode 100644 aws_advanced_python_wrapper/encryption/sql_dialect.py create mode 100644 aws_advanced_python_wrapper/encryption/type_marker.py create mode 100644 tests/unit/resources/encryption/conformance_vectors.json create mode 100644 tests/unit/resources/encryption/generate_conformance_vectors.py create mode 100644 tests/unit/test_connection_source.py create mode 100644 tests/unit/test_data_key_cache.py create mode 100644 tests/unit/test_encryption_config.py create mode 100644 tests/unit/test_encryption_conformance.py create mode 100644 tests/unit/test_encryption_import_guard.py create mode 100644 tests/unit/test_encryption_service.py create mode 100644 tests/unit/test_key_management_utility.py create mode 100644 tests/unit/test_key_manager.py create mode 100644 tests/unit/test_metadata_manager.py create mode 100644 tests/unit/test_type_marker.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 03eec8a12..74d6db5f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] ### :magic_wand: Added +* 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)) +### :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 * Python 3.14 support. ([PR #1252](https://github.com/aws/aws-advanced-python-wrapper/pull/1252)) 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/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..c9b63bf2a --- /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 Any, Union + +BytesLike = Union[bytes, bytearray, memoryview] + + +def wipe(buffer: Any) -> 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..ac3638591 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/config.py @@ -0,0 +1,179 @@ +# 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 os +import re +from dataclasses import dataclass, field +from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Type, + TypeVar) + +from aws_advanced_python_wrapper.errors import EncryptionConfigError +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_]*") + +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 _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] = field(default_factory=frozenset) + kms_endpoint: Optional[str] = None + metadata_schema: str = "encrypt" + metadata_cache_enabled: bool = True + metadata_cache_expiration_sec: float = 3600.0 + metadata_cache_refresh_interval_sec: float = 300.0 + data_key_cache_enabled: bool = True + data_key_cache_max_size: int = 1000 + data_key_cache_expiration_sec: float = 300.0 + key_management_max_retries: int = 3 + key_management_retry_backoff_base_sec: float = 0.1 + audit_logging_enabled: bool = False + return_unverified_data: bool = False + + def __post_init__(self) -> None: + if not self.kms_region or not self.kms_region.strip(): + raise EncryptionConfigError(Messages.get("EncryptionConfig.MissingRegion")) + # 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 + # A blank value at one level falls through to the next. + region = (_stripped(wp.ENCRYPTION_KMS_REGION.get(props)) + or _stripped(os.environ.get("AWS_REGION")) + or _stripped(os.environ.get("AWS_DEFAULT_REGION"))) + config = cls( + kms_region=region, + kms_endpoint=wp.ENCRYPTION_KMS_ENDPOINT.get(props), + # 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)), + 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), + ) + + 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 _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.""" + 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..78c382f10 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/connection_source.py @@ -0,0 +1,113 @@ +# 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. + +"""Where the key and metadata layer gets a connection to run its SQL on.""" + +from __future__ import annotations + +from contextlib import contextmanager +from threading import local +from typing import (TYPE_CHECKING, Any, ContextManager, Iterator, Optional, + Protocol) + +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.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 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 + if conn is not None: + 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: + 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 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..8aeb7eb0b --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/data_key_cache.py @@ -0,0 +1,228 @@ +# 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 collections import OrderedDict +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 + +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 _Entry: + __slots__ = ("data_key", "expires_at") + + def __init__(self, data_key: bytearray, expires_at: float): + self.data_key = data_key + self.expires_at = expires_at + + def __repr__(self) -> str: + return f"_Entry(data_key='[REDACTED]', expires_at={self.expires_at!r})" + + +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 wrapper's shared storage service is not used here, because data keys + need a bounded size with oldest-first eviction. Their bytes are zeroed when + they leave 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: OrderedDict[str, _Entry] = OrderedDict() + 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 enabled(self) -> bool: + return self._enabled + + @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 + entry = self._entries.get(key) + if entry is None: + self._misses += 1 + return None + if entry.expires_at <= time.monotonic(): + del self._entries[key] + wipe(entry.data_key) + self._misses += 1 + return None + self._hits += 1 + return bytearray(entry.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 + entry = _Entry(bytearray(data_key), time.monotonic() + self._ttl_sec) + with self._lock: + if self._closed: + wipe(entry.data_key) + return + self._discard(key) + while len(self._entries) >= self._max_size: + _, oldest = self._entries.popitem(last=False) + wipe(oldest.data_key) + self._evictions += 1 + self._entries[key] = entry + + def remove(self, key: str) -> None: + with self._lock: + self._discard(key) + + def clear(self) -> None: + """Zero and drop every cached data key.""" + DataKeyCache._wipe_all(self._entries, self._lock) + + def remove_expired(self) -> int: + """Drop every expired entry. Returns the number removed.""" + now = time.monotonic() + with self._lock: + expired = [k for k, e in self._entries.items() if e.expires_at <= now] + for k in expired: + self._discard(k) + return len(expired) + + 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. + entry = self._entries.pop(key, None) + if entry is not None: + wipe(entry.data_key) + + @staticmethod + def _wipe_all(entries: OrderedDict[str, _Entry], lock: Lock) -> None: + with lock: + for entry in entries.values(): + wipe(entry.data_key) + entries.clear() + + @staticmethod + def _release(entries: OrderedDict[str, _Entry], 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. + DataKeyCache._wipe_all(entries, lock) + 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: # pragma: no cover - defensive + 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..8738e49ad --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/encryption_service.py @@ -0,0 +1,529 @@ +# 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 + +try: + from cryptography.exceptions import InvalidTag + from cryptography.hazmat.primitives.ciphers.aead import AESGCM +except ModuleNotFoundError as e: # pragma: no cover - exercised by the import-guard test + # 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( + "The KMS encryption plugin needs the 'cryptography' package. " + "Install it with: pip install 'aws-advanced-python-wrapper[encryption]'") 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_MILLIS = -((_EPOCH - datetime.min.replace(tzinfo=timezone.utc)) // _MILLISECOND) +_MAX_MILLIS = (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) + + # ---- public API ---- + + @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( + f"Encrypted data is too short: {len(data)} bytes, " + f"expected at least {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( + "Integrity check failed: the value was modified, was never encrypted, " + "or was signed with a different HMAC key", + 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) + + # ---- serialization ---- + + @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(f"Unsupported type marker: {marker!r}") + 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( + f"Cannot write a value of type {type(value).__name__} as {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("BYTE_ARRAY needs a bytes-like value") + 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( + "Integer value exceeds the signed 64-bit range", 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("BOOLEAN needs a bool") + 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( + "Cannot encrypt a non-finite Decimal", 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( + f"Cannot write a value of type {type(value).__name__} as LOCAL_DATE_TIME", + data_type="LOCAL_DATE_TIME") + cls._require_naive(value, "LOCAL_DATE_TIME") + return cls._utf8_bytes(value.isoformat()) + raise EncryptionFailedError( # pragma: no cover - serialize_value checks the marker first + f"Unsupported type marker: {marker!r}") + + @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( + f"Unsupported type marker: {marker!r}", data_type=str(marker) + ) + raise TypeConversionError( + f"Failed to deserialize {TypeMarker.name_for(failed_marker) or failed_marker}", + data_type=TypeMarker.name_for(failed_marker), + ) + + # ---- AES-GCM ---- + + @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: # pragma: no cover - cryptography rarely fails here + raise EncryptionFailedError( + f"Failed to encrypt value: {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( + "Failed to decrypt value: the authentication tag does not match this data key", + algorithm=algorithm, data_type=TypeMarker.name_for(marker), + ) from e + + # ---- helpers ---- + + @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( + f"Cannot convert {source_name} to {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( + f"Data key must be {expected} bytes for {algorithm}, got {got!r}", + algorithm=algorithm, + ) + + @classmethod + def _validate_hmac_key(cls, hmac_key: BytesLike) -> None: + if not isinstance(hmac_key, (bytes, bytearray, memoryview)) or len(hmac_key) == 0: + raise InvalidKeyError("An HMAC key is required to protect encrypted values") + + @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( + f"A valid key id is required to tag an encrypted value, got {key_id!r}" + ) + + @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( + f"Cannot write a timezone-aware value as {marker_name}", data_type=marker_name) + + @classmethod + def _expect_length(cls, data: bytes, length: int, marker: int) -> bytes: + if len(data) != length: + raise TypeConversionError( + f"Expected {length} bytes for {TypeMarker.name_for(marker)}, got {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( + "Cannot encrypt a string with no UTF-8 form", 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(f"{marker_name} needs a date or datetime") + 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_MILLIS: + # Rounding up past the last representable millisecond (for example + # an aware datetime.max, a common "never" value) keeps that + # millisecond. + millis = _MAX_MILLIS + if not _MIN_MILLIS <= millis <= _MAX_MILLIS: + # A UTC offset put the instant outside what a datetime can hold, + # so it could not be read back. + raise EncryptionFailedError( + "In UTC, the value is outside the range a datetime can represent", 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..89017e1c2 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/key_management_utility.py @@ -0,0 +1,270 @@ +# 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 typing import TYPE_CHECKING, Any, List, Optional, cast + +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 \ + CallerConnectionSource +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.models import (KeyMetadata, + mask_arn, + mask_arns_in_text) +from aws_advanced_python_wrapper.encryption.sql_dialect import (SqlDialect, + execute, + fetch_rows) +from aws_advanced_python_wrapper.errors import KeyManagementError +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 aws_advanced_python_wrapper.encryption.config import EncryptionConfig + +logger = Logger(__name__) + + +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. Each + 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. + + 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-" + + def __init__(self, connection: Any, kms_client: Any, config: EncryptionConfig, + *, engine: Optional[str] = None): + """ + :param engine: ``"postgresql"`` or ``"mysql"``. Inferred from + ``connection`` when omitted. + """ + if connection is None or kms_client is None or config is None: + raise ValueError(Messages.get("KeyManagementUtility.MissingArgument")) + self._sql = SqlDialect.for_name(engine) if engine else SqlDialect.for_connection(connection) + self._connections = CallerConnectionSource(connection) + self._kms = kms_client + self._config = config + self._schema = config.metadata_schema # interpolated into every statement below + # The utility never decrypts a data key, so there is nothing to cache. + self._key_manager = KeyManager(kms_client, self._connections, self._sql, 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._sql, 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), mask_arns_in_text(str(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="INITIALIZE_COLUMN") + 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 + if not EncryptionAlgorithm.is_supported(algorithm): + raise EncryptionAlgorithm.unsupported(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._sql.upsert_clause(("table_name", "column_name"), ("encryption_algorithm", "key_id"), + extra_assignments=("updated_at = CURRENT_TIMESTAMP",))) + self._run("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 a new data key. New writes use it; values + written with the previous key stay readable, because each payload + records its ``key_storage.id`` and the old row is kept. + + 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) + 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)) + + 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="ROTATE_DATA_KEY") + 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="ROTATE_DATA_KEY") + + 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._sql.equals} %s AND column_name {self._sql.equals} %s") + if self._run("UPDATE_ENCRYPTION_METADATA", sql, (key_storage_id, table_name, column_name)) == 0: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NotEncrypted", table_name, column_name), + operation="ROTATE_DATA_KEY") + logger.info("KeyManagementUtility.RotatedDataKey", table_name, column_name, current.key_id, key_storage_id) + return key_storage_id + + 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._sql.equals} %s AND column_name {self._sql.equals} %s") + removed = self._run("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._sql.equals} %s ORDER BY table_name, column_name") + try: + with self._connections.connection() as conn: + rows = fetch_rows(conn, sql, (key_storage_id,)) + except Exception as e: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", + "SELECT_COLUMNS_USING_KEY", e), + operation="SELECT_COLUMNS_USING_KEY") from e + return [f"{r['table_name']}.{r['column_name']}" for r in rows] + + 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) + + # ---- internals ---- + + 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: str, sql: str, params: Any) -> int: + try: + with self._connections.connection() as conn: + return execute(conn, sql, params) + except Exception as e: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", operation, e), + operation=operation) from e + + @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..6c6934d0c --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/key_manager.py @@ -0,0 +1,445 @@ +# 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.models import (DEFAULT_KEY_SPEC, + KeyMetadata, + mask_arn, + mask_arns_in_text) +from aws_advanced_python_wrapper.encryption.sql_dialect import (execute, + fetch_rows) +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.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.sql_dialect import SqlDialect + +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. They are installed 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 + + +@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. + """ + + 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, sql_dialect: SqlDialect, + config: EncryptionConfig, data_key_cache: DataKeyCache, + *, sleep: Callable[[float], None] = time.sleep): + self._kms = kms_client + self._connections = connection_source + self._sql = sql_dialect + self._config = config + self._cache = data_key_cache + self._sleep = sleep + + @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) + + # ---- data keys ---- + + 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_arn) + if encrypted_data_key is None or not encrypted_data_key.strip(): + raise InvalidKeyMetadataError( + Messages.get("KeyManager.MissingEncryptedDataKey"), operation="DECRYPT_DATA_KEY") + + 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="DECRYPT_DATA_KEY") + + # 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("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_arn) + key_spec = EncryptionAlgorithm.data_key_spec(algorithm) + response = self._call_kms( + "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="GENERATE_DATA_KEY") + 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") + + # ---- master keys ---- + + 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("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( + "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) + + # ---- key_storage ---- + + 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="STORE_KEY_METADATA") + + 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._sql.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 = self._describe_failure(e) + if failure is not None: + raise KeyManagementError( + Messages.get_formatted("KeyManager.StoreKeyMetadataFailed", failure), operation="STORE_KEY_METADATA") + 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._sql.equals} %s") + try: + with self._connections.connection() as conn: + rows = fetch_rows(conn, sql, (key_storage_id,)) + except Exception as e: + raise KeyManagementError( + Messages.get_formatted("KeyManager.ReadKeyMetadataFailed", e), + operation="GET_KEY_METADATA") from e + 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._sql.equals} %s") + try: + with self._connections.connection() as conn: + execute(conn, sql, (key_uuid,)) + except Exception as e: + logger.debug("KeyManager.TouchKeyFailed", key_uuid, e) + + # ---- internals ---- + + def _authorize(self, master_key_arn: Optional[str]) -> None: + 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="AUTHORIZE_MASTER_KEY") + + @staticmethod + def _describe_failure(error: Exception) -> str: + """The exception type plus any SQLSTATE / errno the driver reports. + Neither carries statement text, unlike the error message.""" + 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 _call_kms(self, operation: str, 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: + # KMS's error text can name the master key and the caller's + # role session. The error, kept as __cause__, keeps that text. + if attempt >= max_retries or not is_retryable(e): + raise KeyManagementError( + Messages.get_formatted("KeyManager.KmsCallFailed", operation, attempt + 1, + mask_arns_in_text(str(e))), + operation=operation) from e + delay = self._backoff_sec(attempt) + logger.debug("KeyManager.Retrying", operation, attempt + 1, max_retries + 1, delay, + mask_arns_in_text(str(e))) + 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/metadata_manager.py b/aws_advanced_python_wrapper/encryption/metadata_manager.py new file mode 100644 index 000000000..1b2934988 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -0,0 +1,302 @@ +# 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.models import ( + ColumnEncryptionConfig, KeyMetadata) +from aws_advanced_python_wrapper.encryption.sql_dialect import fetch_rows +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.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.connection_source import \ + ConnectionSource + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + +logger = Logger(__name__) + +_KS_PREFIX = "ks_" + + +class _Snapshot(NamedTuple): + 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. + + 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, sql_dialect: SqlDialect, config: EncryptionConfig): + self._connections = connection_source + self._sql = sql_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) + + # ---- lifecycle ---- + + 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() + + # ---- lookups ---- + + 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) + if snapshot is not None: + return snapshot.columns.get((table_name, column_name)) + rows = self._query( + f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s AND em.column_name {self._sql.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(table_name, ()) + rows = self._query(f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s", + (table_name,), table_name=table_name) + return tuple(self._to_column_config(row) for row in rows) + + @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 + + # ---- internals ---- + + 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) + by_table: Dict[str, List[ColumnEncryptionConfig]] = {} + for config in columns.values(): + by_table.setdefault(config.table_name, []).append(config) + snapshot = _Snapshot( + MappingProxyType(dict(columns)), + 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(conn, sql, params) + except Exception as e: + raise MetadataError(Messages.get_formatted("MetadataManager.LoadFailed", e), + table_name=table_name, column_name=column_name) from e + + 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._sql.equals} 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=row["table_name"], + column_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 _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..f33d9a1fa --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/models.py @@ -0,0 +1,158 @@ +# 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 +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Mapping, Optional, cast + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm + +if TYPE_CHECKING: + from datetime import datetime + +REDACTED = "[REDACTED]" +DEFAULT_KEY_SPEC = "AES_256" + +# 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'\".,;:!?)\]])") + + +def mask_key_id(value: Optional[str]) -> Optional[str]: + """Keep the first and last four characters of an identifier; one of 8 + characters or fewer becomes ``***``.""" + if value is None: + return None + return f"{value[:4]}***{value[-4:]}" if len(value) > 8 else "***" + + +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. ARNs are identifiers, + not secrets: the messages that quote a KMS error mask the ARNs in its text + with :func:`mask_arns_in_text`, but the KMS error itself, kept as the + ``__cause__``, still shows them.""" + if value is None: + return None + _, sep, key = value.rpartition("/") + return f"arn:aws:kms:***:***:key/{mask_key_id(key) if sep and key else '***'}" + + +def mask_arns_in_text(text: str) -> str: + """Mask the ARNs in ``text`` that name an account, such as those in a + failed KMS call's error message: the master key and, for an access denial, + the caller's role session. A KMS key ARN is masked as :func:`mask_arn` + does; any other ARN keeps only its partition and service. Text without + such an ARN comes back unchanged.""" + return _ARN_IN_TEXT.sub(_mask_matched_arn, 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: + return 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) diff --git a/aws_advanced_python_wrapper/encryption/sql_dialect.py b/aws_advanced_python_wrapper/encryption/sql_dialect.py new file mode 100644 index 000000000..6b28721d8 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_dialect.py @@ -0,0 +1,162 @@ +# 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. + +"""Runs the plugin's own ``encryption_metadata`` / ``key_storage`` SQL. + +Both supported drivers (psycopg and MySQL Connector/Python) use the +``pyformat`` paramstyle, so the SQL is written once with ``%s`` placeholders. +Only a few grammar details differ by engine, and :class:`SqlDialect` holds +them. The wrapper's driver dialects manage connection lifecycle only, which is +why this module exists. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from contextlib import closing +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Sequence + +from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes +from aws_advanced_python_wrapper.errors import EncryptionConfigError +from aws_advanced_python_wrapper.utils.messages import Messages + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + +Row = Dict[str, Any] + + +class SqlDialect(ABC): + """Engine-specific grammar for the plugin's own statements.""" + + name: str = "" + + #: Equality operator used in every comparison the plugin writes. + equals: str = "=" + + @abstractmethod + def upsert_clause(self, conflict_columns: Sequence[str], update_columns: Sequence[str], + extra_assignments: Sequence[str] = ()) -> str: + """The trailing upsert clause for an ``INSERT``: on a conflict over + ``conflict_columns``, overwrite ``update_columns`` from the incoming + row and apply any literal ``extra_assignments``.""" + ... + + @abstractmethod + def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int: + """Run an ``INSERT`` (without ``RETURNING``) and return the generated + ``id``.""" + ... + + @staticmethod + def for_driver_dialect(driver_dialect: DriverDialect) -> SqlDialect: + code = driver_dialect.dialect_code + if code == DriverDialectCodes.PSYCOPG: + return PG + if code == DriverDialectCodes.MYSQL_CONNECTOR_PYTHON: + return MYSQL + raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", code)) + + @staticmethod + def for_connection(conn: Any) -> SqlDialect: + """Infer the engine from a raw psycopg / mysql-connector connection or + an ``AwsWrapperConnection`` wrapping one.""" + target = getattr(conn, "target_connection", conn) + module = type(target).__module__ + if module.startswith("psycopg"): + return PG + if module.startswith("mysql.connector") or module.startswith("_mysql_connector"): + return MYSQL + raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", type(target).__qualname__)) + + @staticmethod + def for_name(name: str) -> SqlDialect: + lowered = name.lower() + if lowered in ("pg", "postgres", "postgresql", "psycopg"): + return PG + if lowered in ("mysql", "mysql-connector", "mysql-connector-python"): + return MYSQL + raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", name)) + + def __repr__(self) -> str: + return f"{type(self).__name__}()" + + +class PgSqlDialect(SqlDialect): + name = "postgresql" + # An unqualified operator resolves through search_path, where a + # user-defined "=" with a closer type match would win. Pin the built-in. + equals = "OPERATOR(pg_catalog.=)" + + 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: Any, sql: str, params: Sequence[Any]) -> int: + with closing(conn.cursor()) as cursor: + cursor.execute(f"{sql} RETURNING id", params) + row = cursor.fetchone() + # A connection opened with a dict-like row factory returns a mapping. + return int(next(iter(row.values())) if isinstance(row, Mapping) else row[0]) + + +class MySqlSqlDialect(SqlDialect): + name = "mysql" + # MySQL has no user-defined operators. + equals = "=" + + 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: Any, sql: str, params: Sequence[Any]) -> int: + with closing(conn.cursor()) as cursor: + cursor.execute(sql, params) + return int(cursor.lastrowid) + + +PG = PgSqlDialect() +MYSQL = MySqlSqlDialect() + + +def fetch_rows(conn: Any, sql: str, params: Sequence[Any] = ()) -> List[Row]: + """Run a query and return its rows as dicts keyed by lower-cased column + name. MySQL reports ``information_schema`` names in upper case on some + versions, so callers never depend on result-key case. + + Rows may 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. + """ + with closing(conn.cursor()) as cursor: + cursor.execute(sql, params) + if cursor.description is None: + return [] + names = [_lower(d[0]) for d in cursor.description] + return [{_lower(k): v for k, v in row.items()} if isinstance(row, Mapping) else dict(zip(names, row)) + for row in cursor.fetchall()] + + +def _lower(name: Any) -> Any: + return name.lower() if isinstance(name, str) else name + + +def execute(conn: Any, sql: str, params: Sequence[Any] = ()) -> int: + """Run a statement and return the affected-row count.""" + with closing(conn.cursor()) as cursor: + cursor.execute(sql, params) + return max(cursor.rowcount, 0) 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..597825718 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/type_marker.py @@ -0,0 +1,113 @@ +# 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 + + +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(f"Unknown type marker: {value!r}") + 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/errors.py b/aws_advanced_python_wrapper/errors.py index 7af9a752e..2355d36c1 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): @@ -73,3 +74,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..e265b934d 100644 --- a/aws_advanced_python_wrapper/mysql_driver_dialect.py +++ b/aws_advanced_python_wrapper/mysql_driver_dialect.py @@ -69,6 +69,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 } diff --git a/aws_advanced_python_wrapper/pep249_methods.py b/aws_advanced_python_wrapper/pep249_methods.py index 0406c1d43..c1d656176 100644 --- a/aws_advanced_python_wrapper/pep249_methods.py +++ b/aws_advanced_python_wrapper/pep249_methods.py @@ -61,19 +61,20 @@ class DbApiMethod(Enum): 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 = (40, "*", 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..63d86dc74 100644 --- a/aws_advanced_python_wrapper/pg_driver_dialect.py +++ b/aws_advanced_python_wrapper/pg_driver_dialect.py @@ -59,6 +59,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 } 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 469303799..a97f723cc 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -45,7 +45,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 @@ -241,6 +244,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: ... @@ -573,6 +593,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 @@ -861,6 +885,36 @@ 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``. 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 + + +# 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): @@ -1067,13 +1121,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) @@ -1083,9 +1142,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 a166a12b5..d99708d40 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 3c5726725..a30656b4c 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 @@ -545,3 +545,37 @@ 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.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 encryption_kms_region, or the AWS_REGION or AWS_DEFAULT_REGION environment variable. +EncryptionConfig.OutOfRange=[EncryptionConfig] The value of {} is out of range: it must be {}. +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.MissingArgument=[KeyManagementUtility] connection, kms_client, and config 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.RequiredArgument=[KeyManagementUtility] {} is required. +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.StatementFailed=[KeyManagementUtility] {} failed: {} +KeyManagementUtility.StoredDataKey=[KeyManagementUtility] Stored a data key for {}.{} as key_storage id {}. +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 {:.3f}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. +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). +SqlDialect.UnsupportedDriver=[SqlDialect] The kms_encryption plugin does not support driver {}; use psycopg or mysql-connector-python. diff --git a/aws_advanced_python_wrapper/utils/properties.py b/aws_advanced_python_wrapper/utils/properties.py index f84b8fbe0..a7e53f67b 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -218,6 +218,81 @@ 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", + "Log an audit record for every key-management, encryption, and decryption operation " + "(used by the kms_encryption plugin).", + 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, + ) + DIALECT = WrapperProperty( "wrapper_dialect", "A unique identifier for the supported database dialect." ) diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 8ad8e7eb4..1a10d88a1 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -405,8 +405,13 @@ def execute( *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, @@ -414,7 +419,7 @@ 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 nextset(self) -> bool: @@ -434,7 +439,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 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/development-guide/LoadablePlugins.md b/docs/development-guide/LoadablePlugins.md index 7ea35af0a..30c529f61 100644 --- a/docs/development-guide/LoadablePlugins.md +++ b/docs/development-guide/LoadablePlugins.md @@ -59,6 +59,15 @@ Plugins can also subscribe to specific [pipelines](./Pipelines.md) by including | [Connection changed notification pipeline](./Pipelines.md#connection-changed-notification-pipeline) | notify_connection_changed | | [Host list changed notification pipeline](./Pipelines.md#host-list-changed-notification-pipeline) | notify_host_list_changed | +A loop over a cursor (`for row in cursor`) calls the plugins subscribed to `Cursor.__iter__` once per loop, not once per row. +Such a plugin calls `execute_func()` to get the target driver's iterator and returns an iterator over it, for example a generator that changes each row. +The driver's iterator fetches the rows after the plugins have returned, so a server-side cursor still fetches a page at a time, and an error raised while fetching a row does not pass through the plugins' `execute` methods. +The asynchronous cursor sends each row of a loop through the plugins as `Cursor.fetchone` instead. + +With psycopg, `cursor.execute()` returns the wrapper's cursor, so a fetch chained onto it, such as `cursor.execute(query).fetchone()`, goes through the plugins as well. +On the synchronous cursor, `next(cursor)` returns the next row through the plugins subscribed to `Cursor.__next__`, once per row. +Such a plugin also runs on the call that ends the rows, where `execute_func()` returns `None`, and should return that `None` unchanged so that `next(cursor)` raises `StopIteration`. + ### Tips on Creating a Custom Plugin A custom plugin can subscribe to all Python methods being executed by setting the Plugin's `subscribed_methods` attribute to `{"*"}`. In this case, the plugin will be active in every workflow. We recommend that you be aware of the performance impact of subscribing to all Python methods, especially if your plugin regularly performs demanding tasks for common Python method calls. @@ -122,6 +131,9 @@ When creating custom plugins, it is important to **avoid** the following bad pra - the plugin should always call the pipeline lambdas (i.e. `connect_func: Callable` or `force_connect_func: Callable`) 4. Running long tasks synchronously: - the Python method calls are executed by all subscribed plugins synchronously; if one plugin runs a long task during the execution it blocks the execution for the other plugins +5. Modifying the arguments a method is called with: + - the objects passed to a plugin's `execute` belong to the caller (its query parameters, for example) and must not be changed + - to send different arguments to the plugins after it and to the target driver, a plugin assigns new ones to the [call context](./PluginService.md#the-call-context) See the following examples for more details: diff --git a/docs/development-guide/PluginService.md b/docs/development-guide/PluginService.md index 3f5eee7e3..60a40a1ae 100644 --- a/docs/development-guide/PluginService.md +++ b/docs/development-guide/PluginService.md @@ -27,6 +27,44 @@ The value belongs to a single connect. `PluginService.connect()` clears it on entry and `set_current_connection()` clears it once a host has been adopted, so a plugin never reads a host left over from an earlier connect. +## The Call Context + +A plugin may need to change the arguments that `Cursor.execute` or `Cursor.executemany` passes to the target driver, for example to replace a parameter value or to rewrite the statement. +The call context covers these two methods only. + +While one of them runs through the plugins, `PluginService.current_call_context` holds the call's arguments as a `PluginCallContext` with two attributes, `args` (a tuple) and `kwargs` (a mapping). +A plugin that changes them **assigns** a new tuple to `args` and a new mapping to `kwargs` before it calls `execute_func`: + +```python +def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + context = self._plugin_service.current_call_context + if context is not None: + context.args, context.kwargs = self._rewrite(args, kwargs) # a new tuple and a new dict + return execute_func() +``` + +The plugins after it in the chain, and the target driver, receive exactly the new arguments, even when they are empty; the plugins before it keep theirs. +Changing `args` or `kwargs` in place is not allowed, and the caller's own objects must never be modified. + +`current_call_context` is set whenever a plugin handles one of these two methods through the wrapper. +A plugin that must change the arguments, rather than one that may, should raise when it finds `None` instead of calling `execute_func` with the arguments unchanged. + +A replacement lasts until the plugin that made it returns. +A plugin before it that calls `execute_func` again starts again from the arguments it saw, so the replacement is made once per run. +The arguments the target driver receives are fixed when the call reaches `DefaultPlugin`, the last plugin in the chain, so a driver call that `socket_timeout` runs on a worker thread sends them even if it starts late. +That covers `DefaultPlugin` only: a plugin that runs `execute_func` on a thread of its own must wait for that call before it returns, since a call that reaches `DefaultPlugin` after the plugin that made a replacement has returned sends the arguments without it. +Such a plugin must also run `execute_func` in a copy of the calling thread's context, for example `executor.submit(contextvars.copy_context().run, execute_func)`, because the plugins after it read `current_call_context` on the thread they run on and find `None` otherwise. + +Each `Cursor.execute` and `Cursor.executemany` call has its own context, a call made from inside a plugin included, and the enclosing call's context is current again when it returns. +Other methods get no context of their own: during a `Cursor.fetchone` called from inside an `execute`, for example, `current_call_context` still returns the enclosing call's context. +So read it only while handling `Cursor.execute` or `Cursor.executemany`. +It is `None` when no such call is running on the thread. + +The context belongs to the calling thread, not to the connection's plugin service. +Another thread sees it only through a copy of the 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. + +The call context is available to synchronous plugins only. + ## Host List Providers The plugin service uses the host list provider to retrieve the most recent host information or topology information about the database. diff --git a/poetry.lock b/poetry.lock index 2364d9b3b..ab2f45c8c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -841,6 +841,120 @@ files = [ {file = "certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae"}, ] +[[package]] +name = "cffi" +version = "2.1.1" +description = "Foreign Function Interface for Python calling C code." +optional = false +python-versions = ">=3.10" +groups = ["main", "dev"] +files = [ + {file = "cffi-2.1.1-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be"}, + {file = "cffi-2.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9"}, + {file = "cffi-2.1.1-cp310-cp310-win32.whl", hash = "sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41"}, + {file = "cffi-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1"}, + {file = "cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12"}, + {file = "cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa"}, + {file = "cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3"}, + {file = "cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0"}, + {file = "cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455"}, + {file = "cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0"}, + {file = "cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf"}, + {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517"}, + {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735"}, + {file = "cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e"}, + {file = "cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a"}, + {file = "cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80"}, + {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e"}, + {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c"}, + {file = "cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6"}, + {file = "cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2"}, + {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b"}, + {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7"}, + {file = "cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac"}, + {file = "cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d"}, + {file = "cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973"}, + {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c"}, + {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb"}, + {file = "cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54"}, + {file = "cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96"}, + {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527"}, + {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13"}, + {file = "cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c"}, + {file = "cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48"}, + {file = "cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836"}, + {file = "cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3"}, + {file = "cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676"}, + {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e"}, + {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f"}, + {file = "cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4"}, + {file = "cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e"}, + {file = "cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5"}, + {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d"}, + {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b"}, + {file = "cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4"}, + {file = "cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399"}, + {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688"}, + {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7"}, + {file = "cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac"}, + {file = "cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960"}, + {file = "cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1"}, + {file = "cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc"}, + {file = "cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6"}, + {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94"}, + {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5"}, + {file = "cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66"}, + {file = "cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3"}, + {file = "cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692"}, + {file = "cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be"}, +] +markers = {main = "extra == \"encryption\" and platform_python_implementation != \"PyPy\"", dev = "platform_python_implementation != \"PyPy\""} + +[package.dependencies] +pycparser = {version = "*", markers = "implementation_name != \"PyPy\""} + [[package]] name = "charset-normalizer" version = "3.4.0" @@ -1115,6 +1229,83 @@ files = [ [package.extras] toml = ["tomli ; python_full_version <= \"3.11.0a6\""] +[[package]] +name = "cryptography" +version = "50.0.2" +description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." +optional = false +python-versions = "!=3.9.0,!=3.9.1,>=3.9" +groups = ["main", "dev"] +files = [ + {file = "cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079"}, + {file = "cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51"}, + {file = "cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93"}, + {file = "cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c"}, + {file = "cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05"}, + {file = "cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e"}, + {file = "cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e"}, + {file = "cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c"}, + {file = "cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c"}, + {file = "cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e"}, + {file = "cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94"}, + {file = "cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452"}, + {file = "cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5"}, +] +markers = {main = "extra == \"encryption\""} + +[package.dependencies] +cffi = {version = ">=2.0.0", markers = "platform_python_implementation != \"PyPy\""} +typing-extensions = {version = ">=4.13.2", markers = "python_full_version < \"3.11.0\""} + +[package.extras] +ssh = ["bcrypt (>=3.1.5)"] + [[package]] name = "debugpy" version = "1.8.22" @@ -2742,6 +2933,32 @@ files = [ {file = "pycodestyle-2.15.0.tar.gz", hash = "sha256:318f5db083869b4c4dad922d0b11124fb27ab181b6730b93371da671e31bd50e"}, ] +[[package]] +name = "pycparser" +version = "3.11" +description = "C parser in Python" +optional = false +python-versions = ">=3.10" +groups = ["main", "dev"] +files = [ + {file = "pycparser-3.11-py3-none-any.whl", hash = "sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80"}, + {file = "pycparser-3.11.tar.gz", hash = "sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc"}, +] +markers = {main = "extra == \"encryption\" and platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version < \"3.13\"", dev = "platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version < \"3.13\""} + +[[package]] +name = "pycparser" +version = "3.12" +description = "C parser in Python" +optional = false +python-versions = ">=3.11" +groups = ["main", "dev"] +files = [ + {file = "pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e"}, + {file = "pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6"}, +] +markers = {main = "extra == \"encryption\" and platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version >= \"3.13\"", dev = "platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version >= \"3.13\""} + [[package]] name = "pydevd-pycharm" version = "263.7307.206" @@ -3965,7 +4182,10 @@ idna = ">=2.0" multidict = ">=4.0" propcache = ">=0.2.1" +[extras] +encryption = ["cryptography"] + [metadata] lock-version = "2.1" python-versions = "^3.10.0" -content-hash = "ef1d83160e6b4eacd82c37e91fa1c66ca9c0a21ac85b476bfbf0972c5d9791c5" +content-hash = "7cd044243bd145b872f30416b3db964cb7cfe39d37c44ad1a3df05b1abe9a88e" diff --git a/pyproject.toml b/pyproject.toml index 4ded4d606..48ad28a84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,6 +46,16 @@ aws-xray-sdk = "^2.15.0" opentelemetry-api = "^1.22.0" opentelemetry-sdk = "^1.22.0" requests = "^2.33.1" +# The KMS Encryption plugin needs this for AES-GCM, which the stdlib lacks. +# It is installed only with the `encryption` extra, so users who don't use the +# plugin don't pick up a native dependency: +# pip install "aws-advanced-python-wrapper[encryption]" +# The import is lazy as well: nothing on the core import path imports it. +cryptography = { version = ">=42.0.0", optional = true } + +[tool.poetry.extras] +# `pip install "aws-advanced-python-wrapper[encryption]"` to use the KMS Encryption plugin. +encryption = ["cryptography"] [tool.poetry.group.dev.dependencies] mypy = "^1.20.2" @@ -63,6 +73,9 @@ aiomysql = ">=0.2" aiohttp = ">=3" boto3-stubs = "^1.43.0" types_aws_xray_sdk = "^2.13.0" +# Non-optional in the dev group so the encryption unit tests run without needing +# to install the `encryption` extra explicitly. +cryptography = ">=42.0.0" [tool.poetry.group.test.dependencies] boto3 = "^1.42.95" diff --git a/tests/unit/resources/encryption/conformance_vectors.json b/tests/unit/resources/encryption/conformance_vectors.json new file mode 100644 index 000000000..75c31c328 --- /dev/null +++ b/tests/unit/resources/encryption/conformance_vectors.json @@ -0,0 +1,122 @@ +{ + "data_key_b64": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", + "hmac_key_b64": "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8=", + "key_id": 7, + "vectors": [ + { + "name": "string", + "marker": 1, + "ciphertext_b64": "XslAWGOdcN33t9PGj/Ad5P2qduJW98IIcAO9D35GFO8AAAAHAQAAAAAAAAAAAAAAAGbZ2bLaDgxGefOoJST14EmSceFvMA==", + "expect": "hello" + }, + { + "name": "unicode", + "marker": 1, + "ciphertext_b64": "r7RX2BhwDQ3/4ji+pOzRQupCqxDM9QEpUhV/L5bNJqIAAAAHAQEBAQEBAQEBAQEBARSig/bBqI7adrHKj2d74NVpKj+1BpQ7PUtA0bg=", + "expect": "café-漢字" + }, + { + "name": "long", + "marker": 3, + "ciphertext_b64": "WtKO+JQ/tvljs2m6wN/20mtP0RjxSgOL9OQ+/AtWav4AAAAHAwICAgICAgICAgICApsoGKTIIjWQjDIWKCI17OeKddqJp0Xvgw==", + "expect": 1234567890123 + }, + { + "name": "double", + "marker": 4, + "ciphertext_b64": "B4A5M6ZEJQZhnd/k0/LgE74ZEkxhxi7r1AiK0AJuwoIAAAAHBAMDAwMDAwMDAwMDA65CHS/7idR4htDh6LqJIRV4KrT1LPgvWg==", + "expect": 3.14159 + }, + { + "name": "bool_t", + "marker": 6, + "ciphertext_b64": "0QKYtGKWTimUZeF5rFkGpcuwB6mRzUyNm713I+0rYacAAAAHBgQEBAQEBAQEBAQEBGUFno4Yz+nLDktDMtW6jjZK", + "expect": true + }, + { + "name": "bool_f", + "marker": 6, + "ciphertext_b64": "Fd2/bfeCseuDMNlQ4wBzKmtZDKAnzpa+be/TPBd7fhMAAAAHBgkJCQkJCQkJCQkJCbOAaSswGIgGR2DJzfBb9MbL", + "expect": false + }, + { + "name": "bytes", + "marker": 14, + "ciphertext_b64": "4qouGFi5vlgvx7Rr7VLCeesTvPJgLaBP1ABPORv0V4cAAAAHDgUFBQUFBQUFBQUFBUw32o7IuuK9V+EU923mD2KtAiyc", + "expect_b64": "AAEC/w==" + }, + { + "name": "decimal", + "marker": 7, + "ciphertext_b64": "EmpCpu9th4vd3tEf2qu5tGBxSZTnWfm/e7kMV3D/JFMAAAAHBwYGBgYGBgYGBgYGBg1q3r1Mm5um410VyuIP4OFlsM5NmnsY75E6", + "expect": "12345.6789" + }, + { + "name": "local_date_time_no_seconds", + "marker": 13, + "ciphertext_b64": "1BOLaYntqR3/P5GfqTTB6HsTEhxZRJgQJJnrcCB3uOwAAAAHDQcHBwcHBwcHBwcHBz1almtCPuXZ9q5HsbBrxa7tcVb6A5KNZFPMDTj2EitF", + "expect_datetime_iso": "2007-12-03T10:15:00" + }, + { + "name": "local_date_time_nanos", + "marker": 13, + "ciphertext_b64": "UTa3QSMzLg1ZyYUYUrL4UimhX3cbz6cHc5wjtJIMvkAAAAAHDQgICAgICAgICAgICBhz6OHAtQTb4GQPqbCnQQ3ZJjOBpPBKW3AgPhnEX+JmSXag1k5jcXP4ga5VPw==", + "expect_datetime_iso": "2007-12-03T10:15:30.123456" + }, + { + "name": "integer", + "marker": 2, + "ciphertext_b64": "eOjLIF5tb1OCcnBTi+h7nxvFOtVd+NmtCGtZU6IxifYAAAAHAgoKCgoKCgoKCgoKCqkiX7oSxf4sLsV4FSb1y5CTV/oI", + "expect": 42 + }, + { + "name": "float", + "marker": 5, + "ciphertext_b64": "/ulkKAJhrDor0stkZ16KM2KKCOd3XQk4t+zX/teATxMAAAAHBQsLCwsLCwsLCwsLC5dOEqHZRC4CFhC5avX7u2WdDKWC", + "expect": 1.5 + }, + { + "name": "date", + "marker": 8, + "ciphertext_b64": "p+uSc2TNIcaP5ruV+NEvf4xjE3RCnApAyQTYDmfn6xEAAAAHCAwMDAwMDAwMDAwMDPSzGmawBxpvykNLvDWPv/5UtW5bmBoPsg==", + "expect_date_iso": "2026-08-11" + }, + { + "name": "time", + "marker": 9, + "ciphertext_b64": "EftLwzjMHEUhv76vaVgWILaZtg9goKRutGtb5+KwC9AAAAAHCQ0NDQ0NDQ0NDQ0NDaKnfgiMSltx4lDj1WEzScuM4/WBYNaOwg==", + "expect_datetime_iso": "1970-01-01T12:30:45.123000+00:00" + }, + { + "name": "timestamp", + "marker": 10, + "ciphertext_b64": "mfjc/A2m/fQoq1EWSSLklbT6uGR9ZvXKP7ClrrXtW1UAAAAHCg4ODg4ODg4ODg4ODrelf6h+tOq93dfcMl1rsXo8Qm9wX/NIww==", + "expect_datetime_iso": "2026-08-11T12:30:45.123000+00:00" + }, + { + "name": "local_date", + "marker": 11, + "ciphertext_b64": "7eeSdnDrnok30SucUVN6pvDCYC6BhA5htaxCRGty5ecAAAAHCw8PDw8PDw8PDw8PD0ckPqE9KQ1scV6pfRRfC+MmsXUEC64BcbUr", + "expect_date_iso": "2007-12-03" + }, + { + "name": "local_time_no_seconds", + "marker": 12, + "ciphertext_b64": "bx61rRIToPxvhAq481GeumDtezr7aFFxQrTVpE9vQrMAAAAHDBAQEBAQEBAQEBAQEKjdzfbcFmPEIYNw6BYON9f9PaeG+w==", + "expect": "10:15" + }, + { + "name": "generic", + "marker": 99, + "ciphertext_b64": "76Xi1+ZYD8ulCnru9AZ0KW3m/kanQLPF6zCHdyNYMfEAAAAHYxEREREREREREREREfQI/dHfxQZ/gEzVTDKr9oQIYpRGSw==", + "expect": "thing" + }, + { + "name": "key_id_high_bit", + "marker": 1, + "key_id": 2147483649, + "ciphertext_b64": "mmb5W6w+PE/QCKtTbxqrVJZNpNJVa6vxVPyecF4rg3CAAAABARISEhISEhISEhISErf4IQifpVL7RuZxPZ6Kthpa8Q==", + "expect": "hi" + } + ] +} diff --git a/tests/unit/resources/encryption/generate_conformance_vectors.py b/tests/unit/resources/encryption/generate_conformance_vectors.py new file mode 100644 index 000000000..8de7bc4da --- /dev/null +++ b/tests/unit/resources/encryption/generate_conformance_vectors.py @@ -0,0 +1,123 @@ +# 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. + +"""Reference encoder for ``conformance_vectors.json``. + +Builds each payload straight from the wire-format spec with raw +``cryptography`` and the standard library. It imports nothing from +``aws_advanced_python_wrapper``, so decrypting its output tests +the wrapper against the spec rather than against itself. + +Each vector uses a fixed IV made of one repeated byte, unique per vector, so +the output is deterministic and can never come from the wrapper's own +encrypt (which draws a random IV). Add a vector with the next unused IV byte, +then regenerate:: + + python tests/unit/resources/encryption/generate_conformance_vectors.py > \\ + tests/unit/resources/encryption/conformance_vectors.json + +``test_encryption_conformance.py`` checks that the committed file matches +this script's output. +""" + +import base64 +import hashlib +import hmac +import json +import struct +import sys +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, List, NamedTuple + +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +DATA_KEY = bytes(range(32)) +HMAC_KEY = bytes(range(32, 64)) +KEY_ID = 7 + +STRING, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, BIG_DECIMAL = 1, 2, 3, 4, 5, 6, 7 +DATE, TIME, TIMESTAMP, LOCAL_DATE, LOCAL_TIME, LOCAL_DATE_TIME, BYTE_ARRAY = 8, 9, 10, 11, 12, 13, 14 +GENERIC = 99 + + +def _millis(iso: str) -> bytes: + instant = datetime.fromisoformat(iso).replace(tzinfo=timezone.utc) + return struct.pack(">q", (instant - datetime(1970, 1, 1, tzinfo=timezone.utc)) // timedelta(milliseconds=1)) + + +class Vector(NamedTuple): + name: str + marker: int + plaintext: bytes + iv_byte: int + expected: Dict[str, Any] + key_id: int = KEY_ID + + +VECTORS: List[Vector] = [ + Vector("string", STRING, b"hello", 0x00, {"expect": "hello"}), + Vector("unicode", STRING, "café-漢字".encode(), 0x01, {"expect": "café-漢字"}), + Vector("long", LONG, struct.pack(">q", 1234567890123), 0x02, {"expect": 1234567890123}), + Vector("double", DOUBLE, struct.pack(">d", 3.14159), 0x03, {"expect": 3.14159}), + Vector("bool_t", BOOLEAN, b"\x01", 0x04, {"expect": True}), + Vector("bool_f", BOOLEAN, b"\x00", 0x09, {"expect": False}), + Vector("bytes", BYTE_ARRAY, b"\x00\x01\x02\xff", 0x05, {"expect_b64": "AAEC/w=="}), + Vector("decimal", BIG_DECIMAL, b"12345.6789", 0x06, {"expect": "12345.6789"}), + Vector("local_date_time_no_seconds", LOCAL_DATE_TIME, b"2007-12-03T10:15", 0x07, + {"expect_datetime_iso": "2007-12-03T10:15:00"}), + Vector("local_date_time_nanos", LOCAL_DATE_TIME, b"2007-12-03T10:15:30.123456789", 0x08, + {"expect_datetime_iso": "2007-12-03T10:15:30.123456"}), + # Markers this wrapper reads but never writes. + Vector("integer", INTEGER, struct.pack(">i", 42), 0x0A, {"expect": 42}), + Vector("float", FLOAT, struct.pack(">f", 1.5), 0x0B, {"expect": 1.5}), + Vector("date", DATE, _millis("2026-08-11T00:00:00"), 0x0C, {"expect_date_iso": "2026-08-11"}), + Vector("time", TIME, _millis("1970-01-01T12:30:45.123"), 0x0D, + {"expect_datetime_iso": "1970-01-01T12:30:45.123000+00:00"}), + Vector("timestamp", TIMESTAMP, _millis("2026-08-11T12:30:45.123"), 0x0E, + {"expect_datetime_iso": "2026-08-11T12:30:45.123000+00:00"}), + Vector("local_date", LOCAL_DATE, b"2007-12-03", 0x0F, {"expect_date_iso": "2007-12-03"}), + Vector("local_time_no_seconds", LOCAL_TIME, b"10:15", 0x10, {"expect": "10:15"}), + Vector("generic", GENERIC, b"thing", 0x11, {"expect": "thing"}), + # The key id is an unsigned 32-bit integer. + Vector("key_id_high_bit", STRING, b"hi", 0x12, {"expect": "hi"}, 0x80000001), +] + + +def build() -> Dict[str, Any]: + vectors = [] + for v in VECTORS: + iv = bytes([v.iv_byte]) * 12 + body = struct.pack(">I", v.key_id) + bytes([v.marker]) + iv + AESGCM(DATA_KEY).encrypt(iv, v.plaintext, None) + payload = hmac.new(HMAC_KEY, body, hashlib.sha256).digest() + body + vector: Dict[str, Any] = {"name": v.name, "marker": v.marker} + if v.key_id != KEY_ID: + vector["key_id"] = v.key_id + vector["ciphertext_b64"] = base64.b64encode(payload).decode("ascii") + vector.update(v.expected) + vectors.append(vector) + return { + "data_key_b64": base64.b64encode(DATA_KEY).decode("ascii"), + "hmac_key_b64": base64.b64encode(HMAC_KEY).decode("ascii"), + "key_id": KEY_ID, + "vectors": vectors, + } + + +def render() -> str: + return json.dumps(build(), indent=2, ensure_ascii=False) + "\n" + + +if __name__ == "__main__": + # Written as UTF-8 bytes, so the non-ASCII vector works on any console. + sys.stdout.buffer.write(render().encode("utf-8")) diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py index 8e5f20684..ebdd9f07c 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -14,7 +14,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Callable, Iterator, List, Optional, Set from unittest.mock import MagicMock, patch import psycopg @@ -23,9 +23,18 @@ if TYPE_CHECKING: from aws_advanced_python_wrapper.pep249 import Connection +from aws_advanced_python_wrapper.default_plugin import DefaultPlugin +from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.plugin import Plugin from aws_advanced_python_wrapper.plugin_service import ( - PluginServiceImpl, PluginServiceManagerContainer) + PluginManager, PluginServiceImpl, PluginServiceManagerContainer) +from aws_advanced_python_wrapper.read_write_splitting_plugin import \ + AbstractReadWriteSplittingPlugin +from aws_advanced_python_wrapper.utils.properties import Properties from aws_advanced_python_wrapper.wrapper import (AwsWrapperConnection, AwsWrapperCursor) @@ -218,3 +227,365 @@ def test_connection_prepare_threshold_and_prepared_max_forward(): wrapper.prepared_max = 100 assert target.prepare_threshold == 99 assert target.prepared_max == 100 + + +class UpperRowsPlugin(Plugin): + """Upper-cases the rows of the methods it subscribes to, and records the methods it handles.""" + + def __init__(self, methods: Set[str], calls: List[str]): + self._methods = methods + self._calls = calls + + @property + def subscribed_methods(self) -> Set[str]: + return self._methods + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + self._calls.append(method_name) + if method_name == "Cursor.__iter__": + return (row.upper() for row in execute_func()) + return execute_func().upper() + + +def _cursor_with_plugins(driver_cursor: Any, plugins: List[Plugin], current_connection: Any = None) -> AwsWrapperCursor: + """A wrapper cursor over driver_cursor whose plugin manager runs the given plugins, then DefaultPlugin.""" + plugin_service = MagicMock() + plugin_service.current_connection = driver_cursor.connection if current_connection is None else current_connection + plugin_service.driver_dialect.get_connection_from_obj.side_effect = lambda obj: obj.connection + plugin_service.driver_dialect.unwrap_connection.side_effect = lambda conn: conn + plugin_service.driver_dialect.execute.side_effect = lambda method_name, func, *args, **kwargs: func() + container = MagicMock() + container.plugin_service = plugin_service + manager = PluginManager.__new__(PluginManager) + manager._container = container + manager._telemetry_factory = MagicMock() + manager._telemetry_in_use = False + manager._function_cache = [None] * (DbApiMethod.ALL.id + 1) + manager._plugins = plugins + [DefaultPlugin(plugin_service, MagicMock())] + return AwsWrapperCursor(MagicMock(), plugin_service, manager, driver_cursor) + + +def test_cursor_loop_runs_the_iter_subscribers_once_per_loop(): + calls: List[str] = [] + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) + # So a route that fetches row by row ends (and fails) instead of looping forever. + driver_cursor.fetchone.return_value = None + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({"Cursor.__iter__"}, calls)]) + + assert [row for row in cursor] == ["A", "B", "C"] + assert calls == ["Cursor.__iter__"] + + +def test_cursor_loop_does_not_run_the_next_subscribers(): + plugin = MagicMock(spec=Plugin) + plugin.subscribed_methods = {"Cursor.__next__"} + plugin.execute.side_effect = lambda target, method_name, execute_func, *args, **kwargs: execute_func() + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) + driver_cursor.fetchone.return_value = None + cursor = _cursor_with_plugins(driver_cursor, [plugin]) + + assert [row for row in cursor] == ["a", "b", "c"] + plugin.execute.assert_not_called() + + +@pytest.mark.parametrize("network_bound", [True, False]) +def test_cursor_loop_without_subscribers_returns_the_driver_iterator(network_bound): + # A method the dialect doesn't count as network-bound skips the pipeline when nothing subscribes to it. + rows = iter(["a", "b"]) + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = rows + cursor = _cursor_with_plugins(driver_cursor, []) + cursor._plugin_service.is_network_bound_method.return_value = network_bound + + assert iter(cursor) is rows + assert list(cursor) == ["a", "b"] + + +def test_cursor_loop_after_a_break_continues_with_the_next_row(): + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({"Cursor.__iter__"}, [])]) + + for first in cursor: + break + + assert first == "A" + assert list(cursor) == ["B", "C"] + assert list(cursor) == [] + + +def test_cursor_loop_over_a_cursor_of_an_old_connection_raises(): + # After failover, say: the connection the driver cursor belongs to is no longer the current one. + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a"]) + cursor = _cursor_with_plugins(driver_cursor, [], current_connection=MagicMock()) + + with pytest.raises(AwsWrapperError): + for _ in cursor: + pass + + +def test_cursor_execute_returns_the_wrapper_cursor_when_the_driver_returns_its_own(): + # psycopg's Cursor.execute returns the cursor, so a fetch chained onto it must go through the plugins too. + calls: List[str] = [] + driver_cursor = MagicMock() + driver_cursor.execute.return_value = driver_cursor + driver_cursor.fetchone.return_value = "row" + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({DbApiMethod.CURSOR_FETCHONE.method_name}, calls)]) + + assert cursor.execute("SELECT 1") is cursor + assert cursor.execute("SELECT 1").fetchone() == "ROW" + assert calls == [DbApiMethod.CURSOR_FETCHONE.method_name] + + +@pytest.mark.parametrize("driver_result", [None, object()]) +def test_cursor_execute_passes_any_other_driver_result_through(driver_result): + # mysql-connector's Cursor.execute returns None. + driver_cursor = MagicMock() + driver_cursor.execute.return_value = driver_result + + assert _cursor_with_plugins(driver_cursor, []).execute("SELECT 1") is driver_result + + +def test_next_on_the_cursor_returns_the_next_row_through_the_next_subscribers(): + # psycopg's Cursor.execute returns the cursor, which is an iterator, so next(cursor.execute(query)) is the first row. + calls: List[str] = [] + driver_cursor = MagicMock() + driver_cursor.execute.return_value = driver_cursor + driver_cursor.fetchone.return_value = "row" + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({DbApiMethod.CURSOR_NEXT.method_name}, calls)]) + + assert next(cursor.execute("SELECT 1")) == "ROW" + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +def test_next_on_an_exhausted_cursor_raises_stop_iteration(): + driver_cursor = MagicMock() + driver_cursor.fetchone.return_value = None + cursor = _cursor_with_plugins(driver_cursor, []) + + with pytest.raises(StopIteration): + next(cursor) + + +def test_next_on_the_cursor_returns_an_empty_row(): + # A query with no columns (SELECT FROM t on PostgreSQL) has empty rows; only None ends the rows. + driver_cursor = MagicMock() + driver_cursor.fetchone.return_value = () + cursor = _cursor_with_plugins(driver_cursor, []) + + assert next(cursor) == () + + +class _ServerSideRows: + """A server-side cursor's result of five rows; each read is a round trip that returns the rows after the server's position.""" + + def __init__(self) -> None: + self.connection = MagicMock() + self.fetches = 0 + self._rows = ["a", "b", "c", "d", "e"] + self._position = 0 + + def _fetch(self, size: int) -> List[str]: + self.fetches += 1 + rows = self._rows[self._position:self._position + size] + self._position += len(rows) + return rows + + def fetchone(self) -> Optional[str]: + rows = self._fetch(1) + return rows[0] if rows else None + + +class _SelfIteratingServerCursor(_ServerSideRows): + """Shaped like psycopg 3.3's ServerCursor: it is its own iterator, and its next() serves a page of 3 rows it read ahead.""" + + def __init__(self) -> None: + super().__init__() + self._page: List[str] = [] + + def __iter__(self) -> _SelfIteratingServerCursor: + return self + + def __next__(self) -> str: + if not self._page: + self._page = self._fetch(3) + if not self._page: + raise StopIteration + return self._page.pop(0) + + +class _GeneratorServerCursor(_ServerSideRows): + """Shaped like psycopg 3.2's ServerCursor: each iter() starts a generator that reads a page of 3 rows at a time; no next().""" + + def __iter__(self) -> Iterator[str]: + while True: + page = self._fetch(3) + yield from page + if len(page) < 3: + return + + +class _LostConnectionError(Exception): + pass + + +class _FetchoneIteratingCursor: + """Shaped like mysql-connector's cursor: iter() calls fetchone for each row, and next() turns a driver error into the end of the rows.""" + + def __init__(self) -> None: + self.connection = MagicMock() + + def fetchone(self) -> Any: + raise _LostConnectionError("Lost connection to the server during query") + + def __iter__(self) -> Iterator[Any]: + return iter(self.fetchone, None) + + def __next__(self) -> Any: + try: + return self.fetchone() + except _LostConnectionError: + raise StopIteration from None + + +def test_next_after_a_partial_loop_returns_the_row_after_the_loop_row(): + # The loop read a page ahead, so the server is already past the row after the loop's. + calls: List[str] = [] + driver_cursor = _SelfIteratingServerCursor() + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({DbApiMethod.CURSOR_NEXT.method_name}, calls)]) + + for first in cursor: + break + + assert first == "a" + assert next(cursor) == "B" + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +def test_next_reads_a_cursor_that_is_its_own_iterator_a_page_at_a_time(): + driver_cursor = _SelfIteratingServerCursor() + cursor = _cursor_with_plugins(driver_cursor, []) + + assert [next(cursor) for _ in range(5)] == ["a", "b", "c", "d", "e"] + assert driver_cursor.fetches == 2 + + +def test_next_passes_a_driver_error_to_the_next_subscribers(): + # A lost connection must reach the plugins (failover, say) instead of ending the rows. + calls: List[str] = [] + cursor = _cursor_with_plugins(_FetchoneIteratingCursor(), [UpperRowsPlugin({DbApiMethod.CURSOR_NEXT.method_name}, calls)]) + + with pytest.raises(_LostConnectionError): + next(cursor) + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +def test_next_on_a_cursor_with_a_generator_iterator_keeps_every_row(): + # Each iter() on this cursor starts a generator that reads a page, so next() must not take its row from a new one. + cursor = _cursor_with_plugins(_GeneratorServerCursor(), []) + + assert [next(cursor) for _ in range(5)] == ["a", "b", "c", "d", "e"] + + +class _SelfIteratingRowsCursor: + """Shaped like psycopg 3.3's Cursor with a row factory that can return None (scalar_row on a NULL): it is its own iterator.""" + + def __init__(self, rows: List[Optional[str]]) -> None: + self.connection = MagicMock() + self._rows = iter(rows) + + def __iter__(self) -> _SelfIteratingRowsCursor: + return self + + def __next__(self) -> Optional[str]: + return next(self._rows) + + +def test_next_on_a_cursor_that_is_its_own_iterator_returns_a_none_row(): + cursor = _cursor_with_plugins(_SelfIteratingRowsCursor(["a", None, "c"]), []) + + assert [next(cursor) for _ in range(3)] == ["a", None, "c"] + with pytest.raises(StopIteration): + next(cursor) + + +def test_next_when_a_next_plugin_returns_none_without_reading_raises_stop_iteration(): + # A plugin that answers None without reading a row ends the rows; else next() would return None forever. + plugin = MagicMock(spec=Plugin) + plugin.subscribed_methods = {DbApiMethod.CURSOR_NEXT.method_name} + plugin.execute.return_value = None + driver_cursor = _SelfIteratingServerCursor() + cursor = _cursor_with_plugins(driver_cursor, [plugin]) + + with pytest.raises(StopIteration): + next(cursor) + assert driver_cursor.fetches == 0 + + +class _WrapErrorsPlugin(Plugin): + """Raises AwsWrapperError from any error of Cursor.__next__, as failover does with an error that isn't a lost connection.""" + + @property + def subscribed_methods(self) -> Set[str]: + return {DbApiMethod.CURSOR_NEXT.method_name} + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + try: + return execute_func() + except Exception as e: + raise AwsWrapperError(str(e)) from e + + +def test_next_at_the_end_of_a_cursor_that_is_its_own_iterator_raises_stop_iteration(): + # The driver's end of rows must not reach the plugins as an error: failover would raise AwsWrapperError from it. + cursor = _cursor_with_plugins(_SelfIteratingServerCursor(), [_WrapErrorsPlugin()]) + + assert [next(cursor) for _ in range(5)] == ["a", "b", "c", "d", "e"] + with pytest.raises(StopIteration): + next(cursor) + + +def _fetchone_rows_cursor() -> MagicMock: + """A driver cursor that isn't its own iterator, so next() takes its row from fetchone.""" + driver_cursor = MagicMock() + driver_cursor.fetchone.return_value = "row" + return driver_cursor + + +def test_next_at_the_end_of_a_fetchone_cursor_raises_stop_iteration(): + driver_cursor = _fetchone_rows_cursor() + driver_cursor.fetchone.side_effect = ["row", None] + cursor = _cursor_with_plugins(driver_cursor, [_WrapErrorsPlugin()]) + + assert next(cursor) == "row" + with pytest.raises(StopIteration): + next(cursor) + + +@pytest.mark.parametrize("new_driver_cursor", [_fetchone_rows_cursor, lambda: _SelfIteratingRowsCursor(["row"])], ids=["fetchone", "own_iterator"]) +@pytest.mark.parametrize( + "methods", + [PgDriverDialect(Properties()).network_bound_methods, + MySQLDriverDialect(Properties()).network_bound_methods, + AbstractReadWriteSplittingPlugin._SUBSCRIBED_METHODS], + ids=["pg", "mysql", "read_write_splitting"]) +def test_next_runs_the_plugins_subscribed_through_the_network_bound_methods(methods, new_driver_cursor): + # Failover, host monitoring and the connection tracker subscribe to the dialect's network-bound methods, and read/write + # splitting to its own list, so each must hold Cursor.__next__ for those plugins to see next(). + calls: List[str] = [] + cursor = _cursor_with_plugins(new_driver_cursor(), [UpperRowsPlugin(methods, calls)]) + + assert next(cursor) == "ROW" + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +@pytest.mark.parametrize("new_driver_cursor", [_fetchone_rows_cursor, lambda: _SelfIteratingRowsCursor(["row"])], ids=["fetchone", "own_iterator"]) +def test_next_does_not_run_the_fetchone_subscribers(new_driver_cursor): + calls: List[str] = [] + cursor = _cursor_with_plugins(new_driver_cursor(), [UpperRowsPlugin({DbApiMethod.CURSOR_FETCHONE.method_name}, calls)]) + + assert next(cursor) == "row" + assert calls == [] diff --git a/tests/unit/test_connection_source.py b/tests/unit/test_connection_source.py new file mode 100644 index 000000000..16591f8b3 --- /dev/null +++ b/tests/unit/test_connection_source.py @@ -0,0 +1,154 @@ +# 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 typing import Any, List +from unittest.mock import MagicMock + +import pytest + +from aws_advanced_python_wrapper.encryption.connection_source import ( + CallerConnectionSource, PluginConnectionSource) + + +@pytest.fixture +def conn(): + # The caller's connection: a source that commits, rolls back or closes it fails the test. + raw = MagicMock() + for name in ("commit", "rollback", "close"): + getattr(raw, name).side_effect = AssertionError(f"the caller source must not {name}") + return raw + + +class TestConnectionSources: + def test_caller_source_yields_the_same_connection(self, conn): + with CallerConnectionSource(conn).connection() as c: + assert c is conn + + def test_plugin_source_opens_an_independent_autocommit_connection_and_closes_it(self): + service = MagicMock() + service.props = {"plugins": "kms_encryption", "user": "u"} + raw = MagicMock() + service.force_connect.return_value = raw + plugin = object() + with PluginConnectionSource(service, plugin).connection() as c: + assert c is raw + host, props, skip = service.force_connect.call_args.args + assert host is service.current_host_info and skip is plugin + assert props == service.props and props is not service.props + service.driver_dialect.set_autocommit.assert_called_once_with(raw, True) + service.driver_dialect.execute.assert_called_once() # close routed through the dialect + + def test_plugin_source_closes_on_error(self): + service = MagicMock() + service.props = {} + with pytest.raises(RuntimeError): + with PluginConnectionSource(service).connection(): + raise RuntimeError("query failed") + service.driver_dialect.execute.assert_called_once() + + +@pytest.fixture +def raws(): + return [MagicMock(name="first"), MagicMock(name="second")] + + +@pytest.fixture +def service(raws): + service = MagicMock() + service.props = {} + service.force_connect.side_effect = raws + # Run the close the source routes through the dialect, so each connection records its own. + service.driver_dialect.execute.side_effect = lambda method_name, func, **kwargs: func() + return service + + +@pytest.fixture +def source(service): + return PluginConnectionSource(service) + + +class TestStatementScope: + def test_statement_shares_one_connection_and_closes_it_at_the_end(self, service, raws, source): + with source.statement(): + for _ in range(3): + with source.connection() as c: + assert c is raws[0] + raws[0].close.assert_not_called() + raws[0].close.assert_called_once() + assert service.force_connect.call_count == 1 + service.driver_dialect.set_autocommit.assert_called_once_with(raws[0], True) + + def test_statement_closes_its_connection_when_a_lookup_fails(self, raws, source): + with pytest.raises(RuntimeError, match="query failed"): + with source.statement(): + with source.connection(): + raise RuntimeError("query failed") + raws[0].close.assert_called_once() + # The failed scope has ended, so a lookup gets a connection of its own again. + with source.connection() as c: + assert c is raws[1] + raws[1].close.assert_called_once() + + def test_statement_without_a_lookup_opens_nothing(self, service, source): + with source.statement(): + pass + service.force_connect.assert_not_called() + service.driver_dialect.execute.assert_not_called() + + def test_statement_is_per_thread(self, raws, source): + seen: List[Any] = [] + + def lookup(): + with source.connection() as c: + seen.append(c) + + with source.statement(): + with source.connection(): + pass + other = threading.Thread(target=lookup, daemon=True) + other.start() + other.join(5) + assert not other.is_alive() + assert seen == [raws[1]] + raws[1].close.assert_called_once() + raws[0].close.assert_not_called() + raws[0].close.assert_called_once() + + def test_nested_statement_keeps_the_outer_connection(self, service, raws, source): + with source.statement(): + with source.connection() as outer: + pass + with source.statement(): + with source.connection() as inner: + assert inner is outer + raws[0].close.assert_not_called() + with source.connection() as after: + assert after is outer + raws[0].close.assert_called_once() + assert service.force_connect.call_count == 1 + + def test_autocommit_failure_in_a_statement_closes_the_half_opened_connection(self, service, raws, source): + service.driver_dialect.set_autocommit.side_effect = [RuntimeError("autocommit failed"), None] + with source.statement(): + with pytest.raises(RuntimeError, match="autocommit failed"): + with source.connection(): + pass + raws[0].close.assert_called_once() + with source.connection() as c: + assert c is raws[1] + raws[1].close.assert_not_called() + raws[1].close.assert_called_once() diff --git a/tests/unit/test_data_key_cache.py b/tests/unit/test_data_key_cache.py new file mode 100644 index 000000000..23b6d3c40 --- /dev/null +++ b/tests/unit/test_data_key_cache.py @@ -0,0 +1,275 @@ +# 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. + +import gc +import time +import weakref +from types import SimpleNamespace + +import pytest + +from aws_advanced_python_wrapper.encryption import data_key_cache as module +from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache + + +class Clock: + def __init__(self): + self.now = 1000.0 + + def __call__(self): + return self.now + + +@pytest.fixture +def clock(monkeypatch): + # Replace the module's view of `time` only, so no other thread in the + # process sees a frozen clock. + c = Clock() + monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=c)) + return c + + +def make(max_size=3, ttl=60.0, enabled=True): + return DataKeyCache(max_size, ttl, enabled, start_cleanup_thread=False) + + +def test_get_returns_a_copy_the_caller_can_wipe(clock): + cache = make() + cache.put("k", b"\x01" * 32) + first = cache.get("k") + assert first == bytearray(b"\x01" * 32) + first[:] = b"\x00" * 32 + assert cache.get("k") == bytearray(b"\x01" * 32) + + +def test_put_copies_so_the_caller_keeps_ownership(clock): + cache = make() + key = bytearray(b"\x02" * 32) + cache.put("k", key) + key[:] = b"\x00" * 32 + assert cache.get("k") == bytearray(b"\x02" * 32) + + +def test_oldest_entry_is_evicted_and_wiped(clock): + cache = make(max_size=2) + cache.put("a", b"a" * 4) + entry_a = cache._entries["a"].data_key + cache.put("b", b"b" * 4) + cache.put("c", b"c" * 4) + assert cache.get("a") is None + assert entry_a == bytearray(4) + assert len(cache) == 2 + assert cache.stats().evictions == 1 + + +def test_replacing_a_key_wipes_the_old_value_and_does_not_evict(clock): + cache = make(max_size=2) + cache.put("a", b"1111") + cache.put("b", b"2222") + old = cache._entries["a"].data_key + cache.put("a", b"3333") + assert old == bytearray(4) + assert cache.get("a") == bytearray(b"3333") + assert cache.get("b") == bytearray(b"2222") + assert cache.stats().evictions == 0 + + +def test_expired_entry_is_never_returned_and_is_wiped(clock): + cache = make(ttl=10) + cache.put("k", b"kkkk") + stored = cache._entries["k"].data_key + clock.now += 9.9 + assert cache.get("k") is not None + clock.now += 0.1 + assert cache.get("k") is None + assert stored == bytearray(4) + assert len(cache) == 0 + + +def test_remove_expired(clock): + cache = make(ttl=10) + cache.put("old", b"o") + clock.now += 5 + cache.put("new", b"n") + clock.now += 5 + assert cache.remove_expired() == 1 + assert cache.get("new") is not None + + +def test_clear_and_close_wipe_everything(clock): + cache = make() + cache.put("a", b"aa") + stored = cache._entries["a"].data_key + cache.close() + assert stored == bytearray(2) + assert len(cache) == 0 + cache.close() # idempotent + + +def test_disabled_cache_never_stores(clock): + cache = make(enabled=False) + cache.put("k", b"x") + assert cache.get("k") is None + assert len(cache) == 0 + assert cache.stats().misses == 0 + + +def test_stats(clock): + cache = make() + cache.put("k", b"x") + cache.get("k") + cache.get("missing") + stats = cache.stats() + assert (stats.size, stats.hits, stats.misses) == (1, 1, 1) + assert stats.hit_rate == 50.0 + + +def test_repr_does_not_show_key_material(clock): + cache = make() + cache.put("k", b"SECRET") + assert "SECRET" not in repr(cache._entries["k"]) + + +def test_cleanup_interval_has_a_floor(): + assert make(ttl=40).cleanup_interval_sec == DataKeyCache.MIN_CLEANUP_INTERVAL_SEC + assert make(ttl=400).cleanup_interval_sec == 100.0 + + +def test_cleanup_thread_stops_promptly_on_close(): + cache = DataKeyCache(10, 3600.0) + try: + thread = cache._cleanup_thread + assert thread is not None and thread.daemon and thread.is_alive() + started = time.monotonic() + cache.close() + assert not thread.is_alive() + assert time.monotonic() - started < 2.0 + finally: + cache.close() + + +def test_closed_cache_stores_nothing(clock): + # A KMS round trip that finishes after close() must not leave a plaintext + # key in a cache nobody will wipe. + cache = make() + cache.close() + key = bytearray(b"\x05" * 32) + cache.put("k", key) + assert cache.get("k") is None + assert len(cache) == 0 + assert key == bytearray(b"\x05" * 32) # the caller's buffer is left alone + + +def test_finalizer_wipes_first_and_never_sets_the_event_from_the_cleanup_thread(clock): + # A collection on the cleanup thread can run inside Event.wait, which + # holds the event's lock, so stop.set() there would deadlock. The keys + # are wiped regardless. + import threading + cache = make() + cache.put("k", b"\x09" * 4) + stored = cache._entries["k"].data_key + stop = threading.Event() + DataKeyCache._release(cache._entries, cache._lock, stop, [threading.current_thread()]) + assert stored == bytearray(4) and len(cache) == 0 + assert not stop.is_set() + DataKeyCache._release(cache._entries, cache._lock, stop, [None]) + assert stop.is_set() + + +def test_close_on_the_cleanup_thread_stops_it_without_joining_itself(): + # There the finalizer leaves the event alone, so close() must set it, and + # it must not join its own thread. + import threading + cache = DataKeyCache(10, 3600.0, start_cleanup_thread=False) + errors = [] + + def run(): + try: + cache.close() + except BaseException as e: + errors.append(e) + + t = threading.Thread(target=run, daemon=True) + cache._thread_holder[0] = t + cache._cleanup_thread = t + t.start() + t.join(5) + assert not t.is_alive() + assert errors == [] + assert cache._stop.is_set() + + +def test_finalizer_wipes_the_keys_even_if_stopping_the_thread_fails(clock): + cache = make() + cache.put("k", b"\x09" * 4) + stored = cache._entries["k"].data_key + + class BrokenStop: + def set(self): + raise RuntimeError("cannot stop") + + with pytest.raises(RuntimeError): + DataKeyCache._release(cache._entries, cache._lock, BrokenStop(), [None]) # type: ignore[arg-type] + assert stored == bytearray(4) + + +def test_a_cache_hit_does_not_protect_an_entry_from_eviction(clock): + # Eviction is oldest-first by insertion, not least recently used. + cache = make(max_size=2) + cache.put("a", b"aaaa") + cache.put("b", b"bbbb") + assert cache.get("a") == bytearray(b"aaaa") + cache.put("c", b"cccc") + assert cache.get("a") is None + assert cache.get("b") == bytearray(b"bbbb") + + +def test_put_after_close_wipes_the_copy_it_refuses(clock, monkeypatch): + wiped = [] + real = module.wipe + monkeypatch.setattr(module, "wipe", lambda buf: (wiped.append(buf), real(buf))) + cache = make() + cache.close() + cache.put("k", b"\x07" * 4) + assert len(cache) == 0 + assert wiped == [bytearray(4)] + + +def test_finalizer_is_given_the_cleanup_thread(): + cache = DataKeyCache(10, 3600.0) + try: + assert cache._cleanup_thread is not None + assert cache._thread_holder == [cache._cleanup_thread] + assert any(arg is cache._thread_holder for arg in cache._finalizer.peek()[2]) # type: ignore[index] + finally: + cache.close() + + +def test_unclosed_cache_is_wiped_and_its_thread_stops_when_collected(): + cache = DataKeyCache(10, 3600.0) + cache.put("k", b"\x07" * 32) + stored = cache._entries["k"].data_key + thread = cache._cleanup_thread + ref = weakref.ref(cache) + del cache + for _ in range(100): + gc.collect() + if ref() is None: + break + time.sleep(0.01) + assert ref() is None + assert stored == bytearray(32) + assert thread is not None + thread.join(5) + assert not thread.is_alive() diff --git a/tests/unit/test_encryption_config.py b/tests/unit/test_encryption_config.py new file mode 100644 index 000000000..0300df9eb --- /dev/null +++ b/tests/unit/test_encryption_config.py @@ -0,0 +1,253 @@ +# 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. + +import pytest + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.config import ( + EncryptionConfig, validate_schema_name) +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata, mask_arn, mask_arns_in_text) +from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + InterfaceError) +from aws_advanced_python_wrapper.utils.properties import Properties + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" + + +@pytest.fixture(autouse=True) +def no_region_env(monkeypatch): + monkeypatch.delenv("AWS_REGION", raising=False) + monkeypatch.delenv("AWS_DEFAULT_REGION", raising=False) + + +def props(**kwargs) -> Properties: + base = {"encryption_kms_region": "us-east-1", "encryption_allowed_master_key_arns": ARN} + base.update(kwargs) + return Properties({k: v for k, v in base.items() if v is not None}) + + +class TestFromProps: + def test_defaults_match_the_shared_spec(self): + config = EncryptionConfig.from_props(props()) + assert config.kms_region == "us-east-1" + assert config.kms_endpoint is None + assert config.metadata_schema == "encrypt" + assert config.metadata_cache_enabled is True + assert config.metadata_cache_expiration_sec == 3600.0 + assert config.metadata_cache_refresh_interval_sec == 300.0 + assert config.data_key_cache_enabled is True + assert config.data_key_cache_max_size == 1000 + assert config.data_key_cache_expiration_sec == 300.0 + assert config.key_management_max_retries == 3 + assert config.key_management_retry_backoff_base_sec == 0.1 + assert config.audit_logging_enabled is False + assert config.return_unverified_data is False + + def test_string_values_are_parsed(self): + config = EncryptionConfig.from_props(props( + encryption_metadata_cache_enabled="false", + encryption_metadata_cache_refresh_interval_sec="0", + encryption_data_key_cache_max_size="5", + encryption_key_management_retry_backoff_base_sec="0.25", + )) + assert config.metadata_cache_enabled is False + assert config.metadata_cache_refresh_interval_sec == 0.0 + assert config.background_refresh_enabled is False + assert config.data_key_cache_max_size == 5 + assert config.key_management_retry_backoff_base_sec == 0.25 + + def test_region_falls_back_to_aws_region_then_default_region(self, monkeypatch): + monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "eu-west-1" + monkeypatch.setenv("AWS_REGION", "ap-south-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "ap-south-1" + + @pytest.mark.parametrize("env", ["AWS_REGION", "AWS_DEFAULT_REGION"]) + def test_region_property_beats_environment(self, monkeypatch, env): + # On Lambda, ECS, or EC2 AWS_REGION is usually set; an explicit + # encryption_kms_region must still win. + monkeypatch.setenv(env, "eu-west-1") + assert EncryptionConfig.from_props(props()).kms_region == "us-east-1" + + def test_blank_region_property_falls_back_to_the_environment(self, monkeypatch): + monkeypatch.setenv("AWS_REGION", "eu-west-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=" ")).kms_region == "eu-west-1" + + @pytest.mark.parametrize("name", [ + "encryption_metadata_cache_expiration_sec", + "encryption_metadata_cache_refresh_interval_sec", + "encryption_data_key_cache_expiration_sec", + "encryption_key_management_retry_backoff_base_sec", + ]) + def test_infinite_durations_are_refused(self, name): + # Event.wait() rejects an infinite timeout, which would kill the + # background threads. + with pytest.raises(EncryptionConfigError, match=name): + EncryptionConfig.from_props(props(**{name: "inf"})) + + def test_blank_aws_region_falls_back_to_aws_default_region(self, monkeypatch): + monkeypatch.setenv("AWS_REGION", " ") + monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "eu-west-1" + + def test_region_is_stripped(self): + assert EncryptionConfig.from_props(props(encryption_kms_region=" us-east-1 ")).kms_region == "us-east-1" + + def test_missing_region_is_rejected(self): + with pytest.raises(EncryptionConfigError, match="region"): + EncryptionConfig.from_props(props(encryption_kms_region=None)) + + def test_allow_list_is_required_by_default(self): + with pytest.raises(EncryptionConfigError, match="encryption_allowed_master_key_arns"): + EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=None)) + with pytest.raises(EncryptionConfigError): + EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=" , ")) + + def test_allow_list_can_be_waived_for_admin_use(self): + config = EncryptionConfig.from_props( + props(encryption_allowed_master_key_arns=None), require_allowed_master_keys=False) + assert not config.restricts_master_keys + assert config.is_master_key_allowed(ARN) + assert config.is_master_key_allowed(None) + + def test_non_numeric_value_is_a_config_error_naming_the_property(self): + with pytest.raises(EncryptionConfigError, match="encryption_data_key_cache_max_size"): + EncryptionConfig.from_props(props(encryption_data_key_cache_max_size="lots")) + + @pytest.mark.parametrize("name, value", [ + ("encryption_metadata_cache_expiration_sec", "0"), + ("encryption_metadata_cache_refresh_interval_sec", "-1"), + ("encryption_data_key_cache_max_size", "0"), + ("encryption_data_key_cache_expiration_sec", "-5"), + ("encryption_key_management_max_retries", "-1"), + ("encryption_key_management_retry_backoff_base_sec", "0"), + ]) + def test_out_of_range_values_name_the_property(self, name, value): + with pytest.raises(EncryptionConfigError, match=name) as err: + EncryptionConfig.from_props(props(**{name: value})) + assert ">" in str(err.value).partition("must be")[2] + + def test_config_error_is_an_interface_error(self): + with pytest.raises(InterfaceError): + EncryptionConfig.from_props(props(encryption_kms_region=None)) + + +class TestAllowList: + def test_string_list_is_split_trimmed_and_deduplicated(self): + other = ARN.replace("1234abcd", "9999ffff") + config = EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=f" {ARN} ,{other},{ARN},")) + assert config.allowed_master_key_arns == frozenset({ARN, other}) + + def test_python_list_is_accepted(self): + config = EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=[ARN, " "])) + assert config.allowed_master_key_arns == frozenset({ARN}) + + def test_match_is_exact(self): + config = EncryptionConfig.from_props(props()) + assert config.is_master_key_allowed(ARN) + assert not config.is_master_key_allowed(ARN.upper()) + assert not config.is_master_key_allowed(ARN + " ") + assert not config.is_master_key_allowed("alias/whatever") + assert not config.is_master_key_allowed(None) + + def test_direct_construction_normalizes_too(self): + config = EncryptionConfig(kms_region="us-east-1", allowed_master_key_arns=f"{ARN}, ") # type: ignore[arg-type] + assert config.allowed_master_key_arns == frozenset({ARN}) + + +class TestSchemaName: + @pytest.mark.parametrize("name", ["encrypt", "_x", "App_Encrypt2"]) + def test_plain_identifiers_are_accepted(self, name): + assert validate_schema_name(name) == name + + @pytest.mark.parametrize("name", ["", " ", "1abc", "a-b", "a b", "a;drop", "a.b", '"q"', "a/*c*/", None, 5]) + def test_anything_else_is_rejected(self, name): + with pytest.raises(EncryptionConfigError): + validate_schema_name(name) + + def test_props_schema_is_validated(self): + with pytest.raises(EncryptionConfigError): + EncryptionConfig.from_props(props(encryption_metadata_schema="x; DROP TABLE y")) + + +class TestModels: + def test_key_metadata_repr_redacts_key_material(self): + km = KeyMetadata(id=1, key_id="uuid", master_key_arn=ARN, encrypted_data_key="SECRET-EDK", + hmac_key=b"SECRET-HMAC-KEY-BYTES") + for text in (repr(km), str(km), repr(ColumnEncryptionConfig("t", "c", key_metadata=km))): + assert "SECRET" not in text + assert "123456789012" not in text + assert "[REDACTED]" in text + + def test_mask_arn(self): + assert mask_arn(ARN) == "arn:aws:kms:***:***:key/1234***90ab" + assert mask_arn("short/abc") == "arn:aws:kms:***:***:key/***" + assert mask_arn("no-slash") == "arn:aws:kms:***:***:key/***" + assert mask_arn(None) is None + + @pytest.mark.parametrize("partition", ["aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b", "aws-iso-f"]) + def test_mask_arns_in_text_covers_every_partition(self, partition): + key = f"arn:{partition}:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" + session = f"arn:{partition}:sts::123456789012:assumed-role/app-role/app-session" + text = f"User: {session} is not authorized to perform: kms:Decrypt on resource: {key}" + assert mask_arns_in_text(text) == (f"User: arn:{partition}:sts:***:***:*** is not authorized to perform: " + "kms:Decrypt on resource: arn:aws:kms:***:***:key/1234***90ab") + + @pytest.mark.parametrize("text, expected", [ + pytest.param("arn:aws:kms:us-east-1:123456789012:alias/app-key is not found.", + "arn:aws:kms:***:***:*** is not found.", id="alias"), + pytest.param("arn:aws:iam::123456789012:role/app-role", "arn:aws:iam:***:***:***", id="iam-role"), + pytest.param(f"{ARN} and arn:aws:kms:us-east-1:123456789012:key/ffffffff-12ab-34cd-56ef-1234567890ab", + "arn:aws:kms:***:***:key/1234***90ab and arn:aws:kms:***:***:key/ffff***90ab", id="two-arns"), + pytest.param(f"{ARN} is disabled.", "arn:aws:kms:***:***:key/1234***90ab is disabled.", id="space"), + pytest.param(f"key {ARN}.", "key arn:aws:kms:***:***:key/1234***90ab.", id="period"), + pytest.param(f"{ARN}, then", "arn:aws:kms:***:***:key/1234***90ab, then", id="comma"), + pytest.param(f"{ARN}; then", "arn:aws:kms:***:***:key/1234***90ab; then", id="semicolon"), + pytest.param(f"'{ARN}'", "'arn:aws:kms:***:***:key/1234***90ab'", id="single-quotes"), + pytest.param(f'"{ARN}"', '"arn:aws:kms:***:***:key/1234***90ab"', id="double-quotes"), + pytest.param(f"key {ARN}", "key arn:aws:kms:***:***:key/1234***90ab", id="end-of-text"), + # A role session name may hold '.', ',' and '@'; none of it is left. + pytest.param("arn:aws:sts::123456789012:assumed-role/app-role/first.last@example.com.", + "arn:aws:sts:***:***:***.", id="dots-in-session-name"), + pytest.param("arn:aws:sts::123456789012:assumed-role/app-role/a,b is not authorized", + "arn:aws:sts:***:***:*** is not authorized", id="comma-in-session-name"), + pytest.param("Invalid arn us-east-1", "Invalid arn us-east-1", id="no-arn"), + pytest.param("", "", id="empty"), + pytest.param("arn:aws:kms:***:***:key/1234***90ab is disabled.", + "arn:aws:kms:***:***:key/1234***90ab is disabled.", id="already-masked"), + ]) + def test_mask_arns_in_text(self, text, expected): + assert mask_arns_in_text(text) == expected + + def test_usability(self): + good = KeyMetadata(master_key_arn=ARN, encrypted_data_key="e", hmac_key=b"h") + assert good.is_usable + assert not KeyMetadata(master_key_arn=" ", encrypted_data_key="e", hmac_key=b"h").is_usable + assert not KeyMetadata(master_key_arn=ARN, encrypted_data_key=None, hmac_key=b"h").is_usable + assert not KeyMetadata(master_key_arn=ARN, encrypted_data_key="e", hmac_key=b"").is_usable + assert ColumnEncryptionConfig("t", "c", key_metadata=good).is_usable + assert not ColumnEncryptionConfig("t", "c", key_metadata=None).is_usable + assert not ColumnEncryptionConfig("t", "c", algorithm="DES", key_metadata=good).is_usable + + def test_from_row_normalizes_binary_and_prefix(self): + row = {"ks_id": "7", "ks_key_id": "u", "ks_hmac_key": memoryview(b"hk"), "ks_key_spec": None} + km = KeyMetadata.from_row(row, "ks_") + assert km.id == 7 and km.key_id == "u" and km.hmac_key == b"hk" and km.key_spec == "AES_256" + + +def test_data_key_spec_matches_algorithm_key_length(): + assert EncryptionAlgorithm.data_key_spec(EncryptionAlgorithm.AES_256_GCM) == "AES_256" + assert EncryptionAlgorithm.data_key_spec(EncryptionAlgorithm.AES_128_GCM) == "AES_128" diff --git a/tests/unit/test_encryption_conformance.py b/tests/unit/test_encryption_conformance.py new file mode 100644 index 000000000..8ac7fee4c --- /dev/null +++ b/tests/unit/test_encryption_conformance.py @@ -0,0 +1,126 @@ +# 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. + +"""Byte-format conformance tests for the KMS encryption wire format. + +These check that Python matches the payload layout shown below. The +database-side trigger checks its minimum length and its HMAC tag. + +The vectors in ``resources/encryption/conformance_vectors.json`` come from +the reference encoder next to them, ``generate_conformance_vectors.py``, which +builds each payload from the spec with raw ``cryptography`` and the stdlib, +without importing the wrapper, so decrypting them tests the code against the +spec. The encrypt->decrypt round trips in test_encryption_service.py can't do +that by themselves, because they would still pass if the whole format were +wrong. + +The format under test:: + + [ HMAC-SHA256 : 32 ][ key id : 4 ][ marker : 1 ][ IV : 12 ][ ciphertext ][ GCM tag : 16 ] +""" + +import base64 +import hashlib +import hmac +import importlib.util +import json +from datetime import date, datetime +from decimal import Decimal +from pathlib import Path + +import pytest + +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService + +_RESOURCES = Path(__file__).parent / "resources" / "encryption" +_VECTORS_PATH = _RESOURCES / "conformance_vectors.json" +_IV_OFFSET = EncryptionService.HMAC_TAG_LENGTH + EncryptionService.KEY_ID_LENGTH + EncryptionService.TYPE_MARKER_LENGTH + + +def _load(): + data = json.loads(_VECTORS_PATH.read_text(encoding="utf-8")) + dk = base64.b64decode(data["data_key_b64"]) + hk = base64.b64decode(data["hmac_key_b64"]) + return dk, hk, data["key_id"], data["vectors"] + + +DK, HK, KEY_ID, VECTORS = _load() +_IDS = [v["name"] for v in VECTORS] + + +@pytest.mark.parametrize("vec", VECTORS, ids=_IDS) +def test_decrypts_independent_reference_payload(vec): + """Python decrypts a payload it did not produce to the expected value.""" + ciphertext = base64.b64decode(vec["ciphertext_b64"]) + result = EncryptionService.decrypt(ciphertext, DK, HK) + + if "expect_b64" in vec: + assert result == base64.b64decode(vec["expect_b64"]) + elif "expect_datetime_iso" in vec: + # LOCAL_DATE_TIME vectors include the no-seconds and nanosecond forms + # the reader accepts. Python must read them to the microsecond. + assert result == datetime.fromisoformat(vec["expect_datetime_iso"]) + elif "expect_date_iso" in vec: + assert result == date.fromisoformat(vec["expect_date_iso"]) + elif vec["name"] == "decimal": + assert Decimal(result) == Decimal(vec["expect"]) + else: + # The type matters too: INTEGER must read as int, not 42.0. + assert result == vec["expect"] + assert type(result) is type(vec["expect"]) + + +@pytest.mark.parametrize("vec", VECTORS, ids=_IDS) +def test_reference_payload_carries_expected_key_id(vec): + ciphertext = base64.b64decode(vec["ciphertext_b64"]) + assert EncryptionService.key_id_from_payload(ciphertext) == vec.get("key_id", KEY_ID) + + +@pytest.mark.parametrize("vec", VECTORS, ids=_IDS) +def test_our_encrypt_output_passes_the_db_trigger_hmac(vec): + """Check our output the way the DB-side trigger does: the HMAC over + everything after the 32-byte tag, computed with the stored HMAC key, must + match the tag. The trigger would reject any write that fails this. + """ + # Re-encrypt the decrypted value, then recompute the HMAC. + value = EncryptionService.decrypt(base64.b64decode(vec["ciphertext_b64"]), DK, HK) + payload = EncryptionService.encrypt(value, DK, HK, key_id=vec.get("key_id", KEY_ID)) + assert len(payload) >= EncryptionService.MIN_ENCRYPTED_LENGTH + stored_tag = payload[:EncryptionService.HMAC_TAG_LENGTH] + body = payload[EncryptionService.HMAC_TAG_LENGTH:] + recomputed = hmac.new(HK, body, hashlib.sha256).digest() + assert hmac.compare_digest(stored_tag, recomputed) + + +def test_vectors_use_distinct_fixed_ivs(): + """Each vector's IV is one repeated byte, unique per vector. The wrapper's + encrypt draws a random IV, so it could not have produced these payloads.""" + ivs = [] + for vec in VECTORS: + iv = base64.b64decode(vec["ciphertext_b64"])[_IV_OFFSET:_IV_OFFSET + EncryptionService.GCM_IV_LENGTH] + assert len(set(iv)) == 1, vec["name"] + ivs.append(iv) + assert len(set(ivs)) == len(ivs) + + +def test_committed_vectors_match_the_reference_encoder(): + """The JSON file is exactly what the reference encoder produces, so the + vectors can be regenerated and reviewed from source.""" + spec = importlib.util.spec_from_file_location("generate_conformance_vectors", + _RESOURCES / "generate_conformance_vectors.py") + assert spec is not None and spec.loader is not None + generator = importlib.util.module_from_spec(spec) + spec.loader.exec_module(generator) + assert _VECTORS_PATH.read_text(encoding="utf-8") == generator.render() diff --git a/tests/unit/test_encryption_import_guard.py b/tests/unit/test_encryption_import_guard.py new file mode 100644 index 000000000..666917176 --- /dev/null +++ b/tests/unit/test_encryption_import_guard.py @@ -0,0 +1,132 @@ +# 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. + +"""``cryptography`` is an optional extra (``encryption``). The wrapper must +import without it, and only the module that encrypts may need it. + +Each check runs in a fresh interpreter, most with ``cryptography`` blocked, +since the test environment always has it installed.""" + +import subprocess +import sys +import textwrap + +import pytest + +_BLOCKER = textwrap.dedent(""" + import sys + + class _Block: + def find_spec(self, name, path=None, target=None): + if name == "cryptography" or name.startswith("cryptography."): + raise ModuleNotFoundError(f"No module named {name!r}", name=name) + return None + + sys.meta_path.insert(0, _Block()) +""") + + +def _run(code: str, block: bool = True) -> subprocess.CompletedProcess: + script = (_BLOCKER if block else "import sys\n") + textwrap.dedent(code) + return subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120) + + +_CORE_MODULES = [ + "aws_advanced_python_wrapper", + "aws_advanced_python_wrapper.aio", + "aws_advanced_python_wrapper.psycopg", + "aws_advanced_python_wrapper.mysql_connector", + "aws_advanced_python_wrapper.sqlalchemy_dialects.pg", + "aws_advanced_python_wrapper.sqlalchemy_dialects.mysql", + "aws_advanced_python_wrapper.sqlalchemy_dialects.pg_async", + "aws_advanced_python_wrapper.sqlalchemy_dialects.mysql_async", + "aws_advanced_python_wrapper.django.backends.mysql_connector.base", +] + + +_KEY_LAYER_MODULES = [ + # The key and metadata layer, including the admin utility, does no + # encryption itself. + "aws_advanced_python_wrapper.encryption.config", + "aws_advanced_python_wrapper.encryption.data_key_cache", + "aws_advanced_python_wrapper.encryption.key_manager", + "aws_advanced_python_wrapper.encryption.metadata_manager", + "aws_advanced_python_wrapper.encryption.key_management_utility", +] + + +@pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) +def test_imports_without_cryptography(module): + result = _run(f""" + import importlib + importlib.import_module({module!r}) + """) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) +def test_does_not_load_cryptography_even_when_installed(module): + # With cryptography available, importing these must still not load it, + # so users who never encrypt don't pay its import cost. + result = _run(f""" + import importlib + importlib.import_module({module!r}) + assert "cryptography" not in sys.modules, "cryptography was imported" + """, block=False) + assert result.returncode == 0, result.stderr + + +def test_encryption_service_names_the_extra_when_cryptography_is_missing(): + result = _run(""" + try: + import aws_advanced_python_wrapper.encryption.encryption_service + except ImportError as e: + print(e) + else: + raise SystemExit("imported without cryptography") + """) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" in result.stdout + + +_BROKEN = textwrap.dedent(""" + import sys + + class _Broken: + def find_spec(self, name, path=None, target=None): + if name == "cryptography": + raise {error} + return None + + sys.meta_path.insert(0, _Broken()) +""") + + +@pytest.mark.parametrize("error", [ + 'ImportError("DLL load failed while importing _rust")', + 'ModuleNotFoundError("No module named \'_cffi_backend\'", name="_cffi_backend")', +], ids=["ImportError", "other-module-missing"]) +def test_a_broken_cryptography_is_not_reported_as_missing(error): + # Only a missing cryptography package gets the install hint; an installed + # but broken one surfaces its own error. + code = _BROKEN.format(error=error) + textwrap.dedent(""" + try: + import aws_advanced_python_wrapper.encryption.encryption_service + except ImportError as e: + print(e) + """) + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" not in result.stdout + assert ("DLL load failed" in result.stdout) or ("_cffi_backend" in result.stdout) diff --git a/tests/unit/test_encryption_service.py b/tests/unit/test_encryption_service.py new file mode 100644 index 000000000..66ef481bf --- /dev/null +++ b/tests/unit/test_encryption_service.py @@ -0,0 +1,864 @@ +# 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. + +import hashlib +import hmac +import struct +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal +from enum import Enum + +import pytest + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker +from aws_advanced_python_wrapper.errors import (DecryptionError, + EncryptionError, + EncryptionFailedError, + IntegrityCheckError, + InvalidAlgorithmError, + InvalidKeyError, + TypeConversionError) + +DATA_KEY = bytes(range(32)) # 32 bytes +HMAC_KEY = bytes(range(32, 64)) # 32 bytes +KEY_ID = 7 + + +class Color(str, Enum): + RED = "red" + + +class Masked(str): + def __str__(self): + return "***" + + +def enc(value, key_id=KEY_ID, dk=DATA_KEY, hk=HMAC_KEY, algorithm=EncryptionAlgorithm.DEFAULT): + return EncryptionService.encrypt(value, dk, hk, algorithm, key_id=key_id) + + +def dec(payload, dk=DATA_KEY, hk=HMAC_KEY, algorithm=EncryptionAlgorithm.DEFAULT, target_type=None): + return EncryptionService.decrypt(payload, dk, hk, algorithm, target_type=target_type) + + +# ---- payload layout ---- + +class TestPayloadLayout: + def test_min_length_is_65(self): + assert EncryptionService.MIN_ENCRYPTED_LENGTH == 65 + + def test_layout_sizes(self): + payload = enc("hello") + assert len(payload) == 32 + 4 + 1 + 12 + len(b"hello") + 16 + + def test_hmac_covers_everything_after_itself(self): + import hashlib + import hmac + payload = enc("hello") + expected = hmac.new(HMAC_KEY, payload[32:], hashlib.sha256).digest() + assert payload[:32] == expected + + def test_key_id_recorded_before_marker(self): + payload = enc("hello", key_id=12345) + assert struct.unpack(">I", payload[32:36])[0] == 12345 + + def test_marker_recorded_after_key_id(self): + payload = enc("hello") + assert payload[36] == TypeMarker.STRING + + def test_key_id_from_payload(self): + assert EncryptionService.key_id_from_payload(enc("x", key_id=999)) == 999 + assert EncryptionService.key_id_from_payload(None) is None + assert EncryptionService.key_id_from_payload(b"\x00" * 10) is None # too short + + +# ---- round trips for every supported type ---- + +class TestRoundTrip: + @pytest.mark.parametrize("value", [ + "hello", "", "café-ümlaut-漢字", "a" * 10000, + ]) + def test_string(self, value): + assert dec(enc(value)) == value + + def test_bytes(self): + payload = enc(b"\x00\x01\x02\xff") + out = dec(payload) + assert out == b"\x00\x01\x02\xff" + assert isinstance(out, bytes) + + @pytest.mark.parametrize("value", [0, 1, -1, 1234567890123, -1234567890123, 2 ** 62]) + def test_int(self, value): + assert dec(enc(value)) == value + + @pytest.mark.parametrize("value", [0.0, 3.141592653589793, -2.5, 1e300]) + def test_float(self, value): + assert dec(enc(value)) == value + + @pytest.mark.parametrize("value", [True, False]) + def test_bool(self, value): + assert dec(enc(value)) is value + + def test_decimal(self): + value = Decimal("12345.6789") + assert dec(enc(value)) == value + + def test_local_date(self): + value = date(2023, 6, 15) + assert dec(enc(value)) == value + + def test_local_datetime(self): + value = datetime(2023, 6, 15, 13, 45, 30) + assert dec(enc(value)) == value + + def test_none_passthrough(self): + assert enc(None) is None + assert dec(None) is None + + +# ---- target type coercion ---- + +class TestTargetType: + def test_coerce_to_str(self): + assert dec(enc(123), target_type=str) == "123" + + def test_coerce_to_int(self): + assert dec(enc("42"), target_type=int) == 42 + + def test_coerce_to_bool(self): + assert dec(enc("yes"), target_type=bool) is True + assert dec(enc("no"), target_type=bool) is False + + +# ---- fail-closed behavior ---- + +class TestFailClosed: + def test_too_short_raises_integrity(self): + with pytest.raises(IntegrityCheckError): + dec(b"\x00" * 10) + + def test_tampered_body_fails_hmac(self): + payload = bytearray(enc("hello")) + payload[-1] ^= 0xFF # flip a ciphertext/tag byte + with pytest.raises(IntegrityCheckError): + dec(bytes(payload)) + + def test_tampered_key_id_fails_hmac(self): + payload = bytearray(enc("hello")) + payload[34] ^= 0xFF # key id is inside the HMAC-covered region + with pytest.raises(IntegrityCheckError): + dec(bytes(payload)) + + @pytest.mark.parametrize("body", [ + b"", # tag only + struct.pack(">I", 7), # tag + key id + struct.pack(">I", 7) + bytes([TypeMarker.STRING]), # + marker, no IV + ]) + def test_signed_but_too_short_payload_is_an_integrity_error(self, body): + # Signed with the right HMAC key, so only the length check refuses it; + # without it the framing would fail with a bare IndexError/ValueError. + payload = hmac.new(HMAC_KEY, body, hashlib.sha256).digest() + body + with pytest.raises(IntegrityCheckError, match="too short"): + dec(payload) + + def test_wrong_data_key_fails_gcm_not_hmac(self): + # Decrypt with a different data key. The HMAC still matches (same HMAC + # key and body), so this has to fail at GCM with DecryptionError, never + # with IntegrityCheckError. + import hashlib + import hmac + payload = enc("hello") + wrong_dk = bytes([(b + 1) % 256 for b in DATA_KEY]) + with pytest.raises(DecryptionError): + dec(payload, dk=wrong_dk) + _ = (hashlib, hmac) + + def test_bad_data_key_length(self): + with pytest.raises(InvalidKeyError): + EncryptionService.encrypt("x", b"short", HMAC_KEY, key_id=1) + + def test_empty_hmac_key(self): + with pytest.raises(InvalidKeyError): + EncryptionService.encrypt("x", DATA_KEY, b"", key_id=1) + + @pytest.mark.parametrize("bad", [-1, 2 ** 32, True, "7", 1.5]) + def test_bad_key_id(self, bad): + with pytest.raises(EncryptionError): + EncryptionService.encrypt("x", DATA_KEY, HMAC_KEY, key_id=bad) + + +# ---- key rotation: value carries the id it was written with ---- + +class TestKeyId: + def test_payload_carries_write_key_id(self): + for kid in (0, 1, 7, 2 ** 32 - 1): + assert EncryptionService.key_id_from_payload(enc("v", key_id=kid)) == kid + + +# ---- randomized IV ---- + +def test_iv_is_random_per_call(): + a = enc("same-value") + b = enc("same-value") + assert a != b # fresh IV each time + assert dec(a) == dec(b) == "same-value" + + +# ---- AES-128 ---- + +def test_aes_128_round_trip(): + dk16 = bytes(range(16)) + payload = EncryptionService.encrypt("x", dk16, HMAC_KEY, EncryptionAlgorithm.AES_128_GCM, key_id=1) + assert EncryptionService.decrypt(payload, dk16, HMAC_KEY, EncryptionAlgorithm.AES_128_GCM) == "x" + + +# ---- wipe ---- + +def test_wipe_zeroes_bytearray(): + buf = bytearray(b"secret-key-material") + EncryptionService.wipe(buf) + assert buf == bytearray(len(buf)) + + +def test_datetime_tz_normalization_matches_millis_contract(): + # Under the TIMESTAMP marker, a timezone-naive datetime is taken as UTC. + naive = datetime(2023, 1, 1, 0, 0, 0) + millis = EncryptionService._to_millis(naive, "TIMESTAMP") + assert millis == int(datetime(2023, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) + + +# ---- marker coverage: generic, time, and reading an externally-written INTEGER ---- + +class TestMarkerCoverage: + def test_generic_falls_back_to_str(self): + class Thing: + def __str__(self): + return "thing-repr" + assert dec(enc(Thing())) == "thing-repr" + + def test_time_round_trips_as_iso_text(self): + from datetime import time + value = time(13, 45, 30) + # LOCAL_TIME is written as ISO text and read back as that text. + assert dec(enc(value)) == value.isoformat() + + def test_reads_externally_written_integer_marker(self): + # This wrapper writes integers as LONG; the 4-byte INTEGER marker (2) is still understood on read. + import hashlib + import hmac + import struct + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + iv = b"\x09" * 12 + sealed = AESGCM(DATA_KEY).encrypt(iv, struct.pack(">i", 42), None) + body = struct.pack(">I", KEY_ID) + bytes([TypeMarker.INTEGER]) + iv + sealed + payload = hmac.new(HMAC_KEY, body, hashlib.sha256).digest() + body + assert dec(payload) == 42 + + def test_decimal_plain_not_scientific(self): + # The wire contract requires plain notation for a Decimal that would + # otherwise print in scientific notation. A round trip can't catch a + # scientific-notation serializer, because "1E+2" decodes back equal to + # 100 (str(Decimal("1E+2")) == "1E+2"), so assert the bytes. + value = Decimal("1E+2") + assert EncryptionService.serialize_value(value, TypeMarker.BIG_DECIMAL) == b"100" + out = dec(enc(value)) + assert out == value + + +class TestAlgorithm: + def test_unsupported_algorithm_raises(self): + with pytest.raises(InvalidAlgorithmError): + EncryptionService.encrypt("x", DATA_KEY, HMAC_KEY, "AES-999-XYZ", key_id=1) + + +# ===================================================================== +# Edge cases, plus tests that pin behavior specific to Python. +# ===================================================================== + + +def _resign(payload: bytes, hmac_key: bytes) -> bytes: + """Re-sign a payload whose body was edited, so a test can get past the + integrity check and exercise the decryption path itself.""" + body = payload[ES_TAG:] + return hmac.new(hmac_key, body, hashlib.sha256).digest() + body + + +ES_TAG = 32 # HMAC_TAG_LENGTH +ES_KEYID = 4 # KEY_ID_LENGTH +MARKER_OFFSET = ES_TAG + ES_KEYID + + +# ---- serialize_value: markers it can/can't write ---- + +class TestSerializeValue: + def test_raises_for_unknown_marker(self): + # 12345 is no marker at all, so any value is refused. + with pytest.raises(EncryptionFailedError, match="Unsupported type marker: 12345"): + EncryptionService.serialize_value("x", 12345) + + def test_long_overflow_raises_without_leaking_the_value(self): + # Every Python int but bool uses the LONG marker, so one outside the + # signed 64-bit range must be refused. The error must not expose the + # integer through its message, __cause__, or __context__. + too_big = 2 ** 63 # one past the signed 64-bit max + with pytest.raises(EncryptionFailedError) as ei: + enc(too_big) + err = ei.value + assert err.data_type == "LONG" + assert str(too_big) not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + def test_long_underflow_raises_without_leaking_the_value(self): + # The lower half of the range check, held to the same no-leak rule as + # the upper half. (test_long_out_of_range_keeps_its_own_message pins + # the message.) + too_small = -(2 ** 63) - 1 + with pytest.raises(EncryptionFailedError) as ei: + enc(too_small) + err = ei.value + assert err.data_type == "LONG" + assert str(too_small) not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + @pytest.mark.parametrize("value", [Decimal("NaN"), Decimal("Infinity"), Decimal("-Infinity"), Decimal("sNaN")]) + def test_non_finite_decimal_is_refused(self, value): + with pytest.raises(EncryptionFailedError): + enc(value) + + def test_aware_time_is_refused(self): + # A local time of day has no offset on the wire; writing one would drop it. + with pytest.raises(EncryptionFailedError): + enc(time(10, 30, tzinfo=timezone.utc)) + + def test_aware_datetime_cannot_be_forced_into_local_date_time(self): + with pytest.raises(EncryptionFailedError): + EncryptionService.serialize_value(datetime(2024, 1, 1, tzinfo=timezone.utc), TypeMarker.LOCAL_DATE_TIME) + + @pytest.mark.parametrize("value,expected", [ + (date(999, 1, 2), b"0999-01-02"), + (datetime(999, 1, 2, 3, 4, 5, 678), b"0999-01-02T03:04:05.000678"), + ]) + def test_years_before_1000_keep_four_digits(self, value, expected): + # strftime("%Y") does not zero-pad on every platform; the reader needs + # four digits. + assert EncryptionService.serialize_value(value) == expected + assert dec(enc(value)) == value + + @pytest.mark.parametrize("micros,expected_millis", [ + (1500, 2), (2500, 3), (2499, 2), (-1500, -2), (-2500, -3), + ]) + def test_millis_round_half_away_from_zero(self, micros, expected_millis): + value = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(microseconds=micros) + assert EncryptionService._to_millis(value, "TIMESTAMP") == expected_millis + + def test_millis_are_exact_far_from_the_epoch(self): + value = datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=timezone.utc) + expected = (value - datetime(1970, 1, 1, tzinfo=timezone.utc)) // timedelta(milliseconds=1) + assert EncryptionService._to_millis(value, "TIMESTAMP") == expected + + @pytest.mark.parametrize("value,marker", [ + (date(2024, 1, 2), TypeMarker.LOCAL_DATE_TIME), # a date is not a date-time + ("not a date", TypeMarker.LOCAL_DATE), + ("SECRET-123", TypeMarker.LONG), + ("SECRET-123", TypeMarker.INTEGER), + (2 ** 40, TypeMarker.INTEGER), # out of the 32-bit range + ("SECRET-123", TypeMarker.DOUBLE), + ("SECRET-123", TypeMarker.TIMESTAMP), + ("SECRET-123", TypeMarker.DATE), + (Decimal("NaN"), TypeMarker.LONG), # TypeError: a Decimal is not an integer + (7, TypeMarker.BYTE_ARRAY), # bytes(7) would be 7 zero bytes + ("false", TypeMarker.BOOLEAN), # not truthiness + (1e300, TypeMarker.FLOAT), # OverflowError: too large for a 32-bit float + (time(3, 4, 5), TypeMarker.LOCAL_DATE_TIME), # a time of day is not a date-time + ]) + def test_value_that_does_not_fit_an_explicit_marker(self, value, marker): + # Mostly reachable only with an explicit marker. The error is a wrapper + # error, names the marker, and quotes nothing of the value. + with pytest.raises(EncryptionFailedError) as ei: + EncryptionService.serialize_value(value, marker) + err = ei.value + assert "SECRET" not in str(err) + assert err.__cause__ is None and err.__context__ is None + assert err.data_type == TypeMarker.name_for(marker) + + @pytest.mark.parametrize("marker", [TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP]) + def test_out_of_range_instant_is_refused_naming_its_marker(self, marker): + value = datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))) # after year 9999 in UTC + with pytest.raises(EncryptionFailedError, match="outside the range") as ei: + EncryptionService.serialize_value(value, marker) + assert ei.value.data_type == TypeMarker.name_for(marker) + + @pytest.mark.parametrize("value", [bytearray(b"\x00\x01\xff"), memoryview(b"\x00\x01\xff")], + ids=["bytearray", "memoryview"]) + def test_bytes_like_values_round_trip_as_byte_array(self, value): + # bytearray and memoryview (bytes is covered above) are accepted as + # BYTE_ARRAY, and the caller's buffer is left alone. + assert EncryptionService.serialize_value(value) == b"\x00\x01\xff" + assert dec(enc(value)) == b"\x00\x01\xff" + assert bytes(value) == b"\x00\x01\xff" + + @pytest.mark.parametrize("value", [1, 0]) + def test_int_is_not_written_as_boolean(self, value): + with pytest.raises(EncryptionFailedError) as ei: + EncryptionService.serialize_value(value, TypeMarker.BOOLEAN) + assert ei.value.data_type == "BOOLEAN" + + @pytest.mark.parametrize("value", [1e300, Decimal("1E+30"), 1.5]) + def test_non_int_as_long_gets_the_generic_message(self, value): + with pytest.raises(EncryptionFailedError, match="Cannot write a value of type") as ei: + EncryptionService.serialize_value(value, TypeMarker.LONG) + assert ei.value.data_type == "LONG" + + def test_instant_just_past_the_last_millisecond_is_refused(self): + # The clamp only undoes rounding: the first millisecond after year + # 9999 in UTC (no sub-millisecond part to round) is still refused. + value = datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-1))) # 10000-01-01T00:00Z + with pytest.raises(EncryptionFailedError, match="outside the range"): + EncryptionService.serialize_value(value) + + def test_int_subclass_is_written_as_long(self): + # TypeMarker.from_object sends any int but bool (an IntEnum, say) + # to LONG. + from enum import IntEnum + + class Level(IntEnum): + HIGH = 7 + + assert EncryptionService.serialize_value(Level.HIGH) == EncryptionService.serialize_value(7) + assert dec(enc(Level.HIGH)) == 7 + + def test_integer_like_value_is_accepted_as_long(self): + # Anything with __index__ (numpy integer types, for example) is + # accepted as LONG, as it is as INTEGER. + class Index: + def __index__(self): + return 5 + + assert EncryptionService.serialize_value(Index(), TypeMarker.LONG) == struct.pack(">q", 5) + + def test_value_whose_str_fails_is_refused(self): + # str() of a huge int raises ValueError (the int-digit limit). + with pytest.raises(EncryptionFailedError) as ei: + EncryptionService.serialize_value(10 ** 5000, TypeMarker.STRING) + assert ei.value.__cause__ is None and ei.value.__context__ is None + + @pytest.mark.parametrize("value", [2 ** 63, -(2 ** 63) - 1]) + def test_long_out_of_range_keeps_its_own_message(self, value): + with pytest.raises(EncryptionFailedError, match="signed 64-bit range"): + EncryptionService.serialize_value(value) + + def test_datetime_written_as_local_date_keeps_only_the_date(self): + data = EncryptionService.serialize_value(datetime(2024, 1, 2, 3, 4, 5), TypeMarker.LOCAL_DATE) + assert data == b"2024-01-02" + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_DATE) == date(2024, 1, 2) + + @pytest.mark.parametrize("value", [ + datetime(1, 1, 1, 0, 30, tzinfo=timezone(timedelta(hours=1))), # before year 1 in UTC + datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))), # after year 9999 in UTC + ]) + def test_timestamp_that_could_not_be_read_back_is_refused(self, value): + with pytest.raises(EncryptionFailedError): + enc(value) + + def test_timestamp_at_the_edges_of_the_range_round_trips(self): + for value in (datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=timezone.utc), + datetime(1, 1, 1, tzinfo=timezone.utc)): + assert dec(enc(value)) == value + + def test_aware_datetime_max_keeps_its_last_millisecond(self): + # A common "never" value: rounding .999999 up would pass the end of + # the range, so it keeps the last representable millisecond instead. + value = datetime.max.replace(tzinfo=timezone.utc) + assert dec(enc(value)) == value.replace(microsecond=999000) + + def test_long_boundary_values_round_trip(self): + # The signed 64-bit edges serialize and decrypt back exactly. + for value in (2 ** 63 - 1, -(2 ** 63)): + assert dec(enc(value)) == value + + @pytest.mark.parametrize("value", [Color.RED, Masked("red")], ids=["str_enum", "overridden_str"]) + def test_str_subclass_is_stored_as_its_own_text(self, value): + # str() gives 'Color.RED' for the member and '***' for Masked. + assert EncryptionService.serialize_value(value) == b"red" + + def test_str_subclass_reads_back_as_plain_str(self): + out = dec(enc(Color.RED)) + assert out == "red" and type(out) is str + + @pytest.mark.parametrize("value,marker,expected", [ + (Color.RED, TypeMarker.GENERIC, b"Color.RED"), + (42, TypeMarker.STRING, b"42"), + (Decimal("1.5"), TypeMarker.STRING, b"1.5"), + ]) + def test_generic_and_non_str_under_string_keep_str_of_value(self, value, marker, expected): + assert EncryptionService.serialize_value(value, marker) == expected + + def test_object_that_only_claims_to_be_a_str_keeps_str_of_value(self, mocker): + # isinstance() trusts a faked __class__ (proxies, mocks) and picks + # STRING, but str.__str__ needs a real str, so the check is on type(). + proxy = mocker.MagicMock(spec=str) + proxy.__str__.return_value = "red" + assert EncryptionService.serialize_value(proxy) == b"red" + + +# ---- deserialize_value: reading every marker ---- + +class TestDeserializeExternalMarkers: + """This wrapper never writes some of these markers or forms, but it must + read every one.""" + + def test_reads_32bit_integer(self): + assert EncryptionService.deserialize_value(struct.pack(">i", 42), TypeMarker.INTEGER) == 42 + + def test_reads_32bit_float(self): + assert EncryptionService.deserialize_value(struct.pack(">f", 1.5), TypeMarker.FLOAT) == 1.5 + + def test_reads_date_marker_as_date(self): + millis = int(datetime(2026, 8, 11, tzinfo=timezone.utc).timestamp() * 1000) + out = EncryptionService.deserialize_value(struct.pack(">q", millis), TypeMarker.DATE) + assert out == date(2026, 8, 11) + + def test_reads_time_marker_as_datetime(self): + millis = int(datetime(2026, 8, 11, 12, 30, 45, tzinfo=timezone.utc).timestamp() * 1000) + out = EncryptionService.deserialize_value(struct.pack(">q", millis), TypeMarker.TIME) + assert abs(out.timestamp() - millis / 1000.0) < 0.001 + + def test_reads_local_time_as_string(self): + data = EncryptionService.serialize_value("12:30:45", TypeMarker.LOCAL_TIME) + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_TIME) == "12:30:45" + + @pytest.mark.parametrize("text,expected", [ + # The local date-time forms the reader accepts: with or without seconds, + # and with 3, 6, or 9 fractional digits. A naive fromisoformat fails on + # the 9-digit (nanosecond) form on the Python 3.10 floor, so that form + # needs coverage. + ("2007-12-03T10:15", datetime(2007, 12, 3, 10, 15)), + ("2007-12-03T10:15:30", datetime(2007, 12, 3, 10, 15, 30)), + ("2007-12-03T10:15:30.123", datetime(2007, 12, 3, 10, 15, 30, 123000)), + ("2007-12-03T10:15:30.123456", datetime(2007, 12, 3, 10, 15, 30, 123456)), + # nanoseconds truncated to microseconds (datetime has no finer precision) + ("2007-12-03T10:15:30.123456789", datetime(2007, 12, 3, 10, 15, 30, 123456)), + # a suffix after the fraction is kept, whatever the fraction's length + ("2007-12-03T10:15:30.123456789+00:00", datetime(2007, 12, 3, 10, 15, 30, 123456, tzinfo=timezone.utc)), + ("2007-12-03T10:15:30.123+00:00", datetime(2007, 12, 3, 10, 15, 30, 123000, tzinfo=timezone.utc)), + ]) + def test_reads_every_accepted_local_date_time_form(self, text, expected): + data = text.encode("utf-8") + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_DATE_TIME) == expected + + def test_reads_own_local_date_time_write_form(self): + # Round-trip the form this wrapper writes for a whole-second value, + # which has no fraction. + value = datetime(2023, 6, 15, 13, 45, 30) + data = EncryptionService.serialize_value(value, TypeMarker.LOCAL_DATE_TIME) + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_DATE_TIME) == value + + def test_unparseable_local_date_time(self): + with pytest.raises(TypeConversionError): + EncryptionService.deserialize_value(b"not a datetime", TypeMarker.LOCAL_DATE_TIME) + + def test_wrong_width_for_marker(self): + with pytest.raises(EncryptionError) as ei: + EncryptionService.deserialize_value(b"ab", TypeMarker.INTEGER) + assert "Expected 4 bytes for INTEGER, got 2" in str(ei.value) + + def test_unparseable_big_decimal(self): + with pytest.raises(TypeConversionError): + EncryptionService.deserialize_value(b"not a number", TypeMarker.BIG_DECIMAL) + + def test_unparseable_local_date(self): + with pytest.raises(TypeConversionError): + EncryptionService.deserialize_value(b"not a date", TypeMarker.LOCAL_DATE) + + @pytest.mark.parametrize("marker,data", [ + (TypeMarker.LOCAL_DATE, b"SECRET-ssn-123-45-6789"), + (TypeMarker.LOCAL_DATE_TIME, b"SECRET-ssn-123-45-6789"), + (TypeMarker.BIG_DECIMAL, b"SECRET-ssn-123-45-6789"), + # UnicodeDecodeError.object holds the raw plaintext bytes. + (TypeMarker.STRING, b"SECRET-ssn-\xff"), + ]) + def test_deserialize_error_does_not_leak_plaintext(self, marker, data): + # A value that passes HMAC and GCM but doesn't parse as its declared + # type must not leak its plaintext through the error message, + # __cause__, or __context__. This is the read-side counterpart of the + # encrypt-side leak tests. + with pytest.raises(TypeConversionError) as ei: + EncryptionService.deserialize_value(data, marker) + err = ei.value + assert "SECRET" not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + @pytest.mark.parametrize("marker", [TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP]) + @pytest.mark.parametrize("millis", [2 ** 63 - 1, -(2 ** 63), 10 ** 15]) + def test_out_of_range_epoch_millis_is_a_type_conversion_error(self, marker, millis): + # Another writer can store epoch millis no datetime can hold; the + # resulting OverflowError must surface as the wrapper's error. + with pytest.raises(TypeConversionError) as ei: + EncryptionService.deserialize_value(struct.pack(">q", millis), marker) + assert ei.value.__cause__ is None and ei.value.__context__ is None + + def test_unknown_marker_on_read(self): + with pytest.raises(EncryptionError) as ei: + EncryptionService.deserialize_value(b"x", 12345) + assert "Unsupported type marker: 12345" in str(ei.value) + + +# ---- decrypt path: unknown marker inside a (re-signed) payload ---- + +def test_decrypt_rejects_unknown_marker_in_payload(): + payload = bytearray(enc("123-45-6789")) + payload[MARKER_OFFSET] = 77 # overwrite the marker byte + resigned = _resign(bytes(payload), HMAC_KEY) + with pytest.raises(DecryptionError) as ei: + dec(resigned) + assert "Unknown type marker: 77" in str(ei.value) + + +# ---- decrypt-path data-key validation (past length check, before GCM) ---- + +def test_decrypt_rejects_wrong_length_data_key(): + payload = enc("123-45-6789") + with pytest.raises(InvalidKeyError): + EncryptionService.decrypt(payload, bytes(range(16)), HMAC_KEY) + + +# ---- missing data key / hmac key messages ---- + +def test_missing_data_key_message(): + with pytest.raises(EncryptionError) as ei: + EncryptionService.encrypt("x", None, HMAC_KEY, key_id=1) + assert "got None" in str(ei.value) + + +# ---- target-type coercion edge cases ---- + +class TestTargetTypeEdges: + def test_boolean_db_spellings_true(self): + for v in ("t", "true", "TRUE", "y", "yes", "1"): + assert dec(enc(v), target_type=bool) is True + + def test_boolean_db_spellings_false(self): + for v in ("f", "false", "n", "no", "0", ""): + assert dec(enc(v), target_type=bool) is False + + def test_already_target_type_passes_through(self): + assert dec(enc("42"), target_type=str) == "42" + + def test_unknown_target_type_raises(self): + with pytest.raises(TypeConversionError): + dec(enc("abc"), target_type=list) + + def test_uncoercible_value_raises(self): + with pytest.raises(TypeConversionError): + dec(enc("abc"), target_type=int) + + @pytest.mark.parametrize("value", [float("inf"), float("nan"), Decimal("Infinity")]) + def test_non_finite_to_int_is_a_type_conversion_error(self, value): + # int() raises OverflowError / ValueError here, outside the PEP 249 + # hierarchy unless it is converted. + with pytest.raises(TypeConversionError) as ei: + EncryptionService._convert_to_target_type(value, int) + assert ei.value.__cause__ is None + assert ei.value.__context__ is None + + @pytest.mark.parametrize("target_type", [int, float, Decimal]) + def test_target_type_coercion_failure_does_not_leak_plaintext(self, target_type): + # A value that decrypts but can't be coerced to the requested + # target_type must not leak its plaintext through the error message, + # __cause__, or __context__. int() and float() quote their input + # ("invalid literal for int() ... 'SECRET...'"), so this path needs its + # own test alongside the deserialize and encrypt leak tests. + secret = "SECRET-ssn-123-45-6789" + with pytest.raises(TypeConversionError) as ei: + dec(enc(secret), target_type=target_type) + err = ei.value + assert "SECRET" not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + def test_float_to_int_target_truncates_python_difference(self): + # int(1.5) truncates to 1 rather than raising. target_type is an + # explicit opt-in and default reads return strings, so Python keeps its + # native semantics. The test pins this so any change gets noticed. + assert dec(enc(1.5), target_type=int) == 1 + + +# ---- key and plaintext buffers ---- + +def test_encrypt_wipes_the_buffer_aes_gcm_saw_and_copies_no_key(monkeypatch): + # The keys reach AES-GCM and HMAC as given (no immutable copy of a + # bytearray key), and the plaintext buffer AES-GCM read is the one wiped. + from types import SimpleNamespace + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + from aws_advanced_python_wrapper.encryption import encryption_service + seen = {} + + class SpyAESGCM: + def __init__(self, key): + seen["data_key"] = key + self._real = AESGCM(key) + + def encrypt(self, iv, plaintext, aad): + seen["plaintext"] = plaintext + return self._real.encrypt(iv, plaintext, aad) + + def spy_hmac_new(key, msg, digestmod): + seen["hmac_key"] = key + return hmac.new(key, msg, digestmod) + + monkeypatch.setattr(encryption_service, "AESGCM", SpyAESGCM) + monkeypatch.setattr(encryption_service, "hmac", SimpleNamespace(new=spy_hmac_new, compare_digest=hmac.compare_digest)) + data_key, hmac_key = bytearray(DATA_KEY), bytearray(HMAC_KEY) + EncryptionService.encrypt("secret", data_key, hmac_key, key_id=1) + assert seen["data_key"] is data_key + assert seen["hmac_key"] is hmac_key + assert isinstance(seen["plaintext"], bytearray) + assert seen["plaintext"] == bytearray(len(seen["plaintext"])) + + +@pytest.mark.parametrize("dk_type,hk_type", [ + (memoryview, memoryview), (bytearray, memoryview), (memoryview, bytes)]) +def test_memoryview_keys_are_accepted(dk_type, hk_type): + # BytesLike includes memoryview; hmac does not accept one directly. + dk, hk = dk_type(DATA_KEY), hk_type(HMAC_KEY) + payload = EncryptionService.encrypt("v", dk, hk, key_id=1) + assert EncryptionService.decrypt(payload, dk, hk) == "v" + assert EncryptionService.decrypt(payload, DATA_KEY, HMAC_KEY) == "v" + + +# ---- immutability: the caller's value is not mutated ---- + +def test_encrypt_does_not_mutate_caller_bytes(): + value = bytearray(b"123-45-6789") + snapshot = bytes(value) + enc(bytes(value)) + assert bytes(value) == snapshot + + +# ---- precision contract ---- + +class TestPrecision: + def test_timestamp_marker_keeps_millisecond(self): + # A value read via the TIMESTAMP marker keeps millisecond precision + # (epoch-millis storage). + millis = int(datetime(2026, 8, 11, 12, 30, 45, 123000, tzinfo=timezone.utc).timestamp() * 1000) + out = EncryptionService.deserialize_value(struct.pack(">q", millis), TypeMarker.TIMESTAMP) + assert abs(out.timestamp() * 1000 - millis) < 1.0 + + def test_aware_datetime_keeps_its_instant(self): + # An aware datetime is written as TIMESTAMP (epoch millis), so the + # instant survives and it reads back as aware UTC, to the millisecond. + v = datetime(2024, 1, 1, 12, 0, 0, 123456, tzinfo=timezone(timedelta(hours=5))) + payload = enc(v) + assert payload[MARKER_OFFSET] == TypeMarker.TIMESTAMP + out = dec(payload) + assert out == v.replace(microsecond=123000) + assert out.utcoffset() == timedelta(0) + + def test_naive_datetime_keeps_microseconds(self): + # A naive datetime is written as LOCAL_DATE_TIME (ISO text) with its + # fraction, so it reads back equal, to the microsecond. + v = datetime(2026, 8, 11, 12, 30, 45, 123456) + payload = enc(v) + assert payload[MARKER_OFFSET] == TypeMarker.LOCAL_DATE_TIME + out = dec(payload) + assert out == v + assert out.microsecond == 123456 + + def test_whole_second_naive_datetime_text_is_unchanged(self): + # isoformat() leaves out a zero fraction, so a whole-second value is + # still written as YYYY-MM-DDTHH:MM:SS and its stored text stays the + # same. + v = datetime(2026, 8, 11, 12, 30, 45) + assert EncryptionService.serialize_value(v) == b"2026-08-11T12:30:45" + + +# ---- no-UTF-8-form string is refused without quoting the plaintext ---- + +def test_lone_surrogate_string_refused_without_quoting_plaintext(): + secret = "secret-\ud800-value" # lone surrogate: no valid UTF-8 form + with pytest.raises(EncryptionError) as ei: + enc(secret) + # UnicodeEncodeError holds the plaintext in .object. The production code + # raises outside the except block so that error isn't attached as + # __cause__ or __context__. Check the plaintext isn't reachable at all. + assert "secret" not in str(ei.value) + assert ei.value.__cause__ is None + assert ei.value.__context__ is None + + +# ---- GCM auth independence from HMAC ---- + +def test_gcm_auth_tag_bound_to_data_key(): + # A payload encrypted+signed under a different data key (same HMAC key) must + # pass the HMAC check but fail GCM when decrypted with the original data key. + other_dk = bytes([(b + 7) % 256 for b in DATA_KEY]) + other = EncryptionService.encrypt("v", other_dk, HMAC_KEY, key_id=KEY_ID) + with pytest.raises(DecryptionError): + dec(other) # HMAC matches (HMAC_KEY), data key wrong for DATA_KEY decrypt + + +# ---- exception hierarchy: lenient read mode relies on this ---- + +class TestExceptionHierarchy: + """The read path's lenient mode (encryption_return_unverified_data) will + catch IntegrityCheckError and let every other failure through. These tests + pin the class hierarchy that makes `except IntegrityCheckError` work. + """ + + def test_integrity_check_error_classifies_as_integrity_error(self): + # SQLAlchemy takes the first PEP 249 class in the MRO, so + # IntegrityError has to come before EncryptionError's OperationalError. + from aws_advanced_python_wrapper.pep249 import (IntegrityError, + OperationalError) + mro = IntegrityCheckError.__mro__ + assert mro.index(IntegrityError) < mro.index(OperationalError) + sqlalchemy_exc = pytest.importorskip("sqlalchemy.exc") + wrapped = sqlalchemy_exc.DBAPIError.instance("SELECT 1", {}, IntegrityCheckError("x"), Exception) + assert isinstance(wrapped, sqlalchemy_exc.IntegrityError) + + def test_integrity_and_decryption_are_distinct_subclasses(self): + assert issubclass(IntegrityCheckError, EncryptionError) + assert issubclass(DecryptionError, EncryptionError) + assert not issubclass(DecryptionError, IntegrityCheckError) + + def test_tampered_value_is_catchable_as_integrity_only(self): + payload = bytearray(enc("hello")) + payload[-1] ^= 0xFF + # Lenient mode would swallow this... + with pytest.raises(IntegrityCheckError): + dec(bytes(payload)) + + def test_wrong_key_is_not_an_integrity_error(self): + # ...but it must not swallow a wrong-key failure. That raises + # DecryptionError, which is not an IntegrityCheckError. + wrong_dk = bytes([(b + 1) % 256 for b in DATA_KEY]) + with pytest.raises(DecryptionError): + dec(enc("hello"), dk=wrong_dk) + try: + dec(enc("hello"), dk=wrong_dk) + except IntegrityCheckError: # pragma: no cover - must not happen + pytest.fail("wrong-key failure must not be an IntegrityCheckError") + except DecryptionError: + pass diff --git a/tests/unit/test_key_management_utility.py b/tests/unit/test_key_management_utility.py new file mode 100644 index 000000000..f8ae7bf05 --- /dev/null +++ b/tests/unit/test_key_management_utility.py @@ -0,0 +1,320 @@ +# 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. + +import logging +from typing import Any, List, Tuple +from unittest.mock import MagicMock, create_autospec + +import boto3 +import pytest +from botocore.stub import Stubber + +from aws_advanced_python_wrapper.encryption import \ + key_management_utility as kmu_module +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 ( + GeneratedDataKey, KeyManager) +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata, mask_arn) +from aws_advanced_python_wrapper.encryption.sql_dialect import (MYSQL, PG, + SqlDialect, + fetch_rows) +from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + InvalidAlgorithmError, + KeyManagementError) + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" +ALIAS_ARN = "arn:aws:kms:us-east-1:123456789012:alias/python-kms-encryption-1700000000000" +ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/kiro-admin-role/kiro-admin-session" + + +class RecordingConnection: + """A raw-driver-shaped connection that records SQL and must never be + committed, rolled back, or closed by the utility.""" + + def __init__(self): + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + self.rowcount = 1 + self.rows: List[Tuple[Any, ...]] = [] + self.commit = MagicMock(side_effect=AssertionError("utility must not commit")) + self.rollback = MagicMock(side_effect=AssertionError("utility must not roll back")) + self.close = MagicMock(side_effect=AssertionError("utility must not close")) + + def cursor(self): + conn = self + + class Cursor: + description = [("table_name",), ("column_name",)] + + def execute(self, sql, params=()): + conn.executed.append((sql, tuple(params))) + self.rowcount = conn.rowcount + + def fetchall(self): + return conn.rows + + def close(self): + pass + + return Cursor() + + +@pytest.fixture +def conn(): + return RecordingConnection() + + +def config(restricted=False): + return EncryptionConfig(kms_region="us-east-1", + allowed_master_key_arns=frozenset({ARN}) if restricted else frozenset()) + + +def utility(conn, restricted=False, engine="postgresql"): + kms = MagicMock() + u = KeyManagementUtility(conn, kms, config(restricted), engine=engine) + # Autospec, so a misspelled method fails here as it would in production. + u._key_manager = create_autospec(KeyManager, instance=True) + u._key_manager.generate_data_key.return_value = GeneratedDataKey( + bytearray(b"P" * 32), "ZWRr", b"h" * 32, "AES_256") + u._key_manager.store_key_metadata.side_effect = lambda km: KeyMetadata(**{**km.__dict__, "id": 11}) + u._metadata = create_autospec(MetadataManager, instance=True) + u._metadata.is_column_encrypted.return_value = False + return u, kms + + +class TestInitialize: + def test_generates_stores_and_upserts_metadata(self, conn): + u, _ = utility(conn) + assert u.initialize_encryption_for_column("users", "ssn", ARN) == 11 + stored = u._key_manager.store_key_metadata.call_args[0][0] + assert stored.master_key_arn == ARN and stored.key_spec == "AES_256" + assert stored.key_name.startswith("key-users-ssn-") + sql, params = conn.executed[-1] + assert sql.startswith("INSERT INTO encrypt.encryption_metadata") + assert "ON CONFLICT (table_name, column_name) DO UPDATE SET encryption_algorithm = " \ + "EXCLUDED.encryption_algorithm, key_id = EXCLUDED.key_id, updated_at = CURRENT_TIMESTAMP" in sql + assert params == ("users", "ssn", "AES-256-GCM", 11) + + def test_wipes_the_generated_plaintext(self, conn): + u, _ = utility(conn) + u.initialize_encryption_for_column("users", "ssn", ARN) + generated = u._key_manager.generate_data_key.return_value + assert generated.plaintext == bytearray(32) + + def test_wipes_the_plaintext_even_when_storing_fails(self, conn): + u, _ = utility(conn) + u._key_manager.store_key_metadata.side_effect = KeyManagementError("x") + with pytest.raises(KeyManagementError): + u.initialize_encryption_for_column("users", "ssn", ARN) + assert u._key_manager.generate_data_key.return_value.plaintext == bytearray(32) + + def test_mysql_upsert_grammar(self, conn): + u, _ = utility(conn, engine="mysql") + u.initialize_encryption_for_column("users", "ssn", ARN, "AES-128-GCM") + sql = conn.executed[-1][0] + assert "ON DUPLICATE KEY UPDATE encryption_algorithm = VALUES(encryption_algorithm), " \ + "key_id = VALUES(key_id), updated_at = CURRENT_TIMESTAMP" in sql + u._key_manager.generate_data_key.assert_called_with(ARN, "AES-128-GCM") + + def test_refuses_an_already_encrypted_column(self, conn): + u, _ = utility(conn) + u._metadata.is_column_encrypted.return_value = True + with pytest.raises(KeyManagementError, match="already encrypted"): + u.initialize_encryption_for_column("users", "ssn", ARN) + u._key_manager.generate_data_key.assert_not_called() + + def test_unsupported_algorithm(self, conn): + u, _ = utility(conn) + with pytest.raises(InvalidAlgorithmError): + u.initialize_encryption_for_column("users", "ssn", ARN, "DES") + + @pytest.mark.parametrize("args", [(None, "c", ARN), ("t", "", ARN), ("t", "c", None)]) + def test_required_arguments(self, conn, args): + u, _ = utility(conn) + with pytest.raises(ValueError): + u.initialize_encryption_for_column(*args) + + def test_statement_failure_is_wrapped(self, conn): + u, _ = utility(conn) + conn.cursor = MagicMock(side_effect=RuntimeError("fk violation")) + with pytest.raises(KeyManagementError, match="fk violation"): + u.initialize_encryption_for_column("users", "ssn", ARN) + + +class TestRotate: + def _current(self, u, arn=ARN, algorithm="AES-256-GCM"): + km = KeyMetadata(id=4, master_key_arn=arn, encrypted_data_key="e", hmac_key=b"h") + u._metadata.column_config.return_value = ColumnEncryptionConfig( + "users", "ssn", algorithm, 4, km if arn else None) + + def test_rotate_onto_the_current_master_key_needs_the_allow_list(self, conn): + u, _ = utility(conn, restricted=False) + with pytest.raises(ValueError, match="encryption_allowed_master_key_arns"): + u.rotate_data_key("users", "ssn") + + def test_rotate_keeping_the_current_master_key(self, conn): + u, _ = utility(conn, restricted=True) + self._current(u, algorithm="AES-128-GCM") + assert u.rotate_data_key("users", "ssn") == 11 + u._key_manager.generate_data_key.assert_called_with(ARN, "AES-128-GCM") + sql, params = conn.executed[-1] + assert sql.startswith("UPDATE encrypt.encryption_metadata SET key_id = %s") + assert params == (11, "users", "ssn") + + def test_rotate_onto_a_new_master_key(self, conn): + u, _ = utility(conn) + self._current(u) + other = ARN.replace("1234abcd", "eeeeeeee") + u.rotate_data_key("users", "ssn", other) + u._key_manager.generate_data_key.assert_called_with(other, "AES-256-GCM") + + def test_rotate_unknown_column(self, conn): + u, _ = utility(conn) + u._metadata.column_config.return_value = None + with pytest.raises(KeyManagementError, match="No kms_encryption configuration"): + u.rotate_data_key("users", "ssn", ARN) + + def test_rotate_with_missing_key_row_and_no_new_arn(self, conn): + u, _ = utility(conn, restricted=True) + self._current(u, arn=None) + with pytest.raises(KeyManagementError, match="no current master key"): + u.rotate_data_key("users", "ssn") + + def test_rotate_fails_if_no_row_was_updated(self, conn): + u, _ = utility(conn) + self._current(u) + conn.rowcount = 0 + with pytest.raises(KeyManagementError): + u.rotate_data_key("users", "ssn", ARN) + + +class TestRemoveAndQuery: + def test_remove_deletes_only_the_metadata_row(self, conn): + u, _ = utility(conn) + assert u.remove_encryption_for_column("users", "ssn") is True + assert len(conn.executed) == 1 + sql, params = conn.executed[0] + assert sql.startswith("DELETE FROM encrypt.encryption_metadata ") + assert "key_storage" not in sql + assert params == ("users", "ssn") + + def test_remove_reports_nothing_removed(self, conn): + u, _ = utility(conn) + conn.rowcount = 0 + assert u.remove_encryption_for_column("users", "ssn") is False + + def test_columns_using_key(self, conn): + u, _ = utility(conn) + conn.rows = [("orders", "card"), ("users", "ssn")] + assert u.columns_using_key(4) == ["orders.card", "users.ssn"] + assert conn.executed[0][1] == (4,) + + +class TestMasterKeys: + def test_create_master_key_with_alias(self, conn): + u, kms = utility(conn) + u._key_manager.create_master_key.return_value = ARN + assert u.create_master_key("d") == ARN + alias = kms.create_alias.call_args.kwargs + assert alias["AliasName"].startswith("alias/python-kms-encryption-") + assert alias["TargetKeyId"] == ARN + + def test_alias_failure_is_not_fatal(self, conn): + u, kms = utility(conn) + u._key_manager.create_master_key.return_value = ARN + kms.create_alias.side_effect = RuntimeError("AlreadyExists") + assert u.create_master_key("d") == ARN + + # AWS KMS's own texts: they name the alias, and an access denial names + # the caller's role session. + @pytest.mark.parametrize("code, text", [ + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:CreateAlias on resource: " + f"{ALIAS_ARN} because no identity-based policy allows the kms:CreateAlias action", + id="access-denied"), + pytest.param("AlreadyExistsException", f"An alias with the name {ALIAS_ARN} already exists", + id="already-exists"), + ]) + def test_alias_failure_warning_masks_the_arns_kms_quotes(self, conn, caplog, code, text): + kms = boto3.client("kms", region_name="us-east-1", aws_access_key_id="x", aws_secret_access_key="x") + u = KeyManagementUtility(conn, kms, config(), engine="postgresql") + u._key_manager = create_autospec(KeyManager, instance=True) + u._key_manager.create_master_key.return_value = ARN + with Stubber(kms) as stubber, caplog.at_level(logging.WARNING, logger=kmu_module.__name__): + stubber.add_client_error("create_alias", code, service_message=text, http_status_code=400) + assert u.create_master_key("d") == ARN + stubber.assert_no_pending_responses() + # By logger name: threads other tests leave behind also log into caplog. + warnings = [r.getMessage() for r in caplog.records + if r.name == kmu_module.__name__ and r.levelno == logging.WARNING] + assert len(warnings) == 1 + assert f"({code})" in warnings[0] and mask_arn(ARN) in warnings[0] + assert "arn:aws:kms:***:***:***" in warnings[0] + for identifier in (ARN, ALIAS_ARN, ROLE_SESSION_ARN, "123456789012", "kiro-admin-role", "kiro-admin-session"): + assert identifier not in warnings[0] + + def test_no_alias(self, conn): + u, kms = utility(conn) + u._key_manager.create_master_key.return_value = ARN + u.create_master_key("d", create_alias=False) + kms.create_alias.assert_not_called() + + +class TestEngineInference: + def test_requires_arguments(self, conn): + with pytest.raises(ValueError): + KeyManagementUtility(None, MagicMock(), config()) + + def test_unknown_driver(self, conn): + with pytest.raises(EncryptionConfigError): + KeyManagementUtility(conn, MagicMock(), config()) + + def test_infers_from_driver_module_and_wrapper_connection(self): + pg_conn = type("Connection", (), {"__module__": "psycopg"})() + mysql_conn = type("CMySQLConnection", (), {"__module__": "mysql.connector.connection_cext"})() + wrapper = type("AwsWrapperConnection", (), {"target_connection": mysql_conn})() + assert SqlDialect.for_connection(pg_conn) is PG + assert SqlDialect.for_connection(mysql_conn) is MYSQL + assert SqlDialect.for_connection(wrapper) is MYSQL + assert SqlDialect.for_name("PostgreSQL") is PG + + def test_from_driver_dialect(self): + assert SqlDialect.for_driver_dialect(MagicMock(dialect_code="psycopg")) is PG + assert SqlDialect.for_driver_dialect(MagicMock(dialect_code="mysql-connector-python")) is MYSQL + with pytest.raises(EncryptionConfigError): + SqlDialect.for_driver_dialect(MagicMock(dialect_code="generic")) + + +def test_fetch_rows_lower_cases_keys_and_handles_no_result(): + conn = RecordingConnection() + conn.rows = [("t", "c")] + assert fetch_rows(conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] + + +def test_fetch_rows_accepts_dict_rows(): + # A connection opened with a dict-like row factory (psycopg dict_row) + # returns mappings; their keys are lower-cased like tuple rows' names. + conn = RecordingConnection() + conn.rows = [{"TABLE_NAME": "t", "column_name": "c"}] # type: ignore[list-item] + assert fetch_rows(conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] + + +def test_columns_using_key_with_dict_rows(conn): + conn.rows = [{"table_name": "users", "column_name": "ssn"}] # type: ignore[list-item] + u, _ = utility(conn) + assert u.columns_using_key(3) == ["users.ssn"] diff --git a/tests/unit/test_key_manager.py b/tests/unit/test_key_manager.py new file mode 100644 index 000000000..0c660535e --- /dev/null +++ b/tests/unit/test_key_manager.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. + +import base64 +import json +import logging +import threading +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack, contextmanager +from typing import Any, List, Optional, Tuple + +import boto3 +import pytest +from botocore.awsrequest import AWSResponse +from botocore.exceptions import ClientError, EndpointConnectionError +from botocore.stub import Stubber + +from aws_advanced_python_wrapper.encryption import key_manager as km_module +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +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.models import KeyMetadata, mask_arn +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.errors import (InvalidKeyMetadataError, + KeyManagementError, + OperationalError, + UnauthorizedMasterKeyError) + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" +OTHER_ARN = "arn:aws:kms:us-east-1:123456789012:key/ffffffff-12ab-34cd-56ef-1234567890ab" +DATA_KEY = bytes(range(32)) +BLOB = b"kms-ciphertext-blob" +EDK = base64.b64encode(BLOB).decode() +# The caller's identity, as KMS names it when it denies a call. +ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/kiro-app-role/kiro-app-session" +MASKED_ROLE_SESSION_ARN = "arn:aws:sts:***:***:***" + + +class FakeCursor: + def __init__(self, db: "FakeDb"): + self._db = db + self.description: Optional[List[Tuple[str]]] = None + self.rowcount = -1 + self.lastrowid = None + self._rows: List[Tuple[Any, ...]] = [] + + def execute(self, sql, params=()): + self._db.executed.append((sql, tuple(params))) + if self._db.error is not None: + raise self._db.error + names, rows = self._db.result + self.description = [(n,) for n in names] if names else None + self._rows = list(rows) + self.rowcount = self._db.rowcount + self.lastrowid = self._db.lastrowid + + def fetchone(self): + return self._rows[0] if self._rows else None + + def fetchall(self): + return self._rows + + def close(self): + pass + + +class FakeDb: + def __init__(self): + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + self.result: Tuple[List[str], List[Tuple[Any, ...]]] = ([], []) + self.rowcount = 1 + self.lastrowid: Optional[int] = None + self.error: Optional[Exception] = None + + def cursor(self): + return FakeCursor(self) + + @contextmanager + def connection(self): + yield self + + +def config(**overrides) -> EncryptionConfig: + values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), + key_management_retry_backoff_base_sec=0.1) + values.update(overrides) + return EncryptionConfig(**values) # type: ignore[arg-type] + + +@pytest.fixture +def kms(): + client = boto3.client("kms", region_name="us-east-1", + aws_access_key_id="x", aws_secret_access_key="x") + with Stubber(client) as stubber: + yield client, stubber + stubber.assert_no_pending_responses() + + +@pytest.fixture +def db(): + return FakeDb() + + +LOGGERS = ("", "botocore", "botocore.parsers", "botocore.endpoint", "botocore.auth") +OUR_FILTERS = (km_module._NoKmsPlaintext, km_module._NoKmsRequestCredentials) + + +@pytest.fixture(autouse=True) +def no_filters(mocker): + """Neither filter installed when the test starts; every logger's filters + as they were when it ends. Every test in this module uses it, so the + module leaves the process's loggers and install flag as it found them.""" + loggers = [logging.getLogger(name) for name in LOGGERS] + saved = [list(lg.filters) for lg in loggers] + for lg in loggers: + lg.filters = [f for f in lg.filters if not isinstance(f, OUR_FILTERS)] + mocker.patch.object(km_module, "_filters_installed", False) + yield + for lg, filters in zip(loggers, saved): + lg.filters = filters + + +def manager(kms_client, db, cfg=None, cache=None, sleeps=None, sql=PG): + sleeps = sleeps if sleeps is not None else [] + return KeyManager(kms_client, db, sql, cfg or config(), + cache or DataKeyCache(10, 60, start_cleanup_thread=False), sleep=sleeps.append) + + +class TestDecryptDataKey: + def test_decrypts_with_key_id_and_caches(self, kms, db): + client, stubber = kms + stubber.add_response("decrypt", {"Plaintext": DATA_KEY, "KeyId": ARN}, + {"CiphertextBlob": BLOB, "KeyId": ARN}) + km = manager(client, db) + first = km.decrypt_data_key(EDK, ARN) + assert isinstance(first, bytearray) and first == DATA_KEY + # Second call is served from the cache: no further stubbed response. + first[:] = bytes(32) + assert km.decrypt_data_key(EDK, ARN) == DATA_KEY + + def test_unlisted_master_key_is_refused_before_kms(self, kms, db): + client, _ = kms # no stubbed responses: any KMS call would fail + km = manager(client, db) + with pytest.raises(UnauthorizedMasterKeyError) as err: + km.decrypt_data_key(EDK, OTHER_ARN) + assert "123456789012" not in str(err.value) + with pytest.raises(UnauthorizedMasterKeyError): + km.decrypt_data_key(EDK, None) + + def test_allow_list_is_checked_even_on_a_cache_hit(self, kms, db): + client, _ = kms + cache = DataKeyCache(10, 60, start_cleanup_thread=False) + cache.put(KeyManager.data_key_cache_key(EDK), DATA_KEY) + with pytest.raises(UnauthorizedMasterKeyError): + manager(client, db, cache=cache).decrypt_data_key(EDK, OTHER_ARN) + + @pytest.mark.parametrize("edk", [None, "", " "]) + def test_missing_encrypted_data_key(self, kms, db, edk): + with pytest.raises(InvalidKeyMetadataError): + manager(kms[0], db).decrypt_data_key(edk, ARN) + + @pytest.mark.parametrize("edk", ["not base64!!", "ZWRr\u200b==", "Y\u00e9=="], + ids=["bad-chars", "zero-width-space", "non-ascii"]) + def test_malformed_base64(self, kms, db, edk): + # A non-ASCII string makes b64decode raise a plain ValueError rather + # than binascii.Error; it must still be InvalidKeyMetadataError. + with pytest.raises(InvalidKeyMetadataError): + manager(kms[0], db).decrypt_data_key(edk, ARN) + + def test_base64_with_line_breaks_is_accepted(self, kms, db): + client, stubber = kms + stubber.add_response("decrypt", {"Plaintext": DATA_KEY}, {"CiphertextBlob": BLOB, "KeyId": ARN}) + wrapped = EDK[:8] + "\n" + EDK[8:] + assert manager(client, db).decrypt_data_key(wrapped, ARN) == DATA_KEY + + def test_no_master_key_arn_leaves_key_id_to_kms(self, kms, db): + # Only possible without an allow-list. KMS reads the key from the + # ciphertext; passing KeyId=None would fail boto3's validation. + client, stubber = kms + stubber.add_response("decrypt", {"Plaintext": DATA_KEY, "KeyId": ARN}, {"CiphertextBlob": BLOB}) + km = manager(client, db, config(allowed_master_key_arns=frozenset())) + assert km.decrypt_data_key(EDK, None) == bytearray(DATA_KEY) + + def test_non_retryable_kms_error_fails_immediately(self, kms, db): + client, stubber = kms + stubber.add_client_error("decrypt", "IncorrectKeyException", http_status_code=400) + sleeps: List[float] = [] + with pytest.raises(KeyManagementError) as err: + manager(client, db, sleeps=sleeps).decrypt_data_key(EDK, ARN) + assert sleeps == [] + assert err.value.operation == "DECRYPT_DATA_KEY" + assert isinstance(err.value, OperationalError) + assert not isinstance(err.value, UnauthorizedMasterKeyError) + + +class TestRetries: + def test_throttling_is_retried_with_backoff(self, kms, db): + client, stubber = kms + stubber.add_client_error("decrypt", "ThrottlingException", http_status_code=400) + stubber.add_client_error("decrypt", "KMSInternalException", http_status_code=500) + stubber.add_response("decrypt", {"Plaintext": DATA_KEY}, {"CiphertextBlob": BLOB, "KeyId": ARN}) + sleeps: List[float] = [] + assert manager(client, db, sleeps=sleeps).decrypt_data_key(EDK, ARN) == DATA_KEY + assert len(sleeps) == 2 + assert 0.1 <= sleeps[0] <= 0.125 + assert 0.15 <= sleeps[1] <= 0.25 + + def test_retries_stop_at_the_configured_maximum(self, kms, db): + client, stubber = kms + for _ in range(3): + stubber.add_client_error("decrypt", "ServiceUnavailable", http_status_code=503) + sleeps: List[float] = [] + cfg = config(key_management_max_retries=2) + with pytest.raises(KeyManagementError, match="3 attempt"): + manager(client, db, cfg, sleeps=sleeps).decrypt_data_key(EDK, ARN) + assert len(sleeps) == 2 + + def test_429_and_network_errors_are_retryable(self): + from botocore.exceptions import ClientError + throttled = ClientError({"Error": {"Code": "Other"}, "ResponseMetadata": {"HTTPStatusCode": 429}}, "Decrypt") + assert KeyManager._is_retryable(throttled) + assert KeyManager._is_retryable(EndpointConnectionError(endpoint_url="https://kms")) + bad = ClientError({"Error": {"Code": "NotFoundException"}, "ResponseMetadata": {"HTTPStatusCode": 400}}, "D") + assert not KeyManager._is_retryable(bad) + assert not KeyManager._is_retryable(ValueError("x")) + + @pytest.mark.parametrize("status", [500, 502, 503, 504]) + def test_any_5xx_is_retryable_even_with_an_unlisted_code(self, status): + # A load balancer or VPC endpoint in front of KMS can answer with a + # code outside RETRYABLE_ERROR_CODES. + from botocore.exceptions import ClientError + err = ClientError({"Error": {"Code": "SomethingNew"}, "ResponseMetadata": {"HTTPStatusCode": status}}, "D") + assert KeyManager._is_retryable(err) + + def test_backoff_is_capped_and_floored(self, kms, db): + km = manager(kms[0], db, config(key_management_retry_backoff_base_sec=1.0)) + assert all(1.0 <= km._backoff_sec(0) <= 1.25 for _ in range(50)) + assert km._backoff_sec(10) == KeyManager.MAX_BACKOFF_SEC + huge = manager(kms[0], db, config(key_management_retry_backoff_base_sec=60.0)) + assert huge._backoff_sec(0) == KeyManager.MAX_BACKOFF_SEC + + def test_kms_client_has_botocore_retries_disabled(self): + session = boto3.Session(aws_access_key_id="x", aws_secret_access_key="x") + client = KeyManager.create_kms_client(session, config(kms_endpoint="http://localhost:4566")) + assert client.meta.region_name == "us-east-1" + assert client.meta.endpoint_url == "http://localhost:4566" + assert client.meta.config.retries["total_max_attempts"] == 1 + # botocore's 60 s defaults would let one blackholed call take minutes. + assert client.meta.config.connect_timeout == KeyManager.CONNECT_TIMEOUT_SEC + assert client.meta.config.read_timeout == KeyManager.READ_TIMEOUT_SEC + assert client.meta.config.connect_timeout < 60 and client.meta.config.read_timeout < 60 + + +def _assert_names_no_identifier(text: str) -> None: + for identifier in (ARN, ARN.rpartition("/")[2], ROLE_SESSION_ARN, "123456789012", "kiro-app-role", + "kiro-app-session"): + assert identifier not in text + + +def _key_manager_messages(caplog, level: int) -> List[str]: + # By logger name: threads other tests leave behind also log into caplog. + return [r.getMessage() for r in caplog.records if r.name == km_module.__name__ and r.levelno == level] + + +class TestQuotedKmsErrorsAreMasked: + # AWS KMS's own texts: they name the master key, and an access denial + # names the caller's role session. + @pytest.mark.parametrize("code, text", [ + pytest.param("DisabledException", f"{ARN} is disabled.", id="disabled"), + pytest.param("KMSInvalidStateException", f"{ARN} is pending deletion.", id="pending-deletion"), + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on resource: {ARN} " + "with an explicit deny in a resource-based policy", id="explicit-deny"), + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on the resource " + "associated with this ciphertext because the resource does not exist in this Region, no " + "resource-based policies allow access, or a resource-based policy explicitly denies access", + id="wrong-region"), + ]) + def test_decrypt_failure_masks_the_arns_kms_quotes(self, kms, db, code, text): + client, stubber = kms + stubber.add_client_error("decrypt", code, service_message=text, http_status_code=400) + with pytest.raises(KeyManagementError) as err: + manager(client, db).decrypt_data_key(EDK, ARN) + message = str(err.value) + assert message.startswith("[KeyManager] KMS DECRYPT_DATA_KEY failed after 1 attempt(s): ") + assert f"An error occurred ({code}) when calling the Decrypt operation: " in message + assert (mask_arn(ARN) in message) == (ARN in text) + assert (MASKED_ROLE_SESSION_ARN in message) == (ROLE_SESSION_ARN in text) + _assert_names_no_identifier(message) + # The SDK's error keeps KMS's full text, with its code and response. + assert isinstance(err.value.__cause__, ClientError) + assert text in str(err.value.__cause__) + + def test_decrypt_failure_without_an_arn_quotes_kms_unchanged(self, kms, db): + client, stubber = kms + stubber.add_client_error("decrypt", "NotFoundException", service_message="Invalid arn us-east-1", + http_status_code=400) + with pytest.raises(KeyManagementError) as err: + manager(client, db).decrypt_data_key(EDK, ARN) + assert isinstance(err.value.__cause__, ClientError) + assert str(err.value) == ("[KeyManager] KMS DECRYPT_DATA_KEY failed after 1 attempt(s): " + f"{err.value.__cause__}") + assert str(err.value).endswith(": Invalid arn us-east-1") + + # KeyUnavailableException's text names the key as DisabledException's does. + # Throttling's text names none today; this one does, so the test doesn't + # depend on which retryable error quotes an ARN. + @pytest.mark.parametrize("code, text, status", [ + pytest.param("ThrottlingException", f"Rate exceeded for {ARN}.", 400, id="throttling"), + pytest.param("KeyUnavailableException", f"{ARN} is unavailable.", 500, id="key-unavailable"), + ]) + def test_retry_record_masks_the_arns_kms_quotes(self, kms, db, caplog, code, text, status): + client, stubber = kms + stubber.add_client_error("decrypt", code, service_message=text, http_status_code=status) + stubber.add_response("decrypt", {"Plaintext": DATA_KEY}, {"CiphertextBlob": BLOB, "KeyId": ARN}) + with caplog.at_level(logging.DEBUG, logger=km_module.__name__): + assert manager(client, db).decrypt_data_key(EDK, ARN) == DATA_KEY + retries = [m for m in _key_manager_messages(caplog, logging.DEBUG) if "retrying in" in m] + assert len(retries) == 1 + assert f"({code})" in retries[0] and mask_arn(ARN) in retries[0] + _assert_names_no_identifier(retries[0]) + + def test_validation_warning_masks_the_arns_kms_quotes(self, kms, db, caplog): + client, stubber = kms + text = (f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:DescribeKey on resource: {ARN} " + "because no identity-based policy allows the kms:DescribeKey action") + stubber.add_client_error("describe_key", "AccessDeniedException", service_message=text, http_status_code=400) + with caplog.at_level(logging.WARNING, logger=km_module.__name__): + assert manager(client, db).is_master_key_valid(ARN) is False + warnings = _key_manager_messages(caplog, logging.WARNING) + assert len(warnings) == 1 + assert "(AccessDeniedException)" in warnings[0] and MASKED_ROLE_SESSION_ARN in warnings[0] + assert mask_arn(ARN) in warnings[0] + _assert_names_no_identifier(warnings[0]) + + +class TestGenerateAndCreate: + @pytest.mark.parametrize("algorithm, spec", [ + (EncryptionAlgorithm.AES_256_GCM, "AES_256"), (EncryptionAlgorithm.AES_128_GCM, "AES_128")]) + def test_generate_data_key_sizes_the_key_for_the_algorithm(self, kms, db, algorithm, spec): + client, stubber = kms + key = DATA_KEY[:EncryptionAlgorithm.key_length(algorithm)] + stubber.add_response("generate_data_key", {"Plaintext": key, "CiphertextBlob": BLOB}, + {"KeyId": ARN, "KeySpec": spec}) + generated = manager(client, db).generate_data_key(ARN, algorithm) + assert generated.plaintext == key and isinstance(generated.plaintext, bytearray) + assert base64.b64decode(generated.encrypted_data_key) == BLOB + assert len(generated.hmac_key) == 32 + assert generated.key_spec == spec + assert "bytearray" not in repr(generated) and str(BLOB) not in repr(generated) + + def test_mis_sized_data_key_is_rejected_at_setup(self, kms, db): + client, stubber = kms + stubber.add_response("generate_data_key", {"Plaintext": DATA_KEY, "CiphertextBlob": BLOB}, + {"KeyId": ARN, "KeySpec": "AES_128"}) + with pytest.raises(KeyManagementError, match="32-byte"): + manager(client, db).generate_data_key(ARN, EncryptionAlgorithm.AES_128_GCM) + + def test_mis_sized_data_key_is_wiped(self, kms, db, monkeypatch): + wiped: List[bytearray] = [] + real = km_module.wipe + monkeypatch.setattr(km_module, "wipe", lambda buf: (wiped.append(buf), real(buf))) + client, stubber = kms + stubber.add_response("generate_data_key", {"Plaintext": DATA_KEY, "CiphertextBlob": BLOB}, + {"KeyId": ARN, "KeySpec": "AES_128"}) + with pytest.raises(KeyManagementError): + manager(client, db).generate_data_key(ARN, EncryptionAlgorithm.AES_128_GCM) + assert len(wiped) == 1 and wiped[0] == bytearray(len(DATA_KEY)) + + def test_generate_is_gated_on_the_allow_list(self, kms, db): + with pytest.raises(UnauthorizedMasterKeyError): + manager(kms[0], db).generate_data_key(OTHER_ARN) + + def test_create_master_key_is_not_retried_after_an_ambiguous_failure(self, kms, db): + # After a 5xx the key may already exist; retrying would create a second one. + client, stubber = kms + stubber.add_client_error("create_key", "KMSInternalException", http_status_code=500) + sleeps: List[float] = [] + with pytest.raises(KeyManagementError, match="1 attempt"): + manager(client, db, sleeps=sleeps).create_master_key("d") + assert sleeps == [] + + def test_create_master_key_is_not_retried_on_a_quota_error(self, kms, db): + # LimitExceededException on CreateKey is the key-count quota; retrying + # only delays the same failure. + client, stubber = kms + stubber.add_client_error("create_key", "LimitExceededException", http_status_code=400) + sleeps: List[float] = [] + with pytest.raises(KeyManagementError, match="1 attempt"): + manager(client, db, sleeps=sleeps).create_master_key("d") + assert sleeps == [] + + def test_create_master_key_retries_a_connection_that_was_never_made(self, kms, db): + client, stubber = kms + km = manager(client, db) + calls = [] + + def create_key(**kwargs): + calls.append(kwargs) + if len(calls) == 1: + raise EndpointConnectionError(endpoint_url="https://kms") + return {"KeyMetadata": {"KeyId": "k", "Arn": ARN}} + + client.create_key = create_key # type: ignore[method-assign] + assert km.create_master_key("d") == ARN + assert len(calls) == 2 + + def test_create_master_key_retries_a_connect_timeout(self, kms, db): + # ConnectTimeoutError does not derive from EndpointConnectionError, so + # it needs its own guard. + from botocore.exceptions import ConnectTimeoutError + client, _ = kms + km = manager(client, db) + calls = [] + + def create_key(**kwargs): + calls.append(kwargs) + if len(calls) == 1: + raise ConnectTimeoutError(endpoint_url="https://kms") + return {"KeyMetadata": {"KeyId": "k", "Arn": ARN}} + + client.create_key = create_key # type: ignore[method-assign] + assert km.create_master_key("d") == ARN + assert len(calls) == 2 + + def test_create_master_key_retries_a_429(self, kms, db): + # A 429 means KMS did not act, whatever error code comes with it. + client, stubber = kms + stubber.add_client_error("create_key", "TooManyRequestsException", http_status_code=429) + stubber.add_response("create_key", {"KeyMetadata": {"KeyId": "k", "Arn": ARN}}, + {"Description": "d", "KeyUsage": "ENCRYPT_DECRYPT", "KeySpec": "SYMMETRIC_DEFAULT"}) + assert manager(client, db).create_master_key("d") == ARN + + def test_create_master_key_retries_throttling(self, kms, db): + client, stubber = kms + stubber.add_client_error("create_key", "ThrottlingException", http_status_code=400) + stubber.add_response("create_key", {"KeyMetadata": {"KeyId": "k", "Arn": ARN}}, + {"Description": "d", "KeyUsage": "ENCRYPT_DECRYPT", "KeySpec": "SYMMETRIC_DEFAULT"}) + sleeps: List[float] = [] + assert manager(client, db, sleeps=sleeps).create_master_key("d") == ARN + assert len(sleeps) == 1 + + def test_create_master_key(self, kms, db): + client, stubber = kms + stubber.add_response("create_key", {"KeyMetadata": {"KeyId": "k", "Arn": ARN}}, + {"Description": "d", "KeyUsage": "ENCRYPT_DECRYPT", "KeySpec": "SYMMETRIC_DEFAULT", + "Policy": "{}"}) + assert manager(client, db).create_master_key("d", policy="{}") == ARN + + @pytest.mark.parametrize("metadata, expected", [ + ({"KeyId": "k", "Enabled": True, "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT"}, True), + ({"KeyId": "k", "Enabled": False, "KeyState": "Disabled", "KeyUsage": "ENCRYPT_DECRYPT"}, False), + ({"KeyId": "k", "Enabled": True, "KeyState": "Enabled", "KeyUsage": "SIGN_VERIFY"}, False), + ]) + def test_is_master_key_valid(self, kms, db, metadata, expected): + client, stubber = kms + stubber.add_response("describe_key", {"KeyMetadata": metadata}, {"KeyId": ARN}) + assert manager(client, db).is_master_key_valid(ARN) is expected + + def test_is_master_key_valid_is_false_on_error(self, kms, db): + client, stubber = kms + stubber.add_client_error("describe_key", "NotFoundException", http_status_code=400) + assert manager(client, db).is_master_key_valid(ARN) is False + + +class TestKeyStorage: + def _key(self, **kw) -> KeyMetadata: + values = dict(key_name="n", master_key_arn=ARN, encrypted_data_key=EDK, hmac_key=b"H" * 32) + values.update(kw) + return KeyMetadata(**values) # type: ignore[arg-type] + + def test_store_on_postgres_uses_returning(self, kms, db): + db.result = (["id"], [(42,)]) + stored = manager(kms[0], db).store_key_metadata(self._key()) + assert stored.id == 42 + assert stored.key_id and len(stored.key_id) == 36 # generated UUID + sql, params = db.executed[0] + assert sql.startswith("INSERT INTO encrypt.key_storage ") and sql.endswith(" RETURNING id") + assert params[4] == b"H" * 32 and params[5] == "AES_256" + + def test_store_on_mysql_uses_lastrowid_and_keeps_given_uuid(self, kms, db): + db.lastrowid = 9 + stored = manager(kms[0], db, sql=MYSQL).store_key_metadata(self._key(key_id="given")) + assert (stored.id, stored.key_id) == (9, "given") + assert "RETURNING" not in db.executed[0][0] + + def test_unusable_metadata_is_refused(self, kms, db): + with pytest.raises(InvalidKeyMetadataError): + manager(kms[0], db).store_key_metadata(self._key(encrypted_data_key=None)) + assert db.executed == [] + + def test_store_failure_does_not_leak_the_hmac_key(self, kms, db): + secret = b"SECRET-HMAC-" + b"x" * 20 + db.error = RuntimeError(f"syntax error near '{secret!r}'") + with pytest.raises(KeyManagementError) as err: + manager(kms[0], db).store_key_metadata(self._key(hmac_key=secret)) + assert "SECRET-HMAC" not in str(err.value) + assert err.value.__cause__ is None + assert err.value.__context__ is None + assert "RuntimeError" in str(err.value) + + def test_store_failure_reports_the_driver_error_codes(self, kms, db): + # SQLSTATE and errno carry no statement text, so they can be shown. + class DriverError(Exception): + sqlstate = "42P01" + errno = 1146 + + db.error = DriverError("relation key_storage does not exist: 'SECRET-HMAC'") + with pytest.raises(KeyManagementError) as err: + manager(kms[0], db).store_key_metadata(self._key()) + assert "DriverError" in str(err.value) and "sqlstate 42P01" in str(err.value) + assert "errno 1146" in str(err.value) and "SECRET" not in str(err.value) + + def test_store_on_postgres_reads_the_id_from_a_dict_row(self, kms, db): + class DictCursor(FakeCursor): + def fetchone(self): + return {"id": 42} + + db.cursor = lambda: DictCursor(db) # type: ignore[method-assign] + db.result = (["id"], []) + assert manager(kms[0], db).store_key_metadata(self._key()).id == 42 + + def test_key_metadata_by_id(self, kms, db): + db.result = (["ID", "KEY_ID", "NAME", "MASTER_KEY_ARN", "ENCRYPTED_DATA_KEY", "HMAC_KEY", "KEY_SPEC", + "CREATED_AT", "LAST_USED_AT"], + [(3, "u", "n", ARN, EDK, memoryview(b"hk"), "AES_256", None, None)]) + km = manager(kms[0], db).key_metadata_by_id(3) + assert km is not None and km.id == 3 and km.hmac_key == b"hk" and km.master_key_arn == ARN + assert "WHERE id OPERATOR(pg_catalog.=) %s" in db.executed[0][0] + assert db.executed[0][1] == (3,) + + def test_key_metadata_by_id_missing(self, kms, db): + db.result = (["id"], []) + assert manager(kms[0], db).key_metadata_by_id(3) is None + + def test_key_metadata_by_id_failure(self, kms, db): + # The plugin passes ids read from stored values, which may be four + # bytes of legacy plaintext, so the message leaves the id out. + db.error = RuntimeError("boom") + with pytest.raises(KeyManagementError, match="boom") as err: + manager(kms[0], db).key_metadata_by_id(1802201963) + assert "1802201963" not in str(err.value) + + def test_touch_key_swallows_errors(self, kms, db): + db.error = RuntimeError("boom") + manager(kms[0], db).touch_key("u") + assert "last_used_at = CURRENT_TIMESTAMP" in db.executed[0][0] + + +# ---- botocore log filters ---- + +B64_KEY = base64.b64encode(DATA_KEY).decode() +# Distinctive fake credentials: easy to search for, and no test signs with the +# ambient credential chain. +FAKE_KEY_ID = "KIROUNITFAKEKEYID0001" +FAKE_SECRET = "kiro-unit-fake-secret-key" +FAKE_TOKEN = "kiro-unit-fake-session-token" +UNREACHABLE = "http://127.0.0.1:9" # never contacted: the canned answer comes first +KMS_OPERATIONS = ["TrentService.GenerateDataKey", "TrentService.Decrypt"] + + +class _Body: + """The raw stream botocore reads a canned response from.""" + + def __init__(self, body: bytes): + self._body = body + + def stream(self, **kwargs): + yield self._body + + +def _session(): + return boto3.Session(aws_access_key_id=FAKE_KEY_ID, aws_secret_access_key=FAKE_SECRET, + aws_session_token=FAKE_TOKEN) + + +def _answer_kms(client) -> Tuple[List[str], List[str]]: + """Answer each KMS request just before it would be sent, so botocore's + real signer and parser run and nothing leaves the host. Returns the + operations answered and the signatures of their requests.""" + answered: List[str] = [] + signatures: List[str] = [] + + def answer(request, **kwargs): + target = request.headers.get("X-Amz-Target", b"") + target = target.decode() if isinstance(target, bytes) else target + answered.append(target) + auth = request.headers.get("Authorization", b"") + auth = auth.decode() if isinstance(auth, bytes) else auth + signatures.append(auth.rpartition("Signature=")[2]) + body = {"KeyId": ARN, "Plaintext": B64_KEY} + if target.endswith("GenerateDataKey"): + body["CiphertextBlob"] = EDK + return AWSResponse(request.url, 200, {"Content-Type": "application/x-amz-json-1.1"}, + _Body(json.dumps(body).encode())) + + client.meta.events.register("before-send.kms.*", answer) + return answered, signatures + + +def _call_kms(client) -> int: + """GenerateDataKey then Decrypt; returns the id of the thread that called.""" + # A fresh manager and cache, so Decrypt reaches KMS instead of the cache. + cache = DataKeyCache(10, 60, start_cleanup_thread=False) + try: + km = KeyManager(client, FakeDb(), PG, config(), cache) + km.generate_data_key(ARN) + km.decrypt_data_key(EDK, ARN) + finally: + cache.close() + return threading.get_ident() + + +def _run(client, on_thread: bool) -> None: + if not on_thread: + _call_kms(client) + return + with ThreadPoolExecutor(max_workers=1) as pool: + worker = pool.submit(_call_kms, client).result(timeout=30) + assert worker != threading.get_ident() + + +@contextmanager +def _debug_log(caplog): + """Root and botocore's loggers at DEBUG for the block: the setup that leaks.""" + with ExitStack() as stack: + for name in LOGGERS: + stack.enter_context(caplog.at_level(logging.DEBUG, logger=name)) + yield caplog.records + + +def _holding(records, text: str) -> List[logging.LogRecord]: + return [r for r in records if text in r.getMessage()] + + +def _records(records, logger: str, msg: str) -> List[logging.LogRecord]: + return [r for r in records if r.name == logger and r.msg == msg] + + +def _state(name: str): + lg = logging.getLogger(name) + return lg.level, list(lg.handlers), lg.propagate, list(lg.filters) + + +class TestBotocoreLogFilters: + @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) + def test_botocore_logs_kms_secrets_at_debug(self, caplog, on_thread): + # The canaries: if botocore changes one of these records, the filter + # rules need another look. + client = _session().client("kms", region_name="us-east-1") + answered, signatures = _answer_kms(client) + with _debug_log(caplog) as records: + _run(client, on_thread) + assert answered == KMS_OPERATIONS + bodies = _records(records, "botocore.parsers", "Response body:\n%r") + assert len(bodies) == 2 and len(_holding(records, B64_KEY)) == 2 + assert all(isinstance(r.args, tuple) and isinstance(r.args[0], bytes) and b'"Plaintext"' in r.args[0] + for r in bodies) + sent = _records(records, "botocore.endpoint", "Sending http request: %s") + canonical = _records(records, "botocore.auth", "CanonicalRequest:\n%s") + assert len(sent) == 2 and len(canonical) == 2 + assert all(FAKE_KEY_ID in r.getMessage() and FAKE_TOKEN in r.getMessage() for r in sent) + assert all(FAKE_TOKEN in r.getMessage() for r in canonical) + signed = _records(records, "botocore.auth", "Signature:\n%s") + assert [r.getMessage() for r in signed] == [f"Signature:\n{s}" for s in signatures] + assert len(signatures) == 2 and all(len(s) == 64 for s in signatures) + + @pytest.mark.parametrize("endpoint", [None, UNREACHABLE], ids=["kms", "endpoint"]) + @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) + def test_create_kms_client_keeps_data_keys_out_of_the_log(self, caplog, on_thread, endpoint): + client = KeyManager.create_kms_client(_session(), config(kms_endpoint=endpoint)) + answered, signatures = _answer_kms(client) + with _debug_log(caplog) as records: + _run(client, on_thread) + assert answered == KMS_OPERATIONS + assert _holding(records, B64_KEY) == [] + assert _holding(records, '"Plaintext"') == [] + assert len(_records(records, "botocore.parsers", "Response headers: %r")) == 2 + assert _records(records, "botocore.auth", "Signature:\n%s") == [] + assert len(signatures) == 2 and all(_holding(records, s) == [] for s in signatures) + + @pytest.mark.parametrize("endpoint", [None, UNREACHABLE], ids=["kms", "endpoint"]) + @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) + def test_create_kms_client_keeps_request_credentials_out_of_the_log(self, caplog, on_thread, endpoint): + client = KeyManager.create_kms_client(_session(), config(kms_endpoint=endpoint)) + answered, signatures = _answer_kms(client) + with _debug_log(caplog) as records: + _run(client, on_thread) + assert answered == KMS_OPERATIONS + for secret in (FAKE_KEY_ID, FAKE_SECRET, FAKE_TOKEN): + assert _holding(records, secret) == [] + assert _records(records, "botocore.auth", "Signature:\n%s") == [] + assert len(signatures) == 2 and all(_holding(records, s) == [] for s in signatures) + # The unsigned record names the KMS target but carries no credential, + # so it stays: the rule needs both parts. + making = _records(records, "botocore.endpoint", "Making request for %s with params: %s") + assert len(making) == 2 and all("TrentService." in r.getMessage() for r in making) + + def test_other_services_lose_only_the_signature_record(self, caplog): + session = _session() + sts = session.client("sts", region_name="us-east-1") + body = (b'' + b"arn:aws:iam::123456789012:user/u") + sts.meta.events.register( + "before-send.sts.GetCallerIdentity", + lambda request, **kwargs: AWSResponse(request.url, 200, {"Content-Type": "text/xml"}, _Body(body))) + sts.get_caller_identity() # warm up, so both captures see the same records + + def capture() -> List[logging.LogRecord]: + caplog.clear() + with _debug_log(caplog) as records: + sts.get_caller_identity() + # botocore's records only: a thread another test left running can log while the root logger is at DEBUG + return [r for r in records if r.name.split(".")[0] == "botocore"] + + without = capture() + KeyManager.create_kms_client(session, config()) + with_filters = capture() + # The signature also sits in the Authorization header of the request + # record, which other services keep. + expected = [(r.name, r.msg) for r in without] + assert expected.count(("botocore.auth", "Signature:\n%s")) == 1 + expected.remove(("botocore.auth", "Signature:\n%s")) + assert [(r.name, r.msg) for r in with_filters] == expected + sent = _records(with_filters, "botocore.endpoint", "Sending http request: %s") + canonical = _records(with_filters, "botocore.auth", "CanonicalRequest:\n%s") + assert len(sent) == 1 and FAKE_KEY_ID in sent[0].getMessage() and FAKE_TOKEN in sent[0].getMessage() + assert "Signature=" in sent[0].getMessage() + assert len(canonical) == 1 and FAKE_TOKEN in canonical[0].getMessage() + + def test_filters_are_installed_once_on_their_loggers_only(self): + # Pin a level and propagate flag first, so a change the install makes + # shows even if an earlier install in this process made it already. + loggers = [logging.getLogger(name) for name in LOGGERS] + saved = [(lg.level, lg.propagate) for lg in loggers] + try: + for lg in loggers: + lg.setLevel(logging.ERROR + 1) + lg.propagate = True + before = {name: _state(name) for name in LOGGERS} + KeyManager.create_kms_client(_session(), config()) + KeyManager.create_kms_client(_session(), config(kms_endpoint=UNREACHABLE)) + after = {name: _state(name) for name in LOGGERS} + finally: + for lg, (level, propagate) in zip(loggers, saved): + lg.setLevel(level) + lg.propagate = propagate + added = {} + for name in LOGGERS: + level, handlers, propagate, filters = after[name] + assert (level, handlers, propagate) == before[name][:3] + added[name] = [type(f) for f in filters if f not in before[name][3]] + assert added == {"": [], "botocore": [], "botocore.parsers": [km_module._NoKmsPlaintext], + "botocore.endpoint": [km_module._NoKmsRequestCredentials], + "botocore.auth": [km_module._NoKmsRequestCredentials]} + + def test_a_removed_filter_stays_removed(self): + # The filters are installed once per process, so a positive control + # that removes a filter and builds a new client sees the leak. + KeyManager.create_kms_client(_session(), config()) + for name in LOGGERS: + lg = logging.getLogger(name) + lg.filters = [f for f in lg.filters if not isinstance(f, OUR_FILTERS)] + KeyManager.create_kms_client(_session(), config()) + assert not any(isinstance(f, OUR_FILTERS) for name in LOGGERS for f in logging.getLogger(name).filters) + + def test_concurrent_first_installs_add_each_filter_once(self, mocker): + # Thread A's first addFilter call waits until thread B has had time to + # run its own first install. The lock holds B until A is done, so B + # finds the filters installed and adds none. + entered, release = threading.Event(), threading.Event() + real_add_filter = logging.Logger.addFilter + + def add_filter(lg: logging.Logger, flt: logging.Filter) -> None: + if lg.name == "botocore.parsers" and not entered.is_set(): + entered.set() + release.wait(5) + real_add_filter(lg, flt) + + mocker.patch.object(logging.Logger, "addFilter", add_filter) + a = threading.Thread(target=km_module._install_botocore_filters, daemon=True) + b = threading.Thread(target=km_module._install_botocore_filters, daemon=True) + a.start() + try: + assert entered.wait(5), "thread A never reached addFilter" + b.start() + b.join(0.2) + finally: + # Release A and join both threads on every path, so neither thread + # is still adding filters when no_filters restores the loggers. + release.set() + for thread in (a, b): + if thread.is_alive(): + thread.join(5) + installed = {name: [type(f) for f in logging.getLogger(name).filters if isinstance(f, OUR_FILTERS)] + for name in ("botocore.parsers", "botocore.endpoint", "botocore.auth")} + assert installed == {"botocore.parsers": [km_module._NoKmsPlaintext], + "botocore.endpoint": [km_module._NoKmsRequestCredentials], + "botocore.auth": [km_module._NoKmsRequestCredentials]} + + +def _record(name: str, msg: str, args) -> logging.LogRecord: + return logging.LogRecord(name, logging.DEBUG, __file__, 0, msg, args, None) + + +class TestBotocoreLogFilterRules: + @pytest.mark.parametrize("msg, args, kept", [ + ("Response body:\n%r", (b'{"KeyId": "k", "Plaintext": "x"}',), False), + ("Response body:\n%r", (bytearray(b'{"Plaintext": "x"}'),), False), + ("%s %r", ("Response body", b'{"Plaintext": "x"}'), False), + ("Response body:\n%r", ('{"Plaintext": "x"}',), True), + ("Response body:\n%r", (b'{"KeyId": "k"}',), True), + ("Response headers: %r", None, True), + ("%(body)s", ({"body": b'{"Plaintext": "x"}'},), True), + ]) + def test_plaintext_filter_drops_only_bytes_carrying_a_plaintext_field(self, msg, args, kept): + assert km_module._NoKmsPlaintext().filter(_record("botocore.parsers", msg, args)) is kept + + @pytest.mark.parametrize("msg, args, kept", [ + ("Sending http request: %s", ("{'X-Amz-Target': b'TrentService.Decrypt', 'Authorization': b'AWS4'}",), False), + ("CanonicalRequest:\n%s", ("x-amz-security-token:t\nx-amz-target:TrentService.Decrypt",), False), + ("CanonicalRequest:\n%s", ("X-AMZ-SECURITY-TOKEN:t\nx-amz-target:TrentService.Decrypt",), False), + ("Signature:\n%s", ("0f3a" * 16,), False), + ("Signature:\n%s", ("TrentService.Decrypt " + "0f3a" * 16,), False), + ("Making request for %s with params: %s", ("Decrypt", "{'X-Amz-Target': 'TrentService.Decrypt'}"), True), + ("Sending http request: %s", ("{'X-Amz-Target': b'Other.Op', 'Authorization': b'AWS4'}",), True), + ("Calculating signature using v4 auth.", None, True), + ("StringToSign:\n%s", ("AWS4-HMAC-SHA256\nSignature:\n" + "0f3a" * 16,), True), + ("Signature: %s", ("0f3a" * 16,), True), + ("TrentService. Authorization %s %s", ("only one argument",), True), + ]) + def test_request_filter_drops_only_signed_kms_records(self, msg, args, kept): + assert km_module._NoKmsRequestCredentials().filter(_record("botocore.endpoint", msg, args)) is kept diff --git a/tests/unit/test_metadata_manager.py b/tests/unit/test_metadata_manager.py new file mode 100644 index 000000000..70a53b99d --- /dev/null +++ b/tests/unit/test_metadata_manager.py @@ -0,0 +1,517 @@ +# 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. + +import gc +import threading +import weakref +from contextlib import contextmanager +from types import SimpleNamespace +from typing import Any, List, Optional, Tuple + +import pytest + +from aws_advanced_python_wrapper.encryption import metadata_manager as module +from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.errors import MetadataError + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" + +COLUMNS = ["table_name", "column_name", "encryption_algorithm", "key_id", "created_at", "updated_at", + "ks_id", "ks_key_id", "ks_name", "ks_master_key_arn", "ks_encrypted_data_key", "ks_hmac_key", + "ks_key_spec", "ks_created_at", "ks_last_used_at"] + + +def row(table, column, key_id=1, with_key=True, algorithm="AES-256-GCM"): + key = (key_id, "uuid", "n", ARN, "ZWRr", b"h" * 32, "AES_256", None, None) if with_key else (None,) * 9 + return (table, column, algorithm, key_id, None, None) + key + + +class FakeDb: + def __init__(self, rows=()): + self.rows: List[Tuple[Any, ...]] = list(rows) + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + self.error: Optional[Exception] = None + self.opened = 0 + + @contextmanager + def connection(self): + self.opened += 1 + yield self + + def cursor(self): + db = self + + class Cursor: + description = None + + def execute(self, sql, params=()): + db.executed.append((sql, tuple(params))) + if db.error is not None: + raise db.error + self.description = [(c.upper(),) for c in COLUMNS] # upper case, as some MySQL versions report + rows = db.rows + if "WHERE em.table_name" in sql: + rows = [r for r in rows if r[0] == params[0] and (len(params) < 2 or r[1] == params[1])] + self._rows = rows + + def fetchall(self): + return self._rows + + def close(self): + pass + + return Cursor() + + +class Clock: + now = 100.0 + + def __call__(self): + return self.now + + +@pytest.fixture +def clock(monkeypatch): + # Replace the module's view of `time` only, so no other thread in the + # process sees a frozen clock. + c = Clock() + monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=c)) + return c + + +@pytest.fixture +def managers(): + """Collects managers and closes them even when a test fails, so no + refresh thread outlives its test.""" + created: List[MetadataManager] = [] + yield created + for mm in created: + mm.close() + + +def config(**overrides): + values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), + metadata_cache_refresh_interval_sec=0.0, metadata_cache_expiration_sec=60.0) + values.update(overrides) + return EncryptionConfig(**values) # type: ignore[arg-type] + + +def test_joined_query_is_a_left_join_on_the_integer_id(): + db = FakeDb() + MetadataManager(db, PG, config()).load_metadata() + sql = db.executed[0][0] + assert "FROM encrypt.encryption_metadata em LEFT JOIN encrypt.key_storage ks" in sql + assert "ON em.key_id OPERATOR(pg_catalog.=) ks.id" in sql + assert "ks.key_id AS ks_key_id" in sql + + +def test_mysql_uses_plain_equals(): + db = FakeDb() + MetadataManager(db, MYSQL, config(metadata_schema="app_enc")).load_metadata() + assert "ON em.key_id = ks.id" in db.executed[0][0] + assert "app_enc.encryption_metadata" in db.executed[0][0] + + +def test_start_loads_snapshot_and_lookups_hit_the_cache(clock): + db = FakeDb([row("users", "ssn"), row("users", "dob", 2), row("orders", "card", 3)]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.cache_size == 3 and db.opened == 1 + assert mm.is_column_encrypted("users", "ssn") + assert not mm.is_column_encrypted("users", "name") + assert not mm.is_column_encrypted(None, "ssn") + config_ = mm.column_config("users", "dob") + assert config_ is not None and config_.key_id == 2 and config_.key_metadata.id == 2 + assert config_.key_metadata.hmac_key == b"h" * 32 and config_.is_usable + assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} + assert mm.table_configs("nope") == () + assert db.opened == 1 + + +def test_column_with_missing_key_row_still_reads_as_encrypted(clock): + db = FakeDb([row("users", "ssn", key_id=7, with_key=False)]) + mm = MetadataManager(db, PG, config()) + mm.start() + config_ = mm.column_config("users", "ssn") + assert config_ is not None + assert config_.key_id == 7 and config_.key_metadata is None + assert not config_.is_usable + assert mm.is_column_encrypted("users", "ssn") + + +def _expired_with_background_refresh(clock, managers, db): + # A background refresh is configured but hasn't run yet when the snapshot + # expires, so the next lookup is what reloads it. + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0, + metadata_cache_refresh_interval_sec=3600.0)) + managers.append(mm) + mm.start() + clock.now += 10.0 + return mm + + +def test_expired_snapshot_is_reloaded_with_the_background_refresh_on(clock, managers): + db = FakeDb([row("users", "ssn")]) + mm = _expired_with_background_refresh(clock, managers, db) + assert mm.is_column_encrypted("users", "ssn") + assert mm.column_config("users", "ssn") is not None + assert db.opened == 2 # start() plus one reload, not a query per lookup + assert "WHERE" not in db.executed[-1][0] + assert mm._fresh(mm._snapshot) is not None + + +def test_expired_snapshot_reload_sees_a_column_added_since(clock, managers): + # A column encrypted after the snapshot was taken must show up once the + # snapshot expires; serving the stale snapshot would let a write store + # plaintext. + db = FakeDb([row("users", "ssn")]) + mm = _expired_with_background_refresh(clock, managers, db) + db.rows = [row("users", "ssn"), row("users", "dob", 2)] + assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} + assert mm.cache_size == 2 # the reload cached the new column + assert mm.is_column_encrypted("users", "dob") + assert db.opened == 2 + + +def test_expired_snapshot_is_reloaded_when_there_is_no_background_refresh(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # refresh interval 0 + mm.start() + clock.now += 10.0 + db.rows = [row("users", "ssn"), row("users", "dob", 2)] + assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} + assert mm.is_column_encrypted("users", "dob") + assert db.opened == 2 # one reload, then served from the new snapshot + assert "WHERE" not in db.executed[-1][0] + + +def test_manager_that_was_never_started_always_queries(clock): + # The admin utility relies on this: it never starts its manager, so every + # lookup sees the caller's own transaction. + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + assert mm.is_column_encrypted("users", "ssn") + assert mm.is_column_encrypted("users", "ssn") + assert db.opened == 2 and not mm.is_cache_loaded + + +def test_disabled_cache_always_queries(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + mm.start() + assert db.opened == 0 and not mm.is_cache_loaded + assert mm.is_column_encrypted("users", "ssn") + assert [c.column_name for c in mm.table_configs("users")] == ["ssn"] + assert db.opened == 2 + + +def test_refresh_replaces_the_snapshot_atomically(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + mm.start() + db.rows = [row("users", "dob")] + assert mm.refresh() == 1 + assert not mm.is_column_encrypted("users", "ssn") + assert mm.is_column_encrypted("users", "dob") + + +def test_failed_refresh_keeps_the_previous_snapshot(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + mm.start() + db.error = RuntimeError("db down") + with pytest.raises(MetadataError, match="db down"): + mm.refresh() + assert mm.is_column_encrypted("users", "ssn") + + +def test_initial_load_failure_raises_metadata_error(): + db = FakeDb() + db.error = RuntimeError("no such schema") + with pytest.raises(MetadataError): + MetadataManager(db, PG, config()).start() + + +def test_lookup_failure_carries_table_and_column(clock): + db = FakeDb() + db.error = RuntimeError("x") + mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + with pytest.raises(MetadataError) as err: + mm.column_config("users", "ssn") + assert (err.value.table_name, err.value.column_name) == ("users", "ssn") + + +def test_background_refresh_thread_runs_and_stops(managers): + db = FakeDb([row("users", "ssn")]) + refreshed = threading.Event() + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + managers.append(mm) + original = mm.refresh + + def counting_refresh(): + n = original() + if db.opened >= 3: + refreshed.set() + return n + + mm.refresh = counting_refresh # type: ignore[method-assign] + mm.start() + thread = mm._refresh_thread + assert thread is not None and thread.daemon + assert refreshed.wait(5) + mm.close() + assert not thread.is_alive() + assert not mm.is_cache_loaded + mm.close() # idempotent + + +def test_background_refresh_survives_errors(managers): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + managers.append(mm) + mm.start() + db.error = RuntimeError("blip") + attempts = len(db.executed) + for _ in range(500): + if len(db.executed) > attempts + 2: + break + threading.Event().wait(0.01) + assert len(db.executed) > attempts + 2 # the loop kept trying + assert mm._refresh_thread is not None and mm._refresh_thread.is_alive() + + +class BlockingDb(FakeDb): + """A FakeDb that, while ``block`` is set, holds the next query's + connection open after the query ran, until released.""" + + def __init__(self, rows=()): + super().__init__(rows) + self.block = False + self.entered = threading.Event() + self.release = threading.Event() + + @contextmanager + def connection(self): + with super().connection() as conn: + yield conn + if self.block: + self.entered.set() + self.release.wait(5) + + +def test_refresh_finishing_after_close_does_not_repopulate_the_cache(managers): + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + managers.append(mm) + mm.start() + db.block = True + worker = threading.Thread(target=mm.refresh, daemon=True) + worker.start() + assert db.entered.wait(5) + mm.close() + db.release.set() + worker.join(5) + assert not worker.is_alive() + assert not mm.is_cache_loaded + # ...and a lookup after close reads the database instead of a cache. + db.block = False + opened = db.opened + assert mm.is_column_encrypted("users", "ssn") + assert db.opened == opened + 1 and not mm.is_cache_loaded + + +def test_start_after_close_does_nothing(): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + mm.close() + mm.start() + assert db.opened == 0 and mm._refresh_thread is None and not mm.is_cache_loaded + + +def test_concurrent_refreshes_cannot_publish_older_data(): + # The first refresh has read the old rows but not yet published them when + # the data changes and a second refresh starts. Refreshes are serialized, + # so the second one's newer data is published last. + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + db.block = True + first = threading.Thread(target=mm.refresh, daemon=True) + first.start() + assert db.entered.wait(5) + db.block = False + db.rows = [row("users", "dob")] + second = threading.Thread(target=mm.refresh, daemon=True) + second.start() + second.join(0.2) + assert second.is_alive() # waits for the first refresh + db.release.set() + first.join(5) + second.join(5) + assert not first.is_alive() and not second.is_alive() + assert mm.is_column_encrypted("users", "dob") + assert not mm.is_column_encrypted("users", "ssn") + + +def test_unclosed_manager_stops_its_thread_when_collected(): + # A long interval, so the thread stops because the finalizer wakes it, + # not because its next wait happened to time out. + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=60.0)) + mm.start() + thread = mm._refresh_thread + ref = weakref.ref(mm) + del mm + for _ in range(100): + gc.collect() + if ref() is None: + break + threading.Event().wait(0.01) + assert ref() is None + assert thread is not None + thread.join(2) + assert not thread.is_alive() + + +def test_finalizer_does_not_set_the_event_from_the_refresh_thread_itself(): + # On the refresh thread the collection can run inside Event.wait, which + # holds the event's lock, so stop.set() there would deadlock. + stop = threading.Event() + MetadataManager._finalize(stop, [threading.current_thread()]) + assert not stop.is_set() + MetadataManager._finalize(stop, [None]) + assert stop.is_set() + + +def test_close_from_the_refresh_thread_does_not_fail(managers): + # Only the refresh thread reports; start()'s initial refresh runs on the + # calling thread and must not satisfy the test. + errors: List[BaseException] = [] + done = threading.Event() + + class ClosingDb(FakeDb): + @contextmanager + def connection(self): + if threading.current_thread().name == "kms-encryption-metadata-refresh": + try: + mm.close() + except BaseException as e: + errors.append(e) + finally: + done.set() + with super().connection() as conn: + yield conn + + mm = MetadataManager(ClosingDb([row("users", "ssn")]), PG, config(metadata_cache_refresh_interval_sec=0.01)) + managers.append(mm) + mm.start() + assert done.wait(5) + assert errors == [] + assert mm._stop.is_set() + + +def test_finalizer_is_given_the_refresh_thread(managers): + # The _finalize test passes the holder by hand; this pins the wiring. + mm = MetadataManager(FakeDb([row("users", "ssn")]), PG, config(metadata_cache_refresh_interval_sec=60.0)) + managers.append(mm) + mm.start() + assert mm._refresh_thread is not None + assert mm._thread_holder == [mm._refresh_thread] + + +def test_failed_reload_from_table_configs_names_the_table(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) + mm.start() + clock.now += 10.0 + db.error = RuntimeError("db down") + with pytest.raises(MetadataError) as err: + mm.table_configs("users") + assert (err.value.table_name, err.value.column_name) == ("users", None) + + +def test_snapshot_age_counts_from_the_start_of_the_load(clock, managers): + # A slow load must not stretch how long its data is trusted. + class SlowDb(FakeDb): + @contextmanager + def connection(self): + with super().connection() as conn: + yield conn + clock.now += 5.0 # the load takes 5 s + + db = SlowDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0, + metadata_cache_refresh_interval_sec=3600.0)) + managers.append(mm) + mm.start() + clock.now += 5.0 # 10 s after the data was read, 5 s after the query returned + opened = db.opened + mm.column_config("users", "ssn") + assert db.opened == opened + 1 # expired: read from the database + + +def test_lookups_that_expire_together_share_one_reload(clock): + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh + mm.start() + clock.now += 10.0 + db.block = True + first = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) + first.start() + assert db.entered.wait(5) # the first lookup's reload is inside its read + db.block = False + others = [threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) for _ in range(4)] + for t in others: + t.start() + db.release.set() + for t in [first] + others: + t.join(5) + assert not any(t.is_alive() for t in [first] + others) + assert db.opened == 2 # start() plus a single reload + + +def test_lookups_queued_when_close_runs_do_not_reload(clock): + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh + mm.start() + clock.now += 10.0 + db.block = True + first = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) + first.start() + assert db.entered.wait(5) + db.block = False + queued = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) + queued.start() + queued.join(0.2) + assert queued.is_alive() # waiting for the first reload + mm.close() + db.release.set() + first.join(5) + queued.join(5) + assert not first.is_alive() and not queued.is_alive() + full_loads = [sql for sql, _ in db.executed if "WHERE" not in sql] + assert len(full_loads) == 2 # start() and the first lookup's reload; the queued one only queries its column + + +def test_failed_reload_names_the_lookup(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) + mm.start() + clock.now += 10.0 + db.error = RuntimeError("db down") + with pytest.raises(MetadataError) as err: + mm.column_config("users", "ssn") + assert (err.value.table_name, err.value.column_name) == ("users", "ssn") diff --git a/tests/unit/test_plugin_manager.py b/tests/unit/test_plugin_manager.py index 6408825a2..804cad3a0 100644 --- a/tests/unit/test_plugin_manager.py +++ b/tests/unit/test_plugin_manager.py @@ -14,6 +14,11 @@ from __future__ import annotations +import contextvars +import logging +import threading +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import TimeoutError as FuturesTimeoutError from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -21,7 +26,7 @@ from aws_advanced_python_wrapper.pep249 import Connection from enum import Enum -from typing import Any, Callable, Dict, List, Optional, Set +from typing import Any, Callable, Dict, List, Optional, Set, Tuple import psycopg import pytest @@ -37,10 +42,14 @@ from aws_advanced_python_wrapper.iam_plugin import IamAuthPlugin from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.plugin import Plugin -from aws_advanced_python_wrapper.plugin_service import PluginManager +from aws_advanced_python_wrapper.plugin_service import (PluginCallContext, + PluginManager, + PluginServiceImpl) +from aws_advanced_python_wrapper.utils.decorators import timeout from aws_advanced_python_wrapper.utils.notifications import ( ConnectionEvent, HostEvent, OldConnectionSuggestedAction) from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.wrapper import AwsWrapperCursor class DbApiMethodTest(Enum): @@ -714,6 +723,380 @@ def test_must_use_pipeline(mocker, container, mock_telemetry_factory): assert manager.must_use_pipeline(DbApiMethod.CURSOR_LASTROWID) +# A value the call-context tests look for where no argument may appear. +CALL_CONTEXT_MARKER = "call-context-marker-7f3a" + + +class CallContextPlugin(Plugin): + """Records the arguments it is entered with. It can replace the call's arguments, run the rest of the chain more + than once, or run something while it handles the call.""" + + def __init__( + self, + plugin_service: PluginServiceImpl, + name: str, + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]], + replace_with: Optional[Tuple[Tuple[Any, ...], Dict[str, Any]]] = None, + runs: int = 1, + during: Optional[Callable[[], None]] = None): + self._plugin_service = plugin_service + self._name = name + self._seen = seen + self._replace_with = replace_with + self._runs = runs + self._during = during + + @property + def subscribed_methods(self) -> Set[str]: + return {DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_EXECUTEMANY.method_name} + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + self._seen.append((self._name, args, kwargs)) + if self._during is not None: + self._during() + context = self._plugin_service.current_call_context + if self._replace_with is not None and context is not None: + context.args, context.kwargs = self._replace_with + result = None + for _ in range(self._runs): + result = execute_func() + return result + + +class CallContextObserverPlugin(Plugin): + """Records, for each call it handles, the arguments of the call context it reads.""" + + def __init__(self, plugin_service: PluginServiceImpl, methods: Set[str], observed: List[Tuple[str, Optional[Tuple[Any, ...]]]]): + self._plugin_service = plugin_service + self._methods = methods + self._observed = observed + + @property + def subscribed_methods(self) -> Set[str]: + return self._methods + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + context = self._plugin_service.current_call_context + self._observed.append((method_name, None if context is None else context.args)) + return execute_func() + + +def _call_context_service() -> PluginServiceImpl: + # current_call_context reads only the calling thread's context, so the service needs no set-up. + return PluginServiceImpl.__new__(PluginServiceImpl) + + +def _call_context_manager(mocker, container, mock_telemetry_factory, plugins: List[Plugin]) -> PluginManager: + container.plugin_service.driver_dialect.execute.side_effect = \ + lambda method_name, func, *args, **kwargs: func() + mocker.patch.object(PluginManager, "__init__", lambda w, x, y, z: None) + manager = PluginManager(mocker.MagicMock(), mocker.MagicMock(), mocker.MagicMock()) + manager._container = container + manager._plugins = plugins + [DefaultPlugin(container.plugin_service, mocker.MagicMock())] + manager._telemetry_factory = mock_telemetry_factory + manager._telemetry_in_use = False + manager._function_cache = [None] * (DbApiMethod.ALL.id + 1) + return manager + + +def test_call_context_replacement_reaches_later_plugins_and_the_driver(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + driver_calls = [] + caller_params = ["plain"] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + CallContextPlugin(service, "before", seen), + CallContextPlugin(service, "replacer", seen, replace_with=(("q", ("ENC",)), {"prepare": True})), + CallContextPlugin(service, "after", seen)]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: driver_calls.append((a, kw)), "q", caller_params) + + assert seen == [("before", ("q", ["plain"]), {}), + ("replacer", ("q", ["plain"]), {}), + ("after", ("q", ("ENC",)), {"prepare": True})] + assert seen[0][1][1] is caller_params + assert driver_calls == [(("q", ("ENC",)), {"prepare": True})] + assert caller_params == ["plain"] + + +@pytest.mark.parametrize("method_name", ["execute", "executemany"]) +@pytest.mark.parametrize("replacement", [((), {}), (("q", [("ENC",)]), {"prepare": True})]) +def test_cursor_driver_method_receives_the_replacement_as_written( + mocker, container, mock_telemetry_factory, mock_cursor, method_name, replacement): + # An empty replacement too: the driver then fails on it, instead of receiving the caller's arguments. + service = _call_context_service() + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=replacement)]) + cursor = AwsWrapperCursor(mocker.MagicMock(), container.plugin_service, manager, mock_cursor) + + getattr(cursor, method_name)("q", [("plain",)]) + + getattr(mock_cursor, method_name).assert_called_once_with(*replacement[0], **replacement[1]) + + +def test_without_a_replacement_the_driver_gets_the_callers_arguments(mocker, container, mock_telemetry_factory, mock_conn): + driver_calls = [] + params = ["v"] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, []) + + # Nothing subscribed and not network bound: the call bypasses the pipeline. + container.plugin_service.is_network_bound_method.return_value = False + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: driver_calls.append((a, kw)), "q", params, prepare=True) + assert container.plugin_service.driver_dialect.execute.call_count == 0 + + # Network bound: the call goes through DefaultPlugin. + container.plugin_service.is_network_bound_method.return_value = True + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: driver_calls.append((a, kw)), "q", params, prepare=True) + assert container.plugin_service.driver_dialect.execute.call_count == 1 + + assert driver_calls == [(("q", ["v"]), {"prepare": True})] * 2 + # The driver gets the caller's own objects, not copies of them. + assert all(call[0][1] is params for call in driver_calls) + + +def test_call_context_outer_rerun_starts_from_the_arguments_the_outer_plugin_saw( + mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + driver_calls = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + CallContextPlugin(service, "retrier", seen, runs=2), + CallContextPlugin(service, "replacer", seen, replace_with=(("q", ("ENC",)), {"prepare": True}))]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: driver_calls.append(a), "q", ("plain",)) + + assert [entry for entry in seen if entry[0] == "replacer"] == [("replacer", ("q", ("plain",)), {})] * 2 + assert driver_calls == [("q", ("ENC",))] * 2 + + +def test_call_context_outer_retry_after_an_error_starts_from_the_arguments_the_outer_plugin_saw( + mocker, container, mock_telemetry_factory, mock_conn): + # A plugin after the replacer fails once and a plugin before it runs the rest again: the replacement made in the + # failed run is undone, so the replacer starts again from the caller's arguments and replaces them once. + service = _call_context_service() + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + driver_calls = [] + failures = [ValueError("inner plugin failed")] + + def fail_once() -> None: + if failures: + raise failures.pop() + + class RetryPlugin(CallContextPlugin): + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + try: + return execute_func() + except ValueError: + return execute_func() + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + RetryPlugin(service, "retrier", seen), + CallContextPlugin(service, "replacer", seen, replace_with=(("q", ("ENC",)), {"prepare": True})), + CallContextPlugin(service, "failer", seen, during=fail_once)]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: driver_calls.append(a), "q", ("plain",)) + + assert [entry for entry in seen if entry[0] == "replacer"] == [("replacer", ("q", ("plain",)), {})] * 2 + assert driver_calls == [("q", ("ENC",))] + + +def test_current_call_context_is_none_outside_a_call_and_after_an_error(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=(("q", ("ENC",)), {}))]) + + def failing_driver(*args, **kwargs): + raise ValueError("driver failed") + + assert service.current_call_context is None + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("plain",)) + assert service.current_call_context is None + with pytest.raises(ValueError): + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, failing_driver, "q", ("plain",)) + assert service.current_call_context is None + + +def test_only_execute_and_executemany_get_a_call_context(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + observed: List[Tuple[str, Optional[Tuple[Any, ...]]]] = [] + methods = [DbApiMethod.CURSOR_EXECUTE, DbApiMethod.CURSOR_EXECUTEMANY, DbApiMethod.CURSOR_FETCHONE, DbApiMethod.CURSOR_FETCHMANY] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextObserverPlugin(service, {method.method_name for method in methods}, observed)]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("v",)) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTEMANY, lambda *a, **kw: None, "q", [("v",)]) + manager.execute(mock_conn, DbApiMethod.CURSOR_FETCHONE, lambda: None) + manager.execute(mock_conn, DbApiMethod.CURSOR_FETCHMANY, lambda: None, 5) + + assert observed == [(DbApiMethod.CURSOR_EXECUTE.method_name, ("q", ("v",))), + (DbApiMethod.CURSOR_EXECUTEMANY.method_name, ("q", [("v",)])), + (DbApiMethod.CURSOR_FETCHONE.method_name, None), + (DbApiMethod.CURSOR_FETCHMANY.method_name, None)] + + +def test_nested_execute_has_its_own_call_context_and_restores_the_enclosing_one( + mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + observed: List[Any] = [] + + def nested_execute(): + if observed: + return # only the enclosing call makes a nested one + enclosing = service.current_call_context + observed.append(("enclosing", None if enclosing is None else enclosing.args)) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: observed.append(("nested", a, service.current_call_context is not enclosing)), + "nested q", ("n",)) + observed.append(("restored", service.current_call_context is enclosing)) + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "nester", [], during=nested_execute)]) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("o",)) + + assert observed == [("enclosing", ("q", ("o",))), ("nested", ("nested q", ("n",)), True), ("restored", True)] + + +def test_other_method_inside_execute_sees_the_enclosing_call_context(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + observed: List[Tuple[str, Optional[Tuple[Any, ...]]]] = [] + + def nested_fetchone(): + manager.execute(mock_conn, DbApiMethod.CURSOR_FETCHONE, lambda: "row") + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + CallContextObserverPlugin(service, {DbApiMethod.CURSOR_FETCHONE.method_name}, observed), + CallContextPlugin(service, "nester", [], during=nested_fetchone)]) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("o",)) + + assert observed == [(DbApiMethod.CURSOR_FETCHONE.method_name, ("q", ("o",)))] + + +def test_call_contexts_of_concurrent_threads_are_separate(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + barrier = threading.Barrier(2) + mismatches: List[Any] = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [CallContextPlugin(service, "plugin", [])]) + + def driver(*args, **kwargs): + # Both threads are inside a call here at the same time. + barrier.wait(timeout=5) + context = service.current_call_context + if context is None or context.args != args: + mismatches.append(args) + + def run(sql: str): + for _ in range(20): + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, sql, ()) + + threads = [threading.Thread(target=run, args=(sql,)) for sql in ("q0", "q1")] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=30) + + assert not any(thread.is_alive() for thread in threads) + assert mismatches == [] + + +def test_late_socket_timeout_worker_sends_the_replacement(mocker, container, mock_telemetry_factory, mock_conn): + # With the dialect's pool busy, the driver call is still queued when the statement times out and every + # replacement has been undone. When a worker finally runs it, it must still send the replacement. + service = _call_context_service() + release = threading.Event() + sent = [] + + def driver(*args, **kwargs): + sent.append((args, kwargs)) + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=(("q", ("ENC",)), {}))]) + with ThreadPoolExecutor(max_workers=1) as pool: + pool.submit(release.wait, 10) # the only worker is held by an earlier operation that is stuck + container.plugin_service.driver_dialect.execute.side_effect = \ + lambda method_name, func, *args, **kwargs: timeout(pool, 0.05)(func)() + + with pytest.raises(FuturesTimeoutError): + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, "q", ("plain",)) + assert sent == [] + + release.set() + # timeout() doesn't cancel a call that is still queued, so the worker runs it now. If timeout() ever cancels it, + # nothing is sent. Either way the driver never gets the caller's arguments or the cleared ones. + + assert sent in ([], [(("q", ("ENC",)), {})]) + + +def test_socket_timeout_worker_sends_the_replacement(mocker, container, mock_telemetry_factory, mock_conn): + # With socket_timeout set, the dialect runs the driver call on a worker thread, which doesn't see this thread's + # call context. The worker must still send the replacement. + service = _call_context_service() + sent = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=(("q", ("ENC",)), {}))]) + with ThreadPoolExecutor(max_workers=1) as pool: + pool.submit(lambda: None).result(5) # start the worker before the call, so it can't inherit the call's context + container.plugin_service.driver_dialect.execute.side_effect = \ + lambda method_name, func, *args, **kwargs: timeout(pool, 5)(func)() + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: sent.append((a, kw)), "q", ("plain",)) + + assert sent == [(("q", ("ENC",)), {})] + + +@pytest.mark.parametrize("fails", [False, True], ids=["returns", "raises"]) +def test_context_copied_during_a_call_holds_no_argument_after_it(mocker, container, mock_telemetry_factory, mock_conn, caplog, fails): + caplog.set_level(logging.DEBUG) + service = _call_context_service() + copies: List[contextvars.Context] = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "copier", [], during=lambda: copies.append(contextvars.copy_context()))]) + + driver_error = ValueError("driver failed") + + def driver(*args: Any, **kwargs: Any) -> None: + if fails: + raise driver_error + + if fails: + with pytest.raises(ValueError) as excinfo: + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, "q", (CALL_CONTEXT_MARKER,), params=CALL_CONTEXT_MARKER) + # The driver's own error arrives unchanged, with nothing of the call's arguments added to it. + assert excinfo.value is driver_error + assert excinfo.value.__cause__ is None + assert excinfo.value.__context__ is None + else: + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, "q", (CALL_CONTEXT_MARKER,), params=CALL_CONTEXT_MARKER) + + copied = copies[0].run(lambda: service.current_call_context) + assert copied is not None + assert copied.args == () + assert copied.kwargs == {} + # The core neither logs nor traces the call's arguments. + assert [record for record in caplog.records if CALL_CONTEXT_MARKER in record.getMessage()] == [] + assert CALL_CONTEXT_MARKER not in str(mock_telemetry_factory.mock_calls) + + +def test_call_context_repr_and_str_show_no_argument(): + context = PluginCallContext(("q", (CALL_CONTEXT_MARKER,)), {"params": CALL_CONTEXT_MARKER}) + + assert CALL_CONTEXT_MARKER not in repr(context) + assert CALL_CONTEXT_MARKER not in str(context) + assert CALL_CONTEXT_MARKER not in format(context) + + +def test_call_context_rejects_an_unknown_attribute(): + context = PluginCallContext((), {}) + + with pytest.raises(AttributeError): + context.kwarg = {} # a misspelt kwargs fails instead of never reaching the driver + + context.args, context.kwargs = ("q",), {"params": ()} + assert context.args == ("q",) + assert context.kwargs == {"params": ()} + + class CMySQLCursor: """Stands in for a mysql-connector cursor, whose str() quotes the start of its last statement with the values.""" diff --git a/tests/unit/test_psycopg3_parity_passthroughs.py b/tests/unit/test_psycopg3_parity_passthroughs.py index 1ea2d55bb..7afe740b4 100644 --- a/tests/unit/test_psycopg3_parity_passthroughs.py +++ b/tests/unit/test_psycopg3_parity_passthroughs.py @@ -258,9 +258,10 @@ def test_sync_wrapper_execute_delegates_with_all_kwargs() -> None: target = MagicMock() wrapper = _sync_wrapper(target) # Route plugin_manager.execute straight to the provided callable so the - # underlying cursor work actually runs. + # underlying cursor work actually runs. Like the plugin manager, pass the + # call's arguments on: the cursor's driver function takes them. wrapper._plugin_manager.execute = MagicMock( # type: ignore[method-assign] - side_effect=lambda obj, method, func, *a, **k: func()) + side_effect=lambda obj, method, func, *a, **k: func(*a, **k)) result = wrapper.execute("SELECT 1", ("p",), prepare=True, binary=True) diff --git a/tests/unit/test_sql_alchemy_driver_dialect.py b/tests/unit/test_sql_alchemy_driver_dialect.py index 314876011..4be7a11f8 100644 --- a/tests/unit/test_sql_alchemy_driver_dialect.py +++ b/tests/unit/test_sql_alchemy_driver_dialect.py @@ -12,11 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. +import threading + import pytest import sqlalchemy from aws_advanced_python_wrapper.driver_dialect import DriverDialect from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect from aws_advanced_python_wrapper.sqlalchemy_driver_dialect import \ SqlAlchemyDriverDialect from aws_advanced_python_wrapper.utils.properties import Properties @@ -117,3 +121,26 @@ def test_transfer_session_states_with_null_connection(underlying_dialect, sqlalc sqlalchemy_dialect = SqlAlchemyDriverDialect(underlying_dialect, Properties()) with pytest.raises(AwsWrapperError): sqlalchemy_dialect.set_read_only(sqlalchemy_mock_conn, False) + + +def test_loop_start_runs_on_the_calling_thread_with_socket_timeout(sqlalchemy_mock_conn): + props = Properties({"socket_timeout": "5"}) + sqlalchemy_dialect = SqlAlchemyDriverDialect(PgDriverDialect(props), props) + threads = [] + + sqlalchemy_dialect.execute( + DbApiMethod.CURSOR_ITER.method_name, lambda: threads.append(threading.current_thread()), conn=sqlalchemy_mock_conn) + + assert threads == [threading.current_thread()] + + +@pytest.mark.parametrize("method", [DbApiMethod.CURSOR_FETCHONE, DbApiMethod.CURSOR_NEXT], ids=["fetchone", "next"]) +def test_fetch_still_runs_on_the_timeout_worker_with_socket_timeout(method, sqlalchemy_mock_conn): + props = Properties({"socket_timeout": "5"}) + sqlalchemy_dialect = SqlAlchemyDriverDialect(PgDriverDialect(props), props) + threads = [] + + sqlalchemy_dialect.execute( + method.method_name, lambda: threads.append(threading.current_thread()), conn=sqlalchemy_mock_conn) + + assert len(threads) == 1 and threads[0] is not threading.current_thread() diff --git a/tests/unit/test_type_marker.py b/tests/unit/test_type_marker.py new file mode 100644 index 000000000..a925f42f3 --- /dev/null +++ b/tests/unit/test_type_marker.py @@ -0,0 +1,72 @@ +# 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 datetime import date, datetime, time, timezone +from decimal import Decimal + +import pytest + +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker + + +class TestFromObject: + @pytest.mark.parametrize("value,expected", [ + ("s", TypeMarker.STRING), + (b"x", TypeMarker.BYTE_ARRAY), + (bytearray(b"x"), TypeMarker.BYTE_ARRAY), + (memoryview(b"x"), TypeMarker.BYTE_ARRAY), + (True, TypeMarker.BOOLEAN), # must win over int + (False, TypeMarker.BOOLEAN), + (5, TypeMarker.LONG), # every Python int but bool -> LONG + (5.0, TypeMarker.DOUBLE), + (Decimal("1.5"), TypeMarker.BIG_DECIMAL), + (datetime(2020, 1, 1), TypeMarker.LOCAL_DATE_TIME), # must win over date + (datetime(2020, 1, 1, tzinfo=timezone.utc), TypeMarker.TIMESTAMP), # aware: an instant + (date(2020, 1, 1), TypeMarker.LOCAL_DATE), + (time(1, 2, 3), TypeMarker.LOCAL_TIME), + (object(), TypeMarker.GENERIC), + ]) + def test_from_object(self, value, expected): + assert TypeMarker.from_object(value) == expected + + +class TestFromValue: + def test_known(self): + assert TypeMarker.from_value(TypeMarker.STRING) == TypeMarker.STRING + + def test_unknown_raises(self): + with pytest.raises(ValueError): + TypeMarker.from_value(200) + + +class TestNames: + def test_name_for_known(self): + assert TypeMarker.name_for(TypeMarker.LONG) == "LONG" + + def test_name_for_unknown(self): + assert TypeMarker.name_for(200) is None + + def test_is_known(self): + assert TypeMarker.is_known(TypeMarker.GENERIC) + assert not TypeMarker.is_known(200) + + +def test_marker_numbers_never_change(): + # The marker numbers are stored in every payload, so they can't change + # without breaking values already written. + assert (TypeMarker.STRING, TypeMarker.INTEGER, TypeMarker.LONG, TypeMarker.DOUBLE, + TypeMarker.FLOAT, TypeMarker.BOOLEAN, TypeMarker.BIG_DECIMAL, TypeMarker.DATE, + TypeMarker.TIME, TypeMarker.TIMESTAMP, TypeMarker.LOCAL_DATE, TypeMarker.LOCAL_TIME, + TypeMarker.LOCAL_DATE_TIME, TypeMarker.BYTE_ARRAY, TypeMarker.GENERIC) == \ + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 99) From aaed53d0309986fd61239bfb8c14632dc1d386c0 Mon Sep 17 00:00:00 2001 From: JuanLeee Date: Tue, 17 Nov 2026 17:21:55 -0700 Subject: [PATCH 2/6] feat: sql analysis (#1317) --- .../encryption/metadata_manager.py | 36 +- .../encryption/sql_analyzer.py | 1448 +++++++++++++ .../encryption/sql_dialect.py | 46 + .../encryption/sql_tokenizer.py | 581 ++++++ ...dvanced_python_wrapper_messages.properties | 1 + poetry.lock | 22 +- pyproject.toml | 9 +- tests/unit/test_encryption_import_guard.py | 52 +- tests/unit/test_metadata_manager.py | 60 + tests/unit/test_sql_analyzer.py | 1815 +++++++++++++++++ tests/unit/test_sql_tokenizer.py | 415 ++++ 11 files changed, 4467 insertions(+), 18 deletions(-) create mode 100644 aws_advanced_python_wrapper/encryption/sql_analyzer.py create mode 100644 aws_advanced_python_wrapper/encryption/sql_tokenizer.py create mode 100644 tests/unit/test_sql_analyzer.py create mode 100644 tests/unit/test_sql_tokenizer.py diff --git a/aws_advanced_python_wrapper/encryption/metadata_manager.py b/aws_advanced_python_wrapper/encryption/metadata_manager.py index 1b2934988..693b08520 100644 --- a/aws_advanced_python_wrapper/encryption/metadata_manager.py +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -42,6 +42,7 @@ class _Snapshot(NamedTuple): + # Keyed by SqlDialect.metadata_key of the names. columns: Mapping[Tuple[str, str], ColumnEncryptionConfig] by_table: Mapping[str, Tuple[ColumnEncryptionConfig, ...]] loaded_at: float # time.monotonic() @@ -60,6 +61,12 @@ class MetadataManager: 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:`SqlDialect.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. @@ -162,7 +169,7 @@ def column_config(self, table_name: Optional[str], column_name: Optional[str]) - return None snapshot = self._usable_snapshot(table_name, column_name) if snapshot is not None: - return snapshot.columns.get((table_name, column_name)) + return snapshot.columns.get((self._sql.metadata_key(table_name), self._sql.metadata_key(column_name))) rows = self._query( f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s AND em.column_name {self._sql.equals} %s", (table_name, column_name), table_name=table_name, column_name=column_name) @@ -174,7 +181,7 @@ def table_configs(self, table_name: Optional[str]) -> Sequence[ColumnEncryptionC return () snapshot = self._usable_snapshot(table_name) if snapshot is not None: - return snapshot.by_table.get(table_name, ()) + return snapshot.by_table.get(self._sql.metadata_key(table_name), ()) rows = self._query(f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s", (table_name,), table_name=table_name) return tuple(self._to_column_config(row) for row in rows) @@ -213,11 +220,12 @@ def _load_snapshot(self, *, table_name: Optional[str] = None, column_name: Optio # returned. loaded_at = time.monotonic() columns = self._load_all(table_name=table_name, column_name=column_name) + key = self._sql.metadata_key by_table: Dict[str, List[ColumnEncryptionConfig]] = {} for config in columns.values(): - by_table.setdefault(config.table_name, []).append(config) + by_table.setdefault(key(config.table_name), []).append(config) snapshot = _Snapshot( - MappingProxyType(dict(columns)), + 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: @@ -269,8 +277,8 @@ def _joined_sql(self) -> str: 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=row["table_name"], - column_name=row["column_name"], + 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, @@ -278,6 +286,22 @@ def _to_column_config(row: Mapping[str, Any]) -> ColumnEncryptionConfig: 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 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..e4efb1608 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_analyzer.py @@ -0,0 +1,1448 @@ +# 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, Iterator, List, + Optional, Sequence, Set, Tuple) + +try: + import sqlglot + from sqlglot import exp +except ModuleNotFoundError as e: # pragma: no cover - exercised by the import-guard test + # 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( + "The KMS encryption plugin needs the 'sqlglot' package. " + "Install it with: pip install 'aws-advanced-python-wrapper[encryption]'") 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.sql_dialect import SqlDialect + + +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). + 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 + #: 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) + + @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 analyze(sql: str, dialect: SqlDialect, 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: SqlDialect, 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 + + +# Leading words of the statements handed to the parser. Anything else is +# reported without parsing it: sqlglot falls back to an opaque "command" for +# what it doesn't support, and logs it. +_PARSED = { + "postgresql": frozenset({"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "COPY", "VALUES", "PREPARE"}), + "mysql": frozenset({"SELECT", "WITH", "INSERT", "REPLACE", "UPDATE", "DELETE", "VALUES"}), +} +_SQLGLOT_DIALECT = {"postgresql": "postgres", "mysql": "mysql"} +_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: SqlDialect, 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 parser reads a hidden placeholder as literal or comment text, so + # the tables are still known, and a caller can refuse the statement + # when one of them has encrypted columns. + tables = _named_tables(tokens, dialect) if early is AnalysisGap.HIDDEN_PLACEHOLDER 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) + if any(w not in _PARSED[dialect.name] 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) + + mismatch = _placeholder_mismatch(trees, tokens) + if mismatch is not None or not trees or any(isinstance(t, exp.Command) for t in trees): + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), + gap=AnalysisGap.PLACEHOLDER_MISMATCH if mismatch else AnalysisGap.UNPARSEABLE, detail=mismatch) + + 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: SqlDialect) -> Tuple[Optional[List[exp.Expression]], Optional[str]]: + try: + with _QUIET.active(): + parsed = sqlglot.parse(text, read=_SQLGLOT_DIALECT[dialect.name]) + 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: SqlDialect) -> 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 a MySQL INSERT or REPLACE + that doesn't parse is tried again without its column qualifiers. ``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 tokens.leading_words in (("INSERT",), ("REPLACE",)) and dialect.name == "mysql": + 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: SqlDialect) -> 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 _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 in tokens.leading_words: + if leading in _WRITE_LEADING or (leading == "COPY" and "FROM" in words): + return True + if leading in ("WITH", "EXPLAIN", "PREPARE") and words & _WRITE_WORDS: + return True + if leading == "EXPLAIN" and "EXECUTE" in words: + return True # EXPLAIN ANALYZE EXECUTE runs the prepared statement + # 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: + continue # a "?" or ":name" the driver does not bind + 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 + + +# ---- the walk ---- + +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: SqlDialect, 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]] = {} + + # ---- entry ---- + + 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) + 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, + gap=self._gap if self._writes else None) + + # ---- statements ---- + + 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): + return False # a join, a filter, a limit, ... (or an arg this code does not know) + 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): + return False # one value would fill two columns + assert isinstance(values, exp.Values) + 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.name != "mysql": + same_row[self._key("excluded")] = 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 ()): + 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)) + + # ---- writes ---- + + 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)) + 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): + pass # bound by a later EXECUTE; the statement's gap says so + 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.name == "mysql" 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" + + # ---- comparisons ---- + + 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) + self._compare(node, node.args.get("query"), node.this) # %s IN (SELECT ssn FROM users) + 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 + ref = self._column_ref(column, column) # a sub-select's column is resolved in the sub-select + 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)): + return None # it may return rows for no input row, such as a count of 0 + 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: + return [] # a set operation or a parenthesized query that is the statement + 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 + + # ---- values ---- + + @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 + + # ---- names and scopes ---- + + 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): + return None # a function or a subquery + name = self._fold(table.this) + assert name is not None + 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): + return # an absent arg can be None or False + 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")) + add(query.args.get("using")) # a list for DELETE ... 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 + + # ---- results ---- + + 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: + inner = item.this if isinstance(item, exp.Alias) else item + if isinstance(inner, exp.Star) or (isinstance(inner, exp.Column) and isinstance(inner.this, exp.Star)): + return None + ref = self._column_ref(inner, inner) if isinstance(inner, exp.Column) else None + if (ref is None or ref.table is None) and isinstance(tree, exp.Select): + # Read through a derived table or CTE: follow it to its table. + ref = self._trace(inner, tree, 0) + result.append(ref if ref is not None and ref.table is not None else None) + return tuple(result) + + 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; ``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")) + inner = self._derived_query(None if qualifier is None else self._dialect.metadata_key(qualifier), query) + if not isinstance(inner, exp.Select): + return None + key = self._dialect.metadata_key(name) + for item in inner.expressions: + # The alias is folded from its Identifier, so quoting counts. + out = self._fold(item.args.get("alias")) if isinstance(item, exp.Alias) else self._identifier(item) + 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[exp.Expression]: + """The query behind the derived table or CTE that ``query`` reads as + ``qualifier``, or behind its only source when there is no qualifier. + A source whose alias lists column names is not followed: the list + renames the columns by position. 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 = isinstance(alias, exp.TableAlias) and bool(alias.args.get("columns")) + 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 else node.this + 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: + 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: + return None # PostgreSQL lets a RECURSIVE list read later CTEs + break # a CTE sees only the CTEs before it + cte_alias = cte.args.get("alias") + if isinstance(cte_alias, exp.TableAlias) and self._key(cte_alias.this) == key: + return None if cte_alias.args.get("columns") else cte.this + inside = outer.parent + outer = self._nearest_query(outer) + return None + return None + + def _note(self, gap: AnalysisGap) -> None: + if self._gap is None: + self._gap = gap diff --git a/aws_advanced_python_wrapper/encryption/sql_dialect.py b/aws_advanced_python_wrapper/encryption/sql_dialect.py index 6b28721d8..9a8e8690f 100644 --- a/aws_advanced_python_wrapper/encryption/sql_dialect.py +++ b/aws_advanced_python_wrapper/encryption/sql_dialect.py @@ -23,6 +23,7 @@ from __future__ import annotations +import string from abc import ABC, abstractmethod from contextlib import closing from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Sequence @@ -59,6 +60,22 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int ``id``.""" ... + @abstractmethod + def fold_identifier(self, name: str, quoted: bool) -> str: + """The name the server resolves an identifier written in SQL to. + ``name`` is the identifier without its quotes (doubled quotes undone) + and ``quoted`` says whether it was quoted.""" + ... + + @abstractmethod + def metadata_key(self, name: str) -> str: + """The form a table or column name is compared in when looking it up + in ``encryption_metadata``. Names with the same key share encryption + metadata: usually because the engine treats them as the same object, + but on MySQL with ``lower_case_table_names=0`` table names that differ + only in case share a key too.""" + ... + @staticmethod def for_driver_dialect(driver_dialect: DriverDialect) -> SqlDialect: code = driver_dialect.dialect_code @@ -111,6 +128,17 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int # A connection opened with a dict-like row factory returns a mapping. return int(next(iter(row.values())) if isinstance(row, Mapping) else row[0]) + def fold_identifier(self, 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 metadata_key(self, name: str) -> str: + # Catalog names are case-sensitive: "Users" and users are two tables. + return name + class MySqlSqlDialect(SqlDialect): name = "mysql" @@ -128,6 +156,24 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int cursor.execute(sql, params) return int(cursor.lastrowid) + def fold_identifier(self, name: str, quoted: bool) -> str: + # MySQL keeps identifiers as written (quoting only allows reserved words + # and special characters). Whether it folds table names depends on + # lower_case_table_names, which metadata_key allows for by comparing + # case-insensitively. + return name + + def metadata_key(self, 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() + + +_ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase) PG = PgSqlDialect() MYSQL = MySqlSqlDialect() 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..8f505129d --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py @@ -0,0 +1,581 @@ +# 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, Union + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + +#: 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: SqlDialect) -> ParamStyle: + """The style the driver for ``dialect`` applies to ``params``, the + second argument of ``execute``.""" + if dialect.name == "mysql": + # Connector/Python substitutes only for a non-empty dict, list or + # tuple. + if not params: + return cls.NONE + if isinstance(params, dict): + return cls.NAMED + return cls.POSITIONAL if isinstance(params, (list, tuple)) else cls.NONE + if params is None: + 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:`SqlDialect.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, ...] + #: 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, ...] = () + + @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"}) + +# MySQL statement modifiers between the keyword and the table. They change how +# a statement runs and leave what it writes alone. The structural parser reads +# "UPDATE LOW_PRIORITY users" as a table named LOW_PRIORITY aliased users, so +# they are dropped from the normalized copy. All are reserved words except +# QUICK, which can only follow DELETE. +_MYSQL_MODIFIERS = { + "INSERT": frozenset({"LOW_PRIORITY", "HIGH_PRIORITY", "DELAYED", "IGNORE"}), + "REPLACE": frozenset({"LOW_PRIORITY", "DELAYED"}), + "UPDATE": frozenset({"LOW_PRIORITY", "IGNORE"}), + "DELETE": frozenset({"LOW_PRIORITY", "QUICK", "IGNORE"}), +} + +# ---- lexers ---- +# +# Alternatives are tried in order at each token boundary. The ``*_end`` groups +# capture a closing quote, empty when the literal runs to the end of the text. + +_PG_TOKEN = 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) + +_MYSQL_TOKEN = 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) + +_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 engine'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) +_PG_REF_PART = re.compile(r'(?P\w+)|"(?P(?:[^"]|"")+)"') +_MYSQL_REF_PART = re.compile(r"(?P\w+)|`(?P(?:[^`]|``)+)`") + +# A MySQL charset introducer (_binary, _utf8mb4, ...) and the space after it, +# directly before a placeholder. +_INTRODUCER = re.compile(r"(?[A-Za-z0-9]+)\s*\Z") +_MYSQL_CHARSETS = 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", +}) +_WORD = re.compile(r"[^\W\d][\w$]*") +_COMMENT_DELIMITER = re.compile(r"/\*|\*/") + +# The drivers' own placeholder patterns. +_PSYCOPG_PLACEHOLDER = re.compile(r"%(?:\(([^)]+)\).|.)") # no DOTALL, as in psycopg +_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: + hidden_spans: List[Tuple[int, int]] # literals, quoted identifiers, comments; sorted + 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]] + separators: List[int] # offsets of the ";" between statements + unterminated: bool = False + executable_comment: bool = False + # Words inside MySQL executable comments, which the server runs. + executable_words: List[str] = field(default_factory=list) + + +def tokenize(sql: str, dialect: SqlDialect, 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(f"sql must be a str, not {type(sql).__name__}") + mysql = dialect.name == "mysql" + lexed = _lex(sql, _MYSQL_TOKEN if mysql else _PG_TOKEN, mysql=mysql) + + edits: List[_Edit] = [] + if mysql: + placeholders, driver_error = _mysql_placeholders(sql, style, lexed, edits) + placeholders = _attach_introducers(sql, lexed, placeholders, edits) + else: + placeholders, driver_error = _psycopg_placeholders(sql, style, lexed, 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) + if mysql: + edits.extend(_mysql_rewrites(words, bounds)) + + keywords = {w for w, _, _ in words if w in _KEYWORDS} + keywords.update(w for w in lexed.executable_words if w in _KEYWORDS) + return TokenizedSql( + style=style, + placeholders=tuple(placeholders), + normalized=_apply(sql, edits), + leading_words=_leading_words(words, bounds), + keywords=frozenset(keywords), + unterminated=lexed.unterminated, + executable_comment=lexed.executable_comment, + driver_error=driver_error, + stray_annotations=tuple(stray), + ) + + +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 + + +# ---- driver placeholders ---- +# +# 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, 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 _MYSQL_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 + + +# ---- annotations ---- + +def _attach_annotations(sql: str, dialect: SqlDialect, 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: SqlDialect) -> Optional[ColumnRef]: + mysql = dialect.name == "mysql" + part_re, quote = (_MYSQL_REF_PART, "`") if mysql else (_PG_REF_PART, '"') + parts: List[str] = [] + pos = 0 + while pos <= len(text): + if text.startswith(".", pos) or pos == len(text): + parts.append("") # an empty part, as in ".c" or "t..c" + 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. + table = next((part for part in reversed(parts[:-1]) if part), None) + return ColumnRef(column=parts[-1], table=table) + + +# ---- lexing ---- + +def _lex(sql: str, token_re: re.Pattern, mysql: bool) -> _Lexed: + lexed = _Lexed([], [], [], []) + pos, n = 0, len(sql) + while pos < n: + m = token_re.match(sql, pos) + assert m is not None # "other" matches any character + kind, end = m.lastgroup, m.end() + if kind == "block_comment": + if not mysql: + 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 mysql and (sql.startswith("/*!", pos) or sql.startswith("/*M!", pos)): + lexed.executable_comment = True + lexed.executable_words.extend(w.upper() for w in _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 + 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(next((w for w, _, _ in words[begin:end] if w), "") for begin, end in bounds) + + +def _mysql_rewrites(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> List[_Edit]: + leading = {begin for begin, _ in bounds} + edits: List[_Edit] = [] + for i, (word, start, end) in enumerate(words): + modifiers = _MYSQL_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/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index a30656b4c..a56e4a847 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 @@ -575,6 +575,7 @@ 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. +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). diff --git a/poetry.lock b/poetry.lock index ab2f45c8c..026a64875 100644 --- a/poetry.lock +++ b/poetry.lock @@ -3328,6 +3328,24 @@ postgresql-psycopgbinary = ["psycopg[binary] (>=3.0.7)"] pymysql = ["pymysql"] sqlcipher = ["sqlcipher3_binary"] +[[package]] +name = "sqlglot" +version = "30.25.0" +description = "An easily customizable SQL parser and transpiler" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "sqlglot-30.25.0-py3-none-any.whl", hash = "sha256:7d5a292d5f61b7fc860e65a8fa41083c726db0e27fb6efb224cca63c3a5980f7"}, + {file = "sqlglot-30.25.0.tar.gz", hash = "sha256:d2d6e4d4865a210b1e33a801b105a6782ef12280cc2b6d0969bdc2634aef427a"}, +] +markers = {main = "extra == \"encryption\""} + +[package.extras] +c = ["sqlglotc (==30.25.0) ; python_version >= \"3.10\""] +dev = ["duckdb (>=0.6)", "mypy (>=2.4.0) ; python_version >= \"3.10\"", "mypy ; python_version < \"3.10\"", "pandas", "pandas-stubs", "pdoc", "pre-commit", "pyperf", "python-dateutil", "pytz", "ruff (==0.15.6)", "setuptools_scm", "types-python-dateutil", "types-pytz", "typing_extensions"] +rs = ["sqlglotc (==30.25.0) ; python_version >= \"3.10\"", "sqlglotrs (==0.13.0)"] + [[package]] name = "sqlparse" version = "0.6.0" @@ -4183,9 +4201,9 @@ multidict = ">=4.0" propcache = ">=0.2.1" [extras] -encryption = ["cryptography"] +encryption = ["cryptography", "sqlglot"] [metadata] lock-version = "2.1" python-versions = "^3.10.0" -content-hash = "7cd044243bd145b872f30416b3db964cb7cfe39d37c44ad1a3df05b1abe9a88e" +content-hash = "511c6be5d88dd7b486441f4c4099f84b00bfdb3cbb91dec4e064c60182ac5e16" diff --git a/pyproject.toml b/pyproject.toml index 48ad28a84..03d70d7ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,10 +52,16 @@ requests = "^2.33.1" # pip install "aws-advanced-python-wrapper[encryption]" # The import is lazy as well: nothing on the core import path imports it. cryptography = { version = ">=42.0.0", optional = true } +# The plugin's SQL analysis (which bind parameter fills which column) parses +# statements with this pure-Python parser. Also only in the `encryption` extra +# and imported lazily. Capped below the next major: its expression tree changes +# shape between majors, and the analysis walks that tree. The floor is the +# oldest release the analysis tests pass on. +sqlglot = { version = ">=30.14.0,<31.0.0", optional = true } [tool.poetry.extras] # `pip install "aws-advanced-python-wrapper[encryption]"` to use the KMS Encryption plugin. -encryption = ["cryptography"] +encryption = ["cryptography", "sqlglot"] [tool.poetry.group.dev.dependencies] mypy = "^1.20.2" @@ -76,6 +82,7 @@ types_aws_xray_sdk = "^2.13.0" # Non-optional in the dev group so the encryption unit tests run without needing # to install the `encryption` extra explicitly. cryptography = ">=42.0.0" +sqlglot = ">=30.14.0,<31.0.0" [tool.poetry.group.test.dependencies] boto3 = "^1.42.95" diff --git a/tests/unit/test_encryption_import_guard.py b/tests/unit/test_encryption_import_guard.py index 666917176..5a8119599 100644 --- a/tests/unit/test_encryption_import_guard.py +++ b/tests/unit/test_encryption_import_guard.py @@ -12,11 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""``cryptography`` is an optional extra (``encryption``). The wrapper must -import without it, and only the module that encrypts may need it. +"""``cryptography`` and ``sqlglot`` are installed only with the optional +``encryption`` extra. The wrapper must import without them; only the module +that encrypts needs ``cryptography`` and only the SQL analyzer needs +``sqlglot``. -Each check runs in a fresh interpreter, most with ``cryptography`` blocked, -since the test environment always has it installed.""" +Each check runs in a fresh interpreter, most with both packages blocked, +since the test environment always has them installed.""" import subprocess import sys @@ -29,7 +31,7 @@ class _Block: def find_spec(self, name, path=None, target=None): - if name == "cryptography" or name.startswith("cryptography."): + if name.partition(".")[0] in ("cryptography", "sqlglot"): raise ModuleNotFoundError(f"No module named {name!r}", name=name) return None @@ -63,11 +65,14 @@ def _run(code: str, block: bool = True) -> subprocess.CompletedProcess: "aws_advanced_python_wrapper.encryption.key_manager", "aws_advanced_python_wrapper.encryption.metadata_manager", "aws_advanced_python_wrapper.encryption.key_management_utility", + # Placeholder scanning is dependency-free; only the structural parse + # needs sqlglot. + "aws_advanced_python_wrapper.encryption.sql_tokenizer", ] @pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) -def test_imports_without_cryptography(module): +def test_imports_without_cryptography_or_sqlglot(module): result = _run(f""" import importlib importlib.import_module({module!r}) @@ -76,13 +81,14 @@ def test_imports_without_cryptography(module): @pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) -def test_does_not_load_cryptography_even_when_installed(module): - # With cryptography available, importing these must still not load it, - # so users who never encrypt don't pay its import cost. +def test_does_not_load_the_extra_even_when_installed(module): + # With the packages available, importing these must still not load them, + # so users who never encrypt don't pay their import cost. result = _run(f""" import importlib importlib.import_module({module!r}) assert "cryptography" not in sys.modules, "cryptography was imported" + assert "sqlglot" not in sys.modules, "sqlglot was imported" """, block=False) assert result.returncode == 0, result.stderr @@ -100,6 +106,20 @@ def test_encryption_service_names_the_extra_when_cryptography_is_missing(): assert "aws-advanced-python-wrapper[encryption]" in result.stdout +def test_sql_analyzer_names_the_extra_when_sqlglot_is_missing(): + result = _run(""" + try: + import aws_advanced_python_wrapper.encryption.sql_analyzer + except ImportError as e: + print(e) + else: + raise SystemExit("imported without sqlglot") + """) + assert result.returncode == 0, result.stderr + assert "'sqlglot'" in result.stdout + assert "aws-advanced-python-wrapper[encryption]" in result.stdout + + _BROKEN = textwrap.dedent(""" import sys @@ -130,3 +150,17 @@ def test_a_broken_cryptography_is_not_reported_as_missing(error): assert result.returncode == 0, result.stderr assert "aws-advanced-python-wrapper[encryption]" not in result.stdout assert ("DLL load failed" in result.stdout) or ("_cffi_backend" in result.stdout) + + +def test_a_broken_sqlglot_is_not_reported_as_missing(): + code = _BROKEN.replace('"cryptography"', '"sqlglot"').format( + error='ModuleNotFoundError("No module named \'sqlglotc\'", name="sqlglotc")') + textwrap.dedent(""" + try: + import aws_advanced_python_wrapper.encryption.sql_analyzer + except ImportError as e: + print(e) + """) + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" not in result.stdout + assert "sqlglotc" in result.stdout diff --git a/tests/unit/test_metadata_manager.py b/tests/unit/test_metadata_manager.py index 70a53b99d..768a516a1 100644 --- a/tests/unit/test_metadata_manager.py +++ b/tests/unit/test_metadata_manager.py @@ -515,3 +515,63 @@ def test_failed_reload_names_the_lookup(clock): with pytest.raises(MetadataError) as err: mm.column_config("users", "ssn") assert (err.value.table_name, err.value.column_name) == ("users", "ssn") + + +# ---- name matching ---- + +def test_postgresql_lookups_are_exact(clock): + # Names are stored as the catalog has them; "Users" and users differ. + db = FakeDb([row("users", "ssn"), row("Users", "SSN", 2)]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.column_config("users", "ssn").key_id == 1 + assert mm.column_config("Users", "SSN").key_id == 2 + assert mm.column_config("USERS", "ssn") is None + assert [c.key_id for c in mm.table_configs("Users")] == [2] + + +def test_mysql_lookups_ignore_case(clock): + # MySQL compares these names case-insensitively, as the uncached query's + # WHERE does under the metadata table's collation. + db = FakeDb([row("Users", "SSN")]) + mm = MetadataManager(db, MYSQL, config()) + mm.start() + found = mm.column_config("users", "ssn") + assert found is not None and (found.table_name, found.column_name) == ("Users", "SSN") + assert mm.is_column_encrypted("USERS", "Ssn") + assert [c.column_name for c in mm.table_configs("users")] == ["SSN"] + assert [c.column_name for c in mm.table_configs("USERS")] == ["SSN"] + assert db.opened == 1 # all from the cache + + +def test_load_metadata_keeps_the_stored_names(): + db = FakeDb([row("Users", "SSN")]) + assert list(MetadataManager(db, MYSQL, config()).load_metadata()) == [("Users", "SSN")] + + +@pytest.mark.parametrize("raw", [b"users", bytearray(b"users"), memoryview(b"users")]) +def test_bytes_names_are_decoded(clock, raw): + # psycopg on a SQL_ASCII database, or Connector/Python with + # use_unicode=False, returns text as bytes. Undecoded, the snapshot would + # be keyed by bytes and no str lookup would find the encrypted column. + db = FakeDb([row(raw, b"ssn")]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.is_column_encrypted("users", "ssn") + assert mm.column_config("users", "ssn").table_name == "users" + + +@pytest.mark.parametrize("raw", [b"\xff\xfe", 42, None]) +def test_names_that_are_not_text_are_refused(clock, raw): + db = FakeDb([row(raw, "ssn")]) + mm = MetadataManager(db, PG, config()) + with pytest.raises(MetadataError, match="table_name") as info: + mm.start() + assert info.value.__context__ is None + + +def test_names_that_are_not_text_are_refused_on_an_uncached_lookup(): + db = FakeDb([row("users", 7)]) + mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + with pytest.raises(MetadataError, match="column_name"): + mm.column_config("users", 7) # type: ignore[arg-type] diff --git a/tests/unit/test_sql_analyzer.py b/tests/unit/test_sql_analyzer.py new file mode 100644 index 000000000..89250d59d --- /dev/null +++ b/tests/unit/test_sql_analyzer.py @@ -0,0 +1,1815 @@ +# 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. + +import dataclasses +import logging +import sys +import threading + +import pytest +import sqlglot +from sqlglot import exp + +from aws_advanced_python_wrapper.encryption import sql_analyzer +from aws_advanced_python_wrapper.encryption.sql_analyzer import (AnalysisGap, + StatementKind, + TableRef, + analyze) +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.encryption.sql_tokenizer import (ColumnRef, + ParamStyle, + tokenize) + + +@pytest.fixture(autouse=True) +def _fresh_cache(): + # The analysis cache is process-wide: without this a test can pass on an + # earlier test's cached result instead of the code path it names. + sql_analyzer._cached_analysis.cache_clear() + yield + sql_analyzer._cached_analysis.cache_clear() + + +BOTH = pytest.mark.parametrize("dialect", [PG, MYSQL], ids=["pg", "mysql"]) +P = (1,) # positional parameters +N = {"x": 1} # named parameters + + +def assigned(a): + return [(u.ordinal, str(u.column)) for u in a.assignments] + + +def compared(a): + return [(u.ordinal, str(u.column)) for u in a.comparisons] + + +def unbound(a): + return [str(c) for c in a.unbound_writes] + + +def names(tables): + return [str(t) for t in tables] + + +def safety(sql, dialect): + return [u.safe for u in analyze(sql, dialect, P).comparisons] + + +def on(both=(), pg=(), mysql=()): + """Parametrizes ``dialect, sql``: each of ``both`` on PostgreSQL and on + MySQL, then each of ``pg`` and ``mysql`` on its own dialect.""" + cases = [(d, s) for s in both for d in (PG, MYSQL)] + [(PG, s) for s in pg] + [(MYSQL, s) for s in mysql] + return pytest.mark.parametrize("dialect, sql", cases, ids=[f"{d.name}: {s}" for d, s in cases]) + + +class TestInsert: + @BOTH + def test_columns_pair_with_their_placeholders(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s)", dialect, P) + assert a.kind is StatementKind.INSERT and a.writes and a.complete + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + assert names(a.written_tables) == ["users"] + assert a.parameter_columns() == {0: ColumnRef("name", "users"), 1: ColumnRef("ssn", "users")} + + @BOTH + def test_multi_row_values(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s), (%s, %s)", dialect, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.name"), (3, "users.ssn")] + + @BOTH + def test_named_placeholders(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%(n)s, %(s)s)", dialect, N) + pairs = [(u.placeholder.key, str(u.column)) for u in a.assignments] + assert pairs == [("n", "users.name"), ("s", "users.ssn")] + + @BOTH + def test_expression_literal_and_default_are_unbound(self, dialect): + a = analyze("INSERT INTO users (a, b, c, d) VALUES (lower(%s), 'x', DEFAULT, %s)", dialect, P) + assert assigned(a) == [(1, "users.d")] + assert unbound(a) == ["users.a", "users.b", "users.c"] + assert a.complete + + @BOTH + def test_null_needs_no_encryption(self, dialect): + a = analyze("INSERT INTO users (a, b) VALUES (%s, NULL)", dialect, P) + assert assigned(a) == [(0, "users.a")] + assert unbound(a) == [] + + @BOTH + def test_casts_are_reported(self, dialect): + sql = ("INSERT INTO users (a, b) VALUES (%s::VARCHAR, CAST(%s AS BINARY))" if dialect is PG + else "INSERT INTO users (a, b) VALUES (CAST(%s AS CHAR), CAST(%s AS BINARY))") + a = analyze(sql, dialect, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b")] + assert all(u.casts for u in a.assignments) + + def test_casts_are_outermost_first(self): + a = analyze("INSERT INTO users (a) VALUES (CAST(%s::text AS bytea))", PG, P) + assert a.assignments[0].casts == ("VARBINARY", "TEXT") + + @BOTH + def test_no_column_list(self, dialect): + a = analyze("INSERT INTO users VALUES (%s, %s)", dialect, P) + assert a.writes and a.gap is AnalysisGap.NO_COLUMN_LIST + assert assigned(a) == [] + + def test_default_values(self): + assert analyze("INSERT INTO users DEFAULT VALUES", PG).gap is AnalysisGap.NO_COLUMN_LIST + + @BOTH + def test_insert_select(self, dialect): + a = analyze("INSERT INTO users (name, ssn) SELECT name, ssn FROM staging WHERE id = %s", dialect, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY + assert assigned(a) == [] + assert compared(a) == [(0, "staging.id")] + assert names(a.tables) == ["users", "staging"] and names(a.written_tables) == ["users"] + + @BOTH + def test_row_length_mismatch(self, dialect): + assert analyze("INSERT INTO users (a, b) VALUES (%s)", dialect, P).gap is AnalysisGap.ROW_LENGTH_MISMATCH + + def test_schema_qualified_table(self): + a = analyze("INSERT INTO app.users (ssn) VALUES (%s)", PG, P) + assert a.written_tables == (TableRef("users", "app"),) + assert assigned(a) == [(0, "users.ssn")] + + def test_alias_with_column_list(self): + a = analyze("INSERT INTO users AS u (ssn) VALUES (%s)", PG, P) + assert assigned(a) == [(0, "users.ssn")] + + def test_returning_columns(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) RETURNING id, ssn AS s, 1", PG, P) + assert a.result_columns == (ColumnRef("id", "users"), ColumnRef("ssn", "users"), None) + + +class TestUpsert: + def test_on_conflict_assignments(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON CONFLICT (id) DO UPDATE SET ssn = %s, note = 'x' WHERE users.age > %s", PG, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.ssn")] + assert unbound(a) == ["users.note"] + assert compared(a) == [(3, "users.age")] + + def test_excluded_copy_of_the_same_column_is_not_a_write(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT (id) DO UPDATE SET ssn = EXCLUDED.ssn", + PG, P) + assert unbound(a) == [] + + def test_excluded_copy_of_another_column_is(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON CONFLICT (id) DO UPDATE SET ssn = EXCLUDED.name", PG, P) + assert unbound(a) == ["users.ssn"] + + def test_on_conflict_do_nothing(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT DO NOTHING", PG, P) + assert assigned(a) == [(0, "users.ssn")] and a.complete + + def test_on_duplicate_key_update(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON DUPLICATE KEY UPDATE ssn = %s, name = VALUES(name), note = VALUES(ssn)", MYSQL, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.ssn")] + assert unbound(a) == ["users.note"] + + def test_on_duplicate_key_update_with_row_alias(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new " + "ON DUPLICATE KEY UPDATE ssn = new.ssn, name = new.ssn", MYSQL, P) + assert unbound(a) == ["users.name"] + + def test_replace(self): + a = analyze("REPLACE INTO users (name, ssn) VALUES (%s, %s)", MYSQL, P) + assert a.kind is StatementKind.INSERT + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + + def test_insert_set_form(self): + a = analyze("INSERT IGNORE INTO users SET name = %s, ssn = %s, note = NULL", MYSQL, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + + @pytest.mark.parametrize("sql", [ + "INSERT LOW_PRIORITY INTO users (ssn) VALUES (%s)", + "INSERT HIGH_PRIORITY IGNORE INTO users (ssn) VALUES (%s)", + "INSERT DELAYED INTO users (ssn) VALUES (%s)", + "REPLACE LOW_PRIORITY INTO users (ssn) VALUES (%s)", + "REPLACE users SET ssn = %s", + ]) + def test_mysql_modifiers(self, sql): + assert assigned(analyze(sql, MYSQL, P)) == [(0, "users.ssn")] + + def test_values_row(self): + a = analyze("INSERT INTO users (a, b) VALUES ROW(%s, %s), ROW(%s, NULL)", MYSQL, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b"), (2, "users.a")] + + +class TestUpdate: + @BOTH + def test_set_and_where(self, dialect): + a = analyze("UPDATE users SET ssn = %s, name = 'x' WHERE id = %s", dialect, P) + assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert assigned(a) == [(0, "users.ssn")] + assert unbound(a) == ["users.name"] + assert compared(a) == [(1, "users.id")] + + @BOTH + def test_alias_and_qualified_assignment(self, dialect): + a = analyze("UPDATE users u SET u.ssn = %s WHERE u.id = %s", dialect, P) + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "users.id")] + + @pytest.mark.parametrize("sql", ["UPDATE LOW_PRIORITY users SET ssn = %s", + "UPDATE IGNORE users SET ssn = %s", + "UPDATE LOW_PRIORITY IGNORE users SET ssn = %s"]) + def test_mysql_modifiers(self, sql): + # Unhandled, the parser reads LOW_PRIORITY as the table. + a = analyze(sql, MYSQL, P) + assert names(a.written_tables) == ["users"] + assert assigned(a) == [(0, "users.ssn")] + + def test_mysql_multi_table_qualified(self): + a = analyze("UPDATE users u JOIN orders o ON o.uid = u.id SET u.ssn = %s, o.total = %s WHERE o.id = %s", + MYSQL, P) + assert a.complete + assert assigned(a) == [(0, "users.ssn"), (1, "orders.total")] + assert compared(a) == [(2, "orders.id")] + assert names(a.written_tables) == ["users", "orders"] + + def test_mysql_multi_table_comma(self): + a = analyze("UPDATE users, orders SET users.ssn = %s WHERE users.id = orders.uid", MYSQL, P) + assert assigned(a) == [(0, "users.ssn")] and a.complete + + def test_mysql_multi_table_unqualified_is_ambiguous(self): + a = analyze("UPDATE users u JOIN orders o ON o.uid = u.id SET ssn = %s", MYSQL, P) + assert a.gap is AnalysisGap.AMBIGUOUS_TABLE + assert assigned(a) == [(0, "ssn")] + + def test_postgresql_from_does_not_add_a_written_table(self): + a = analyze("UPDATE users SET ssn = %s FROM other o WHERE o.id = users.id AND o.ssn = %s", PG, P) + assert names(a.written_tables) == ["users"] + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "other.ssn")] + + def test_multi_column_assignment(self): + a = analyze("UPDATE users SET (a, b) = (%s, %s), (c, d) = ROW(%s, 'x'), (e, f) = (SELECT 1, 2)", PG, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b"), (2, "users.c")] + assert unbound(a) == ["users.d", "users.e", "users.f"] + + def test_set_default(self): + assert unbound(analyze("UPDATE users SET ssn = DEFAULT", PG)) == ["users.ssn"] + + def test_returning(self): + a = analyze("UPDATE users SET ssn = %s RETURNING ssn", PG, P) + assert a.result_columns == (ColumnRef("ssn", "users"),) + + +class TestOtherWrites: + def test_merge(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id " + "WHEN MATCHED AND s.flag = %s THEN UPDATE SET ssn = %s " + "WHEN MATCHED THEN DELETE " + "WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (%s, s.ssn)", PG, P) + assert a.kind is StatementKind.MERGE and a.writes and a.complete + assert assigned(a) == [(1, "users.ssn"), (2, "users.id")] + assert unbound(a) == ["users.ssn"] + assert compared(a) == [(0, "src.flag")] + assert names(a.written_tables) == ["users"] + + def test_merge_insert_without_columns(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id " + "WHEN NOT MATCHED THEN INSERT VALUES (%s, %s)", PG, P) + assert a.gap is AnalysisGap.NO_COLUMN_LIST + + def test_merge_that_only_deletes(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id WHEN MATCHED THEN DELETE", PG) + assert a.writes and a.complete and assigned(a) == [] and unbound(a) == [] + + def test_data_modifying_cte(self): + a = analyze("WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", PG, P) + assert a.kind is StatementKind.SELECT and a.writes + assert assigned(a) == [(0, "users.ssn")] + assert names(a.tables) == ["users"] # w is a CTE, not a table + + def test_update_cte(self): + a = analyze("WITH w AS (UPDATE users SET ssn = %s WHERE id = %s RETURNING id) SELECT id FROM w", PG, P) + assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + + def test_read_only_cte_is_a_read(self): + a = analyze("WITH w AS (SELECT ssn FROM users) SELECT ssn FROM w WHERE ssn = %s", PG, P) + assert not a.writes + assert names(a.tables) == ["users"] + assert compared(a) == [(0, "ssn")] # a CTE column has no table + assert a.result_columns == (ColumnRef("ssn", "users"),) + + def test_cte_insert_select(self): + a = analyze("WITH a AS (SELECT %s AS v) INSERT INTO users (ssn) SELECT v FROM a", PG, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY + + def test_copy_from_names_unbound_columns(self): + a = analyze("COPY users (name, ssn) FROM STDIN", PG) + assert a.kind is StatementKind.COPY_FROM and a.writes and a.complete + assert unbound(a) == ["users.name", "users.ssn"] + + def test_copy_from_without_columns(self): + assert analyze("COPY users FROM STDIN WITH (FORMAT csv)", PG).gap is AnalysisGap.NO_COLUMN_LIST + + def test_copy_to_is_a_read(self): + a = analyze("COPY users TO STDOUT", PG) + assert a.kind is StatementKind.COPY_TO and not a.writes + assert names(a.tables) == ["users"] + + def test_copy_query_to(self): + a = analyze("COPY (SELECT ssn FROM users) TO STDOUT", PG) + assert not a.writes and names(a.tables) == ["users"] + + def test_several_statements_are_all_read(self): + # The ordinals run across the whole string, so each statement's + # placeholders still map to the right parameters. + a = analyze("UPDATE t SET a = %s; INSERT INTO users (name, ssn) VALUES (%s, %s)", MYSQL, P) + assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert assigned(a) == [(0, "t.a"), (1, "users.name"), (2, "users.ssn")] + assert a.result_columns is None + + @BOTH + def test_delete(self, dialect): + a = analyze("DELETE FROM users WHERE ssn = %s", dialect, P) + assert a.kind is StatementKind.DELETE and not a.writes + assert compared(a) == [(0, "users.ssn")] + + def test_mysql_multi_table_delete(self): + a = analyze("DELETE t FROM t JOIN u ON u.id = t.id WHERE u.a = %s", MYSQL, P) + assert compared(a) == [(0, "u.a")] + + +class TestComparisons: + def test_operators(self): + a = analyze("SELECT * FROM t WHERE a = %s AND b <> %s AND c < %s AND d >= %s AND e LIKE %s " + "AND f ILIKE %s AND g IS NOT DISTINCT FROM %s AND %s = h", PG, P) + assert compared(a) == [(i, f"t.{c}") for i, c in enumerate("abcdefgh")] + + @BOTH + def test_a_parenthesized_column_is_paired_with_its_value(self, dialect): + a = analyze("SELECT * FROM users u WHERE (ssn) = %s AND ((u.dob)) IN (%s, %s) AND %s <> (ssn) " + "AND (ssn) BETWEEN %s AND %s", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.dob"), (3, "users.ssn"), + (4, "users.ssn"), (5, "users.ssn")] + + @BOTH + def test_a_sub_selects_only_column_is_paired_with_the_value(self, dialect): + # The sub-select's rows hold that column's values, and its column is resolved in the sub-select, not in t. + a = analyze("SELECT name FROM t WHERE %s IN (SELECT ssn FROM users) AND %s = ANY (SELECT u.dob FROM users u) " + "AND %s = SOME (SELECT ssn AS s FROM users) AND %s <> ALL (SELECT ((ssn)) FROM users) " + "AND %s = (SELECT ssn FROM users LIMIT 1) AND (SELECT ssn FROM users LIMIT 1) = %s " + "AND %s IN ((SELECT ssn FROM users))", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.ssn"), (3, "users.ssn"), + (4, "users.ssn"), (5, "users.ssn"), (6, "users.ssn")] + assert not any(u.array for u in a.comparisons) + + @BOTH + def test_a_sub_select_with_more_than_its_column_is_not_paired(self, dialect): + a = analyze("SELECT name FROM t WHERE %s IN (SELECT ssn FROM users UNION SELECT ssn FROM archive) " + "AND %s IN (SELECT lower(ssn) FROM users) AND %s IN (SELECT * FROM users) " + "AND (%s, %s) IN (SELECT ssn, dob FROM users) AND ssn IN (SELECT %s) " + "AND %s IN (SELECT ssn, dob FROM users)", dialect, P) + assert compared(a) == [] + + @BOTH + def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_paired(self, dialect): + # sqlglot reads ALL ((SELECT ...)) and SOME ((SELECT ...)) as functions; both servers read a sub-select. + a = analyze("SELECT name FROM t WHERE %s <> ALL ((SELECT ssn FROM users)) " + "AND %s = SOME (((SELECT u.ssn AS s FROM users u))) AND %s = some ((select dob from users))", + dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.ssn"), (2, "users.dob")] + assert not any(u.array for u in a.comparisons) + + @BOTH + def test_all_or_some_over_anything_but_a_sub_select_of_the_column_is_not_paired(self, dialect): + # The last two compare the value with the elements of an array column, not with the column. + a = analyze("SELECT name FROM t WHERE %s <> ALL ((SELECT ssn FROM users UNION SELECT ssn FROM archive)) " + "AND %s = SOME ((SELECT lower(ssn) FROM users)) " + "AND %s = SOME ((SELECT ssn FROM users), (SELECT dob FROM users)) " + "AND %s = foo((SELECT ssn FROM users)) AND %s = SOME ((ssn) ORDER BY 1) " + "AND %s = ALL (tags) AND %s = SOME (tags)", + dialect, P) + assert compared(a) == [] + + @BOTH + def test_a_sub_select_with_order_by_or_limit_after_its_parentheses_is_paired(self, dialect): + # sqlglot puts an ORDER BY or LIMIT between the parentheses of ALL ((...)) or SOME ((...)) over the Subquery. + a = analyze("SELECT name FROM t WHERE %s = SOME ((SELECT ssn FROM users) ORDER BY 1) " + "AND %s <> ALL ((SELECT dob FROM users) LIMIT 5) " + "AND %s = some ((select u.ssn as s from users u) order by 1 limit 5)", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.ssn")] + assert not any(u.array for u in a.comparisons) + + def test_in_between_and_any(self): + a = analyze("SELECT * FROM t WHERE a IN (%s, %s) AND b BETWEEN %s AND %s AND c = ANY(%s)", PG, P) + assert compared(a) == [(0, "t.a"), (1, "t.a"), (2, "t.b"), (3, "t.b"), (4, "t.c")] + assert [u.array for u in a.comparisons] == [False] * 4 + [True] + + def test_mysql_null_safe_equals(self): + assert compared(analyze("SELECT * FROM t WHERE a <=> %s", MYSQL, P)) == [(0, "t.a")] + + def test_join_resolves_aliases_and_leaves_unqualified_columns_open(self): + a = analyze("SELECT u.ssn FROM users u JOIN orders o ON o.uid = u.id " + "WHERE u.name = %s AND o.id = %s AND total = %s", PG, P) + assert compared(a) == [(0, "users.name"), (1, "orders.id"), (2, "total")] + + def test_subquery_scope(self): + a = analyze("SELECT * FROM users WHERE id IN (SELECT uid FROM orders WHERE total = %s) AND ssn = %s", + PG, P) + assert compared(a) == [(0, "orders.total"), (1, "users.ssn")] + + def test_correlated_qualifier_from_an_outer_query(self): + a = analyze("SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.uid = u.id AND u.ssn = %s)", + PG, P) + assert compared(a) == [(0, "users.ssn")] + + def test_column_against_column_is_not_a_parameter(self): + assert compared(analyze("SELECT * FROM t WHERE a = b", PG)) == [] + + def test_jsonb_question_mark_operator(self): + # "?" is an operator on PostgreSQL, not a placeholder. + a = analyze("SELECT ssn FROM users WHERE data ? 'k' AND id = %s", PG, P) + assert a.complete and compared(a) == [(0, "users.id")] + + def test_unknown_qualifier_is_taken_as_a_table(self): + assert compared(analyze("SELECT * FROM users WHERE other.ssn = %s", PG, P)) == [(0, "other.ssn")] + + +class TestComparisonSafety: + """``ParameterUse.safe``: whether a comparison that never matches can only + remove rows from what the statement reads or changes.""" + + @on(both=["SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE %s = ssn", + "SELECT id FROM users WHERE ssn IN (%s, %s)", + "SELECT id FROM users WHERE ssn LIKE %s", + "SELECT id FROM users WHERE ssn LIKE %s ESCAPE '!'"], + pg=["SELECT id FROM users WHERE ssn = ANY(%s)", + "SELECT id FROM users WHERE ssn = SOME(%s)", + "SELECT id FROM users WHERE ssn ILIKE %s", + "SELECT id FROM users WHERE ssn IS NOT DISTINCT FROM %s", + "SELECT id FROM users WHERE ssn LIKE ANY(%s)", + "SELECT id FROM users WHERE ssn LIKE SOME(%s)", + "SELECT id FROM users WHERE ssn ILIKE ANY(%s)"], + mysql=["SELECT id FROM users WHERE ssn LIKE BINARY %s", + "SELECT id FROM users WHERE ssn <=> %s"]) + def test_safe_operators(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and all(flags) + + @on(both=["SELECT id FROM users WHERE ssn <> %s", + "SELECT id FROM users WHERE %s <> ssn", + "SELECT id FROM users WHERE ssn != %s", + "SELECT id FROM users WHERE ssn < %s", + "SELECT id FROM users WHERE ssn <= %s", + "SELECT id FROM users WHERE ssn > %s", + "SELECT id FROM users WHERE ssn >= %s", + "SELECT id FROM users WHERE ssn BETWEEN %s AND %s", + "SELECT id FROM users WHERE ssn NOT BETWEEN %s AND %s", + "SELECT id FROM users WHERE ssn NOT IN (%s, %s)", + "SELECT id FROM users WHERE ssn NOT LIKE %s", + "SELECT id FROM users WHERE ssn NOT LIKE %s ESCAPE '!'"], + pg=["SELECT id FROM users WHERE ssn IS DISTINCT FROM %s", + "SELECT id FROM users WHERE ssn NOT ILIKE %s", + "SELECT id FROM users WHERE ssn <> ALL(%s)", + "SELECT id FROM users WHERE ssn <> ANY(%s)", + "SELECT id FROM users WHERE ssn = ALL(%s)", + "SELECT id FROM users WHERE ssn LIKE ALL(%s)", + "SELECT id FROM users WHERE ssn NOT LIKE ANY(%s)"]) + def test_unsafe_operators(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and not any(flags) + + @BOTH + def test_a_parenthesized_column_is_judged_like_the_column(self, dialect): + # sqlglot keeps the parentheses as a Paren node around the column. + assert safety("SELECT id FROM users WHERE (ssn) = %s OR ((ssn)) LIKE %s", dialect) == [True, True] + assert safety("DELETE FROM users WHERE (ssn) <> %s", dialect) == [False] + assert safety("DELETE FROM users WHERE %s <> (ssn) OR ((ssn)) NOT LIKE %s", dialect) == [False, False] + + @BOTH + def test_a_sub_selects_only_column_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s IN (SELECT ssn FROM users) OR %s = ANY (SELECT ssn FROM users) " + "OR %s = (SELECT ssn FROM users LIMIT 1)", dialect) == [True] * 3 + # = ALL over no rows is true, so only ALL itself makes it unsafe. + unsafe = ["%s NOT IN (SELECT ssn FROM users)", "%s <> ALL (SELECT ssn FROM users)", + "%s = ALL (SELECT ssn FROM users)", "%s <> ANY (SELECT ssn FROM users)", + "%s <> (SELECT ssn FROM users LIMIT 1)", "%s > (SELECT ssn FROM users LIMIT 1)"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + assert safety("SELECT %s IN (SELECT ssn FROM users) FROM t", dialect) == [False] + + @BOTH + def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users)) " + "OR %s = some (((select ssn from users)))", dialect) == [True, True] + unsafe = ["%s <> ALL ((SELECT ssn FROM users))", "%s = ALL ((SELECT ssn FROM users))", + "%s = all (((select ssn from users)))", "%s <> SOME ((SELECT ssn FROM users))"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_a_sub_select_read_by_some_in_doubled_parentheses_is_judged_like_any(self, dialect): + assert safety("DELETE FROM orders WHERE uid = SOME ((SELECT id FROM users WHERE ssn = %s)) " + "OR uid = some (((select id from users where dob = %s)))", dialect) == [True, True] + # ALL over a sub-select whose filter never holds is true for every row. + assert safety("DELETE FROM orders WHERE uid = ALL ((SELECT id FROM users WHERE ssn = %s))", dialect) == [False] + # As under <> ANY (SELECT ...), only = reads the sub-select. + assert safety("DELETE FROM orders WHERE uid <> SOME ((SELECT id FROM users WHERE ssn = %s))", dialect) == [False] + + @BOTH + def test_a_sub_select_with_order_by_or_limit_after_its_parentheses_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users) LIMIT 5)", dialect) == [True] + unsafe = ["%s <> ALL ((SELECT ssn FROM users) ORDER BY 1)", "%s <> ALL ((SELECT ssn FROM users) LIMIT 5)", + "%s = all ((select ssn from users) order by 1 limit 5)"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_a_read_sub_select_with_order_by_or_limit_after_its_parentheses_is_judged_by_its_reader(self, dialect): + assert safety("DELETE FROM orders WHERE uid = SOME ((SELECT id FROM users WHERE ssn = %s) LIMIT 5) " + "OR uid = SOME ((SELECT id FROM users WHERE dob = %s) ORDER BY 1) " + "OR EXISTS ((SELECT 1 FROM users WHERE name = %s) ORDER BY 1 LIMIT 1)", dialect) == [True] * 3 + # ALL over a sub-select whose filter never holds is true for every row, and a LIMIT count taken from such a + # sub-select is NULL, which PostgreSQL reads as no limit. + unsafe = ["uid = ALL ((SELECT id FROM users WHERE ssn = %s) LIMIT 5)", + "uid = SOME ((SELECT id FROM t2) LIMIT (SELECT id FROM users WHERE ssn = %s))"] + assert [safety(f"DELETE FROM orders WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_not_like_is_unsafe_without_a_not_node(self, dialect): + sql = "SELECT id FROM users WHERE ssn NOT LIKE %s" + trees, _ = sql_analyzer._parse(tokenize(sql, dialect, ParamStyle.of(P, dialect)).normalized, dialect) + # sqlglot sets the LIKE's negate flag rather than adding a NOT node, + # so only the operator check can see the negation. + assert trees and trees[0].find(exp.Not) is None and trees[0].find(exp.Like).args.get("negate") + assert safety(sql, dialect) == [False] + + @on(both=["SELECT id FROM users WHERE (ssn = %s)", + "SELECT id FROM users WHERE id > 0 AND (name = 'a' OR (ssn = %s))", + "SELECT id FROM users WHERE ((ssn = %s) OR (id > 0 AND ssn = %s))", + "SELECT id FROM users u, orders o WHERE o.uid = u.id AND u.ssn = %s", + "SELECT name FROM users GROUP BY name, ssn HAVING ssn = %s", + "SELECT name, COUNT(*) FROM users GROUP BY name, ssn HAVING ssn = %s", + "SELECT a.name FROM users a JOIN users b ON a.id = b.id AND b.ssn = %s", + "SELECT a.id FROM users a JOIN users b ON b.ssn = %s AND a.id = b.id", + "SELECT u.id FROM users u INNER JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "SELECT name FROM users WHERE id IN (SELECT id FROM users WHERE ssn = %s)", + "SELECT id FROM users WHERE id IN ((SELECT id FROM users WHERE ssn = %s))", + "SELECT id FROM users WHERE id IN (SELECT id FROM users WHERE ssn = %s UNION SELECT id FROM users)", + "SELECT id FROM users u WHERE EXISTS (SELECT 1 FROM users v WHERE v.id = u.id AND v.ssn = %s)", + "SELECT id FROM orders WHERE EXISTS (SELECT id FROM users WHERE ssn = %s AND my_fn(id))", + "DELETE FROM orders WHERE uid = (SELECT id FROM users WHERE ssn = %s)", + "UPDATE orders SET note = 'x' WHERE (SELECT id FROM users WHERE ssn = %s) = uid", + "DELETE FROM orders WHERE uid = ANY(SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid = SOME(SELECT id FROM users WHERE ssn = %s)", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u JOIN orders o ON o.uid = u.id", + "SELECT u.id FROM orders o JOIN (SELECT id FROM users WHERE ssn = %s) u ON o.uid = u.id", + "UPDATE orders SET note = 'x' WHERE uid IN (SELECT id FROM (SELECT id FROM users WHERE ssn = %s) d)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w", + "WITH c AS (SELECT id, ssn FROM users WHERE ssn = %s) SELECT id FROM c", + "WITH c AS (SELECT id, ssn FROM users) SELECT id FROM c WHERE ssn = %s", + "WITH a AS (SELECT id FROM users WHERE ssn = %s), b AS (SELECT id FROM a) SELECT id FROM b", + "WITH a AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM users WHERE id IN (SELECT id FROM a)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT u.id FROM users u JOIN w ON w.id = u.id", + "SELECT id FROM users WHERE ssn = %s UNION SELECT id FROM users", + "SELECT id FROM users UNION ALL SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s INTERSECT SELECT id FROM users", + "SELECT id FROM users INTERSECT SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s EXCEPT SELECT id FROM users", + "(SELECT id FROM users WHERE ssn = %s)", + "((SELECT id FROM users WHERE ssn = %s) UNION (SELECT id FROM users))", + "SELECT id FROM users WHERE ssn = %s ORDER BY id LIMIT 1", + "UPDATE users SET note = 'x' WHERE ssn = %s", + "DELETE FROM users WHERE ssn = %s", + "INSERT INTO audit (uid) SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s; DELETE FROM users WHERE ssn = %s"], + pg=["UPDATE users SET note = 'x' WHERE ssn = %s RETURNING id", + "DELETE FROM users WHERE ssn = %s RETURNING id", + "UPDATE users SET name = 'x' FROM users v WHERE v.id = users.id AND v.ssn = %s", + "DELETE FROM users USING users v WHERE v.id = users.id AND v.ssn = %s", + "WITH d AS (DELETE FROM users WHERE ssn = %s RETURNING id) SELECT id FROM d", + "WITH users AS (SELECT id FROM public.users WHERE ssn = %s) SELECT id FROM users"], + mysql=["UPDATE users u JOIN orders o ON o.uid = u.id AND u.ssn = %s SET o.note = 'x'", + "UPDATE users u JOIN orders o ON o.uid = u.id SET o.note = 'x' WHERE u.ssn = %s", + "DELETE u FROM users u JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "DELETE t FROM t JOIN u ON u.id = t.id WHERE u.ssn = %s", + "SELECT u.id FROM users u STRAIGHT_JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "SELECT u.id FROM users u CROSS JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "WITH users AS (SELECT id FROM mydb.users WHERE ssn = %s) SELECT id FROM users"]) + def test_safe_positions(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and all(flags) + + @on(both=["SELECT id FROM users WHERE NOT ssn = %s", + "SELECT id FROM users WHERE NOT (ssn = %s OR id = 1)", + "SELECT id FROM users WHERE (ssn = %s) IS TRUE", + "SELECT id FROM users WHERE (ssn = %s) IS NOT TRUE", + "SELECT id FROM users WHERE (ssn = %s) IS FALSE", + "SELECT id FROM users WHERE (ssn = %s) = FALSE", + "SELECT id FROM users WHERE CASE WHEN ssn = %s THEN FALSE ELSE TRUE END", + "SELECT id FROM users WHERE COALESCE(ssn = %s, FALSE)", + "SELECT ssn = %s FROM users", + "SELECT (SELECT 1 FROM users WHERE ssn = %s) FROM orders", + "SELECT id FROM users ORDER BY ssn = %s", + "SELECT COUNT(*) FROM users GROUP BY ssn = %s", + "UPDATE users SET flag = (ssn = %s)", + "UPDATE users SET note = (SELECT note FROM orders WHERE orders.ssn = %s)", + "INSERT INTO audit (uid) VALUES ((SELECT id FROM users WHERE ssn = %s))", + "SELECT u.id FROM users u LEFT JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u LEFT JOIN users v ON v.id = u.id AND u.ssn = %s", + "SELECT u.id FROM users u LEFT OUTER JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u RIGHT JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u RIGHT JOIN users v ON v.id = u.id AND u.ssn = %s", + "DELETE FROM orders WHERE uid NOT IN (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id = orders.uid AND users.ssn = %s)", + "DELETE FROM orders WHERE uid <> ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid > ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid = ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid <> ANY (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid <> (SELECT id FROM users WHERE ssn = %s)", + "SELECT id FROM users EXCEPT SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM orders WHERE uid IN (SELECT id FROM users EXCEPT SELECT id FROM users WHERE ssn = %s)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) DELETE FROM orders WHERE uid NOT IN (SELECT id FROM w)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT u.id FROM users u LEFT JOIN w ON w.id = u.id", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w UNION SELECT id FROM orders " + "WHERE uid NOT IN (SELECT id FROM w)", + "SELECT v.id FROM users v LEFT JOIN (SELECT id FROM users WHERE ssn = %s) u ON v.id = u.id", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u LEFT JOIN users v ON v.id = u.id", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u JOIN orders o ON o.uid = u.id " + "RIGHT JOIN items i ON i.oid = o.id", + "SELECT id FROM orders WHERE (SELECT id FROM users WHERE ssn = %s) IN (1, 2)", + "SELECT u.id FROM users u JOIN orders o ON (SELECT TRUE FROM users v WHERE v.ssn = %s)"], + pg=["UPDATE users SET note = 'x' RETURNING ssn = %s", + "WITH x AS (INSERT INTO audit (uid) SELECT id FROM users WHERE ssn = %s RETURNING uid) SELECT uid FROM x", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) INSERT INTO w (id) VALUES (1)", + "SELECT u.id FROM users u ANTI JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "DELETE FROM orders WHERE uid IS DISTINCT FROM (SELECT id FROM users WHERE ssn = %s)", + "MERGE INTO users t USING src s ON t.ssn = %s WHEN MATCHED THEN DELETE", + "MERGE INTO users t USING src s ON t.id = s.id WHEN MATCHED AND t.ssn = %s THEN DELETE", + "MERGE INTO orders t USING (SELECT id FROM users WHERE ssn = %s) s ON t.uid = s.id WHEN MATCHED THEN DELETE", + "INSERT INTO users (id, ssn) VALUES (%s, %s) ON CONFLICT (id) DO UPDATE SET note = 'x' WHERE users.ssn = %s", + "SELECT u.id FROM users u FULL JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT id FROM orders o, LATERAL (SELECT 1 FROM users v WHERE v.ssn = %s) x", + "SELECT id FROM orders o CROSS JOIN LATERAL (SELECT 1 FROM users v WHERE v.ssn = %s) x"], + mysql=["SELECT id FROM users WHERE ssn = %s XOR TRUE", + "SELECT id FROM users WHERE IF(ssn = %s, 0, 1) = 1", + "DELETE FROM orders WHERE uid <=> (SELECT id FROM users WHERE ssn = %s)", + "DELETE u FROM users u LEFT JOIN orders o ON o.uid = u.id AND u.ssn = %s WHERE o.uid IS NULL", + "UPDATE users u LEFT JOIN orders o ON o.uid = u.id AND u.ssn = %s SET u.note = 'x' WHERE o.uid IS NULL"]) + def test_unsafe_positions(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and not any(flags) + + @pytest.mark.parametrize("dialect, sql, column", [ + (PG, "SELECT i.id FROM users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (MYSQL, "DELETE i FROM users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT o.id FROM users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (MYSQL, "SELECT o.id FROM users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT u.id FROM users u LEFT JOIN (orders o JOIN items i ON i.oid = o.id{on}) ON o.uid = u.id{where}", + "o.ssn"), + (MYSQL, "SELECT u.id FROM users u LEFT JOIN (orders o JOIN items i ON i.oid = o.id{on}) ON o.uid = u.id{where}", + "o.ssn"), + (PG, "SELECT i.id FROM (users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id){where}", + "u.ssn"), + (PG, "SELECT r.id FROM users u CROSS JOIN (orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id){where}", "o.ssn"), + (MYSQL, "SELECT r.id FROM users u CROSS JOIN (orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id){where}", "o.ssn"), + (PG, "UPDATE users SET note = 'x' FROM orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id{where}", "o.ssn"), + (PG, "DELETE FROM users USING orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r ON r.iid = i.id{where}", + "o.ssn"), + (MYSQL, "UPDATE users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id SET u.note = 'x'{where}", + "u.ssn"), + (MYSQL, "DELETE FROM i USING users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT r.id FROM ((orders JOIN items ON items.oid = orders.id{on}) RIGHT JOIN refs r ON r.iid = items.id){where}", + "orders.ssn"), + (MYSQL, "DELETE u FROM users u CROSS JOIN ((orders JOIN items ON items.oid = orders.id{on}) RIGHT JOIN refs r " + "ON r.iid = items.id){where}", "orders.ssn"), + ], ids=["pg-right", "mysql-delete-right", "pg-later-left", "mysql-later-left", "pg-parenthesized-under-left", + "mysql-parenthesized-under-left", "pg-right-inside-parentheses", "pg-right-inside-a-joined-parenthesis", + "mysql-right-inside-a-joined-parenthesis", "pg-update-from", "pg-delete-using", "mysql-update", + "mysql-delete-using", "pg-right-around-nested-parentheses", "mysql-delete-right-around-nested-parentheses"]) + def test_inner_join_in_a_query_with_an_outer_join_is_unsafe(self, dialect, sql, column): + # A later RIGHT or FULL join keeps every row of its side when the + # earlier join matches nothing, and so does a LEFT join around a + # parenthesized join. A WHERE filters the joined rows. + assert safety(sql.format(on=f" AND {column} = %s", where=""), dialect) == [False] + assert safety(sql.format(on="", where=f" WHERE {column} = %s"), dialect) == [True] + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "UPDATE users SET note = 'x' FROM (SELECT id FROM orders) o " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = o.id WHERE d.id IS NULL AND o.id = users.id"), + (PG, "DELETE FROM users USING (SELECT id FROM orders) o " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = o.id WHERE d.id IS NULL AND o.id = users.id"), + (MYSQL, "UPDATE (SELECT id FROM orders) o JOIN users u ON u.id = o.id " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = u.id SET u.note = 'x' WHERE d.id IS NULL"), + (PG, "SELECT r.id FROM users u CROSS JOIN (((SELECT id FROM users WHERE ssn = %s) d JOIN items ON items.oid = d.id) " + "RIGHT JOIN refs r ON r.iid = items.id)"), + ], ids=["pg-update-from-derived-table", "pg-delete-using-derived-table", "mysql-update-derived-table", + "pg-derived-table-in-nested-parentheses"]) + def test_outer_join_after_a_parenthesized_source_is_seen(self, dialect, sql): + # sqlglot hangs the joins that follow a derived table or a + # parenthesized join on its Subquery. When the derived table d matches + # nothing, the sided join there still keeps every row of its other side. + assert safety(sql, dialect) == [False] + + @pytest.mark.parametrize("sql, safe", [ + ("SELECT id FROM users WHERE (SELECT COUNT(*) FROM users WHERE ssn = %s) = 0", False), + ("DELETE FROM orders WHERE (SELECT COUNT(*) FROM users v WHERE v.id = orders.uid AND v.ssn = %s) = 0", False), + ("SELECT id FROM users WHERE EXISTS (SELECT COUNT(*) FROM users WHERE ssn = %s)", False), + ("SELECT id FROM orders WHERE uid = (SELECT MAX(id) FROM users WHERE ssn = %s)", False), + ("SELECT id FROM users WHERE id IN (SELECT uid FROM orders WHERE ssn = %s GROUP BY uid HAVING COUNT(*) < 2)", + False), + ("SELECT id FROM users WHERE id IN (SELECT uid FROM orders WHERE ssn = %s GROUP BY uid)", False), + ("SELECT id FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s HAVING COUNT(*) < 2)", False), + ("SELECT d.id FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM users WHERE ssn = %s) d", False), + ("WITH c AS (SELECT COUNT(*) AS n FROM users WHERE ssn = %s) SELECT n FROM c", False), + ("SELECT COUNT(*) FROM users WHERE ssn = %s", True), + ], ids=["count-equals-zero", "correlated-count", "exists-count", "max", "group-having", "group", "having", + "window", "cte", "the-statement"]) + @BOTH + def test_aggregating_sub_select_is_unsafe(self, dialect, sql, safe): + assert safety(sql, dialect) == [safe] + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "DELETE FROM orders WHERE EXISTS (SELECT jsonb_agg(id) FROM users WHERE ssn = %s)"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT JSON_ARRAYAGG(id) FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT my_agg(id) FROM users WHERE ssn = %s)"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT my_agg(id) FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s ORDER BY COUNT(*))"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s ORDER BY COUNT(*))"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT DISTINCT ON (COUNT(*)) 1 FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s WINDOW w AS (ORDER BY COUNT(*)))"), + ], ids=["pg-jsonb-agg", "mysql-json-arrayagg", "pg-user-defined", "mysql-user-defined", "pg-order-by", + "mysql-order-by", "pg-distinct-on", "pg-window-clause"]) + def test_possible_aggregate_in_a_sub_select_is_unsafe(self, dialect, sql): + # An aggregate without GROUP BY returns a row for no input row, so the + # EXISTS holds and every order is deleted. sqlglot reads some built-in + # aggregates and every user-defined one as a function it doesn't know, + # and a query's own aggregate can also sit in ORDER BY, DISTINCT ON or + # WINDOW. + assert safety(sql, dialect) == [False] + + @pytest.mark.parametrize("sql", [ + "WITH RECURSIVE r AS (SELECT id FROM users WHERE ssn = %s " + "UNION ALL SELECT u.id FROM users u JOIN r ON u.id = r.id + 1) SELECT id FROM r", + "WITH RECURSIVE r AS (SELECT id FROM users " + "UNION ALL SELECT u.id FROM users u JOIN r ON u.id = r.id + 1 WHERE u.ssn = %s) SELECT id FROM r", + ], ids=["anchor", "recursive-part"]) + @BOTH + def test_recursive_cte_reference_is_unsafe(self, dialect, sql): + assert safety(sql, dialect) == [False] + + @pytest.mark.timeout(5) + @BOTH + def test_long_cte_chain_is_followed_without_recursion(self, dialect): + # Each CTE reads the one before it, so the statement, 2000 queries + # out, decides the comparison's position. + ctes = ["c0 AS (SELECT id FROM users WHERE ssn = %s)"] + [f"c{i} AS (SELECT id FROM c{i - 1})" for i in range(1, 2000)] + assert safety("WITH " + ", ".join(ctes) + " SELECT id FROM c1999", dialect) == [True] + + @BOTH + def test_assignments_and_annotations_keep_the_default(self, dialect): + a = analyze("UPDATE users SET ssn = %s WHERE id <> /*@encrypt:users.ssn*/ %s", dialect, P) + assert [(u.ordinal, u.safe) for u in a.assignments] == [(0, True)] + assert [(u.ordinal, u.safe) for u in a.annotations] == [(1, True)] + assert [(u.ordinal, u.safe) for u in a.comparisons] == [(1, False)] + assert [u.safe for u in analyze("INSERT INTO users (id, ssn) VALUES (%s, %s)", dialect, P).assignments] \ + == [True, True] + + @pytest.mark.timeout(10) + def test_comparison_safety_is_time_bounded_in_a_long_or_chain(self): + # Without the memo, each comparison climbs the rest of the chain: far + # past the timeout at this length. + sql = "SELECT id FROM users WHERE " + " OR ".join(["ssn = %s"] * 40000) + flags = safety(sql, PG) + assert len(flags) == 40000 and all(flags) + + +class TestReads: + @BOTH + def test_tables_and_result_columns(self, dialect): + a = analyze("SELECT u.ssn AS s, o.ssn, name, 1 FROM users u JOIN orders o ON o.uid = u.id", dialect) + assert a.kind is StatementKind.SELECT and not a.writes + assert names(a.tables) == ["users", "orders"] + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("ssn", "orders"), None, None) + + def test_single_table_unqualified(self): + a = analyze("SELECT ssn, name FROM users WHERE id = %s", PG, P) + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("name", "users")) + + @pytest.mark.parametrize("sql", ["SELECT * FROM users", "SELECT u.* FROM users u", + "SELECT ssn FROM users UNION SELECT ssn FROM archive"]) + def test_result_columns_unknown(self, sql): + assert analyze(sql, PG).result_columns is None + + def test_subquery_column_is_traced_to_its_table(self): + a = analyze("SELECT s.ssn FROM (SELECT ssn FROM users) s", PG) + assert a.result_columns == (ColumnRef("ssn", "users"),) + assert names(a.tables) == ["users"] + + @BOTH + @pytest.mark.parametrize("sql, params, expected", [ + ("SELECT x.ssn FROM (SELECT ssn FROM users) AS x", None, (ColumnRef("ssn", "users"),)), + ("SELECT ssn FROM (SELECT ssn FROM users) x", None, (ColumnRef("ssn", "users"),)), + ("WITH c AS (SELECT ssn FROM users) SELECT c.ssn FROM c", None, (ColumnRef("ssn", "users"),)), + ("SELECT y.ssn FROM (SELECT x.ssn FROM (SELECT ssn FROM users) x) y", None, (ColumnRef("ssn", "users"),)), + ("SELECT x.s FROM (SELECT ssn AS s FROM users) x", None, (ColumnRef("ssn", "users"),)), + ("WITH c AS (SELECT ssn FROM users) SELECT x.ssn FROM (SELECT ssn FROM c) x", None, + (ColumnRef("ssn", "users"),)), + ("SELECT u.name, d.ssn FROM users u JOIN (SELECT id, ssn FROM archive) d ON d.id = u.id", None, + (ColumnRef("name", "users"), ColumnRef("ssn", "archive"))), + ("WITH a AS (SELECT id FROM archive), c AS (SELECT ssn FROM users) SELECT c.ssn FROM c", None, + (ColumnRef("ssn", "users"),)), + ("SELECT y.ssn FROM (SELECT id FROM archive) x JOIN (SELECT id, ssn FROM users) y ON x.id = y.id", None, + (ColumnRef("ssn", "users"),)), + # SQLAlchemy's legacy Query.first() over a model with a joined eager load. + ("SELECT anon_1.users_id AS anon_1_users_id, anon_1.users_ssn AS anon_1_users_ssn, addresses_1.id AS addresses_1_id " + "FROM (SELECT users.id AS users_id, users.ssn AS users_ssn FROM users LIMIT %s) AS anon_1 " + "LEFT OUTER JOIN addresses AS addresses_1 ON anon_1.users_id = addresses_1.user_id", P, + (ColumnRef("id", "users"), ColumnRef("ssn", "users"), ColumnRef("id", "addresses"))), + ], ids=["derived", "only_source", "cte", "nested", "relabelled", "cte_behind_derived", "joined", "two_ctes", + "second_derived", "orm_first"]) + def test_derived_and_cte_columns_trace_to_their_table(self, dialect, sql, params, expected): + assert analyze(sql, dialect, params).result_columns == expected + + @BOTH + @pytest.mark.parametrize("sql", [ + "SELECT x.ssn FROM (SELECT ssn FROM users UNION SELECT ssn FROM archive) x", + "SELECT x.ssn FROM (SELECT * FROM users) x", + "SELECT x.s FROM (SELECT upper(ssn) AS s FROM users) x", + "SELECT ssn FROM (SELECT ssn FROM users) x, (SELECT ssn FROM archive) y", + "SELECT g.ssn FROM (SELECT ssn FROM users) y CROSS JOIN generate_series(1, 2) AS g", + ], ids=["set_operation", "star", "expression", "two_sources", "function_source"]) + def test_untraceable_derived_columns_stay_unknown(self, dialect, sql): + assert analyze(sql, dialect).result_columns == (None,) + + @BOTH + def test_self_shadowing_cte_stays_unknown(self, dialect): + # The inner users is the table, but every unqualified users reads as + # the CTE, and a CTE doesn't see itself, so the trace stops there. + assert analyze("WITH users AS (SELECT ssn FROM users) SELECT ssn FROM users", dialect).result_columns == (None,) + + @BOTH + @pytest.mark.parametrize("sql, expected", [ + # Inside c, users is the table: a later CTE of that name isn't seen. + ("WITH c AS (SELECT ssn FROM users), users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c", (None,)), + ("WITH c AS (SELECT u.ssn FROM users u), users AS (SELECT name AS ssn FROM people) SELECT c.ssn FROM c", (None,)), + ("WITH c AS (SELECT x.ssn FROM (SELECT ssn FROM users) x), users AS (SELECT name AS ssn FROM people) " + "SELECT ssn FROM c", (None,)), + ("WITH users AS (SELECT name AS ssn FROM people), c AS (SELECT ssn FROM users) SELECT ssn FROM c", + (ColumnRef("name", "people"),)), + # Past c, the trace takes the outer users; under RECURSIVE, PostgreSQL + # reads the later inner one instead, so the column stays unknown. + ("WITH users AS (SELECT addr AS ssn FROM homes) SELECT z.ssn FROM (WITH c AS (SELECT ssn FROM users), " + "users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c) z", (ColumnRef("addr", "homes"),)), + ("WITH users AS (SELECT addr AS ssn FROM homes) SELECT z.ssn FROM (WITH RECURSIVE c AS (SELECT ssn FROM users), " + "users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c) z", (None,)), + ], ids=["forward", "forward_qualified", "forward_in_derived", "backward", "nested_outer", "nested_outer_recursive"]) + def test_a_cte_sees_only_the_ctes_before_it(self, dialect, sql, expected): + assert analyze(sql, dialect).result_columns == expected + + @BOTH + @pytest.mark.parametrize("sql", [ + "WITH c(ssn, name) AS (SELECT name, ssn FROM users) SELECT c.ssn, c.name FROM c", + "SELECT x.ssn, x.name FROM (SELECT name, ssn FROM users) AS x(ssn, name)", + ], ids=["cte", "derived"]) + def test_a_source_with_a_column_list_stays_unknown(self, dialect, sql): + # The list renames the columns by position (here c.ssn is users.name), + # which the trace doesn't follow. + assert analyze(sql, dialect).result_columns == (None, None) + + @pytest.mark.parametrize("sql, expected", [ + ("WITH c AS (SELECT name, ssn FROM users) SELECT x.ssn FROM c AS x(ssn, name)", (None,)), + ("SELECT d.ssn FROM users AS u(a, b) JOIN (SELECT id, ssn FROM archive) d ON d.id = u.a", + (ColumnRef("ssn", "archive"),)), + ], ids=["cte_renamed_where_read", "other_source_renamed"]) + def test_only_a_column_list_on_the_traced_source_matters(self, sql, expected): + assert analyze(sql, PG).result_columns == expected + + def test_returning_list_is_not_traced(self): + a = analyze("UPDATE users SET name = %s FROM (SELECT id, ssn FROM archive) x WHERE users.id = x.id " + "RETURNING x.ssn", PG, P) + assert a.result_columns == (None,) + + def test_trace_stops_after_eight_levels(self): + def nested(levels): + sql = "SELECT ssn FROM users" + for i in range(levels): + sql = f"SELECT t{i}.ssn FROM ({sql}) t{i}" + return sql + + assert analyze(nested(8), PG).result_columns == (ColumnRef("ssn", "users"),) + assert analyze(nested(9), PG).result_columns == (None,) + + @pytest.mark.parametrize("sql, expected", [ + ('SELECT x."S" FROM (SELECT ssn AS "S" FROM users) x', (ColumnRef("ssn", "users"),)), + ('SELECT x.s FROM (SELECT ssn AS "S" FROM users) x', (None,)), + ], ids=["quoted", "unquoted"]) + def test_quoted_alias_matches_as_quoted(self, sql, expected): + assert analyze(sql, PG).result_columns == expected + + @pytest.mark.parametrize("sql", [ + "SELECT x.s FROM (SELECT ssn AS `S` FROM users) x", + "SELECT X.SSN FROM (SELECT ssn FROM users) x", + ], ids=["alias", "qualifier"]) + def test_mysql_traces_names_without_case(self, sql): + assert analyze(sql, MYSQL).result_columns == (ColumnRef("ssn", "users"),) + + def test_union_tables(self): + assert names(analyze("SELECT ssn FROM users UNION ALL SELECT ssn FROM archive", PG).tables) == [ + "users", "archive"] + + def test_for_update_is_not_a_write(self): + assert not analyze("SELECT * FROM users WHERE id = %s FOR UPDATE", PG, P).writes + + +class TestIdentifiers: + def test_postgresql_folds_ascii_letters_only(self): + # As PostgreSQL does in a multibyte (UTF-8) database. + assert PG.fold_identifier("ÄBc", quoted=False) == "Äbc" + assert PG.fold_identifier("ÄBc", quoted=True) == "ÄBc" + assert MYSQL.fold_identifier("ÄBc", quoted=False) == "ÄBc" + assert (PG.metadata_key("Users"), MYSQL.metadata_key("Users")) == ("Users", "users") + + def test_postgresql_folds_unquoted_names(self): + a = analyze('INSERT INTO Users (Name, "SSN") VALUES (%s, %s)', PG, P) + assert assigned(a) == [(0, "users.name"), (1, "users.SSN")] + + def test_postgresql_quoted_table(self): + a = analyze('UPDATE "Users" SET ssn = %s', PG, P) + assert names(a.written_tables) == ["Users"] + + def test_mysql_keeps_case_and_strips_backticks(self): + a = analyze("INSERT INTO `Users` (`Name`, SSN) VALUES (%s, %s)", MYSQL, P) + assert assigned(a) == [(0, "Users.Name"), (1, "Users.SSN")] + + def test_mysql_alias_match_is_case_insensitive(self): + a = analyze("UPDATE users U SET u.ssn = %s WHERE U.id = %s", MYSQL, P) + assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + + def test_quoted_alias(self): + a = analyze('SELECT "U".ssn FROM users "U" WHERE "U".id = %s', PG, P) + assert compared(a) == [(0, "users.id")] + + +class TestAnnotations: + def test_annotation_overrides_inference(self): + a = analyze("INSERT INTO t (a, b) VALUES (/*@encrypt:users.ssn*/ %s, %s)", PG, P) + assert [(u.ordinal, str(u.column)) for u in a.annotations] == [(0, "users.ssn")] + assert a.parameter_columns() == {0: ColumnRef("ssn", "users"), 1: ColumnRef("b", "t")} + + def test_alias_qualifier_is_resolved(self): + a = analyze("UPDATE users u SET note = /*@encrypt:u.ssn*/ %s", PG, P) + assert [str(u.column) for u in a.annotations] == ["users.ssn"] + + def test_annotations_survive_an_unparseable_statement(self): + a = analyze("INSERT INTO t OVERRIDING SYSTEM VALUE VALUES (/*@encrypt:t.ssn*/ %s)", PG, P) + assert a.gap is AnalysisGap.UNPARSEABLE + assert [str(u.column) for u in a.annotations] == ["t.ssn"] + + def test_annotations_survive_an_unsupported_statement(self): + a = analyze("EXPLAIN ANALYZE INSERT INTO t (a) VALUES (/*@encrypt:t.a*/ %s)", PG, P) + assert [str(u.column) for u in a.annotations] == ["t.a"] + + def test_stray_annotations_are_reported(self): + a = analyze("INSERT INTO t (a) VALUES (%s) /*@encrypt:t.a*/", PG, P) + assert a.stray_annotations == ("/*@encrypt:t.a*/",) + + +class TestNotEstablished: + @pytest.mark.parametrize("dialect, sql, params, gap", [ + (PG, "INSERT INTO t (a) VALUES ('%s')", P, AnalysisGap.HIDDEN_PLACEHOLDER), + (MYSQL, "INSERT INTO t (a) VALUES (%s) -- %s", P, AnalysisGap.HIDDEN_PLACEHOLDER), + (PG, "INSERT INTO t (a) VALUES (%s, %(x)s)", P, AnalysisGap.DRIVER_ERROR), + (PG, "INSERT INTO t (a) VALUES (%s) WHERE 1 % 2", P, AnalysisGap.DRIVER_ERROR), + (PG, "INSERT INTO t (a) VALUES ('abc", P, AnalysisGap.UNPARSEABLE), + (PG, "INSERT INTO t (a VALUES (%s)", P, AnalysisGap.UNPARSEABLE), + (PG, "INSERT INTO t (a) OVERRIDING SYSTEM VALUE VALUES (%s)", P, AnalysisGap.UNPARSEABLE), + (PG, "EXPLAIN ANALYZE INSERT INTO t (a) VALUES (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "EXECUTE p (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + (MYSQL, "LOAD DATA INFILE 'x' INTO TABLE t", None, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "SET search_path TO app; INSERT INTO t (a) VALUES (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + ]) + def test_writes_not_established(self, dialect, sql, params, gap): + a = analyze(sql, dialect, params) + assert a.writes and a.gap is gap and not a.complete + assert a.assignments == () and a.unbound_writes == () + + @pytest.mark.parametrize("dialect, sql, tables", [ + (PG, "INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (PG, 'SELECT a AS "x%s" FROM t WHERE b = %s', (TableRef("t"),)), + (PG, "UPDATE app.t SET a = %s /* %s */ WHERE id = %s", (TableRef("t", "app"),)), + (PG, "SELECT t.a FROM t JOIN u ON u.id = t.id WHERE t.b = %s AND t.c = 'x%s'", (TableRef("t"), TableRef("u"))), + (PG, "WITH c AS (SELECT a FROM t) SELECT a FROM c WHERE a = %s -- %s", (TableRef("t"),)), + (PG, "PREPARE p AS INSERT INTO t (a, b) VALUES ($1, 'x%s')", (TableRef("t"),)), + (MYSQL, "INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (MYSQL, "SELECT a AS `x%s` FROM t WHERE b = %s", (TableRef("t"),)), + (MYSQL, "UPDATE app.t SET a = %s WHERE id = %s -- %s", (TableRef("t", "app"),)), + (MYSQL, "INSERT INTO t (a, `b%s`) VALUES (%s, %s)", (TableRef("t"),)), + (MYSQL, "SELECT t.a FROM t JOIN u ON u.id = t.id WHERE t.b = %s # %s", (TableRef("t"), TableRef("u"))), + (MYSQL, "INSERT INTO t (t.a, t.b) VALUES (%s, 'x%s')", (TableRef("t"),)), + # The main path doesn't analyze these statements, but their tables + # must still be listed, or a caller would let them reach a table with + # encrypted columns. + (PG, "SET search_path TO app; INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (PG, "CREATE TABLE u AS SELECT a FROM t WHERE b = %s AND c = 'x%s'", (TableRef("u"), TableRef("t"))), + (MYSQL, "EXPLAIN INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (MYSQL, "DESCRIBE SELECT a FROM t WHERE b = %s AND c = 'x%s'", (TableRef("t"),)), + ], ids=["pg_literal", "pg_identifier_select", "pg_comment", "pg_join", "pg_cte", "pg_prepare", "mysql_literal", + "mysql_identifier_select", "mysql_comment", "mysql_identifier", "mysql_join", "mysql_qualified_columns", + "pg_set_then_insert", "pg_create_table_as", "mysql_explain_insert", "mysql_describe_select"]) + def test_hidden_placeholder_gap_still_lists_the_tables(self, dialect, sql, tables): + # The tables are what lets a caller refuse such a statement when one + # of them has encrypted columns; the placeholders still can't be + # paired with columns, so nothing else is reported. + a = analyze(sql, dialect, P) + assert a.gap is AnalysisGap.HIDDEN_PLACEHOLDER and a.kind is StatementKind.UNKNOWN + assert a.tables == tables + assert a.assignments == () and a.comparisons == () and a.annotations == () and a.result_columns is None + + def test_unparseable_read_is_not_a_write(self): + a = analyze("SELECT FROM WHERE %s", PG, P) + assert a.kind is StatementKind.UNKNOWN and not a.writes + + @pytest.mark.parametrize("sql", ["CREATE TABLE t (a int)", "BEGIN", "CALL p(1)", "", " -- just a comment"]) + def test_statements_that_write_no_column(self, sql): + a = analyze(sql, PG) + assert not a.writes and a.complete + + def test_placeholder_text_in_the_sql_is_a_mismatch(self): + # Something that looks like a normalized placeholder must not be + # taken for one. + a = analyze("INSERT INTO t (a, b) VALUES (%s, :_kms_p0)", PG, P) + assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH + + def test_parser_failure_of_any_kind_is_unparseable(self, monkeypatch): + def boom(*_args, **_kwargs): + raise RecursionError("too deep") + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", boom) + a = sql_analyzer._analysis("INSERT INTO t (a) VALUES (%s)", PG, sql_analyzer.ParamStyle.POSITIONAL) + assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "RecursionError" + + def test_mysql_without_params_leaves_percent_s(self): + # Connector/Python sends %s as written when there are no parameters. + a = analyze("INSERT INTO t (a) VALUES (%s)", MYSQL, ()) + assert a.placeholders == () and a.gap is AnalysisGap.UNPARSEABLE + + +class TestApi: + def test_cached_and_immutable(self): + a = analyze("SELECT * FROM t WHERE a = %s", PG, P) + assert analyze("SELECT * FROM t WHERE a = %s", PG, [2]) is a + with pytest.raises(AttributeError): + a.writes = True # type: ignore[misc] + + def test_cache_is_per_dialect_and_style(self): + sql = "SELECT * FROM t WHERE a = %s" + assert analyze(sql, PG, P) is not analyze(sql, MYSQL, P) + assert analyze(sql, PG, P) is not analyze(sql, PG, None) + + def test_long_sql_is_not_cached(self): + rows = ", ".join(["(%s, %s)"] * 2000) + sql = f"INSERT INTO users (name, ssn) VALUES {rows}" + assert len(sql) > sql_analyzer.CACHEABLE_SQL_LENGTH + a = analyze(sql, MYSQL, P) + assert len(a.assignments) == 4000 and a.assignments[-1].ordinal == 3999 + assert analyze(sql, MYSQL, P) is not a + + def test_short_sql_with_many_placeholders_is_not_cached(self): + # A bulk INSERT under the length limit still holds an object per + # placeholder; caching every row count would grow without need. + sql = "INSERT INTO t (a) VALUES " + ",".join(["(%s)"] * (sql_analyzer.CACHEABLE_PERCENT_SIGNS + 1)) + assert len(sql) <= sql_analyzer.CACHEABLE_SQL_LENGTH + assert analyze(sql, PG, P) is not analyze(sql, PG, P) + + def test_nested_results_are_frozen(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s)", PG, P) + with pytest.raises(dataclasses.FrozenInstanceError): + a.assignments[0].column = ColumnRef("x") # type: ignore[misc] + with pytest.raises(dataclasses.FrozenInstanceError): + a.assignments[0].column.table = "x" # type: ignore[misc] + with pytest.raises(dataclasses.FrozenInstanceError): + a.placeholders[0].key = 5 # type: ignore[misc] + + def test_recursion_error_is_not_cached(self, monkeypatch): + # How deep sqlglot can recurse depends on the caller's stack, so a + # failure for one caller must not be served to the next. + real = sqlglot.parse + calls = [] + + def flaky(sql, read): + calls.append(sql) + if len(calls) == 1: + raise RecursionError("too deep") + return real(sql, read=read) + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", flaky) + sql = "UPDATE users SET ssn = %s" + assert analyze(sql, PG, P).gap is AnalysisGap.UNPARSEABLE + assert analyze(sql, PG, P).gap is None + + def test_deep_nesting_from_a_deep_stack_is_a_gap(self): + sql = "UPDATE users SET ssn = " + "(" * 40 + "%s" + ")" * 40 + result = [] + + def deep(n): + if n: + return deep(n - 1) + result.append(analyze(sql, PG, P)) + + thread = threading.Thread(target=deep, args=(sys.getrecursionlimit() - 200,)) + thread.start() + thread.join() + assert result and result[0].gap is AnalysisGap.UNPARSEABLE + + def test_type_error_for_non_str(self): + with pytest.raises(TypeError): + analyze(b"SELECT 1", PG) # type: ignore[arg-type] + + @pytest.mark.parametrize("dialect, sql, params", [ + (MYSQL, "CALL p(%s)", P), + (PG, "EXPLAIN ANALYZE INSERT INTO t (a) VALUES (%s)", P), + # Parsed, but sqlglot falls back to a command (and would log the + # statement, literal included). + (PG, "COPY users (ssn) FROM STDIN WITH (FORMAT text) WHERE ssn <> '123-45-6789'", None), + (MYSQL, "SELECT JSON_EXTRACT(doc, '$[last]') FROM t WHERE ssn = '123-45-6789'", None), + ]) + def test_the_parser_never_logs_statement_text(self, caplog, dialect, sql, params): + with caplog.at_level(logging.DEBUG, logger="sqlglot"): + analyze(sql, dialect, params) + assert caplog.records == [] + + def test_the_applications_own_sqlglot_logging_is_untouched(self, caplog): + with caplog.at_level(logging.WARNING, logger="sqlglot"): + sqlglot.parse("CALL p(1)", read="mysql") + assert caplog.records + + @pytest.mark.parametrize("dialect, sql, params", [ + (PG, "INSERT INTO t (c, d) VALUES ('100%(card 4111-1111-1111-1111)x', %s)", P), + (PG, "INSERT INTO t (c, d) VALUES ('4111-1111-1111-1111 %d', %s)", P), + (MYSQL, "INSERT INTO t (c) VALUES (%(ssn 123-45-6789)d)", {"a": 1}), + (PG, "INSERT INTO t (secret_col) VALUES ('top secret', %s", P), + ]) + def test_detail_never_quotes_the_sql(self, dialect, sql, params): + a = analyze(sql, dialect, params) + assert a.gap is not None + assert a.detail is not None or a.gap is AnalysisGap.UNPARSEABLE + for secret in ("4111", "123-45", "secret"): + assert secret not in (a.detail or "") + + +class TestReviewRegressions: + """Regression tests for statements the analysis once got wrong: annotation + scopes, MySQL syntax, ORM-rendered SQL and statement kinds.""" + + # ---- annotations resolve in the placeholder's own scope ---- + + @pytest.mark.parametrize("dialect, sql, expected", [ + (MYSQL, "UPDATE accounts u SET x = %s WHERE id = 1; UPDATE users u SET ssn = /*@encrypt:u.ssn*/ %s", + {0: "accounts.x", 1: "users.ssn"}), + (PG, "WITH w AS (UPDATE users u SET ssn = /*@encrypt:u.ssn*/ %s RETURNING u.id) SELECT * FROM w", + {0: "users.ssn"}), + (PG, "WITH w AS (INSERT INTO users AS u (ssn) VALUES (/*@encrypt:u.ssn*/ %s) RETURNING id) SELECT * FROM w", + {0: "users.ssn"}), + (PG, "UPDATE users u SET name = %s WHERE id IN " + "(SELECT uid FROM accounts u WHERE u.secret = /*@encrypt:u.secret*/ %s)", + {0: "users.name", 1: "accounts.secret"}), + (PG, "SELECT 1 FROM accounts u UNION SELECT 1 FROM users u WHERE u.ssn = /*@encrypt:u.ssn*/ %s", + {0: "users.ssn"}), + ]) + def test_annotation_alias_is_resolved_where_the_placeholder_is(self, dialect, sql, expected): + a = analyze(sql, dialect, P) + assert {k: str(v) for k, v in a.parameter_columns().items()} == expected + + def test_bare_annotation_keeps_the_table_the_analysis_found(self): + a = analyze("UPDATE users SET ssn = /*@encrypt:ssn*/ %s", PG, P) + assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} + + def test_bare_annotation_naming_another_column_takes_the_only_table(self): + a = analyze("INSERT INTO users (note) VALUES (/*@encrypt:ssn*/ %s)", PG, P) + assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} + + def test_mysql_annotation_alias_is_case_insensitive(self): + a = analyze("UPDATE users u SET note = /*@encrypt:U.ssn*/ %s", MYSQL, P) + assert [str(u.column) for u in a.annotations] == ["users.ssn"] + + @pytest.mark.parametrize("sql", [ + "INSERT INTO t (a, b) VALUES (/*@encrypt:t.a*/ %s, '%s')", # hidden placeholder + "INSERT INTO t (a, b) VALUES (/*@encrypt:t.a*/ %s, :_kms_p0)", # placeholder mismatch + ]) + def test_annotations_survive_every_gap(self, sql): + a = analyze(sql, PG, P) + assert a.gap is not None + assert [str(u.column) for u in a.annotations] == ["t.a"] + + # ---- MySQL executable comments run on the server ---- + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (/*!80000 ssn, */ name) VALUES (%s /*!80000 , DEFAULT*/)", + "INSERT INTO users (name, ssn) VALUES (%s, %s) /*! ON DUPLICATE KEY UPDATE ssn = 'plain' */", + "UPDATE users SET name = %s /*!, ssn = 'plain' */ WHERE id = %s", + "SELECT 1 /*M! , 2 */", + ]) + def test_executable_comment_is_not_established(self, sql): + a = analyze(sql, MYSQL, P) + assert a.gap is AnalysisGap.EXECUTABLE_COMMENT + assert a.assignments == () + + def test_executable_comment_write_keyword_counts(self): + assert analyze("SELECT 1 /*! ; INSERT INTO t (a) VALUES (1) */", MYSQL).writes + + def test_optimizer_hint_is_an_ordinary_comment(self): + a = analyze("UPDATE /*+ NO_INDEX_MERGE(users) */ users SET ssn = %s", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + # ---- MySQL charset introducers (Django renders binary values as _binary %s) ---- + + def test_binary_introducer_in_insert(self): + a = analyze("INSERT INTO `Person` (`name`, `ssn`, `note`) VALUES (%s, _binary %s, %s), (%s, _binary %s, %s)", + MYSQL, P) + assert a.complete and unbound(a) == [] + assert assigned(a) == [(0, "Person.name"), (1, "Person.ssn"), (2, "Person.note"), + (3, "Person.name"), (4, "Person.ssn"), (5, "Person.note")] + assert [p.introducer for p in a.placeholders] == [None, "_binary", None] * 2 + + def test_binary_introducer_in_update_and_upsert(self): + a = analyze("UPDATE `Person` SET `ssn` = _binary %s, `name` = %s WHERE `Person`.`id` = %s", MYSQL, P) + assert a.complete and assigned(a) == [(0, "Person.ssn"), (1, "Person.name")] + a = analyze("INSERT INTO `Person` (`ssn`) VALUES (_binary %s) AS new ON DUPLICATE KEY UPDATE `ssn` = new.`ssn`", + MYSQL, P) + assert a.complete and unbound(a) == [] + + def test_introducer_needs_a_known_charset(self): + # "_x %s" is not an introducer, so the statement reads as written. + a = analyze("SELECT _x %s", MYSQL, P) + assert [p.introducer for p in a.placeholders] == [None] + + def test_introducer_only_on_mysql(self): + assert analyze("SELECT _binary %s", PG, P).placeholders[0].introducer is None + + # ---- MySQL row alias with a column list renames by position ---- + + def test_row_alias_columns_copy_by_position(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new(n, s) ON DUPLICATE KEY UPDATE ssn = new.s", + MYSQL, P) + assert unbound(a) == [] + + def test_row_alias_column_naming_another_insert_column_is_unbound(self): + # new.ssn is the incoming *name*: alias columns rename by position. + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new(ssn, name) " + "ON DUPLICATE KEY UPDATE ssn = new.ssn", MYSQL, P) + assert unbound(a) == ["users.ssn"] + + # ---- copies from another table ---- + + @pytest.mark.parametrize("dialect, sql", [ + (MYSQL, "UPDATE users u JOIN orders o ON o.uid = u.id SET u.ssn = o.ssn"), + (PG, "UPDATE users SET ssn = o.ssn FROM other o WHERE o.id = users.id"), + ]) + def test_copy_of_another_tables_column_of_the_same_name_is_unbound(self, dialect, sql): + assert unbound(analyze(sql, dialect)) == ["users.ssn"] + + # ---- SQLAlchemy's multi-row ORM insert on PostgreSQL ---- + + def test_insert_select_from_values_list(self): + sql = ("INSERT INTO users (name, ssn) SELECT p0::VARCHAR, p1::BYTEA FROM " + "(VALUES (%(name__0)s::VARCHAR, %(ssn__0)s, 0), (%(name__1)s::VARCHAR, %(ssn__1)s, 1)) " + "AS imp_sen(p0, p1, sen_counter) ORDER BY sen_counter RETURNING users.id, users.id AS id__1") + a = analyze(sql, PG, N) + assert a.complete + assert [(u.placeholder.key, str(u.column)) for u in a.assignments] == [ + ("name__0", "users.name"), ("ssn__0", "users.ssn"), ("name__1", "users.name"), ("ssn__1", "users.ssn")] + assert a.assignments[1].casts == ("VARBINARY",) + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (ssn) SELECT v.p0 FROM (VALUES (%s)) AS v(p0) WHERE v.p0 IS NOT NULL", + "INSERT INTO users (ssn) SELECT upper(p0) FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (ssn) SELECT p0 FROM (VALUES (%s)) AS v(p0) JOIN x ON true", + "INSERT INTO users (ssn) SELECT q FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (name, ssn) SELECT %s, %s", + ]) + def test_other_insert_selects_are_values_from_query(self, sql): + assert analyze(sql, PG, P).gap is AnalysisGap.VALUES_FROM_QUERY + + # ---- statements that run a stored statement ---- + + def test_execute_may_write(self): + a = analyze("EXECUTE ins_user(%s, %s)", PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + + def test_prepare_body_is_read(self): + a = analyze("PREPARE ins (text, text) AS INSERT INTO users (name, ssn) VALUES ($1, '123-45-6789')", PG) + assert a.kind is StatementKind.INSERT and a.writes + assert a.gap is AnalysisGap.PREPARED_PARAMETERS + # The literal is reported as an unbound write; $1 is bound by a later + # EXECUTE. + assert unbound(a) == ["users.ssn"] + + def test_prepare_of_a_read(self): + a = analyze('PREPARE "q" AS SELECT ssn FROM users WHERE id = $1', PG) + assert a.kind is StatementKind.SELECT and not a.writes and a.complete + + # ---- DELETE ... USING ---- + + def test_delete_using_aliases_are_in_scope(self): + a = analyze("DELETE FROM users USING accounts a WHERE a.uid = users.id AND a.secret = %s RETURNING a.secret", + PG, P) + assert compared(a) == [(0, "accounts.secret")] + assert a.result_columns == (ColumnRef("secret", "accounts"),) + + # ---- ALL / SOME ---- + + @pytest.mark.parametrize("sql", ["SELECT * FROM t WHERE c <> ALL(%s)", "SELECT * FROM t WHERE c = SOME(%s)", + "SELECT * FROM t WHERE c = ANY(%s::text[])"]) + def test_all_some_and_any_are_array_comparisons(self, sql): + a = analyze(sql, PG, P) + assert [(u.ordinal, str(u.column), u.array) for u in a.comparisons] == [(0, "t.c", True)] + + # ---- MySQL qualified INSERT column lists ---- + + @pytest.mark.parametrize("sql, expected", [ + ("INSERT INTO users (users.name, users.ssn) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn")]), + ("INSERT INTO mydb.users (mydb.users.ssn) VALUES (%s)", [(0, "users.ssn")]), + ("INSERT INTO `users` (`users`.`ssn`) VALUES (%s)", [(0, "users.ssn")]), + ]) + def test_mysql_qualified_insert_columns(self, sql, expected): + a = analyze(sql, MYSQL, P) + assert a.complete and assigned(a) == expected + + # ---- names that are not plain identifiers ---- + + def test_subscripted_column_is_not_a_column_name(self): + a = analyze("MERGE INTO t USING s ON 1=1 WHEN NOT MATCHED THEN INSERT (ssn[1]) VALUES (%s)", PG, P) + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + assert assigned(a) == [] + + # ---- keyword fallback ---- + + @pytest.mark.parametrize("sql", [ + "SET search_path TO app; WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", + "SET search_path TO app; COPY users (ssn) FROM STDIN", + ]) + def test_unparsed_statement_before_a_write_is_not_complete(self, sql): + a = analyze(sql, PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + + # ---- parse-trust guards ---- + + def test_placeholder_missing_from_the_parse_is_a_mismatch(self, monkeypatch): + real = sqlglot.parse + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", + lambda _sql, read: real("INSERT INTO users (name, ssn) VALUES (:_kms_p0, 'x')", read=read)) + a = sql_analyzer._analysis("INSERT INTO users (name, ssn) VALUES (%s, %s)", PG, ParamStyle.POSITIONAL) + assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH and a.assignments == () + + def test_command_fallback_is_unparseable(self, monkeypatch): + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", lambda _sql, read: [exp.Command(this="INSERT")]) + a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES ('x')", PG, ParamStyle.NONE) + assert a.writes and a.gap is AnalysisGap.UNPARSEABLE + + def test_unterminated_is_unparseable_even_if_the_parser_accepts_it(self, monkeypatch): + real = sqlglot.parse + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", + lambda _sql, read: real("INSERT INTO users (ssn) VALUES (:_kms_p0)", read=read)) + a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES (%s) /* a /* b */", PG, ParamStyle.POSITIONAL) + assert a.writes and a.gap is AnalysisGap.UNPARSEABLE and a.assignments == () + + # ---- row lengths ---- + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (a) VALUES (%s, %s)", + "MERGE INTO users u USING src s ON u.id = s.id WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (%s)", + "MERGE INTO users u USING src s ON u.id = s.id WHEN NOT MATCHED THEN INSERT (id) VALUES (%s, %s)", + ]) + def test_row_length_mismatch_both_ways(self, sql): + assert analyze(sql, PG, P).gap is AnalysisGap.ROW_LENGTH_MISMATCH + + def test_several_selects_have_no_result_columns(self): + assert analyze("SELECT ssn FROM users; SELECT name FROM accounts", PG).result_columns is None + + # ---- performance ---- + + def test_long_boolean_chain_is_linear(self): + sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 3000) + a = analyze(sql, PG, P) + assert len(a.comparisons) == 6000 and a.comparisons[-1].column == ColumnRef("ssn", "users") + + +class TestReviewRegressionsRound2: + """Regression tests: annotations across tables, SQLAlchemy's multi-row + insert, regex cost, caching and the logging filter.""" + + # ---- annotations ---- + + @pytest.mark.parametrize("sql, expected", [ + ("UPDATE users u SET name = %s WHERE id IN (SELECT uid FROM accounts a WHERE a.x = /*@encrypt:u.ssn*/ %s)", + {0: "users.name", 1: "users.ssn"}), + ("SELECT * FROM users u WHERE EXISTS " + "(SELECT 1 FROM accounts a WHERE a.uid = u.id AND a.x = /*@encrypt:u.ssn*/ %s)", + {0: "users.ssn"}), + ]) + def test_annotation_qualifier_resolves_through_outer_queries(self, sql, expected): + assert {k: str(v) for k, v in analyze(sql, PG, P).parameter_columns().items()} == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "UPDATE users SET ssn = /*@encrypt:ssn*/ %s FROM accounts a WHERE a.id = users.id", + ColumnRef("ssn", "users")), + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id SET u.SSN = /*@encrypt:ssn*/ %s", + ColumnRef("ssn", "users")), + # A column other than the one assigned: the single written table. + (PG, "UPDATE users SET note = /*@encrypt:ssn*/ %s FROM accounts a WHERE a.id = users.id", + ColumnRef("ssn", "users")), + # Several written tables and another column: the table can't be told. + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id SET u.note = /*@encrypt:ssn*/ %s, a.x = 1", + ColumnRef("ssn")), + ]) + def test_bare_annotation_with_several_tables(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns() == {0: expected} + + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "INSERT INTO orders (user_id, payment_info) SELECT id, /*@encrypt:payment_info*/ %s FROM temp", + ColumnRef("payment_info", "orders")), + (MYSQL, "INSERT INTO orders (payment_info) SELECT /*@encrypt:payment_info*/ %s FROM DUAL", + ColumnRef("payment_info", "orders")), + (PG, "INSERT INTO users (name, ssn) SELECT name, /*@encrypt:ssn*/ %s FROM accounts", ColumnRef("ssn", "users")), + (PG, "UPDATE users SET ssn = (SELECT /*@encrypt:ssn*/ %s FROM accounts)", ColumnRef("ssn", "users")), + ]) + def test_bare_annotation_in_a_query_feeding_a_write_names_the_written_table(self, dialect, sql, expected): + # The value goes to the write's target, even though the subquery reads another table. + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + # ---- SQLAlchemy's multi-row insert ---- + + def test_insert_select_from_values_maps_select_items_by_name(self): + a = analyze("INSERT INTO users (name, ssn) SELECT p1, p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", PG, P) + assert a.complete + assert assigned(a) == [(0, "users.ssn"), (1, "users.name")] + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (ssn, note) SELECT p0, p0 FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (name, ssn) SELECT v.p0, p0::text FROM (VALUES (%s, %s)) AS v(p0, p1)", + ]) + def test_insert_select_from_values_using_a_column_twice_is_not_read(self, sql): + # One value would fill two columns, and could be encrypted for only one. + a = analyze(sql, PG, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY and a.assignments == () + + @pytest.mark.parametrize("sql, gap", [ + ("INSERT INTO users (name, ssn) SELECT p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", AnalysisGap.VALUES_FROM_QUERY), + ("INSERT INTO users (name, ssn) SELECT p0, p1 FROM (VALUES (%s, %s), (%s)) AS v(p0, p1)", + AnalysisGap.ROW_LENGTH_MISMATCH), + ("INSERT INTO users (ssn) SELECT p0 FROM (VALUES (%s)) AS v(p0) FETCH FIRST 1 ROWS ONLY", + AnalysisGap.VALUES_FROM_QUERY), + ]) + def test_insert_select_from_values_widths_and_extras(self, sql, gap): + assert analyze(sql, PG, P).gap is gap + + # ---- regex cost on indented SQL ---- + + @pytest.mark.timeout(10) + @pytest.mark.parametrize("dialect, sql", [ + (MYSQL, "\n" + " " * 60 + "\n" + " " * 60 + "UPDATE users SET ssn = %s WHERE id = %s AND (name = 'x'"), + (MYSQL, " " * 60 + "SELECT a FROM t WHERE b = %s INTO OUTFILE '/tmp/x'"), + (MYSQL, " " * 60 + "INSERT INTO users (users.ssn) VALUE (%s"), + (PG, "\n" + " " * 60 + "PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ($1)"), + (PG, "/* a */" * 60 + " PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ($1)"), + ]) + def test_leading_whitespace_and_comments_do_not_backtrack(self, dialect, sql): + assert analyze(sql, dialect, P).gap is not None + + def test_indented_prepare_and_qualified_insert_are_still_read(self): + a = analyze("\n PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ('x')", PG) + assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] + a = analyze("\n INSERT INTO users (users.ssn) VALUES (%s)", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + # ---- MySQL qualified INSERT columns with dotted back-quoted names ---- + + @pytest.mark.parametrize("sql, expected", [ + ("INSERT INTO users (users.name, `x.ssn`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.x.ssn")]), + ("INSERT INTO users (users.name, `ssn.v2`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn.v2")]), + ("INSERT INTO users (`users`.`ssn`, name) VALUES (%s, %s)", [(0, "users.ssn"), (1, "users.name")]), + ]) + def test_back_quoted_name_with_a_dot_is_one_name(self, sql, expected): + a = analyze(sql, MYSQL, P) + assert a.complete and assigned(a) == expected + + def test_qualifier_retry_only_for_inserts(self, monkeypatch): + calls = [] + real = sql_analyzer._without_insert_column_qualifiers + monkeypatch.setattr(sql_analyzer, "_without_insert_column_qualifiers", + lambda text: calls.append(text) or real(text)) + analyze("UPDATE users SET ssn = %s WHERE (", MYSQL, P) + assert calls == [] + + # ---- keyword fallback ---- + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "SET search_path TO app; PREPARE p AS INSERT INTO users (ssn) VALUES ('123-45-6789')"), + (PG, "EXPLAIN ANALYZE EXECUTE p(%s)"), + (MYSQL, "SELECT 1 /*!LOAD DATA INFILE 'x' INTO TABLE users */"), + ]) + def test_more_statements_that_may_write(self, dialect, sql): + a = analyze(sql, dialect, P) + assert a.writes and a.gap is not None + + # ---- names that are not plain identifiers ---- + + def test_subscripted_update_target_is_unsupported(self): + a = analyze("UPDATE users SET ssn[1] = %s", PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT and a.assignments == () + + # ---- TABLE is not parsed (sqlglot reads it as an alias) ---- + + def test_table_statement_is_not_parsed(self): + a = analyze("TABLE users", PG) + assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () + + # ---- scopes ---- + + def test_nearest_query_memo_does_not_cross_queries(self): + a = analyze("SELECT * FROM users u WHERE EXISTS " + "(SELECT 1 FROM accounts WHERE u.name = %s GROUP BY secret HAVING secret = %s)", PG, P) + assert compared(a) == [(0, "users.name"), (1, "accounts.secret")] + + @pytest.mark.timeout(10) + def test_long_boolean_chain_is_time_bounded(self): + sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 12000) + assert len(analyze(sql, PG, P).comparisons) == 24000 + + # ---- caching ---- + + def test_long_sql_with_few_placeholders_is_not_cached(self): + sql = "UPDATE users SET ssn = %s WHERE note = '" + "x" * sql_analyzer.CACHEABLE_SQL_LENGTH + "'" + assert sql.count("%") <= sql_analyzer.CACHEABLE_PERCENT_SIGNS + assert analyze(sql, PG, P) is not analyze(sql, PG, P) + + def test_recursion_error_wrapped_by_the_tokenizer_is_not_cached(self, monkeypatch): + real = sqlglot.parse + calls = [] + + def flaky(sql, read): + calls.append(sql) + if len(calls) == 1: + try: + raise RecursionError("too deep") + except RecursionError as e: + raise sqlglot.errors.TokenError("wrapped") from e + return real(sql, read=read) + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", flaky) + sql = "SELECT a FROM users WHERE ssn = %s" + first = analyze(sql, PG, P) + assert first.gap is AnalysisGap.UNPARSEABLE and first.detail == "RecursionError" + assert analyze(sql, PG, P).gap is None + + # ---- the logging filter is per thread ---- + + def test_quiet_filter_does_not_silence_other_threads(self, caplog): + entered, release = threading.Event(), threading.Event() + + def parse_elsewhere(): + with sql_analyzer._QUIET.active(): + entered.set() + release.wait(5) + + thread = threading.Thread(target=parse_elsewhere) + thread.start() + try: + assert entered.wait(5) + with caplog.at_level(logging.WARNING, logger="sqlglot"): + logging.getLogger("sqlglot").warning("application record") + assert [r.getMessage() for r in caplog.records] == ["application record"] + finally: + release.set() + thread.join() + + +class TestReviewRegressionsRound3: + """Regression tests: regexes that fail after a long gap, and which table a + bare annotation gets.""" + + # ---- regexes that fail after a long run of whitespace or comments ---- + + _BAD_PREPARE = "PREPARE p (int AS INSERT INTO users (ssn) VALUES ($1)" # unbalanced header + _PARTITION = "INSERT INTO users PARTITION (p0) (users.ssn) VALUES (%s)" # valid MySQL neither read can parse + + @pytest.mark.timeout(10) + @pytest.mark.parametrize("dialect, sql, gap", [ + (PG, " " * 60 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "/* a */ " * 60 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- " + "-" * 60 + "\n" + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- " * 60 + "\n" + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- header line\r\n" * 40 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "PREPARE p" + "-- c\r\n" * 40 + "INSERT INTO users (ssn) VALUES ($1)", AnalysisGap.UNSUPPORTED_STATEMENT), + (MYSQL, " " * 60 + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "/* a */ " * 60 + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- " + "-" * 60 + "\n" + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- " + " -- ".join("abcdefghijklmnopqrstuvwxyz") + "\n" + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- c \n" * 40 + "INSERT INTO users SET ssn = %s, note = 'a' 'b' garbage(", AnalysisGap.UNPARSEABLE), + ], ids=["pg-spaces", "pg-comments", "pg-dash-banner", "pg-dashes", "pg-crlf", "pg-crlf-header", "my-spaces", + "my-comments", "my-dash-banner", "my-dashed-prose", "my-trailing-space"]) + def test_a_regex_that_fails_after_a_long_gap_fails_fast(self, dialect, sql, gap): + assert analyze(sql, dialect, P).gap is gap + + def test_line_comments_in_a_prepare_header(self): + a = analyze("-- c\r\n PREPARE -- x\r\n p (int) -- y \r\n AS INSERT INTO users (ssn) VALUES ('x')", PG) + assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] + + # ---- bare annotations: written vs compared values ---- + + @pytest.mark.parametrize("dialect, sql, ordinal, expected", [ + # A filter value gets the table it is compared in, even in a statement that writes. + (PG, "UPDATE users SET note = %s WHERE id IN " + "(SELECT user_id FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s)", 1, ColumnRef("pan", "cards")), + (PG, "INSERT INTO audit (note) SELECT note FROM users WHERE coalesce(ssn, '') = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "users")), + (PG, "WITH c AS (SELECT user_id FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s) " + "UPDATE users SET flag = true WHERE id IN (SELECT user_id FROM c)", 0, ColumnRef("pan", "cards")), + # Another statement's write doesn't count. + (MYSQL, "UPDATE a SET x = %s; SELECT * FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s", + 1, ColumnRef("pan", "cards")), + (MYSQL, "SELECT * FROM users u WHERE u.tax = /*@encrypt:ssn*/ %s; UPDATE audit SET n = n + 1", + 0, ColumnRef("ssn", "users")), + (PG, "INSERT INTO logs (msg) VALUES (%s); SELECT id FROM users WHERE ssn || '' = /*@encrypt:ssn*/ %s", + 1, ColumnRef("ssn", "users")), + # Values that flow into the write: the written table. + (PG, "INSERT INTO users (ssn) SELECT /*@encrypt:ssn*/ %s FROM temp", 0, ColumnRef("ssn", "users")), + (PG, "UPDATE users SET note = (SELECT /*@encrypt:ssn*/ %s FROM temp LIMIT 1)", 0, ColumnRef("ssn", "users")), + # Values bound in a source of the write may feed it or only be compared + # with another table's column: the table can't be told. + (PG, "MERGE INTO users t USING (SELECT /*@encrypt:ssn*/ %s AS v) s ON t.id = 1 " + "WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (1, s.v)", 0, ColumnRef("ssn")), + (PG, "WITH s AS (SELECT /*@encrypt:ssn*/ %s AS v) INSERT INTO users (ssn) SELECT v FROM s", + 0, ColumnRef("ssn")), + # Several written tables: the table can't be told. + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id " + "SET u.note = (SELECT /*@encrypt:ssn*/ %s FROM temp), a.x = 1", 0, ColumnRef("ssn")), + ]) + def test_bare_annotation_by_where_the_value_goes(self, dialect, sql, ordinal, expected): + assert analyze(sql, dialect, P).parameter_columns()[ordinal] == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + # A value compared or tested inside a written expression is not written. + (PG, "INSERT INTO audit (note) SELECT CASE WHEN lower(ssn) = /*@encrypt:ssn*/ %s THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) = /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (note) SELECT IF(lower(ssn) = /*@encrypt:ssn*/ %s, 'm', 'n') FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (note) SELECT CASE lower(ssn) WHEN /*@encrypt:ssn*/ %s THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + (PG, "UPDATE users SET flag = (SELECT lower(pan) = /*@encrypt:pan*/ %s FROM cards LIMIT 1)", + ColumnRef("pan", "cards")), + (PG, "UPDATE users SET note = CASE WHEN lower(a.tax) = /*@encrypt:tax*/ %s THEN 'x' END " + "FROM accounts a WHERE a.uid = users.id", ColumnRef("tax")), + # The THEN value is written. + (PG, "UPDATE users SET note = CASE WHEN flag THEN /*@encrypt:ssn*/ %s END", ColumnRef("ssn", "users")), + # A parameter CTE or derived table compared with another table's column. + (PG, "WITH params AS (SELECT /*@encrypt:ssn*/ %s::text AS ssn) UPDATE orders o SET status = 'flagged' " + "FROM customers c, params p WHERE o.customer_id = c.id AND c.ssn = p.ssn", ColumnRef("ssn")), + (PG, "WITH params AS (SELECT /*@encrypt:ssn*/ %s AS ssn) INSERT INTO audit (customer_id) " + "SELECT c.id FROM customers c JOIN params p ON c.ssn = p.ssn", ColumnRef("ssn")), + (MYSQL, "INSERT INTO audit (customer_id) WITH params AS (SELECT /*@encrypt:ssn*/ %s AS ssn) " + "SELECT c.id FROM customers c JOIN params p ON c.ssn = p.ssn", ColumnRef("ssn")), + # A value fed to the write through a source: bare as well. + (PG, "INSERT INTO t (a) SELECT j.v FROM src JOIN (SELECT /*@encrypt:ssn*/ %s AS v) j ON true", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT s.v FROM (SELECT /*@encrypt:ssn*/ %s AS v) s", ColumnRef("ssn")), + ], ids=["case-when", "boolean-item", "mysql-if", "simple-case", "set-subquery-item", "set-case-two-sources", + "case-then", "param-cte-update", "param-cte-insert", "mysql-param-cte", "join-source", "from-source"]) + def test_bare_annotation_on_a_compared_or_source_value(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + # THEN, ELSE and IF() results in an INSERT ... SELECT reading another table are written. + (PG, "INSERT INTO audit (note) SELECT CASE WHEN flag THEN /*@encrypt:ssn*/ %s END FROM users", + ColumnRef("ssn", "audit")), + (PG, "INSERT INTO audit (note) SELECT CASE WHEN flag THEN 'a' ELSE /*@encrypt:ssn*/ %s END FROM users", + ColumnRef("ssn", "audit")), + (MYSQL, "INSERT INTO audit (note) SELECT IF(flag, /*@encrypt:ssn*/ %s, 'n') FROM users", + ColumnRef("ssn", "audit")), + # Tests other than the plain comparisons. + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) IN (/*@encrypt:ssn*/ %s) FROM users", ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) BETWEEN /*@encrypt:ssn*/ %s AND 'z' FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT ssn ~ /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT doc @> /*@encrypt:ssn*/ %s::jsonb FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (flag) SELECT ssn REGEXP /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (flag) SELECT MATCH (ssn) AGAINST (/*@encrypt:ssn*/ %s) FROM users", + ColumnRef("ssn", "users")), + # The operand of a simple CASE. + (PG, "INSERT INTO audit (note) SELECT CASE /*@encrypt:ssn*/ %s WHEN lower(ssn) THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + # A window's PARTITION BY is not written. + (PG, "INSERT INTO audit (n) SELECT row_number() OVER (PARTITION BY /*@encrypt:ssn*/ %s) FROM users", + ColumnRef("ssn", "users")), + # Sources that read a table: bare, not that table. + (PG, "INSERT INTO t (a) SELECT j.v FROM src JOIN (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) j ON true", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT s.v FROM (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) s", ColumnRef("ssn")), + (PG, "WITH s AS (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) INSERT INTO users (note) SELECT v FROM s", + ColumnRef("ssn")), + (PG, "MERGE INTO users t USING (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) s ON t.id = 1 " + "WHEN NOT MATCHED THEN INSERT (id, note) VALUES (1, s.v)", ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT l.v FROM src CROSS JOIN LATERAL (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) l", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT l.v FROM src, LATERAL (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) l", + ColumnRef("ssn")), + # A SET value in an UPDATE that also reads another table: the assignment is not a test. + (PG, "UPDATE users SET note = /*@encrypt:ssn*/ %s FROM cards c WHERE c.uid = users.id", + ColumnRef("ssn", "users")), + ], ids=["then", "else", "mysql-if-true", "in", "between", "regex", "jsonb-contains", "mysql-regexp", + "mysql-match", "simple-case-operand", "partition-by", "join-source-reads", "from-source-reads", + "cte-reads", "merge-using-reads", "cross-join-lateral-reads", "comma-lateral-reads", "set-with-from"]) + def test_bare_annotation_written_tested_or_from_a_source(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + # A value tested by any of these operators resolves to the table it is tested against on + # every supported sqlglot, though the operators are Predicates only from 30.16. + @pytest.mark.parametrize("op", ["~*", "!~*", "<@", "&&", "?", "?|", "?&", "-|-", "&<", "&>"]) + def test_bare_annotation_tested_by_an_operator(self, op): + sql = f"UPDATE audit SET flag = (SELECT ssn {op} /*@encrypt:ssn*/ %s FROM users LIMIT 1)" + assert analyze(sql, PG, P).parameter_columns()[0] == ColumnRef("ssn", "users") + + def test_bare_annotation_tested_by_overlaps(self): + sql = "UPDATE audit SET flag = (SELECT (d1, ssn) OVERLAPS (d2, /*@encrypt:ssn*/ %s) FROM users LIMIT 1)" + assert analyze(sql, PG, P).parameter_columns()[0] == ColumnRef("ssn", "users") + + # A condition with no test operator around the value (a function sqlglot + # does not model as one): only the slot keeps the value out of the write. + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "INSERT INTO audit (uid) SELECT id FROM users WHERE starts_with(ssn, /*@encrypt:ssn*/ %s)", + ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (uid) SELECT id FROM users WHERE LOCATE(/*@encrypt:ssn*/ %s, ssn)", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (n) SELECT count(*) FROM users GROUP BY note " + "HAVING bool_or(starts_with(ssn, /*@encrypt:ssn*/ %s))", ColumnRef("ssn", "users")), + (PG, "UPDATE users SET flag = true FROM cards c " + "WHERE c.uid = users.id AND starts_with(c.pan, /*@encrypt:pan*/ %s)", ColumnRef("pan")), + (PG, "MERGE INTO users t USING cards c ON t.id = c.uid AND starts_with(c.pan, /*@encrypt:pan*/ %s) " + "WHEN MATCHED THEN UPDATE SET flag = true", ColumnRef("pan")), + (PG, "MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED AND starts_with(c.pan, /*@encrypt:pan*/ %s) THEN UPDATE SET flag = true", ColumnRef("pan")), + ], ids=["where", "mysql-where", "having", "update-from-where", "merge-on", "merge-when-condition"]) + def test_bare_annotation_in_a_condition_slot(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + @pytest.mark.parametrize("sql, ordinal, expected", [ + ("INSERT INTO audit (n) SELECT count(*) FROM users GROUP BY note HAVING max(lower(ssn)) = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "users")), + ("MERGE INTO users t USING cards c ON t.id = c.uid AND lower(c.pan) = /*@encrypt:pan*/ %s " + "WHEN MATCHED THEN UPDATE SET flag = true", 0, ColumnRef("pan")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED AND lower(c.pan) = /*@encrypt:pan*/ %s THEN UPDATE SET flag = true", 0, ColumnRef("pan")), + ("UPDATE users SET flag = true FROM cards c WHERE c.uid = users.id AND lower(c.pan) = /*@encrypt:pan*/ %s", + 0, ColumnRef("pan")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN NOT MATCHED THEN INSERT (id, note) VALUES (c.uid, /*@encrypt:ssn*/ %s)", 0, ColumnRef("ssn", "users")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED THEN UPDATE SET note = /*@encrypt:ssn*/ %s", 0, ColumnRef("ssn", "users")), + ("INSERT INTO logs (msg) VALUES (%s); UPDATE users SET note = /*@encrypt:ssn*/ %s", 1, ColumnRef("ssn", "users")), + ("INSERT INTO t (a) VALUES (1) ON CONFLICT (a) DO UPDATE SET note = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "t")), + ], ids=["having", "merge-on", "merge-when-condition", "update-from-where", "merge-when-insert", "merge-when-update", + "two-writes", "on-conflict-set"]) + def test_bare_annotation_slots(self, sql, ordinal, expected): + assert analyze(sql, PG, P).parameter_columns()[ordinal] == expected + + # ---- one-dialect gaps ---- + + def test_replace_with_qualified_columns_is_read(self): + a = analyze("REPLACE INTO users (users.ssn) VALUES (%s)", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + @BOTH + def test_table_statement_is_not_parsed_on_either_dialect(self, dialect): + a = analyze("TABLE users", dialect) + assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () + + # ---- a cyclic exception chain ends ---- + + @pytest.mark.timeout(10) + def test_cyclic_exception_chain_does_not_hang(self, monkeypatch): + def cyclic(sql, read): + error = sqlglot.errors.ParseError("x") + error.__cause__ = error + raise error + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", cyclic) + a = sql_analyzer._analysis("SELECT 1", PG, ParamStyle.NONE) + assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "ParseError" diff --git a/tests/unit/test_sql_tokenizer.py b/tests/unit/test_sql_tokenizer.py new file mode 100644 index 000000000..032217c2c --- /dev/null +++ b/tests/unit/test_sql_tokenizer.py @@ -0,0 +1,415 @@ +# 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. + +import re +from types import MappingProxyType + +import pytest + +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.encryption.sql_tokenizer import ( + ColumnRef, ParamStyle, normalized_ordinal, tokenize) + +POS, NAMED, NONE = ParamStyle.POSITIONAL, ParamStyle.NAMED, ParamStyle.NONE + + +def keys(tokens): + return [p.key for p in tokens.placeholders] + + +def hidden(tokens): + return [p.hidden for p in tokens.placeholders] + + +class TestParamStyle: + @pytest.mark.parametrize("params, expected", [ + (None, NONE), ((), POS), ([], POS), ((1,), POS), ([1], POS), + ({}, NAMED), ({"a": 1}, NAMED), (MappingProxyType({"a": 1}), NAMED), + ]) + def test_psycopg(self, params, expected): + # psycopg splits the query whenever params is not None, even if empty. + assert ParamStyle.of(params, PG) is expected + + @pytest.mark.parametrize("params, expected", [ + (None, NONE), ((), NONE), ([], NONE), ({}, NONE), ((1,), POS), ([1], POS), ({"a": 1}, NAMED), + # Connector/Python only accepts a dict, list or tuple. + (MappingProxyType({"a": 1}), NONE), ("abc", NONE), + ]) + def test_mysql_connector(self, params, expected): + # Connector/Python substitutes only for a non-empty dict, list or tuple. + assert ParamStyle.of(params, MYSQL) is expected + + +class TestPsycopgPlaceholders: + def test_positional_in_order(self): + t = tokenize("INSERT INTO t (a, b) VALUES (%s, %s)", PG, POS) + assert keys(t) == [0, 1] + assert [p.ordinal for p in t.placeholders] == [0, 1] + + def test_binary_and_text_formats_are_placeholders(self): + assert keys(tokenize("VALUES (%s, %b, %t)", PG, POS)) == [0, 1, 2] + + def test_named_may_repeat(self): + t = tokenize("UPDATE t SET a = %(v)s, b = %(v)s WHERE id = %(id)b", PG, NAMED) + assert keys(t) == ["v", "v", "id"] + assert [p.ordinal for p in t.placeholders] == [0, 1, 2] + + def test_double_percent_is_a_percent_sign(self): + t = tokenize("SELECT 7 %% 2, a FROM t WHERE b LIKE 'x%%' AND c = %s", PG, POS) + assert keys(t) == [0] + assert "7 % 2" in t.normalized and "'x%'" in t.normalized + + def test_placeholders_inside_literals_and_comments_are_still_bound(self): + # psycopg does not skip quotes or comments, so neither may we: the + # second %s is the second parameter even though it's in a string. + sql = "SELECT %s, '%s', \"%s\", $$%s$$, $tag$%s$tag$, E'\\'%s', /* %s */ -- %s\n %s" + t = tokenize(sql, PG, POS) + assert keys(t) == list(range(9)) + assert hidden(t) == [False, True, True, True, True, True, True, True, False] + assert t.has_hidden_placeholders + + def test_nested_block_comments(self): + t = tokenize("/* a /* b */ %s */ SELECT %s", PG, POS) + assert hidden(t) == [True, False] + + @pytest.mark.timeout(10) + def test_deeply_nested_comments_stay_linear(self): + depth = 100_000 + t = tokenize("SELECT /*" + " /*" * depth + " */" * (depth + 1) + " %s", PG, POS) + assert hidden(t) == [False] + + def test_dollar_number_is_not_a_dollar_quote(self): + t = tokenize("SELECT $1, %s", PG, POS) + assert hidden(t) == [False] + + def test_identifier_with_dollar_is_not_a_dollar_quote(self): + t = tokenize("SELECT a$b$, %s", PG, POS) + assert hidden(t) == [False] + + def test_standard_strings_do_not_escape_backslash(self): + # standard_conforming_strings=on: 'a\' is a whole literal. + t = tokenize("SELECT 'a\\', %s", PG, POS) + assert hidden(t) == [False] + + def test_escape_strings_do(self): + t = tokenize("SELECT E'a\\', %s'", PG, POS) + assert hidden(t) == [True] + + def test_doubled_quotes(self): + t = tokenize("SELECT 'it''s', \"a\"\"b\", %s", PG, POS) + assert hidden(t) == [False] + + @pytest.mark.parametrize("sql, rejected", [ + ("SELECT 1 % 2", True), ("SELECT '100%'", True), ("SELECT %d", True), ("SELECT %()s", True), + # A lone % at the very end is not matched by psycopg's pattern either. + ("SELECT %", False), + ]) + def test_driver_rejects_other_percent_sequences(self, sql, rejected): + assert (tokenize(sql, PG, POS).driver_error is not None) is rejected + + @pytest.mark.parametrize("sql, style", [ + ("SELECT '%(card 4111-1111-1111-1111)x', %s", POS), + ("SELECT '4111-1111-1111-1111 %d'", POS), + ("VALUES (%s, %(4111-1111)s)", NAMED), + ]) + def test_driver_error_never_quotes_the_sql(self, sql, style): + error = tokenize(sql, PG, style).driver_error + assert error is not None and "4111" not in error + + def test_percent_before_newline_is_left_alone(self): + # psycopg's pattern does not match a newline after %. + assert tokenize("SELECT 1 %\n2", PG, POS).driver_error is None + + @pytest.mark.parametrize("style", [POS, NAMED]) + def test_mixed_styles_are_a_driver_error(self, style): + assert tokenize("VALUES (%s, %(a)s)", PG, style).driver_error is not None + + @pytest.mark.parametrize("sql, style", [("VALUES (%s)", NAMED), ("VALUES (%(a)s)", POS)]) + def test_style_mismatch_is_a_driver_error(self, sql, style): + assert tokenize(sql, PG, style).driver_error is not None + + def test_no_params_means_no_placeholders(self): + t = tokenize("SELECT '%s', %s, 1 %% 2", PG, NONE) + assert t.placeholders == () + assert t.driver_error is None + assert t.normalized == "SELECT '%s', %s, 1 %% 2" + + def test_spans(self): + sql = "SELECT %(name)s" + p = tokenize(sql, PG, NAMED).placeholders[0] + assert sql[p.start:p.end] == "%(name)s" + + +class TestMySqlPlaceholders: + def test_positional(self): + assert keys(tokenize("INSERT INTO t (a, b) VALUES (%s, %s)", MYSQL, POS)) == [0, 1] + + def test_double_percent_is_not_an_escape(self): + # Connector/Python replaces every "%s" substring, including in "%%s". + t = tokenize("SELECT 5 %% 2, %%s", MYSQL, POS) + assert keys(t) == [0] + assert t.driver_error is None + + def test_any_other_percent_sequence_is_left_alone(self): + t = tokenize("SELECT a FROM t WHERE b LIKE 'x%' AND c = %d AND d = %s", MYSQL, POS) + assert keys(t) == [0] + assert t.driver_error is None + + def test_named_only_with_a_dict(self): + assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, NAMED)) == ["a"] + assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, POS)) == [0] + + def test_named_percent_conversion_is_a_percent_sign(self): + t = tokenize("SELECT %(a)s, 5 %(x)% 2", MYSQL, NAMED) + assert keys(t) == ["a"] + assert "5 % 2" in t.normalized + + def test_named_other_conversion_is_a_driver_error(self): + error = tokenize("SELECT '%(123-45-6789)d'", MYSQL, NAMED).driver_error + assert error is not None and "123-45" not in error + + def test_no_params_means_no_placeholders(self): + assert tokenize("SELECT %s", MYSQL, NONE).placeholders == () + + def test_placeholders_inside_literals_and_comments_are_still_bound(self): + sql = "SELECT %s, '%s', \"%s\", `%s`, /* %s */, # %s\n -- %s\n %s" + t = tokenize(sql, MYSQL, POS) + assert hidden(t) == [False, True, True, True, True, True, True, False] + + def test_backslash_escapes_in_strings(self): + t = tokenize("SELECT 'a\\'b', \"c\\\"d\", %s", MYSQL, POS) + assert hidden(t) == [False] + + def test_double_dash_needs_whitespace_to_start_a_comment(self): + t = tokenize("SELECT 1--%s", MYSQL, POS) + assert hidden(t) == [False] + assert hidden(tokenize("SELECT 1-- %s", MYSQL, POS)) == [True] + + def test_block_comments_do_not_nest(self): + t = tokenize("/* a /* b */ %s */", MYSQL, POS) + assert hidden(t) == [False] + + @pytest.mark.parametrize("sql, executable", [ + ("SELECT /*!40001 SQL_NO_CACHE */ 1", True), + ("SELECT /*! 1 */", True), + ("SELECT /*M!100000 1 */", True), + ("SELECT /*+ hint */ 1", False), + ("SELECT '/*! x */'", False), + ]) + def test_executable_comments(self, sql, executable): + assert tokenize(sql, MYSQL, NONE).executable_comment is executable + + def test_executable_comment_is_only_a_mysql_notion(self): + assert not tokenize("SELECT /*! 1 */", PG, NONE).executable_comment + + def test_executable_comment_keywords(self): + assert "INSERT" in tokenize("SELECT 1 /*! ; INSERT INTO t VALUES (1) */", MYSQL, NONE).keywords + + @pytest.mark.parametrize("sql, introducers", [ + ("VALUES (_binary %s, _utf8mb4'x', %s)", ["_binary", None]), + ("VALUES (_BINARY %s)", ["_binary"]), + ("VALUES (_x %s, a_binary %s)", [None, None]), + ("VALUES ('_binary' %s)", [None]), + ("VALUES (_binary '%s')", [None]), + ]) + def test_charset_introducers(self, sql, introducers): + t = tokenize(sql, MYSQL, POS) + assert [p.introducer for p in t.placeholders] == introducers + if introducers[0]: + assert "_binary" not in t.normalized.lower() + + def test_introducer_inside_a_comment_is_ignored(self): + t = tokenize("VALUES (-- _binary\n%s)", MYSQL, POS) + assert [p.introducer for p in t.placeholders] == [None] + assert "_binary" in t.normalized + + +class TestLexing: + @pytest.mark.parametrize("dialect, sql", [ + (PG, "SELECT 'abc"), (PG, "SELECT \"abc"), (PG, "SELECT $$abc"), (PG, "SELECT /* /* */"), + (PG, "SELECT 'it''"), (MYSQL, "SELECT 'abc\\'"), (MYSQL, "SELECT `a"), (MYSQL, "SELECT /* a"), + ]) + def test_unterminated(self, dialect, sql): + assert tokenize(sql, dialect, POS).unterminated + + def test_leading_words_per_statement(self): + t = tokenize("/* hint */ insert INTO t VALUES (1); -- c\n (SELECT 1); ; UPDATE t SET a = 1;", PG, NONE) + assert t.leading_words == ("INSERT", "SELECT", "UPDATE") + + def test_semicolon_in_literal_does_not_split(self): + assert tokenize("SELECT ';' ; SELECT 2", PG, NONE).leading_words == ("SELECT", "SELECT") + assert tokenize("SELECT ';'", MYSQL, NONE).leading_words == ("SELECT",) + + def test_keywords_ignore_literals_comments_and_placeholder_names(self): + t = tokenize("SELECT 'INSERT' /* UPDATE */ FROM t WHERE a = %(merge)s", PG, NAMED) + assert t.keywords == {"FROM"} + + def test_type_error_for_non_str(self): + with pytest.raises(TypeError): + tokenize(b"SELECT 1", PG, NONE) # type: ignore[arg-type] + + +class TestNormalized: + def test_placeholders_carry_their_ordinal(self): + t = tokenize("VALUES (%s, %s)", PG, POS) + names = re.findall(r":(\w+)", t.normalized) + assert [normalized_ordinal(n) for n in names] == [0, 1] + + def test_cast_after_placeholder_stays_readable(self): + assert ":_kms_p0 ::bytea" in tokenize("VALUES (%s::bytea)", PG, POS).normalized + + @pytest.mark.parametrize("name, expected", [ + ("_kms_p0", 0), ("_kms_p12", 12), ("_kms_p", None), ("_kms_px", None), ("other", None), (None, None), + ("_kms_pÙ£", None), # a non-ASCII digit + ]) + def test_normalized_ordinal(self, name, expected): + assert normalized_ordinal(name) == expected + + @pytest.mark.parametrize("sql, expected", [ + ("REPLACE INTO t (a) VALUES (%s)", "INSERT INTO t (a) VALUES"), + ("REPLACE LOW_PRIORITY INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("INSERT HIGH_PRIORITY IGNORE INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("INSERT DELAYED INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("UPDATE LOW_PRIORITY IGNORE t SET a = %s", "UPDATE t SET"), + ("DELETE LOW_PRIORITY QUICK IGNORE FROM t WHERE a = %s", "DELETE FROM t"), + ("/* x */ replace t SET a = %s", "/* x */ INSERT t SET"), + ]) + def test_mysql_statement_modifiers_and_replace(self, sql, expected): + assert expected in " ".join(tokenize(sql, MYSQL, POS).normalized.split()) + + def test_replace_function_is_left_alone(self): + t = tokenize("SELECT REPLACE(a, 'x', 'y') FROM t; UPDATE t SET a = REPLACE(a, 'x', %s)", MYSQL, POS) + assert t.normalized.count("REPLACE(") == 2 + + def test_modifier_words_elsewhere_are_left_alone(self): + # QUICK is not reserved and can name a table. + t = tokenize("UPDATE quick SET a = %s", MYSQL, POS) + assert "UPDATE quick" in t.normalized + + def test_postgresql_keeps_modifier_words(self): + assert "UPDATE ignore" in tokenize("UPDATE ignore SET a = %s", PG, POS).normalized + + +class TestAnnotations: + def test_annotation_before_a_placeholder(self): + t = tokenize("INSERT INTO t (a, b) VALUES (%s, /*@encrypt:users.ssn*/ %s)", PG, POS) + assert [p.annotation for p in t.placeholders] == [None, ColumnRef("ssn", "users")] + assert t.stray_annotations == () + + def test_named_placeholder(self): + t = tokenize("UPDATE t SET b = /*@encrypt:ssn*/%(ssn)s", PG, NAMED) + assert t.placeholders[0].annotation == ColumnRef("ssn") + + def test_schema_is_dropped(self): + t = tokenize("VALUES (/*@encrypt:app.users.ssn*/ %s)", PG, POS) + assert t.placeholders[0].annotation == ColumnRef("ssn", "users") + + @pytest.mark.parametrize("ref, expected", [ + # References the shared [\w.]+ grammar allows: empty and extra parts. + (".ssn", ColumnRef("ssn")), + ("t..ssn", ColumnRef("ssn", "t")), + ("a.b.t.ssn", ColumnRef("ssn", "t")), + ("9t.1a", ColumnRef("1a", "9t")), + ]) + def test_empty_and_extra_parts(self, ref, expected): + t = tokenize(f"VALUES (/*@encrypt:{ref}*/ %s)", PG, POS) + assert t.placeholders[0].annotation == expected + + def test_doubled_quote_in_a_quoted_part(self): + t = tokenize('VALUES (/*@encrypt:"a""b".ssn*/ %s)', PG, POS) + assert t.placeholders[0].annotation == ColumnRef("ssn", 'a"b') + + def test_postgresql_folds_unquoted_parts_and_keeps_quoted_ones(self): + t = tokenize('VALUES (/*@encrypt:Users."SSN"*/ %s)', PG, POS) + assert t.placeholders[0].annotation == ColumnRef("SSN", "users") + + def test_mysql_backtick_parts(self): + t = tokenize("VALUES (/*@encrypt:`My Table`.SSN*/ %s)", MYSQL, POS) + assert t.placeholders[0].annotation == ColumnRef("SSN", "My Table") + + @pytest.mark.parametrize("sql", [ + "VALUES (%s /*@encrypt:users.ssn*/)", # after, not before + "VALUES (/*@encrypt:users.ssn*/ 'x', %s)", # not followed by a placeholder + "VALUES (/*@encrypt:users.*/ %s)", # no column + "VALUES (/*@encrypt:users ssn*/ %s)", + "VALUES (/*@encrypt:users.ssn*/ '%s')", # a literal, not a placeholder, follows + ]) + def test_stray_annotations(self, sql): + t = tokenize(sql, PG, POS) + assert all(p.annotation is None for p in t.placeholders) + assert len(t.stray_annotations) == 1 + + def test_annotation_before_a_hidden_placeholder_is_stray(self): + # psycopg reads %("x")s as one placeholder that starts outside a + # quoted identifier and ends inside it. + t = tokenize('VALUES (/*@encrypt:t.a*/ %("x")s)', PG, NAMED) + assert hidden(t) == [True] + assert t.placeholders[0].annotation is None and len(t.stray_annotations) == 1 + + def test_space_after_comment_opener_is_not_an_annotation(self): + t = tokenize("VALUES (/* @encrypt:users.ssn*/ %s)", PG, POS) + assert t.placeholders[0].annotation is None + assert t.stray_annotations == () + + def test_annotation_inside_a_literal_is_text(self): + t = tokenize("VALUES ('/*@encrypt:users.ssn*/', %s)", PG, POS) + assert t.placeholders[0].annotation is None + + +# ---- the drivers themselves as the oracle ---- +# +# These call the drivers' own placeholder scanning, so a driver upgrade that +# changes what it binds fails here rather than silently shifting which value +# the plugin encrypts. + +_ORACLE_SQL = [ + "INSERT INTO t (a, b) VALUES (%s, %s)", + "SELECT %s, '%s', \"%s\" -- %s\n, %s", + "SELECT 7 %% 2, %s, '%%s', /* %s */ %s", + "UPDATE t SET a = %s WHERE b LIKE 'x%%' AND c IN (%s, %s)", + "SELECT $$ %s $$, E'\\'%s', %s", + "SELECT %%s, %s%s", +] + +_NAMED_ORACLE_SQL = [ + "INSERT INTO t (a, b) VALUES (%(a)s, %(b)s)", + "UPDATE t SET a = %(v)s, b = %(v)s WHERE c = '%(w)s' -- %(x)s", + "SELECT %(a)s, 5 %% 2, %(b)s", +] + + +@pytest.mark.parametrize("sql", _ORACLE_SQL + _NAMED_ORACLE_SQL) +def test_matches_psycopg(sql): + queries = pytest.importorskip("psycopg._queries") + named = "%(" in sql + parts = queries._split_query(sql.encode()) + expected = [part.item for part in parts[:-1]] + t = tokenize(sql, PG, NAMED if named else POS) + assert keys(t) == expected + assert t.driver_error is None # psycopg accepted it + + +@pytest.mark.parametrize("sql", _ORACLE_SQL) +def test_matches_mysql_connector_positional(sql): + cursor = pytest.importorskip("mysql.connector.cursor") + expected = list(range(len(cursor.RE_PY_PARAM.findall(sql.encode())))) + assert keys(tokenize(sql, MYSQL, POS)) == expected + + +@pytest.mark.parametrize("sql", _NAMED_ORACLE_SQL) +def test_matches_mysql_connector_named(sql): + cursor = pytest.importorskip("mysql.connector.cursor") + expected = [m.group("mapping_key").decode() for m in cursor.RE_PY_MAPPING_PARAM.finditer(sql.encode()) + if m.group("conversion_type") == b"s"] + assert keys(tokenize(sql, MYSQL, NAMED)) == expected From 5ee042faaab950a9244a24f8a99d80db20e15745 Mon Sep 17 00:00:00 2001 From: JuanLeee Date: Wed, 2 Dec 2026 10:40:27 -0700 Subject: [PATCH 3/6] feat: kms encryption plugin (#1331) Co-authored-by: Karen [C] Chen <64801825+karenc-bq@users.noreply.github.com> --- CHANGELOG.md | 1 + .../driver_dialect_manager.py | 52 +- .../encryption/buffers.py | 4 +- .../encryption/config.py | 96 +- .../encryption/connection_source.py | 90 +- .../encryption/data_key_cache.py | 93 +- .../encryption/encryption_service.py | 131 +- .../encryption/key_management_utility.py | 571 ++- .../encryption/key_manager.py | 136 +- .../encryption/kms_encryption_plugin.py | 847 +++++ .../encryption/metadata_manager.py | 54 +- .../encryption/models.py | 119 +- .../encryption/sql/trigger_mysql.sql | 125 + .../encryption/sql/trigger_pg.sql | 73 + .../encryption/sql_analyzer.py | 372 +- .../encryption/sql_dialect.py | 208 - .../encryption/sql_tokenizer.py | 215 +- .../encryption/type_marker.py | 4 +- .../encryption_driver_dialect.py | 204 + .../mysql_driver_dialect.py | 146 +- aws_advanced_python_wrapper/pep249_methods.py | 8 +- .../pg_driver_dialect.py | 156 +- aws_advanced_python_wrapper/plugin_service.py | 20 +- ...dvanced_python_wrapper_messages.properties | 99 +- .../utils/properties.py | 20 +- aws_advanced_python_wrapper/wrapper.py | 32 +- docs/README.md | 1 + docs/development-guide/PluginService.md | 1 + .../PluginChainCompatibility.md | 1 + .../SqlAlchemySupport.md | 3 + .../UsingThePythonWrapper.md | 1 + .../UsingTheKmsEncryptionPlugin.md | 657 ++++ tests/integration/test_kms_encryption_live.py | 1914 ++++++++++ tests/unit/conftest.py | 28 + tests/unit/test_connection.py | 47 +- tests/unit/test_connection_source.py | 105 +- tests/unit/test_data_key_cache.py | 107 +- tests/unit/test_driver_dialect_manager.py | 88 + tests/unit/test_encryption_config.py | 117 +- tests/unit/test_encryption_conformance.py | 7 +- tests/unit/test_encryption_driver_dialect.py | 66 + tests/unit/test_encryption_import_guard.py | 38 +- tests/unit/test_encryption_service.py | 180 +- tests/unit/test_key_management_utility.py | 741 +++- tests/unit/test_key_manager.py | 330 +- tests/unit/test_kms_encryption_plugin.py | 3336 +++++++++++++++++ tests/unit/test_kms_trigger_sql.py | 64 + tests/unit/test_metadata_manager.py | 276 +- tests/unit/test_models.py | 89 + tests/unit/test_mysql_driver_dialect.py | 83 + tests/unit/test_pg_driver_dialect.py | 101 +- tests/unit/test_plugin_manager.py | 63 +- tests/unit/test_properties_utils.py | 29 +- .../unit/test_psycopg3_parity_passthroughs.py | 49 + tests/unit/test_sql_alchemy_driver_dialect.py | 7 +- tests/unit/test_sql_analyzer.py | 551 ++- tests/unit/test_sql_tokenizer.py | 89 +- tests/unit/test_type_marker.py | 3 +- 58 files changed, 11648 insertions(+), 1400 deletions(-) create mode 100644 aws_advanced_python_wrapper/encryption/kms_encryption_plugin.py create mode 100644 aws_advanced_python_wrapper/encryption/sql/trigger_mysql.sql create mode 100644 aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql delete mode 100644 aws_advanced_python_wrapper/encryption/sql_dialect.py create mode 100644 aws_advanced_python_wrapper/encryption_driver_dialect.py create mode 100644 docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md create mode 100644 tests/integration/test_kms_encryption_live.py create mode 100644 tests/unit/test_driver_dialect_manager.py create mode 100644 tests/unit/test_encryption_driver_dialect.py create mode 100644 tests/unit/test_kms_encryption_plugin.py create mode 100644 tests/unit/test_kms_trigger_sql.py create mode 100644 tests/unit/test_models.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 74d6db5f9..2323a5d8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### :magic_wand: Added * 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)) 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/buffers.py b/aws_advanced_python_wrapper/encryption/buffers.py index c9b63bf2a..f7f4d7b48 100644 --- a/aws_advanced_python_wrapper/encryption/buffers.py +++ b/aws_advanced_python_wrapper/encryption/buffers.py @@ -20,12 +20,12 @@ from __future__ import annotations -from typing import Any, Union +from typing import Union BytesLike = Union[bytes, bytearray, memoryview] -def wipe(buffer: Any) -> None: +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 diff --git a/aws_advanced_python_wrapper/encryption/config.py b/aws_advanced_python_wrapper/encryption/config.py index ac3638591..13af175b9 100644 --- a/aws_advanced_python_wrapper/encryption/config.py +++ b/aws_advanced_python_wrapper/encryption/config.py @@ -15,13 +15,14 @@ from __future__ import annotations import math -import os import re -from dataclasses import dataclass, field -from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Type, - TypeVar) +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) @@ -34,6 +35,17 @@ # 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) @@ -46,6 +58,10 @@ def validate_schema_name(name: Any) -> str: 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: @@ -60,23 +76,26 @@ class EncryptionConfig: properties. Build it with :meth:`from_props`; the constructor validates.""" kms_region: str - allowed_master_key_arns: FrozenSet[str] = field(default_factory=frozenset) - kms_endpoint: Optional[str] = None - metadata_schema: str = "encrypt" - metadata_cache_enabled: bool = True - metadata_cache_expiration_sec: float = 3600.0 - metadata_cache_refresh_interval_sec: float = 300.0 - data_key_cache_enabled: bool = True - data_key_cache_max_size: int = 1000 - data_key_cache_expiration_sec: float = 300.0 - key_management_max_retries: int = 3 - key_management_retry_backoff_base_sec: float = 0.1 - audit_logging_enabled: bool = False - return_unverified_data: bool = False + 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("EncryptionConfig.MissingRegion")) + 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)) @@ -110,16 +129,13 @@ def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = Tr :raises EncryptionConfigError: if a value is missing or out of range. """ wp = WrapperProperties - # A blank value at one level falls through to the next. - region = (_stripped(wp.ENCRYPTION_KMS_REGION.get(props)) - or _stripped(os.environ.get("AWS_REGION")) - or _stripped(os.environ.get("AWS_DEFAULT_REGION"))) + # 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=region, + kms_region=_kms_region(_stripped(wp.ENCRYPTION_KMS_REGION.get(props)), allowed_master_key_arns), kms_endpoint=wp.ENCRYPTION_KMS_ENDPOINT.get(props), - # 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)), + 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), @@ -132,6 +148,7 @@ def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = Tr 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: @@ -162,6 +179,29 @@ def _require(condition: bool, prop: WrapperProperty, requirement: str) -> None: 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() @@ -173,6 +213,10 @@ def _finite(value: float) -> bool: 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: diff --git a/aws_advanced_python_wrapper/encryption/connection_source.py b/aws_advanced_python_wrapper/encryption/connection_source.py index 78c382f10..6f5e75287 100644 --- a/aws_advanced_python_wrapper/encryption/connection_source.py +++ b/aws_advanced_python_wrapper/encryption/connection_source.py @@ -12,19 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Where the key and metadata layer gets a connection to run its SQL on.""" +"""How the key and metadata layer gets a connection and runs its SQL through the driver dialect.""" from __future__ import annotations -from contextlib import contextmanager +from contextlib import closing, contextmanager from threading import local -from typing import (TYPE_CHECKING, Any, ContextManager, Iterator, Optional, - Protocol) +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 @@ -72,8 +77,9 @@ def statement(self) -> Iterator[None]: 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 scope that looks nothing up opens - nothing. + 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 @@ -85,7 +91,9 @@ def statement(self) -> Iterator[None]: self._scope.depth = depth if depth == 0: conn, self._scope.conn = self._scope.conn, None - if conn is not 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 @@ -99,7 +107,10 @@ def connection(self) -> Iterator[Any]: try: yield conn finally: - RetryUtil.close_connection(self._plugin_service, conn) + # 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 @@ -111,3 +122,66 @@ def _open(self) -> Any: 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)) + 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 index 8aeb7eb0b..76ef470cd 100644 --- a/aws_advanced_python_wrapper/encryption/data_key_cache.py +++ b/aws_advanced_python_wrapper/encryption/data_key_cache.py @@ -14,15 +14,15 @@ from __future__ import annotations -import time import weakref -from collections import OrderedDict 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__) @@ -41,24 +41,14 @@ def hit_rate(self) -> float: return 100.0 * self.hits / total if total else 0.0 -class _Entry: - __slots__ = ("data_key", "expires_at") - - def __init__(self, data_key: bytearray, expires_at: float): - self.data_key = data_key - self.expires_at = expires_at - - def __repr__(self) -> str: - return f"_Entry(data_key='[REDACTED]', expires_at={self.expires_at!r})" - - 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 wrapper's shared storage service is not used here, because data keys - need a bounded size with oldest-first eviction. Their bytes are zeroed when - they leave the cache. Each ``get`` returns a fresh ``bytearray`` copy, so a + 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. @@ -78,7 +68,8 @@ def __init__(self, max_size: int, ttl_sec: float, enabled: bool = True, self._max_size = max_size self._ttl_sec = ttl_sec self._enabled = enabled - self._entries: OrderedDict[str, _Entry] = OrderedDict() + self._entries: ExpirationTrackingCache[str, bytearray] = ExpirationTrackingCache( + int(ttl_sec * 1_000_000_000)) self._lock = Lock() self._hits = 0 self._misses = 0 @@ -99,10 +90,6 @@ def __init__(self, max_size: int, ttl_sec: float, enabled: bool = True, self._thread_holder[0] = self._cleanup_thread self._cleanup_thread.start() - @property - def enabled(self) -> bool: - return self._enabled - @property def cleanup_interval_sec(self) -> float: return max(self._ttl_sec / 4, self.MIN_CLEANUP_INTERVAL_SEC) @@ -115,17 +102,14 @@ def get(self, key: str) -> Optional[bytearray]: with self._lock: if self._closed: return None - entry = self._entries.get(key) - if entry is None: - self._misses += 1 - return None - if entry.expires_at <= time.monotonic(): - del self._entries[key] - wipe(entry.data_key) + 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(entry.data_key) + 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. @@ -133,34 +117,28 @@ def put(self, key: str, data_key: BytesLike) -> None: stores nothing.""" if not self._enabled: return - entry = _Entry(bytearray(data_key), time.monotonic() + self._ttl_sec) + copy = bytearray(data_key) with self._lock: if self._closed: - wipe(entry.data_key) + wipe(copy) return self._discard(key) while len(self._entries) >= self._max_size: - _, oldest = self._entries.popitem(last=False) - wipe(oldest.data_key) + oldest, _ = self._entries.items()[0] + self._discard(oldest) self._evictions += 1 - self._entries[key] = entry - - def remove(self, key: str) -> None: - with self._lock: - self._discard(key) - - def clear(self) -> None: - """Zero and drop every cached data key.""" - DataKeyCache._wipe_all(self._entries, self._lock) + self._entries.put(key, copy) def remove_expired(self) -> int: """Drop every expired entry. Returns the number removed.""" - now = time.monotonic() + removed = 0 with self._lock: - expired = [k for k, e in self._entries.items() if e.expires_at <= now] - for k in expired: - self._discard(k) - return len(expired) + 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: @@ -189,26 +167,21 @@ def close(self) -> None: def _discard(self, key: str) -> None: # Callers hold the lock. - entry = self._entries.pop(key, None) - if entry is not None: - wipe(entry.data_key) + data_key = self._entries.remove(key) + if data_key is not None: + wipe(data_key) @staticmethod - def _wipe_all(entries: OrderedDict[str, _Entry], lock: Lock) -> None: - with lock: - for entry in entries.values(): - wipe(entry.data_key) - entries.clear() - - @staticmethod - def _release(entries: OrderedDict[str, _Entry], lock: Lock, stop: Event, + 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. - DataKeyCache._wipe_all(entries, lock) + with lock: + for data_key in entries.clear(): + wipe(data_key) if thread_holder[0] is not current_thread(): stop.set() @@ -223,6 +196,6 @@ def _cleanup_loop(cache_ref: weakref.ref[DataKeyCache], stop: Event, interval_se return try: cache.remove_expired() - except Exception as e: # pragma: no cover - defensive + 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 index 8738e49ad..0417db880 100644 --- a/aws_advanced_python_wrapper/encryption/encryption_service.py +++ b/aws_advanced_python_wrapper/encryption/encryption_service.py @@ -23,17 +23,17 @@ 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: # pragma: no cover - exercised by the import-guard test +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( - "The KMS encryption plugin needs the 'cryptography' package. " - "Install it with: pip install 'aws-advanced-python-wrapper[encryption]'") from e + raise ImportError(Messages.get("EncryptionService.CryptographyMissing")) from e from aws_advanced_python_wrapper.encryption import buffers from aws_advanced_python_wrapper.encryption.algorithm import \ @@ -52,8 +52,8 @@ _MICROSECOND = timedelta(microseconds=1) _MILLISECOND = timedelta(milliseconds=1) # The epoch-millis range a datetime can be read back into. -_MIN_MILLIS = -((_EPOCH - datetime.min.replace(tzinfo=timezone.utc)) // _MILLISECOND) -_MAX_MILLIS = (datetime.max.replace(tzinfo=timezone.utc) - _EPOCH) // _MILLISECOND +_MIN_EPOCH_MS = -((_EPOCH - datetime.min.replace(tzinfo=timezone.utc)) // _MILLISECOND) +_MAX_EPOCH_MS = (datetime.max.replace(tzinfo=timezone.utc) - _EPOCH) // _MILLISECOND class EncryptionService: @@ -93,8 +93,6 @@ class EncryptionService: #: Zero a ``bytearray`` in place; see :func:`buffers.wipe`. wipe = staticmethod(buffers.wipe) - # ---- public API ---- - @classmethod def encrypt(cls, value: Any, data_key: BytesLike, hmac_key: BytesLike, algorithm: str = EncryptionAlgorithm.DEFAULT, *, key_id: int) -> Optional[bytes]: @@ -160,8 +158,7 @@ def decrypt(cls, encrypted: Optional[BytesLike], data_key: BytesLike, hmac_key: data = cls._to_bytes(encrypted) if len(data) < cls.MIN_ENCRYPTED_LENGTH: raise IntegrityCheckError( - f"Encrypted data is too short: {len(data)} bytes, " - f"expected at least {cls.MIN_ENCRYPTED_LENGTH}", + Messages.get_formatted("EncryptionService.DataTooShort", len(data), cls.MIN_ENCRYPTED_LENGTH), algorithm=algorithm, ) @@ -173,11 +170,7 @@ def decrypt(cls, encrypted: Optional[BytesLike], data_key: BytesLike, hmac_key: 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( - "Integrity check failed: the value was modified, was never encrypted, " - "or was signed with a different HMAC key", - algorithm=algorithm, - ) + raise IntegrityCheckError(Messages.get("EncryptionService.IntegrityCheckFailed"), algorithm=algorithm) payload = body[cls.KEY_ID_LENGTH:] marker = cls._read_marker(payload) @@ -186,7 +179,44 @@ def decrypt(cls, encrypted: Optional[BytesLike], data_key: BytesLike, hmac_key: plaintext = cls._unseal(payload, data_key, algorithm, marker) return cls._convert_to_target_type(cls.deserialize_value(plaintext, marker), target_type) - # ---- serialization ---- + @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: @@ -200,7 +230,7 @@ def serialize_value(cls, value: Any, marker: Optional[int] = None) -> bytes: if marker is None: marker = TypeMarker.from_object(value) if not TypeMarker.is_known(marker): - raise EncryptionFailedError(f"Unsupported type marker: {marker!r}") + raise EncryptionFailedError(Messages.get_formatted("EncryptionService.UnsupportedTypeMarker", marker)) try: return cls._serialize(value, marker) except (TypeError, ValueError, AttributeError, ArithmeticError, struct.error): @@ -211,7 +241,7 @@ def serialize_value(cls, value: Any, marker: Optional[int] = None) -> bytes: # and decimal.InvalidOperation. pass raise EncryptionFailedError( - f"Cannot write a value of type {type(value).__name__} as {TypeMarker.name_for(marker)}", + Messages.get_formatted("EncryptionService.CannotWriteType", type(value).__name__, TypeMarker.name_for(marker)), data_type=TypeMarker.name_for(marker)) @classmethod @@ -233,7 +263,7 @@ def _serialize(cls, value: Any, marker: int) -> bytes: 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("BYTE_ARRAY needs a bytes-like value") + raise TypeError(Messages.get("EncryptionService.NeedsBytes")) return cls._to_bytes(value) if marker == TypeMarker.INTEGER: return struct.pack(">i", value) @@ -245,9 +275,7 @@ def _serialize(cls, value: Any, marker: int) -> bytes: # float or Decimal. value = operator.index(value) if not (-(2 ** 63) <= value <= 2 ** 63 - 1): - raise EncryptionFailedError( - "Integer value exceeds the signed 64-bit range", data_type="LONG" - ) + raise EncryptionFailedError(Messages.get("EncryptionService.LongOutOfRange"), data_type="LONG") return struct.pack(">q", value) if marker == TypeMarker.DOUBLE: return struct.pack(">d", value) @@ -256,15 +284,14 @@ def _serialize(cls, value: Any, marker: int) -> bytes: if marker == TypeMarker.BOOLEAN: # Not truthiness: "false" must not be written as True. if not isinstance(value, bool): - raise TypeError("BOOLEAN needs a 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( - "Cannot encrypt a non-finite Decimal", data_type="BIG_DECIMAL") + 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 "")) @@ -276,12 +303,11 @@ def _serialize(cls, value: Any, marker: int) -> bytes: if marker == TypeMarker.LOCAL_DATE_TIME: if not isinstance(value, datetime): raise EncryptionFailedError( - f"Cannot write a value of type {type(value).__name__} as LOCAL_DATE_TIME", + 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( # pragma: no cover - serialize_value checks the marker first - f"Unsupported type marker: {marker!r}") + raise EncryptionFailedError(Messages.get_formatted("EncryptionService.UnsupportedTypeMarker", marker)) @classmethod def deserialize_value(cls, data: bytes, marker: int) -> Any: @@ -318,15 +344,12 @@ def deserialize_value(cls, data: bytes, marker: int) -> Any: failed_marker = marker else: raise DecryptionError( - f"Unsupported type marker: {marker!r}", data_type=str(marker) - ) + Messages.get_formatted("EncryptionService.UnsupportedTypeMarker", marker), data_type=str(marker)) raise TypeConversionError( - f"Failed to deserialize {TypeMarker.name_for(failed_marker) or failed_marker}", + Messages.get_formatted("EncryptionService.DeserializeFailed", TypeMarker.name_for(failed_marker) or failed_marker), data_type=TypeMarker.name_for(failed_marker), ) - # ---- AES-GCM ---- - @classmethod def _seal(cls, plaintext: BytesLike, marker: int, data_key: BytesLike, algorithm: str) -> bytes: try: @@ -337,9 +360,9 @@ def _seal(cls, plaintext: BytesLike, marker: int, data_key: BytesLike, algorithm # 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: # pragma: no cover - cryptography rarely fails here + except Exception as e: raise EncryptionFailedError( - f"Failed to encrypt value: {type(e).__name__}", + Messages.get_formatted("EncryptionService.EncryptFailed", type(e).__name__), algorithm=algorithm, data_type=TypeMarker.name_for(marker), ) from e @@ -353,12 +376,9 @@ def _unseal(cls, payload: bytes, data_key: BytesLike, algorithm: str, marker: in # 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( - "Failed to decrypt value: the authentication tag does not match this data key", - algorithm=algorithm, data_type=TypeMarker.name_for(marker), + Messages.get("EncryptionService.TagMismatch"), algorithm=algorithm, data_type=TypeMarker.name_for(marker), ) from e - # ---- helpers ---- - @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): @@ -385,7 +405,7 @@ def _convert_to_target_type(cls, value: Any, target_type: Optional[type]) -> Any # Reached after a caught conversion failure, or when target_type # matched no branch above. raise TypeConversionError( - f"Cannot convert {source_name} to {target_type}", + Messages.get_formatted("EncryptionService.CannotConvert", source_name, target_type), data_type=str(target_type), ) @@ -402,22 +422,18 @@ def _validate_key(cls, data_key: BytesLike, algorithm: str) -> None: 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( - f"Data key must be {expected} bytes for {algorithm}, got {got!r}", - algorithm=algorithm, - ) + 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 len(hmac_key) == 0: - raise InvalidKeyError("An HMAC key is required to protect encrypted values") + 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( - f"A valid key id is required to tag an encrypted value, got {key_id!r}" - ) + raise EncryptionFailedError(Messages.get_formatted("EncryptionService.InvalidKeyId", key_id)) @staticmethod def _require_naive(value: Any, marker_name: str) -> None: @@ -426,13 +442,13 @@ def _require_naive(value: Any, marker_name: str) -> None: # TIMESTAMP instead (see TypeMarker.from_object). if isinstance(value, (datetime, time)) and value.utcoffset() is not None: raise EncryptionFailedError( - f"Cannot write a timezone-aware value as {marker_name}", data_type=marker_name) + 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( - f"Expected {length} bytes for {TypeMarker.name_for(marker)}, got {len(data)}", + Messages.get_formatted("EncryptionService.WrongValueLength", length, TypeMarker.name_for(marker), len(data)), data_type=TypeMarker.name_for(marker), ) return data @@ -463,9 +479,7 @@ def _utf8_bytes(cls, string: str) -> bytes: # UnicodeEncodeError holds the full plaintext in `.object`; raised # below, outside the handler (see the class docstring). pass - raise EncryptionFailedError( - "Cannot encrypt a string with no UTF-8 form", data_type="str" - ) + raise EncryptionFailedError(Messages.get("EncryptionService.NoUtf8Form"), data_type="str") @classmethod def _to_millis(cls, value: Any, marker_name: str) -> int: @@ -481,22 +495,21 @@ def _to_millis(cls, value: Any, marker_name: str) -> int: elif isinstance(value, date): dt = datetime(value.year, value.month, value.day, tzinfo=timezone.utc) else: - raise TypeError(f"{marker_name} needs a date or datetime") + 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_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_MILLIS - if not _MIN_MILLIS <= millis <= _MAX_MILLIS: + 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( - "In UTC, the value is outside the range a datetime can represent", data_type=marker_name) + raise EncryptionFailedError(Messages.get("EncryptionService.OutsideDatetimeRange"), data_type=marker_name) return millis @classmethod diff --git a/aws_advanced_python_wrapper/encryption/key_management_utility.py b/aws_advanced_python_wrapper/encryption/key_management_utility.py index 89017e1c2..384f5df8c 100644 --- a/aws_advanced_python_wrapper/encryption/key_management_utility.py +++ b/aws_advanced_python_wrapper/encryption/key_management_utility.py @@ -15,33 +15,70 @@ from __future__ import annotations import time -from typing import TYPE_CHECKING, Any, List, Optional, cast +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.connection_source import \ - CallerConnectionSource +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 +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 (KeyMetadata, - mask_arn, - mask_arns_in_text) -from aws_advanced_python_wrapper.encryption.sql_dialect import (SqlDialect, - execute, - fetch_rows) -from aws_advanced_python_wrapper.errors import KeyManagementError +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 WrapperProperties +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 @@ -66,10 +103,14 @@ class KeyManagementUtility: utility.initialize_encryption_for_column("users", "ssn", arn) conn.commit() - The connection is never closed, committed, or rolled back here. Each + 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. + 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, @@ -87,26 +128,53 @@ class KeyManagementUtility: """ 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, - *, engine: Optional[str] = None): + *, props: Optional[Dict[str, Any]] = None): """ - :param engine: ``"postgresql"`` or ``"mysql"``. Inferred from - ``connection`` when omitted. + :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")) - self._sql = SqlDialect.for_name(engine) if engine else SqlDialect.for_connection(connection) + 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 - self._schema = config.metadata_schema # interpolated into every statement below + # 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._sql, config, + 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._sql, config) + 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: @@ -120,7 +188,7 @@ def create_master_key(self, description: str, *, policy: Optional[str] = None, try: self._kms.create_alias(AliasName=alias, TargetKeyId=arn) except Exception as e: - logger.warning("KeyManagementUtility.CreateAliasFailed", mask_arn(arn), mask_arns_in_text(str(e))) + logger.warning("KeyManagementUtility.CreateAliasFailed", mask_arn(arn), describe_kms_failure(e)) logger.info("KeyManagementUtility.CreatedMasterKey", mask_arn(arn)) return arn @@ -136,7 +204,7 @@ def initialize_encryption_for_column(self, table_name: str, column_name: str, ma if self._metadata.is_column_encrypted(table_name, column_name): raise KeyManagementError( Messages.get_formatted("KeyManagementUtility.AlreadyEncrypted", table_name, column_name), - operation="INITIALIZE_COLUMN") + 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, @@ -149,22 +217,26 @@ def generate_and_store_data_key(self, table_name: str, column_name: str, master_ """ self._require(table_name=table_name, column_name=column_name, master_key_arn=master_key_arn) algorithm = algorithm or EncryptionAlgorithm.DEFAULT - if not EncryptionAlgorithm.is_supported(algorithm): - raise EncryptionAlgorithm.unsupported(algorithm) + # 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._sql.upsert_clause(("table_name", "column_name"), ("encryption_algorithm", "key_id"), - extra_assignments=("updated_at = CURRENT_TIMESTAMP",))) - self._run("STORE_ENCRYPTION_METADATA", sql, (table_name, column_name, algorithm, key_storage_id)) + + 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 a new data key. New writes use it; values - written with the previous key stay readable, because each payload - records its ``key_storage.id`` and the old row is kept. + """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 @@ -174,31 +246,148 @@ def rotate_data_key(self, table_name: str, column_name: str, new_master_key_arn: :return: the ``key_storage.id`` of the new data key. """ self._require(table_name=table_name, column_name=column_name) - 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)) + 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="ROTATE_DATA_KEY") + 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="ROTATE_DATA_KEY") + 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._sql.equals} %s AND column_name {self._sql.equals} %s") - if self._run("UPDATE_ENCRYPTION_METADATA", sql, (key_storage_id, table_name, column_name)) == 0: + 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="ROTATE_DATA_KEY") + 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 @@ -208,8 +397,8 @@ def remove_encryption_for_column(self, table_name: str, column_name: str) -> boo """ self._require(table_name=table_name, column_name=column_name) sql = (f"DELETE FROM {self._schema}.encryption_metadata " - f"WHERE table_name {self._sql.equals} %s AND column_name {self._sql.equals} %s") - removed = self._run("DELETE_ENCRYPTION_METADATA", sql, (table_name, column_name)) > 0 + 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 @@ -218,16 +407,52 @@ 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._sql.equals} %s ORDER BY table_name, column_name") + 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(conn, sql, (key_storage_id,)) + rows = fetch_rows(self._driver_dialect, conn, sql, (key_storage_id,)) except Exception as e: raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", - "SELECT_COLUMNS_USING_KEY", e), - operation="SELECT_COLUMNS_USING_KEY") from e + 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 @@ -235,8 +460,6 @@ def is_master_key_valid(self, master_key_arn: str) -> bool: self._require(master_key_arn=master_key_arn) return self._key_manager.is_master_key_valid(master_key_arn) - # ---- internals ---- - 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``.""" @@ -255,13 +478,259 @@ def _store_new_data_key(self, table_name: str, column_name: str, master_key_arn: finally: wipe(generated.plaintext) - def _run(self, operation: str, sql: str, params: Any) -> int: + 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 execute(conn, sql, params) + return fetch_rows(self._driver_dialect, conn, sql, params) except Exception as e: - raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", operation, e), - operation=operation) from 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: diff --git a/aws_advanced_python_wrapper/encryption/key_manager.py b/aws_advanced_python_wrapper/encryption/key_manager.py index 6c6934d0c..704721d32 100644 --- a/aws_advanced_python_wrapper/encryption/key_manager.py +++ b/aws_advanced_python_wrapper/encryption/key_manager.py @@ -34,12 +34,14 @@ 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_arns_in_text) -from aws_advanced_python_wrapper.encryption.sql_dialect import (execute, - fetch_rows) + mask_error_text, + mask_key_id) from aws_advanced_python_wrapper.errors import (InvalidKeyMetadataError, KeyManagementError, UnauthorizedMasterKeyError) @@ -50,12 +52,14 @@ 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.sql_dialect import SqlDialect + from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect logger = Logger(__name__) @@ -94,8 +98,9 @@ def filter(self, record: logging.LogRecord) -> bool: # A logger's filters don't see its children's records, so each filter goes on -# the logger that emits the records. They are installed once per process, so a -# filter that was removed on purpose stays removed. +# 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 @@ -112,6 +117,22 @@ def _install_botocore_filters() -> None: _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 @@ -132,6 +153,9 @@ class KeyManager: 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 @@ -162,15 +186,17 @@ class KeyManager: # 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, sql_dialect: SqlDialect, - config: EncryptionConfig, data_key_cache: DataKeyCache, + 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._sql = sql_dialect + 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: @@ -199,8 +225,6 @@ def create_kms_client(session: Session, config: EncryptionConfig) -> Any: return session.client("kms", endpoint_url=config.kms_endpoint, config=client_config) return session.client("kms", config=client_config) - # ---- data keys ---- - 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. @@ -210,10 +234,10 @@ def decrypt_data_key(self, encrypted_data_key: Optional[str], master_key_arn: Op :raises InvalidKeyMetadataError: there is no usable encrypted data key. :raises KeyManagementError: KMS rejected the request. """ - self._authorize(master_key_arn) + 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="DECRYPT_DATA_KEY") + 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) @@ -228,7 +252,7 @@ def decrypt_data_key(self, encrypted_data_key: Optional[str], master_key_arn: Op ciphertext = None if not ciphertext: raise InvalidKeyMetadataError( - Messages.get("KeyManager.MalformedEncryptedDataKey"), operation="DECRYPT_DATA_KEY") + 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 @@ -237,7 +261,7 @@ def decrypt_data_key(self, encrypted_data_key: Optional[str], master_key_arn: Op request: Dict[str, Any] = {"CiphertextBlob": ciphertext} if master_key_arn: request["KeyId"] = master_key_arn - response = self._call_kms("DECRYPT_DATA_KEY", lambda: self._kms.decrypt(**request)) + 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 @@ -250,10 +274,10 @@ def generate_data_key(self, master_key_arn: str, :raises UnauthorizedMasterKeyError: the master key is not allowed. :raises KeyManagementError: KMS rejected the request. """ - self._authorize(master_key_arn) + self.authorize_master_key(master_key_arn) key_spec = EncryptionAlgorithm.data_key_spec(algorithm) response = self._call_kms( - "GENERATE_DATA_KEY", lambda: self._kms.generate_data_key(KeyId=master_key_arn, KeySpec=key_spec)) + 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 @@ -262,7 +286,7 @@ def generate_data_key(self, master_key_arn: str, wipe(plaintext) raise KeyManagementError( Messages.get_formatted("KeyManager.WrongDataKeyLength", length, key_spec, algorithm), - operation="GENERATE_DATA_KEY") + operation=KeyOperation.GENERATE_DATA_KEY.value) return GeneratedDataKey( plaintext=plaintext, encrypted_data_key=base64.b64encode(response["CiphertextBlob"]).decode("ascii"), @@ -276,8 +300,6 @@ def data_key_cache_key(cls, encrypted_data_key: str) -> str: digest = hashlib.sha256(encrypted_data_key.encode("utf-8")).digest() return cls._CACHE_KEY_PREFIX + base64.b64encode(digest).decode("ascii") - # ---- master keys ---- - 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. @@ -289,7 +311,7 @@ def create_master_key(self, description: str, *, policy: Optional[str] = None) - request = {"Description": description, "KeyUsage": self.KEY_USAGE, "KeySpec": self.MASTER_KEY_SPEC} if policy and policy.strip(): request["Policy"] = policy - response = self._call_kms("CREATE_MASTER_KEY", lambda: self._kms.create_key(**request), + response = self._call_kms(KeyOperation.CREATE_MASTER_KEY, lambda: self._kms.create_key(**request), retryable=self._is_not_processed) return response["KeyMetadata"]["Arn"] @@ -301,15 +323,13 @@ def is_master_key_valid(self, master_key_arn: str) -> bool: """ try: metadata = self._call_kms( - "DESCRIBE_MASTER_KEY", lambda: self._kms.describe_key(KeyId=master_key_arn))["KeyMetadata"] + 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) - # ---- key_storage ---- - 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. @@ -319,7 +339,7 @@ def store_key_metadata(self, key_metadata: KeyMetadata) -> KeyMetadata: """ if not key_metadata.is_usable: raise InvalidKeyMetadataError( - Messages.get("KeyManager.RefusingUnusableKeyMetadata"), operation="STORE_KEY_METADATA") + 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 " @@ -331,62 +351,56 @@ def store_key_metadata(self, key_metadata: KeyMetadata) -> KeyMetadata: failure: Optional[str] = None try: with self._connections.connection() as conn: - new_id = self._sql.insert_returning_id(conn, sql, params) + 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 = self._describe_failure(e) + failure = describe_failure(e) if failure is not None: raise KeyManagementError( - Messages.get_formatted("KeyManager.StoreKeyMetadataFailed", failure), operation="STORE_KEY_METADATA") + 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._sql.equals} %s") + 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(conn, sql, (key_storage_id,)) + 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", e), - operation="GET_KEY_METADATA") from e + 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._sql.equals} %s") + f"WHERE key_id {self._encryption_dialect.equals_operator} %s") try: with self._connections.connection() as conn: - execute(conn, sql, (key_uuid,)) + run_statement(self._driver_dialect, conn, sql, (key_uuid,)) except Exception as e: - logger.debug("KeyManager.TouchKeyFailed", key_uuid, e) + logger.debug("KeyManager.TouchKeyFailed", mask_key_id(key_uuid), describe_failure(e)) - # ---- internals ---- - - def _authorize(self, master_key_arn: Optional[str]) -> None: + 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="AUTHORIZE_MASTER_KEY") + operation=KeyOperation.AUTHORIZE_MASTER_KEY.value) - @staticmethod - def _describe_failure(error: Exception) -> str: - """The exception type plus any SQLSTATE / errno the driver reports. - Neither carries statement text, unlike the error message.""" - 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 _call_kms(self, operation: str, call: Callable[[], T], + 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 @@ -398,16 +412,16 @@ def _call_kms(self, operation: str, call: Callable[[], T], try: return call() except Exception as e: - # KMS's error text can name the master key and the caller's - # role session. The error, kept as __cause__, keeps that text. - if attempt >= max_retries or not is_retryable(e): - raise KeyManagementError( - Messages.get_formatted("KeyManager.KmsCallFailed", operation, attempt + 1, - mask_arns_in_text(str(e))), - operation=operation) from e - delay = self._backoff_sec(attempt) - logger.debug("KeyManager.Retrying", operation, attempt + 1, max_retries + 1, delay, - mask_arns_in_text(str(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 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 index 693b08520..a8b1db55a 100644 --- a/aws_advanced_python_wrapper/encryption/metadata_manager.py +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -23,18 +23,21 @@ 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.encryption.sql_dialect import fetch_rows 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.sql_dialect import SqlDialect + from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect logger = Logger(__name__) @@ -42,7 +45,7 @@ class _Snapshot(NamedTuple): - # Keyed by SqlDialect.metadata_key of the names. + # 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() @@ -62,7 +65,7 @@ class MetadataManager: disabled, each lookup queries the database. Lookups compare names the way the engine does - (:meth:`SqlDialect.metadata_key`): exactly on PostgreSQL, where names are + (: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. @@ -78,9 +81,11 @@ class MetadataManager: SHUTDOWN_TIMEOUT_SEC = 5.0 - def __init__(self, connection_source: ConnectionSource, sql_dialect: SqlDialect, config: EncryptionConfig): + def __init__(self, connection_source: ConnectionSource, driver_dialect: DriverDialect, + encryption_dialect: EncryptionDriverDialect, config: EncryptionConfig): self._connections = connection_source - self._sql = sql_dialect + self._driver_dialect = driver_dialect + self._encryption_dialect = encryption_dialect self._config = config self._snapshot: Optional[_Snapshot] = None self._started = False @@ -96,8 +101,6 @@ def __init__(self, connection_source: ConnectionSource, sql_dialect: SqlDialect, self._thread_holder: List[Optional[Thread]] = [None] weakref.finalize(self, MetadataManager._finalize, self._stop, self._thread_holder) - # ---- lifecycle ---- - def start(self) -> None: """Load the cache and start the background refresh, as configured. @@ -152,8 +155,6 @@ def load_metadata(self) -> Dict[Tuple[str, str], ColumnEncryptionConfig]: cache. Keyed by ``(table_name, column_name)``.""" return self._load_all() - # ---- lookups ---- - 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 @@ -168,10 +169,12 @@ def column_config(self, table_name: Optional[str], column_name: Optional[str]) - 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((self._sql.metadata_key(table_name), self._sql.metadata_key(column_name))) + 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 {self._sql.equals} %s AND em.column_name {self._sql.equals} %s", + 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 @@ -181,11 +184,19 @@ def table_configs(self, table_name: Optional[str]) -> Sequence[ColumnEncryptionC return () snapshot = self._usable_snapshot(table_name) if snapshot is not None: - return snapshot.by_table.get(self._sql.metadata_key(table_name), ()) - rows = self._query(f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s", + 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 @@ -195,8 +206,6 @@ def cache_size(self) -> int: def is_cache_loaded(self) -> bool: return self._snapshot is not None - # ---- internals ---- - def _usable_snapshot(self, table_name: Optional[str] = None, column_name: Optional[str] = None) -> Optional[_Snapshot]: if not self._config.metadata_cache_enabled: @@ -220,7 +229,7 @@ def _load_snapshot(self, *, table_name: Optional[str] = None, column_name: Optio # returned. loaded_at = time.monotonic() columns = self._load_all(table_name=table_name, column_name=column_name) - key = self._sql.metadata_key + 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) @@ -252,10 +261,13 @@ def _query(self, sql: str, params: Sequence[Any], *, table_name: Optional[str] = column_name: Optional[str] = None) -> List[Dict[str, Any]]: try: with self._connections.connection() as conn: - return fetch_rows(conn, sql, params) + return fetch_rows(self._driver_dialect, conn, sql, params) except Exception as e: - raise MetadataError(Messages.get_formatted("MetadataManager.LoadFailed", e), - table_name=table_name, column_name=column_name) from 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 @@ -271,7 +283,7 @@ def _joined_sql(self) -> str: 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._sql.equals} ks.id") + 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: diff --git a/aws_advanced_python_wrapper/encryption/models.py b/aws_advanced_python_wrapper/encryption/models.py index f33d9a1fa..6d6710b0e 100644 --- a/aws_advanced_python_wrapper/encryption/models.py +++ b/aws_advanced_python_wrapper/encryption/models.py @@ -18,11 +18,14 @@ from __future__ import annotations import re +import unicodedata from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Mapping, Optional, cast +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 @@ -30,6 +33,27 @@ 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 @@ -37,35 +61,83 @@ _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 ``***``.""" + characters or fewer becomes ``***``. Control characters in the kept part + become ``?``.""" if value is None: return None - return f"{value[:4]}***{value[-4:]}" if len(value) > 8 else "***" + 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. ARNs are identifiers, - not secrets: the messages that quote a KMS error mask the ARNs in its text - with :func:`mask_arns_in_text`, but the KMS error itself, kept as the - ``__cause__``, still shows them.""" + 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_arns_in_text(text: str) -> str: - """Mask the ARNs in ``text`` that name an account, such as those in a - failed KMS call's error message: the master key and, for an access denial, - the caller's role session. A KMS key ARN is masked as :func:`mask_arn` - does; any other ARN keeps only its partition and service. Text without - such an ARN comes back unchanged.""" - return _ARN_IN_TEXT.sub(_mask_matched_arn, text) +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: @@ -149,10 +221,27 @@ class ColumnEncryptionConfig: @property def column_identifier(self) -> str: - return f"{self.table_name}.{self.column_name}" + """``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 index e4efb1608..d9b0de3c8 100644 --- a/aws_advanced_python_wrapper/encryption/sql_analyzer.py +++ b/aws_advanced_python_wrapper/encryption/sql_analyzer.py @@ -39,27 +39,29 @@ from dataclasses import dataclass, field from enum import Enum from functools import lru_cache -from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List, - Optional, Sequence, Set, Tuple) +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: # pragma: no cover - exercised by the import-guard test +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( - "The KMS encryption plugin needs the 'sqlglot' package. " - "Install it with: pip install 'aws-advanced-python-wrapper[encryption]'") from e + 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.sql_dialect import SqlDialect + from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect class StatementKind(Enum): @@ -160,7 +162,8 @@ class StatementAnalysis: writes: bool placeholders: Tuple[Placeholder, ...] #: Every table the string names, without duplicates and excluding CTE - #: names (outer queries first, not in text order). + #: 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, ...] = () @@ -187,6 +190,20 @@ class StatementAnalysis: #: 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. @@ -196,6 +213,9 @@ class StatementAnalysis: 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: @@ -218,7 +238,12 @@ def parameter_columns(self) -> Dict[int, ColumnRef]: CACHEABLE_PERCENT_SIGNS = 64 -def analyze(sql: str, dialect: SqlDialect, params: Any = None) -> StatementAnalysis: +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 @@ -246,7 +271,7 @@ def __init__(self, analysis: StatementAnalysis): @lru_cache(maxsize=1024) -def _cached_analysis(sql: str, dialect: SqlDialect, style: ParamStyle) -> StatementAnalysis: +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 @@ -255,14 +280,6 @@ def _cached_analysis(sql: str, dialect: SqlDialect, style: ParamStyle) -> Statem return result -# Leading words of the statements handed to the parser. Anything else is -# reported without parsing it: sqlglot falls back to an opaque "command" for -# what it doesn't support, and logs it. -_PARSED = { - "postgresql": frozenset({"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "COPY", "VALUES", "PREPARE"}), - "mysql": frozenset({"SELECT", "WITH", "INSERT", "REPLACE", "UPDATE", "DELETE", "VALUES"}), -} -_SQLGLOT_DIALECT = {"postgresql": "postgres", "mysql": "mysql"} _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, @@ -321,7 +338,7 @@ def active(self) -> Iterator[None]: logging.getLogger("sqlglot").addFilter(_QUIET) -def _analysis(sql: str, dialect: SqlDialect, style: ParamStyle) -> StatementAnalysis: +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) @@ -340,16 +357,17 @@ def result(**kwargs: Any) -> StatementAnalysis: elif tokens.executable_comment: early = AnalysisGap.EXECUTABLE_COMMENT if early is not None: - # The parser reads a hidden placeholder as literal or comment text, so - # the tables are still known, and a caller can refuse the statement + # The tables are still listed, so a caller can refuse the statement # when one of them has encrypted columns. - tables = _named_tables(tokens, dialect) if early is AnalysisGap.HIDDEN_PLACEHOLDER else () + 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) - if any(w not in _PARSED[dialect.name] for w in tokens.leading_words): + # 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 @@ -363,12 +381,14 @@ def result(**kwargs: Any) -> StatementAnalysis: trees, failure = parsed if trees is None: return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), gap=AnalysisGap.UNPARSEABLE, - detail=failure) + 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): + 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) + 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: @@ -376,11 +396,12 @@ def result(**kwargs: Any) -> StatementAnalysis: return walker.result(trees, annotations, result) -def _parse(text: str, dialect: SqlDialect) -> Tuple[Optional[List[exp.Expression]], Optional[str]]: +def _parse(text: str, dialect: Type[EncryptionDriverDialect]) -> Tuple[Optional[List[exp.Expression]], Optional[str]]: try: with _QUIET.active(): - parsed = sqlglot.parse(text, read=_SQLGLOT_DIALECT[dialect.name]) - except Exception as e: # sqlglot raises ParseError/TokenError, but must never break a statement + 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() @@ -393,11 +414,12 @@ def _parse(text: str, dialect: SqlDialect) -> Tuple[Optional[List[exp.Expression return [t for t in parsed if isinstance(t, exp.Expression)], None -def _parse_statement(tokens: TokenizedSql, dialect: SqlDialect) -> Optional[Tuple[Optional[List[exp.Expression]], Optional[str]]]: +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 a MySQL INSERT or REPLACE - that doesn't parse is tried again without its column qualifiers. ``None`` - when a PREPARE has no such prefix.""" + ``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) @@ -406,14 +428,14 @@ def _parse_statement(tokens: TokenizedSql, dialect: SqlDialect) -> Optional[Tupl text = text[m.end():] trees, failure = _parse(text, dialect) - if trees is None and tokens.leading_words in (("INSERT",), ("REPLACE",)) and dialect.name == "mysql": + 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: SqlDialect) -> Tuple[TableRef, ...]: +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) @@ -426,6 +448,29 @@ def _named_tables(tokens: TokenizedSql, dialect: SqlDialect) -> Tuple[TableRef, 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"): @@ -437,13 +482,18 @@ def _without_insert_column_qualifiers(text: str) -> Optional[str]: def _may_write(tokens: TokenizedSql) -> bool: # Keywords only: what a statement that could not be read may be doing. words = tokens.keywords - for leading in tokens.leading_words: - if leading in _WRITE_LEADING or (leading == "COPY" and "FROM" in words): + for leading, copies_query in zip(tokens.leading_words, tokens.copy_queries): + if leading in _WRITE_LEADING: + return True + if leading in ("WITH", "EXPLAIN", "PREPARE", "COPY") and words & _WRITE_WORDS: return True - if leading in ("WITH", "EXPLAIN", "PREPARE") and words & _WRITE_WORDS: + 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: - return True # EXPLAIN ANALYZE EXECUTE runs the prepared statement + # 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)) @@ -454,7 +504,8 @@ def _placeholder_mismatch(trees: List[exp.Expression], tokens: TokenizedSql) -> for node in tree.find_all(exp.Placeholder): ordinal = normalized_ordinal(node.name) if ordinal is None: - continue # a "?" or ":name" the driver does not bind + # 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) @@ -463,8 +514,6 @@ def _placeholder_mismatch(trees: List[exp.Expression], tokens: TokenizedSql) -> return None -# ---- the walk ---- - def _by_ordinal(use: ParameterUse) -> int: return use.ordinal @@ -521,7 +570,7 @@ def _by_ordinal(use: ParameterUse) -> int: class _Walker: """Collects what one or more parsed statements write, compare and read.""" - def __init__(self, dialect: SqlDialect, tokens: TokenizedSql, prepared: bool = False): + 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. @@ -555,8 +604,6 @@ def __init__(self, dialect: SqlDialect, tokens: TokenizedSql, prepared: bool = F # Tables each write node (INSERT, UPDATE, MERGE) writes. self._written_by: Dict[int, List[TableRef]] = {} - # ---- entry ---- - def statement(self, tree: exp.Expression) -> None: self.collect_tables(tree) for found in tree.find_all(exp.Placeholder): @@ -606,6 +653,7 @@ def result(self, trees: List[exp.Expression], annotations: Tuple[ParameterUse, . 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, @@ -616,9 +664,10 @@ def result(self, trees: List[exp.Expression], annotations: Tuple[ParameterUse, . annotations=resolved, unbound_writes=tuple(self._unbound), result_columns=self._result_columns(trees[0]) if len(trees) == 1 and not self._prepared else None, - gap=self._gap if self._writes else None) - - # ---- statements ---- + 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): @@ -693,7 +742,8 @@ def _insert_from_values(self, columns: List[Optional[str]], table: Optional[str] 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): - return False # a join, a filter, a limit, ... (or an arg this code does not know) + # 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 @@ -711,16 +761,18 @@ def _insert_from_values(self, columns: List[Optional[str]], table: Optional[str] return False positions.append((names[self._key(inner.this)], casts)) if len({position for position, _ in positions}) != len(positions): - return False # one value would fill two columns - assert isinstance(values, exp.Values) + # 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.name != "mysql": - same_row[self._key("excluded")] = None + 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 @@ -797,8 +849,6 @@ def _copy(self, node: exp.Copy) -> None: else: self._unbound.append(ColumnRef(column, name)) - # ---- writes ---- - 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): @@ -834,7 +884,8 @@ def _write(self, column: ColumnRef, value: exp.Expression, outer_casts: Tuple[st ordinal, casts, _ = param self._assignments.append(ParameterUse(self._tokens.placeholders[ordinal], column, outer_casts + casts)) elif self._prepared and self._server_parameter(value): - pass # bound by a later EXECUTE; the statement's gap says so + # Bound by a later EXECUTE; the statement's gap says so. + pass elif not isinstance(value, exp.Null): self._unbound.append(column) @@ -858,7 +909,7 @@ def _copies_same_column(self, value: exp.Expression, column: str, same_row: _Sam 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.name == "mysql" and isinstance(value, exp.Anonymous) \ + 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: @@ -883,8 +934,6 @@ def _row_values(self, row: Optional[exp.Expression]) -> Optional[List[exp.Expres def _is_row(node: exp.Expression) -> bool: return isinstance(node, exp.Anonymous) and str(node.this).upper() == "ROW" - # ---- comparisons ---- - def _collect_comparisons(self, tree: exp.Expression) -> None: for node in tree.walk(): if id(node) in self._assignment_nodes: @@ -895,7 +944,8 @@ def _collect_comparisons(self, tree: exp.Expression) -> None: elif isinstance(node, exp.In): for item in node.expressions: self._compare(node, node.this, item) - self._compare(node, node.args.get("query"), node.this) # %s IN (SELECT ssn FROM users) + # %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")) @@ -909,7 +959,8 @@ def _compare(self, node: exp.Expression, column: Optional[exp.Expression], if param is None: return ordinal, casts, function = param - ref = self._column_ref(column, column) # a sub-select's column is resolved in the sub-select + # 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: @@ -970,7 +1021,8 @@ def _deciding_query(self, node: exp.Expression) -> Optional[exp.Expression]: break path.append(id(parent)) child, parent = parent, parent.parent - else: # reached without a memo hit: the clause the condition is in decides + 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)): @@ -1027,12 +1079,14 @@ def _requirements(self, query: exp.Expression) -> Optional[List[exp.Expression]] 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)): - return None # it may return rows for no input row, such as a count of 0 + # 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: - return [] # a set operation or a parenthesized query that is the statement + # 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 @@ -1107,8 +1161,6 @@ def _has_outer_join(query: exp.Expression) -> bool: sources.extend(source.args.get("joins") or ()) return False - # ---- values ---- - @staticmethod def _unwrap_casts(value: exp.Expression) -> Tuple[exp.Expression, Tuple[str, ...]]: casts: List[str] = [] @@ -1142,8 +1194,6 @@ def _param(self, value: exp.Expression) -> Optional[Tuple[int, Tuple[str, ...], return ordinal, casts, function return None - # ---- names and scopes ---- - 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.""" @@ -1166,9 +1216,11 @@ def _key(self, name: Any) -> str: def _table_ref(self, table: exp.Table) -> Optional[TableRef]: if not isinstance(table.this, exp.Identifier): - return None # a function or a subquery + # A function or a subquery. + return None name = self._fold(table.this) - assert name is not None + 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 @@ -1229,7 +1281,8 @@ def add(node: Any) -> None: add(item) return if not isinstance(node, exp.Expression): - return # an absent arg can be None or False + # An absent arg can be None or False. + return if isinstance(node, (exp.From, exp.Join)): add(node.this) return @@ -1252,7 +1305,8 @@ def add(node: Any) -> None: add(query.args.get("this")) add(query.args.get("from_")) add(query.args.get("joins")) - add(query.args.get("using")) # a list for DELETE ... USING + # A list for DELETE ... USING. + add(query.args.get("using")) add(query.args.get("tables")) self._scopes[id(query)] = sources return sources @@ -1350,8 +1404,6 @@ def _resolve_annotation(self, placeholder: Placeholder, ref: ColumnRef, return ColumnRef(ref.column, only.name) return ref - # ---- results ---- - def _result_columns(self, tree: exp.Expression) -> Optional[Tuple[Optional[ColumnRef], ...]]: if isinstance(tree, exp.Select): items = tree.expressions @@ -1362,20 +1414,121 @@ def _result_columns(self, tree: exp.Expression) -> Optional[Tuple[Optional[Colum items = returning.expressions result: List[Optional[ColumnRef]] = [] for item in items: - inner = item.this if isinstance(item, exp.Alias) else item - if isinstance(inner, exp.Star) or (isinstance(inner, exp.Column) and isinstance(inner.this, exp.Star)): + if _is_star(item): return None - ref = self._column_ref(inner, inner) if isinstance(inner, exp.Column) else None - if (ref is None or ref.table is None) and isinstance(tree, exp.Select): - # Read through a derived table or CTE: follow it to its table. - ref = self._trace(inner, tree, 0) - result.append(ref if ref is not None and ref.table is not None else 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; ``None`` past a set operation, ``*``, - an expression or :data:`_MAX_DEPTH` levels.""" + 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) @@ -1385,25 +1538,25 @@ def _trace(self, node: exp.Expression, query: exp.Expression, depth: int) -> Opt if name is None: return None qualifier = self._fold(node.args.get("table")) - inner = self._derived_query(None if qualifier is None else self._dialect.metadata_key(qualifier), query) - if not isinstance(inner, exp.Select): + 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 item in inner.expressions: - # The alias is folded from its Identifier, so quoting counts. - out = self._fold(item.args.get("alias")) if isinstance(item, exp.Alias) else self._identifier(item) + 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[exp.Expression]: + 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. - A source whose alias lists column names is not followed: the list - renames the columns by position. 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.""" + ``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: @@ -1414,16 +1567,16 @@ def _derived_query(self, qualifier: Optional[str], query: exp.Expression) -> Opt for node in nodes: alias = node.args.get("alias") alias_name = self._fold(alias.this) if isinstance(alias, exp.TableAlias) else None - renamed = isinstance(alias, exp.TableAlias) and bool(alias.args.get("columns")) + 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 else node.this + 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: + if renamed is None: return None outer: Optional[exp.Expression] = query inside: Any = None @@ -1433,16 +1586,33 @@ def _derived_query(self, qualifier: Optional[str], query: exp.Expression) -> Opt for cte in (with_.expressions if with_ is not None else ()): if cte is inside: if recursive: - return None # PostgreSQL lets a RECURSIVE list read later CTEs - break # a CTE sees only the CTEs before it + # 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: - return None if cte_alias.args.get("columns") else cte.this + 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_dialect.py b/aws_advanced_python_wrapper/encryption/sql_dialect.py deleted file mode 100644 index 9a8e8690f..000000000 --- a/aws_advanced_python_wrapper/encryption/sql_dialect.py +++ /dev/null @@ -1,208 +0,0 @@ -# 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. - -"""Runs the plugin's own ``encryption_metadata`` / ``key_storage`` SQL. - -Both supported drivers (psycopg and MySQL Connector/Python) use the -``pyformat`` paramstyle, so the SQL is written once with ``%s`` placeholders. -Only a few grammar details differ by engine, and :class:`SqlDialect` holds -them. The wrapper's driver dialects manage connection lifecycle only, which is -why this module exists. -""" - -from __future__ import annotations - -import string -from abc import ABC, abstractmethod -from contextlib import closing -from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Sequence - -from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes -from aws_advanced_python_wrapper.errors import EncryptionConfigError -from aws_advanced_python_wrapper.utils.messages import Messages - -if TYPE_CHECKING: - from aws_advanced_python_wrapper.driver_dialect import DriverDialect - -Row = Dict[str, Any] - - -class SqlDialect(ABC): - """Engine-specific grammar for the plugin's own statements.""" - - name: str = "" - - #: Equality operator used in every comparison the plugin writes. - equals: str = "=" - - @abstractmethod - def upsert_clause(self, conflict_columns: Sequence[str], update_columns: Sequence[str], - extra_assignments: Sequence[str] = ()) -> str: - """The trailing upsert clause for an ``INSERT``: on a conflict over - ``conflict_columns``, overwrite ``update_columns`` from the incoming - row and apply any literal ``extra_assignments``.""" - ... - - @abstractmethod - def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int: - """Run an ``INSERT`` (without ``RETURNING``) and return the generated - ``id``.""" - ... - - @abstractmethod - def fold_identifier(self, name: str, quoted: bool) -> str: - """The name the server resolves an identifier written in SQL to. - ``name`` is the identifier without its quotes (doubled quotes undone) - and ``quoted`` says whether it was quoted.""" - ... - - @abstractmethod - def metadata_key(self, name: str) -> str: - """The form a table or column name is compared in when looking it up - in ``encryption_metadata``. Names with the same key share encryption - metadata: usually because the engine treats them as the same object, - but on MySQL with ``lower_case_table_names=0`` table names that differ - only in case share a key too.""" - ... - - @staticmethod - def for_driver_dialect(driver_dialect: DriverDialect) -> SqlDialect: - code = driver_dialect.dialect_code - if code == DriverDialectCodes.PSYCOPG: - return PG - if code == DriverDialectCodes.MYSQL_CONNECTOR_PYTHON: - return MYSQL - raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", code)) - - @staticmethod - def for_connection(conn: Any) -> SqlDialect: - """Infer the engine from a raw psycopg / mysql-connector connection or - an ``AwsWrapperConnection`` wrapping one.""" - target = getattr(conn, "target_connection", conn) - module = type(target).__module__ - if module.startswith("psycopg"): - return PG - if module.startswith("mysql.connector") or module.startswith("_mysql_connector"): - return MYSQL - raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", type(target).__qualname__)) - - @staticmethod - def for_name(name: str) -> SqlDialect: - lowered = name.lower() - if lowered in ("pg", "postgres", "postgresql", "psycopg"): - return PG - if lowered in ("mysql", "mysql-connector", "mysql-connector-python"): - return MYSQL - raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", name)) - - def __repr__(self) -> str: - return f"{type(self).__name__}()" - - -class PgSqlDialect(SqlDialect): - name = "postgresql" - # An unqualified operator resolves through search_path, where a - # user-defined "=" with a closer type match would win. Pin the built-in. - equals = "OPERATOR(pg_catalog.=)" - - 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: Any, sql: str, params: Sequence[Any]) -> int: - with closing(conn.cursor()) as cursor: - cursor.execute(f"{sql} RETURNING id", params) - row = cursor.fetchone() - # A connection opened with a dict-like row factory returns a mapping. - return int(next(iter(row.values())) if isinstance(row, Mapping) else row[0]) - - def fold_identifier(self, 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 metadata_key(self, name: str) -> str: - # Catalog names are case-sensitive: "Users" and users are two tables. - return name - - -class MySqlSqlDialect(SqlDialect): - name = "mysql" - # MySQL has no user-defined operators. - equals = "=" - - 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: Any, sql: str, params: Sequence[Any]) -> int: - with closing(conn.cursor()) as cursor: - cursor.execute(sql, params) - return int(cursor.lastrowid) - - def fold_identifier(self, name: str, quoted: bool) -> str: - # MySQL keeps identifiers as written (quoting only allows reserved words - # and special characters). Whether it folds table names depends on - # lower_case_table_names, which metadata_key allows for by comparing - # case-insensitively. - return name - - def metadata_key(self, 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() - - -_ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase) - -PG = PgSqlDialect() -MYSQL = MySqlSqlDialect() - - -def fetch_rows(conn: Any, sql: str, params: Sequence[Any] = ()) -> List[Row]: - """Run a query and return its rows as dicts keyed by lower-cased column - name. MySQL reports ``information_schema`` names in upper case on some - versions, so callers never depend on result-key case. - - Rows may 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. - """ - with closing(conn.cursor()) as cursor: - cursor.execute(sql, params) - if cursor.description is None: - return [] - names = [_lower(d[0]) for d in cursor.description] - return [{_lower(k): v for k, v in row.items()} if isinstance(row, Mapping) else dict(zip(names, row)) - for row in cursor.fetchall()] - - -def _lower(name: Any) -> Any: - return name.lower() if isinstance(name, str) else name - - -def execute(conn: Any, sql: str, params: Sequence[Any] = ()) -> int: - """Run a statement and return the affected-row count.""" - with closing(conn.cursor()) as cursor: - cursor.execute(sql, params) - return max(cursor.rowcount, 0) diff --git a/aws_advanced_python_wrapper/encryption/sql_tokenizer.py b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py index 8f505129d..8f1b255da 100644 --- a/aws_advanced_python_wrapper/encryption/sql_tokenizer.py +++ b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py @@ -60,10 +60,16 @@ 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, Union +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.sql_dialect import SqlDialect + 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. @@ -83,18 +89,10 @@ class ParamStyle(Enum): NAMED = "named" @classmethod - def of(cls, params: Any, dialect: SqlDialect) -> ParamStyle: + def of(cls, params: Any, dialect: Type[EncryptionDriverDialect]) -> ParamStyle: """The style the driver for ``dialect`` applies to ``params``, the second argument of ``execute``.""" - if dialect.name == "mysql": - # Connector/Python substitutes only for a non-empty dict, list or - # tuple. - if not params: - return cls.NONE - if isinstance(params, dict): - return cls.NAMED - return cls.POSITIONAL if isinstance(params, (list, tuple)) else cls.NONE - if params is None: + if not dialect.binds_parameters(params): return cls.NONE return cls.NAMED if isinstance(params, Mapping) else cls.POSITIONAL @@ -102,7 +100,7 @@ def of(cls, params: Any, dialect: SqlDialect) -> ParamStyle: @dataclass(frozen=True, slots=True) class ColumnRef: """A column a statement names, with names folded the way the engine folds - them (see :meth:`SqlDialect.fold_identifier`).""" + them (see :meth:`EncryptionDriverDialect.fold_identifier`).""" column: str #: The table, without any schema; ``None`` when the statement does not say @@ -153,6 +151,9 @@ class TokenizedSql: 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 @@ -171,6 +172,12 @@ class TokenizedSql: #: ``/*@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: @@ -179,78 +186,30 @@ def has_hidden_placeholders(self) -> bool: _KEYWORDS = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT", "COPY", "FROM", "EXECUTE", "LOAD"}) -# MySQL statement modifiers between the keyword and the table. They change how -# a statement runs and leave what it writes alone. The structural parser reads -# "UPDATE LOW_PRIORITY users" as a table named LOW_PRIORITY aliased users, so -# they are dropped from the normalized copy. All are reserved words except -# QUICK, which can only follow DELETE. -_MYSQL_MODIFIERS = { - "INSERT": frozenset({"LOW_PRIORITY", "HIGH_PRIORITY", "DELAYED", "IGNORE"}), - "REPLACE": frozenset({"LOW_PRIORITY", "DELAYED"}), - "UPDATE": frozenset({"LOW_PRIORITY", "IGNORE"}), - "DELETE": frozenset({"LOW_PRIORITY", "QUICK", "IGNORE"}), -} - -# ---- lexers ---- -# -# Alternatives are tried in order at each token boundary. The ``*_end`` groups -# capture a closing quote, empty when the literal runs to the end of the text. - -_PG_TOKEN = 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) - -_MYSQL_TOKEN = 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) - _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 engine's identifier quote. Every [\w.]+ reference +# 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) -_PG_REF_PART = re.compile(r'(?P\w+)|"(?P(?:[^"]|"")+)"') -_MYSQL_REF_PART = re.compile(r"(?P\w+)|`(?P(?:[^`]|``)+)`") +_REF_PARTS = { + '"': re.compile(r'(?P\w+)|"(?P(?:[^"]|"")+)"'), + "`": re.compile(r"(?P\w+)|`(?P(?:[^`]|``)+)`"), +} -# A MySQL charset introducer (_binary, _utf8mb4, ...) and the space after it, +# A charset introducer (_binary, _utf8mb4, ...) and the space after it, # directly before a placeholder. _INTRODUCER = re.compile(r"(?[A-Za-z0-9]+)\s*\Z") -_MYSQL_CHARSETS = 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", -}) _WORD = re.compile(r"[^\W\d][\w$]*") _COMMENT_DELIMITER = re.compile(r"/\*|\*/") # The drivers' own placeholder patterns. -_PSYCOPG_PLACEHOLDER = re.compile(r"%(?:\(([^)]+)\).|.)") # no DOTALL, as in psycopg +# No DOTALL, as in psycopg. +_PSYCOPG_PLACEHOLDER = re.compile(r"%(?:\(([^)]+)\).|.)") _MYSQL_POSITIONAL = re.compile(r"%s") _MYSQL_NAMED = re.compile(r"%\((?P[^)]+)\)(?P[diouxXeEfFgGcrs%])") @@ -260,35 +219,39 @@ def has_hidden_placeholders(self) -> bool: @dataclass class _Lexed: - hidden_spans: List[Tuple[int, int]] # literals, quoted identifiers, comments; sorted + # 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]] - separators: List[int] # offsets of the ";" between statements + # Offsets of the ";" between statements. + separators: List[int] unterminated: bool = False executable_comment: bool = False - # Words inside MySQL executable comments, which the server runs. + # 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: SqlDialect, style: ParamStyle) -> TokenizedSql: +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(f"sql must be a str, not {type(sql).__name__}") - mysql = dialect.name == "mysql" - lexed = _lex(sql, _MYSQL_TOKEN if mysql else _PG_TOKEN, mysql=mysql) + raise TypeError(Messages.get_formatted("SqlTokenizer.SqlNotStr", type(sql).__name__)) + lexed = _lex(sql, dialect) edits: List[_Edit] = [] - if mysql: - placeholders, driver_error = _mysql_placeholders(sql, style, lexed, edits) - placeholders = _attach_introducers(sql, lexed, placeholders, edits) - else: + 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: @@ -297,21 +260,26 @@ def tokenize(sql: str, dialect: SqlDialect, style: ParamStyle) -> TokenizedSql: # 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) - if mysql: - edits.extend(_mysql_rewrites(words, bounds)) + 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 for w in lexed.executable_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), ) @@ -324,8 +292,6 @@ def normalized_ordinal(name: Optional[str]) -> Optional[int]: return int(digits) if digits.isascii() and digits.isdigit() else None -# ---- driver placeholders ---- -# # The error texts never quote the SQL: a rejected "%(...)x" sequence can sit # inside a literal holding a value. @@ -396,7 +362,7 @@ def _overlaps(spans: List[Tuple[int, int]], start: int, end: int) -> bool: return i + 1 < len(spans) and spans[i + 1][0] < end -def _attach_introducers(sql: str, lexed: _Lexed, placeholders: List[Placeholder], +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), @@ -409,7 +375,7 @@ def _attach_introducers(sql: str, lexed: _Lexed, placeholders: List[Placeholder] 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 _MYSQL_CHARSETS \ + 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()}") @@ -417,9 +383,7 @@ def _attach_introducers(sql: str, lexed: _Lexed, placeholders: List[Placeholder] return result -# ---- annotations ---- - -def _attach_annotations(sql: str, dialect: SqlDialect, lexed: _Lexed, +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) @@ -439,14 +403,15 @@ def _attach_annotations(sql: str, dialect: SqlDialect, lexed: _Lexed, return result -def _annotation_ref(text: str, dialect: SqlDialect) -> Optional[ColumnRef]: - mysql = dialect.name == "mysql" - part_re, quote = (_MYSQL_REF_PART, "`") if mysql else (_PG_REF_PART, '"') +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): - parts.append("") # an empty part, as in ".c" or "t..c" + # An empty part, as in ".c" or "t..c". + parts.append("") else: m = part_re.match(text, pos) if m is None: @@ -463,29 +428,34 @@ def _annotation_ref(text: str, dialect: SqlDialect) -> Optional[ColumnRef]: 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. - table = next((part for part in reversed(parts[:-1]) if part), None) - return ColumnRef(column=parts[-1], table=table) - + for part in reversed(parts[:-1]): + if part: + return ColumnRef(column=parts[-1], table=part) + return ColumnRef(column=parts[-1], table=None) -# ---- lexing ---- -def _lex(sql: str, token_re: re.Pattern, mysql: bool) -> _Lexed: +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) - assert m is not None # "other" matches any character + # 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 not mysql: + 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 mysql and (sql.startswith("/*!", pos) or sql.startswith("/*M!", pos)): + if dialect.executable_comments and (sql.startswith("/*!", pos) or sql.startswith("/*M!", pos)): lexed.executable_comment = True - lexed.executable_words.extend(w.upper() for w in _WORD.findall(sql, pos, end)) + lexed.executable_words.extend(_WORD.findall(sql, pos, end)) lexed.block_comments.append((pos, end)) lexed.hidden_spans.append((pos, end)) elif kind == "dollar": @@ -498,6 +468,9 @@ def _lex(sql: str, token_re: re.Pattern, mysql: bool) -> _Lexed: 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)) @@ -546,14 +519,44 @@ def _statement_bounds(words: List[Tuple[str, int, int]], separators: List[int]) 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(next((w for w, _, _ in words[begin:end] if w), "") for begin, end in bounds) + 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]): + if word in ("STDIN", "STDOUT") and sql[start] == "(": + edits.append((start, start, "WITH ")) + return edits -def _mysql_rewrites(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> List[_Edit]: +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 = _MYSQL_MODIFIERS.get(word) + modifiers = statement_modifiers.get(word) if modifiers is None: continue if word == "REPLACE": diff --git a/aws_advanced_python_wrapper/encryption/type_marker.py b/aws_advanced_python_wrapper/encryption/type_marker.py index 597825718..34d080914 100644 --- a/aws_advanced_python_wrapper/encryption/type_marker.py +++ b/aws_advanced_python_wrapper/encryption/type_marker.py @@ -18,6 +18,8 @@ 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 @@ -68,7 +70,7 @@ class TypeMarker: 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(f"Unknown type marker: {value!r}") + raise ValueError(Messages.get_formatted("TypeMarker.UnknownMarker", value)) return value @classmethod 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/mysql_driver_dialect.py b/aws_advanced_python_wrapper/mysql_driver_dialect.py index e265b934d..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, @@ -224,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 c1d656176..0d64bf0ed 100644 --- a/aws_advanced_python_wrapper/pep249_methods.py +++ b/aws_advanced_python_wrapper/pep249_methods.py @@ -56,6 +56,12 @@ 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) @@ -74,7 +80,7 @@ class DbApiMethod(Enum): ACCEPTS_STRATEGY = (39, "accepts_strategy", True) # Special marker for all methods - ALL = (40, "*", 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 63d86dc74..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, @@ -179,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_service.py b/aws_advanced_python_wrapper/plugin_service.py index a97f723cc..18be02d7b 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 \ @@ -890,7 +892,8 @@ class PluginCallContext: 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``. Changing either object in place is not allowed, and + 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. @@ -904,6 +907,17 @@ 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)) + 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. @@ -945,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 @@ -961,6 +976,7 @@ class PluginManager(CanReleaseResources): ReadWriteSplittingPluginFactory: 300, SimpleReadWriteSplittingPluginFactory: 310, GdbReadWriteSplittingPluginFactory: 320, + KmsEncryptionPluginFactory: 390, FailoverPluginFactory: 400, FailoverV2PluginFactory: 410, GdbFailoverPluginFactory: 420, 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 a56e4a847..157a4d9b0 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 @@ -547,36 +547,127 @@ MonitorService.StuckMonitorDetected=[MonitorService] Stuck monitor detected for 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 encryption_kms_region, or the AWS_REGION or AWS_DEFAULT_REGION environment variable. +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.MissingArgument=[KeyManagementUtility] connection, kms_client, and config are required. +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 {:.3f}s: {} +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). -SqlDialect.UnsupportedDriver=[SqlDialect] The kms_encryption plugin does not support driver {}; use psycopg or mysql-connector-python. +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 a7e53f67b..5999a5386 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -281,8 +281,8 @@ class WrapperProperties: ) ENCRYPTION_AUDIT_LOGGING_ENABLED = WrapperProperty( "encryption_audit_logging_enabled", - "Log an audit record for every key-management, encryption, and decryption operation " - "(used by the kms_encryption plugin).", + "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( @@ -292,6 +292,13 @@ class WrapperProperties: "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." @@ -998,18 +1005,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 1a10d88a1..81401db15 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -398,7 +398,7 @@ 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, @@ -422,6 +422,36 @@ def executemany( 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()) diff --git a/docs/README.md b/docs/README.md index a1ceef710..1d25240bc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -27,6 +27,7 @@ - [Reader Selection Strategies](using-the-python-wrapper/ReaderSelectionStrategies.md) - [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) + - [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/PluginService.md b/docs/development-guide/PluginService.md index 60a40a1ae..0f81eb793 100644 --- a/docs/development-guide/PluginService.md +++ b/docs/development-guide/PluginService.md @@ -48,6 +48,7 @@ Changing `args` or `kwargs` in place is not allowed, and the caller's own object `current_call_context` is set whenever a plugin handles one of these two methods through the wrapper. A plugin that must change the arguments, rather than one that may, should raise when it finds `None` instead of calling `execute_func` with the arguments unchanged. +Before it assigns, a plugin can call `context.holds(args, kwargs)`, which returns `True` only when the context holds the argument objects the plugin was handed (each positional argument and each keyword value, compared with `is`), so the plugin never replaces another call's arguments. A replacement lasts until the plugin that made it returns. A plugin before it that calls `execute_func` again starts again from the arguments it saw, so the replacement is made once per run. diff --git a/docs/using-the-python-wrapper/PluginChainCompatibility.md b/docs/using-the-python-wrapper/PluginChainCompatibility.md index 02b543843..67fdd7693 100644 --- a/docs/using-the-python-wrapper/PluginChainCompatibility.md +++ b/docs/using-the-python-wrapper/PluginChainCompatibility.md @@ -15,6 +15,7 @@ a chain you haven't used before. | Plugin | Requires | Why | |---------------------|-----------------------------------|-----| | `read_write_splitting` | `failover_v2` (not `failover`) | `failover_v2` starts the cluster topology monitor on the **initial** connect. With plain `failover`, the host list stays at `{writer-only}` until a later failover signal fires, and `conn.read_only = True` flips silently fall back to the writer rather than splitting to a reader. | +| `kms_encryption` | to run before `failover`, `failover_v2` and `gdb_failover` (the default order while `auto_sort_wrapper_plugin_order` is on) | Listed after a failover plugin with auto-sort off, the errors it raises from `execute()` and the fetch methods reach the application wrapped in the failover plugin's `AwsWrapperError` instead of their own classes. With the failover plugin's `preserve_driver_exception_type` on, they keep their own classes. | ## Driver-specific incompatibilities diff --git a/docs/using-the-python-wrapper/SqlAlchemySupport.md b/docs/using-the-python-wrapper/SqlAlchemySupport.md index b4d5afd76..bda86ba98 100644 --- a/docs/using-the-python-wrapper/SqlAlchemySupport.md +++ b/docs/using-the-python-wrapper/SqlAlchemySupport.md @@ -182,11 +182,14 @@ Plugins are configured identically to non-SA usage — via the `plugins` connect | [Fastest Response Strategy Plugin](using-plugins/UsingTheFastestResponseStrategyPlugin.md) | `fastest_response_strategy` | ✓ | | [Blue/Green Deployment Plugin](using-plugins/UsingTheBlueGreenPlugin.md) | `bg` | ✓ | | [Limitless Plugin](using-plugins/UsingTheLimitlessPlugin.md) | `limitless` | ✓ | +| [KMS Encryption Plugin](using-plugins/UsingTheKmsEncryptionPlugin.md) | `kms_encryption` | ✓ | | [Read Write Splitting Plugin](using-plugins/UsingTheReadWriteSplittingPlugin.md) | `read_write_splitting` | ✗ | | [Simple Read Write Splitting Plugin](using-plugins/UsingTheSimpleReadWriteSplittingPlugin.md) | `srw` | ✗ | Read/write splitting is **not** supported with SQLAlchemy: the plugins switch instances by setting `read_only` on a long-lived connection, and there is currently no routing of SQLAlchemy's `execution_options(...readonly=True)` to the wrapper's `read_only` attribute. For read/write workloads, use SQLAlchemy's own session binding — see the [official SQLAlchemy documentation on the Session API](https://docs.sqlalchemy.org/en/20/orm/session_api.html). +The KMS Encryption Plugin works with synchronous engines only, and its guide's [Using SQLAlchemy and Django](using-plugins/UsingTheKmsEncryptionPlugin.md#using-sqlalchemy-and-django) section gives the column type to declare. + ## Async usage > [!NOTE]\ diff --git a/docs/using-the-python-wrapper/UsingThePythonWrapper.md b/docs/using-the-python-wrapper/UsingThePythonWrapper.md index 384dc1fb5..6b1ed3128 100644 --- a/docs/using-the-python-wrapper/UsingThePythonWrapper.md +++ b/docs/using-the-python-wrapper/UsingThePythonWrapper.md @@ -107,6 +107,7 @@ The AWS Advanced Python Wrapper has several built-in plugins that are available | [Fastest Response Strategy Plugin](./using-plugins/UsingTheFastestResponseStrategyPlugin.md) | `fastest_response_strategy` | Aurora | A host selection strategy plugin that uses a host monitoring service to monitor each reader host's response time and choose the host with the fastest response. | None | | [Blue/Green Deployment Plugin](./using-plugins/UsingTheBlueGreenPlugin.md) | `bg` | Aurora,
RDS Instance | Enables client-side Blue/Green Deployment support. | None | | [Limitless Plugin](./using-plugins/UsingTheLimitlessPlugin.md) | `limitless` | Aurora | Enables client-side load-balancing of Transaction Routers on Amazon Aurora Limitless Databases. | None | +| [KMS Encryption Plugin](./using-plugins/UsingTheKmsEncryptionPlugin.md) | `kms_encryption` | Any database | Encrypts the values an application writes to configured columns, with data keys protected by AWS Key Management Service (KMS), and decrypts them when they are read back. Every encrypted column also needs a database-side trigger. | The `encryption` extra (`pip install "aws-advanced-python-wrapper[encryption]"`) and [valid AWS credentials](./AwsCredentials.md) | In addition to the built-in plugins, you can also create custom plugins more suitable for your needs. For more information, see [Custom Plugins](../development-guide/LoadablePlugins.md#using-custom-plugins). diff --git a/docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md b/docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md new file mode 100644 index 000000000..317924181 --- /dev/null +++ b/docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md @@ -0,0 +1,657 @@ +# KMS Encryption Plugin + +The KMS Encryption Plugin (`kms_encryption`) encrypts the values an application binds for configured columns before the driver sends them, and decrypts them when they are read back. +Each column has its own data key, which the database stores only in a form encrypted by an AWS Key Management Service (KMS) master key, so neither the plaintext nor a usable data key reaches the database. + +The plugin works with the synchronous wrapper, on PostgreSQL with psycopg and on MySQL with MySQL Connector/Python, on Python 3.10 to 3.14. +It has no async support. + +> [!WARNING]\ +> Every encrypted column needs a database-side trigger. +> The plugin sees only the statements sent on connections that enable it, and it finds encrypted columns by reading the SQL, so some statements reach the database without it (see [What the plugin does not see](#what-the-plugin-does-not-see)). +> The trigger runs in the database and rejects an `INSERT` or `UPDATE` that stores anything but a valid encrypted value in the column. +> See [Enforce encryption in the database](#enforce-encryption-in-the-database). + +## Prerequisites + +- Install the `encryption` extra, which adds `cryptography` and `sqlglot`, for PostgreSQL and MySQL alike: `pip install "aws-advanced-python-wrapper[encryption]"`. + Install the target driver (`psycopg` or `mysql-connector-python`) as usual. + With any other driver, connecting raises `EncryptionConfigError`. +- AWS credentials, found as [AWS Credentials](../AwsCredentials.md) describes. + At run time the application needs only `kms:Decrypt` on the master keys it uses (see [Hardening](#hardening)). +- Each encrypted column is binary: `BYTEA` on PostgreSQL, `VARBINARY` or `BLOB` on MySQL. + A stored value is 65 bytes longer than the encoded value, which for a string is its UTF-8 bytes, so an 11-character ASCII string takes 76 bytes; size a `VARBINARY` column for the longest value (MySQL refuses a longer one with error 1406 and stores nothing). +- On PostgreSQL, a `TEXT` column, or a `VARCHAR` wide enough for it, accepts the plugin's writes and stores each encrypted value as hex text, which the plugin then refuses to read with `IntegrityCheckError`. + Declare the column `BYTEA`, or convert it with `ALTER TABLE ALTER COLUMN TYPE bytea USING ::bytea`. + On MySQL a text column refuses the write (error 1366). +- The two metadata tables, `encryption_metadata` and `key_storage`, in the schema named by `encryption_metadata_schema` (default `encrypt`). + An administrator creates them once with the SQL in [Create the metadata tables](#create-the-metadata-tables). + On MySQL that account needs the global `CREATE` privilege, which an application user usually lacks (error 1044). + Create them exactly as that SQL does. + The plugin doesn't check the schema: a missing table or column makes its metadata reads raise `MetadataError`, and a missing primary key, unique constraint or foreign key goes unnoticed. + To check it, call `KeyManagementUtility.validate_schema()` after you create the tables: it returns one message per missing table, column, key or foreign key, or an empty list, and it needs only `SELECT` on the schema. +- At run time the plugin only reads the metadata schema, so the application's database user needs only `SELECT` on it, besides its privileges on its own tables. + On MySQL the account that installs the trigger SQL needs `SELECT` there too, and the application user needs no grant for the trigger. + On PostgreSQL the trigger runs with the rights of the role whose statement fires it, so every role that writes an encrypted column needs `USAGE` on the metadata schema and `SELECT` on `key_storage` and `encryption_metadata`; without them each such write fails with a `permission denied` error. +- `key_storage` holds the only copy of each column's encrypted data key and its HMAC key, so back it up with the data. + Without its row, a column's values can't be read (`InvalidKeyMetadataError`). +- The HMAC key in `key_storage` is stored unencrypted. + A role that can read `key_storage` can compute a tag the trigger accepts, so it can store values that pass the trigger and then fail to decrypt. + A role that can write it can replace a column's HMAC key with one of its own and forge values the trigger accepts. + Neither can decrypt a stored value, because the data key is stored encrypted under the master key. + Grant `SELECT` on `key_storage` only to the roles that need it (the application's role and, on MySQL, the account that installed the trigger SQL), and write access only to the administrator who runs `KeyManagementUtility`. + +## Create the metadata tables + +Create the schema and both tables once, before setting up any encrypted column. +The statements below use the default schema name `encrypt`; replace it if `encryption_metadata_schema` is set to something else. +On MySQL a schema is a database, so `CREATE SCHEMA` creates a database named `encrypt`. +`encryption_metadata.key_id` references `key_storage.id`, not `key_storage.key_id`. + +```sql +-- PostgreSQL +CREATE SCHEMA IF NOT EXISTS encrypt; + +CREATE TABLE encrypt.key_storage ( + id SERIAL PRIMARY KEY, + key_id VARCHAR(255) UNIQUE NOT NULL, + name VARCHAR(255) NOT NULL, + master_key_arn VARCHAR(512) NOT NULL, + encrypted_data_key TEXT NOT NULL, + hmac_key BYTEA NOT NULL, + key_spec VARCHAR(50) DEFAULT 'AES_256', + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + last_used_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE encrypt.encryption_metadata ( + table_name VARCHAR(255) NOT NULL, + column_name VARCHAR(255) NOT NULL, + encryption_algorithm VARCHAR(50) NOT NULL, + key_id INTEGER NOT NULL, + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (table_name, column_name), + FOREIGN KEY (key_id) REFERENCES encrypt.key_storage(id) +); +``` + +```sql +-- MySQL +CREATE SCHEMA IF NOT EXISTS encrypt; + +CREATE TABLE encrypt.key_storage ( + id INT AUTO_INCREMENT PRIMARY KEY, + key_id VARCHAR(255) UNIQUE NOT NULL, + name VARCHAR(255) NOT NULL, + master_key_arn VARCHAR(512) NOT NULL, + encrypted_data_key TEXT NOT NULL, + hmac_key VARBINARY(32) NOT NULL, + key_spec VARCHAR(50) DEFAULT 'AES_256', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + last_used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE encrypt.encryption_metadata ( + table_name VARCHAR(255) NOT NULL, + column_name VARCHAR(255) NOT NULL, + encryption_algorithm VARCHAR(50) NOT NULL, + key_id INT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (table_name, column_name), + FOREIGN KEY (key_id) REFERENCES encrypt.key_storage(id) +); +``` + +Then install the trigger SQL, as [Enforce encryption in the database](#enforce-encryption-in-the-database) describes, and set up each column with `KeyManagementUtility`. + +## Set up an encrypted column + +`KeyManagementUtility` creates a master key in KMS, generates the column's data key and records the column in the metadata tables. +Run it as an administrator, from a setup or migration script: + +```python +import boto3 +import psycopg + +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) +kms = KeyManager.create_kms_client(boto3.Session(), config) + +with psycopg.connect("host=db.example.com dbname=mydb user=admin password=...") as conn: + utility = KeyManagementUtility(conn, kms, config) + master_key_arn = utility.create_master_key("users.ssn encryption") + utility.initialize_encryption_for_column("users", "ssn", master_key_arn) + conn.commit() +``` + +On MySQL, open the connection with `mysql.connector.connect(...)` instead; the rest is the same. + +- Call `conn.commit()`. + The utility runs its statements in the connection's transaction and never commits. + psycopg's `with` block commits when it ends without an error, but mysql-connector's closes the connection without committing, so on MySQL the setup is lost without `commit()` and the KMS key it created is left unused. +- To use an existing KMS key, pass its ARN to `initialize_encryption_for_column` and skip `create_master_key`. +- The utility sets up and rotates `AES-256-GCM` columns only: any other `algorithm` raises `InvalidAlgorithmError` before any KMS call or write. + The plugin still reads and writes an `AES-128-GCM` column that was set up before. +- Add the master key's ARN to `encryption_allowed_master_key_arns` on the application's connections, or the plugin refuses to read or write the column (`UnauthorizedMasterKeyError`). +- Run the utility on a DB-API connection. + From a SQLAlchemy engine, keep the connection `engine.raw_connection()` returns and give the utility its `driver_connection`, or pass `props={"wrapper_driver_dialect": "psycopg"}` (`"mysql-connector-python"` on MySQL; see [driver dialect codes](../DriverDialects.md#list-of-available-driver-codes)). + After `commit()`, close the connection `raw_connection()` returned, not its `driver_connection`, so the pool gets a working connection back. + With a mysql-connector pooled connection (`PooledMySQLConnection`), pass `props={"wrapper_driver_dialect": "mysql-connector-python"}`. +- To limit how long each utility statement runs, put `socket_timeout` (in seconds) in `props`. + It applies only when you pass a psycopg or mysql-connector connection itself. + On an `AwsWrapperConnection`, set `socket_timeout` on that connection instead; on any other object, such as a `PooledMySQLConnection` or the connection `raw_connection()` returns, the utility doesn't limit its statements. + When a statement runs longer, the call raises `KeyManagementError` or `MetadataError`, and the connection can't be used again: open a new connection and run the setup again (a master key that `create_master_key` already created stays in KMS). + On mysql-connector's C extension, `socket_timeout` can't stop the statement: the error comes after up to twice `socket_timeout`, and the connection must stay open until the statement ends, so don't set `socket_timeout`, or connect with `use_pure=True` (not with `sjis`, `cp932`, `big5` or `gbk`, which need the C extension). +- The utility doesn't create the trigger. + Create the column's trigger in the same change, as [Enforce encryption in the database](#enforce-encryption-in-the-database) describes, and check that it exists in the engine's trigger list. + The version queries there show only that the trigger SQL is installed. + +```sql +-- PostgreSQL: tgenabled is O while the trigger is enabled, D after ALTER TABLE ... DISABLE TRIGGER +SELECT tgname, tgenabled FROM pg_trigger WHERE tgrelid = 'users'::regclass AND NOT tgisinternal; +-- MySQL: the BEFORE INSERT and BEFORE UPDATE triggers of each column +SELECT TRIGGER_NAME, ACTION_TIMING, EVENT_MANIPULATION FROM information_schema.TRIGGERS + WHERE EVENT_OBJECT_SCHEMA = DATABASE() AND EVENT_OBJECT_TABLE = 'users'; +``` + +### Rotate a column's data key + +```python +result = utility.rotate_data_key_and_reencrypt("users", "ssn", "id", master_key_arn) +``` + +`rotate_data_key(table_name, column_name, new_master_key_arn=None)` gives a column that holds no value a new data key, encrypted by `new_master_key_arn`; call `conn.commit()` after it. +On a column that holds a value it raises `KeyManagementError` before any change, because the values already stored would stay under the data key the rotation means to retire. + +For a column with data, `rotate_data_key_and_reencrypt(table_name, column_name, primary_key_column, new_master_key_arn=None, batch_size=1000)` checks that every value is under the column's current key and that the table and both columns exist, stores the new key row, switches the column to it and commits. +Then it re-encrypts the values in primary key order, `batch_size` rows (1 to 100000) per transaction, and returns a `DataKeyReencryptionResult` with the counts of re-encrypted, already current and unmatched values. +Run it in a maintenance window on the driver's own connection, with no open transaction: it commits as it goes, refuses an `AwsWrapperConnection`, and sets the connection's autocommit setting back at the end. +`primary_key_column` names a unique `NOT NULL` column; on PostgreSQL it needs a built-in type or a domain over one. +Each name must be a plain identifier of at most 64 characters, and the table name can be `schema.table`. +Reads of the rows that aren't converted yet keep working, because each value names the key row it was written with. +If a batch fails, the committed batches stay, and the error names the earlier key id. +Finish with `reencrypt_remaining_rows(table_name, column_name, primary_key_column, old_key_ids, batch_size=1000)`, which needs `encryption_allowed_master_key_arns`, skips the values already under the current key and leaves the values under no listed key as they are. +Writes from connections whose metadata hasn't refreshed yet fail at the trigger until the refresh (see below), so run `reencrypt_remaining_rows` again after `encryption_metadata_cache_refresh_interval_sec`. +The earlier key row and its KMS key are never deleted. +Leaving out `new_master_key_arn` keeps the column's current master key, which needs `encryption_allowed_master_key_arns` in the utility's configuration. +To rotate onto another master key, add its ARN to `encryption_allowed_master_key_arns` before the rotation (on the application's connections, and in the utility's configuration if it has the parameter); the utility refuses an unlisted master key before any change. +Keep the old ARN listed, and keep the application's `kms:Decrypt` permission on that key, while any row or backup holds data under it. +If the old ARN leaves `encryption_allowed_master_key_arns` too early, a read of such a value raises `UnauthorizedMasterKeyError` before any KMS call; without `kms:Decrypt`, the read raises `KeyManagementError` with the error code `AccessDeniedException` and the HTTP status once the old data key has left the data-key cache. + +To rotate a master key itself, use KMS automatic or on-demand key rotation: the key keeps its ARN, and KMS still decrypts the data keys encrypted before the rotation. +When `key_storage.master_key_arn` holds an alias and the alias is moved to another key, KMS refuses to decrypt the data keys encrypted under the earlier key, and the columns that use them can be neither read nor written until the alias points back. + +A connection opened before the rotation keeps the old data key until its next metadata refresh (`encryption_metadata_cache_refresh_interval_sec`, 300 seconds by default) or until its cached metadata expires. +Until then its writes to the column use the old key, and the trigger, which checks each new value against the column's current key, rejects them. +To pick up a rotation sooner, set `encryption_metadata_cache_refresh_interval_sec` to a smaller value above `0` and keep `encryption_metadata_cache_expiration_sec` above it. + +## Enable the plugin + +To enable the KMS Encryption Plugin, add the plugin code `kms_encryption` to the [`plugins`](../UsingThePythonWrapper.md#connection-plugin-manager-parameters) value. +This example connects to PostgreSQL with the default plugins and `kms_encryption`: + +```python +import psycopg + +from aws_advanced_python_wrapper import AwsWrapperConnection, release_resources + +try: + with AwsWrapperConnection.connect( + psycopg.Connection.connect, + "host=db.example.com dbname=mydb user=app password=...", + plugins="initial_connection,aurora_connection_tracker,failover_v2,host_monitoring_v2,kms_encryption", + encryption_kms_region="us-east-1", + encryption_allowed_master_key_arns="arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", + autocommit=True, + ) as conn, conn.cursor() as cur: + cur.execute("INSERT INTO users (name, ssn) VALUES (%s, %s)", ("Jane Doe", "000-00-0000")) + cur.execute("SELECT ssn FROM users WHERE name = %s", ("Jane Doe",)) + print(cur.fetchone()) +finally: + release_resources() +``` + +- `plugins` replaces the default plugin list, so list the plugins you use together with `kms_encryption`. + The example lists the PostgreSQL defaults; on MySQL the defaults are the same without `host_monitoring_v2`. +- Keep `auto_sort_wrapper_plugin_order` on (the default), or list `kms_encryption` before the failover plugins, so the plugin's errors keep their class (see [Plugin Chain Compatibility](../PluginChainCompatibility.md)). +- SQLAlchemy: pass the list as `connect_args={"plugins": "..."}`, or as `?wrapper_plugins=...` in the URL. + SQLAlchemy removes a `?plugins=` query parameter, so with it the plugin is silently not loaded (see [SQLAlchemy Support](../SqlAlchemySupport.md)). +- Django (MySQL only): put `"plugins": "..."` and the `encryption_*` parameters in the database's `OPTIONS` (see [Django Support](../DjangoSupport.md)). +- There is no `aws_credentials_provider` parameter, and the driver rejects it at connect: use `aws_profile` or the default credential chain. +- Each connection loads the metadata at its first statement, decrypts the data keys it needs with KMS, and keeps up to two background threads until it closes. + The metadata load, each background refresh and the first read of a value written under an earlier key open a separate short-lived connection with the application connection's properties. + When `socket_timeout` is set, it also limits each statement the plugin runs on these connections: a metadata load that runs longer raises `MetadataError`, a `key_storage` lookup raises `KeyManagementError`, and a background refresh logs a warning. + On mysql-connector's C extension, the plugin can't stop such a statement: the error comes after up to twice `socket_timeout`, and that connection stays open until the statement ends, so for that time the application uses one more connection. + Under any connection limit (a PostgreSQL role's `CONNECTION LIMIT`, MySQL's `max_user_connections`, the server's `max_connections`), leave room for one more connection per application connection (with `encryption_metadata_cache_enabled` off, one for each thread running a statement on that connection at the same time); otherwise the first statement raises `MetadataError`. + If the limit is reached later, each background refresh logs a warning, and once the cached copy expires, every statement that names a table raises `MetadataError` until a connection can be opened again. + A background refresh can run while a read looks up a `key_storage` row, so for that moment the application connection uses two short-lived connections, plus one for each other thread reading through it at the same time. + A read that finds no room raises `KeyManagementError`. + An application that opens a connection per request should use a connection pool, or Django's `CONN_MAX_AGE`. +- Closing the connection stops the plugin's background threads, wipes its cached data keys and closes its KMS client. + If one of these steps raises, the plugin logs a warning that names it and still runs the others, and `close()` doesn't raise for it. +- In a process that forks after using the plugin (a gunicorn or Celery prefork worker, `multiprocessing` with the `fork` start method), the child has none of the plugin's background threads. + Open new connections in the child, which start their own, and don't use a connection the parent opened. + While a connection that used the plugin is open, its threads run, so on Python 3.12 and later each `fork()` emits a `DeprecationWarning`; the `forkserver` and `spawn` start methods avoid it. + +## Configuration Parameters + +| Parameter | Value | Required | Description | Default Value | +|---|---|---|---|---| +| `encryption_kms_region` | String | Yes, unless every KMS key or alias ARN in `encryption_allowed_master_key_arns` names one region | AWS region of the KMS calls. When it isn't set, the plugin takes the region of the key and alias ARNs in `encryption_allowed_master_key_arns` (alias names such as `alias/app-key` and bare key ids name no region). With no ARN region, or ARNs in more than one region, connecting raises `EncryptionConfigError`. The `AWS_REGION` and `AWS_DEFAULT_REGION` environment variables and the AWS config file aren't read. When it is set and the allow-list holds a key or alias ARN in another region, the plugin logs a warning once, because KMS calls with that key fail. | `None` | +| `encryption_kms_endpoint` | String | No | KMS endpoint URL override. It must name a KMS endpoint you trust, over HTTPS, because every data key comes back through it. | `None` | +| `encryption_allowed_master_key_arns` | String or list | Yes | The master key ARNs the plugin may use, as a comma-separated string or a list. Each must equal a `key_storage.master_key_arn` value exactly; a data key encrypted by any other master key is refused before KMS is called. | `None` | +| `encryption_metadata_schema` | String | No | Schema (database, on MySQL) of the `encryption_metadata` and `key_storage` tables: a letter or `_`, then letters, digits and `_`. | `encrypt` | +| `encryption_metadata_cache_enabled` | Boolean | No | Keep the metadata in memory. When off, each statement that names a table reads the tables on one new connection, which closes before the statement returns. | `True` | +| `encryption_metadata_cache_expiration_sec` | Float | No | How long the cached metadata answers lookups, in seconds. Keep it above `encryption_metadata_cache_refresh_interval_sec`. Once the cached copy has expired, the next statement that names a table reads the tables again on one new connection and caches them, whether or not the background refresh is on; if they can't be read, that statement raises `MetadataError` (see [Errors](#errors)). | `3600.0` | +| `encryption_metadata_cache_refresh_interval_sec` | Float | No | How often the metadata is refreshed in the background, in seconds. `0` turns the background refresh off. | `300.0` | +| `encryption_data_key_cache_enabled` | Boolean | No | Keep decrypted data keys in memory. When off, the plugin calls KMS `Decrypt` once per data key for each `execute`, `executemany` and fetch call, and for each value a `for` loop reads, which adds latency and cost and can reach KMS request-rate limits; leave it on in production. | `True` | +| `encryption_data_key_cache_max_size` | Integer | No | Most decrypted data keys held in memory. | `1000` | +| `encryption_data_key_cache_expiration_sec` | Float | No | How long a decrypted data key stays cached after the plugin caches it, in seconds. Using a key doesn't extend it. | `300.0` | +| `encryption_key_management_max_retries` | Integer | No | Retries of a throttled or failed KMS call before it raises `KeyManagementError`. Each attempt waits up to 5 seconds to connect and 10 seconds for KMS to answer, so at the default a KMS endpoint that stops answering holds a statement for about 40 seconds before the error. | `3` | +| `encryption_key_management_retry_backoff_base_sec` | Float | No | Base delay of the exponential backoff between KMS retries, in seconds. | `0.1` | +| `encryption_audit_logging_enabled` | Boolean | No | Accepted. When `True`, each connection logs one warning that no audit records are written: "[KmsEncryptionPlugin] encryption_audit_logging_enabled is True, but this release writes no audit records." | `False` | +| `encryption_return_unverified_data` | Boolean | No | **Not for production.** See [Reading data written before encryption](#reading-data-written-before-encryption). | `False` | +| `encryption_fail_on_unmapped_parameter` | Boolean | No | Refuse a statement with parameters on a table with encrypted columns when the plugin can't pair each parameter with its column, and refuse SQL passed to `execute` or `executemany` that the plugin can't analyze at all while any column is encrypted (see **Refused by default** in [What the plugin encrypts and decrypts](#what-the-plugin-encrypts-and-decrypts)). `False` runs such a statement unchanged, with a warning when it writes or can't be analyzed, except a psycopg `cursor.copy()` that the plugin can't parse and that can write the table, which it still refuses. A string other than `"true"` in any case, or a non-string value that Python treats as false, such as `False`, `0` or `None`, turns the refusal off. | `True` | + +Boolean parameters are on for the string `"true"` in any case and for any non-string value that Python treats as true, such as `True` or a non-zero number. +The settings are read when the connection is created, and a missing or invalid value raises `EncryptionConfigError`, whose message names the parameter. +Two setup failures show only at the first statement (see [Errors](#errors)). + +## What the plugin encrypts and decrypts + +**Writes.** On `execute` and `executemany`, the plugin encrypts each bound parameter that goes into an encrypted column: `INSERT` (multi-row `VALUES` included), `UPDATE`, upserts (`ON CONFLICT`, `ON DUPLICATE KEY UPDATE`), `MERGE` and data-modifying CTEs. +Parameters can be positional (`%s`) or named (`%(name)s`); a repeated `%(name)s` is encrypted once, with the first column's key, and a name also used for a column that isn't encrypted, a comparison with one, or a place with no column (such as `LIMIT`) is refused with `MetadataError`, so give each use its own name. +The parameter objects you pass are never changed, and `None` stays `NULL`. +`executemany` reads an iterable once, before the plugin's checks and its setup, so pass a list if you may retry the call. +Each stored value carries an HMAC-SHA256 tag, the column's `key_storage` id, a type marker, the AES-GCM nonce, the ciphertext and the GCM tag, at least 65 bytes in all. +Encryption is randomized, so equal values are stored differently. + +**Comparisons.** A bound parameter compared with an encrypted column by `=`, `IN (...)`, `= ANY(...)`, `LIKE`, `ILIKE`, `<=>` or `IS NOT DISTINCT FROM` is encrypted too, so the comparison never matches, when it sits in the `WHERE` or `HAVING` of a query or in the `ON` of an inner join and is joined to the rest of the condition only by `AND` and `OR`. +Django `filter()` and SQLAlchemy `filter_by()` then find nothing, and Django `get()` raises `DoesNotExist`. +On PostgreSQL, an `ILIKE` comparison fails on the server with `operator does not exist: bytea ~~* bytea`, because `bytea` has no `ILIKE`; the value is still sent encrypted. +`execute()` raises psycopg's `UndefinedFunction`, or under a failover plugin `AwsWrapperError` with it as `__cause__` (see [Errors](#errors)). +A list bound to `= ANY(%s)` raises `EncryptionFailedError` instead, because a list has no stored form (see **Refused**). +A sub-select whose select list is only the encrypted column counts as that column, so `%s IN (SELECT ssn FROM users)`, `%s = ANY (SELECT ssn FROM users)` and `%s = (SELECT ssn FROM users WHERE id = 1)` are encrypted in the same places. +The same holds in `UPDATE` and `DELETE`, in a sub-select that `IN`, `EXISTS`, `= ANY` or `=` reads, and in a derived table or CTE that its query reads in `FROM`, `USING`, a `JOIN` or the table list of a MySQL multi-table `UPDATE`, unless that query has an outer join or the derived table or CTE comes first in `USING` or in the table list of a MySQL multi-table `UPDATE` or `DELETE`. +In a write the plugin passes through, such as an `INSERT ... SELECT` with `encryption_fail_on_unmapped_parameter=False` (see **Passed through**), such a comparison is neither refused nor encrypted: its value is sent as written, and the database's statement log holds it. +Any other comparison of a parameter with an encrypted column is refused with `MetadataError` before anything is sent, because there a comparison that never matches would select every row or arbitrary rows. +That covers `<>`, `!=`, `<`, `>`, `<=`, `>=`, `BETWEEN`, `NOT IN`, `NOT LIKE`, `IS DISTINCT FROM`, `<> ALL(...)` and `= ALL(...)`, also with a sub-select of the column (`%s NOT IN (SELECT ssn FROM users)`, `%s <> ALL (SELECT ssn FROM users)`). +It also covers a comparison under `NOT` or `IS` (`IS FALSE`, `IS NOT TRUE`), inside `CASE`, `IF`, `COALESCE` or another function, or in a select list, `ORDER BY` or `SET` value; one in the `ON` of an outer join or a `MERGE`, in `ON CONFLICT ... WHERE`, or in any join or derived table of a query that has an outer join; and one in a sub-select that `NOT IN`, `NOT EXISTS` or `EXCEPT` reads, or that groups, aggregates, calls a window function or has a `WINDOW` clause, as in `DELETE FROM users WHERE id NOT IN (SELECT id FROM users WHERE ssn = %s)`. +A sub-select whose select list, `ORDER BY` or `DISTINCT ON` calls a function the plugin's SQL parser doesn't know, such as a user-defined aggregate or `to_jsonb`, counts as one that aggregates. +Filter, look up and join on a column that isn't encrypted. +For the same reason, a unique index or an upsert's conflict target on an encrypted column never detects a duplicate. +A value compared with something the plugin can't tie to the column is sent as written and isn't refused, and the database's statement log holds it. +Examples are an expression over the column (`COALESCE(ssn, alt) = %s`) or over the value (a function other than `CAST` or `CONVERT`, `COLLATE`, a sub-select or, on PostgreSQL, `||` around it, as in `ssn = lower(%s)`), a sub-select of the column that is a set operation or selects anything but the column (`%s IN (SELECT ssn FROM users UNION SELECT ssn FROM archive)`, `%s IN (SELECT lower(ssn) FROM users)`), a row value, `%s IN (ssn, alt)`, `ssn = ANY(ARRAY[%s])`, `SIMILAR TO`, a regular expression, a column inside a parenthesized join, or on MySQL inside a parenthesized table or table list, that is qualified by its alias, or that is unqualified in a query that reads exactly one table outside the parentheses (see [What the plugin does not see](#what-the-plugin-does-not-see)), and, on PostgreSQL, a sub-select under `ALL` or `SOME` followed by `FETCH FIRST` inside the function's parentheses (`%s <> ALL ((SELECT ssn FROM users) FETCH FIRST 5 ROWS ONLY)`), which the plugin's SQL parser drops. +With `<>` or another operator the plugin refuses, such a comparison matches every non-NULL row or arbitrary rows. + +**Annotations.** An `/*@encrypt:table.column*/` comment directly before a placeholder names the column its value is for, and wins over the column the plugin infers. +Leading schema names are ignored, and `/*@encrypt:ssn*/` names that column of the table the statement writes, or of the only table it reads. +An annotation doesn't make an unbound write acceptable: `SET ssn = upper(/*@encrypt:users.ssn*/ %s)` is refused. + +**Types.** A value reads back as the Python type it was written as: `str`, `bool`, `int`, `float`, `Decimal`, `date`, `datetime` or `bytes` (`bytearray` and `memoryview` read back as `bytes`). +An aware `datetime` reads back in UTC with millisecond precision, and a naive one reads back with its microseconds. +A `datetime.time` reads back as ISO text, and a `str` subclass, such as a `(str, Enum)` member, is stored as its own text and reads back as a plain `str`. +An `IntEnum` or `IntFlag` member reads back as a plain `int`, and an `int` outside the signed 64-bit range or a `Decimal` NaN or infinity raises `EncryptionFailedError`. + +**SQL types.** SQL passed as `bytes` and psycopg `sql` objects are analyzed like `str` SQL. +The plugin can't analyze a `bytes` statement that the connection's encoding doesn't decode exactly: with PostgreSQL's `SHIFT_JIS_2004`, whose Python codec reads the bytes of `\` and `~` as a yen sign and an overline, that is every `bytes` statement. +On MySQL only `bytes` SQL that is all ASCII is analyzed. +While `encryption_fail_on_unmapped_parameter` is on and the metadata has an encrypted column, SQL the plugin can't analyze raises `MetadataError` at `execute` and `executemany` before anything is sent, with a message that names the SQL's type and doesn't quote it. +A psycopg `cursor.copy()` of such SQL raises `MetadataError` whenever the metadata has an encrypted column, whatever the parameter says. +With the parameter off, or with no encrypted column, such SQL runs unchanged, and the plugin logs a warning once per connection for each SQL type. +Send such SQL as `str`, which is analyzed. + +**Refused.** These raise before anything is sent, on every cursor kind, psycopg `RawCursor` and prepared cursors included: + +- A write to an encrypted column of anything but a bind parameter (a literal, an expression, `DEFAULT` or another column), and a `COPY ... FROM` sent through `execute`, raise `MetadataError` with `table_name` and `column_name` set. + Bind the value instead. + A `NULL` in the SQL text is stored. +- A value with no exact stored form (a UUID, a plain `Enum` member, a list, tuple or dict, an IP address, a `timedelta`, psycopg `Jsonb` or `psycopg.Binary`), written to or compared with an encrypted column, raises `EncryptionFailedError` naming the parameter (its position from 1, or its name), its type and the column. + Convert it first; for `psycopg.Binary`, pass `bytes`. +- An annotation that names a column without encryption metadata (a plain column, a typo, a table that doesn't exist), on a value written to or compared with an encrypted column, raises `MetadataError` naming the encrypted column. +- In a statement that reads several tables, one of which has an encrypted column of that name, a value compared with a column the plugin can't tie to a table (a derived table's or CTE's column joined with another table, or an unqualified column in a join) raises `MetadataError` naming the encrypted column, also when the value's annotation names no table the statement uses. + To run the statement, annotate the value with the table and column it is compared with, a plain column's included (`/*@encrypt:archive.ssn*/ %s`). +- A comparison of a bound value with an encrypted column where a comparison that never matches would still select rows (see **Comparisons**) raises `MetadataError` naming the column, with `table_name` and `column_name` set, also in a write that is otherwise passed through. + Compare a column that isn't encrypted instead. +- A multi-statement string is analyzed as one statement, so a literal written to an encrypted column in any of its statements is refused too. + +**Refused by default.** A statement with parameters on a table with encrypted columns raises `MetadataError` before anything is sent when the plugin can't pair each parameter with its column. +That covers an `INSERT` without a column list, an `INSERT ... SELECT` (its compared values included), a multi-statement string that holds such a write, on MySQL an `UPDATE` of several tables whose `SET` names any column without its table (qualify every column it sets, as in `SET u.ssn = %s`, and the plugin encrypts the encrypted ones), and a read or write the plugin can't parse. +SQL the plugin can't analyze at all, such as `bytes` it can't decode (see **SQL types**), is refused at `execute`, `executemany` and psycopg `cursor.copy()` with or without parameters while any column is encrypted. +A psycopg `cursor.copy()` with parameters on such a table is refused the same way, because the plugin doesn't encrypt a COPY's parameters. +The message names the tables and what the plugin couldn't analyze. +It doesn't quote the statement or its values. + +**Passed through.** A write whose target columns the plugin can't list runs unchanged, with a warning, when it has no parameters or when `encryption_fail_on_unmapped_parameter` is `False`. +A psycopg `cursor.copy()` that the plugin can't parse and that can write such a table raises `MetadataError` instead, with or without parameters and whatever `encryption_fail_on_unmapped_parameter` is (see [What the plugin does not see](#what-the-plugin-does-not-see)). +With `False`, a read that **Refused by default** covers runs unchanged with no warning. +A multi-statement string that holds such a write is sent whole, the other statements' values included. +SQL objects that aren't `str`, `bytes` or a psycopg `sql` object, such as `bytearray`, `memoryview` and Python 3.14 template strings, can't be analyzed either, so they are refused or run unchanged as **SQL types** describes; what the driver then does with one that runs is the driver's. +The warning is logged once per connection for each statement shape, from a bounded set, and says what the plugin couldn't analyze, as in "(the statement does not name the columns it writes)". +The trigger rejects any plaintext such a statement writes. +A value it compares with an encrypted column reaches the database's statement log, unless the comparison is one the plugin refuses (see **Comparisons**). +On mysql-connector, the first 40 characters of the statement as sent, values included, also appear in the `AwsWrapperError` the cursor raises if it is used again after failover or read-write splitting has changed the connection. + +**Reads.** `fetchone`, `fetchmany`, `fetchall`, `next(cursor)`, `for row in cursor` and psycopg's `cur.execute(query).fetchone()` return decrypted values. +`cursor.description` is the driver's, unchanged: an encrypted column reports its storage type (on PostgreSQL `bytea`, type code 17; on MySQL the binary column's type, 253 for `VARBINARY`) while the row holds the decrypted value, so don't infer a value's type from `type_code`. +Result columns are matched to their source column, so aliases, joins, `RETURNING`, derived tables and CTEs decrypt, also under a column list that renames a derived table's or a CTE's columns by position (`SELECT x FROM (SELECT ssn FROM users) AS t(x)`); an expression, a set operation's column and the columns a `*` reads are matched by name only (see [What the plugin does not see](#what-the-plugin-does-not-see)). +Two result columns with the same name, which a `*` reads from two derived tables or CTEs, one of them from an encrypted column, raise `MetadataError` at the fetch (`SELECT * FROM (SELECT ssn AS x FROM users) a JOIN (SELECT name AS x FROM people) b ON TRUE`). +psycopg row factories other than the default, `dict_row` and `namedtuple_row` raise `MetadataError` on a result with an encrypted column. +A `for` loop over a cursor decrypts its rows for the statement that was current when the loop started, so finish the loop before you call `nextset()` or run another statement on the same cursor. +Once the cursor has run another statement, and either statement names a table with an encrypted column, the loop's next row raises `MetadataError`; after `nextset()`, the loop's later rows can come back still encrypted or raise `IntegrityCheckError`. +In psycopg's pipeline mode (`with conn.pipeline():`), the plugin reads a result's columns when its rows arrive, so the row-factory check and a loop's decoding happen then. + +### Errors + +Import the error classes from `aws_advanced_python_wrapper.errors`; `EncryptionPluginError` catches every one of them. +Django doesn't translate them into `django.db` errors. +SQLAlchemy wraps them in its own classes instead: `IntegrityCheckError` arrives as `sqlalchemy.exc.IntegrityError`, and `MetadataError`, `EncryptionFailedError` and `KeyManagementError` as `sqlalchemy.exc.OperationalError`, with the plugin's error as `orig`; the connection stays usable. +A column whose key row is missing or unusable raises `InvalidKeyMetadataError` on write and on read (a value written under an earlier key still decrypts with that key), and a column whose `encryption_metadata` row names an algorithm other than exactly `AES-256-GCM` or `AES-128-GCM` raises `InvalidAlgorithmError`, naming the column and the algorithm, before KMS is called; a master key outside the allow-list raises `UnauthorizedMasterKeyError`, a `KeyManagementError`, before KMS is called; and KMS failing after the retries raises `KeyManagementError`. +KMS's own error text can name the master key's ARN (a disabled key, a key pending deletion, a key policy that denies the call) and, for an access denial, the ARN of the role session the application runs as, so the message leaves that text out. +It names the operation, the AWS SDK error's class, the KMS error code (`unknown` when there is none) and the HTTP status, as in `KMS DECRYPT_DATA_KEY failed after 1 attempt(s): ClientError, error code AccessDeniedException, HTTP status 400`. +For an error that doesn't come from KMS, such as an endpoint that can't be reached, the message keeps that error's text, with ARNs, the user info of a URL and the value of each `name=value` pair whose name contains `password`, `passwd`, `pwd`, `secret`, `token` or `credential`, or ends in `key` (a quoted value to its closing quote, any other value to the next whitespace), masked, control characters replaced by `?`, and the text cut to 200 characters. +The `DEBUG` record logged before each retry and the warning that `create_master_key` logs when it can't create an alias give the same summary. +The AWS SDK's error isn't chained to the `KeyManagementError`, as `__cause__` or as `__context__`, so a traceback shows nothing that the message doesn't. +With the metadata cache on, if the metadata tables can't be read at a connection's first statement, that statement and every later one, including a `SELECT 1`, raise `MetadataError` until the tables can be read. +If they can't be read after the cached copy expires (`encryption_metadata_cache_expiration_sec`), or at any lookup with the metadata cache off, every statement that names a table raises `MetadataError` instead of passing through, even if the table has no encrypted columns; until the cached copy expires, it keeps answering. +In each of these cases the plugin raises the `MetadataError` itself, before the statement reaches a failover plugin, so it doesn't start failover. +If the database host can't be reached, close the connection (with SQLAlchemy, call `invalidate()` on it) and open a new one. + +The plugin's own errors keep their classes with or without a failover plugin in the chain (on mysql-connector, see the note on unread rows below). +A trigger's rejection reaches the application as the driver's own error (`psycopg.errors.RaiseException`, `mysql.connector.errors.DatabaseError`) when no failover plugin is in the chain. +Under `failover` or `failover_v2`, which the default plugin lists include, or under `gdb_failover`, `execute()` raises it as `AwsWrapperError` with the driver's error as `__cause__`, unless [`preserve_driver_exception_type`](./UsingTheFailover2Plugin.md#failover-plugin-v2-configuration-parameters) is on: then it is the driver's own error. +From `executemany()` it is still the driver's own error, because the failover plugins don't intercept `executemany`. + +A setup failure at the first statement, such as an `aws_profile` that doesn't exist or a malformed `encryption_kms_endpoint`, raises the AWS SDK's or Python's own error (`botocore.exceptions.ProfileNotFound`, `ValueError`), not a plugin error class. +Nothing is sent, and the next statement tries the setup again. + +When a stored value can't be read, the errors for a missing or unusable key row, for an unsupported algorithm, for a value whose key id names no usable key row (`IntegrityCheckError`) and for a value that isn't binary (`IntegrityCheckError`) name the column. +A value that is too short, fails its HMAC check or doesn't decrypt raises `IntegrityCheckError` or `DecryptionError` without naming the column. + +On mysql-connector's default cursor, a read error can leave the rest of the result unread. +A `MetadataError` that the plugin raises at a fetch comes before the driver reads a row, so it leaves the whole result unread, on the C extension and with `use_pure=True`. +Until it is read, the driver raises its own `InternalError` ("Unread result found") when that cursor closes and when the connection opens its next cursor (under the default plugins, as `AwsWrapperError`), so leaving a `with conn.cursor()` block raises the driver's error, with the plugin's error as its `__context__`. +Connect with `consume_results=True`, or open such cursors with `buffered=True`, to get the plugin's error and keep using the connection; `conn.rollback()` also discards the unread rows. +The driver behaves the same after any fetch that stops before the end of a result. + +### Reading data written before encryption + +When a column already holds plaintext, reading it through the plugin raises `IntegrityCheckError`. +Encrypt the existing rows first: read each value without the plugin and write it back through the plugin. +Only for a short, controlled migration, set `encryption_return_unverified_data=True`: a value the plugin can't verify as the column's encrypted value then comes back as the driver returned it (usually `bytes`), next to the decrypted values, and the plugin logs nothing; a value that verifies but doesn't decrypt still raises. +While the column's own key row is missing or unusable, a value shorter than 36 bytes, or one that carries the column's key id, raises `InvalidKeyMetadataError` with this setting too. +**Don't enable it in production:** a tampered value then reads back without an error. +While a column still holds such values, each read of one that is 36 bytes or longer looks up the `key_storage` row its bytes 32 to 35 name, on a new database connection each time and in both modes, so a database statement log records those four bytes as a number on every read: migrate such values first. + +## What the plugin does not see + +The plugin doesn't see the statements and results below, except where a line says otherwise. +Plaintext written through them is stopped only by the trigger. +A value they compare with an encrypted column is sent as written, so the database's statement log holds it. +Encrypted values read through them come back as stored bytes. + +- psycopg `cursor.copy()` with a `COPY ... TO`, which runs unchanged, so its rows come back as stored bytes. + A `cursor.copy()` with parameters on a table with encrypted columns raises `MetadataError` by default (see **Refused by default**), because the plugin doesn't encrypt a COPY's parameters. + A `COPY ... FROM` that names an encrypted column raises `MetadataError` before anything is sent, and so does a `COPY` the plugin can't parse that can write a table with encrypted columns: a `COPY ... FROM`, or a `COPY (...) TO` whose query is an `INSERT`, `UPDATE` or `MERGE`. + Write those rows with `execute` or `executemany`. + One without a column list on such a table runs with the pass-through warning, so only the trigger stops plaintext. +- psycopg `cursor.stream()`, `cursor.results()` and `cursor.set_result()`, and mysql-connector `cursor.fetchsets()` and `cursor.stored_results()`. + Their rows don't pass through the plugin, so while the plugin is on, each of them raises `MetadataError` before the driver runs it. + To read a large result in pages, use a named cursor with `fetchmany`; to read the sets of several statements, run one statement per `execute()`. + Called on `cursor.target_cursor`, they run as the driver's methods and return stored bytes. +- After `nextset()` moves to a later result set of a multi-statement string, a fetch raises `MetadataError` when a column of that set has the name of an encrypted column of a table the string names, because the plugin can't tell which statement produced the set. + The sets of an `executemany` are matched again for each set. + psycopg's `executemany(..., returning=True)` sets all come from one statement and decrypt like the first. + The first result set of a multi-statement string is matched by name only, as a select list with `*` is (see below), and so is each later set when mysql-connector's `executemany` runs such a string with one parameter set. + An encrypted column in such a set decrypts when no other table the string names has an encrypted column of that name (`a.users` and `b.users` count as one table, see below) and no other column of the set has that name; otherwise the fetch raises `MetadataError`. + Run one `SELECT` per `execute()` when it reads encrypted columns. +- `callproc()`, SQL `CALL`, `DO`, `PREPARE` and `EXECUTE` (on PostgreSQL, a `PREPARE` of a write gets the pass-through warning), `LOAD DATA`, stored routines and triggers. + A `callproc()` with arguments raises `MetadataError` before the driver call while `encryption_fail_on_unmapped_parameter` is on and the metadata has an encrypted column. + With the parameter off, its arguments reach the routine unchanged (mysql-connector sends them as SQL text, as in `SET @_sp_arg1=...`), and only the trigger keeps plaintext out of a column. + Its OUT and INOUT values aren't decrypted, so read an encrypted column with a query on its table. + On mysql-connector, a procedure's result sets can be read only through `cursor.target_cursor.stored_results()`, as stored bytes. +- psycopg `RawCursor` (`$1`) and `?` placeholders on mysql-connector prepared cursors are not supported for encrypted columns: a write that names an encrypted column is refused, and a write whose columns the plugin can't list goes to the trigger. + mysql-connector prepared cursors with `%s` placeholders are encrypted and decrypted like default cursors. +- Connections taken from `target_connection`, the driver's cursor that `cursor.target_cursor` returns, reads through a view, and connections whose `plugins` list doesn't include `kms_encryption`. +- SQL sent through the driver connection's own methods, such as mysql-connector's `cmd_query()` and psycopg's `conn.pgconn`. +- A column renamed by a set operation (`SELECT ssn AS x FROM users UNION ALL ...`) and an expression over an encrypted column, also behind a derived table, unless the expression keeps the column's name. + The columns of a `SELECT` or `RETURNING` whose list has `*` or `t.*` are matched by name in any letter case: an encrypted column there decrypts under its own name, and the fetch raises `MetadataError` when another result column has that name or another table the statement reads has an encrypted column of that name. + So a fetch raises for a `*` over a join whose tables share the name, and for a `*` beside another column of that name (`SELECT *, ssn FROM users`, `SELECT *, upper(name) AS SSN FROM users`). + An alias beside the `*`, and a derived table's new name that the `*` reads, decrypt by the column they come from (`SELECT *, ssn AS x FROM users`, `SELECT * FROM (SELECT ssn AS x FROM users) s`), and a plain column under such a name comes back as it is. + When a `*` or an unqualified column of the select list reads a plain column of a derived table or CTE under the name of an encrypted column, and the query also reads a table, or a derived table or CTE whose select list has a `*` or an expression with no alias, the fetch raises `MetadataError` with any join, because a `USING` or `NATURAL` join can merge the other source's column into it (`SELECT * FROM users u LEFT JOIN (SELECT id, photo AS ssn FROM people) d USING (ssn)`, where `photo` is a plain binary column). + The column comes back as stored bytes when the `*` is in a derived table or CTE whose column the outer query renames (`SELECT s.ssn AS social FROM (SELECT * FROM users) s`). + The metadata names a table without its schema, so `a.users` and `b.users` count as one table (on MySQL, so do `users` and `USERS`), and `ssn` decrypts in `SELECT * FROM a.users WHERE id IN (SELECT id FROM b.users)`. + The name-matching rule doesn't check which table a column comes from, so a plain column that meets it is decoded as the encrypted column of its name: with a plain `archive.ssn`, reading `SELECT a.* FROM archive a JOIN users u ON u.id = a.user_id` raises `IntegrityCheckError`, which can name `users.ssn`; with `encryption_return_unverified_data=True`, the read returns the value as is. + List the columns instead of `*`. +- A statement with a CTE that has the name of a table with encrypted columns raises `MetadataError` before it is sent, on both engines, because the plugin reads the name as the CTE while the database can read or write the table. + For example, `WITH users AS (SELECT 1 AS x) INSERT INTO users (ssn) VALUES (%s)` writes the table `users`. + Rename the CTE. +- A value compared with a column that a derived table or CTE renames (`SELECT s.x FROM (SELECT ssn AS x FROM users) s WHERE s.x = %s`, or a CTE column list), or with an unqualified column that a subquery takes from the outer query, is sent as written, isn't refused, and the database's statement log holds it. + With `=` it matches no row; with an operator the plugin refuses on an encrypted column, such as `<>`, it matches every non-NULL row or arbitrary rows. + Compare the table's own column, name its table (`u.ssn`), or annotate the value. +- In a statement that reads several tables, an annotation that names a table the statement uses is trusted. + One that names that table's plain column, a misspelled column, or the right column on the wrong table, on a value compared with an encrypted column the plugin can't tie to a table, is sent as written in the same way. + Annotate with the table whose column the value is compared with. +- A parenthesized join, as in `FROM orders o JOIN (users u JOIN items i ON i.uid = u.id) ON o.uid = u.id`, and on MySQL a parenthesized table or table list, as in `FROM (users u)` or `JOIN (users u, items i) ON ...`. + A value compared with a column inside the parentheses that is qualified by its alias (`u.ssn`), or that is unqualified in a query that reads exactly one table outside the parentheses, is sent as written, isn't refused, and the database's statement log holds it; with `<>` it matches every non-NULL row. + An encrypted column read in either of those two ways comes back as stored bytes. + On MySQL, an `UPDATE` whose tables are all inside parentheses, as in `UPDATE (users u) SET u.ssn = %s`, and a multi-table `DELETE` from a parenthesized table, as in `DELETE u FROM (users u) WHERE u.ssn = %s`, raise `MetadataError` when they have parameters and a table they name has encrypted columns (see **Refused by default**). + Without parameters, the `UPDATE` runs with the pass-through warning and the `DELETE` runs unchanged. + Write the tables without the parentheses. +- `EXPLAIN ANALYZE` of a write runs unchanged with no warning. +- On MySQL, a statement with a `/*! ... */` executable comment raises `MetadataError` before it is sent when a name in it, inside the comment or outside, is a table with encrypted columns, because the server runs the comment's body and the plugin can't analyze it. + That includes a comment of keywords only, as in `INSERT /*!50000 LOW_PRIORITY */ INTO users ...`, and a read without parameters, such as mysqldump's `SELECT /*!40001 SQL_NO_CACHE */ * FROM users`. + On PostgreSQL, `/*! ... */` is a plain comment. +- SQL the plugin can't parse is refused, as **Refused by default** describes, when it has parameters and a word or quoted name in it is a table with encrypted columns; without parameters a write runs with the pass-through warning, and a read runs unchanged. + A psycopg `cursor.copy()` that the plugin can't parse and that can write such a table is refused with or without parameters (see `cursor.copy()` above). + A statement with a placeholder inside a quoted literal, quoted identifier or comment is refused with `MetadataError` when the plugin can tie it to a table with encrypted columns, because the driver binds that placeholder too and the plugin can't tell which value goes to which column. + On other tables it runs unchanged. +- Servers that don't use the default quoting rules: MySQL `NO_BACKSLASH_ESCAPES` or `ANSI_QUOTES`, PostgreSQL `standard_conforming_strings=off`. +- The `encryption` extra installs sqlglot's pure-Python build. + sqlglot's compiled build, the `sqlglotc` package that `sqlglot[c]` and `sqlglot[rs]` install, can crash on very deeply nested SQL, so don't install it alongside the plugin. +- Keep text decoding on for the plugin's connections: the mysql-connector connection options `use_unicode=False` and `raw=True` also apply to the plugin's own metadata reads and aren't supported (a `raw=True` cursor works); on PostgreSQL, use a UTF-8 client encoding (on a `SQL_ASCII` connection, psycopg returns text as bytes, so reads and writes of encrypted columns raise `InvalidAlgorithmError`, whose message shows the algorithm's name as bytes, for example `b'AES-256-GCM'`). + +## Enforce encryption in the database + +Every encrypted column needs a trigger that checks each value written to it. +The trigger needs no help from the application: the HMAC key that signs each value is stored unencrypted in `key_storage`, so the database can check that a value carries a valid tag without holding the data key. +The trigger SQL ships with the wrapper, in the `aws_advanced_python_wrapper/encryption/sql` folder of the package: + +- [`trigger_pg.sql`](../../../aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql) installs the `pgcrypto` extension if it isn't installed, and creates the `enforce_encrypted_column()` trigger function. + The function reads the metadata tables as `SCHEMA_NAME.encryption_metadata` and `SCHEMA_NAME.key_storage`: replace `SCHEMA_NAME` in the file with your metadata schema (`encrypt` unless `encryption_metadata_schema` is set to something else). + A file run with `SCHEMA_NAME` left in installs, then fails every write of a non-NULL value to an encrypted column with `relation "schema_name.encryption_metadata" does not exist`. + If `pgcrypto` is already installed in a schema other than `public`, replace `public` in `public.hmac` with that schema. +- [`trigger_mysql.sql`](../../../aws_advanced_python_wrapper/encryption/sql/trigger_mysql.sql) builds HMAC-SHA256 from `SHA2()`, because MySQL has no HMAC function, and creates the two functions and two validation procedures that the per-column triggers call. + Follow the MySQL steps below before you run it. + +Run the file for your engine once per database, in a single `cursor.execute()`. +psycopg runs `trigger_pg.sql` with no parameters (passed `params=()`, it reads the file's `%` signs as placeholders and fails), and mysql-connector 9.2 or later runs `trigger_mysql.sql` with its `DELIMITER` lines (older versions reject the file with error 1064); read every result set it returns: + +```python +from importlib.resources import files + +sql_dir = files("aws_advanced_python_wrapper.encryption") / "sql" + +# PostgreSQL, with SCHEMA_NAME replaced by the metadata schema +with conn.cursor() as cur: + cur.execute((sql_dir / "trigger_pg.sql").read_text(encoding="utf-8").replace("SCHEMA_NAME", "encrypt")) +conn.commit() + +# MySQL, with SCHEMA_NAME replaced by the metadata schema (step 2 below) +with conn.cursor() as cur: + cur.execute((sql_dir / "trigger_mysql.sql").read_text(encoding="utf-8").replace("SCHEMA_NAME", "encrypt")) + while cur.nextset(): + pass +conn.commit() +``` + +Then create a trigger for every column that you want to encrypt. +On PostgreSQL that is one trigger per column, and on MySQL a `BEFORE INSERT` and a `BEFORE UPDATE` trigger per column. +Through a driver, send each `CREATE TRIGGER` in its own `cursor.execute()`; the `DELIMITER` lines and the `$$` after each `END` are for the `mysql` command-line client. + +```sql +-- PostgreSQL +CREATE TRIGGER users_ssn_encrypted +BEFORE INSERT OR UPDATE ON users +FOR EACH ROW EXECUTE FUNCTION enforce_encrypted_column('ssn'); +``` + +```sql +-- MySQL +DELIMITER $$ +CREATE TRIGGER users_ssn_hmac_check +BEFORE INSERT ON users +FOR EACH ROW +BEGIN + CALL validate_encrypted_data_hmac_before_insert('users', 'ssn', NEW.ssn); +END$$ + +CREATE TRIGGER users_ssn_hmac_check_update +BEFORE UPDATE ON users +FOR EACH ROW +BEGIN + CALL validate_encrypted_data_hmac_before_update('users', 'ssn', NEW.ssn, OLD.ssn); +END$$ +DELIMITER ; +``` + +Each file records its version in a database comment, which the queries below return. +The text ends with `kms_encryption trigger v2` for `trigger_pg.sql` and `kms_encryption trigger v1` for `trigger_mysql.sql`, the versions this guide describes. +When a later release of the wrapper ships a newer version of a file, its CHANGELOG entry says so: run the file again. +That replaces the functions and procedures without changing data, and the per-column triggers keep working. +On MySQL a write to an encrypted column can fail while a routine is dropped and re-created, so run it while writes are quiet. + +```sql +-- PostgreSQL +SELECT obj_description('enforce_encrypted_column'::regproc, 'pg_proc'); +-- MySQL, in the schema the routines were created in +SELECT ROUTINE_COMMENT FROM information_schema.ROUTINES + WHERE ROUTINE_SCHEMA = DATABASE() AND ROUTINE_NAME = 'validate_encrypted_data_hmac_before_insert'; +``` + +On MySQL, also do the following: + +1. With binary logging on, an account without `SUPER` can't create the routines (error 1419). + On a self-managed server it can't create the per-column triggers either (error 1419), and if a `CREATE TRIGGER` fails, the column is unprotected and plaintext is stored without an error. + On Aurora MySQL the master user can create the per-column triggers without the routines; every write to the column then fails with error 1305 and stores nothing until the routines are installed. + Binary logging is on by default since MySQL 8.0; on Aurora MySQL it is off unless the DB cluster parameter group sets `binlog_format`. + Where it is on, have an administrator set `log_bin_trust_function_creators` to `1` first. + On a self-managed server: + + ```sql + SET GLOBAL log_bin_trust_function_creators = 1; + ``` + + On Aurora MySQL, the master user can't run that statement (error 1227: it needs `SUPER` or `SYSTEM_VARIABLES_ADMIN`). + Set the parameter in the DB cluster parameter group instead. + +2. Replace `SCHEMA_NAME` in `trigger_mysql.sql` with your metadata schema, and run the file in every schema that holds an encrypted table: the per-column triggers call the routines unqualified (error 1305 otherwise). + A file run with `SCHEMA_NAME` left in installs, then fails every write: with error 1142 when the account that ran it can't read `SCHEMA_NAME.*`, and with error 1146 when it can, as an Aurora master user's global `SELECT` allows. +3. The routines run as their definer, the account that ran the file (`schema_owner` below). + Grant it read access to the metadata schema: + + ```sql + GRANT SELECT ON encrypt.* TO 'schema_owner'@'%'; + ``` + + Don't drop that account or revoke that grant while the triggers exist: every write the trigger checks then fails, with `The user specified as a definer ... does not exist` or `SELECT command denied`. + +To stop encrypting a column, drop its triggers in the same change, or every later write to it fails: + +```python +with conn.cursor() as cur: + # PostgreSQL. On MySQL, drop the column's BEFORE INSERT and BEFORE UPDATE triggers: DROP TRIGGER , without ON. + cur.execute("DROP TRIGGER users_ssn_encrypted ON users") +utility.remove_encryption_for_column("users", "ssn") +conn.commit() +``` + +### Updates after a key rotation + +The trigger checks a new value against the column's current HMAC key, and rotating a column's data key also gives it a new HMAC key. +Values written before the rotation keep the earlier key's tag, which stays valid for them: the plugin reads them with the key they were written with. +So the trigger doesn't check an `UPDATE` that leaves the encrypted value unchanged. +Without that, every update of a row written before the rotation, even one that changes only another column, would be rejected until the row's values were encrypted again. +An `INSERT`, or an `UPDATE` that changes the encrypted column, is checked and must carry the current key's tag, which the plugin's writes do once the connection has the new key (see [Rotate a column's data key](#rotate-a-columns-data-key)). + +## Hardening + +Three controls decide how much the encryption protects: which KMS keys the application can use, who can write the metadata schema, and who can change the trigger. +The first three steps cover them, and the fourth covers what none of them stops. + +- **KMS keys.** The plugin takes a column's master key from its `key_storage` row, not from its own settings, so the allow-list and the application's IAM policy keep a changed row from pointing it at another key. List every master key the columns use in `encryption_allowed_master_key_arns`, in the form `key_storage.master_key_arn` holds. The plugin refuses any other key before calling KMS (`UnauthorizedMasterKeyError`), on reads and writes alike, and `encryption_return_unverified_data` doesn't change that. Add a new master key before rotating a column onto it, and keep the old one listed, with `kms:Decrypt` allowed, while values written under it remain. Give the application's credentials only `kms:Decrypt`, on those key ARNs, never `"Resource": "*"`, and use a separate key per environment. Run `KeyManagementUtility`, which also calls `kms:GenerateDataKey`, `kms:CreateKey`, `kms:CreateAlias` and `kms:DescribeKey`, under a separate administrative credential. Don't add a `kms:ViaService` condition to these policies. It matches only requests an AWS service makes on your behalf, and the plugin calls KMS directly, so every `Decrypt` would be denied. + + ```json + {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "kms:Decrypt", + "Resource": "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"}]} + ``` + +- The plugin's KMS calls carry no encryption context, so a key policy or grant can't limit a role to one column's data keys. +- **Metadata schema.** A role that can write `key_storage` can replace a column's HMAC key and forge values the trigger accepts, or delete or swap a column's key rows and make its values unreadable; the allow-list stops only a switch to an unlisted master key. + Grant the application's database role only `SELECT` on the metadata schema (PostgreSQL: `GRANT USAGE ON SCHEMA encrypt TO app_role; GRANT SELECT ON ALL TABLES IN SCHEMA encrypt TO app_role;`, MySQL: `GRANT SELECT ON encrypt.* TO 'app_user'@'%';`). + Grant `INSERT`, `UPDATE` and `DELETE` there only to the administrative role that runs `KeyManagementUtility`. +- **Triggers.** Create the encrypted tables, the trigger SQL and the per-column triggers as an administrative role, and don't run the application as that role or as the master user. + A table's owner can disable or drop its triggers (`ALTER TABLE users DISABLE TRIGGER users_ssn_encrypted` on PostgreSQL). + A role with the `TRIGGER` privilege can add a trigger that runs after the check and stores plaintext, and on MySQL can drop triggers. + The owner of the trigger function on PostgreSQL, or an account with `ALTER ROUTINE` on the routines on MySQL (their creator has it), can replace them. + A superuser, the RDS master user included, can do all of this, and on PostgreSQL can skip triggers with `SET session_replication_role = replica`. + Give the application's role data privileges only (PostgreSQL: `GRANT SELECT, INSERT, UPDATE, DELETE ON users TO app_role; GRANT USAGE ON SEQUENCE users_id_seq TO app_role;`, MySQL: `GRANT SELECT, INSERT, UPDATE, DELETE ON mydb.users TO 'app_user'@'%';`), never `TRIGGER` or `ALTER ROUTINE`. +- **Rows.** An encrypted value isn't tied to its row. + A value copied into another row of the same column passes the trigger and decrypts there, so a role that can `UPDATE` the table, the application's own included (and so any SQL injection), can move values between rows without a key. + A value moved to another column fails the trigger, because each column has its own keys. + Grant `UPDATE` on encrypted tables only where it is needed. + Where a value must belong to its row, store the row's key inside the value and check it after reading. +- The plugins that run before `kms_encryption` receive your unencrypted parameters; the plugins after it and the driver receive the encrypted values. + With `auto_sort_wrapper_plugin_order` on, the plugins before it are `custom_endpoint`, `initial_connection`, `aurora_connection_tracker`, `stale_dns`, `read_write_splitting`, `srw` and `gdb_rw`; `connect_time`, `execute_time` and `dev` sort right after the plugin listed before them, so they run before it when that plugin does or when they are listed first. + No built-in plugin logs parameters; if you write your own plugin, don't log them either. +- Keep the root logger and the `botocore` logger above `DEBUG` in production (see [Logging](../UsingThePythonWrapper.md#logging)). + At `DEBUG`, botocore logs every AWS request with its access key id, session token and signature, and, with a profile that assumes a role, the temporary credentials it fetches. + Once the plugin has created its KMS client, or a script has built a `KeyManagementUtility` or called `KeyManager.create_kms_client`, the wrapper drops from then on, for every KMS client in the process (the application's included), the botocore records of KMS calls that would carry a data key or these credentials, and for every AWS service botocore's separate record of each request's signature and its record of any response body that contains the quoted word `"Plaintext"`. + It drops no other records. + At `DEBUG`, botocore's `botocore.endpoint` record of each KMS request names the master key ARN. + When KMS refuses a call, botocore's `botocore.parsers` record of the error response can name the caller's ARN (for an assumed role, its role and session names) and the master key ARN. +- SQLAlchemy's error messages include bound values unless the engine is created with `hide_parameters=True`: set it, and leave `echo` off. + Keep Django's `django.db.backends` logger above `DEBUG`. +- Error reporters that record local variables (Sentry's default) capture plaintext values from the wrapper's frames, the plugin's included: a statement's values when it raises (a refused write, or the driver's own error such as a duplicate key), and, when a read fails, the values already decrypted from that row. + Turn that off, or scrub every frame of the `aws_advanced_python_wrapper` package. +- Data keys are wiped from memory after use on a best-effort basis; Python and `cryptography` may keep copies. + +## Using SQLAlchemy and Django + +On PostgreSQL, SQLAlchemy casts typed parameters (`%(ssn)s::VARCHAR`), which the server rejects for a `bytea` column, and nothing is stored. +Declare encrypted columns with a pass-through type, which works with any value type: + +```python +from sqlalchemy.types import UserDefinedType + + +class EncryptedValue(UserDefinedType): + cache_ok = True + + def get_col_spec(self, **kw): + return "BYTEA" +``` + +`LargeBinary` also works, but only with `bytes` values. +On MySQL, declare encrypted time columns as `String`: a `Time` column fails on read, and a `String` one reads back the ISO text. + +On MySQL the plugin adds `_binary` before each encrypted value, so the server raises no warning 1300, and its SQL shows `_binary '...'`. +On `executemany`, a placeholder whose value is `None` in any parameter set gets no prefix in any set, so that call keeps warning 1300, and with `raise_on_warnings=True` it raises the driver's `DatabaseError`. +For an `INSERT ... VALUES`, which mysql-connector sends as one statement, the error comes after every row is written. +Any other statement is sent once per parameter set, so the error comes after the first set that warns, and the later sets aren't sent. +Write `_binary` directly before the placeholder or leave it out: with a comment between them, an `INSERT`'s value is refused as an unbound write, and a comparison or `UPDATE` isn't seen. + +Django (MySQL only): `DEBUG=True` works. +`DateField` reads back as `str`. +`DateTimeField` and `TimeField` aren't supported on encrypted columns: they read back as `bytes`, and with `USE_TZ=True` reading a `DateTimeField` raises. +`bulk_update()` on an encrypted column is refused, because it writes the value inside a `CASE` expression. + +On MySQL, connections that write encrypted columns should use the default `utf8mb4` or a single-byte client character set whose MySQL name Python accepts as a codec name, such as `latin1`. +With `sjis`, `cp932`, `big5` or `gbk`, use mysql-connector's C extension, not `use_pure=True`, and don't use `gb18030` on either build: there the driver changes some of the encrypted values it sends, so the trigger refuses those writes (without the trigger they are stored, and reading them raises `IntegrityCheckError`), and other writes fail with the driver's own error. +Set the character set with mysql-connector's `charset` connection argument, not with `SET NAMES` sent as SQL: after such a statement, mysql-connector keeps reporting the one it negotiated, and in a session switched that way to `swe7`, a value bound for an encrypted table or column whose name holds É, Ä, Ö, Å, Ü or their lowercase forms can be sent unencrypted with no warning. +Given as the `charset` argument, a character set whose MySQL name isn't a Python codec name, such as `koi8r` (Python calls it `koi8_r`) or `swe7` (Python has no codec for it), makes the first statement raise `MetadataError` ("[MetadataManager] Failed to read the kms_encryption metadata: ..."), whose message names the class of the error the driver raised but not its text. diff --git a/tests/integration/test_kms_encryption_live.py b/tests/integration/test_kms_encryption_live.py new file mode 100644 index 000000000..530f69382 --- /dev/null +++ b/tests/integration/test_kms_encryption_live.py @@ -0,0 +1,1914 @@ +# 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. + +"""Live checks of the KMS Encryption Plugin on PostgreSQL 16, MySQL 8 and LocalStack's KMS, all on 127.0.0.1. + +The module seeds both databases with the metadata tables, the trigger SQL that the package ships in +``aws_advanced_python_wrapper/encryption/sql`` and two encrypted columns with key rows of their own: ``users.ssn``, +which has the trigger, and ``users.dob``, which has none. +It first drops ``users``, ``addresses``, the ``encrypt`` schema and the trigger SQL's routines, and on MySQL turns on +``log_bin_trust_function_creators``, so point it only at servers it may reset. It runs the typical driver and ORM +shapes through the plugin, reads every stored value back with a plain driver, and counts plaintext in both servers' +own logs. It fails, never skips, when a server or a setting is missing, and reaches KMS only on LocalStack, with dummy +credentials. Give one run the two servers to itself: the log checks count every statement each server logs during the +run, and MySQL has one ``encrypt`` database per server, which every run drops and recreates whatever its ``DB_NAME``. +Run the module with:: + + pytest tests/integration/test_kms_encryption_live.py + +All of these environment variables are required. ``PG_PORT``, ``MYSQL_PORT`` and ``KMS_PORT`` are the local ports. +``DB_USER``, ``DB_PASSWORD`` and ``DB_NAME`` name a PostgreSQL superuser and a MySQL user with that password and +database; MySQL's root account uses ``DB_PASSWORD`` too. ``PG_LOG_COMMAND`` and +``MYSQL_LOG_COMMAND`` each hold a command that prints that server's statement log (PostgreSQL started with +``log_statement=all``, MySQL with its general log on); each is split into arguments and run without a shell. If +``AWS_PROFILE`` or ``AWS_DEFAULT_PROFILE`` is set, it must name a profile that exists, because importing the wrapper +reads it; the module removes both for its run. If SQLAlchemy or Django can't connect, pytest's failure report shows the +wrapper's connection properties, ``DB_PASSWORD`` included, so use a password that belongs to these local servers only. +""" + +from __future__ import annotations + +import contextlib +import copy +import io +import logging +import os +import re +import shlex +import subprocess +import time +import uuid +from dataclasses import dataclass, field +from datetime import datetime, timedelta +from decimal import Decimal +from enum import Enum, IntEnum +from importlib.resources import files +from ipaddress import IPv4Address +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List, + Optional, Set, Tuple, Type) + +import boto3 +import django +import mysql.connector +import psycopg +import pytest +from botocore.exceptions import (BotoCoreError, ClientError, + EndpointConnectionError) +from django.conf import settings as django_settings +from django.db import connection as django_connection +from django.db import models +from django.test.utils import override_settings +from psycopg import sql as pgsql +from psycopg.rows import class_row, dict_row, namedtuple_row, scalar_row +from psycopg.types.json import Jsonb +from sqlalchemy import (Column, ForeignKey, Integer, MetaData, String, Table, + create_engine) +from sqlalchemy import exc as sa_exc +from sqlalchemy import insert, select, text +from sqlalchemy.engine import URL +from sqlalchemy.orm import (DeclarativeBase, Session, joinedload, + mapped_column, relationship) +from sqlalchemy.types import UserDefinedType + +from aws_advanced_python_wrapper import AwsWrapperConnection +from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +from aws_advanced_python_wrapper.encryption.connection_source import ( + CallerConnectionSource, PluginConnectionSource) +from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService +from aws_advanced_python_wrapper.encryption.key_management_utility import \ + KeyManagementUtility +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.errors import (AwsWrapperError, + EncryptionError, + EncryptionFailedError, + IntegrityCheckError, + InvalidKeyMetadataError, + KeyManagementError, + MetadataError, + UnauthorizedMasterKeyError) +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory +from aws_advanced_python_wrapper.plugin_service import PluginManager +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) + +if TYPE_CHECKING: + from sqlalchemy.engine import Engine + + from aws_advanced_python_wrapper.plugin_service import PluginService + +_HOST = "127.0.0.1" +_REGION = "us-east-1" +_REQUIRED = ("PG_PORT", "MYSQL_PORT", "KMS_PORT", "DB_USER", "DB_PASSWORD", "DB_NAME", "PG_LOG_COMMAND", + "MYSQL_LOG_COMMAND") +_PORTS = ("PG_PORT", "MYSQL_PORT", "KMS_PORT") +_LOG_TIMEOUT = 120 # seconds for a log command +_STAMP = re.compile(r"kms_encryption trigger v(\d+)") +_INSERT = "INSERT INTO users (name, ssn) VALUES (%s, %s)" +_SELECT = "SELECT ssn FROM users WHERE name = %s ORDER BY id" +_INSERT_DOB = "INSERT INTO users (name, dob) VALUES (%s, %s)" +_SELECT_DOB = "SELECT dob FROM users WHERE name = %s ORDER BY id" +_COLUMN_SELECT = {"ssn": _SELECT, "dob": _SELECT_DOB} +_BUILDS = pytest.mark.parametrize("build", ["pg", "mysql-cext", "mysql-pure"]) +_MYSQL_BUILDS = pytest.mark.parametrize("build", ["mysql-cext", "mysql-pure"]) +_ENGINES = pytest.mark.parametrize("engine", ["pg", "mysql"]) +_CURSOR_CLASS = {"mysql-cext": "CMySQLCursor", "mysql-pure": "MySQLCursor"} +_ENGINE = {"pg": "pg", "mysql-cext": "mysql", "mysql-pure": "mysql"} +_SERVER = {"pg": "PostgreSQL", "mysql": "MySQL"} + +# The metadata DDL as the guide's "Create the metadata tables" gives it. +_PG_METADATA_DDL = """ +CREATE SCHEMA IF NOT EXISTS encrypt; + +CREATE TABLE encrypt.key_storage ( + id SERIAL PRIMARY KEY, + key_id VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL, + master_key_arn VARCHAR(512) NOT NULL, + encrypted_data_key TEXT NOT NULL, + hmac_key BYTEA NOT NULL, + key_spec VARCHAR(50) DEFAULT 'AES_256', + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + last_used_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE encrypt.encryption_metadata ( + table_name VARCHAR(255) NOT NULL, + column_name VARCHAR(255) NOT NULL, + encryption_algorithm VARCHAR(50) NOT NULL, + key_id INTEGER NOT NULL, + created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (table_name, column_name), + FOREIGN KEY (key_id) REFERENCES encrypt.key_storage(id) +); +""" + +_MYSQL_METADATA_DDL = """ +CREATE SCHEMA IF NOT EXISTS encrypt; + +CREATE TABLE encrypt.key_storage ( + id INT AUTO_INCREMENT PRIMARY KEY, + key_id VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL, + master_key_arn VARCHAR(512) NOT NULL, + encrypted_data_key TEXT NOT NULL, + hmac_key VARBINARY(32) NOT NULL, + key_spec VARCHAR(50) DEFAULT 'AES_256', + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + last_used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE encrypt.encryption_metadata ( + table_name VARCHAR(255) NOT NULL, + column_name VARCHAR(255) NOT NULL, + encryption_algorithm VARCHAR(50) NOT NULL, + key_id INT NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (table_name, column_name), + FOREIGN KEY (key_id) REFERENCES encrypt.key_storage(id) +); +""" + +_PG_TABLES = ( + "CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT, ssn BYTEA, dob BYTEA)", + """CREATE TRIGGER users_ssn_encrypted +BEFORE INSERT OR UPDATE ON users +FOR EACH ROW EXECUTE FUNCTION enforce_encrypted_column('ssn')""", + "CREATE TABLE addresses (id SERIAL PRIMARY KEY, user_id INTEGER, email TEXT)", +) + +_MYSQL_TABLES = ( + "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), ssn VARBINARY(1024), dob VARBINARY(1024))", + """CREATE TRIGGER users_ssn_hmac_check +BEFORE INSERT ON users +FOR EACH ROW +BEGIN + CALL validate_encrypted_data_hmac_before_insert('users', 'ssn', NEW.ssn); +END""", + """CREATE TRIGGER users_ssn_hmac_check_update +BEFORE UPDATE ON users +FOR EACH ROW +BEGIN + CALL validate_encrypted_data_hmac_before_update('users', 'ssn', NEW.ssn, OLD.ssn); +END""", + "CREATE TABLE addresses (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, email VARCHAR(100))", +) + +_MYSQL_RESET = ("DROP TABLE IF EXISTS addresses, users", "DROP DATABASE IF EXISTS encrypt", + "DROP FUNCTION IF EXISTS hmac_sha256", "DROP FUNCTION IF EXISTS verify_encrypted_data_hmac", + "DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_insert", + "DROP PROCEDURE IF EXISTS validate_encrypted_data_hmac_before_update") + + +@dataclass(frozen=True) +class _Env: + pg_port: int + mysql_port: int + kms_port: int + user: str + password: str = field(repr=False) + dbname: str + pg_log_command: str = field(repr=False) + mysql_log_command: str = field(repr=False) + + +@dataclass(frozen=True) +class _Bed: + """The seeded databases: per engine, the master key ARN and ``key_storage`` id of ``users.ssn``, and what the + standalone utility's DEBUG log showed while it gave ``users.dob`` its key rows (booleans only).""" + env: _Env + arns: Dict[str, str] + key_ids: Dict[str, int] + marker: str + utility_log: Dict[str, Dict[str, bool]] + + +@pytest.fixture(scope="module", autouse=True) +def _localstack_only() -> Iterator[None]: + # The plugin's AWS session reads the process environment, so this is what keeps ambient credentials out. + with pytest.MonkeyPatch.context() as patch: + for name, value in (("AWS_ACCESS_KEY_ID", "test"), ("AWS_SECRET_ACCESS_KEY", "test"), + ("AWS_CONFIG_FILE", os.devnull), ("AWS_SHARED_CREDENTIALS_FILE", os.devnull)): + patch.setenv(name, value) + for name in ("AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_SESSION_TOKEN", "AWS_SECURITY_TOKEN"): + patch.delenv(name, raising=False) + yield + + +@pytest.fixture(scope="module") +def env() -> _Env: + # Every value is read from os.environ by name, so no local holds the password and pytest's report can't show it. + missing = [name for name in _REQUIRED if not os.environ.get(name, "").strip()] + if missing: + pytest.fail(f"Set {', '.join(missing)}: the module docstring says what each one holds.") + not_ports = [name for name in _PORTS if not os.environ[name].strip().isdecimal()] + if not_ports: + pytest.fail(f"Set {', '.join(not_ports)} to a port number.") + return _Env(pg_port=int(os.environ["PG_PORT"]), mysql_port=int(os.environ["MYSQL_PORT"]), + kms_port=int(os.environ["KMS_PORT"]), user=os.environ["DB_USER"], password=os.environ["DB_PASSWORD"], + dbname=os.environ["DB_NAME"], pg_log_command=os.environ["PG_LOG_COMMAND"], mysql_log_command=os.environ["MYSQL_LOG_COMMAND"]) + + +def _plain(engine: str, env: _Env, *, root: bool = False) -> Any: + """A driver connection without the wrapper.""" + # The driver's connect frame holds the password, and pytest's report prints a raising frame's arguments, so the + # error is turned into a message here and the test fails outside the except block. + port = env.pg_port if engine == "pg" else env.mysql_port + try: + if engine == "pg": + return psycopg.connect(host=_HOST, port=port, user=env.user, password=env.password, dbname=env.dbname, + connect_timeout=5) + return mysql.connector.connect(host=_HOST, port=port, user="root" if root else env.user, + password=env.password, database=env.dbname, connection_timeout=5) + except (psycopg.Error, mysql.connector.Error) as err: + failure = f"Couldn't connect to {_SERVER[engine]} on {_HOST}:{port}: {type(err).__name__}: {err}" + pytest.fail(failure) + + +def _kms_props(env: _Env) -> Properties: + return Properties({"encryption_kms_region": _REGION, "encryption_kms_endpoint": f"http://{_HOST}:{env.kms_port}"}) + + +def _kms_client(env: _Env) -> Any: + config = EncryptionConfig.from_props(_kms_props(env), require_allowed_master_keys=False) + session = boto3.Session(aws_access_key_id="test", aws_secret_access_key="test", region_name=_REGION) + return KeyManager.create_kms_client(session, config) + + +@pytest.fixture(scope="module", autouse=True) +def _services(env: _Env, _localstack_only: None) -> None: + for engine in ("pg", "mysql"): + _plain(engine, env).close() # fails naming the server and its port + try: + _kms_client(env).list_keys() + reached = True + except (BotoCoreError, ClientError): + reached = False + if not reached: + pytest.fail(f"LocalStack's KMS isn't reachable on {_HOST}:{env.kms_port}; start it before running this module.") + + +def _trigger_sql(name: str) -> str: + """The trigger SQL as the installed package ships it.""" + return (files("aws_advanced_python_wrapper.encryption") / "sql" / name).read_text(encoding="utf-8") + + +def _check_stamp(name: str, row: Any) -> None: + if not _STAMP.search((row or [None])[0] or ""): + pytest.fail(f"{name} installed without its version stamp.") + + +def _utility(conn: Any, env: _Env, allowed: Optional[str] = None) -> KeyManagementUtility: + """A utility on a plain connection, with its KMS client built by ``create_kms_client`` as KeyManagementUtility's + docstring shows.""" + props = _kms_props(env) + if allowed is not None: + props["encryption_allowed_master_key_arns"] = allowed + config = EncryptionConfig.from_props(props, require_allowed_master_keys=False) + return KeyManagementUtility(conn, _kms_client(env), config) + + +def _encrypt_column(conn: Any, env: _Env) -> Tuple[str, int]: + """Turns encryption on for ``users.ssn`` under a new master key, then commits: the utility never does.""" + utility = _utility(conn, env) + arn = utility.create_master_key("live module users.ssn") + key_id = utility.initialize_encryption_for_column("users", "ssn", arn) + conn.commit() + return arn, key_id + + +def _encrypt_dob(engine: str, env: _Env, arn: str) -> Dict[str, bool]: + """Gives ``users.dob`` its own key row under ``users.ssn``'s master key, with the root logger at DEBUG and no + plugin connection opened yet in the process, then rotates it once with the plaintext filter removed. Returns + booleans only: the captured text holds a data key, so it is never kept.""" + parsers = logging.getLogger("botocore.parsers") + with _plain(engine, env) as conn: + utility = _utility(conn, env) + with _debug_log() as log: + utility.initialize_encryption_for_column("users", "dob", arn) + conn.commit() + seen = {"plaintext": '"Plaintext"' in log.getvalue(), + "kms-request": "TrentService.GenerateDataKey" in log.getvalue()} + # The positive control: without the filter, generating the next data key logs it. + removed = [f for f in parsers.filters if type(f).__name__ == "_NoKmsPlaintext"] + for f in removed: + parsers.removeFilter(f) + try: + with _debug_log() as log: + utility.rotate_data_key("users", "dob", arn) + conn.commit() + seen.update({"filter-found": bool(removed), "control-plaintext": '"Plaintext"' in log.getvalue()}) + finally: + for f in removed: + parsers.addFilter(f) + return seen + + +def _seed_pg(env: _Env) -> Tuple[str, int]: + with _plain("pg", env) as conn: + with conn.cursor() as cur: + for statement in ("DROP TABLE IF EXISTS addresses, users CASCADE", "DROP SCHEMA IF EXISTS encrypt CASCADE", + "DROP FUNCTION IF EXISTS enforce_encrypted_column() CASCADE", _PG_METADATA_DDL): + cur.execute(statement) + cur.execute(_trigger_sql("trigger_pg.sql").replace("SCHEMA_NAME", "encrypt")) # no parameters, or psycopg parses the file's % signs + cur.execute("SELECT obj_description('enforce_encrypted_column'::regproc, 'pg_proc')") + _check_stamp("trigger_pg.sql", cur.fetchone()) + for statement in _PG_TABLES: + cur.execute(statement) + conn.commit() + return _encrypt_column(conn, env) + + +def _run_script(cur: Any, script: str) -> None: + # mysql-connector 9.7 runs a script, DELIMITER lines included, in one execute(); on its C extension every result + # has to be read before the next statement. + cur.execute(script) + while cur.nextset(): + pass + + +def _seed_mysql(env: _Env) -> Tuple[str, int]: + # Root runs only the administrator's steps; DB_USER does the rest. Without log_bin_trust_function_creators, a user + # without SUPER can't create the routines or the triggers while binary logging is on. + with _plain("mysql", env, root=True) as root, root.cursor() as cur: + for statement in _MYSQL_RESET: + cur.execute(statement) + _run_script(cur, _MYSQL_METADATA_DDL) + cur.execute("SET GLOBAL log_bin_trust_function_creators = 1") + cur.execute("GRANT SELECT, INSERT, UPDATE, DELETE ON encrypt.* TO %s", (env.user,)) + with _plain("mysql", env) as conn: + with conn.cursor() as cur: + # The file asks for SCHEMA_NAME to be replaced with the metadata schema. + _run_script(cur, _trigger_sql("trigger_mysql.sql").replace("SCHEMA_NAME", "encrypt")) + cur.execute("SELECT ROUTINE_COMMENT FROM information_schema.ROUTINES WHERE ROUTINE_SCHEMA = DATABASE() " + "AND ROUTINE_NAME = 'validate_encrypted_data_hmac_before_insert'") + _check_stamp("trigger_mysql.sql", cur.fetchone()) + for statement in _MYSQL_TABLES: + cur.execute(statement) + conn.commit() + return _encrypt_column(conn, env) + + +@pytest.fixture(scope="module") +def bed(env: _Env, _services: None) -> _Bed: + seeds = {"pg": _seed_pg(env), "mysql": _seed_mysql(env)} + utility_log = {engine: _encrypt_dob(engine, env, seed[0]) for engine, seed in seeds.items()} + # The log checks count only what each server logs after this statement. + marker = f"kms_live_{uuid.uuid4().hex}" + for engine in seeds: + with _plain(engine, env) as conn, conn.cursor() as cur: + cur.execute("SELECT %s", (marker,)) + cur.fetchall() + return _Bed(env, {e: s[0] for e, s in seeds.items()}, {e: s[1] for e, s in seeds.items()}, marker, utility_log) + + +def _plugin_props(engine: str, bed: _Bed) -> Dict[str, Any]: + chain = WrapperProperties.DEFAULT_PLUGINS if engine == "pg" else WrapperProperties.MYSQL_CONNECTOR_DEFAULT_PLUGINS + return {"plugins": f"kms_encryption,{chain}", "wrapper_dialect": engine, + "encryption_allowed_master_key_arns": bed.arns[engine], **_kms_props(bed.env)} + + +def _connect(build: str, bed: _Bed, **overrides: Any) -> AwsWrapperConnection: + # As in _plain: the wrapper's connect frames hold the password, so the test fails outside the except block. + env, engine = bed.env, _ENGINE[build] + props = {**_plugin_props(engine, bed), **overrides} + port = env.pg_port if engine == "pg" else env.mysql_port + try: + if engine == "pg": + return AwsWrapperConnection.connect(psycopg.Connection.connect, host=_HOST, port=port, user=env.user, + password=env.password, dbname=env.dbname, **props) + return AwsWrapperConnection.connect(mysql.connector.Connect, host=_HOST, port=port, user=env.user, + password=env.password, database=env.dbname, + use_pure=build == "mysql-pure", **props) + except (psycopg.Error, mysql.connector.Error, AwsWrapperError) as err: + failure = (f"Couldn't connect to {_SERVER[engine]} on {_HOST}:{port} through the wrapper ({build}): " + f"{type(err).__name__}: {err}") + pytest.fail(failure) + + +class _Verifier: + """Reads stored values with a plain driver and opens them with EncryptionService and a KeyManager of its own: a + value counts as written only if a reader without the plugin finds a payload of the column's current key that + decrypts to it.""" + + def __init__(self, engine: str, bed: _Bed, column: str = "ssn"): + self._conn = _plain(engine, bed.env) + self._conn.autocommit = True + self._select = _COLUMN_SELECT[column] + config = EncryptionConfig.from_props(Properties(_kms_props(bed.env), + encryption_allowed_master_key_arns=bed.arns[engine])) + source = CallerConnectionSource(self._conn) + dialect = PgDriverDialect(Properties()) if engine == "pg" else MySQLDriverDialect(Properties()) + metadata = MetadataManager(source, dialect, dialect, config) + found = metadata.column_config("users", column) + metadata.close() + if (found is None or found.key_id is None or found.key_metadata is None + or found.key_metadata.hmac_key is None): + pytest.fail(f"users.{column} has no usable key row after seeding.") + self._key_id = bed.key_ids[engine] if column == "ssn" else found.key_id + self._key = found.key_metadata + self._hmac_key = found.key_metadata.hmac_key + self._algorithm = found.algorithm + self._cache = DataKeyCache(10, 60.0, start_cleanup_thread=False) + self._keys = KeyManager(_kms_client(bed.env), source, dialect, dialect, config, self._cache) + + def stored(self, name: str) -> List[Any]: + with self._conn.cursor() as cur: + cur.execute(self._select, (name,)) + return [row[0] for row in cur.fetchall()] + + def check(self, name: str, expected: List[Any]) -> None: + stored = self.stored(name) + assert len(stored) == len(expected) + for value, want in zip(stored, expected): + if want is None: + assert value is None + continue + payload = bytes(value) + assert len(payload) >= 65 and EncryptionService.key_id_from_payload(payload) == self._key_id + data_key = self._keys.decrypt_data_key(self._key.encrypted_data_key, self._key.master_key_arn) + hmac_key = bytearray(self._hmac_key) + try: + plain = EncryptionService.decrypt(payload, data_key, hmac_key, self._algorithm) + finally: + EncryptionService.wipe(data_key) + EncryptionService.wipe(hmac_key) + assert plain == want and type(plain) is type(want) + + def seal(self, value: Any) -> Optional[bytes]: + """The payload a writer other than the plugin would store for ``value`` under this column's key.""" + data_key = self._keys.decrypt_data_key(self._key.encrypted_data_key, self._key.master_key_arn) + hmac_key = bytearray(self._hmac_key) + try: + return EncryptionService.encrypt(value, data_key, hmac_key, self._algorithm, key_id=self._key_id) + finally: + EncryptionService.wipe(data_key) + EncryptionService.wipe(hmac_key) + + def empty(self) -> None: + with self._conn.cursor() as cur: + cur.execute("DELETE FROM addresses") + cur.execute("DELETE FROM users") + + def close(self) -> None: + self._cache.close() + self._conn.close() + + +@pytest.fixture(scope="module") +def verifiers(bed: _Bed) -> Iterator[Dict[str, _Verifier]]: + opened = {engine: _Verifier(engine, bed) for engine in ("pg", "mysql")} + yield opened + for verifier in opened.values(): + verifier.close() + + +@pytest.fixture(autouse=True) +def _empty_tables(verifiers: Dict[str, _Verifier]) -> None: + # Each test writes the rows it reads, so no test depends on another one's. + for verifier in verifiers.values(): + verifier.empty() + + +@dataclass(frozen=True) +class _Db: + conn: AwsWrapperConnection + verifier: _Verifier + + +@pytest.fixture +def db(build: str, bed: _Bed, verifiers: Dict[str, _Verifier]) -> Iterator[_Db]: + with _connect(build, bed) as conn: + if build in _CURSOR_CLASS: # so a missing C extension fails instead of running the pure build twice + with conn.cursor() as cur: + driver_class = type(cur.target_cursor).__name__ + if driver_class != _CURSOR_CLASS[build]: + pytest.fail(f"On {build} the driver's cursor is a {driver_class}, not a {_CURSOR_CLASS[build]}.") + yield _Db(conn, verifiers[_ENGINE[build]]) + + +def _write(conn: AwsWrapperConnection, sql: str, params: Any) -> None: + with conn.cursor() as cur: + cur.execute(sql, params) + conn.commit() + + +def _read_one(conn: AwsWrapperConnection, name: str) -> Any: + with conn.cursor() as cur: + cur.execute(_SELECT, (name,)) + row = cur.fetchone() + cur.fetchall() # an unread row on mysql-connector's default cursor would fail the next statement + return None if row is None else row[0] + + +def _write_many(conn: AwsWrapperConnection, name: str, as_generator: bool = False) -> List[str]: + values = [f"pt-{name}-{i}" for i in range(3)] + rows = [(name, value) for value in values] + with conn.cursor() as cur: + cur.executemany(_INSERT, (row for row in rows) if as_generator else rows) + conn.commit() + return values + + +# ---- DB-API: psycopg, and mysql-connector on its C extension and with use_pure=True ---- + +@_BUILDS +@pytest.mark.parametrize("sql, params, by_keyword, want", [ + pytest.param(_INSERT, ("d1", "pt-tuple-1"), False, "pt-tuple-1", id="insert-tuple"), + pytest.param(_INSERT, ["d1", "pt-tuple-1"], False, "pt-tuple-1", id="caller-params-unchanged"), + pytest.param("INSERT INTO users (name, ssn) VALUES (%(n)s, %(s)s)", {"n": "d1", "s": "pt-dict-2"}, False, + "pt-dict-2", id="insert-dict"), + pytest.param(_INSERT, ("d1", "pt-kw-3"), True, "pt-kw-3", id="params-keyword"), + pytest.param(_INSERT, ("d1", 42), False, 42, id="insert-int"), + pytest.param(_INSERT, ("d1", None), False, None, id="insert-null")]) +def test_write_stores_a_payload(db: _Db, sql: str, params: Any, by_keyword: bool, want: Any) -> None: + caller = copy.copy(params) + with db.conn.cursor() as cur: + if by_keyword: + cur.execute(sql, params=params) + else: + cur.execute(sql, params) + db.conn.commit() + assert params == caller + value = _read_one(db.conn, "d1") + assert value == want and type(value) is type(want) + db.verifier.check("d1", [want]) + + +@_BUILDS +@pytest.mark.parametrize("as_generator", [False, True], ids=["list", "generator"]) +def test_executemany_stores_every_row(db: _Db, as_generator: bool) -> None: + name = "g" if as_generator else "m" + db.verifier.check(name, _write_many(db.conn, name, as_generator)) + + +@_BUILDS +def test_update_stores_a_new_payload(db: _Db) -> None: + _write(db.conn, _INSERT, ("d1", "pt-tuple-1")) + _write(db.conn, "UPDATE users SET ssn = %s WHERE name = %s", ("pt-upd-1", "d1")) + assert _read_one(db.conn, "d1") == "pt-upd-1" + db.verifier.check("d1", ["pt-upd-1"]) + + +@_BUILDS +@pytest.mark.parametrize("read", ["fetchall", "fetchmany", "fetchone", "next", "iterate"]) +def test_reads_decrypt_rows_in_order(db: _Db, read: str) -> None: + want = _write_many(db.conn, "m") + with db.conn.cursor() as cur: + cur.execute(_SELECT, ("m",)) + if read == "fetchall": + got = [row[0] for row in cur.fetchall()] + elif read == "fetchmany": + got = [row[0] for row in cur.fetchmany(2)] + [row[0] for row in cur.fetchmany(5)] + elif read == "fetchone": + got = [cur.fetchone()[0] for _ in want] + assert cur.fetchone() is None + elif read == "next": # psycopg 3.3's cursor is its own iterator; mysql-connector's isn't + got = [next(cur)[0] for _ in want] + with pytest.raises(StopIteration): + next(cur) + else: + got = [row[0] for row in cur] + assert got == want + db.verifier.check("m", want) + + +@_BUILDS +@pytest.mark.parametrize("sql, params, at, want", [ + pytest.param("SELECT * FROM users WHERE name = %s", ("d1",), 2, "pt-tuple-1", id="select-star"), + pytest.param("SELECT count(*) FROM users WHERE ssn = %s", ("pt-tuple-1",), 0, 0, id="where-never-matches"), + pytest.param("SELECT s.ssn FROM (SELECT ssn FROM users WHERE name = %s) s", ("d1",), 0, "pt-tuple-1", + id="derived-table"), + pytest.param("WITH w AS (SELECT ssn FROM users WHERE name = %s) SELECT ssn FROM w", ("d1",), 0, "pt-tuple-1", + id="cte")]) +def test_one_row_reads(db: _Db, sql: str, params: Tuple[str], at: int, want: Any) -> None: + # An equality on the encrypted column compares payloads, so it never matches; the others decrypt. + _write(db.conn, _INSERT, ("d1", "pt-tuple-1")) + with db.conn.cursor() as cur: + cur.execute(sql, params) + assert cur.fetchone()[at] == want + db.verifier.check("d1", ["pt-tuple-1"]) + + +@pytest.mark.parametrize("build", ["pg"]) +@pytest.mark.parametrize("read", ["chained-fetchone", "chained-iterate", "named-cursor", "dict-row"]) +def test_psycopg_chained_named_and_dict_row_reads(db: _Db, read: str) -> None: + values = _write_many(db.conn, "m") + want = values + cursor_args: Dict[str, Any] = {"named-cursor": {"name": "live_named"}, "dict-row": {"row_factory": dict_row}} + with db.conn.cursor(**cursor_args.get(read, {})) as cur: + chained = cur.execute(_SELECT, ("m",)) + if read == "chained-fetchone": + got = [chained.fetchone()[0]] + want = values[:1] + elif read == "dict-row": + got = [cur.fetchone()["ssn"]] + want = values[:1] + else: + got = [row[0] for row in (chained if read == "chained-iterate" else cur)] + db.conn.commit() + assert got == want + db.verifier.check("m", values) + + +@_MYSQL_BUILDS +@pytest.mark.parametrize("cursor_args", [{"dictionary": True}, {"buffered": True}], ids=["dictionary", "buffered"]) +def test_mysql_dictionary_and_buffered_cursors(db: _Db, cursor_args: Dict[str, bool]) -> None: + _write(db.conn, _INSERT, ("d2", "pt-dict-2")) + with db.conn.cursor(**cursor_args) as cur: + cur.execute(_SELECT, ("d2",)) + row = cur.fetchone() + assert (row["ssn"] if "dictionary" in cursor_args else row[0]) == "pt-dict-2" + db.verifier.check("d2", ["pt-dict-2"]) + + +@_BUILDS +def test_literal_into_the_encrypted_column_is_refused(db: _Db) -> None: + with db.conn.cursor() as cur, pytest.raises(MetadataError) as raised: + cur.execute("INSERT INTO users (name, ssn) VALUES (%s, 'net-literal')", ("refused",)) + db.conn.rollback() + err = raised.value + assert type(err).__module__ == "aws_advanced_python_wrapper" + assert (err.table_name, err.column_name) == ("users", "ssn") + assert err.__cause__ is None and err.__context__ is None + assert db.verifier.stored("refused") == [] + + +@_BUILDS +def test_insert_without_a_column_list_reaches_the_trigger(db: _Db, build: str) -> None: + # Passed through with a warning; the server log checks find each control value once. + control = {"pg": "net-unanalysed", "mysql-cext": "net-unanalysed-cext", "mysql-pure": "net-unanalysed-pure"}[build] + with db.conn.cursor() as cur, pytest.raises(AwsWrapperError) as raised: + cur.execute("INSERT INTO users VALUES (DEFAULT, %s, %s, NULL)", ("netrow", control)) + db.conn.rollback() + assert type(raised.value) is AwsWrapperError + assert isinstance(raised.value.__cause__, (psycopg.Error, mysql.connector.Error)) + assert db.verifier.stored("netrow") == [] + + +# ---- SQLAlchemy Core and ORM ---- + +class EncryptedValue(UserDefinedType): + cache_ok = True + + def get_col_spec(self, **kw: Any) -> str: + return "BYTEA" + + +# The guide's pass-through type on PostgreSQL, where SQLAlchemy would cast a typed parameter that bytea rejects. +_SSN = EncryptedValue().with_variant(String(1024), "mysql") +_USERS = Table("users", MetaData(), Column("id", Integer, primary_key=True), Column("name", String(100)), + Column("ssn", _SSN)) + + +class _Base(DeclarativeBase): + pass + + +class _User(_Base): + __tablename__ = "users" + id = mapped_column(Integer, primary_key=True) + name = mapped_column(String(100)) + ssn = mapped_column(_SSN) + + +class _JoinedBase(DeclarativeBase): + pass + + +class _Owner(_JoinedBase): + """``users`` with its addresses loaded by a join, so a LIMIT reads the encrypted column through a subquery.""" + __tablename__ = "users" + id = mapped_column(Integer, primary_key=True) + name = mapped_column(String(100)) + ssn = mapped_column(_SSN) + addresses = relationship("_Address", lazy="joined", order_by="_Address.id") + + +class _Address(_JoinedBase): + __tablename__ = "addresses" + id = mapped_column(Integer, primary_key=True) + user_id = mapped_column(ForeignKey("users.id")) + email = mapped_column(String(100)) + + +@dataclass(frozen=True) +class _Orm: + engine: Engine + verifier: _Verifier + + +@pytest.fixture +def sa(engine: str, bed: _Bed, verifiers: Dict[str, _Verifier]) -> Iterator[_Orm]: + env, pg = bed.env, engine == "pg" + url = URL.create("postgresql+aws_wrapper_psycopg" if pg else "mysql+aws_wrapper_mysqlconnector", + username=env.user, password=env.password, host=_HOST, + port=env.pg_port if pg else env.mysql_port, database=env.dbname) + sa_engine = create_engine(url, connect_args=_plugin_props(engine, bed)) # a ?plugins= in the URL would be dropped + yield _Orm(sa_engine, verifiers[engine]) + sa_engine.dispose() + + +@_ENGINES +@pytest.mark.parametrize("shape", ["insert-values-select-scalar", "executemany-select-all", "result-iteration"]) +def test_core_writes_and_reads(sa: _Orm, shape: str) -> None: + want = ["pt-sa-core-1"] if shape == "insert-values-select-scalar" else ["pt-sa-many-0", "pt-sa-many-1"] + with sa.engine.begin() as conn: + if len(want) == 1: + conn.execute(insert(_USERS).values(name="sa", ssn=want[0])) + else: + conn.execute(insert(_USERS), [{"name": "sa", "ssn": value} for value in want]) + query = select(_USERS.c.ssn).where(_USERS.c.name == "sa").order_by(_USERS.c.id) + with sa.engine.connect() as conn: + if len(want) == 1: + got = [conn.execute(query).scalar()] + else: + got = [row.ssn if shape == "executemany-select-all" else row[0] for row in conn.execute(query)] + assert got == want + sa.verifier.check("sa", want) + + +def _orm_users(sa: _Orm, values: List[str]) -> List[int]: + with Session(sa.engine) as session: + session.add_all([_User(name="orm", ssn=value) for value in values]) + session.commit() + return [user.id for user in session.scalars(select(_User).where(_User.name == "orm").order_by(_User.id))] + + +@_ENGINES +@pytest.mark.parametrize("read", ["add-all-scalars", "session-get", "legacy-filter-by-first"]) +def test_orm_reads(sa: _Orm, read: str) -> None: + values = [f"pt-orm-{i}" for i in range(3)] + ids = _orm_users(sa, values) + with Session(sa.engine) as session: + if read == "add-all-scalars": + users: List[Optional[_User]] = list(session.scalars(select(_User).where(_User.name == "orm") + .order_by(_User.id))) + want = values + elif read == "session-get": + users = [session.get(_User, ids[1])] + want = values[1:2] + else: + users = [session.query(_User).filter_by(id=ids[2]).first()] + want = values[2:] + assert [user.ssn if user else None for user in users] == want + sa.verifier.check("orm", values) + + +@_ENGINES +def test_orm_attribute_update(sa: _Orm) -> None: + ids = _orm_users(sa, [f"pt-orm-{i}" for i in range(3)]) + with Session(sa.engine) as session: + user = session.get(_User, ids[0]) + assert user is not None + user.ssn = "pt-orm-upd" + session.commit() + with Session(sa.engine) as session: + user = session.get(_User, ids[0]) + assert user is not None and user.ssn == "pt-orm-upd" + sa.verifier.check("orm", ["pt-orm-upd", "pt-orm-1", "pt-orm-2"]) + + +@_ENGINES +@pytest.mark.parametrize("read", ["legacy-query-first", "joinedload-limit"]) +def test_joined_eager_reads(sa: _Orm, read: str) -> None: + with Session(sa.engine) as session: + owner = _Owner(name="ow", ssn="pt-owner-1", addresses=[_Address(email="a1@example.com"), + _Address(email="a2@example.com")]) + session.add(owner) + session.commit() + owner_id = owner.id + with Session(sa.engine) as session: + if read == "legacy-query-first": + found = session.query(_Owner).filter(_Owner.id == owner_id).first() + else: + found = session.scalars(select(_Owner).options(joinedload(_Owner.addresses)).limit(1)).unique().first() + assert found is not None and found.ssn == "pt-owner-1" and len(found.addresses) == 2 + sa.verifier.check("ow", ["pt-owner-1"]) + + +# ---- botocore at DEBUG ---- + +@contextlib.contextmanager +def _debug_log() -> Iterator[io.StringIO]: + # While the root logger is at DEBUG, this handler is its only one, so the data key that the positive control logs + # reaches no other handler, pytest's included, and so no report. + root = logging.getLogger() + level, others = root.level, list(root.handlers) + buffer = io.StringIO() + handler = logging.StreamHandler(buffer) + for other in others: + root.removeHandler(other) + root.addHandler(handler) + root.setLevel(logging.DEBUG) + try: + yield buffer + finally: + root.removeHandler(handler) + root.setLevel(level) + for other in others: + root.addHandler(other) + + +@_ENGINES +def test_debug_log_holds_no_data_key(engine: str, bed: _Bed, verifiers: Dict[str, _Verifier]) -> None: + build = "pg" if engine == "pg" else "mysql-cext" + with _connect(build, bed) as conn: + _write(conn, _INSERT, ("dbg", "pt-debug-1")) + verifiers[engine].check("dbg", ["pt-debug-1"]) + with _debug_log() as log, _connect(build, bed) as conn: # a new connection decrypts its data key through KMS + value = _read_one(conn, "dbg") + holds_plaintext, logged_decrypt = '"Plaintext"' in log.getvalue(), "TrentService.Decrypt" in log.getvalue() + assert value == "pt-debug-1" and not holds_plaintext and logged_decrypt + # The positive control: without the filter the same read logs the data key. + parsers = logging.getLogger("botocore.parsers") + removed = [f for f in parsers.filters if type(f).__name__ == "_NoKmsPlaintext"] + for f in removed: + parsers.removeFilter(f) + try: + with _debug_log() as log, _connect(build, bed) as conn: + _read_one(conn, "dbg") + control_logged = '"Plaintext"' in log.getvalue() + finally: + for f in removed: + parsers.addFilter(f) + assert removed and control_logged + + +# ---- Django on MySQL ---- + +@pytest.fixture(scope="module") +def django_model(bed: _Bed) -> Iterator[Any]: + env = bed.env + if django_settings.configured: # another module's settings would point these shapes at another database + pytest.fail("Django settings are already configured in this process; run this module on its own.") + django_settings.configure( + DEBUG=False, USE_TZ=False, INSTALLED_APPS=[], DEFAULT_AUTO_FIELD="django.db.models.AutoField", + DATABASES={"default": {"ENGINE": "aws_advanced_python_wrapper.django.backends.mysql_connector", + "NAME": env.dbname, "USER": env.user, "PASSWORD": env.password, "HOST": _HOST, + "PORT": env.mysql_port, "OPTIONS": _plugin_props("mysql", bed)}}) + django.setup() + + class LiveUser(models.Model): + name: models.CharField[str, str] = models.CharField(max_length=100) + ssn: models.CharField[Optional[str], Optional[str]] = models.CharField(max_length=100, null=True) + + class Meta: + app_label = "kms_live" + db_table = "users" + managed = False + + yield LiveUser + django_connection.close() + + +@pytest.mark.parametrize("write", ["create", "bulk-create", "save", "queryset-update"]) +def test_django_writes(django_model: Any, verifiers: Dict[str, _Verifier], write: str) -> None: + objects = django_model.objects + if write == "bulk-create": + want = ["pt-djb-0", "pt-djb-1"] + assert len(objects.bulk_create([django_model(name="dj", ssn=value) for value in want])) == 2 + else: + want = [{"create": "pt-dj-1", "save": "pt-dj-upd", "queryset-update": "pt-dj-qsupd"}[write]] + assert objects.create(name="dj", ssn="pt-dj-1").ssn == "pt-dj-1" + if write == "save": + user = objects.get(name="dj") + user.ssn = want[0] + user.save() + elif write == "queryset-update": + objects.filter(name="dj").update(ssn=want[0]) + assert objects.get(name="dj").ssn == want[0] + verifiers["mysql"].check("dj", want) + + +@pytest.mark.parametrize("read", ["get", "values-list", "iterator", "raw", "connection-cursor"]) +def test_django_reads(django_model: Any, verifiers: Dict[str, _Verifier], read: str) -> None: + want = ["pt-djb-0", "pt-djb-1"] + django_model.objects.bulk_create([django_model(name="djb", ssn=value) for value in want]) + rows = django_model.objects.filter(name="djb").order_by("id") + if read == "get": + got = [django_model.objects.get(pk=pk).ssn for pk in rows.values_list("id", flat=True)] + elif read == "values-list": + got = list(rows.values_list("ssn", flat=True)) + elif read == "iterator": + got = [user.ssn for user in rows.iterator(chunk_size=1)] + elif read == "raw": + got = [user.ssn for user in django_model.objects.raw("SELECT id, name, ssn FROM users WHERE name = %s " + "ORDER BY id", ["djb"])] + else: + with django_connection.cursor() as cur: + cur.execute(_SELECT, ["djb"]) + got = [row[0] for row in cur] + assert got == want + verifiers["mysql"].check("djb", want) + + +# ---- The servers' own logs (after every test above, so they cover them) ---- + +def _log_lines(bed: _Bed, variable: str) -> List[bytes]: + """The lines a server logged after this run's marker statement, from the command in ``variable``. + + A failure names the variable and holds neither the command nor its output; the tests report counts, never a line. + """ + command = bed.env.pg_log_command if variable == "PG_LOG_COMMAND" else bed.env.mysql_log_command + failure = "" + try: + done = subprocess.run(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + timeout=_LOG_TIMEOUT) + except subprocess.TimeoutExpired: # its text holds the command + failure = f"{variable} didn't finish within {_LOG_TIMEOUT} seconds." + except (OSError, ValueError): # no such program, one that can't run, or an unclosed quote + failure = f"{variable} couldn't be started; check its program and its quoting." + if failure: + pytest.fail(failure) + if done.returncode != 0: + pytest.fail(f"{variable} exited with status {done.returncode}.") + lines = done.stdout.splitlines() + starts = [i for i, line in enumerate(lines) if bed.marker.encode() in line] + if not starts: + pytest.fail(f"The output of {variable} has no line with this run's marker statement.") + return lines[starts[-1] + 1:] + + +def _counts(lines: List[bytes], needles: Tuple[str, ...]) -> Dict[str, int]: + return {needle: sum(needle.encode() in line for line in lines) for needle in needles} + + +def test_postgresql_log_holds_no_plaintext(bed: _Bed) -> None: + lines = _log_lines(bed, "PG_LOG_COMMAND") + total = len(lines) + # PostgreSQL logs a bytea parameter in hex, so a "pt-" value bound as bytes would show as '\x70742d. + # A read of PostgreSQL's container log now and then comes back without some of the lines the log holds. When a + # PostgreSQL log test is the run's only failure and its only count off is one expected above 0 that came out lower, + # re-run the module once: a wrong command misses the line again, and a missed read almost never does. A count + # expected to be 0 that comes out above 0 is a leak even when it is the run's only failure. + counts = _counts(lines, ("pt-", r"'\x70742d", "net-literal", r"'\x6e65742d")) + assert total > 0 + assert counts == {"pt-": 0, r"'\x70742d": 0, "net-literal": 0, r"'\x6e65742d": 1} + + +def test_mysql_general_log_holds_no_plaintext(bed: _Bed) -> None: + lines = _log_lines(bed, "MYSQL_LOG_COMMAND") + total, writes = len(lines), sum(bool(re.search(rb"(?i)(INSERT INTO|UPDATE) `?users", line)) for line in lines) + # The general log holds each encrypted value as raw bytes, so even a run without a leak can show "pt-" by chance, + # though rarely. When this test is the run's only failure and "pt-" its only count off, re-run the module once: a + # leak repeats and a chance match almost never does, so treat a second hit as a leak. + counts = _counts(lines, ("pt-", "net-literal", "net-unanalysed-cext", "net-unanalysed-pure")) + assert total > 0 and writes > 0 + assert counts == {"pt-": 0, "net-literal": 0, "net-unanalysed-cext": 1, "net-unanalysed-pure": 1} + + +# ---- Further checks: error classes, target_cursor, key rows, logging and driver quirks ---- +# They run after the two log tests above, so those tests' counts don't include them. Plaintexts written through the +# plugin here start with "pt-x-", and values meant to reach a server unencrypted with "net-x-"; the file's last two +# tests count them, and count _NAIVE_DATETIME, which can't carry a prefix, by its time of day. + +_LITERAL = "INSERT INTO users (name, ssn) VALUES (%s, 'net-x-literal')" +_SET_ARN = "UPDATE encrypt.key_storage SET master_key_arn = %s WHERE id = %s" +_FOREIGN_KEY_ID = 987654321 # no key_storage row has it +_READS = ("fetchone", "fetchmany", "fetchall", "iterate", "chained") # mysql-connector's execute returns None + + +def _per_build(options: Tuple[str, ...], pg_only: Tuple[str, ...] = (), mysql_only: Tuple[str, ...] = ()) -> List[Any]: + return [pytest.param(build, option, id=f"{build}-{option}") for build in _ENGINE for option in options + if option not in (mysql_only if build == "pg" else pg_only)] + + +def _plain_rows(engine: str, env: _Env, sql: str, params: Any) -> List[Any]: + """The first column of every row a plain driver reads.""" + with _plain(engine, env) as conn, conn.cursor() as cur: + cur.execute(sql, params) + return [row[0] for row in cur.fetchall()] + + +def _plain_write(engine: str, env: _Env, sql: str, params: Any) -> None: + with _plain(engine, env) as conn: + with conn.cursor() as cur: + cur.execute(sql, params) + conn.commit() + + +def _key_id(engine: str, env: _Env, column: str) -> int: + """The column's current ``key_storage`` id, read when the test runs, since a rotation changes it.""" + return int(_plain_rows(engine, env, "SELECT key_id FROM encrypt.encryption_metadata WHERE table_name = %s " + "AND column_name = %s", ("users", column))[0]) + + +@contextlib.contextmanager +def _dob_verifier(engine: str, bed: _Bed) -> Iterator[_Verifier]: + verifier = _Verifier(engine, bed, "dob") + try: + yield verifier + finally: + verifier.close() + + +def _read_all(conn: AwsWrapperConnection, sql: str, name: str) -> List[Any]: + with conn.cursor() as cur: + cur.execute(sql, (name,)) + return [row[0] for row in cur.fetchall()] + + +def _write_tampered(build: str, bed: _Bed) -> None: + """Row ``x-tamper``: ``pt-x-dob`` written through the plugin, then its last byte flipped with a plain driver. The + payload keeps the column's key id, so reading it fails the HMAC check and no other key row is looked up.""" + engine = _ENGINE[build] + with _connect(build, bed) as conn: + _write(conn, _INSERT_DOB, ("x-tamper", "pt-x-dob")) + stored = bytes(_plain_rows(engine, bed.env, _SELECT_DOB, ("x-tamper",))[0]) + tampered = stored[:-1] + bytes([stored[-1] ^ 0x01]) + _plain_write(engine, bed.env, "UPDATE users SET dob = %s WHERE name = %s", (tampered, "x-tamper")) + + +def _read_tampered(cur: Any, read: str) -> Any: + if read == "chained": + return cur.execute(_SELECT_DOB, ("x-tamper",)).fetchone() + cur.execute(_SELECT_DOB, ("x-tamper",)) + if read == "fetchone": + return cur.fetchone() + if read == "fetchmany": + return cur.fetchmany(2) + return cur.fetchall() if read == "fetchall" else list(cur) + + +@contextlib.contextmanager +def _refused(conn: AwsWrapperConnection, cls: Type[BaseException], kms_requests: Optional[int] = None) -> Iterator[Any]: + """Expects exactly ``cls`` from the block, run with the root logger at DEBUG: no failover record names it, and if + ``kms_requests`` is given, that many captured lines name a KMS operation (one request logs more than one; the + captured text is only counted). After a rollback the connection still runs ``SELECT 1``. The rollback also + discards rows a failed read left unread on mysql-connector's default cursor.""" + with _debug_log() as log: + with pytest.raises(cls) as raised: + yield raised + lines = log.getvalue().splitlines() + named = sum("failover" in line.lower() and cls.__name__ in line for line in lines) + sent = sum("TrentService." in line for line in lines) + assert type(raised.value) is cls and named == 0 + if kms_requests is not None: + assert sent == kms_requests + conn.rollback() + with conn.cursor() as cur: + cur.execute("SELECT 1") + assert cur.fetchone()[0] == 1 + + +# Error classes as the application sees them through the default chains, failover_v2 included. + +@pytest.mark.parametrize("build, read", _per_build(_READS, pg_only=("chained",))) +def test_tampered_value_raises_integrity_check_error(db: _Db, bed: _Bed, build: str, read: str) -> None: + _write_tampered(build, bed) + with _refused(db.conn, IntegrityCheckError), db.conn.cursor() as cur: + _read_tampered(cur, read) + + +@_ENGINES +def test_tampered_value_through_sqlalchemy_raises_integrity_error(sa: _Orm, bed: _Bed, engine: str) -> None: + _write_tampered("pg" if engine == "pg" else "mysql-cext", bed) + with sa.engine.connect() as conn, pytest.raises(sa_exc.IntegrityError) as raised: + conn.execute(text("SELECT dob FROM users WHERE name = :n"), {"n": "x-tamper"}).scalar() + assert type(raised.value) is sa_exc.IntegrityError and type(raised.value.orig) is IntegrityCheckError + + +@pytest.mark.parametrize("build, call", _per_build(("execute", "executemany"))) +def test_unserializable_value_keeps_the_encryption_service_error(db: _Db, call: str) -> None: + with pytest.raises(EncryptionError) as direct: # what the encryption service raises for it on its own + EncryptionService.encrypt(2 ** 70, bytearray(32), bytearray(32), "AES-256-GCM", key_id=1) + expected = type(direct.value) + with _refused(db.conn, expected), db.conn.cursor() as cur: + if call == "execute": + cur.execute(_INSERT, ("x-big", 2 ** 70)) + else: + cur.executemany(_INSERT, [("x-big", 2 ** 70)]) + assert expected is EncryptionFailedError and db.verifier.stored("x-big") == [] + + +@_BUILDS +def test_literal_through_executemany_is_refused(db: _Db) -> None: + with _refused(db.conn, MetadataError) as raised, db.conn.cursor() as cur: + cur.executemany(_LITERAL, [("x-lit",)]) + err = raised.value + assert (err.table_name, err.column_name) == ("users", "ssn") + assert err.__cause__ is None and err.__context__ is None + assert db.verifier.stored("x-lit") == [] + + +@_BUILDS +def test_hidden_placeholder_on_an_encrypted_table_is_refused(db: _Db) -> None: + # Both drivers bind the %s in the comment too, so the plugin can't tell which value goes to ssn. Refused before + # anything is sent, so the "pt-x-" count of the last two tests stays 0. + with _refused(db.conn, MetadataError) as raised, db.conn.cursor() as cur: + cur.execute("INSERT INTO users (name, ssn) VALUES (%s, %s) /* %s */", ("x-hidden", "pt-x-hidden", "x-comment")) + err = raised.value + assert str(err) == Messages.get_formatted("KmsEncryptionPlugin.HiddenPlaceholder", "users") + assert err.__cause__ is None and err.__context__ is None + assert db.verifier.stored("x-hidden") == [] + + +@_BUILDS +def test_unsafe_comparison_on_an_encrypted_column_is_refused(db: _Db, bed: _Bed, build: str) -> None: + # An encrypted value equals no stored value, so these comparisons would match every row or arbitrary rows (the + # first would delete every row). They are refused before anything is sent, so no "pt-x-" value reaches a server. + rows = {"x-cmp-1": "pt-x-cmp-1", "x-cmp-2": "pt-x-cmp-2"} + for row in rows.items(): + _write(db.conn, _INSERT, row) + names = "SELECT name FROM users ORDER BY name" + for sql, params in (("DELETE FROM users WHERE ssn <> %s", ("pt-x-cmp-neq",)), + ("DELETE FROM users WHERE id NOT IN (SELECT id FROM users WHERE ssn = %s)", ("pt-x-cmp-not-in",)), + ("UPDATE users SET name = %s WHERE ssn > %s", ("x-cmp-renamed", "pt-x-cmp-gt")), + ("SELECT name FROM users WHERE ssn NOT LIKE %s", ("pt-x-cmp-not-like",))): + with _refused(db.conn, MetadataError) as raised, db.conn.cursor() as cur: + cur.execute(sql, params) + err = raised.value + assert str(err) == Messages.get_formatted("KmsEncryptionPlugin.UnsafeComparison", "users.ssn") + assert (err.table_name, err.column_name) == ("users", "ssn") + assert err.__cause__ is None and err.__context__ is None + assert _plain_rows(_ENGINE[build], bed.env, names, ()) == list(rows) + # An equality is encrypted and still runs: it matches nothing. + with db.conn.cursor() as cur: + cur.execute("DELETE FROM users WHERE ssn = %s", ("pt-x-cmp-eq",)) + deleted = cur.rowcount + cur.execute("WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w", ("pt-x-cmp-cte",)) + found = cur.fetchall() + db.conn.commit() + assert deleted == 0 and found == [] + assert _plain_rows(_ENGINE[build], bed.env, names, ()) == list(rows) + for name, value in rows.items(): + db.verifier.check(name, [value]) + + +def _refused_write_or_read(build: str, bed: _Bed, call: str, label: str, cls: Type[BaseException], + kms_requests: Optional[int] = None, **overrides: Any) -> Any: + """A write, or a read of a row a normal connection wrote first, on a connection with ``overrides``.""" + name, value = f"x-{label}", f"pt-x-{label}" + if call == "read": + with _connect(build, bed) as conn: + _write(conn, _INSERT, (name, value)) + with _connect(build, bed, **overrides) as conn: + with _refused(conn, cls, kms_requests) as raised, conn.cursor() as cur: + if call == "write": + cur.execute(_INSERT, (name, value)) + else: + cur.execute(_SELECT, (name,)) + cur.fetchone() + assert len(_plain_rows(_ENGINE[build], bed.env, _SELECT, (name,))) == (1 if call == "read" else 0) + return raised.value + + +@pytest.mark.parametrize("build, call", _per_build(("write", "read"))) +def test_master_key_outside_the_allow_list_is_refused(bed: _Bed, build: str, call: str) -> None: + other = bed.arns["mysql" if _ENGINE[build] == "pg" else "pg"] # a LocalStack key this run made for the other engine + # Refused before any KMS request: the captured DEBUG text names no TrentService operation. + _refused_write_or_read(build, bed, call, "unauth", UnauthorizedMasterKeyError, kms_requests=0, + encryption_allowed_master_key_arns=other) + + +@pytest.mark.parametrize("build, call", _per_build(("write", "read"))) +def test_unreachable_kms_raises_key_management_error(bed: _Bed, build: str, call: str) -> None: + err = _refused_write_or_read(build, bed, call, "down", KeyManagementError, + encryption_kms_endpoint=f"http://{_HOST}:1", encryption_key_management_max_retries=0) + assert type(err.__cause__) is EndpointConnectionError + + +# target_cursor is the driver's cursor, which the plugin doesn't see. + +@_BUILDS +def test_target_cursor_is_the_driver_cursor(db: _Db) -> None: + with db.conn.cursor() as cur, db.conn.target_connection.cursor() as own: + assert type(cur.target_cursor) is type(own) + + +def _closed(cursor: Any) -> bool: + if isinstance(cursor, psycopg.Cursor): + return cursor.closed + return cursor._connection is None # both mysql-connector builds clear it in close() + + +@_BUILDS +@pytest.mark.parametrize("how", ["close", "leave-with"]) +def test_closing_the_cursor_closes_the_driver_cursor(db: _Db, how: str) -> None: + if how == "close": + cur = db.conn.cursor() + target: Any = cur.target_cursor + cur.close() + else: + with db.conn.cursor() as cur: + target = cur.target_cursor + assert _closed(target) + + +class _ArgsLoggerPlugin(Plugin): + """The parameter-logging row's controls: a plugin that logs the arguments it receives.""" + + @property + def subscribed_methods(self) -> Set[str]: + return {DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_EXECUTEMANY.method_name} + + def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + # stdlib logging: a test can't add a message key, and the record only has to reach the root handler. + logging.getLogger(__name__).debug("args_logger %s %r", method_name, args) + return execute_func() + + +class _ArgsLoggerFactory(PluginFactory): + @staticmethod + def get_instance(plugin_service: PluginService, props: Properties) -> Plugin: + return _ArgsLoggerPlugin() + + +class _LateArgsLoggerFactory(_ArgsLoggerFactory): + """The same plugin at another weight, since a weight belongs to the factory type.""" + + +@pytest.fixture +def args_loggers() -> Iterator[None]: + # Weight 385 puts args_logger before kms_encryption (390), and 395 puts late_args_logger after it and before + # failover_v2 (410). + loggers = {"args_logger": (_ArgsLoggerFactory, 385), "late_args_logger": (_LateArgsLoggerFactory, 395)} + for code, (factory, weight) in loggers.items(): + PluginManager.register_plugin(code, factory, weight) + try: + yield + finally: + for code, (factory, _) in loggers.items(): + PluginManager.PLUGIN_FACTORIES.pop(code, None) + PluginManager.PLUGIN_FACTORY_WEIGHTS.pop(factory, None) + + +@_BUILDS +@pytest.mark.parametrize("extra", ["execute_time", "args_logger", "late_args_logger"]) +def test_other_plugins_log_no_bound_value(bed: _Bed, verifiers: Dict[str, _Verifier], args_loggers: None, build: str, + extra: str) -> None: + # The plugins before kms_encryption receive the caller's values, and the plugins after it the payloads; the + # built-in ones log neither. args_logger is the positive control; late_args_logger logs only payloads. + value = f"pt-x-r7-{build}-{extra}" + plugins = f"{_plugin_props(_ENGINE[build], bed)['plugins']},{extra}" + with _debug_log() as log, _connect(build, bed, plugins=plugins) as conn: + with conn.cursor() as cur: + cur.execute(_INSERT, ("x-r7", value)) + cur.executemany(_INSERT, [("x-r7", f"{value}-m")]) + conn.commit() + back = _read_all(conn, _SELECT, "x-r7") + verifiers[_ENGINE[build]].check("x-r7", [value, f"{value}-m"]) + lines = log.getvalue().splitlines() + logged = sum(value in line for line in lines) + if extra == "args_logger": + assert logged > 0 + else: + assert logged == 0 and back == [value, f"{value}-m"] + if extra == "late_args_logger": + writes = [line for line in lines if line.startswith("args_logger ") and "INSERT INTO users" in line] + assert len(writes) == 2 and all("b'" in line or 'b"' in line for line in writes) + + +@_BUILDS +def test_target_cursor_is_not_seen(db: _Db) -> None: + # Its reads return the stored bytes, and the trigger rejects its plaintext write with the driver's own error. + _write(db.conn, _INSERT, ("x-tc", "pt-x-tc")) + with db.conn.cursor() as cur: + target: Any = cur.target_cursor + target.execute(_SELECT, ("x-tc",)) + stored = target.fetchone()[0] + target.fetchall() + with pytest.raises((psycopg.Error, mysql.connector.Error)): + target.execute(_INSERT, ("x-tc-net", "net-x-target-cursor")) + db.conn.rollback() + db.verifier.check("x-tc", ["pt-x-tc"]) + assert bytes(stored) == bytes(db.verifier.stored("x-tc")[0]) and db.verifier.stored("x-tc-net") == [] + + +# SQL that isn't str, and psycopg row factories. + +@pytest.mark.parametrize("build", ["pg"]) +def test_composable_insert_and_select(db: _Db) -> None: + with db.conn.cursor() as cur: + cur.execute(pgsql.SQL("INSERT INTO {} (name, ssn) VALUES ({}, {})").format( + pgsql.Identifier("users"), pgsql.Placeholder(), pgsql.Placeholder()), ("x-comp", "pt-x-comp")) + db.conn.commit() + cur.execute(pgsql.SQL("SELECT ssn FROM users WHERE name = {}").format(pgsql.Placeholder()), ("x-comp",)) + got = cur.fetchone()[0] + db.verifier.check("x-comp", ["pt-x-comp"]) + assert got == "pt-x-comp" + + +@pytest.mark.parametrize("build", ["pg"]) +def test_composed_insert_with_percent_placeholders_is_encrypted(db: _Db) -> None: + with db.conn.cursor() as cur: + cur.execute(pgsql.SQL("INSERT INTO {} (name, ssn) VALUES (%s, %s)").format(pgsql.Identifier("users")), + ("x-composed", "pt-x-composed")) + db.conn.commit() + db.verifier.check("x-composed", ["pt-x-composed"]) + + +@pytest.mark.parametrize("build", ["pg"]) +def test_bytes_sql_is_analyzed_and_encrypted(db: _Db) -> None: + with _debug_log() as log: + for i in range(2): + with db.conn.cursor() as cur: + cur.execute(b"INSERT INTO users (name, ssn) VALUES (%s, %s)", (f"x-bytes{i}", f"pt-x-bytes{i}")) + db.conn.commit() + plugin_records = log.getvalue().count("[KmsEncryptionPlugin]") + for i in range(2): + db.verifier.check(f"x-bytes{i}", [f"pt-x-bytes{i}"]) + assert plugin_records == 0 + + +@_BUILDS +def test_unanalysed_insert_control_reaches_the_trigger(db: _Db, build: str) -> None: + # The positive control of the last two tests: passed through with a warning, found once in each server's log. + control = {"pg": "net-x-unanalysed", "mysql-cext": "net-x-unanalysed-cext", "mysql-pure": "net-x-unanalysed-pure"} + with db.conn.cursor() as cur, pytest.raises(AwsWrapperError) as raised: + cur.execute("INSERT INTO users VALUES (DEFAULT, %s, %s, NULL)", ("x-netrow", control[build])) + db.conn.rollback() + assert type(raised.value) is AwsWrapperError + assert isinstance(raised.value.__cause__, (psycopg.Error, mysql.connector.Error)) + assert db.verifier.stored("x-netrow") == [] + + +def _first_row(cur: Any, read: str) -> Any: + if read == "chained": + return cur.execute(_SELECT, ("x-rf",)).fetchone() + cur.execute(_SELECT, ("x-rf",)) + return cur.fetchone() if read == "fetchone" else list(cur)[0] + + +@dataclass(frozen=True) +class _NameRow: + name: str + + +@pytest.mark.parametrize("build", ["pg"]) +@pytest.mark.parametrize("factory", ["class_row", "scalar_row", "dict_row", "namedtuple_row"]) +@pytest.mark.parametrize("read", ["fetchone", "iterate", "chained"]) +def test_row_factories(db: _Db, factory: str, read: str) -> None: + _write(db.conn, _INSERT, ("x-rf", "pt-x-rf")) + db.verifier.check("x-rf", ["pt-x-rf"]) + made: List[int] = [] + + class Counted: + def __init__(self, **columns: Any) -> None: + made.append(1) + + row_factory = {"class_row": class_row(Counted), "scalar_row": scalar_row, "dict_row": dict_row, + "namedtuple_row": namedtuple_row}[factory] + with db.conn.cursor(row_factory=row_factory) as cur: + if factory in ("class_row", "scalar_row"): # refused before any row is built + with pytest.raises(MetadataError) as raised: + _first_row(cur, read) + assert type(raised.value) is MetadataError and made == [] + return + row = _first_row(cur, read) + if factory == "dict_row": + assert type(row) is dict and row["ssn"] == "pt-x-rf" + else: + assert type(row).__name__ == "Row" and row.ssn == "pt-x-rf" + + +@pytest.mark.parametrize("build", ["pg"]) +def test_class_row_without_an_encrypted_column_is_not_refused(db: _Db) -> None: + _write(db.conn, _INSERT, ("x-rf", "pt-x-rf")) + db.verifier.check("x-rf", ["pt-x-rf"]) + with db.conn.cursor(row_factory=class_row(_NameRow)) as cur: + cur.execute("SELECT name FROM users WHERE name = %s", ("x-rf",)) + row = cur.fetchone() + assert row == _NameRow("x-rf") + + +# Key rows: rotation, two columns, and values whose key row is missing or unusable. + +@pytest.mark.parametrize("build", ["pg"]) +def test_rotation_keeps_values_under_the_old_key_readable(db: _Db, bed: _Bed) -> None: + env = bed.env + old = [f"pt-x-old-{i}" for i in range(200)] + old_id = _key_id("pg", env, "dob") + with db.conn.cursor() as cur: + cur.executemany(_INSERT_DOB, [("x-old", value) for value in old]) + db.conn.commit() + with _plain("pg", env) as conn: + new_id = _utility(conn, env, allowed=bed.arns["pg"]).rotate_data_key("users", "dob") + conn.commit() + new = [f"pt-x-new-{i}" for i in range(200)] + with _connect("pg", bed) as conn: # an open connection keeps the old key row until its metadata refreshes + old_back = _read_all(conn, _SELECT_DOB, "x-old") + with conn.cursor() as cur: + cur.executemany(_INSERT_DOB, [("x-new", value) for value in new]) + conn.commit() + new_back = _read_all(conn, _SELECT_DOB, "x-new") + with _dob_verifier("pg", bed) as verifier: # built after the rotation, so it checks the new key id + verifier.check("x-new", new) + old_ids = {EncryptionService.key_id_from_payload(bytes(value)) for value in verifier.stored("x-old")} + assert new_id != old_id and old_ids == {old_id} and old_back == old and new_back == new + + +@_BUILDS +def test_two_encrypted_columns_use_their_own_key_rows(db: _Db, bed: _Bed, build: str) -> None: + engine = _ENGINE[build] + _write(db.conn, "INSERT INTO users (name, ssn, dob) VALUES (%s, %s, %s)", ("x-two", "pt-x-two-ssn", "pt-x-two-dob")) + db.verifier.check("x-two", ["pt-x-two-ssn"]) + with _dob_verifier(engine, bed) as verifier: + verifier.check("x-two", ["pt-x-two-dob"]) + assert _key_id(engine, bed.env, "dob") != bed.key_ids[engine] + + +def _fake_payload(key_id: int) -> bytes: + """81 bytes in the payload layout naming ``key_id``; the test owns every byte, and none of them is a key.""" + return bytes(32) + key_id.to_bytes(4, "big") + bytes([1]) + bytes(44) + + +@_BUILDS +def test_foreign_key_id_is_refused_in_strict_mode(bed: _Bed, build: str) -> None: + payload = _fake_payload(_FOREIGN_KEY_ID) + _plain_write(_ENGINE[build], bed.env, _INSERT_DOB, ("x-foreign", payload)) + with _connect(build, bed) as conn, conn.cursor() as cur, pytest.raises(IntegrityCheckError) as raised: + cur.execute(_SELECT_DOB, ("x-foreign",)) + cur.fetchone() + err = raised.value + shown = " ".join((str(err), repr(err), repr(err.args))) + forms = (str(_FOREIGN_KEY_ID), payload[32:36].hex(), repr(payload[32:36])[2:-1], payload.hex()) + leaked = [form for form in forms if form in shown] + assert type(err) is IntegrityCheckError and "users.dob" in str(err) and leaked == [] + assert err.__cause__ is None and err.__context__ is None + + +@_BUILDS +def test_foreign_key_id_comes_back_as_stored_in_lenient_mode(bed: _Bed, build: str) -> None: + payload = _fake_payload(_FOREIGN_KEY_ID) + _plain_write(_ENGINE[build], bed.env, _INSERT_DOB, ("x-foreign", payload)) + with _connect(build, bed, encryption_return_unverified_data=True) as conn: + back = _read_all(conn, _SELECT_DOB, "x-foreign") + as_stored = [bytes(value) for value in back] == [payload] + assert as_stored + + +@pytest.mark.parametrize("build, mode", _per_build(("strict", "lenient"))) +def test_unusable_key_row_of_the_column_raises_in_both_modes(bed: _Bed, build: str, mode: str) -> None: + engine, env = _ENGINE[build], bed.env + key_id = _key_id(engine, env, "dob") + _plain_write(engine, env, _INSERT_DOB, ("x-own", _fake_payload(key_id))) + arn = _plain_rows(engine, env, "SELECT master_key_arn FROM encrypt.key_storage WHERE id = %s", (key_id,))[0] + _plain_write(engine, env, _SET_ARN, ("", key_id)) # a key row with no master key ARN is unusable + try: + with _connect(build, bed, encryption_return_unverified_data=mode == "lenient") as conn: + with conn.cursor() as cur, pytest.raises(InvalidKeyMetadataError) as raised: + cur.execute(_SELECT_DOB, ("x-own",)) + cur.fetchone() + finally: + _plain_write(engine, env, _SET_ARN, (arn, key_id)) + assert type(raised.value) is InvalidKeyMetadataError + + +@_ENGINES +def test_standalone_utility_at_debug_logs_no_data_key(bed: _Bed, engine: str) -> None: + # The bed fixture gave users.dob its key row with the root logger at DEBUG, before any plugin connection existed. + assert bed.utility_log[engine] == {"plaintext": False, "kms-request": True, "filter-found": True, + "control-plaintext": True} + + +# The worker thread socket_timeout uses, named-cursor paging, and kms_encryption listed after failover_v2. + +@_BUILDS +def test_socket_timeout_hands_the_driver_the_encrypted_copy(bed: _Bed, verifiers: Dict[str, _Verifier], + build: str) -> None: + with _connect(build, bed, socket_timeout=5) as conn: # the driver call then runs on a worker thread + _write(conn, _INSERT, ("x-sock", "pt-x-sock")) + got = _read_one(conn, "x-sock") + verifiers[_ENGINE[build]].check("x-sock", ["pt-x-sock"]) + assert got == "pt-x-sock" + + +@pytest.mark.parametrize("build", ["pg"]) +def test_named_cursor_pages_through_250_rows(db: _Db) -> None: + # Its three FETCH FORWARD 100 lines are counted by the PostgreSQL log test at the end of the file, once the + # container's log has had time to arrive. + values = [f"pt-x-page-{i}" for i in range(250)] + with db.conn.cursor() as cur: + cur.executemany(_INSERT, [("x-page", value) for value in values]) + db.conn.commit() + with db.conn.cursor(name="live_paging") as cur: + cur.execute(_SELECT, ("x-page",)) + got = [row[0] for row in cur] + db.conn.commit() + db.verifier.check("x-page", values) + assert got == values + + +_FAILOVER_FIRST: Dict[str, Type[AwsWrapperError]] = { + "execute": AwsWrapperError, "fetchone": AwsWrapperError, "fetchmany": AwsWrapperError, + "fetchall": AwsWrapperError, "executemany": MetadataError, "iterate": IntegrityCheckError, + "chained": AwsWrapperError} # psycopg's chained fetch is the wrapper cursor's fetchone, which failover_v2 handles + + +@pytest.mark.parametrize("build, call", _per_build(tuple(_FAILOVER_FIRST), pg_only=("chained",))) +def test_failover_first_order_wraps_execute_and_fetch_errors(bed: _Bed, build: str, call: str) -> None: + engine = _ENGINE[build] + chain = WrapperProperties.DEFAULT_PLUGINS if engine == "pg" else WrapperProperties.MYSQL_CONNECTOR_DEFAULT_PLUGINS + if call not in ("execute", "executemany"): + _write_tampered(build, bed) + with _connect(build, bed, plugins=f"{chain},kms_encryption", auto_sort_wrapper_plugin_order=False) as conn: + with conn.cursor() as cur, pytest.raises(AwsWrapperError) as raised: + if call == "execute": + cur.execute(_LITERAL, ("x-lit",)) + elif call == "executemany": + cur.executemany(_LITERAL, [("x-lit",)]) + else: + _read_tampered(cur, call) + conn.rollback() + err = raised.value + assert type(err) is _FAILOVER_FIRST[call] + if type(err) is AwsWrapperError: # the failover plugin's wrapping keeps the plugin's error as its cause + assert type(err.__cause__) is (MetadataError if call == "execute" else IntegrityCheckError) + + +# psycopg's pipeline mode, where a result and its cursor.description arrive only when a fetch syncs the pipeline. + +def _pipelined_reads(cur: Any, read: str, count: int) -> List[Any]: + if read == "fetchone": + got = [cur.fetchone()[0] for _ in range(count)] + assert cur.fetchone() is None + return got + if read == "fetchmany": + return [row[0] for row in cur.fetchmany(2)] + [row[0] for row in cur.fetchmany(5)] + return [row[0] for row in (cur.fetchall() if read == "fetchall" else cur)] + + +@pytest.mark.parametrize("build", ["pg"]) +@pytest.mark.parametrize("metadata", ["loaded", "new-connection"]) +@pytest.mark.parametrize("read", ["fetchone", "fetchmany", "fetchall", "iterate"]) +def test_psycopg_pipeline_reads_decrypt(db: _Db, metadata: str, read: str) -> None: + values = [f"pt-x-pipe-{i}" for i in range(3)] + if metadata == "loaded": + _write(db.conn, _INSERT, ("x-pipe-warm", "pt-x-pipe-warm")) # the connection's first statement loads it + with db.conn.cursor() as cur: + with db.conn.pipeline(): + for value in values: + cur.execute(_INSERT, ("x-pipe", value)) + cur.execute(_SELECT, ("x-pipe",)) + got = _pipelined_reads(cur, read, len(values)) + db.conn.commit() + assert got == values + assert _read_all(db.conn, _SELECT, "x-pipe") == values # the same rows, read outside a pipeline + db.verifier.check("x-pipe", values) + + +# Result sets that nextset() moves to. + +@_BUILDS +def test_later_result_set_is_never_decoded_with_the_first_sets_mapping(db: _Db) -> None: + # Without parameters: psycopg's default cursor refuses several statements with parameters. Each set is read to its + # end before nextset(), as mysql-connector's pure build requires. + _write(db.conn, _INSERT, ("x-sets", "pt-x-sets")) + with db.conn.cursor() as cur: + cur.execute("SELECT ssn FROM users; SELECT name FROM users") + first = cur.fetchall() + moved = cur.nextset() + second = cur.fetchall() + last = cur.nextset() + assert first == [("pt-x-sets",)] and moved + assert second == [("x-sets",)] and not last + + +@pytest.mark.parametrize("build", ["pg"]) +def test_psycopg_executemany_returning_later_sets_are_decrypted(db: _Db) -> None: + values = [f"pt-x-returning-{i}" for i in range(3)] + with db.conn.cursor() as cur: + cur.executemany(f"{_INSERT} RETURNING ssn", [("x-returning", value) for value in values], returning=True) + sets = [cur.fetchall()] + while cur.nextset(): + sets.append(cur.fetchall()) + db.conn.commit() + assert sets == [[(value,)] for value in values] # one set per parameter set, all from the one statement + db.verifier.check("x-returning", values) + + +@_MYSQL_BUILDS +def test_mysql_executemany_later_result_set_is_matched_by_its_own_columns(db: _Db) -> None: + # mysql-connector runs a string that isn't an INSERT through execute() for each parameter set. With one, + # nextset() moves to the next statement's set. psycopg refuses several statements in executemany(). + _write(db.conn, _INSERT, ("x-many-sets", "pt-x-many-sets")) + with db.conn.cursor() as cur: + cur.executemany("SELECT ssn FROM users WHERE name = %s; SELECT name, ssn FROM users WHERE name = %s", + [("x-many-sets", "x-many-sets")]) + cur.fetchall() # builds the decoder from the first set's columns; the driver has already read its rows + moved = cur.nextset() + second = cur.fetchall() + assert moved and second == [("x-many-sets", "pt-x-many-sets")] + + +# MySQL's _binary introducer, on both builds and under Django. + +def _warnings_1300(cur: Any) -> int: + cur.execute("SHOW WARNINGS") + return sum(row[1] == 1300 for row in cur.fetchall()) + + +@_MYSQL_BUILDS +def test_mysql_binary_prefix_keeps_payloads_binary(db: _Db, bed: _Bed, build: str) -> None: + one, many = f"x-bin-{build}", f"x-binm-{build}" + values = [f"pt-x-binm-{i}" for i in range(3)] + with db.conn.cursor() as cur: + cur.execute(_INSERT, (one, "pt-x-bin")) + warned = _warnings_1300(cur) + cur.executemany(_INSERT, [(many, value) for value in values]) + warned += _warnings_1300(cur) + db.conn.commit() + db.verifier.check(one, ["pt-x-bin"]) + db.verifier.check(many, values) + lines = [line for line in _log_lines(bed, "MYSQL_LOG_COMMAND") if b"INSERT INTO users" in line] + prefixed = {name: sum(line.count(b"_binary '") for line in lines if f"'{name}'".encode() in line) + for name in (one, many)} + assert warned == 0 and prefixed == {one: 1, many: 3} + + +@_MYSQL_BUILDS +def test_mysql_writes_succeed_with_raise_on_warnings(bed: _Bed, verifiers: Dict[str, _Verifier], build: str) -> None: + values = [f"pt-x-strict-{i}" for i in range(4)] + with _connect(build, bed, raise_on_warnings=True) as conn: + _write(conn, _INSERT, ("x-strict", values[0])) + with conn.cursor() as cur: + cur.executemany(_INSERT, [("x-strict", value) for value in values[1:]]) + conn.commit() + verifiers["mysql"].check("x-strict", values) + + +@_MYSQL_BUILDS +def test_mysql_null_and_mixed_batches_are_stored(db: _Db) -> None: + _write(db.conn, _INSERT, ("x-null", None)) + with db.conn.cursor() as cur: # a set with None keeps that placeholder unprefixed in every set (Warning 1300) + cur.executemany(_INSERT, [("x-mixed", None), ("x-mixed", "pt-x-mixed")]) + db.conn.commit() + db.verifier.check("x-null", [None]) + db.verifier.check("x-mixed", [None, "pt-x-mixed"]) + + +@_MYSQL_BUILDS +def test_mysql_prepared_cursor_gets_no_binary_prefix(db: _Db, bed: _Bed) -> None: + with db.conn.cursor(prepared=True) as cur: + cur.execute("INSERT INTO users (ssn, name) VALUES (%s, %s)", ("pt-x-prep", "x-prep")) + db.conn.commit() + db.verifier.check("x-prep", ["pt-x-prep"]) + # The Prepare line is the SQL text the server received; the Execute line shows the server's own rendering. + prepared = [line for line in _log_lines(bed, "MYSQL_LOG_COMMAND") + if b"Prepare" in line and b"INSERT INTO users (ssn, name)" in line] + assert prepared and not any(b"_binary" in line for line in prepared) + + +@pytest.fixture(scope="module") +def django_binary_model(django_model: Any) -> Any: + class LiveBinaryUser(models.Model): # a second unmanaged model over users needs a class name of its own + name: models.CharField[str, str] = models.CharField(max_length=100) + ssn: models.BinaryField[Optional[bytes], Optional[bytes]] = models.BinaryField(null=True) + + class Meta: + app_label = "kms_live" + db_table = "users" + managed = False + + return LiveBinaryUser + + +def test_django_binary_field_under_debug_gets_one_binary_prefix(django_model: Any, django_binary_model: Any, bed: _Bed, + verifiers: Dict[str, _Verifier]) -> None: + with override_settings(DEBUG=True): + # The backend sets raise_on_warnings from DEBUG when it connects, so the row needs a connection of its own. + django_connection.close() + try: + django_connection.ensure_connection() + strict = django_connection.connection.target_connection.raise_on_warnings is True + logged = django_connection.queries_logged + django_model.objects.create(name="x-djchar", ssn="pt-x-djchar") # the plugin adds the prefix + django_binary_model.objects.create(name="x-djbin", ssn=b"pt-x-djbin") # Django writes "_binary %s" + got = django_binary_model.objects.get(name="x-djbin").ssn + finally: + django_connection.close() # later statements reconnect under DEBUG=False + lines = _log_lines(bed, "MYSQL_LOG_COMMAND") + doubled = sum(b"_binary _binary" in line for line in lines) + prefixes = {name: [line.count(b"_binary ") for line in lines if b"INSERT INTO" in line and name in line] + for name in (b"'x-djchar'", b"'x-djbin'")} + verifiers["mysql"].check("x-djchar", ["pt-x-djchar"]) + verifiers["mysql"].check("x-djbin", [b"pt-x-djbin"]) + assert strict and logged and bytes(got) == b"pt-x-djbin" + assert doubled == 0 and prefixes == {b"'x-djchar'": [1], b"'x-djbin'": [1]} + + +# Values with no exact stored form are refused; the rest still encrypt. + +class _Shade(Enum): + TEAL = "pt-x-enum" + + +class _Size(IntEnum): + LARGE = 7 + + +class _Color(str, Enum): + RED = "pt-x-strenum" + + +# Each refused value, and text of it that no part of the error may show. +_NO_EXACT_FORM: Dict[str, Tuple[Any, str]] = { + "uuid": (uuid.UUID("0c0ffee0-0000-4000-8000-00000000c0de"), "0c0ffee0-0000-4000-8000-00000000c0de"), + "dict": ({"k": "pt-x-dict"}, "pt-x-dict"), "list": (["pt-x-list"], "pt-x-list"), + "ipv4": (IPv4Address("192.0.2.7"), "192.0.2.7"), "timedelta": (timedelta(hours=1, minutes=2, seconds=3), "1:02:03"), + "enum": (_Shade.TEAL, "pt-x-enum"), "jsonb": (Jsonb({"k": "pt-x-jsonb"}), "pt-x-jsonb"), + "psycopg-binary": (psycopg.Binary(b"pt-x-binary"), "pt-x-binary")} + +# Each accepted value, and what it reads back as. +_EXACT_FORM: Dict[str, Tuple[Any, Any]] = { + "none": (None, None), "int-enum": (_Size.LARGE, 7), "decimal": (Decimal("12.50"), Decimal("12.50")), + "str-enum": (_Color.RED, "pt-x-strenum"), + "mysql-binary": (mysql.connector.Binary(b"pt-x-mysql-binary"), b"pt-x-mysql-binary")} + +# A naive datetime with microseconds. A datetime can't carry the "pt-x-" prefix, so the file's last two tests count +# this one's time of day. +_NAIVE_DATETIME = datetime(2026, 8, 11, 12, 30, 45, 123456) + + +@pytest.mark.parametrize("build, kind", _per_build(tuple(_NO_EXACT_FORM), pg_only=("jsonb", "psycopg-binary"))) +def test_value_with_no_exact_stored_form_is_refused(db: _Db, kind: str) -> None: + value, value_text = _NO_EXACT_FORM[kind] + with db.conn.cursor() as cur, pytest.raises(EncryptionFailedError) as raised: + cur.execute(_INSERT, ("x-generic", value)) + db.conn.rollback() + err = raised.value + shown = " ".join((str(err), repr(err), repr(err.args))) + assert type(err) is EncryptionFailedError and err.data_type == "GENERIC" + assert type(value).__name__ in str(err) and "users.ssn" in str(err) + leaked = [text for text in (value_text, str(value), repr(value)) if text in shown] + assert leaked == [] and err.__cause__ is None and err.__context__ is None + assert db.verifier.stored("x-generic") == [] + + +@pytest.mark.parametrize("build, kind", _per_build(tuple(_EXACT_FORM), mysql_only=("mysql-binary",))) +def test_value_with_an_exact_stored_form_is_still_encrypted(db: _Db, kind: str) -> None: + value, want = _EXACT_FORM[kind] + _write(db.conn, _INSERT, ("x-exact", value)) + got = _read_one(db.conn, "x-exact") + db.verifier.check("x-exact", [want]) + assert got == want and type(got) is type(want) + + +@_BUILDS +def test_naive_datetime_reads_back_with_its_microseconds(db: _Db) -> None: + _write(db.conn, _INSERT, ("x-naive", _NAIVE_DATETIME)) + got = _read_one(db.conn, "x-naive") + assert got == _NAIVE_DATETIME and type(got) is datetime and got.tzinfo is None + db.verifier.check("x-naive", [_NAIVE_DATETIME]) + assert bytes(db.verifier.stored("x-naive")[0])[36] == 13 # LOCAL_DATE_TIME, not an instant under TIMESTAMP + + +@_BUILDS +def test_stored_generic_payload_reads_back_as_text(db: _Db, bed: _Bed, build: str) -> None: + value = {"k": "pt-x-generic"} + with _dob_verifier(_ENGINE[build], bed) as verifier: + payload = verifier.seal(value) # the encryption service with users.dob's keys, as another writer would + is_generic = payload is not None and payload[36] == 99 # the GENERIC type marker + assert is_generic + _plain_write(_ENGINE[build], bed.env, _INSERT_DOB, ("x-generic", payload)) + assert _read_all(db.conn, _SELECT_DOB, "x-generic") == [str(value)] + + +# The plugin's own connections with the metadata cache off, or once the cached copy has expired. + +def _yielded_connections(monkeypatch: pytest.MonkeyPatch) -> List[Any]: + """Lists each connection ``PluginConnectionSource.connection`` yields, once per lookup that gets it; the list keeps + every one alive, so two of them never share an ``id``.""" + yielded: List[Any] = [] + original = PluginConnectionSource.connection + + @contextlib.contextmanager + def listed(source: PluginConnectionSource) -> Iterator[Any]: + with original(source) as conn: + yielded.append(conn) + yield conn + + monkeypatch.setattr(PluginConnectionSource, "connection", listed) + return yielded + + +def _driver_closed(conn: Any) -> bool: + return conn.closed if isinstance(conn, psycopg.Connection) else not conn.is_connected() + + +@_BUILDS +@pytest.mark.parametrize("cache", ["off", "expired"]) +def test_cache_off_opens_at_most_one_metadata_connection_per_statement(bed: _Bed, verifiers: Dict[str, _Verifier], + monkeypatch: pytest.MonkeyPatch, build: str, + cache: str) -> None: + # expired: the copy expires 0.2 s after each load and no background refresh comes during the test, so the copy has + # expired at each pause's end, before a statement and before the fetch of its result. + props: Dict[str, Any] = {"encryption_metadata_cache_enabled": False} if cache == "off" else { + "encryption_metadata_cache_expiration_sec": 0.2, "encryption_metadata_cache_refresh_interval_sec": 300.0} + pause = 0.3 if cache == "expired" else 0.0 + yielded = _yielded_connections(monkeypatch) + with _connect(build, bed, **props) as conn: + _write(conn, _INSERT, ("x-scope-warm", "pt-x-scope-warm")) # builds the plugin and caches the data key + at_insert = len(yielded) + closed: List[bool] = [] + with conn.cursor() as cur: + time.sleep(pause) + cur.execute(_INSERT, ("x-scope", "pt-x-scope")) + closed.append(all(map(_driver_closed, yielded))) + conn.commit() + at_select = len(yielded) + time.sleep(pause) + cur.execute(_SELECT, ("x-scope",)) + closed.append(all(map(_driver_closed, yielded))) + time.sleep(pause) + got = cur.fetchall() + closed.append(all(map(_driver_closed, yielded))) + conn.commit() + verifiers[_ENGINE[build]].check("x-scope", ["pt-x-scope"]) + assert got == [("pt-x-scope",)] + assert closed == [True, True, True], "a plugin connection was open when its statement returned" + counts = {"INSERT": len({id(c) for c in yielded[at_insert:at_select]}), + "SELECT": len({id(c) for c in yielded[at_select:]})} + assert counts == {"INSERT": 1, "SELECT": 1}, f"plugin connections per statement: {counts}; each reads the tables on one" + + +# ---- The servers' own logs for the further checks (last, so they cover every test above) ---- + +def _lines_with(lines: List[bytes], *needles: str) -> int: + return sum(any(needle.encode() in line for needle in needles) for line in lines) + + +def test_mysql_general_log_holds_no_further_plaintext(bed: _Bed) -> None: + lines = _log_lines(bed, "MYSQL_LOG_COMMAND") + writes = sum(bool(re.search(rb"(?i)(INSERT INTO|UPDATE) `?users", line)) for line in lines) + naive = _NAIVE_DATETIME.time().isoformat() + counts = _counts(lines, ("pt-x-", "net-x-literal", "net-x-unanalysed-cext", "net-x-unanalysed-pure", naive)) + assert len(lines) > 0 and writes > 0 + assert counts == {"pt-x-": 0, "net-x-literal": 0, "net-x-unanalysed-cext": 1, "net-x-unanalysed-pure": 1, naive: 0} + + +def test_postgresql_log_holds_no_further_plaintext(bed: _Bed) -> None: + # The file's last test: PostgreSQL's container log can lag its newest lines by a moment, and here even the + # named-cursor row's FETCH lines have had the rest of the run to arrive. A count expected above 0 that comes out + # lower gets the one re-run described in test_postgresql_log_holds_no_plaintext. + lines = _log_lines(bed, "PG_LOG_COMMAND") + naive = _NAIVE_DATETIME.time().isoformat() + counts = {"pt-x-": _lines_with(lines, "pt-x-", r"'\x70742d782d"), + "net-x-literal": _lines_with(lines, "net-x-literal", r"'\x6e65742d782d6c"), + "net-x-unanalysed": _lines_with(lines, "net-x-unanalysed", r"'\x6e65742d782d756e616e616c79736564"), + "naive-datetime": _lines_with(lines, naive, naive.encode().hex()), + "live_paging-fetches": sum(b"FETCH FORWARD 100" in line and b"live_paging" in line for line in lines)} + assert len(lines) > 0 + assert counts == {"pt-x-": 0, "net-x-literal": 0, "net-x-unanalysed": 1, "naive-datetime": 0, "live_paging-fetches": 3} diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 95a1ae254..1c9faf531 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +import threading + +import pytest + from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ AsyncOpenedConnectionTracker from aws_advanced_python_wrapper.aio.minor_plugins import AsyncDeveloperPlugin @@ -23,8 +27,11 @@ from aws_advanced_python_wrapper.driver_dialect_manager import \ DriverDialectManager from aws_advanced_python_wrapper.exception_handling import ExceptionManager +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect from aws_advanced_python_wrapper.plugin_service import PluginServiceImpl from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) def pytest_runtest_setup(item): @@ -43,3 +50,24 @@ def pytest_runtest_setup(item): DatabaseDialectManager.reset_custom_dialect() DriverDialectManager.reset_custom_dialect() ExceptionManager.reset_custom_handler() + + +def _wait_then_return(event, value): + def wait(*args): + event.wait(timeout=1) + return value + return wait + + +@pytest.fixture +def wait_then_return(): + return _wait_then_return + + +@pytest.fixture +def timeout_dialect(mocker): + dialect = PgDriverDialect(Properties({WrapperProperties.SOCKET_TIMEOUT_SEC.name: "0.05"})) + event = threading.Event() + # The abort ends the cursor call that waits, so no worker is left running. + mocker.patch.object(dialect, "abort_connection", side_effect=lambda conn: event.set()) + return dialect, event diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py index ebdd9f07c..873e574e1 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -265,7 +265,7 @@ def _cursor_with_plugins(driver_cursor: Any, plugins: List[Plugin], current_conn return AwsWrapperCursor(MagicMock(), plugin_service, manager, driver_cursor) -def test_cursor_loop_runs_the_iter_subscribers_once_per_loop(): +def test_cursor_loop_runs_iter_subscribers_once(): calls: List[str] = [] driver_cursor = MagicMock() driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) @@ -277,7 +277,7 @@ def test_cursor_loop_runs_the_iter_subscribers_once_per_loop(): assert calls == ["Cursor.__iter__"] -def test_cursor_loop_does_not_run_the_next_subscribers(): +def test_cursor_loop_skips_next_subscribers(): plugin = MagicMock(spec=Plugin) plugin.subscribed_methods = {"Cursor.__next__"} plugin.execute.side_effect = lambda target, method_name, execute_func, *args, **kwargs: execute_func() @@ -291,7 +291,7 @@ def test_cursor_loop_does_not_run_the_next_subscribers(): @pytest.mark.parametrize("network_bound", [True, False]) -def test_cursor_loop_without_subscribers_returns_the_driver_iterator(network_bound): +def test_cursor_loop_without_subscribers_returns_driver_iterator(network_bound): # A method the dialect doesn't count as network-bound skips the pipeline when nothing subscribes to it. rows = iter(["a", "b"]) driver_cursor = MagicMock() @@ -303,7 +303,7 @@ def test_cursor_loop_without_subscribers_returns_the_driver_iterator(network_bou assert list(cursor) == ["a", "b"] -def test_cursor_loop_after_a_break_continues_with_the_next_row(): +def test_cursor_loop_after_break_continues_with_next_row(): driver_cursor = MagicMock() driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({"Cursor.__iter__"}, [])]) @@ -316,7 +316,7 @@ def test_cursor_loop_after_a_break_continues_with_the_next_row(): assert list(cursor) == [] -def test_cursor_loop_over_a_cursor_of_an_old_connection_raises(): +def test_cursor_loop_old_connection_cursor_raises(): # After failover, say: the connection the driver cursor belongs to is no longer the current one. driver_cursor = MagicMock() driver_cursor.__iter__.return_value = iter(["a"]) @@ -327,7 +327,16 @@ def test_cursor_loop_over_a_cursor_of_an_old_connection_raises(): pass -def test_cursor_execute_returns_the_wrapper_cursor_when_the_driver_returns_its_own(): +def test_cursor_callproc_passes_name_and_args(): + driver_cursor = MagicMock() + driver_cursor.callproc.return_value = (1, 2) + cursor = _cursor_with_plugins(driver_cursor, []) + + assert cursor.callproc("sp", (1, 2)) == (1, 2) + driver_cursor.callproc.assert_called_once_with("sp", (1, 2)) + + +def test_cursor_execute_driver_returns_own_cursor_returns_wrapper(): # psycopg's Cursor.execute returns the cursor, so a fetch chained onto it must go through the plugins too. calls: List[str] = [] driver_cursor = MagicMock() @@ -349,7 +358,7 @@ def test_cursor_execute_passes_any_other_driver_result_through(driver_result): assert _cursor_with_plugins(driver_cursor, []).execute("SELECT 1") is driver_result -def test_next_on_the_cursor_returns_the_next_row_through_the_next_subscribers(): +def test_next_returns_row_through_next_subscribers(): # psycopg's Cursor.execute returns the cursor, which is an iterator, so next(cursor.execute(query)) is the first row. calls: List[str] = [] driver_cursor = MagicMock() @@ -361,7 +370,7 @@ def test_next_on_the_cursor_returns_the_next_row_through_the_next_subscribers(): assert calls == [DbApiMethod.CURSOR_NEXT.method_name] -def test_next_on_an_exhausted_cursor_raises_stop_iteration(): +def test_next_exhausted_cursor_raises_stop_iteration(): driver_cursor = MagicMock() driver_cursor.fetchone.return_value = None cursor = _cursor_with_plugins(driver_cursor, []) @@ -370,7 +379,7 @@ def test_next_on_an_exhausted_cursor_raises_stop_iteration(): next(cursor) -def test_next_on_the_cursor_returns_an_empty_row(): +def test_next_empty_row_returns_it(): # A query with no columns (SELECT FROM t on PostgreSQL) has empty rows; only None ends the rows. driver_cursor = MagicMock() driver_cursor.fetchone.return_value = () @@ -451,7 +460,7 @@ def __next__(self) -> Any: raise StopIteration from None -def test_next_after_a_partial_loop_returns_the_row_after_the_loop_row(): +def test_next_after_partial_loop_returns_following_row(): # The loop read a page ahead, so the server is already past the row after the loop's. calls: List[str] = [] driver_cursor = _SelfIteratingServerCursor() @@ -465,7 +474,7 @@ def test_next_after_a_partial_loop_returns_the_row_after_the_loop_row(): assert calls == [DbApiMethod.CURSOR_NEXT.method_name] -def test_next_reads_a_cursor_that_is_its_own_iterator_a_page_at_a_time(): +def test_next_self_iterating_cursor_reads_page_at_time(): driver_cursor = _SelfIteratingServerCursor() cursor = _cursor_with_plugins(driver_cursor, []) @@ -473,7 +482,7 @@ def test_next_reads_a_cursor_that_is_its_own_iterator_a_page_at_a_time(): assert driver_cursor.fetches == 2 -def test_next_passes_a_driver_error_to_the_next_subscribers(): +def test_next_driver_error_reaches_next_subscribers(): # A lost connection must reach the plugins (failover, say) instead of ending the rows. calls: List[str] = [] cursor = _cursor_with_plugins(_FetchoneIteratingCursor(), [UpperRowsPlugin({DbApiMethod.CURSOR_NEXT.method_name}, calls)]) @@ -483,7 +492,7 @@ def test_next_passes_a_driver_error_to_the_next_subscribers(): assert calls == [DbApiMethod.CURSOR_NEXT.method_name] -def test_next_on_a_cursor_with_a_generator_iterator_keeps_every_row(): +def test_next_generator_iterator_keeps_every_row(): # Each iter() on this cursor starts a generator that reads a page, so next() must not take its row from a new one. cursor = _cursor_with_plugins(_GeneratorServerCursor(), []) @@ -504,7 +513,7 @@ def __next__(self) -> Optional[str]: return next(self._rows) -def test_next_on_a_cursor_that_is_its_own_iterator_returns_a_none_row(): +def test_next_self_iterating_cursor_returns_none_row(): cursor = _cursor_with_plugins(_SelfIteratingRowsCursor(["a", None, "c"]), []) assert [next(cursor) for _ in range(3)] == ["a", None, "c"] @@ -512,7 +521,7 @@ def test_next_on_a_cursor_that_is_its_own_iterator_returns_a_none_row(): next(cursor) -def test_next_when_a_next_plugin_returns_none_without_reading_raises_stop_iteration(): +def test_next_plugin_returns_none_without_reading_raises_stop_iteration(): # A plugin that answers None without reading a row ends the rows; else next() would return None forever. plugin = MagicMock(spec=Plugin) plugin.subscribed_methods = {DbApiMethod.CURSOR_NEXT.method_name} @@ -539,7 +548,7 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg raise AwsWrapperError(str(e)) from e -def test_next_at_the_end_of_a_cursor_that_is_its_own_iterator_raises_stop_iteration(): +def test_next_end_of_self_iterating_cursor_raises_stop_iteration(): # The driver's end of rows must not reach the plugins as an error: failover would raise AwsWrapperError from it. cursor = _cursor_with_plugins(_SelfIteratingServerCursor(), [_WrapErrorsPlugin()]) @@ -555,7 +564,7 @@ def _fetchone_rows_cursor() -> MagicMock: return driver_cursor -def test_next_at_the_end_of_a_fetchone_cursor_raises_stop_iteration(): +def test_next_end_of_fetchone_cursor_raises_stop_iteration(): driver_cursor = _fetchone_rows_cursor() driver_cursor.fetchone.side_effect = ["row", None] cursor = _cursor_with_plugins(driver_cursor, [_WrapErrorsPlugin()]) @@ -572,7 +581,7 @@ def test_next_at_the_end_of_a_fetchone_cursor_raises_stop_iteration(): MySQLDriverDialect(Properties()).network_bound_methods, AbstractReadWriteSplittingPlugin._SUBSCRIBED_METHODS], ids=["pg", "mysql", "read_write_splitting"]) -def test_next_runs_the_plugins_subscribed_through_the_network_bound_methods(methods, new_driver_cursor): +def test_next_runs_network_bound_subscribers(methods, new_driver_cursor): # Failover, host monitoring and the connection tracker subscribe to the dialect's network-bound methods, and read/write # splitting to its own list, so each must hold Cursor.__next__ for those plugins to see next(). calls: List[str] = [] @@ -583,7 +592,7 @@ def test_next_runs_the_plugins_subscribed_through_the_network_bound_methods(meth @pytest.mark.parametrize("new_driver_cursor", [_fetchone_rows_cursor, lambda: _SelfIteratingRowsCursor(["row"])], ids=["fetchone", "own_iterator"]) -def test_next_does_not_run_the_fetchone_subscribers(new_driver_cursor): +def test_next_skips_fetchone_subscribers(new_driver_cursor): calls: List[str] = [] cursor = _cursor_with_plugins(new_driver_cursor(), [UpperRowsPlugin({DbApiMethod.CURSOR_FETCHONE.method_name}, calls)]) diff --git a/tests/unit/test_connection_source.py b/tests/unit/test_connection_source.py index 16591f8b3..9c8b5862c 100644 --- a/tests/unit/test_connection_source.py +++ b/tests/unit/test_connection_source.py @@ -21,7 +21,12 @@ import pytest from aws_advanced_python_wrapper.encryption.connection_source import ( - CallerConnectionSource, PluginConnectionSource) + CallerConnectionSource, PluginConnectionSource, fetch_rows, run_statement) +from aws_advanced_python_wrapper.errors import QueryTimeoutError +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.utils.decorators import \ + mark_connection_abandoned +from aws_advanced_python_wrapper.utils.properties import Properties @pytest.fixture @@ -34,11 +39,11 @@ def conn(): class TestConnectionSources: - def test_caller_source_yields_the_same_connection(self, conn): + def test_caller_source_yields_same_connection(self, conn): with CallerConnectionSource(conn).connection() as c: assert c is conn - def test_plugin_source_opens_an_independent_autocommit_connection_and_closes_it(self): + def test_plugin_source_opens_autocommit_connection_and_closes_it(self): service = MagicMock() service.props = {"plugins": "kms_encryption", "user": "u"} raw = MagicMock() @@ -47,10 +52,13 @@ def test_plugin_source_opens_an_independent_autocommit_connection_and_closes_it( with PluginConnectionSource(service, plugin).connection() as c: assert c is raw host, props, skip = service.force_connect.call_args.args - assert host is service.current_host_info and skip is plugin - assert props == service.props and props is not service.props + assert host is service.current_host_info + assert skip is plugin + assert props == service.props + assert props is not service.props service.driver_dialect.set_autocommit.assert_called_once_with(raw, True) - service.driver_dialect.execute.assert_called_once() # close routed through the dialect + # The close runs through the dialect. + service.driver_dialect.execute.assert_called_once() def test_plugin_source_closes_on_error(self): service = MagicMock() @@ -82,7 +90,7 @@ def source(service): class TestStatementScope: - def test_statement_shares_one_connection_and_closes_it_at_the_end(self, service, raws, source): + def test_statement_shares_one_connection_and_closes_it(self, service, raws, source): with source.statement(): for _ in range(3): with source.connection() as c: @@ -92,7 +100,7 @@ def test_statement_shares_one_connection_and_closes_it_at_the_end(self, service, assert service.force_connect.call_count == 1 service.driver_dialect.set_autocommit.assert_called_once_with(raws[0], True) - def test_statement_closes_its_connection_when_a_lookup_fails(self, raws, source): + def test_statement_lookup_failure_closes_connection(self, raws, source): with pytest.raises(RuntimeError, match="query failed"): with source.statement(): with source.connection(): @@ -103,7 +111,7 @@ def test_statement_closes_its_connection_when_a_lookup_fails(self, raws, source) assert c is raws[1] raws[1].close.assert_called_once() - def test_statement_without_a_lookup_opens_nothing(self, service, source): + def test_statement_without_lookup_opens_nothing(self, service, source): with source.statement(): pass service.force_connect.assert_not_called() @@ -128,7 +136,7 @@ def lookup(): raws[0].close.assert_not_called() raws[0].close.assert_called_once() - def test_nested_statement_keeps_the_outer_connection(self, service, raws, source): + def test_nested_statement_keeps_outer_connection(self, service, raws, source): with source.statement(): with source.connection() as outer: pass @@ -141,7 +149,7 @@ def test_nested_statement_keeps_the_outer_connection(self, service, raws, source raws[0].close.assert_called_once() assert service.force_connect.call_count == 1 - def test_autocommit_failure_in_a_statement_closes_the_half_opened_connection(self, service, raws, source): + def test_statement_autocommit_failure_closes_connection(self, service, raws, source): service.driver_dialect.set_autocommit.side_effect = [RuntimeError("autocommit failed"), None] with source.statement(): with pytest.raises(RuntimeError, match="autocommit failed"): @@ -152,3 +160,78 @@ def test_autocommit_failure_in_a_statement_closes_the_half_opened_connection(sel assert c is raws[1] raws[1].close.assert_not_called() raws[1].close.assert_called_once() + + +def test_connection_abandoned_connection_left_open(raws, source): + with source.connection() as c: + mark_connection_abandoned(c) + raws[0].close.assert_not_called() + + +def test_statement_abandoned_connection_left_open(raws, source): + with source.statement(): + with source.connection() as c: + mark_connection_abandoned(c) + raws[0].close.assert_not_called() + + +@pytest.fixture +def dialect(): + return PgDriverDialect(Properties()) + + +def test_fetch_rows_lower_cases_keys_and_handles_no_result(dialect, mocker): + conn = mocker.MagicMock() + cursor = conn.cursor.return_value + cursor.description = [("TABLE_NAME",), ("column_name",)] + cursor.fetchall.return_value = [("t", "c")] + assert fetch_rows(dialect, conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] + + cursor.description = None + assert fetch_rows(dialect, conn, "UPDATE") == [] + + +def test_fetch_rows_accepts_dict_rows(dialect, mocker): + # A connection opened with a dict-like row factory (psycopg dict_row) + # returns mappings; their keys are lower-cased like tuple rows' names. + conn = mocker.MagicMock() + cursor = conn.cursor.return_value + cursor.description = [("TABLE_NAME",), ("column_name",)] + cursor.fetchall.return_value = [{"TABLE_NAME": "t", "column_name": "c"}] + assert fetch_rows(dialect, conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] + + +def test_run_statement_returns_affected_rows(dialect, mocker): + conn = mocker.MagicMock() + conn.cursor.return_value.rowcount = -1 + assert run_statement(dialect, conn, "DELETE FROM t WHERE id = %s", (1,)) == 0 + + conn.cursor.return_value.rowcount = 2 + assert run_statement(dialect, conn, "DELETE FROM t WHERE id = %s", (1,)) == 2 + + +def test_fetch_rows_execute_times_out_with_socket_timeout(mocker, timeout_dialect, wait_then_return): + dialect, event = timeout_dialect + conn = mocker.MagicMock() + conn.cursor.return_value.execute.side_effect = wait_then_return(event, None) + with pytest.raises(QueryTimeoutError): + fetch_rows(dialect, conn, "SELECT 1") + + +def test_fetch_rows_fetch_times_out_with_socket_timeout(mocker, timeout_dialect, wait_then_return): + dialect, event = timeout_dialect + conn = mocker.MagicMock() + cursor = conn.cursor.return_value + cursor.description = [("id",)] + cursor.fetchall.side_effect = wait_then_return(event, []) + with pytest.raises(QueryTimeoutError): + fetch_rows(dialect, conn, "SELECT 1") + + +def test_run_statement_times_out_with_socket_timeout(mocker, timeout_dialect, wait_then_return): + dialect, event = timeout_dialect + conn = mocker.MagicMock() + conn.cursor.return_value.execute.side_effect = wait_then_return(event, None) + conn.cursor.return_value.rowcount = 1 + with pytest.raises(QueryTimeoutError): + run_statement(dialect, conn, "DELETE FROM t") diff --git a/tests/unit/test_data_key_cache.py b/tests/unit/test_data_key_cache.py index 23b6d3c40..5ec3e31c2 100644 --- a/tests/unit/test_data_key_cache.py +++ b/tests/unit/test_data_key_cache.py @@ -21,22 +21,35 @@ from aws_advanced_python_wrapper.encryption import data_key_cache as module from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache +from aws_advanced_python_wrapper.utils.storage import expiration_tracking_cache + +NS_PER_SEC = 1_000_000_000 class Clock: def __init__(self): - self.now = 1000.0 + self.now_ns = 1000 * NS_PER_SEC + + def monotonic(self): + return self.now_ns / NS_PER_SEC - def __call__(self): - return self.now + def perf_counter_ns(self): + return self.now_ns + + def advance(self, sec, ns=0): + self.now_ns += round(sec * NS_PER_SEC) + ns @pytest.fixture def clock(monkeypatch): - # Replace the module's view of `time` only, so no other thread in the - # process sees a frozen clock. + # Replace the clock that the two cache modules read, not the time module's. + # Every ExpirationTrackingCache in the process then sees the frozen clock, + # and code that reads the time module keeps the real one. The time patch + # also covers a cache that reads time.monotonic, so the TTL tests never + # fall back to the real clock. c = Clock() - monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=c)) + monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=c.monotonic), raising=False) + monkeypatch.setattr(expiration_tracking_cache, "perf_counter_ns", c.perf_counter_ns) return c @@ -44,7 +57,7 @@ def make(max_size=3, ttl=60.0, enabled=True): return DataKeyCache(max_size, ttl, enabled, start_cleanup_thread=False) -def test_get_returns_a_copy_the_caller_can_wipe(clock): +def test_get_returns_copy(clock): cache = make() cache.put("k", b"\x01" * 32) first = cache.get("k") @@ -53,7 +66,7 @@ def test_get_returns_a_copy_the_caller_can_wipe(clock): assert cache.get("k") == bytearray(b"\x01" * 32) -def test_put_copies_so_the_caller_keeps_ownership(clock): +def test_put_copies_caller_buffer(clock): cache = make() key = bytearray(b"\x02" * 32) cache.put("k", key) @@ -64,7 +77,7 @@ def test_put_copies_so_the_caller_keeps_ownership(clock): def test_oldest_entry_is_evicted_and_wiped(clock): cache = make(max_size=2) cache.put("a", b"a" * 4) - entry_a = cache._entries["a"].data_key + entry_a = dict(cache._entries.items())["a"] cache.put("b", b"b" * 4) cache.put("c", b"c" * 4) assert cache.get("a") is None @@ -73,11 +86,11 @@ def test_oldest_entry_is_evicted_and_wiped(clock): assert cache.stats().evictions == 1 -def test_replacing_a_key_wipes_the_old_value_and_does_not_evict(clock): +def test_put_existing_key_wipes_old_value_without_eviction(clock): cache = make(max_size=2) cache.put("a", b"1111") cache.put("b", b"2222") - old = cache._entries["a"].data_key + old = dict(cache._entries.items())["a"] cache.put("a", b"3333") assert old == bytearray(4) assert cache.get("a") == bytearray(b"3333") @@ -88,29 +101,36 @@ def test_replacing_a_key_wipes_the_old_value_and_does_not_evict(clock): def test_expired_entry_is_never_returned_and_is_wiped(clock): cache = make(ttl=10) cache.put("k", b"kkkk") - stored = cache._entries["k"].data_key - clock.now += 9.9 + stored = dict(cache._entries.items())["k"] + clock.advance(9.9) assert cache.get("k") is not None - clock.now += 0.1 + clock.advance(0.1, ns=1) assert cache.get("k") is None assert stored == bytearray(4) assert len(cache) == 0 +def test_get_at_ttl_returns_key(clock): + cache = make(ttl=10) + cache.put("k", b"kkkk") + clock.advance(10) + assert cache.get("k") == bytearray(b"kkkk") + + def test_remove_expired(clock): cache = make(ttl=10) cache.put("old", b"o") - clock.now += 5 + clock.advance(5) cache.put("new", b"n") - clock.now += 5 + clock.advance(5, ns=1) assert cache.remove_expired() == 1 assert cache.get("new") is not None -def test_clear_and_close_wipe_everything(clock): +def test_close_wipes_every_key(clock): cache = make() cache.put("a", b"aa") - stored = cache._entries["a"].data_key + stored = dict(cache._entries.items())["a"] cache.close() assert stored == bytearray(2) assert len(cache) == 0 @@ -138,10 +158,11 @@ def test_stats(clock): def test_repr_does_not_show_key_material(clock): cache = make() cache.put("k", b"SECRET") - assert "SECRET" not in repr(cache._entries["k"]) + assert "SECRET" not in repr(cache) + assert "SECRET" not in repr(cache._entries) -def test_cleanup_interval_has_a_floor(): +def test_cleanup_interval_has_floor(): assert make(ttl=40).cleanup_interval_sec == DataKeyCache.MIN_CLEANUP_INTERVAL_SEC assert make(ttl=400).cleanup_interval_sec == 100.0 @@ -150,7 +171,9 @@ def test_cleanup_thread_stops_promptly_on_close(): cache = DataKeyCache(10, 3600.0) try: thread = cache._cleanup_thread - assert thread is not None and thread.daemon and thread.is_alive() + assert thread is not None + assert thread.daemon + assert thread.is_alive() started = time.monotonic() cache.close() assert not thread.is_alive() @@ -168,26 +191,28 @@ def test_closed_cache_stores_nothing(clock): cache.put("k", key) assert cache.get("k") is None assert len(cache) == 0 - assert key == bytearray(b"\x05" * 32) # the caller's buffer is left alone + # The caller's buffer is left alone. + assert key == bytearray(b"\x05" * 32) -def test_finalizer_wipes_first_and_never_sets_the_event_from_the_cleanup_thread(clock): +def test_finalizer_on_cleanup_thread_wipes_without_setting_event(clock): # A collection on the cleanup thread can run inside Event.wait, which # holds the event's lock, so stop.set() there would deadlock. The keys # are wiped regardless. import threading cache = make() cache.put("k", b"\x09" * 4) - stored = cache._entries["k"].data_key + stored = dict(cache._entries.items())["k"] stop = threading.Event() DataKeyCache._release(cache._entries, cache._lock, stop, [threading.current_thread()]) - assert stored == bytearray(4) and len(cache) == 0 + assert stored == bytearray(4) + assert len(cache) == 0 assert not stop.is_set() DataKeyCache._release(cache._entries, cache._lock, stop, [None]) assert stop.is_set() -def test_close_on_the_cleanup_thread_stops_it_without_joining_itself(): +def test_close_on_cleanup_thread_does_not_join_itself(): # There the finalizer leaves the event alone, so close() must set it, and # it must not join its own thread. import threading @@ -210,10 +235,10 @@ def run(): assert cache._stop.is_set() -def test_finalizer_wipes_the_keys_even_if_stopping_the_thread_fails(clock): +def test_finalizer_stop_fails_keys_still_wiped(clock): cache = make() cache.put("k", b"\x09" * 4) - stored = cache._entries["k"].data_key + stored = dict(cache._entries.items())["k"] class BrokenStop: def set(self): @@ -224,7 +249,7 @@ def set(self): assert stored == bytearray(4) -def test_a_cache_hit_does_not_protect_an_entry_from_eviction(clock): +def test_eviction_after_hit_removes_oldest(clock): # Eviction is oldest-first by insertion, not least recently used. cache = make(max_size=2) cache.put("a", b"aaaa") @@ -235,7 +260,7 @@ def test_a_cache_hit_does_not_protect_an_entry_from_eviction(clock): assert cache.get("b") == bytearray(b"bbbb") -def test_put_after_close_wipes_the_copy_it_refuses(clock, monkeypatch): +def test_put_after_close_wipes_copy(clock, monkeypatch): wiped = [] real = module.wipe monkeypatch.setattr(module, "wipe", lambda buf: (wiped.append(buf), real(buf))) @@ -246,7 +271,25 @@ def test_put_after_close_wipes_the_copy_it_refuses(clock, monkeypatch): assert wiped == [bytearray(4)] -def test_finalizer_is_given_the_cleanup_thread(): +def test_cleanup_loop_logs_failure_and_runs_next_pass(mocker, clock): + cache = make() + remove_expired = mocker.patch.object(cache, "remove_expired", side_effect=[RuntimeError("boom"), 0]) + logger = mocker.patch.object(module, "logger") + stop = mocker.MagicMock() + stop.wait.side_effect = [False, False, True] + DataKeyCache._cleanup_loop(weakref.ref(cache), stop, 1.0) + logger.debug.assert_called_once_with("DataKeyCache.CleanupFailed", "RuntimeError") + assert remove_expired.call_count == 2 + + +def test_cleanup_loop_cache_collected_ends(mocker): + stop = mocker.MagicMock() + stop.wait.return_value = False + DataKeyCache._cleanup_loop(mocker.MagicMock(return_value=None), stop, 1.0) + assert stop.wait.call_count == 1 + + +def test_finalizer_holds_cleanup_thread(): cache = DataKeyCache(10, 3600.0) try: assert cache._cleanup_thread is not None @@ -259,7 +302,7 @@ def test_finalizer_is_given_the_cleanup_thread(): def test_unclosed_cache_is_wiped_and_its_thread_stops_when_collected(): cache = DataKeyCache(10, 3600.0) cache.put("k", b"\x07" * 32) - stored = cache._entries["k"].data_key + stored = dict(cache._entries.items())["k"] thread = cache._cleanup_thread ref = weakref.ref(cache) del cache diff --git a/tests/unit/test_driver_dialect_manager.py b/tests/unit/test_driver_dialect_manager.py new file mode 100644 index 000000000..d61e3b048 --- /dev/null +++ b/tests/unit/test_driver_dialect_manager.py @@ -0,0 +1,88 @@ +# 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. + + +import psycopg +import pytest +from mysql.connector import MySQLConnection + +from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes +from aws_advanced_python_wrapper.driver_dialect_manager import \ + DriverDialectManager +from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) +from aws_advanced_python_wrapper.utils.utils import Utils + + +@pytest.fixture +def manager(): + return DriverDialectManager() + + +@pytest.fixture +def pg_not_installed(mocker): + pg_path = DriverDialectManager.known_dialects_by_code[DriverDialectCodes.PSYCOPG] + initialize = Utils.initialize_class + mocker.patch.object(Utils, "initialize_class", + side_effect=lambda path, *args: None if path == pg_path else initialize(path, *args)) + + +def code_props(code): + return Properties({WrapperProperties.DRIVER_DIALECT.name: code}) + + +def test_get_dialect_code_selects_dialect(manager, mocker): + assert isinstance(manager.get_dialect(mocker.MagicMock(), code_props(DriverDialectCodes.PSYCOPG)), PgDriverDialect) + + +def test_get_dialect_unknown_code_raises(manager, mocker): + with pytest.raises(AwsWrapperError, match="Unknown target driver dialect code: oracle"): + manager.get_dialect(mocker.MagicMock(), code_props("oracle")) + + +def test_get_dialect_for_connection_custom_dialect_not_used(manager, mocker): + DriverDialectManager.set_custom_dialect(mocker.MagicMock()) + assert manager.get_dialect_for_connection(object(), Properties()) is None + + +def test_get_dialect_for_connection_code_wins_over_detection(manager, mocker): + pg_conn = mocker.MagicMock(spec=psycopg.Connection) + dialect = manager.get_dialect_for_connection(pg_conn, code_props(DriverDialectCodes.MYSQL_CONNECTOR_PYTHON)) + assert isinstance(dialect, MySQLDriverDialect) + + +def test_get_dialect_for_connection_unknown_code_raises(manager): + with pytest.raises(AwsWrapperError, match="Unknown target driver dialect code: pg"): + manager.get_dialect_for_connection(object(), code_props("pg")) + + +def test_get_dialect_for_connection_code_driver_not_installed_raises(manager, pg_not_installed): + with pytest.raises(AwsWrapperError, match="unable to initialize the target driver dialect"): + manager.get_dialect_for_connection(object(), code_props(DriverDialectCodes.PSYCOPG)) + + +@pytest.mark.parametrize("spec, dialect_class", [(psycopg.Connection, PgDriverDialect), (MySQLConnection, MySQLDriverDialect)]) +def test_get_dialect_for_connection_detects_driver(manager, mocker, spec, dialect_class): + assert isinstance(manager.get_dialect_for_connection(mocker.MagicMock(spec=spec), Properties()), dialect_class) + + +def test_get_dialect_for_connection_skips_driver_not_installed(manager, mocker, pg_not_installed): + assert manager.get_dialect_for_connection(mocker.MagicMock(spec=psycopg.Connection), Properties()) is None + + +def test_get_dialect_for_connection_unknown_object_returns_none(manager): + assert manager.get_dialect_for_connection(object(), Properties()) is None diff --git a/tests/unit/test_encryption_config.py b/tests/unit/test_encryption_config.py index 0300df9eb..0d579f938 100644 --- a/tests/unit/test_encryption_config.py +++ b/tests/unit/test_encryption_config.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import logging + import pytest from aws_advanced_python_wrapper.encryption.algorithm import \ @@ -19,9 +21,10 @@ from aws_advanced_python_wrapper.encryption.config import ( EncryptionConfig, validate_schema_name) from aws_advanced_python_wrapper.encryption.models import ( - ColumnEncryptionConfig, KeyMetadata, mask_arn, mask_arns_in_text) + ColumnEncryptionConfig, KeyMetadata, mask_arn, mask_error_text) from aws_advanced_python_wrapper.errors import (EncryptionConfigError, InterfaceError) +from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.properties import Properties ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" @@ -40,7 +43,7 @@ def props(**kwargs) -> Properties: class TestFromProps: - def test_defaults_match_the_shared_spec(self): + def test_defaults_match_shared_spec(self): config = EncryptionConfig.from_props(props()) assert config.kms_region == "us-east-1" assert config.kms_endpoint is None @@ -69,11 +72,41 @@ def test_string_values_are_parsed(self): assert config.data_key_cache_max_size == 5 assert config.key_management_retry_backoff_base_sec == 0.25 - def test_region_falls_back_to_aws_region_then_default_region(self, monkeypatch): - monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-1") - assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "eu-west-1" - monkeypatch.setenv("AWS_REGION", "ap-south-1") - assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "ap-south-1" + @pytest.mark.parametrize("arns, region", [ + (ARN, "us-east-1"), + (f"alias/app-key,{ARN.replace('us-east-1', 'eu-west-1')}", "eu-west-1"), + ("arn:aws:kms:ap-south-1:123456789012:alias/app-key", "ap-south-1"), + ], ids=["key-arn", "alias-name-skipped", "alias-arn"]) + def test_region_from_single_allowed_arn_region(self, arns, region): + config = EncryptionConfig.from_props(props(encryption_kms_region=" ", encryption_allowed_master_key_arns=arns)) + assert config.kms_region == region + + @pytest.mark.parametrize("env", ["AWS_REGION", "AWS_DEFAULT_REGION"]) + def test_environment_region_alone_refused(self, monkeypatch, env): + monkeypatch.setenv(env, "eu-west-1") + with pytest.raises(EncryptionConfigError) as info: + EncryptionConfig.from_props(props(encryption_kms_region=None, encryption_allowed_master_key_arns="alias/app")) + assert str(info.value) == Messages.get_formatted( + "EncryptionConfig.MissingRegion", "encryption_kms_region", "encryption_allowed_master_key_arns") + + def test_several_arn_regions_refused(self): + arns = f"{ARN},{ARN.replace('us-east-1', 'us-west-2')}" + with pytest.raises(EncryptionConfigError) as info: + EncryptionConfig.from_props(props(encryption_kms_region=None, encryption_allowed_master_key_arns=arns)) + assert str(info.value) == Messages.get_formatted( + "EncryptionConfig.AmbiguousRegion", "encryption_allowed_master_key_arns", "encryption_kms_region") + + def test_region_mismatch_warns_once(self, caplog): + mismatched = props(encryption_kms_region="ap-northeast-3") + with caplog.at_level(logging.WARNING): + for _ in range(2): + assert EncryptionConfig.from_props(mismatched).kms_region == "ap-northeast-3" + EncryptionConfig.from_props(props()) + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + assert warnings == [Messages.get_formatted( + "EncryptionConfig.RegionMismatch", "encryption_kms_region", "ap-northeast-3", + "encryption_allowed_master_key_arns", "us-east-1", "ap-northeast-3")] + assert "123456789012" not in warnings[0] @pytest.mark.parametrize("env", ["AWS_REGION", "AWS_DEFAULT_REGION"]) def test_region_property_beats_environment(self, monkeypatch, env): @@ -82,10 +115,6 @@ def test_region_property_beats_environment(self, monkeypatch, env): monkeypatch.setenv(env, "eu-west-1") assert EncryptionConfig.from_props(props()).kms_region == "us-east-1" - def test_blank_region_property_falls_back_to_the_environment(self, monkeypatch): - monkeypatch.setenv("AWS_REGION", "eu-west-1") - assert EncryptionConfig.from_props(props(encryption_kms_region=" ")).kms_region == "eu-west-1" - @pytest.mark.parametrize("name", [ "encryption_metadata_cache_expiration_sec", "encryption_metadata_cache_refresh_interval_sec", @@ -98,17 +127,12 @@ def test_infinite_durations_are_refused(self, name): with pytest.raises(EncryptionConfigError, match=name): EncryptionConfig.from_props(props(**{name: "inf"})) - def test_blank_aws_region_falls_back_to_aws_default_region(self, monkeypatch): - monkeypatch.setenv("AWS_REGION", " ") - monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-1") - assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "eu-west-1" - def test_region_is_stripped(self): assert EncryptionConfig.from_props(props(encryption_kms_region=" us-east-1 ")).kms_region == "us-east-1" def test_missing_region_is_rejected(self): with pytest.raises(EncryptionConfigError, match="region"): - EncryptionConfig.from_props(props(encryption_kms_region=None)) + EncryptionConfig.from_props(props(encryption_kms_region=None, encryption_allowed_master_key_arns="alias/app")) def test_allow_list_is_required_by_default(self): with pytest.raises(EncryptionConfigError, match="encryption_allowed_master_key_arns"): @@ -123,7 +147,7 @@ def test_allow_list_can_be_waived_for_admin_use(self): assert config.is_master_key_allowed(ARN) assert config.is_master_key_allowed(None) - def test_non_numeric_value_is_a_config_error_naming_the_property(self): + def test_non_numeric_value_raises_naming_property(self): with pytest.raises(EncryptionConfigError, match="encryption_data_key_cache_max_size"): EncryptionConfig.from_props(props(encryption_data_key_cache_max_size="lots")) @@ -135,14 +159,43 @@ def test_non_numeric_value_is_a_config_error_naming_the_property(self): ("encryption_key_management_max_retries", "-1"), ("encryption_key_management_retry_backoff_base_sec", "0"), ]) - def test_out_of_range_values_name_the_property(self, name, value): + def test_out_of_range_value_names_property(self, name, value): with pytest.raises(EncryptionConfigError, match=name) as err: EncryptionConfig.from_props(props(**{name: value})) assert ">" in str(err.value).partition("must be")[2] - def test_config_error_is_an_interface_error(self): + def test_fail_on_unmapped_parameter_defaults_on(self): + assert EncryptionConfig.from_props(props()).fail_on_unmapped_parameter is True + config = EncryptionConfig.from_props(props(encryption_fail_on_unmapped_parameter="false")) + assert config.fail_on_unmapped_parameter is False + + @pytest.mark.parametrize("name, attribute", [ + ("encryption_fail_on_unmapped_parameter", "fail_on_unmapped_parameter"), + ("encryption_metadata_cache_enabled", "metadata_cache_enabled"), + ("encryption_data_key_cache_enabled", "data_key_cache_enabled"), + ("encryption_audit_logging_enabled", "audit_logging_enabled"), + ("encryption_return_unverified_data", "return_unverified_data"), + ]) + @pytest.mark.parametrize("value", [2, -1]) + def test_boolean_integer_other_than_one_is_on(self, name, attribute, value): + config = EncryptionConfig.from_props(props(**{name: value})) + assert getattr(config, attribute) is True + + @pytest.mark.parametrize("value, expected", [(True, True), (1, True), ("TRUE", True), ("yes", False), ("1", False)]) + def test_boolean_true_values(self, value, expected): + config = EncryptionConfig.from_props(props(encryption_audit_logging_enabled=value)) + assert config.audit_logging_enabled is expected + + def test_fractional_float_for_integer_refused(self): + with pytest.raises(EncryptionConfigError, match="encryption_data_key_cache_max_size"): + EncryptionConfig.from_props(props(encryption_data_key_cache_max_size=1.5)) + + def test_whole_float_for_integer_accepted(self): + assert EncryptionConfig.from_props(props(encryption_data_key_cache_max_size=5.0)).data_key_cache_max_size == 5 + + def test_config_error_is_interface_error(self): with pytest.raises(InterfaceError): - EncryptionConfig.from_props(props(encryption_kms_region=None)) + EncryptionConfig.from_props(props(encryption_kms_region=None, encryption_allowed_master_key_arns="alias/app")) class TestAllowList: @@ -164,7 +217,12 @@ def test_match_is_exact(self): assert not config.is_master_key_allowed(None) def test_direct_construction_normalizes_too(self): - config = EncryptionConfig(kms_region="us-east-1", allowed_master_key_arns=f"{ARN}, ") # type: ignore[arg-type] + config = EncryptionConfig( + kms_region="us-east-1", allowed_master_key_arns=f"{ARN}, ", # type: ignore[arg-type] + kms_endpoint=None, metadata_schema="encrypt", metadata_cache_enabled=True, + metadata_cache_expiration_sec=3600.0, metadata_cache_refresh_interval_sec=300.0, data_key_cache_enabled=True, + data_key_cache_max_size=1000, data_key_cache_expiration_sec=300.0, key_management_max_retries=3, + key_management_retry_backoff_base_sec=0.1, audit_logging_enabled=False, return_unverified_data=False) assert config.allowed_master_key_arns == frozenset({ARN}) @@ -199,12 +257,12 @@ def test_mask_arn(self): assert mask_arn(None) is None @pytest.mark.parametrize("partition", ["aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b", "aws-iso-f"]) - def test_mask_arns_in_text_covers_every_partition(self, partition): + def test_mask_error_text_masks_arns_in_every_partition(self, partition): key = f"arn:{partition}:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" session = f"arn:{partition}:sts::123456789012:assumed-role/app-role/app-session" text = f"User: {session} is not authorized to perform: kms:Decrypt on resource: {key}" - assert mask_arns_in_text(text) == (f"User: arn:{partition}:sts:***:***:*** is not authorized to perform: " - "kms:Decrypt on resource: arn:aws:kms:***:***:key/1234***90ab") + assert mask_error_text(text) == (f"User: arn:{partition}:sts:***:***:*** is not authorized to perform: " + "kms:Decrypt on resource: arn:aws:kms:***:***:key/1234***90ab") @pytest.mark.parametrize("text, expected", [ pytest.param("arn:aws:kms:us-east-1:123456789012:alias/app-key is not found.", @@ -229,8 +287,8 @@ def test_mask_arns_in_text_covers_every_partition(self, partition): pytest.param("arn:aws:kms:***:***:key/1234***90ab is disabled.", "arn:aws:kms:***:***:key/1234***90ab is disabled.", id="already-masked"), ]) - def test_mask_arns_in_text(self, text, expected): - assert mask_arns_in_text(text) == expected + def test_mask_error_text_masks_arns(self, text, expected): + assert mask_error_text(text) == expected def test_usability(self): good = KeyMetadata(master_key_arn=ARN, encrypted_data_key="e", hmac_key=b"h") @@ -245,7 +303,10 @@ def test_usability(self): def test_from_row_normalizes_binary_and_prefix(self): row = {"ks_id": "7", "ks_key_id": "u", "ks_hmac_key": memoryview(b"hk"), "ks_key_spec": None} km = KeyMetadata.from_row(row, "ks_") - assert km.id == 7 and km.key_id == "u" and km.hmac_key == b"hk" and km.key_spec == "AES_256" + assert km.id == 7 + assert km.key_id == "u" + assert km.hmac_key == b"hk" + assert km.key_spec == "AES_256" def test_data_key_spec_matches_algorithm_key_length(): diff --git a/tests/unit/test_encryption_conformance.py b/tests/unit/test_encryption_conformance.py index 8ac7fee4c..7c04ae0f5 100644 --- a/tests/unit/test_encryption_conformance.py +++ b/tests/unit/test_encryption_conformance.py @@ -89,7 +89,7 @@ def test_reference_payload_carries_expected_key_id(vec): @pytest.mark.parametrize("vec", VECTORS, ids=_IDS) -def test_our_encrypt_output_passes_the_db_trigger_hmac(vec): +def test_encrypt_output_passes_trigger_hmac(vec): """Check our output the way the DB-side trigger does: the HMAC over everything after the 32-byte tag, computed with the stored HMAC key, must match the tag. The trigger would reject any write that fails this. @@ -115,12 +115,13 @@ def test_vectors_use_distinct_fixed_ivs(): assert len(set(ivs)) == len(ivs) -def test_committed_vectors_match_the_reference_encoder(): +def test_committed_vectors_match_reference_encoder(): """The JSON file is exactly what the reference encoder produces, so the vectors can be regenerated and reviewed from source.""" spec = importlib.util.spec_from_file_location("generate_conformance_vectors", _RESOURCES / "generate_conformance_vectors.py") - assert spec is not None and spec.loader is not None + assert spec is not None + assert spec.loader is not None generator = importlib.util.module_from_spec(spec) spec.loader.exec_module(generator) assert _VECTORS_PATH.read_text(encoding="utf-8") == generator.render() diff --git a/tests/unit/test_encryption_driver_dialect.py b/tests/unit/test_encryption_driver_dialect.py new file mode 100644 index 000000000..9bd19c638 --- /dev/null +++ b/tests/unit/test_encryption_driver_dialect.py @@ -0,0 +1,66 @@ +# 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. + + +import pytest + +from aws_advanced_python_wrapper.driver_dialect import DriverDialect +from aws_advanced_python_wrapper.encryption.sql_tokenizer import (ParamStyle, + tokenize) +from aws_advanced_python_wrapper.encryption_driver_dialect import \ + EncryptionDriverDialect +from aws_advanced_python_wrapper.errors import UnsupportedOperationError +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.utils.properties import Properties + + +class _PlainDialect(DriverDialect, EncryptionDriverDialect): + def upsert_clause(self, conflict_columns, update_columns, extra_assignments=()): + return "" + + def insert_returning_id(self, conn, sql, params): + return 0 + + +@pytest.fixture +def dialect(): + return _PlainDialect(Properties()) + + +def test_encryption_driver_dialect_is_abstract(): + with pytest.raises(TypeError, match="abstract"): + EncryptionDriverDialect() # type: ignore[abstract] + + +def test_analyzable_sql_bytes_runs_unanalyzed(dialect, mocker): + assert dialect.analyzable_sql(b"SELECT 1", mocker.MagicMock()) == (None, None) + + +@pytest.mark.parametrize("params, style", [ + (None, ParamStyle.NONE), ({}, ParamStyle.NAMED), ([], ParamStyle.POSITIONAL), ((), ParamStyle.POSITIONAL)]) +def test_param_style_of_any_parameters_binds(params, style): + assert ParamStyle.of(params, _PlainDialect) is style + + +def test_tokenize_without_token_pattern_raises(): + with pytest.raises(UnsupportedOperationError, match="_PlainDialect"): + tokenize("SELECT 1", _PlainDialect, ParamStyle.NONE) + + +def test_encryption_driver_dialect_is_mixed_into_driver_dialects(): + assert not issubclass(EncryptionDriverDialect, DriverDialect) + for dialect in (PgDriverDialect, MySQLDriverDialect): + assert dialect.__mro__[1] is DriverDialect + assert issubclass(dialect, EncryptionDriverDialect) diff --git a/tests/unit/test_encryption_import_guard.py b/tests/unit/test_encryption_import_guard.py index 5a8119599..ea3c9dd00 100644 --- a/tests/unit/test_encryption_import_guard.py +++ b/tests/unit/test_encryption_import_guard.py @@ -54,6 +54,7 @@ def _run(code: str, block: bool = True) -> subprocess.CompletedProcess: "aws_advanced_python_wrapper.sqlalchemy_dialects.pg_async", "aws_advanced_python_wrapper.sqlalchemy_dialects.mysql_async", "aws_advanced_python_wrapper.django.backends.mysql_connector.base", + "aws_advanced_python_wrapper.encryption.kms_encryption_plugin", ] @@ -81,7 +82,7 @@ def test_imports_without_cryptography_or_sqlglot(module): @pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) -def test_does_not_load_the_extra_even_when_installed(module): +def test_import_with_extra_installed_loads_no_extra(module): # With the packages available, importing these must still not load them, # so users who never encrypt don't pay their import cost. result = _run(f""" @@ -93,12 +94,12 @@ def test_does_not_load_the_extra_even_when_installed(module): assert result.returncode == 0, result.stderr -def test_encryption_service_names_the_extra_when_cryptography_is_missing(): +def test_encryption_service_without_cryptography_names_extra(): result = _run(""" try: import aws_advanced_python_wrapper.encryption.encryption_service except ImportError as e: - print(e) + sys.stdout.write(str(e)) else: raise SystemExit("imported without cryptography") """) @@ -106,12 +107,12 @@ def test_encryption_service_names_the_extra_when_cryptography_is_missing(): assert "aws-advanced-python-wrapper[encryption]" in result.stdout -def test_sql_analyzer_names_the_extra_when_sqlglot_is_missing(): +def test_sql_analyzer_without_sqlglot_names_extra(): result = _run(""" try: import aws_advanced_python_wrapper.encryption.sql_analyzer except ImportError as e: - print(e) + sys.stdout.write(str(e)) else: raise SystemExit("imported without sqlglot") """) @@ -120,6 +121,29 @@ def test_sql_analyzer_names_the_extra_when_sqlglot_is_missing(): assert "aws-advanced-python-wrapper[encryption]" in result.stdout +def test_plugin_creation_without_extra_names_extra(): + # The plugin module imports without the extra, so a connection that asks + # for the plugin fails when the plugin is created, with the install hint. + result = _run(""" + from unittest.mock import MagicMock + from aws_advanced_python_wrapper.encryption.kms_encryption_plugin import KmsEncryptionPluginFactory + from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect + from aws_advanced_python_wrapper.utils.properties import Properties + props = Properties(encryption_kms_region="us-east-1", + encryption_allowed_master_key_arns="arn:aws:kms:us-east-1:123456789012:key/k") + service = MagicMock() + service.driver_dialect = PgDriverDialect(Properties()) + try: + KmsEncryptionPluginFactory.get_instance(service, props) + except ImportError as e: + sys.stdout.write(str(e)) + else: + raise SystemExit("created without the extra") + """) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" in result.stdout + + _BROKEN = textwrap.dedent(""" import sys @@ -144,7 +168,7 @@ def test_a_broken_cryptography_is_not_reported_as_missing(error): try: import aws_advanced_python_wrapper.encryption.encryption_service except ImportError as e: - print(e) + sys.stdout.write(str(e)) """) result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) assert result.returncode == 0, result.stderr @@ -158,7 +182,7 @@ def test_a_broken_sqlglot_is_not_reported_as_missing(): try: import aws_advanced_python_wrapper.encryption.sql_analyzer except ImportError as e: - print(e) + sys.stdout.write(str(e)) """) result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) assert result.returncode == 0, result.stderr diff --git a/tests/unit/test_encryption_service.py b/tests/unit/test_encryption_service.py index 66ef481bf..629af59fe 100644 --- a/tests/unit/test_encryption_service.py +++ b/tests/unit/test_encryption_service.py @@ -20,6 +20,7 @@ from enum import Enum import pytest +from cryptography.hazmat.primitives.ciphers.aead import AESGCM from aws_advanced_python_wrapper.encryption.algorithm import \ EncryptionAlgorithm @@ -56,8 +57,6 @@ def dec(payload, dk=DATA_KEY, hk=HMAC_KEY, algorithm=EncryptionAlgorithm.DEFAULT return EncryptionService.decrypt(payload, dk, hk, algorithm, target_type=target_type) -# ---- payload layout ---- - class TestPayloadLayout: def test_min_length_is_65(self): assert EncryptionService.MIN_ENCRYPTED_LENGTH == 65 @@ -87,8 +86,6 @@ def test_key_id_from_payload(self): assert EncryptionService.key_id_from_payload(b"\x00" * 10) is None # too short -# ---- round trips for every supported type ---- - class TestRoundTrip: @pytest.mark.parametrize("value", [ "hello", "", "café-ümlaut-漢字", "a" * 10000, @@ -131,8 +128,6 @@ def test_none_passthrough(self): assert dec(None) is None -# ---- target type coercion ---- - class TestTargetType: def test_coerce_to_str(self): assert dec(enc(123), target_type=str) == "123" @@ -145,8 +140,6 @@ def test_coerce_to_bool(self): assert dec(enc("no"), target_type=bool) is False -# ---- fail-closed behavior ---- - class TestFailClosed: def test_too_short_raises_integrity(self): with pytest.raises(IntegrityCheckError): @@ -160,7 +153,8 @@ def test_tampered_body_fails_hmac(self): def test_tampered_key_id_fails_hmac(self): payload = bytearray(enc("hello")) - payload[34] ^= 0xFF # key id is inside the HMAC-covered region + # Key id is inside the HMAC-covered region. + payload[34] ^= 0xFF with pytest.raises(IntegrityCheckError): dec(bytes(payload)) @@ -169,7 +163,7 @@ def test_tampered_key_id_fails_hmac(self): struct.pack(">I", 7), # tag + key id struct.pack(">I", 7) + bytes([TypeMarker.STRING]), # + marker, no IV ]) - def test_signed_but_too_short_payload_is_an_integrity_error(self, body): + def test_signed_short_payload_raises_integrity_error(self, body): # Signed with the right HMAC key, so only the length check refuses it; # without it the framing would fail with a bare IndexError/ValueError. payload = hmac.new(HMAC_KEY, body, hashlib.sha256).digest() + body @@ -202,16 +196,12 @@ def test_bad_key_id(self, bad): EncryptionService.encrypt("x", DATA_KEY, HMAC_KEY, key_id=bad) -# ---- key rotation: value carries the id it was written with ---- - class TestKeyId: def test_payload_carries_write_key_id(self): for kid in (0, 1, 7, 2 ** 32 - 1): assert EncryptionService.key_id_from_payload(enc("v", key_id=kid)) == kid -# ---- randomized IV ---- - def test_iv_is_random_per_call(): a = enc("same-value") b = enc("same-value") @@ -219,16 +209,12 @@ def test_iv_is_random_per_call(): assert dec(a) == dec(b) == "same-value" -# ---- AES-128 ---- - def test_aes_128_round_trip(): dk16 = bytes(range(16)) payload = EncryptionService.encrypt("x", dk16, HMAC_KEY, EncryptionAlgorithm.AES_128_GCM, key_id=1) assert EncryptionService.decrypt(payload, dk16, HMAC_KEY, EncryptionAlgorithm.AES_128_GCM) == "x" -# ---- wipe ---- - def test_wipe_zeroes_bytearray(): buf = bytearray(b"secret-key-material") EncryptionService.wipe(buf) @@ -242,7 +228,33 @@ def test_datetime_tz_normalization_matches_millis_contract(): assert millis == int(datetime(2023, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) -# ---- marker coverage: generic, time, and reading an externally-written INTEGER ---- +class TestReencryptPayload: + NEW_KEY = bytes(range(64, 96)) + NEW_HMAC = bytes(range(96, 128)) + + @pytest.mark.parametrize("value", ["123-45-6789", Decimal("12.50"), date(2024, 1, 31), b"\x00\xff"]) + def test_marker_and_plaintext_bytes_kept(self, value): + old = EncryptionService.encrypt(value, DATA_KEY, HMAC_KEY, key_id=4) + new = EncryptionService.reencrypt(old, DATA_KEY, HMAC_KEY, self.NEW_KEY, self.NEW_HMAC, + EncryptionAlgorithm.AES_256_GCM, new_key_id=11) + assert EncryptionService.key_id_from_payload(new) == 11 + assert new[36] == old[36] + assert new[37:49] != old[37:49] + assert len(new) == len(old) + assert EncryptionService.verify(new, self.NEW_HMAC) is True + assert EncryptionService.verify(new, HMAC_KEY) is False + assert EncryptionService.decrypt(new, self.NEW_KEY, self.NEW_HMAC) == value + + def test_tampered_payload_refused(self): + old = bytearray(EncryptionService.encrypt("v", DATA_KEY, HMAC_KEY, key_id=4)) + old[-1] ^= 1 + with pytest.raises(IntegrityCheckError): + EncryptionService.reencrypt(bytes(old), DATA_KEY, HMAC_KEY, self.NEW_KEY, self.NEW_HMAC, + EncryptionAlgorithm.AES_256_GCM, new_key_id=11) + + def test_short_value_does_not_verify(self): + assert EncryptionService.verify(b"\x00" * 10, HMAC_KEY) is False + class TestMarkerCoverage: def test_generic_falls_back_to_str(self): @@ -287,11 +299,6 @@ def test_unsupported_algorithm_raises(self): EncryptionService.encrypt("x", DATA_KEY, HMAC_KEY, "AES-999-XYZ", key_id=1) -# ===================================================================== -# Edge cases, plus tests that pin behavior specific to Python. -# ===================================================================== - - def _resign(payload: bytes, hmac_key: bytes) -> bytes: """Re-sign a payload whose body was edited, so a test can get past the integrity check and exercise the decryption path itself.""" @@ -304,19 +311,18 @@ def _resign(payload: bytes, hmac_key: bytes) -> bytes: MARKER_OFFSET = ES_TAG + ES_KEYID -# ---- serialize_value: markers it can/can't write ---- - class TestSerializeValue: def test_raises_for_unknown_marker(self): # 12345 is no marker at all, so any value is refused. - with pytest.raises(EncryptionFailedError, match="Unsupported type marker: 12345"): + with pytest.raises(EncryptionFailedError, match="Unsupported type marker: '12345'"): EncryptionService.serialize_value("x", 12345) - def test_long_overflow_raises_without_leaking_the_value(self): + def test_long_overflow_raises_without_value(self): # Every Python int but bool uses the LONG marker, so one outside the # signed 64-bit range must be refused. The error must not expose the # integer through its message, __cause__, or __context__. - too_big = 2 ** 63 # one past the signed 64-bit max + # One past the signed 64-bit max. + too_big = 2 ** 63 with pytest.raises(EncryptionFailedError) as ei: enc(too_big) err = ei.value @@ -325,7 +331,7 @@ def test_long_overflow_raises_without_leaking_the_value(self): assert err.__cause__ is None assert err.__context__ is None - def test_long_underflow_raises_without_leaking_the_value(self): + def test_long_underflow_raises_without_value(self): # The lower half of the range check, held to the same no-leak rule as # the upper half. (test_long_out_of_range_keeps_its_own_message pins # the message.) @@ -369,39 +375,47 @@ def test_millis_round_half_away_from_zero(self, micros, expected_millis): value = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(microseconds=micros) assert EncryptionService._to_millis(value, "TIMESTAMP") == expected_millis - def test_millis_are_exact_far_from_the_epoch(self): + def test_millis_exact_far_from_epoch(self): value = datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=timezone.utc) expected = (value - datetime(1970, 1, 1, tzinfo=timezone.utc)) // timedelta(milliseconds=1) assert EncryptionService._to_millis(value, "TIMESTAMP") == expected @pytest.mark.parametrize("value,marker", [ - (date(2024, 1, 2), TypeMarker.LOCAL_DATE_TIME), # a date is not a date-time + # A date is not a date-time. + (date(2024, 1, 2), TypeMarker.LOCAL_DATE_TIME), ("not a date", TypeMarker.LOCAL_DATE), ("SECRET-123", TypeMarker.LONG), ("SECRET-123", TypeMarker.INTEGER), - (2 ** 40, TypeMarker.INTEGER), # out of the 32-bit range + # Out of the 32-bit range. + (2 ** 40, TypeMarker.INTEGER), ("SECRET-123", TypeMarker.DOUBLE), ("SECRET-123", TypeMarker.TIMESTAMP), ("SECRET-123", TypeMarker.DATE), - (Decimal("NaN"), TypeMarker.LONG), # TypeError: a Decimal is not an integer - (7, TypeMarker.BYTE_ARRAY), # bytes(7) would be 7 zero bytes + # TypeError: a Decimal is not an integer. + (Decimal("NaN"), TypeMarker.LONG), + # bytes(7) would be 7 zero bytes. + (7, TypeMarker.BYTE_ARRAY), ("false", TypeMarker.BOOLEAN), # not truthiness - (1e300, TypeMarker.FLOAT), # OverflowError: too large for a 32-bit float - (time(3, 4, 5), TypeMarker.LOCAL_DATE_TIME), # a time of day is not a date-time + # OverflowError: too large for a 32-bit float. + (1e300, TypeMarker.FLOAT), + # A time of day is not a date-time. + (time(3, 4, 5), TypeMarker.LOCAL_DATE_TIME), ]) - def test_value_that_does_not_fit_an_explicit_marker(self, value, marker): + def test_value_not_fitting_explicit_marker_raises(self, value, marker): # Mostly reachable only with an explicit marker. The error is a wrapper # error, names the marker, and quotes nothing of the value. with pytest.raises(EncryptionFailedError) as ei: EncryptionService.serialize_value(value, marker) err = ei.value assert "SECRET" not in str(err) - assert err.__cause__ is None and err.__context__ is None + assert err.__cause__ is None + assert err.__context__ is None assert err.data_type == TypeMarker.name_for(marker) @pytest.mark.parametrize("marker", [TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP]) def test_out_of_range_instant_is_refused_naming_its_marker(self, marker): - value = datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))) # after year 9999 in UTC + # After year 9999 in UTC. + value = datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))) with pytest.raises(EncryptionFailedError, match="outside the range") as ei: EncryptionService.serialize_value(value, marker) assert ei.value.data_type == TypeMarker.name_for(marker) @@ -422,12 +436,12 @@ def test_int_is_not_written_as_boolean(self, value): assert ei.value.data_type == "BOOLEAN" @pytest.mark.parametrize("value", [1e300, Decimal("1E+30"), 1.5]) - def test_non_int_as_long_gets_the_generic_message(self, value): + def test_non_int_as_long_raises_generic_message(self, value): with pytest.raises(EncryptionFailedError, match="Cannot write a value of type") as ei: EncryptionService.serialize_value(value, TypeMarker.LONG) assert ei.value.data_type == "LONG" - def test_instant_just_past_the_last_millisecond_is_refused(self): + def test_instant_past_last_millisecond_raises(self): # The clamp only undoes rounding: the first millisecond after year # 9999 in UTC (no sub-millisecond part to round) is still refused. value = datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-1))) # 10000-01-01T00:00Z @@ -458,27 +472,30 @@ def test_value_whose_str_fails_is_refused(self): # str() of a huge int raises ValueError (the int-digit limit). with pytest.raises(EncryptionFailedError) as ei: EncryptionService.serialize_value(10 ** 5000, TypeMarker.STRING) - assert ei.value.__cause__ is None and ei.value.__context__ is None + assert ei.value.__cause__ is None + assert ei.value.__context__ is None @pytest.mark.parametrize("value", [2 ** 63, -(2 ** 63) - 1]) def test_long_out_of_range_keeps_its_own_message(self, value): with pytest.raises(EncryptionFailedError, match="signed 64-bit range"): EncryptionService.serialize_value(value) - def test_datetime_written_as_local_date_keeps_only_the_date(self): + def test_datetime_as_local_date_keeps_date(self): data = EncryptionService.serialize_value(datetime(2024, 1, 2, 3, 4, 5), TypeMarker.LOCAL_DATE) assert data == b"2024-01-02" assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_DATE) == date(2024, 1, 2) @pytest.mark.parametrize("value", [ - datetime(1, 1, 1, 0, 30, tzinfo=timezone(timedelta(hours=1))), # before year 1 in UTC - datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))), # after year 9999 in UTC + # Before year 1 in UTC. + datetime(1, 1, 1, 0, 30, tzinfo=timezone(timedelta(hours=1))), + # After year 9999 in UTC. + datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))), ]) def test_timestamp_that_could_not_be_read_back_is_refused(self, value): with pytest.raises(EncryptionFailedError): enc(value) - def test_timestamp_at_the_edges_of_the_range_round_trips(self): + def test_timestamp_range_edges_round_trip(self): for value in (datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=timezone.utc), datetime(1, 1, 1, tzinfo=timezone.utc)): assert dec(enc(value)) == value @@ -501,7 +518,8 @@ def test_str_subclass_is_stored_as_its_own_text(self, value): def test_str_subclass_reads_back_as_plain_str(self): out = dec(enc(Color.RED)) - assert out == "red" and type(out) is str + assert out == "red" + assert type(out) is str @pytest.mark.parametrize("value,marker,expected", [ (Color.RED, TypeMarker.GENERIC, b"Color.RED"), @@ -511,7 +529,7 @@ def test_str_subclass_reads_back_as_plain_str(self): def test_generic_and_non_str_under_string_keep_str_of_value(self, value, marker, expected): assert EncryptionService.serialize_value(value, marker) == expected - def test_object_that_only_claims_to_be_a_str_keeps_str_of_value(self, mocker): + def test_fake_str_object_keeps_str_of_value(self, mocker): # isinstance() trusts a faked __class__ (proxies, mocks) and picks # STRING, but str.__str__ needs a real str, so the check is on type(). proxy = mocker.MagicMock(spec=str) @@ -519,8 +537,6 @@ def test_object_that_only_claims_to_be_a_str_keeps_str_of_value(self, mocker): assert EncryptionService.serialize_value(proxy) == b"red" -# ---- deserialize_value: reading every marker ---- - class TestDeserializeExternalMarkers: """This wrapper never writes some of these markers or forms, but it must read every one.""" @@ -609,20 +625,19 @@ def test_deserialize_error_does_not_leak_plaintext(self, marker, data): @pytest.mark.parametrize("marker", [TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP]) @pytest.mark.parametrize("millis", [2 ** 63 - 1, -(2 ** 63), 10 ** 15]) - def test_out_of_range_epoch_millis_is_a_type_conversion_error(self, marker, millis): + def test_out_of_range_epoch_millis_raises_type_conversion_error(self, marker, millis): # Another writer can store epoch millis no datetime can hold; the # resulting OverflowError must surface as the wrapper's error. with pytest.raises(TypeConversionError) as ei: EncryptionService.deserialize_value(struct.pack(">q", millis), marker) - assert ei.value.__cause__ is None and ei.value.__context__ is None + assert ei.value.__cause__ is None + assert ei.value.__context__ is None def test_unknown_marker_on_read(self): with pytest.raises(EncryptionError) as ei: EncryptionService.deserialize_value(b"x", 12345) - assert "Unsupported type marker: 12345" in str(ei.value) - + assert "Unsupported type marker: '12345'" in str(ei.value) -# ---- decrypt path: unknown marker inside a (re-signed) payload ---- def test_decrypt_rejects_unknown_marker_in_payload(): payload = bytearray(enc("123-45-6789")) @@ -630,10 +645,8 @@ def test_decrypt_rejects_unknown_marker_in_payload(): resigned = _resign(bytes(payload), HMAC_KEY) with pytest.raises(DecryptionError) as ei: dec(resigned) - assert "Unknown type marker: 77" in str(ei.value) - + assert "Unknown type marker: '77'" in str(ei.value) -# ---- decrypt-path data-key validation (past length check, before GCM) ---- def test_decrypt_rejects_wrong_length_data_key(): payload = enc("123-45-6789") @@ -641,16 +654,12 @@ def test_decrypt_rejects_wrong_length_data_key(): EncryptionService.decrypt(payload, bytes(range(16)), HMAC_KEY) -# ---- missing data key / hmac key messages ---- - def test_missing_data_key_message(): with pytest.raises(EncryptionError) as ei: EncryptionService.encrypt("x", None, HMAC_KEY, key_id=1) assert "got None" in str(ei.value) -# ---- target-type coercion edge cases ---- - class TestTargetTypeEdges: def test_boolean_db_spellings_true(self): for v in ("t", "true", "TRUE", "y", "yes", "1"): @@ -672,7 +681,7 @@ def test_uncoercible_value_raises(self): dec(enc("abc"), target_type=int) @pytest.mark.parametrize("value", [float("inf"), float("nan"), Decimal("Infinity")]) - def test_non_finite_to_int_is_a_type_conversion_error(self, value): + def test_non_finite_to_int_raises_type_conversion_error(self, value): # int() raises OverflowError / ValueError here, outside the PEP 249 # hierarchy unless it is converted. with pytest.raises(TypeConversionError) as ei: @@ -702,9 +711,7 @@ def test_float_to_int_target_truncates_python_difference(self): assert dec(enc(1.5), target_type=int) == 1 -# ---- key and plaintext buffers ---- - -def test_encrypt_wipes_the_buffer_aes_gcm_saw_and_copies_no_key(monkeypatch): +def test_encrypt_wipes_aes_gcm_buffer_without_key_copy(monkeypatch): # The keys reach AES-GCM and HMAC as given (no immutable copy of a # bytearray key), and the plaintext buffer AES-GCM read is the one wiped. from types import SimpleNamespace @@ -747,8 +754,6 @@ def test_memoryview_keys_are_accepted(dk_type, hk_type): assert EncryptionService.decrypt(payload, DATA_KEY, HMAC_KEY) == "v" -# ---- immutability: the caller's value is not mutated ---- - def test_encrypt_does_not_mutate_caller_bytes(): value = bytearray(b"123-45-6789") snapshot = bytes(value) @@ -756,8 +761,6 @@ def test_encrypt_does_not_mutate_caller_bytes(): assert bytes(value) == snapshot -# ---- precision contract ---- - class TestPrecision: def test_timestamp_marker_keeps_millisecond(self): # A value read via the TIMESTAMP marker keeps millisecond precision @@ -794,10 +797,9 @@ def test_whole_second_naive_datetime_text_is_unchanged(self): assert EncryptionService.serialize_value(v) == b"2026-08-11T12:30:45" -# ---- no-UTF-8-form string is refused without quoting the plaintext ---- - def test_lone_surrogate_string_refused_without_quoting_plaintext(): - secret = "secret-\ud800-value" # lone surrogate: no valid UTF-8 form + # Lone surrogate: no valid UTF-8 form. + secret = "secret-\ud800-value" with pytest.raises(EncryptionError) as ei: enc(secret) # UnicodeEncodeError holds the plaintext in .object. The production code @@ -808,19 +810,16 @@ def test_lone_surrogate_string_refused_without_quoting_plaintext(): assert ei.value.__context__ is None -# ---- GCM auth independence from HMAC ---- - def test_gcm_auth_tag_bound_to_data_key(): # A payload encrypted+signed under a different data key (same HMAC key) must # pass the HMAC check but fail GCM when decrypted with the original data key. other_dk = bytes([(b + 7) % 256 for b in DATA_KEY]) other = EncryptionService.encrypt("v", other_dk, HMAC_KEY, key_id=KEY_ID) with pytest.raises(DecryptionError): - dec(other) # HMAC matches (HMAC_KEY), data key wrong for DATA_KEY decrypt + # HMAC matches (HMAC_KEY), data key wrong for DATA_KEY decrypt. + dec(other) -# ---- exception hierarchy: lenient read mode relies on this ---- - class TestExceptionHierarchy: """The read path's lenient mode (encryption_return_unverified_data) will catch IntegrityCheckError and let every other failure through. These tests @@ -850,7 +849,7 @@ def test_tampered_value_is_catchable_as_integrity_only(self): with pytest.raises(IntegrityCheckError): dec(bytes(payload)) - def test_wrong_key_is_not_an_integrity_error(self): + def test_wrong_key_not_integrity_error(self): # ...but it must not swallow a wrong-key failure. That raises # DecryptionError, which is not an IntegrityCheckError. wrong_dk = bytes([(b + 1) % 256 for b in DATA_KEY]) @@ -862,3 +861,24 @@ def test_wrong_key_is_not_an_integrity_error(self): pytest.fail("wrong-key failure must not be an IntegrityCheckError") except DecryptionError: pass + + +def test_serialize_unknown_marker_raises(): + with pytest.raises(EncryptionFailedError, match="Unsupported type marker: '12345'"): + EncryptionService._serialize("x", 12345) + + +def test_encrypt_aesgcm_failure_raises(mocker): + failure = ValueError("boom") + mocker.patch.object(AESGCM, "encrypt", side_effect=failure) + with pytest.raises(EncryptionFailedError, match="Failed to encrypt value: ValueError") as ei: + enc("x") + assert ei.value.__cause__ is failure + + +def test_serialize_date_as_timestamp_uses_midnight_utc(): + assert EncryptionService.serialize_value(date(2020, 1, 2), TypeMarker.TIMESTAMP) == struct.pack(">q", 1577923200000) + + +def test_truthy_bool_returns_it(): + assert EncryptionService._truthy(True) is True diff --git a/tests/unit/test_key_management_utility.py b/tests/unit/test_key_management_utility.py index f8ae7bf05..db70790ea 100644 --- a/tests/unit/test_key_management_utility.py +++ b/tests/unit/test_key_management_utility.py @@ -13,16 +13,27 @@ # limitations under the License. import logging -from typing import Any, List, Tuple +import threading +import time +from dataclasses import replace +from typing import Any, Callable, Dict, List, Optional, Tuple from unittest.mock import MagicMock, create_autospec import boto3 +import psycopg import pytest from botocore.stub import Stubber +from mysql.connector import MySQLConnection +from mysql.connector.pooling import PooledMySQLConnection +from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes +from aws_advanced_python_wrapper.driver_dialect_manager import \ + DriverDialectManager from aws_advanced_python_wrapper.encryption import \ key_management_utility as kmu_module from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService from aws_advanced_python_wrapper.encryption.key_management_utility import \ KeyManagementUtility from aws_advanced_python_wrapper.encryption.key_manager import ( @@ -30,17 +41,23 @@ from aws_advanced_python_wrapper.encryption.metadata_manager import \ MetadataManager from aws_advanced_python_wrapper.encryption.models import ( - ColumnEncryptionConfig, KeyMetadata, mask_arn) -from aws_advanced_python_wrapper.encryption.sql_dialect import (MYSQL, PG, - SqlDialect, - fetch_rows) -from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + ColumnEncryptionConfig, KeyMetadata, KeyOperation, mask_arn) +from aws_advanced_python_wrapper.errors import (AwsWrapperError, + EncryptionConfigError, InvalidAlgorithmError, - KeyManagementError) + KeyManagementError, + QueryTimeoutError) +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) +from aws_advanced_python_wrapper.utils.utils import Utils +from aws_advanced_python_wrapper.wrapper import AwsWrapperConnection ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" ALIAS_ARN = "arn:aws:kms:us-east-1:123456789012:alias/python-kms-encryption-1700000000000" -ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/kiro-admin-role/kiro-admin-session" +ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/test-admin-role/test-admin-session" class RecordingConnection: @@ -81,12 +98,16 @@ def conn(): def config(restricted=False): return EncryptionConfig(kms_region="us-east-1", - allowed_master_key_arns=frozenset({ARN}) if restricted else frozenset()) + allowed_master_key_arns=frozenset({ARN}) if restricted else frozenset(), + kms_endpoint=None, metadata_schema="encrypt", metadata_cache_enabled=True, + metadata_cache_expiration_sec=3600.0, metadata_cache_refresh_interval_sec=300.0, data_key_cache_enabled=True, + data_key_cache_max_size=1000, data_key_cache_expiration_sec=300.0, key_management_max_retries=3, + key_management_retry_backoff_base_sec=0.1, audit_logging_enabled=False, return_unverified_data=False) -def utility(conn, restricted=False, engine="postgresql"): +def utility(conn, restricted=False, driver=DriverDialectCodes.PSYCOPG): kms = MagicMock() - u = KeyManagementUtility(conn, kms, config(restricted), engine=engine) + u = KeyManagementUtility(conn, kms, config(restricted), props={WrapperProperties.DRIVER_DIALECT.name: driver}) # Autospec, so a misspelled method fails here as it would in production. u._key_manager = create_autospec(KeyManager, instance=True) u._key_manager.generate_data_key.return_value = GeneratedDataKey( @@ -102,7 +123,8 @@ def test_generates_stores_and_upserts_metadata(self, conn): u, _ = utility(conn) assert u.initialize_encryption_for_column("users", "ssn", ARN) == 11 stored = u._key_manager.store_key_metadata.call_args[0][0] - assert stored.master_key_arn == ARN and stored.key_spec == "AES_256" + assert stored.master_key_arn == ARN + assert stored.key_spec == "AES_256" assert stored.key_name.startswith("key-users-ssn-") sql, params = conn.executed[-1] assert sql.startswith("INSERT INTO encrypt.encryption_metadata") @@ -110,13 +132,13 @@ def test_generates_stores_and_upserts_metadata(self, conn): "EXCLUDED.encryption_algorithm, key_id = EXCLUDED.key_id, updated_at = CURRENT_TIMESTAMP" in sql assert params == ("users", "ssn", "AES-256-GCM", 11) - def test_wipes_the_generated_plaintext(self, conn): + def test_wipes_generated_plaintext(self, conn): u, _ = utility(conn) u.initialize_encryption_for_column("users", "ssn", ARN) generated = u._key_manager.generate_data_key.return_value assert generated.plaintext == bytearray(32) - def test_wipes_the_plaintext_even_when_storing_fails(self, conn): + def test_wipes_plaintext_when_store_fails(self, conn): u, _ = utility(conn) u._key_manager.store_key_metadata.side_effect = KeyManagementError("x") with pytest.raises(KeyManagementError): @@ -124,14 +146,14 @@ def test_wipes_the_plaintext_even_when_storing_fails(self, conn): assert u._key_manager.generate_data_key.return_value.plaintext == bytearray(32) def test_mysql_upsert_grammar(self, conn): - u, _ = utility(conn, engine="mysql") - u.initialize_encryption_for_column("users", "ssn", ARN, "AES-128-GCM") + u, _ = utility(conn, driver=DriverDialectCodes.MYSQL_CONNECTOR_PYTHON) + u.initialize_encryption_for_column("users", "ssn", ARN) sql = conn.executed[-1][0] assert "ON DUPLICATE KEY UPDATE encryption_algorithm = VALUES(encryption_algorithm), " \ "key_id = VALUES(key_id), updated_at = CURRENT_TIMESTAMP" in sql - u._key_manager.generate_data_key.assert_called_with(ARN, "AES-128-GCM") + u._key_manager.generate_data_key.assert_called_with(ARN, "AES-256-GCM") - def test_refuses_an_already_encrypted_column(self, conn): + def test_already_encrypted_column_raises(self, conn): u, _ = utility(conn) u._metadata.is_column_encrypted.return_value = True with pytest.raises(KeyManagementError, match="already encrypted"): @@ -143,6 +165,24 @@ def test_unsupported_algorithm(self, conn): with pytest.raises(InvalidAlgorithmError): u.initialize_encryption_for_column("users", "ssn", ARN, "DES") + @pytest.mark.parametrize("method", ["initialize_encryption_for_column", "generate_and_store_data_key"]) + def test_aes_128_gcm_refused_before_any_kms_call(self, conn, method): + u, _ = utility(conn, restricted=True) + with pytest.raises(InvalidAlgorithmError) as info: + getattr(u, method)("users", "ssn", ARN.replace("1234abcd", "eeeeeeee"), "AES-128-GCM") + assert str(info.value) == Messages.get_formatted("KeyManagementUtility.UnsupportedAlgorithm", "AES-128-GCM") + u._key_manager.generate_data_key.assert_not_called() + u._key_manager.store_key_metadata.assert_not_called() + assert conn.executed == [] + + def test_refused_algorithm_message_replaces_control_characters(self, conn): + u, _ = utility(conn) + with pytest.raises(InvalidAlgorithmError) as info: + u.initialize_encryption_for_column("users", "ssn", ARN, "AES-256-GCM\x1b[2J\u202e") + assert "'AES-256-GCM?[2J?'" in str(info.value) + assert "\x1b" not in str(info.value) + assert "\u202e" not in str(info.value) + @pytest.mark.parametrize("args", [(None, "c", ARN), ("t", "", ARN), ("t", "c", None)]) def test_required_arguments(self, conn, args): u, _ = utility(conn) @@ -162,27 +202,47 @@ def _current(self, u, arn=ARN, algorithm="AES-256-GCM"): u._metadata.column_config.return_value = ColumnEncryptionConfig( "users", "ssn", algorithm, 4, km if arn else None) - def test_rotate_onto_the_current_master_key_needs_the_allow_list(self, conn): + def test_rotate_onto_current_master_key_needs_allow_list(self, conn): u, _ = utility(conn, restricted=False) with pytest.raises(ValueError, match="encryption_allowed_master_key_arns"): u.rotate_data_key("users", "ssn") - def test_rotate_keeping_the_current_master_key(self, conn): + def test_rotate_keeps_current_master_key(self, conn): u, _ = utility(conn, restricted=True) - self._current(u, algorithm="AES-128-GCM") + self._current(u) assert u.rotate_data_key("users", "ssn") == 11 - u._key_manager.generate_data_key.assert_called_with(ARN, "AES-128-GCM") + u._key_manager.generate_data_key.assert_called_with(ARN, "AES-256-GCM") sql, params = conn.executed[-1] assert sql.startswith("UPDATE encrypt.encryption_metadata SET key_id = %s") assert params == (11, "users", "ssn") - def test_rotate_onto_a_new_master_key(self, conn): + def test_rotate_onto_new_master_key(self, conn): u, _ = utility(conn) self._current(u) other = ARN.replace("1234abcd", "eeeeeeee") u.rotate_data_key("users", "ssn", other) u._key_manager.generate_data_key.assert_called_with(other, "AES-256-GCM") + def test_rotate_aes_128_gcm_column_refused_with_nothing_written(self, conn): + u, _ = utility(conn, restricted=True) + self._current(u, algorithm="AES-128-GCM") + with pytest.raises(InvalidAlgorithmError) as info: + u.rotate_data_key("users", "ssn") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.RotateUnsupportedAlgorithm", "users", "ssn", "AES-128-GCM") + u._key_manager.generate_data_key.assert_not_called() + assert conn.executed == [] + + def test_rotate_column_with_data_refused_before_any_change(self, conn): + u, _ = utility(conn, restricted=True) + self._current(u) + conn.rows = [(1,)] + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key("users", "ssn") + assert str(info.value) == Messages.get_formatted("KeyManagementUtility.RotateColumnHasData", "users", "ssn") + assert conn.executed == [('SELECT 1 FROM "users" WHERE "ssn" IS NOT NULL LIMIT 1', ())] + u._key_manager.generate_data_key.assert_not_called() + def test_rotate_unknown_column(self, conn): u, _ = utility(conn) u._metadata.column_config.return_value = None @@ -203,8 +263,506 @@ def test_rotate_fails_if_no_row_was_updated(self, conn): u.rotate_data_key("users", "ssn", ARN) +OLD_DATA_KEY = bytes(range(32)) +OLD_HMAC = bytes(range(32, 64)) +NEW_DATA_KEY = bytes(range(64, 96)) +NEW_HMAC = bytes(range(96, 128)) +OLDER_DATA_KEY = bytes(range(128, 160)) +OLDER_HMAC = bytes(range(160, 192)) +DATA_KEYS = {"b2xk": OLD_DATA_KEY, "bmV3": NEW_DATA_KEY, "b2xkZXI=": OLDER_DATA_KEY} +OLD_ROW = KeyMetadata(id=4, master_key_arn=ARN, encrypted_data_key="b2xk", hmac_key=OLD_HMAC) +NEW_ROW = KeyMetadata(id=11, master_key_arn=ARN, encrypted_data_key="bmV3", hmac_key=NEW_HMAC) +OLDER_ROW = KeyMetadata(id=3, master_key_arn=ARN, encrypted_data_key="b2xkZXI=", hmac_key=OLDER_HMAC) + + +class DriverError(Exception): + sqlstate = "40001" + + +class TableCursor: + def __init__(self, conn: "TableConnection"): + self._conn = conn + self.description: Optional[List[Tuple[str]]] = None + self.rowcount = -1 + self._rows: List[Tuple[Any, ...]] = [] + + def execute(self, sql, params=()): + conn = self._conn + params = tuple(params) + conn.executed.append((sql, params)) + if conn.hook is not None: + conn.hook(sql, params) + self.description, self.rowcount, self._rows = [("id",), ("ssn",)], 0, [] + if conn.fail is not None and sql.startswith(conn.fail): + raise DriverError("near 'SECRET-ROW-BYTES'") + if sql.startswith("SELECT 1 FROM"): + self._rows = [(1,)] if any(v is not None for v in conn.rows.values()) else [] + elif "ORDER BY" in sql: + last = params[0] if len(params) == 2 else None + found = sorted((pk, v) for pk, v in conn.rows.items() if v is not None and (last is None or pk > last)) + self._rows = found[:params[-1]] + elif sql.startswith("UPDATE encrypt.encryption_metadata"): + new, _, _, old = params + if conn.key_id == old: + conn.key_id, self.rowcount = new, 1 + elif sql.startswith(('UPDATE "users"', "UPDATE `users`")): + new, pk, old = params + if conn.rows.get(pk) == old: + conn.rows[pk], self.rowcount = new, 1 + elif "pg_catalog.format_type" in sql: + self.description = [("type_name",), ("built_in",)] + if conn.key_type is not None: + self._rows = [(conn.key_type, conn.key_type in ("integer", "bigint"))] + if conn.autocommit: + conn.commit() + + def fetchall(self): + return self._rows + + def close(self): + pass + + +class TableConnection: + """A psycopg-shaped connection over ``users (id, ssn)``: a rollback restores the rows and the column's key id + of the last commit.""" + + def __init__(self, rows: Dict[int, Optional[bytes]], key_id: int = 4): + self.rows = dict(rows) + self.key_id = key_id + self.autocommit = True + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + self.commits = 0 + self.rollbacks = 0 + self.fail: Optional[str] = None + self.hook: Optional[Callable[[str, Tuple[Any, ...]], None]] = None + self.key_type: Optional[str] = "integer" + self._saved = (dict(self.rows), key_id) + + def cursor(self): + return TableCursor(self) + + def commit(self): + self.commits += 1 + self._saved = (dict(self.rows), self.key_id) + + def rollback(self): + self.rollbacks += 1 + self.rows, self.key_id = dict(self._saved[0]), self._saved[1] + + +def payload(value: str, key: Any) -> Any: + return EncryptionService.encrypt(value, DATA_KEYS[key.encrypted_data_key], key.hmac_key, key_id=key.id) + + +def opened(stored: Any) -> Any: + key: Any = {4: OLD_ROW, 11: NEW_ROW, 3: OLDER_ROW}.get(EncryptionService.key_id_from_payload(stored) or 0) + return EncryptionService.decrypt(stored, DATA_KEYS[key.encrypted_data_key], key.hmac_key) + + +def reencrypting(mocker, rows: Dict[int, Optional[bytes]], restricted=True, driver=DriverDialectCodes.PSYCOPG): + conn = TableConnection(rows) + u, _ = utility(conn, restricted=restricted, driver=driver) + mocker.patch.object(u._driver_dialect, "get_autocommit", side_effect=lambda c: c.autocommit) + mocker.patch.object(u._driver_dialect, "set_autocommit", side_effect=lambda c, value: setattr(c, "autocommit", value)) + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 4, OLD_ROW) + u._key_manager.generate_data_key.return_value = GeneratedDataKey(bytearray(NEW_DATA_KEY), "bmV3", NEW_HMAC, "AES_256") + u._key_manager.decrypt_data_key.side_effect = lambda edk, arn: bytearray(DATA_KEYS[edk]) + u._key_manager.key_metadata_by_id.side_effect = {4: OLD_ROW, 11: NEW_ROW, 3: OLDER_ROW}.get + return u, conn + + +def writes(conn: TableConnection) -> List[str]: + return [sql for sql, _ in conn.executed if not sql.startswith("SELECT")] + + +class TestReencrypt: + def test_rotate_and_reencrypt_moves_every_value_to_new_key(self, mocker): + rows = {i: payload(f"v{i}", OLD_ROW) for i in range(1, 6)} + rows[6] = None + u, conn = reencrypting(mocker, rows) + result = u.rotate_data_key_and_reencrypt("users", "ssn", "id", batch_size=2) + assert (result.reencrypted_count, result.already_current_count, result.unmatched_count) == (5, 0, 0) + assert result.key_id == 11 + assert result.old_key_ids == (4,) + assert conn.key_id == 11 + assert {pk: EncryptionService.key_id_from_payload(v) for pk, v in conn.rows.items() if v} == dict.fromkeys(range(1, 6), 11) + assert [opened(conn.rows[i]) for i in range(1, 6)] == [f"v{i}" for i in range(1, 6)] + assert conn.autocommit is True + page = [sql for sql, _ in conn.executed if "FOR UPDATE" in sql][0] + assert page == ('SELECT "id", "ssn" FROM "users" WHERE "ssn" IS NOT NULL AND "id" IS NOT NULL ' + 'ORDER BY "id" LIMIT %s FOR UPDATE') + + def test_failed_batch_keeps_committed_batches_and_names_old_key_id(self, mocker): + u, conn = reencrypting(mocker, {i: payload(f"v{i}", OLD_ROW) for i in range(1, 6)}) + updates = [] + + def fail_third_update(sql, params): + if sql.startswith('UPDATE "users"'): + updates.append(params) + if len(updates) == 3: + raise DriverError("near 'SECRET-ROW-BYTES'") + + conn.hook = fail_third_update + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("users", "ssn", "id", batch_size=2) + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.ReencryptFailed", "users", "ssn", 2, 2, "DriverError, sqlstate 40001", 11, "4") + assert [EncryptionService.key_id_from_payload(conn.rows[i]) for i in range(1, 6)] == [11, 11, 4, 4, 4] + assert conn.key_id == 11 + + def test_reencrypt_remaining_rows_skips_current_and_counts_unmatched(self, mocker, caplog): + rows = {1: payload("a", NEW_ROW), 2: payload("b", OLD_ROW), 3: payload("c", OLDER_ROW), 4: b"\x01" * 70} + u, conn = reencrypting(mocker, rows) + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 11, NEW_ROW) + with caplog.at_level(logging.WARNING): + result = u.reencrypt_remaining_rows("users", "ssn", "id", [4]) + assert (result.reencrypted_count, result.already_current_count, result.unmatched_count) == (1, 1, 2) + assert result.unmatched_primary_keys == (3, 4) + assert [EncryptionService.key_id_from_payload(conn.rows[i]) for i in (1, 2, 3)] == [11, 11, 3] + assert opened(conn.rows[2]) == "b" + assert u.reencrypt_remaining_rows("users", "ssn", "id", [4]).reencrypted_count == 0 + assert [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING][0] == Messages.get_formatted( + "KeyManagementUtility.UnmatchedRows", "users", "ssn", 2, 11, "4") + + def test_precheck_refuses_values_not_under_current_key(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW), 2: payload("b", OLDER_ROW)}) + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.RotationPrecheckFailed", "users", "ssn", 1, 4) + assert writes(conn) == [] + u._key_manager.generate_data_key.assert_not_called() + assert conn.key_id == 4 + + def test_wrapper_connection_refused_with_nothing_written(self, mocker): + wrapper = MagicMock(spec=AwsWrapperConnection) + wrapper.target_connection = MagicMock(spec=psycopg.Connection) + u, _ = utility(wrapper) + for call in (lambda: u.rotate_data_key_and_reencrypt("users", "ssn", "id", ARN), + lambda: u.reencrypt_remaining_rows("users", "ssn", "id", [4])): + with pytest.raises(KeyManagementError) as info: + call() + assert str(info.value) == Messages.get("KeyManagementUtility.PluginConnectionNotAllowed") + u._metadata.column_config.assert_not_called() + u._key_manager.generate_data_key.assert_not_called() + + def test_changed_row_fails_batch_nothing_overwritten(self, mocker): + first, second, changed = payload("a", OLD_ROW), payload("b", OLD_ROW), payload("changed", OLD_ROW) + u, conn = reencrypting(mocker, {1: first, 2: second}) + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 11, NEW_ROW) + + def concurrent_change(sql, params): + if sql.startswith('UPDATE "users"') and params[1] == 2: + conn.rows[2] = changed + conn._saved[0][2] = changed + + conn.hook = concurrent_change + with pytest.raises(KeyManagementError) as info: + u.reencrypt_remaining_rows("users", "ssn", "id", [4]) + assert Messages.get("KeyManagementUtility.RowUpdateMissed") in str(info.value) + assert conn.rows[2] == changed + + def test_moved_key_id_stops_switch(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + conn.key_id = 7 + conn.commit() + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.RotationSwitchConflict", "users", "ssn", 4, 11) + assert conn.key_id == 7 + assert EncryptionService.key_id_from_payload(conn.rows[1]) == 4 + assert conn.rollbacks == 1 + + def test_aes_128_gcm_column_refused_with_nothing_written(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-128-GCM", 4, OLD_ROW) + for call in (lambda: u.rotate_data_key_and_reencrypt("users", "ssn", "id"), + lambda: u.reencrypt_remaining_rows("users", "ssn", "id", [3])): + with pytest.raises(InvalidAlgorithmError): + call() + assert writes(conn) == [] + u._key_manager.generate_data_key.assert_not_called() + u._key_manager.decrypt_data_key.assert_not_called() + + @pytest.mark.parametrize("table, column, key", [ + ('users"; DROP TABLE users; --', "ssn", "id"), + ("users", "ssn`", "id"), + ("users", "ssn", "id OR 1=1"), + ("a.b.users", "ssn", "id"), + ("users", "s" * 65, "id"), + ("users", "ssn", "SSN"), + ]) + def test_hostile_identifier_refused_before_any_statement(self, mocker, table, column, key): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + for call in (lambda: u.rotate_data_key_and_reencrypt(table, column, key), + lambda: u.reencrypt_remaining_rows(table, column, key, [3])): + with pytest.raises(ValueError): + call() + assert conn.executed == [] + u._metadata.column_config.assert_not_called() + + def test_value_naming_unlisted_row_unmatched_no_kms_call(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLDER_ROW)}) + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 11, NEW_ROW) + result = u.reencrypt_remaining_rows("users", "ssn", "id", [4]) + assert (result.reencrypted_count, result.unmatched_count) == (0, 1) + u._key_manager.decrypt_data_key.assert_not_called() + assert EncryptionService.key_id_from_payload(conn.rows[1]) == 3 + + def test_tampered_value_stops_precheck(self, mocker): + tampered = bytearray(payload("a", OLD_ROW)) + tampered[-1] ^= 1 + u, conn = reencrypting(mocker, {1: payload("b", OLD_ROW), 2: bytes(tampered)}) + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.RotationPrecheckFailed", "users", "ssn", 1, 4) + assert writes(conn) == [] + u._key_manager.decrypt_data_key.assert_not_called() + + @pytest.mark.parametrize("old_key_ids, key, message", [ + ([4], "OldKeyIsCurrent", (4, "users", "ssn")), + ([5], "OldKeyNotFound", (5,)), + ([12], "KeyRowUnusable", (12,)), + ]) + def test_old_key_ids_refused_before_table_statements(self, mocker, old_key_ids, key, message): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + unusable = replace(OLD_ROW, id=12, hmac_key=None) + u._key_manager.key_metadata_by_id.side_effect = {4: OLD_ROW, 12: unusable}.get + with pytest.raises(KeyManagementError) as info: + u.reencrypt_remaining_rows("users", "ssn", "id", old_key_ids) + assert str(info.value) == Messages.get_formatted(f"KeyManagementUtility.{key}", *message) + assert conn.executed == [] + + @pytest.mark.parametrize("call, error", [ + (lambda u: u.reencrypt_remaining_rows("users", "ssn", "id", []), ValueError), + (lambda u: u.reencrypt_remaining_rows("users", "ssn", "id", [None]), ValueError), + (lambda u: u.rotate_data_key_and_reencrypt("users", "ssn", "id", batch_size=0), ValueError), + (lambda u: u.rotate_data_key_and_reencrypt("users", "ssn", "id", batch_size=100_001), ValueError), + (lambda u: u.rotate_data_key_and_reencrypt("users", "ssn", "id", batch_size=True), ValueError), + ], ids=["no-old-key", "none-old-key", "batch-0", "batch-too-big", "batch-bool"]) + def test_arguments_refused_before_any_statement(self, mocker, call, error): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + with pytest.raises(error): + call(u) + assert conn.executed == [] + + def test_reencrypt_remaining_rows_needs_allow_list(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}, restricted=False) + with pytest.raises(ValueError, match="encryption_allowed_master_key_arns"): + u.reencrypt_remaining_rows("users", "ssn", "id", [3]) + assert conn.executed == [] + + @pytest.mark.parametrize("config", [None, ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 4, None)], + ids=["not-encrypted", "no-key-row"]) + def test_column_without_usable_key_refused(self, mocker, config): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + u._metadata.column_config.return_value = config + with pytest.raises(KeyManagementError): + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert writes(conn) == [] + + def test_new_master_key_checked_against_allow_list(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + other = ARN.replace("1234abcd", "eeeeeeee") + u._key_manager.authorize_master_key.side_effect = lambda arn: None if arn == ARN else (_ for _ in ()).throw( + KeyManagementError("unlisted")) + with pytest.raises(KeyManagementError, match="unlisted"): + u.rotate_data_key_and_reencrypt("users", "ssn", "id", other) + assert conn.executed == [] + u.rotate_data_key_and_reencrypt("users", "ssn", "id", ARN) + u._key_manager.generate_data_key.assert_called_once_with(ARN, "AES-256-GCM") + + def test_missing_table_or_column_refused_before_any_change(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + conn.fail = 'SELECT "id", "ssn" FROM "users" WHERE FALSE' + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.RelationCheckFailed", "users", "ssn", "id", "DriverError, sqlstate 40001") + assert info.value.__context__ is None + assert writes(conn) == [] + + def test_pg_key_column_of_user_defined_type_refused(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + conn.key_type = "app.money_id" + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("app.users", "ssn", "id") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.UnsupportedPrimaryKeyType", "users", "id", "app.money_id") + type_check = [params for sql, params in conn.executed if "pg_catalog.format_type" in sql] + assert type_check == [('"app"."users"', "id")] + u._metadata.column_config.assert_called_with("users", "ssn") + + def test_pg_key_column_type_not_found_refused_before_any_change(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + conn.key_type = None + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.UnsupportedPrimaryKeyType", "users", "id", "unknown") + assert writes(conn) == [] + u._key_manager.generate_data_key.assert_not_called() + + def test_mysql_needs_no_key_type_check_and_prefixes_binary(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}, driver=DriverDialectCodes.MYSQL_CONNECTOR_PYTHON) + conn.executed.clear() + mocker.patch.object(MySQLDriverDialect, "binary_placeholder_prefix", return_value="_binary ") + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 11, NEW_ROW) + assert u.reencrypt_remaining_rows("users", "ssn", "id", [4]).reencrypted_count == 1 + assert not [sql for sql, _ in conn.executed if "format_type" in sql] + assert [sql for sql, _ in conn.executed if sql.startswith("UPDATE")] == [ + "UPDATE `users` SET `ssn` = _binary %s WHERE `id` = %s AND `ssn` = _binary %s"] + + def test_text_value_refused_by_precheck_and_unmatched_after(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW), 2: "123-45-6789"}) + with pytest.raises(KeyManagementError) as info: + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert str(info.value) == Messages.get_formatted( + "KeyManagementUtility.RotationPrecheckFailed", "users", "ssn", 1, 4) + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 11, NEW_ROW) + result = u.reencrypt_remaining_rows("users", "ssn", "id", [4]) + assert (result.reencrypted_count, result.unmatched_count, result.unmatched_primary_keys) == (1, 1, (2,)) + assert conn.rows[2] == "123-45-6789" + + def test_empty_table_counts_no_batch(self, mocker): + u, _ = reencrypting(mocker, {}) + result = u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert (result.reencrypted_count, result.batch_count) == (0, 0) + + def test_rollback_failure_logged_and_original_error_kept(self, mocker, caplog): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW), 2: payload("b", OLDER_ROW)}) + conn.rollback = MagicMock(side_effect=DriverError("near 'SECRET'")) + with caplog.at_level(logging.WARNING): + with pytest.raises(KeyManagementError, match="RotationPrecheckFailed|stopped before any change"): + u.rotate_data_key_and_reencrypt("users", "ssn", "id") + assert [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] == [ + Messages.get_formatted("KeyManagementUtility.RollbackFailed", "DriverError, sqlstate 40001")] + + def test_batch_failure_chains_no_driver_error(self, mocker): + u, conn = reencrypting(mocker, {1: payload("a", OLD_ROW)}) + u._metadata.column_config.return_value = ColumnEncryptionConfig("users", "ssn", "AES-256-GCM", 11, NEW_ROW) + conn.fail = 'UPDATE "users"' + with pytest.raises(KeyManagementError) as info: + u.reencrypt_remaining_rows("users", "ssn", "id", [4]) + assert info.value.__cause__ is None + assert info.value.__context__ is None + assert "SECRET" not in str(info.value) + assert "SECRET" not in repr(info.value.args) + + +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"] + + +class CatalogConnection: + """Answers the catalog queries from ``tables``, ``keys`` and ``foreign_keys``.""" + + def __init__(self, dialect: Any): + self.dialect = dialect + self.tables = {"encryption_metadata": list(METADATA_COLUMNS), "key_storage": list(KEY_STORAGE_COLUMNS)} + self.keys = {"encryption_metadata": [("em_pkey", "PRIMARY KEY", ["table_name", "column_name"])], + "key_storage": [("ks_pkey", "PRIMARY KEY", ["id"]), ("ks_key_id_key", "UNIQUE", ["key_id"])]} + self.foreign_keys = {"encryption_metadata": [("key_id", "key_storage", "id")]} + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + + def cursor(self): + conn = self + + class Cursor: + description: Optional[List[Tuple[str]]] = None + + def execute(self, sql, params=()): + conn.executed.append((sql, tuple(params))) + schema, table = params + assert schema == "encrypt" + if sql == conn.dialect.schema_table_sql: + self.description, self.rows = [("found",)], [(1,)] if table in conn.tables else [] + elif sql == conn.dialect.schema_columns_sql: + self.description, self.rows = [("column_name",)], [(c.upper(),) for c in conn.tables.get(table, [])] + elif sql == conn.dialect.schema_key_constraints_sql: + self.description = [("constraint_name",), ("constraint_type",), ("column_name",)] + self.rows = [(name, kind, c) for name, kind, cols in conn.keys.get(table, []) for c in cols] + elif sql == conn.dialect.schema_foreign_keys_sql: + self.description = [("column_name",), ("referenced_table",), ("referenced_column",)] + self.rows = list(conn.foreign_keys.get(table, [])) + else: + raise AssertionError(sql) + + def fetchall(self): + return self.rows + + def close(self): + pass + + return Cursor() + + +@pytest.fixture(params=[DriverDialectCodes.PSYCOPG, DriverDialectCodes.MYSQL_CONNECTOR_PYTHON], ids=["pg", "mysql"]) +def catalog(request): + dialect = PgDriverDialect if request.param == DriverDialectCodes.PSYCOPG else MySQLDriverDialect + conn = CatalogConnection(dialect) + u, kms = utility(conn, driver=request.param) + return u, conn, kms + + +def problem(key: str, *args: Any) -> str: + return Messages.get_formatted(f"KeyManagementUtility.{key}", *args) + + +class TestValidateSchema: + def test_guide_schema_has_no_problems(self, catalog): + u, conn, kms = catalog + assert u.validate_schema() == [] + assert all(params[0] == "encrypt" for _, params in conn.executed) + assert kms.method_calls == [] + + def test_missing_table_and_column_reported(self, catalog): + u, conn, _ = catalog + del conn.tables["encryption_metadata"] + conn.tables["key_storage"].remove("hmac_key") + conn.tables["key_storage"].remove("key_spec") + assert u.validate_schema() == [ + problem("SchemaMissingTable", "encrypt", "encryption_metadata"), + problem("SchemaMissingColumn", "encrypt", "key_storage", "hmac_key"), + problem("SchemaMissingColumn", "encrypt", "key_storage", "key_spec"), + ] + + def test_missing_keys_reported(self, catalog): + u, conn, _ = catalog + conn.keys["encryption_metadata"] = [("em_name_key", "UNIQUE", ["table_name"])] + conn.keys["key_storage"] = [("ks_key_id_key", "UNIQUE", ["id"])] + conn.foreign_keys = {} + assert u.validate_schema() == [ + problem("SchemaMissingUniqueKey", "encrypt"), + problem("SchemaMissingPrimaryKey", "encrypt"), + ] + + def test_unique_constraint_on_metadata_names_suffices(self, catalog): + u, conn, _ = catalog + conn.keys["encryption_metadata"] = [("em_key", "UNIQUE", ["column_name", "table_name"])] + assert u.validate_schema() == [] + + def test_only_foreign_key_reported_on_sound_schema(self, catalog): + u, conn, _ = catalog + conn.foreign_keys = {"encryption_metadata": [("key_id", "key_storage", "key_id")]} + assert u.validate_schema() == [problem("SchemaMissingForeignKey", "encrypt", "encrypt")] + + def test_catalog_failure_chains_no_driver_error(self, catalog): + u, conn, _ = catalog + conn.cursor = MagicMock(side_effect=DriverError("near 'SECRET'")) + with pytest.raises(KeyManagementError) as info: + u.validate_schema() + assert info.value.__cause__ is None + assert info.value.__context__ is None + assert "SECRET" not in str(info.value) + + class TestRemoveAndQuery: - def test_remove_deletes_only_the_metadata_row(self, conn): + def test_remove_deletes_only_metadata_row(self, conn): u, _ = utility(conn) assert u.remove_encryption_for_column("users", "ssn") is True assert len(conn.executed) == 1 @@ -250,9 +808,9 @@ def test_alias_failure_is_not_fatal(self, conn): pytest.param("AlreadyExistsException", f"An alias with the name {ALIAS_ARN} already exists", id="already-exists"), ]) - def test_alias_failure_warning_masks_the_arns_kms_quotes(self, conn, caplog, code, text): + def test_alias_failure_warning_quotes_no_kms_text(self, conn, caplog, code, text): kms = boto3.client("kms", region_name="us-east-1", aws_access_key_id="x", aws_secret_access_key="x") - u = KeyManagementUtility(conn, kms, config(), engine="postgresql") + u = KeyManagementUtility(conn, kms, config(), props={WrapperProperties.DRIVER_DIALECT.name: DriverDialectCodes.PSYCOPG}) u._key_manager = create_autospec(KeyManager, instance=True) u._key_manager.create_master_key.return_value = ARN with Stubber(kms) as stubber, caplog.at_level(logging.WARNING, logger=kmu_module.__name__): @@ -263,9 +821,10 @@ def test_alias_failure_warning_masks_the_arns_kms_quotes(self, conn, caplog, cod warnings = [r.getMessage() for r in caplog.records if r.name == kmu_module.__name__ and r.levelno == logging.WARNING] assert len(warnings) == 1 - assert f"({code})" in warnings[0] and mask_arn(ARN) in warnings[0] - assert "arn:aws:kms:***:***:***" in warnings[0] - for identifier in (ARN, ALIAS_ARN, ROLE_SESSION_ARN, "123456789012", "kiro-admin-role", "kiro-admin-session"): + assert warnings[0].startswith( + f"[KeyManagementUtility] Created master key {mask_arn(ARN)} but could not create an alias for it: ") + assert warnings[0].endswith(f", error code {code}, HTTP status 400") + for identifier in (ARN, ALIAS_ARN, ROLE_SESSION_ARN, "123456789012", "test-admin-role", "test-admin-session"): assert identifier not in warnings[0] def test_no_alias(self, conn): @@ -284,37 +843,109 @@ def test_unknown_driver(self, conn): with pytest.raises(EncryptionConfigError): KeyManagementUtility(conn, MagicMock(), config()) - def test_infers_from_driver_module_and_wrapper_connection(self): - pg_conn = type("Connection", (), {"__module__": "psycopg"})() - mysql_conn = type("CMySQLConnection", (), {"__module__": "mysql.connector.connection_cext"})() - wrapper = type("AwsWrapperConnection", (), {"target_connection": mysql_conn})() - assert SqlDialect.for_connection(pg_conn) is PG - assert SqlDialect.for_connection(mysql_conn) is MYSQL - assert SqlDialect.for_connection(wrapper) is MYSQL - assert SqlDialect.for_name("PostgreSQL") is PG - - def test_from_driver_dialect(self): - assert SqlDialect.for_driver_dialect(MagicMock(dialect_code="psycopg")) is PG - assert SqlDialect.for_driver_dialect(MagicMock(dialect_code="mysql-connector-python")) is MYSQL - with pytest.raises(EncryptionConfigError): - SqlDialect.for_driver_dialect(MagicMock(dialect_code="generic")) - - -def test_fetch_rows_lower_cases_keys_and_handles_no_result(): - conn = RecordingConnection() - conn.rows = [("t", "c")] - assert fetch_rows(conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] + def test_infers_dialect_from_connection_and_wrapper(self): + pg_conn = MagicMock(spec=psycopg.Connection) + mysql_conn = MagicMock(spec=MySQLConnection) + wrapper = MagicMock(spec=AwsWrapperConnection) + wrapper.target_connection = mysql_conn + manager = DriverDialectManager() + assert isinstance(manager.get_dialect_for_connection(pg_conn, Properties()), PgDriverDialect) + assert isinstance(manager.get_dialect_for_connection(mysql_conn, Properties()), MySQLDriverDialect) + assert isinstance(KeyManagementUtility(wrapper, MagicMock(), config())._driver_dialect, MySQLDriverDialect) + props = Properties({WrapperProperties.DRIVER_DIALECT.name: DriverDialectCodes.PSYCOPG}) + assert isinstance(manager.get_dialect_for_connection(None, props), PgDriverDialect) + + @pytest.mark.parametrize("code", ["oracle", "pg", "postgres", "mysql-connector"]) + def test_unknown_dialect_code_raises(self, conn, code): + with pytest.raises(AwsWrapperError, match=f"Unknown target driver dialect code: {code}"): + KeyManagementUtility(conn, MagicMock(), config(), props={WrapperProperties.DRIVER_DIALECT.name: code}) + + def test_driver_not_installed(self, mocker): + pg_path = DriverDialectManager.known_dialects_by_code[DriverDialectCodes.PSYCOPG] + initialize = Utils.initialize_class + mocker.patch.object(Utils, "initialize_class", + side_effect=lambda path, *args: None if path == pg_path else initialize(path, *args)) + manager = DriverDialectManager() + assert isinstance(manager.get_dialect_for_connection(MagicMock(spec=MySQLConnection), Properties()), MySQLDriverDialect) + with pytest.raises(AwsWrapperError, match="unable to initialize the target driver dialect"): + manager.get_dialect_for_connection(None, Properties({WrapperProperties.DRIVER_DIALECT.name: DriverDialectCodes.PSYCOPG})) + + def test_pooled_mysql_connection_needs_dialect_code(self): + pooled = PooledMySQLConnection.__new__(PooledMySQLConnection) + # The pool's wrapper forwards unknown attributes to the connection it holds. + pooled._cnx = MagicMock(spec=MySQLConnection) + with pytest.raises(EncryptionConfigError, match="'PooledMySQLConnection'.*wrapper_driver_dialect"): + KeyManagementUtility(pooled, MagicMock(), config()) + props = {WrapperProperties.DRIVER_DIALECT.name: DriverDialectCodes.MYSQL_CONNECTOR_PYTHON} + assert isinstance(KeyManagementUtility(pooled, MagicMock(), config(), props=props)._driver_dialect, MySQLDriverDialect) + + +TIMEOUT_PROPS = {WrapperProperties.DRIVER_DIALECT.name: DriverDialectCodes.PSYCOPG, + WrapperProperties.SOCKET_TIMEOUT_SEC.name: "0.05"} + + +def test_props_socket_timeout_bounds_statements(mocker): + released = threading.Event() + pg_conn = MagicMock(spec=psycopg.Connection) + pg_conn.cursor.return_value.execute.side_effect = lambda *args: released.wait(timeout=1) + # The abort ends the statement that waits, so no worker is left running. + abort = mocker.patch.object(PgDriverDialect, "abort_connection", side_effect=lambda c: released.set()) + u = KeyManagementUtility(pg_conn, MagicMock(), config(), props=TIMEOUT_PROPS) + with pytest.raises(KeyManagementError) as error: + u.columns_using_key(3) + assert isinstance(error.value.__cause__, QueryTimeoutError) + abort.assert_called_once_with(pg_conn) + + +def test_props_driver_dialect_code_selects_dialect(conn): + u = KeyManagementUtility(conn, MagicMock(), config(), + props={WrapperProperties.DRIVER_DIALECT.name: DriverDialectCodes.MYSQL_CONNECTOR_PYTHON}) + u.columns_using_key(3) + assert conn.executed[0] == ("SELECT table_name, column_name FROM encrypt.encryption_metadata " + "WHERE key_id = %s ORDER BY table_name, column_name", (3,)) + + +def test_props_socket_timeout_dropped_for_wrapper_connection(mocker): + wrapper = MagicMock(spec=AwsWrapperConnection) + wrapper.target_connection = MagicMock(spec=psycopg.Connection) + cursor = wrapper.cursor.return_value + cursor.execute.side_effect = lambda *args: time.sleep(0.2) + cursor.description = [("table_name",), ("column_name",)] + cursor.fetchall.return_value = [("users", "ssn")] + abort = mocker.spy(PgDriverDialect, "abort_connection") + u = KeyManagementUtility(wrapper, MagicMock(), config(), props=TIMEOUT_PROPS) + assert u.columns_using_key(3) == ["users.ssn"] + assert abort.call_count == 0 -def test_fetch_rows_accepts_dict_rows(): - # A connection opened with a dict-like row factory (psycopg dict_row) - # returns mappings; their keys are lower-cased like tuple rows' names. - conn = RecordingConnection() - conn.rows = [{"TABLE_NAME": "t", "column_name": "c"}] # type: ignore[list-item] - assert fetch_rows(conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] +def test_pg_statements_pin_built_in_equals_operator(conn): + u, _ = utility(conn) + u.columns_using_key(3) + assert "key_id OPERATOR(pg_catalog.=) %s" in conn.executed[0][0] def test_columns_using_key_with_dict_rows(conn): conn.rows = [{"table_name": "users", "column_name": "ssn"}] # type: ignore[list-item] u, _ = utility(conn) assert u.columns_using_key(3) == ["users.ssn"] + + +def test_create_master_key_without_description_raises(conn): + u, _ = utility(conn) + with pytest.raises(ValueError): + u.create_master_key(None) + + +def test_columns_using_key_statement_failure_raises(conn, mocker): + u, _ = utility(conn) + mocker.patch.object(kmu_module, "fetch_rows", side_effect=RuntimeError("boom")) + with pytest.raises(KeyManagementError) as error: + u.columns_using_key(3) + assert error.value.operation == KeyOperation.SELECT_COLUMNS_USING_KEY.value + + +def test_is_master_key_valid_delegates_to_key_manager(conn): + u, _ = utility(conn) + u._key_manager.is_master_key_valid.return_value = True + assert u.is_master_key_valid(ARN) is True + u._key_manager.is_master_key_valid.assert_called_once_with(ARN) diff --git a/tests/unit/test_key_manager.py b/tests/unit/test_key_manager.py index 0c660535e..87063f9ce 100644 --- a/tests/unit/test_key_manager.py +++ b/tests/unit/test_key_manager.py @@ -19,11 +19,13 @@ from concurrent.futures import ThreadPoolExecutor from contextlib import ExitStack, contextmanager from typing import Any, List, Optional, Tuple +from unittest.mock import MagicMock import boto3 import pytest from botocore.awsrequest import AWSResponse -from botocore.exceptions import ClientError, EndpointConnectionError +from botocore.exceptions import (ClientError, CredentialRetrievalError, + EndpointConnectionError) from botocore.stub import Stubber from aws_advanced_python_wrapper.encryption import key_manager as km_module @@ -33,11 +35,16 @@ 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.models import KeyMetadata, mask_arn -from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG from aws_advanced_python_wrapper.errors import (InvalidKeyMetadataError, KeyManagementError, OperationalError, UnauthorizedMasterKeyError) +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.utils.properties import Properties + +PG = PgDriverDialect(Properties()) +MYSQL = MySQLDriverDialect(Properties()) ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" OTHER_ARN = "arn:aws:kms:us-east-1:123456789012:key/ffffffff-12ab-34cd-56ef-1234567890ab" @@ -45,7 +52,7 @@ BLOB = b"kms-ciphertext-blob" EDK = base64.b64encode(BLOB).decode() # The caller's identity, as KMS names it when it denies a call. -ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/kiro-app-role/kiro-app-session" +ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/test-app-role/test-app-session" MASKED_ROLE_SESSION_ARN = "arn:aws:sts:***:***:***" @@ -93,9 +100,18 @@ def connection(self): yield self +class DriverError(Exception): + sqlstate = "42P01" + errno = 1146 + + def config(**overrides) -> EncryptionConfig: - values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), - key_management_retry_backoff_base_sec=0.1) + values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), kms_endpoint=None, + metadata_schema="encrypt", metadata_cache_enabled=True, metadata_cache_expiration_sec=3600.0, + metadata_cache_refresh_interval_sec=300.0, data_key_cache_enabled=True, + data_key_cache_max_size=1000, data_key_cache_expiration_sec=300.0, key_management_max_retries=3, + key_management_retry_backoff_base_sec=0.1, audit_logging_enabled=False, + return_unverified_data=False) values.update(overrides) return EncryptionConfig(**values) # type: ignore[arg-type] @@ -135,7 +151,7 @@ def no_filters(mocker): def manager(kms_client, db, cfg=None, cache=None, sleeps=None, sql=PG): sleeps = sleeps if sleeps is not None else [] - return KeyManager(kms_client, db, sql, cfg or config(), + return KeyManager(kms_client, db, sql, sql, cfg or config(), cache or DataKeyCache(10, 60, start_cleanup_thread=False), sleep=sleeps.append) @@ -146,13 +162,15 @@ def test_decrypts_with_key_id_and_caches(self, kms, db): {"CiphertextBlob": BLOB, "KeyId": ARN}) km = manager(client, db) first = km.decrypt_data_key(EDK, ARN) - assert isinstance(first, bytearray) and first == DATA_KEY + assert isinstance(first, bytearray) + assert first == DATA_KEY # Second call is served from the cache: no further stubbed response. first[:] = bytes(32) assert km.decrypt_data_key(EDK, ARN) == DATA_KEY def test_unlisted_master_key_is_refused_before_kms(self, kms, db): - client, _ = kms # no stubbed responses: any KMS call would fail + # No stubbed responses: any KMS call would fail. + client, _ = kms km = manager(client, db) with pytest.raises(UnauthorizedMasterKeyError) as err: km.decrypt_data_key(EDK, OTHER_ARN) @@ -160,7 +178,7 @@ def test_unlisted_master_key_is_refused_before_kms(self, kms, db): with pytest.raises(UnauthorizedMasterKeyError): km.decrypt_data_key(EDK, None) - def test_allow_list_is_checked_even_on_a_cache_hit(self, kms, db): + def test_allow_list_checked_on_cache_hit(self, kms, db): client, _ = kms cache = DataKeyCache(10, 60, start_cleanup_thread=False) cache.put(KeyManager.data_key_cache_key(EDK), DATA_KEY) @@ -218,7 +236,7 @@ def test_throttling_is_retried_with_backoff(self, kms, db): assert 0.1 <= sleeps[0] <= 0.125 assert 0.15 <= sleeps[1] <= 0.25 - def test_retries_stop_at_the_configured_maximum(self, kms, db): + def test_retries_stop_at_configured_maximum(self, kms, db): client, stubber = kms for _ in range(3): stubber.add_client_error("decrypt", "ServiceUnavailable", http_status_code=503) @@ -237,8 +255,11 @@ def test_429_and_network_errors_are_retryable(self): assert not KeyManager._is_retryable(bad) assert not KeyManager._is_retryable(ValueError("x")) + def test_not_processed_check_other_error_returns_false(self): + assert KeyManager._is_not_processed(ValueError("x")) is False + @pytest.mark.parametrize("status", [500, 502, 503, 504]) - def test_any_5xx_is_retryable_even_with_an_unlisted_code(self, status): + def test_5xx_with_unlisted_code_is_retryable(self, status): # A load balancer or VPC endpoint in front of KMS can answer with a # code outside RETRYABLE_ERROR_CODES. from botocore.exceptions import ClientError @@ -261,12 +282,13 @@ def test_kms_client_has_botocore_retries_disabled(self): # botocore's 60 s defaults would let one blackholed call take minutes. assert client.meta.config.connect_timeout == KeyManager.CONNECT_TIMEOUT_SEC assert client.meta.config.read_timeout == KeyManager.READ_TIMEOUT_SEC - assert client.meta.config.connect_timeout < 60 and client.meta.config.read_timeout < 60 + assert client.meta.config.connect_timeout < 60 + assert client.meta.config.read_timeout < 60 def _assert_names_no_identifier(text: str) -> None: - for identifier in (ARN, ARN.rpartition("/")[2], ROLE_SESSION_ARN, "123456789012", "kiro-app-role", - "kiro-app-session"): + for identifier in (ARN, ARN.rpartition("/")[2], ROLE_SESSION_ARN, "123456789012", "test-app-role", + "test-app-session"): assert identifier not in text @@ -275,46 +297,105 @@ def _key_manager_messages(caplog, level: int) -> List[str]: return [r.getMessage() for r in caplog.records if r.name == km_module.__name__ and r.levelno == level] +def _chained_errors(error: BaseException) -> List[BaseException]: + errors: List[BaseException] = [] + pending: List[Optional[BaseException]] = [error] + while pending: + current = pending.pop() + if current is None or any(current is seen for seen in errors): + continue + errors.append(current) + pending.extend((current.__cause__, current.__context__)) + return errors + + +def _wrapper_frame_locals(error: BaseException) -> List[Any]: + values: List[Any] = [] + tb = error.__traceback__ + while tb is not None: + if "aws_advanced_python_wrapper" in tb.tb_frame.f_code.co_filename: + values.extend(tb.tb_frame.f_locals.values()) + tb = tb.tb_next + return values + + +def _client_error(response: Any) -> ClientError: + return ClientError(response, "Decrypt") + + +def _failing_client(error: Exception) -> MagicMock: + client = MagicMock() + client.decrypt.side_effect = error + return client + + +# AWS KMS's own texts: they name the master key, and an access denial names +# the caller's role session. +KMS_TEXTS = [ + pytest.param("DisabledException", f"{ARN} is disabled.", id="disabled"), + pytest.param("KMSInvalidStateException", f"{ARN} is pending deletion.", id="pending-deletion"), + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on resource: {ARN} " + "with an explicit deny in a resource-based policy", id="explicit-deny"), + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on the resource " + "associated with this ciphertext because the resource does not exist in this Region, no " + "resource-based policies allow access, or a resource-based policy explicitly denies access", + id="wrong-region"), +] + + class TestQuotedKmsErrorsAreMasked: - # AWS KMS's own texts: they name the master key, and an access denial - # names the caller's role session. - @pytest.mark.parametrize("code, text", [ - pytest.param("DisabledException", f"{ARN} is disabled.", id="disabled"), - pytest.param("KMSInvalidStateException", f"{ARN} is pending deletion.", id="pending-deletion"), - pytest.param("AccessDeniedException", - f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on resource: {ARN} " - "with an explicit deny in a resource-based policy", id="explicit-deny"), - pytest.param("AccessDeniedException", - f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on the resource " - "associated with this ciphertext because the resource does not exist in this Region, no " - "resource-based policies allow access, or a resource-based policy explicitly denies access", - id="wrong-region"), - ]) - def test_decrypt_failure_masks_the_arns_kms_quotes(self, kms, db, code, text): + @pytest.mark.parametrize("code, text", KMS_TEXTS) + def test_kms_failure_chains_no_sdk_error(self, kms, db, code, text): client, stubber = kms stubber.add_client_error("decrypt", code, service_message=text, http_status_code=400) with pytest.raises(KeyManagementError) as err: manager(client, db).decrypt_data_key(EDK, ARN) - message = str(err.value) - assert message.startswith("[KeyManager] KMS DECRYPT_DATA_KEY failed after 1 attempt(s): ") - assert f"An error occurred ({code}) when calling the Decrypt operation: " in message - assert (mask_arn(ARN) in message) == (ARN in text) - assert (MASKED_ROLE_SESSION_ARN in message) == (ROLE_SESSION_ARN in text) - _assert_names_no_identifier(message) - # The SDK's error keeps KMS's full text, with its code and response. - assert isinstance(err.value.__cause__, ClientError) - assert text in str(err.value.__cause__) - - def test_decrypt_failure_without_an_arn_quotes_kms_unchanged(self, kms, db): - client, stubber = kms - stubber.add_client_error("decrypt", "NotFoundException", service_message="Invalid arn us-east-1", - http_status_code=400) + chain = _chained_errors(err.value) + assert chain == [err.value] + for error in chain: + for shown in (str(error), repr(error)): + _assert_names_no_identifier(shown) + assert text not in shown + assert not any(isinstance(value, BaseException) for value in _wrapper_frame_locals(err.value)) + + def test_kms_failure_masks_secret_pairs(self, db, caplog): + secret = "MARK-5e7c" + client = MagicMock() + client.decrypt.side_effect = [ + EndpointConnectionError(endpoint_url=f"https://kms.example.com/?token={secret}"), + CredentialRetrievalError(provider="custom-process", + error_msg=f"aws_secret_access_key={secret} password={secret} " + f"api_key='{secret}' user=postgres")] + with caplog.at_level(logging.DEBUG, logger=km_module.__name__): + with pytest.raises(KeyManagementError) as err: + manager(client, db).decrypt_data_key(EDK, ARN) + retries = [m for m in _key_manager_messages(caplog, logging.DEBUG) if "retrying in" in m] + assert len(retries) == 1 + assert "?token=***" in retries[0] + for shown in (str(err.value), repr(err.value), *map(str, err.value.args), *retries): + assert secret not in shown + assert "user=postgres" in str(err.value) + + @pytest.mark.parametrize("error, summary", [ + pytest.param(_client_error({"Error": {"Code": "AccessDeniedException", "Message": f"{ARN} denied"}, + "ResponseMetadata": {"HTTPStatusCode": 400}}), + "ClientError, error code AccessDeniedException, HTTP status 400", id="client-error"), + pytest.param(_client_error({"Error": {"Message": f"{ARN} denied"}, "ResponseMetadata": {"HTTPStatusCode": 403}}), + "ClientError, error code unknown, HTTP status 403", id="no-code"), + pytest.param(_client_error({"Error": {"Code": "Access\nDenied"}}), + "ClientError, error code Access?Denied, HTTP status unknown", id="no-status"), + pytest.param(ValueError("x" * 500), "ValueError: " + "x" * 197 + "...", id="other-error"), + pytest.param(ValueError(), "ValueError", id="no-text"), + ]) + def test_kms_failure_message_names_code_and_status(self, db, error, summary): with pytest.raises(KeyManagementError) as err: - manager(client, db).decrypt_data_key(EDK, ARN) - assert isinstance(err.value.__cause__, ClientError) - assert str(err.value) == ("[KeyManager] KMS DECRYPT_DATA_KEY failed after 1 attempt(s): " - f"{err.value.__cause__}") - assert str(err.value).endswith(": Invalid arn us-east-1") + manager(_failing_client(error), db).decrypt_data_key(EDK, ARN) + assert str(err.value) == f"[KeyManager] KMS DECRYPT_DATA_KEY failed after 1 attempt(s): {summary}" + assert err.value.operation == "DECRYPT_DATA_KEY" + assert err.value.__cause__ is None + assert err.value.__context__ is None # KeyUnavailableException's text names the key as DisabledException's does. # Throttling's text names none today; this one does, so the test doesn't @@ -323,7 +404,7 @@ def test_decrypt_failure_without_an_arn_quotes_kms_unchanged(self, kms, db): pytest.param("ThrottlingException", f"Rate exceeded for {ARN}.", 400, id="throttling"), pytest.param("KeyUnavailableException", f"{ARN} is unavailable.", 500, id="key-unavailable"), ]) - def test_retry_record_masks_the_arns_kms_quotes(self, kms, db, caplog, code, text, status): + def test_retry_record_names_code_and_status(self, kms, db, caplog, code, text, status): client, stubber = kms stubber.add_client_error("decrypt", code, service_message=text, http_status_code=status) stubber.add_response("decrypt", {"Plaintext": DATA_KEY}, {"CiphertextBlob": BLOB, "KeyId": ARN}) @@ -331,10 +412,11 @@ def test_retry_record_masks_the_arns_kms_quotes(self, kms, db, caplog, code, tex assert manager(client, db).decrypt_data_key(EDK, ARN) == DATA_KEY retries = [m for m in _key_manager_messages(caplog, logging.DEBUG) if "retrying in" in m] assert len(retries) == 1 - assert f"({code})" in retries[0] and mask_arn(ARN) in retries[0] + assert retries[0].endswith(f", error code {code}, HTTP status {status}") + assert text not in retries[0] _assert_names_no_identifier(retries[0]) - def test_validation_warning_masks_the_arns_kms_quotes(self, kms, db, caplog): + def test_master_key_validation_warning_quotes_no_kms_text(self, kms, db, caplog): client, stubber = kms text = (f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:DescribeKey on resource: {ARN} " "because no identity-based policy allows the kms:DescribeKey action") @@ -342,26 +424,27 @@ def test_validation_warning_masks_the_arns_kms_quotes(self, kms, db, caplog): with caplog.at_level(logging.WARNING, logger=km_module.__name__): assert manager(client, db).is_master_key_valid(ARN) is False warnings = _key_manager_messages(caplog, logging.WARNING) - assert len(warnings) == 1 - assert "(AccessDeniedException)" in warnings[0] and MASKED_ROLE_SESSION_ARN in warnings[0] - assert mask_arn(ARN) in warnings[0] - _assert_names_no_identifier(warnings[0]) + assert warnings == [f"[KeyManager] Could not validate master key {mask_arn(ARN)}: [KeyManager] KMS " + "DESCRIBE_MASTER_KEY failed after 1 attempt(s): ClientError, error code " + "AccessDeniedException, HTTP status 400"] class TestGenerateAndCreate: @pytest.mark.parametrize("algorithm, spec", [ (EncryptionAlgorithm.AES_256_GCM, "AES_256"), (EncryptionAlgorithm.AES_128_GCM, "AES_128")]) - def test_generate_data_key_sizes_the_key_for_the_algorithm(self, kms, db, algorithm, spec): + def test_generate_data_key_sized_for_algorithm(self, kms, db, algorithm, spec): client, stubber = kms key = DATA_KEY[:EncryptionAlgorithm.key_length(algorithm)] stubber.add_response("generate_data_key", {"Plaintext": key, "CiphertextBlob": BLOB}, {"KeyId": ARN, "KeySpec": spec}) generated = manager(client, db).generate_data_key(ARN, algorithm) - assert generated.plaintext == key and isinstance(generated.plaintext, bytearray) + assert generated.plaintext == key + assert isinstance(generated.plaintext, bytearray) assert base64.b64decode(generated.encrypted_data_key) == BLOB assert len(generated.hmac_key) == 32 assert generated.key_spec == spec - assert "bytearray" not in repr(generated) and str(BLOB) not in repr(generated) + assert "bytearray" not in repr(generated) + assert str(BLOB) not in repr(generated) def test_mis_sized_data_key_is_rejected_at_setup(self, kms, db): client, stubber = kms @@ -379,13 +462,14 @@ def test_mis_sized_data_key_is_wiped(self, kms, db, monkeypatch): {"KeyId": ARN, "KeySpec": "AES_128"}) with pytest.raises(KeyManagementError): manager(client, db).generate_data_key(ARN, EncryptionAlgorithm.AES_128_GCM) - assert len(wiped) == 1 and wiped[0] == bytearray(len(DATA_KEY)) + assert len(wiped) == 1 + assert wiped[0] == bytearray(len(DATA_KEY)) - def test_generate_is_gated_on_the_allow_list(self, kms, db): + def test_generate_gated_on_allow_list(self, kms, db): with pytest.raises(UnauthorizedMasterKeyError): manager(kms[0], db).generate_data_key(OTHER_ARN) - def test_create_master_key_is_not_retried_after_an_ambiguous_failure(self, kms, db): + def test_create_master_key_ambiguous_failure_not_retried(self, kms, db): # After a 5xx the key may already exist; retrying would create a second one. client, stubber = kms stubber.add_client_error("create_key", "KMSInternalException", http_status_code=500) @@ -394,7 +478,7 @@ def test_create_master_key_is_not_retried_after_an_ambiguous_failure(self, kms, manager(client, db, sleeps=sleeps).create_master_key("d") assert sleeps == [] - def test_create_master_key_is_not_retried_on_a_quota_error(self, kms, db): + def test_create_master_key_quota_error_not_retried(self, kms, db): # LimitExceededException on CreateKey is the key-count quota; retrying # only delays the same failure. client, stubber = kms @@ -404,7 +488,7 @@ def test_create_master_key_is_not_retried_on_a_quota_error(self, kms, db): manager(client, db, sleeps=sleeps).create_master_key("d") assert sleeps == [] - def test_create_master_key_retries_a_connection_that_was_never_made(self, kms, db): + def test_create_master_key_endpoint_connection_error_retried(self, kms, db): client, stubber = kms km = manager(client, db) calls = [] @@ -419,7 +503,7 @@ def create_key(**kwargs): assert km.create_master_key("d") == ARN assert len(calls) == 2 - def test_create_master_key_retries_a_connect_timeout(self, kms, db): + def test_create_master_key_connect_timeout_retried(self, kms, db): # ConnectTimeoutError does not derive from EndpointConnectionError, so # it needs its own guard. from botocore.exceptions import ConnectTimeoutError @@ -437,7 +521,7 @@ def create_key(**kwargs): assert km.create_master_key("d") == ARN assert len(calls) == 2 - def test_create_master_key_retries_a_429(self, kms, db): + def test_create_master_key_429_retried(self, kms, db): # A 429 means KMS did not act, whatever error code comes with it. client, stubber = kms stubber.add_client_error("create_key", "TooManyRequestsException", http_status_code=429) @@ -487,10 +571,13 @@ def test_store_on_postgres_uses_returning(self, kms, db): db.result = (["id"], [(42,)]) stored = manager(kms[0], db).store_key_metadata(self._key()) assert stored.id == 42 - assert stored.key_id and len(stored.key_id) == 36 # generated UUID + assert stored.key_id + assert len(stored.key_id) == 36 # generated UUID sql, params = db.executed[0] - assert sql.startswith("INSERT INTO encrypt.key_storage ") and sql.endswith(" RETURNING id") - assert params[4] == b"H" * 32 and params[5] == "AES_256" + assert sql.startswith("INSERT INTO encrypt.key_storage ") + assert sql.endswith(" RETURNING id") + assert params[4] == b"H" * 32 + assert params[5] == "AES_256" def test_store_on_mysql_uses_lastrowid_and_keeps_given_uuid(self, kms, db): db.lastrowid = 9 @@ -503,7 +590,7 @@ def test_unusable_metadata_is_refused(self, kms, db): manager(kms[0], db).store_key_metadata(self._key(encrypted_data_key=None)) assert db.executed == [] - def test_store_failure_does_not_leak_the_hmac_key(self, kms, db): + def test_store_failure_hides_hmac_key(self, kms, db): secret = b"SECRET-HMAC-" + b"x" * 20 db.error = RuntimeError(f"syntax error near '{secret!r}'") with pytest.raises(KeyManagementError) as err: @@ -513,7 +600,7 @@ def test_store_failure_does_not_leak_the_hmac_key(self, kms, db): assert err.value.__context__ is None assert "RuntimeError" in str(err.value) - def test_store_failure_reports_the_driver_error_codes(self, kms, db): + def test_store_failure_reports_driver_error_codes(self, kms, db): # SQLSTATE and errno carry no statement text, so they can be shown. class DriverError(Exception): sqlstate = "42P01" @@ -522,10 +609,12 @@ class DriverError(Exception): db.error = DriverError("relation key_storage does not exist: 'SECRET-HMAC'") with pytest.raises(KeyManagementError) as err: manager(kms[0], db).store_key_metadata(self._key()) - assert "DriverError" in str(err.value) and "sqlstate 42P01" in str(err.value) - assert "errno 1146" in str(err.value) and "SECRET" not in str(err.value) + assert "DriverError" in str(err.value) + assert "sqlstate 42P01" in str(err.value) + assert "errno 1146" in str(err.value) + assert "SECRET" not in str(err.value) - def test_store_on_postgres_reads_the_id_from_a_dict_row(self, kms, db): + def test_store_on_postgres_reads_id_from_dict_row(self, kms, db): class DictCursor(FakeCursor): def fetchone(self): return {"id": 42} @@ -539,7 +628,10 @@ def test_key_metadata_by_id(self, kms, db): "CREATED_AT", "LAST_USED_AT"], [(3, "u", "n", ARN, EDK, memoryview(b"hk"), "AES_256", None, None)]) km = manager(kms[0], db).key_metadata_by_id(3) - assert km is not None and km.id == 3 and km.hmac_key == b"hk" and km.master_key_arn == ARN + assert km is not None + assert km.id == 3 + assert km.hmac_key == b"hk" + assert km.master_key_arn == ARN assert "WHERE id OPERATOR(pg_catalog.=) %s" in db.executed[0][0] assert db.executed[0][1] == (3,) @@ -551,7 +643,7 @@ def test_key_metadata_by_id_failure(self, kms, db): # The plugin passes ids read from stored values, which may be four # bytes of legacy plaintext, so the message leaves the id out. db.error = RuntimeError("boom") - with pytest.raises(KeyManagementError, match="boom") as err: + with pytest.raises(KeyManagementError, match="RuntimeError") as err: manager(kms[0], db).key_metadata_by_id(1802201963) assert "1802201963" not in str(err.value) @@ -560,16 +652,31 @@ def test_touch_key_swallows_errors(self, kms, db): manager(kms[0], db).touch_key("u") assert "last_used_at = CURRENT_TIMESTAMP" in db.executed[0][0] + def test_touch_key_failure_record_masks_key_id(self, kms, db, caplog): + db.error = DriverError("UPDATE ... WHERE key_id = '1234abcd-12ab-34cd-56ef-1234567890ab'") + with caplog.at_level(logging.DEBUG, logger=km_module.__name__): + manager(kms[0], db).touch_key("1234abcd-12ab-34cd-56ef-1234567890ab") + assert _key_manager_messages(caplog, logging.DEBUG) == [ + "[KeyManager] Failed to update last_used_at for key 1234***90ab: DriverError, sqlstate 42P01, errno 1146"] + + def test_read_key_metadata_failure_chains_no_driver_error(self, kms, db): + db.error = DriverError("row bytes 'SECRET-ROW-BYTES'") + with pytest.raises(KeyManagementError) as err: + manager(kms[0], db).key_metadata_by_id(3) + assert str(err.value) == "[KeyManager] Failed to read a key_storage row: DriverError, sqlstate 42P01, errno 1146" + assert _chained_errors(err.value) == [err.value] + assert "SECRET" not in repr(err.value) + assert not any(isinstance(value, BaseException) for value in _wrapper_frame_locals(err.value)) -# ---- botocore log filters ---- B64_KEY = base64.b64encode(DATA_KEY).decode() # Distinctive fake credentials: easy to search for, and no test signs with the # ambient credential chain. -FAKE_KEY_ID = "KIROUNITFAKEKEYID0001" -FAKE_SECRET = "kiro-unit-fake-secret-key" -FAKE_TOKEN = "kiro-unit-fake-session-token" -UNREACHABLE = "http://127.0.0.1:9" # never contacted: the canned answer comes first +FAKE_KEY_ID = "TESTUNITFAKEKEYID0001" +FAKE_SECRET = "test-unit-fake-secret-key" +FAKE_TOKEN = "test-unit-fake-session-token" +# Never contacted: the canned answer comes first. +UNREACHABLE = "http://127.0.0.1:9" KMS_OPERATIONS = ["TrentService.GenerateDataKey", "TrentService.Decrypt"] @@ -617,7 +724,7 @@ def _call_kms(client) -> int: # A fresh manager and cache, so Decrypt reaches KMS instead of the cache. cache = DataKeyCache(10, 60, start_cleanup_thread=False) try: - km = KeyManager(client, FakeDb(), PG, config(), cache) + km = KeyManager(client, FakeDb(), PG, PG, config(), cache) km.generate_data_key(ARN) km.decrypt_data_key(EDK, ARN) finally: @@ -656,32 +763,48 @@ def _state(name: str): return lg.level, list(lg.handlers), lg.propagate, list(lg.filters) +def test_key_manager_with_own_client_drops_plaintext_record(caplog): + client = _session().client("kms", region_name="us-east-1") + _answer_kms(client) + with _debug_log(caplog) as records: + _run(client, on_thread=False) + assert _holding(records, B64_KEY) == [] + assert len(_records(records, "botocore.parsers", "Response headers: %r")) == 2 + + class TestBotocoreLogFilters: @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) - def test_botocore_logs_kms_secrets_at_debug(self, caplog, on_thread): + def test_botocore_logs_kms_secrets_at_debug(self, mocker, caplog, on_thread): # The canaries: if botocore changes one of these records, the filter - # rules need another look. + # rules need another look. The filters count as installed, so the + # KeyManager that makes the calls adds none. + mocker.patch.object(km_module, "_filters_installed", True) client = _session().client("kms", region_name="us-east-1") answered, signatures = _answer_kms(client) with _debug_log(caplog) as records: _run(client, on_thread) assert answered == KMS_OPERATIONS bodies = _records(records, "botocore.parsers", "Response body:\n%r") - assert len(bodies) == 2 and len(_holding(records, B64_KEY)) == 2 - assert all(isinstance(r.args, tuple) and isinstance(r.args[0], bytes) and b'"Plaintext"' in r.args[0] - for r in bodies) + assert len(bodies) == 2 + assert len(_holding(records, B64_KEY)) == 2 + assert all(isinstance(r.args, tuple) for r in bodies) + assert all(isinstance(r.args[0], bytes) for r in bodies) + assert all(b'"Plaintext"' in r.args[0] for r in bodies) sent = _records(records, "botocore.endpoint", "Sending http request: %s") canonical = _records(records, "botocore.auth", "CanonicalRequest:\n%s") - assert len(sent) == 2 and len(canonical) == 2 - assert all(FAKE_KEY_ID in r.getMessage() and FAKE_TOKEN in r.getMessage() for r in sent) + assert len(sent) == 2 + assert len(canonical) == 2 + assert all(FAKE_KEY_ID in r.getMessage() for r in sent) + assert all(FAKE_TOKEN in r.getMessage() for r in sent) assert all(FAKE_TOKEN in r.getMessage() for r in canonical) signed = _records(records, "botocore.auth", "Signature:\n%s") assert [r.getMessage() for r in signed] == [f"Signature:\n{s}" for s in signatures] - assert len(signatures) == 2 and all(len(s) == 64 for s in signatures) + assert len(signatures) == 2 + assert all(len(s) == 64 for s in signatures) @pytest.mark.parametrize("endpoint", [None, UNREACHABLE], ids=["kms", "endpoint"]) @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) - def test_create_kms_client_keeps_data_keys_out_of_the_log(self, caplog, on_thread, endpoint): + def test_create_kms_client_drops_data_keys_from_log(self, caplog, on_thread, endpoint): client = KeyManager.create_kms_client(_session(), config(kms_endpoint=endpoint)) answered, signatures = _answer_kms(client) with _debug_log(caplog) as records: @@ -691,11 +814,12 @@ def test_create_kms_client_keeps_data_keys_out_of_the_log(self, caplog, on_threa assert _holding(records, '"Plaintext"') == [] assert len(_records(records, "botocore.parsers", "Response headers: %r")) == 2 assert _records(records, "botocore.auth", "Signature:\n%s") == [] - assert len(signatures) == 2 and all(_holding(records, s) == [] for s in signatures) + assert len(signatures) == 2 + assert all(_holding(records, s) == [] for s in signatures) @pytest.mark.parametrize("endpoint", [None, UNREACHABLE], ids=["kms", "endpoint"]) @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) - def test_create_kms_client_keeps_request_credentials_out_of_the_log(self, caplog, on_thread, endpoint): + def test_create_kms_client_drops_request_credentials_from_log(self, caplog, on_thread, endpoint): client = KeyManager.create_kms_client(_session(), config(kms_endpoint=endpoint)) answered, signatures = _answer_kms(client) with _debug_log(caplog) as records: @@ -704,13 +828,15 @@ def test_create_kms_client_keeps_request_credentials_out_of_the_log(self, caplog for secret in (FAKE_KEY_ID, FAKE_SECRET, FAKE_TOKEN): assert _holding(records, secret) == [] assert _records(records, "botocore.auth", "Signature:\n%s") == [] - assert len(signatures) == 2 and all(_holding(records, s) == [] for s in signatures) + assert len(signatures) == 2 + assert all(_holding(records, s) == [] for s in signatures) # The unsigned record names the KMS target but carries no credential, # so it stays: the rule needs both parts. making = _records(records, "botocore.endpoint", "Making request for %s with params: %s") - assert len(making) == 2 and all("TrentService." in r.getMessage() for r in making) + assert len(making) == 2 + assert all("TrentService." in r.getMessage() for r in making) - def test_other_services_lose_only_the_signature_record(self, caplog): + def test_other_services_lose_only_signature_record(self, caplog): session = _session() sts = session.client("sts", region_name="us-east-1") body = (b'' @@ -718,7 +844,8 @@ def test_other_services_lose_only_the_signature_record(self, caplog): sts.meta.events.register( "before-send.sts.GetCallerIdentity", lambda request, **kwargs: AWSResponse(request.url, 200, {"Content-Type": "text/xml"}, _Body(body))) - sts.get_caller_identity() # warm up, so both captures see the same records + # Warm up, so both captures see the same records. + sts.get_caller_identity() def capture() -> List[logging.LogRecord]: caplog.clear() @@ -738,9 +865,12 @@ def capture() -> List[logging.LogRecord]: assert [(r.name, r.msg) for r in with_filters] == expected sent = _records(with_filters, "botocore.endpoint", "Sending http request: %s") canonical = _records(with_filters, "botocore.auth", "CanonicalRequest:\n%s") - assert len(sent) == 1 and FAKE_KEY_ID in sent[0].getMessage() and FAKE_TOKEN in sent[0].getMessage() + assert len(sent) == 1 + assert FAKE_KEY_ID in sent[0].getMessage() + assert FAKE_TOKEN in sent[0].getMessage() assert "Signature=" in sent[0].getMessage() - assert len(canonical) == 1 and FAKE_TOKEN in canonical[0].getMessage() + assert len(canonical) == 1 + assert FAKE_TOKEN in canonical[0].getMessage() def test_filters_are_installed_once_on_their_loggers_only(self): # Pin a level and propagate flag first, so a change the install makes @@ -796,7 +926,7 @@ def add_filter(lg: logging.Logger, flt: logging.Filter) -> None: b = threading.Thread(target=km_module._install_botocore_filters, daemon=True) a.start() try: - assert entered.wait(5), "thread A never reached addFilter" + assert entered.wait(5) b.start() b.join(0.2) finally: @@ -827,7 +957,7 @@ class TestBotocoreLogFilterRules: ("Response headers: %r", None, True), ("%(body)s", ({"body": b'{"Plaintext": "x"}'},), True), ]) - def test_plaintext_filter_drops_only_bytes_carrying_a_plaintext_field(self, msg, args, kept): + def test_plaintext_filter_drops_only_bytes_with_plaintext_field(self, msg, args, kept): assert km_module._NoKmsPlaintext().filter(_record("botocore.parsers", msg, args)) is kept @pytest.mark.parametrize("msg, args, kept", [ diff --git a/tests/unit/test_kms_encryption_plugin.py b/tests/unit/test_kms_encryption_plugin.py new file mode 100644 index 000000000..a0fc24252 --- /dev/null +++ b/tests/unit/test_kms_encryption_plugin.py @@ -0,0 +1,3336 @@ +# 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 enum +import gc +import io +import ipaddress +import logging +import os +import re +import threading +import uuid +from dataclasses import replace +from datetime import timedelta +from decimal import Decimal +from pathlib import Path +from types import SimpleNamespace +from typing import (Any, Callable, Dict, Iterator, List, NamedTuple, Optional, + Sequence, Set, Tuple) +from unittest.mock import MagicMock + +import boto3 +import mysql.connector +import psycopg +import pytest +from botocore.exceptions import ProfileNotFound +from mysql.connector import cursor as mysql_cursor +from psycopg import rows as pg_rows +from psycopg import sql as pg_sql +from psycopg.types.json import Json, Jsonb + +from aws_advanced_python_wrapper import errors +from aws_advanced_python_wrapper.aurora_connection_tracker_plugin import \ + AuroraConnectionTrackerPluginFactory +from aws_advanced_python_wrapper.aws_credentials_manager import \ + AwsCredentialsManager +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 import key_manager as km_module +from aws_advanced_python_wrapper.encryption import \ + kms_encryption_plugin as plugin_module +from aws_advanced_python_wrapper.encryption.connection_source import \ + PluginConnectionSource +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService +from aws_advanced_python_wrapper.encryption.key_manager import KeyManager +from aws_advanced_python_wrapper.encryption.kms_encryption_plugin import \ + KmsEncryptionPluginFactory +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata) +from aws_advanced_python_wrapper.encryption.sql_analyzer import AnalysisGap +from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + EncryptionFailedError, + IntegrityCheckError, + InvalidAlgorithmError, + InvalidKeyMetadataError, + MetadataError) +from aws_advanced_python_wrapper.failover_plugin import FailoverPluginFactory +from aws_advanced_python_wrapper.failover_v2_plugin import \ + FailoverV2PluginFactory +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory +from aws_advanced_python_wrapper.plugin_service import (PluginCallContext, + PluginManager, + PluginServiceImpl) +from aws_advanced_python_wrapper.sqlalchemy_driver_dialect import \ + SqlAlchemyDriverDialect +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, + AwsWrapperCursor) + +try: + from mysql.connector.cursor_cext import (CMySQLCursorPrepared, + CMySQLCursorPreparedDict) + + CMYSQL_ENABLED = True +except ImportError: + CMYSQL_ENABLED = False + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" +DATA_KEY = bytes(range(32)) +HMAC_KEY = bytes(range(100, 132)) +PROPS = {"encryption_kms_region": "us-east-1", "encryption_allowed_master_key_arns": ARN} +DIALECTS = {"pg": DriverDialectCodes.PSYCOPG, "mysql": DriverDialectCodes.MYSQL_CONNECTOR_PYTHON} +KEY_ROW = KeyMetadata(id=7, key_id="k7", master_key_arn=ARN, encrypted_data_key="ZWRr", hmac_key=HMAC_KEY) +OLD_HMAC = bytes(range(140, 172)) +SSN = ColumnEncryptionConfig("users", "ssn", key_id=7, key_metadata=KEY_ROW) +DOB = ColumnEncryptionConfig("users", "dob", key_id=8, key_metadata=replace(KEY_ROW, id=8)) +ARCHIVE_SSN = ColumnEncryptionConfig("archive", "ssn", key_id=7, key_metadata=KEY_ROW) +INSERT = "INSERT INTO users (ssn) VALUES (%s)" +SELECT = "SELECT ssn FROM users WHERE id = %s" +# Captured before any test patches them. +REAL_GET_SESSION = AwsCredentialsManager.get_session +REAL_CREATE_KMS_CLIENT = KeyManager.create_kms_client + + +def marker() -> str: + return f"test-plain-{uuid.uuid4()}" + + +def payload(value: Any, key_id: int = 7) -> bytes: + sealed = EncryptionService.encrypt(value, DATA_KEY, HMAC_KEY, key_id=key_id) + assert sealed is not None + return sealed + + +def _clean(err: BaseException, *secrets: str) -> None: + """No secret in the error's text, repr or args, and nothing chained.""" + text = f"{err} {err!r} {err.args!r}" + for key in (DATA_KEY, HMAC_KEY): + assert key.hex() not in text + assert base64.b64encode(key).decode() not in text + assert repr(key) not in text + for secret in secrets: + assert secret not in text + assert err.__cause__ is None + assert err.__context__ is None + + +class FakeMetadata: + """Answers lookups from fixed configurations, comparing names as the real manager does.""" + + def __init__(self, sql: Any, configs: Sequence[ColumnEncryptionConfig], env: Any): + self._sql = sql + self._configs = {(sql.metadata_key(c.table_name), sql.metadata_key(c.column_name)): c for c in configs} + self._env = env + self.starts = 0 + self.closes = 0 + + def start(self) -> None: + self.starts += 1 + self._env.on_start(self) + + def close(self) -> None: + self.closes += 1 + + def column_config(self, table: Optional[str], column: Optional[str]) -> Optional[ColumnEncryptionConfig]: + if table is None or column is None: + return None + return self._configs.get((self._sql.metadata_key(table), self._sql.metadata_key(column))) + + def table_configs(self, table: Optional[str]) -> List[ColumnEncryptionConfig]: + key = None if table is None else self._sql.metadata_key(table) + return [c for (t, _), c in self._configs.items() if t == key] + + def has_encrypted_columns(self) -> bool: + return bool(self._configs) + + +class FakeDriverCursor: + """Records what the driver received and returns the rows it is given. ``sets`` holds the later result sets, each + as its description and rows, for ``nextset()``.""" + + def __init__(self) -> None: + self.calls: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + self.rows: List[Any] = [] + self.description: Optional[List[Tuple[str]]] = None + self.sets: List[Tuple[List[Tuple[str]], List[Any]]] = [] + self.arraysize = 1 + self.fetches = 0 + self.connection: Any = None # psycopg's Composable.as_string reads it + + def execute(self, *args: Any, **kwargs: Any) -> FakeDriverCursor: + self.calls.append(("execute", args, kwargs)) + return self # as psycopg's does + + def executemany(self, *args: Any, **kwargs: Any) -> None: + self.calls.append(("executemany", args, kwargs)) + + def copy(self, *args: Any, **kwargs: Any) -> Any: + self.calls.append(("copy", args, kwargs)) + return MagicMock() + + def stream(self, *args: Any, **kwargs: Any) -> Iterator[Any]: + self.calls.append(("stream", args, kwargs)) + return iter(self.rows) + + def results(self) -> Iterator[Any]: + self.calls.append(("results", (), {})) + return iter([self]) + + def set_result(self, index: int) -> FakeDriverCursor: + self.calls.append(("set_result", (index,), {})) + return self + + def fetchsets(self) -> Iterator[Any]: + self.calls.append(("fetchsets", (), {})) + return iter([self.rows]) + + def stored_results(self) -> Iterator[Any]: + self.calls.append(("stored_results", (), {})) + return iter([self]) + + def fetchone(self) -> Any: + self.fetches += 1 + return self.rows.pop(0) if self.rows else None + + def fetchmany(self, size: int = 0) -> List[Any]: + self.fetches += 1 + # The wrapper passes 0 by default, which the drivers read as arraysize. + size = size or self.arraysize + out, self.rows = self.rows[:size], self.rows[size:] + return out + + def fetchall(self) -> List[Any]: + self.fetches += 1 + out, self.rows = self.rows, [] + return out + + def __iter__(self) -> Iterator[Any]: + # One row at a time, as the drivers do, so a broken loop resumes where it stopped. + while self.rows: + yield self.rows.pop(0) + + def nextset(self) -> Optional[bool]: + if not self.sets: + # As psycopg's at the last set, which stays on that set and keeps its unread rows. + return None + self.description, self.rows = self.sets.pop(0) + return True + + +def _posing_as(cls: type, base: type = FakeDriverCursor) -> Any: + """A subclass of the fake ``base`` whose instances pass ``isinstance`` checks for the driver class ``cls`` and + still record their calls.""" + return type(f"Fake{cls.__name__}", (base,), {"__class__": property(lambda self: cls)}) + + +@pytest.fixture +def env(mocker): + """The plugin's collaborators, patched where the plugin looks them up: no database, no KMS, no thread.""" + env = SimpleNamespace(configs=[SSN, DOB], built=[], on_start=lambda metadata: None) + + def build(source, driver_dialect, sql, config): + env.built.append(FakeMetadata(sql, env.configs, env)) + return env.built[-1] + + env.metadata = mocker.patch.object(plugin_module, "MetadataManager", side_effect=build) + env.keys = mocker.patch.object(plugin_module, "KeyManager") + env.keys.return_value.decrypt_data_key.side_effect = lambda edk, arn: bytearray(DATA_KEY) + env.keys.return_value.key_metadata_by_id.return_value = None + env.cache = mocker.patch.object(plugin_module, "DataKeyCache") + mocker.patch.object(plugin_module, "PluginConnectionSource") + env.session = mocker.patch.object(AwsCredentialsManager, "get_session") + return env + + +def _service(mock: Any) -> Any: + """A mock plugin service whose ``current_call_context`` is the real one: the calling thread's call context.""" + # A mock's type is its own. + type(mock).current_call_context = PluginServiceImpl.current_call_context + return mock + + +def _driver_dialect(code: str, conn: Any) -> Any: + """The real driver dialect for ``code``, whose connection lookup returns ``conn`` and whose ``execute`` runs the call + on the calling thread.""" + dialect: Any = (MySQLDriverDialect if code == DriverDialectCodes.MYSQL_CONNECTOR_PYTHON else PgDriverDialect)(Properties()) + dialect.get_connection_from_obj = MagicMock(return_value=conn) + dialect.execute = MagicMock(side_effect=lambda name, func, *args, **kwargs: func()) + return dialect + + +def make_plugin(mocker, dialect: str = DriverDialectCodes.PSYCOPG, **props: Any) -> Tuple[Any, Any]: + service = _service(mocker.MagicMock()) + service.driver_dialect = _driver_dialect(dialect, MagicMock()) + service.current_host_info = HostInfo("localhost", 5432) + return KmsEncryptionPluginFactory.get_instance(service, Properties({**PROPS, **props})), service + + +@pytest.fixture +def plugin(mocker, env): + return make_plugin(mocker)[0] + + +def cursor(plugin: Any, raw: Optional[FakeDriverCursor] = None) -> Tuple[AwsWrapperCursor, FakeDriverCursor]: + """A wrapper cursor over a fake driver cursor, whose calls run through ``plugin``, then DefaultPlugin.""" + driver = raw if raw is not None else FakeDriverCursor() + return _cursor_over([plugin], driver), driver + + +def call(cur: Any, method: str, *args: Any, **kwargs: Any) -> Any: + """Call a method of the wrapper cursor that ``cursor(plugin)`` returned, so it runs through the plugin chain.""" + return getattr(cur, method)(*args, **kwargs) + + +def plugin_records(caplog: Any) -> List[logging.LogRecord]: + return [r for r in caplog.records if r.name == plugin_module.__name__] + + +def own_records(caplog: Any) -> List[logging.LogRecord]: + """The records the test's own thread logged: a thread an earlier test left running can log while the root logger + is at DEBUG.""" + return [r for r in caplog.records if r.thread == threading.get_ident()] + + +def _carrying(caplog: Any, secret: str) -> List[logging.LogRecord]: + """The records holding the secret anywhere a log reporter could show it: the message, any attribute (args, + exc_info, stack_info, extras), or an exception along the record's whole __cause__/__context__ chain.""" + found = [] + for record in caplog.records: + chain: List[BaseException] = [] + todo: List[Optional[BaseException]] = [record.exc_info[1] if record.exc_info else None] + while todo: + err = todo.pop() + if err is not None and not any(err is e for e in chain): + chain.append(err) + todo += [err.__cause__, err.__context__] + texts = [record.getMessage(), repr(vars(record)), *(f"{e!r} {e.args!r} {e}" for e in chain)] + if any(secret in text for text in texts): + found.append(record) + return found + + +def _undecodable(secret: str) -> bytes: + # 0xff starts no UTF-8 sequence. + return b"INSERT INTO users (ssn) VALUES ('" + secret.encode() + b"\xff')" + + +def _plant_controls(secret: str) -> None: + """One record per channel _carrying reads, each holding the secret where only that channel finds it: a wrapper + message, std-logging args the message leaves out, and a decode error on an exception's context.""" + plugin_module.logger.debug("KmsEncryptionPlugin.NotAnalysed", secret) + logging.getLogger("aws_advanced_python_wrapper.execute_time_plugin").debug("control", {"sql": secret}) + try: + try: + _undecodable(secret).decode("utf-8") + except UnicodeDecodeError: + # The decode error is left on __context__ only. + raise LookupError("control") + except LookupError: + logging.getLogger("aws_advanced_python_wrapper.plugin_service").debug("control", exc_info=True) + + +def spy_crypto(mocker: Any, plugin: Any) -> List[Tuple[str, Any, Any, int, str]]: + """Run the plugin's EncryptionService calls, recording for each the key buffers, the data key's length and the + algorithm it got.""" + seen: List[Tuple[str, Any, Any, int, str]] = [] + + def spy(name: str) -> Callable[..., Any]: + def run(value: Any, data_key: Any, hmac_key: Any, algorithm: str, **kwargs: Any) -> Any: + seen.append((name, data_key, hmac_key, len(data_key), algorithm)) + return getattr(EncryptionService, name)(value, data_key, hmac_key, algorithm, **kwargs) + return run + + mocker.patch.object(plugin, "_crypto", SimpleNamespace( + encrypt=spy("encrypt"), decrypt=spy("decrypt"), wipe=EncryptionService.wipe, + key_id_from_payload=EncryptionService.key_id_from_payload)) + return seen + + +def _connection(plugins: str, raw: FakeDriverCursor, dialect: str = DriverDialectCodes.PSYCOPG) -> AwsWrapperConnection: + """A wrapper connection over a fake driver whose cursors are ``raw``, running the real plugin chain that + ``plugins`` builds.""" + driver_conn, service = MagicMock(), _service(MagicMock()) + driver_conn.cursor.return_value = raw + service.current_connection = driver_conn + service.current_host_info = HostInfo("localhost", 5432) + service.driver_dialect = _driver_dialect(dialect, driver_conn) + # The real dialect's network-bound methods, read before the plugins are built: the plugins that subscribe through + # them (aurora_connection_tracker, failover, host monitoring) then handle the statement, as on a real connection. + service.network_bound_methods = (MySQLDriverDialect if dialect == DriverDialectCodes.MYSQL_CONNECTOR_PYTHON + else PgDriverDialect)(Properties()).network_bound_methods + manager = PluginManager(MagicMock(plugin_service=service), Properties({**PROPS, "plugins": plugins}), MagicMock()) + conn = object.__new__(AwsWrapperConnection) + conn._plugin_service, conn._plugin_manager = service, manager + return conn + + +def _chain(plugins: str, dialect: str = DriverDialectCodes.PSYCOPG) -> Tuple[AwsWrapperConnection, FakeDriverCursor]: + raw = FakeDriverCursor() + return _connection(plugins, raw, dialect), raw + + +def _cursor_over(plugins: List[Any], raw: FakeDriverCursor) -> AwsWrapperCursor: + """A wrapper cursor over ``raw`` whose calls run through ``plugins`` in that order, then DefaultPlugin.""" + conn = _connection("", raw) + # Before the chain is first built. + conn._plugin_manager._plugins[:0] = plugins + return conn.cursor() + + +class _Recorder(Plugin): + """Records the arguments each ``execute`` and ``executemany`` reaches it with, and runs the rest ``runs`` times.""" + + def __init__(self, runs: int = 1) -> None: + self.seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + self._runs = runs + + @property + def subscribed_methods(self) -> Set[str]: + return {"Cursor.execute", "Cursor.executemany"} + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + self.seen.append((method_name, args, kwargs)) + result = None + for _ in range(self._runs): + result = execute_func() + return result + + +class _RecorderFactory(PluginFactory): + @staticmethod + def get_instance(plugin_service: Any, props: Properties) -> Plugin: + return _Recorder() + + +class _LateRecorderFactory(_RecorderFactory): + """The same plugin at another weight, since a weight belongs to the factory type.""" + + +@pytest.fixture +def recorders() -> Iterator[None]: + """Plugin codes ``recorder_385`` and ``recorder_395``, weighted on either side of ``kms_encryption`` (390).""" + factories = {"recorder_385": (_RecorderFactory, 385), "recorder_395": (_LateRecorderFactory, 395)} + for code, (factory, weight) in factories.items(): + PluginManager.register_plugin(code, factory, weight) + try: + yield + finally: + for code, (factory, _) in factories.items(): + PluginManager.PLUGIN_FACTORIES.pop(code, None) + PluginManager.PLUGIN_FACTORY_WEIGHTS.pop(factory, None) + + +class _OpaqueSql: + """SQL given as an object the plugin doesn't analyze (not str, bytes or a psycopg Composable).""" + + def __init__(self, text: str) -> None: + self.text = text + + def __str__(self) -> str: + return self.text + + __repr__ = __str__ + + +class _Row(NamedTuple): + id: int + ssn: Any + + +@pytest.mark.parametrize("context", ["none", "foreign"]) +@pytest.mark.parametrize("method, sql, params", [ + ("execute", INSERT, lambda m: (m,)), + ("executemany", INSERT, lambda m: [(m,)]), + # Nothing to encrypt, but the iterator becomes a list, so the plugin still changes the arguments. + ("executemany", "INSERT INTO audit (note) VALUES (%s)", lambda m: ((m,) for _ in range(1))), +], ids=["execute", "executemany", "iterator"]) +def test_changed_arguments_without_own_context_refused(mocker, env, context, method, sql, params): + plugin, service = make_plugin(mocker) + secret = marker() + handed = params(secret) + # The context of another statement with equal values: what an enclosing statement's context would hold. + foreign = PluginCallContext((sql, params(secret)), {}) + foreign_args = foreign.args + if context == "foreign": + type(service).current_call_context = mocker.PropertyMock(return_value=foreign) + driver = mocker.MagicMock() + with pytest.raises(EncryptionFailedError) as info: + plugin.execute(FakeDriverCursor(), f"Cursor.{method}", driver, sql, handed) + assert str(info.value) == Messages.get("KmsEncryptionPlugin.ArgumentsChanged") + assert driver.call_count == 0 + assert foreign.args is foreign_args + assert foreign.kwargs == {} + _clean(info.value, secret) + + +@pytest.mark.parametrize("form", ["keywords", "shorter", "extra-keyword"]) +def test_a_context_holding_other_arguments_is_refused(mocker, env, form): + # keywords: the call passes only keyword arguments, and the context's params are equal but not the same object. + # shorter: the context holds the same first argument but not the rest. + # extra-keyword: the context holds the same positional arguments and one keyword more. + plugin, service = make_plugin(mocker) + secret = marker() + handed = (secret,) + if form == "keywords": + args, kwargs = (), {"query": INSERT, "params": handed} + foreign = PluginCallContext((), {"query": INSERT, "params": (secret,)}) + elif form == "shorter": + args, kwargs = (INSERT, handed), {} + foreign = PluginCallContext((INSERT,), {}) + else: + args, kwargs = (INSERT, handed), {} + foreign = PluginCallContext((INSERT, handed), {"params": handed}) + type(service).current_call_context = mocker.PropertyMock(return_value=foreign) + driver = mocker.MagicMock() + with pytest.raises(EncryptionFailedError) as info: + plugin.execute(FakeDriverCursor(), "Cursor.execute", driver, *args, **kwargs) + assert driver.call_count == 0 + _clean(info.value, secret) + + +def test_call_context_holds_copies_before_chain_runs(mocker, env): + plugin, service = make_plugin(mocker) + params = (marker(),) + context = PluginCallContext((), {"query": INSERT, "params": params}) + type(service).current_call_context = mocker.PropertyMock(return_value=context) + seen: List[Any] = [] + plugin.execute(FakeDriverCursor(), "Cursor.execute", lambda: seen.append(dict(context.kwargs)), **context.kwargs) + assert seen[0]["query"] is INSERT + assert EncryptionService.decrypt(seen[0]["params"][0], DATA_KEY, HMAC_KEY) == params[0] + + +def test_chain_order_payloads_after_plaintext_before(env, recorders): + conn, raw = _chain("recorder_395,kms_encryption,recorder_385") + before, after = [p for p in conn._plugin_manager._plugins if isinstance(p, _Recorder)] + one, many = (marker(),), [(marker(),), (marker(),)] + snapshot = list(many) + cur = conn.cursor() + cur.execute(INSERT, one) + cur.executemany(INSERT, many) + assert before.seen == [("Cursor.execute", (INSERT, one), {}), ("Cursor.executemany", (INSERT, many), {})] + assert before.seen[0][1][1] is one + assert before.seen[1][1][1] is many + assert many == snapshot + sent = [args for _, args, _ in raw.calls] + assert [args for _, args, _ in after.seen] == sent + assert all(a[1] is b[1] for (_, a, _), b in zip(after.seen, sent)) + assert type(sent[0][1]) is tuple + assert sent[0][1] is not one + assert [EncryptionService.decrypt(sent[0][1][0], DATA_KEY, HMAC_KEY)] == list(one) + assert [EncryptionService.decrypt(r[0], DATA_KEY, HMAC_KEY) for r in sent[1][1]] == [r[0] for r in many] + + +def test_chain_rerun_sends_one_payload_each_time(plugin): + raw = FakeDriverCursor() + retrier = _Recorder(runs=2) + cur = _cursor_over([retrier, plugin], raw) + secret = marker() + cur.execute(INSERT, (secret,)) + sent = [args[1][0] for _, args, _ in raw.calls] + assert len(sent) == 2 + assert sent[0] != sent[1] + assert retrier.seen == [("Cursor.execute", (INSERT, (secret,)), {})] + assert [EncryptionService.decrypt(value, DATA_KEY, HMAC_KEY) for value in sent] == [secret, secret] + + +def test_read_state_per_driver_cursor(plugin): + raw = FakeDriverCursor() + # Nothing to replace, so no context needed. + plugin.execute(raw, "Cursor.execute", lambda: None, SELECT, (1,)) + assert list(plugin._results.keys()) == [raw] + del raw + gc.collect() + assert len(plugin._results) == 0 + + +@pytest.mark.parametrize("method", ["fetchone", "fetchmany", "fetchall"]) +def test_each_value_decrypts_once_on_fetch(plugin, env, method): + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(secret),), (None,)] + result = call(cur, method) + assert (result if method == "fetchone" else result[0]) == (secret,) + assert env.keys.return_value.decrypt_data_key.call_count == 1 + + +def test_iteration_and_chained_reads_decrypt(plugin): + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + assert list(cur) == [(secret,)] + raw.rows = [(payload(secret),)] + assert cur.execute(SELECT, (1,)).fetchone() == (secret,) + + +@pytest.mark.parametrize("late", [False, True], ids=["described", "late-description"]) +def test_loop_after_new_statement_on_cursor_raises(plugin, late): + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", SELECT, (1,)) + raw.description = None if late else [("ssn",)] + raw.rows = [(payload(secret),), (payload(secret),)] + loop = iter(cur) + raw.description = [("ssn",)] + assert next(loop) == (secret,) + call(cur, "execute", "SELECT name FROM users") + with pytest.raises(MetadataError) as info: + next(loop) + assert str(info.value) == Messages.get("KmsEncryptionPlugin.LoopOutlivedStatement") + + +def test_plain_loop_after_encrypted_statement_raises(plugin): + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", "SELECT name FROM users") + raw.description, raw.rows = [("name",)], [("Ann",), (payload(secret),)] + loop = iter(cur) + assert next(loop) == ("Ann",) + call(cur, "execute", SELECT, (1,)) + with pytest.raises(MetadataError) as info: + next(loop) + assert str(info.value) == Messages.get("KmsEncryptionPlugin.LoopOutlivedStatement") + + +class OwnIteratorDriverCursor(FakeDriverCursor): + """As psycopg 3.3's cursor, which is its own iterator, so the wrapper's ``next()`` takes the row from the driver's + ``next()``. ``FakeDriverCursor`` isn't (mysql-connector's shape, and psycopg's before 3.3), so the wrapper's + ``next()`` takes the row from ``fetchone``.""" + + def __iter__(self) -> Iterator[Any]: + return self + + def __next__(self) -> Any: + if not self.rows: + raise StopIteration + return self.rows.pop(0) + + +_NEXT_SHAPES = pytest.mark.parametrize("driver", [OwnIteratorDriverCursor, FakeDriverCursor], + ids=["own-iterator", "fetchone"]) + + +@_NEXT_SHAPES +def test_next_decrypts(plugin, driver): + cur, raw = cursor(plugin, driver()) + first, second = marker(), marker() + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(first),), (payload(second),)] + assert next(cur) == (first,) + assert next(cur) == (second,) + # The plugin returns the end of the rows unchanged. + with pytest.raises(StopIteration): + next(cur) + + +@_NEXT_SHAPES +def test_next_non_payload_refused(plugin, driver): + cur, raw = cursor(plugin, driver()) + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(10 ** 6,)] + with pytest.raises(IntegrityCheckError) as info: + next(cur) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NotAPayload", "users.ssn") + + +class PipelinedDriverCursor(FakeDriverCursor): + """As psycopg's cursor in pipeline mode: ``execute`` returns before the result, and ``arriving`` holds the + description and rows that the first fetch, or the first row of a loop, receives.""" + + def __init__(self) -> None: + super().__init__() + self.arriving: Optional[Tuple[Optional[List[Tuple[str]]], List[Any]]] = None + + def _receive(self) -> None: + if self.arriving is not None: + self.description, self.rows = self.arriving + self.arriving = None + + def fetchone(self) -> Any: + self._receive() + return super().fetchone() + + def fetchmany(self, size: int = 0) -> List[Any]: + self._receive() + return super().fetchmany(size) + + def fetchall(self) -> List[Any]: + self._receive() + return super().fetchall() + + def __iter__(self) -> Iterator[Any]: + # At the loop's first next(), not at iter(): psycopg's __next__ is what syncs the pipeline. + self._receive() + yield from super().__iter__() + + +def _read_rows(cur: Any, read: str, count: int) -> List[Any]: + if read == "fetchone": + rows = [call(cur, "fetchone") for _ in range(count)] + assert call(cur, "fetchone") is None + return rows + if read == "fetchmany": + return call(cur, "fetchmany", count + 1) + return call(cur, "fetchall") if read == "fetchall" else list(cur) + + +@pytest.mark.parametrize("read", ["fetchone", "fetchmany", "fetchall", "iterate"]) +def test_columns_known_only_at_fetch_are_decrypted(plugin, env, read): + raw = PipelinedDriverCursor() + cur, _ = cursor(plugin, raw) + secret = marker() + # Leaves the description None, as pipeline mode does. + call(cur, "execute", SELECT, (1,)) + raw.arriving = ([("ssn",)], [(payload(secret),), (None,)]) + assert _read_rows(cur, read, 2) == [(secret,), (None,)] + assert env.keys.return_value.decrypt_data_key.call_count == 1 + + +@pytest.mark.parametrize("read", ["fetchone", "fetchmany", "fetchall", "iterate"]) +def test_plain_columns_known_only_at_fetch_are_returned_as_given(plugin, env, read): + raw = PipelinedDriverCursor() + cur, _ = cursor(plugin, raw) + rows = [(marker(),), (None,)] + # A table with encrypted columns, none of them read. + call(cur, "execute", "SELECT name FROM users WHERE id = %s", (1,)) + raw.arriving = ([("name",)], list(rows)) + read_back = _read_rows(cur, read, 2) + assert read_back == rows + assert all(got is given for got, given in zip(read_back, rows)) + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +@pytest.mark.parametrize("read", ["fetchone", "fetchmany", "fetchall", "iterate"]) +def test_rows_without_description_refused(plugin, read): + raw = PipelinedDriverCursor() + cur, _ = cursor(plugin, raw) + secret = marker() + call(cur, "execute", SELECT, (1,)) + raw.arriving = (None, [(payload(secret),)]) + with pytest.raises(MetadataError) as info: + _read_rows(cur, read, 1) + assert str(info.value) == Messages.get("KmsEncryptionPlugin.NoResultDescription") + _clean(info.value, secret) + + +@pytest.mark.parametrize("read", ["fetchone", "fetchmany", "fetchall", "iterate"]) +def test_unsupported_row_factory_late_description_refused(plugin, read): + raw = _posing_as(psycopg.Cursor, PipelinedDriverCursor)() + raw.row_factory = pg_rows.class_row(dict) + cur, _ = cursor(plugin, raw) + secret = marker() + call(cur, "execute", SELECT, (1,)) + raw.arriving = ([("ssn",)], [(payload(secret),)]) + with pytest.raises(MetadataError) as info: + _read_rows(cur, read, 1) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.RowFactory", raw.row_factory) + _clean(info.value, secret) + + +@pytest.mark.parametrize("read", ["fetchmany", "fetchall"]) +def test_empty_result_without_description_returns_no_rows(plugin, read): + raw = PipelinedDriverCursor() + cur, _ = cursor(plugin, raw) + call(cur, "execute", SELECT, (1,)) + # No rows to decrypt, so a missing description is nothing to refuse. + raw.arriving = (None, []) + assert _read_rows(cur, read, 0) == [] + + +def test_round_trip_real_chain(env): + conn, raw = _chain("kms_encryption") + secret = marker() + cur = conn.cursor() + cur.execute(INSERT, (secret,)) + stored = raw.calls[0][1][1][0] + assert isinstance(stored, bytes) + assert len(stored) >= 65 + raw.description = [("ssn",)] + cur.execute(SELECT, (1,)) + raw.rows = [(stored,)] + assert cur.fetchall() == [(secret,)] + raw.rows = [(stored,)] + assert [row for row in cur] == [(secret,)] + + +@pytest.mark.parametrize("sql", ["UPDATE users SET dob = %(v)s, ssn = %(v)s WHERE id = %(id)s", + "UPDATE users SET dob = %(v)s WHERE ssn = %(v)s"]) +def test_repeated_named_placeholder_uses_first_key(plugin, sql): + cur, raw = cursor(plugin) + params = {"v": marker(), "id": 1} + snapshot = dict(params) + call(cur, "execute", sql, params) + sent = raw.calls[0][1][1] + assert params == snapshot + assert sent is not params + assert type(sent) is dict + assert EncryptionService.key_id_from_payload(sent["v"]) == DOB.key_id + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("method, sql", [("execute", "INSERT INTO users (ssn, name) VALUES (%(v)s, %(v)s)"), + ("execute", "INSERT INTO users (name, ssn) VALUES (%(v)s, %(v)s)"), + ("execute", "UPDATE users SET ssn = %(v)s WHERE name = %(v)s"), + ("execute", "SELECT id FROM users WHERE ssn = %(v)s OR name = %(v)s"), + # A use with no column at all. + ("execute", "SELECT ssn FROM users WHERE ssn = %(v)s LIMIT %(v)s"), + ("executemany", "INSERT INTO users (ssn, name) VALUES (%(v)s, %(v)s)")], + ids=["insert-encrypted-first", "insert-plain-first", "update", "select", "limit", "insert-many"]) +def test_named_placeholder_shared_with_plain_use_refused(mocker, env, dialect, method, sql): + # One mapping entry can't hold both the payload for ssn and the plaintext for the other use. + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + sets = [{"v": marker()}, {"v": marker()}] + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, method, sql, sets if method == "executemany" else sets[0]) + assert raw.calls == [] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + assert (info.value.table_name, info.value.column_name) == ("users", "ssn") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.SharedParameter", "v", "users.ssn") + _clean(info.value, sets[0]["v"], sets[1]["v"]) + + +@pytest.mark.parametrize("sql_by_name", [False, True], ids=["params", "query-and-params"]) +def test_keyword_params_are_encrypted(plugin, sql_by_name): + cur, raw = cursor(plugin) + secret = marker() + params = (secret,) + if sql_by_name: + call(cur, "execute", query=INSERT, params=params) + else: + call(cur, "execute", INSERT, params=params) + sent = raw.calls[0][2]["params"] + assert params == (secret,) + assert isinstance(sent, tuple) + assert EncryptionService.decrypt(sent[0], DATA_KEY, HMAC_KEY) == secret + + +def test_null_write_without_key_passes(plugin, env): + cur, raw = cursor(plugin) + call(cur, "execute", INSERT, (None,)) + assert raw.calls[0][1][1] == (None,) + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +def test_missing_value_left_to_driver(plugin): + cur, raw = cursor(plugin) + call(cur, "execute", "INSERT INTO users (name, ssn) VALUES (%s, %s)", ("test-name",)) + # The driver raises its own error for the missing value. + assert raw.calls[0][1][1] == ("test-name",) + + +def test_kms_encryption_sorts_between_tracker_and_failover(mocker): + manager = PluginManager(mocker.MagicMock(), Properties(plugins=""), mocker.MagicMock()) + factories = manager.create_plugin_factories_from_list( + ["failover_v2", "failover", "kms_encryption", "aurora_connection_tracker"]) + assert [type(f) for f in factories] == [AuroraConnectionTrackerPluginFactory, KmsEncryptionPluginFactory, + FailoverPluginFactory, FailoverV2PluginFactory] + + +def test_subscribed_methods(plugin): + assert plugin.subscribed_methods == {m.method_name for m in ( + DbApiMethod.CURSOR_EXECUTE, DbApiMethod.CURSOR_EXECUTEMANY, DbApiMethod.CURSOR_FETCHONE, + DbApiMethod.CURSOR_FETCHMANY, DbApiMethod.CURSOR_FETCHALL, DbApiMethod.CURSOR_ITER, DbApiMethod.CURSOR_NEXT, + DbApiMethod.CURSOR_NEXTSET, DbApiMethod.CURSOR_COPY, DbApiMethod.CURSOR_STREAM, DbApiMethod.CURSOR_RESULTS, + DbApiMethod.CURSOR_SET_RESULT, DbApiMethod.CURSOR_FETCHSETS, DbApiMethod.CURSOR_STORED_RESULTS, + DbApiMethod.CURSOR_CALLPROC)} + + +def test_release_resources_closes_metadata_and_cache(mocker, plugin, env): + # Before any build: nothing to close. + make_plugin(mocker)[0].release_resources() + cur, _ = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + # As a read of a rotated-out key leaves it. + plugin._old_keys[9] = replace(KEY_ROW, id=9) + plugin.release_resources() + assert env.built[0].closes == 1 + assert env.cache.return_value.close.call_count == 1 + assert plugin._old_keys == {} + assert env.keys.create_kms_client.return_value.close.call_count == 1 + # Close() and __exit__ both release; the components' close() is idempotent. + plugin.release_resources() + secret = marker() + with pytest.raises(MetadataError) as info: + call(cur, "execute", INSERT, (secret,)) + assert str(info.value) == Messages.get("KmsEncryptionPlugin.Closed") + _clean(info.value, secret) + assert env.metadata.call_count == 1 + assert env.cache.call_count == 1 # nothing is built again + + +@pytest.mark.parametrize("failing", ["metadata", "cache", "kms"]) +def test_each_release_step_runs_when_another_fails(mocker, plugin, env, caplog, failing): + # Named as the real cache's and KMS client's types are, so the warning shows which component failed. + env.cache.return_value = type("DataKeyCache", (MagicMock,), {})() + env.keys.create_kms_client.return_value = type("KMS", (MagicMock,), {})() + cur, _ = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + # As a read of a rotated-out key leaves it. + plugin._old_keys[9] = replace(KEY_ROW, id=9) + secret = marker() + components = {"metadata": env.built[0], "cache": env.cache.return_value, "kms": env.keys.create_kms_client.return_value} + closes = [mocker.patch.object(c, "close", side_effect=RuntimeError(secret) if name == failing else None) + for name, c in components.items()] + with caplog.at_level(logging.DEBUG): + plugin.release_resources() + assert [c.call_count for c in closes] == [1, 1, 1] + assert plugin._old_keys == {} + expected = Messages.get_formatted("KmsEncryptionPlugin.ReleaseFailed", type(components[failing]).__name__, "RuntimeError") + assert [(r.levelno, r.getMessage()) for r in plugin_records(caplog)] == [(logging.WARNING, expected)] + assert _carrying(caplog, secret) == [] + # Close() and __exit__ both release. + plugin.release_resources() + + +def test_release_interrupt_propagates(mocker, plugin, env, caplog): + # Only an Exception from a release step is logged and passed over: a KeyboardInterrupt stops the close and reaches + # the application. + cur, _ = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + mocker.patch.object(env.built[0], "close", side_effect=KeyboardInterrupt) + with caplog.at_level(logging.DEBUG), pytest.raises(KeyboardInterrupt): + plugin.release_resources() + assert plugin_records(caplog) == [] + + +def test_close_during_first_build_releases_build(plugin, env): + # Another thread's close, while start() loads. + env.on_start = lambda metadata: plugin.release_resources() + cur, raw = cursor(plugin) + secret = marker() + with pytest.raises(MetadataError) as info: + call(cur, "execute", INSERT, (secret,)) + assert str(info.value) == Messages.get("KmsEncryptionPlugin.Closed") + _clean(info.value, secret) + assert env.built[0].closes == 1 + assert env.cache.return_value.close.call_count == 1 + assert env.keys.create_kms_client.return_value.close.call_count == 1 + assert raw.calls == [] + + +def test_result_after_close_no_metadata_lookup(mocker, plugin, env): + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + plugin.release_resources() + lookups = [mocker.spy(env.built[0], "column_config"), mocker.spy(env.built[0], "table_configs")] + with pytest.raises(MetadataError) as info: + call(cur, "fetchone") + assert str(info.value) == Messages.get("KmsEncryptionPlugin.Closed") + _clean(info.value, secret) + assert [s.call_count for s in lookups] == [0, 0] + assert raw.fetches == 0 + + +def _rotated_rows(mocker, env, count: int) -> Tuple[Any, AwsWrapperCursor, FakeDriverCursor, str]: + """A plugin whose result holds ``count`` rows under a rotated-out key, so decoding one reads that key's row.""" + old_id = 1802201963 + env.keys.return_value.key_metadata_by_id.return_value = replace( + KEY_ROW, id=old_id, key_id="k-old", encrypted_data_key="b2xk", hmac_key=OLD_HMAC) + plugin, _ = make_plugin(mocker) + secret = marker() + cur, raw = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + raw.description = [("ssn",)] + raw.rows = [(EncryptionService.encrypt(secret, DATA_KEY, OLD_HMAC, key_id=old_id),) for _ in range(count)] + return plugin, cur, raw, secret + + +def _assert_refused_after_close(info: Any, env: Any, plugin: Any, secret: str, counts: Tuple[int, int]) -> None: + keys = env.keys.return_value + assert str(info.value) == Messages.get("KmsEncryptionPlugin.Closed") + _clean(info.value, secret) + # No key row, no KMS call. + assert (keys.key_metadata_by_id.call_count, keys.decrypt_data_key.call_count) == counts + # The close dropped the rotated-out key row, and nothing put it back. + assert plugin._old_keys == {} + + +@pytest.mark.parametrize("fetch", ["fetchone", "fetchall"]) +def test_a_decoder_built_before_close_refuses_after_it(mocker, env, fetch): + plugin, cur, raw, secret = _rotated_rows(mocker, env, 2) + # Builds the result's decoder, which reads the rotated-out key row. + assert call(cur, "fetchone") == (secret,) + plugin.release_resources() + keys = env.keys.return_value + counts, fetches = (keys.key_metadata_by_id.call_count, keys.decrypt_data_key.call_count), raw.fetches + with pytest.raises(MetadataError) as info: + call(cur, fetch) + _assert_refused_after_close(info, env, plugin, secret, counts) + # Refused before the driver reads a row. + assert raw.fetches == fetches + + +def test_a_loop_begun_before_close_refuses_after_it(mocker, env): + plugin, cur, raw, secret = _rotated_rows(mocker, env, 2) + rows = iter(cur) + assert next(rows) == (secret,) + plugin.release_resources() + keys = env.keys.return_value + counts = (keys.key_metadata_by_id.call_count, keys.decrypt_data_key.call_count) + with pytest.raises(MetadataError) as info: + next(rows) + _assert_refused_after_close(info, env, plugin, secret, counts) + + +def test_close_during_rotated_key_lookup_keeps_nothing(mocker, env): + plugin, cur, raw, secret = _rotated_rows(mocker, env, 1) + keys = env.keys.return_value + row = keys.key_metadata_by_id.return_value + + # Another thread closes the connection while this one reads the key row. + def closed_mid_lookup(key_id): + plugin.release_resources() + return row + + keys.key_metadata_by_id.side_effect = closed_mid_lookup + with pytest.raises(MetadataError) as info: + call(cur, "fetchone") + _assert_refused_after_close(info, env, plugin, secret, (1, 0)) + + +def test_a_result_without_encrypted_columns_still_reads_after_close(plugin, env): + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT id FROM users WHERE id = %s", (1,)) + raw.description, raw.rows = [("id",)], [(1,), (2,)] + # Finds no encrypted column, so the result keeps no decoder. + assert call(cur, "fetchone") == (1,) + plugin.release_resources() + # Looks nothing up, so the close doesn't refuse it. + assert call(cur, "fetchall") == [(2,)] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +def test_close_sets_flag_first(plugin, env): + outcome: List[Any] = [] + + # Entered by release_resources() after it sets the flag and before it reads the components. + class Probe: + def __enter__(self) -> None: + try: + outcome.append(plugin._components()) + except MetadataError as e: + outcome.append(e) + + def __exit__(self, *exc: Any) -> None: + return None + + plugin._state_lock = Probe() + plugin.release_resources() # before any build + assert len(outcome) == 1 + assert isinstance(outcome[0], MetadataError) + assert str(outcome[0]) == Messages.get("KmsEncryptionPlugin.Closed") + assert env.metadata.call_count == 0 + + +def test_build_waiter_sees_close(plugin, env): + built = object() + + # While this thread waited, another one built the components and a close released them. + class Contended: + def __enter__(self) -> None: + plugin._metadata = built + plugin._closed = True + + def __exit__(self, *exc: Any) -> None: + return None + + plugin._lock = Contended() + with pytest.raises(MetadataError) as info: + plugin._components() + assert str(info.value) == Messages.get("KmsEncryptionPlugin.Closed") + assert env.metadata.call_count == 0 + + +ERROR_BASES = [ + (errors.EncryptionPluginError, (errors.AwsWrapperError,)), + (errors.EncryptionError, (errors.EncryptionPluginError, errors.OperationalError)), + (errors.IntegrityCheckError, (errors.IntegrityError, errors.EncryptionError)), + (errors.DecryptionError, (errors.EncryptionError,)), + (errors.EncryptionFailedError, (errors.EncryptionError,)), + (errors.InvalidKeyError, (errors.EncryptionError,)), + (errors.InvalidAlgorithmError, (errors.EncryptionError,)), + (errors.TypeConversionError, (errors.EncryptionError,)), + (errors.EncryptionConfigError, (errors.EncryptionPluginError, errors.InterfaceError)), + (errors.KeyManagementError, (errors.EncryptionPluginError, errors.OperationalError)), + (errors.UnauthorizedMasterKeyError, (errors.KeyManagementError,)), + (errors.InvalidKeyMetadataError, (errors.KeyManagementError,)), + (errors.MetadataError, (errors.EncryptionPluginError, errors.OperationalError)), +] + + +@pytest.mark.parametrize("cls, bases", ERROR_BASES, ids=[c.__name__ for c, _ in ERROR_BASES]) +def test_encryption_error_classes(cls, bases): + assert cls.__bases__ == bases + assert cls.__module__ == "aws_advanced_python_wrapper" + + +def test_every_plugin_message_key_is_used_and_exists(): + module = Path(plugin_module.__file__) + used = set(re.findall(r'"(KmsEncryptionPlugin\.\w+)"', module.read_text())) + resource = module.parents[1] / "resources" / "aws_advanced_python_wrapper_messages.properties" + defined = set(re.findall(r"^(KmsEncryptionPlugin\.\w+)=", resource.read_text(), re.M)) + assert used == defined == {f"KmsEncryptionPlugin.{k}" for k in ( + "AnnotationNotEncrypted", "ArgumentsChanged", "AuditNotWritten", "CallprocRefused", "Closed", "CopyNotAnalysed", + "CopyParameters", "CopyRefused", "CopyUnread", "CteShadowsTable", "ExecutableComment", "HiddenPlaceholder", + "LoopOutlivedStatement", "MetadataNotLoaded", "NoExactForm", "NoResultDescription", "NotAnalysed", + "NotAnalysedRefused", "NotAPayload", "PassedThrough", "ReleaseFailed", "ResultMethodNotSupported", "RowFactory", + "SharedParameter", "UnboundWrite", "UnknownColumnTable", "UnknownKey", "UnmappedParameters", "UnplacedColumn", "UnsafeComparison", + "UnsupportedAlgorithm", "UnsupportedDriver", "UnusableColumn")} + + +def test_factory_and_build_install_no_log_filter(mocker, env): + loggers = [logging.getLogger(n) for n in ("", "botocore", "botocore.parsers", "botocore.endpoint", "botocore.auth")] + before = [list(lg.filters) for lg in loggers] + plugin, _ = make_plugin(mocker) + cur, _ = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + assert [list(lg.filters) for lg in loggers] == before + + +def test_dialect_captured_at_get_instance(mocker, env): + plugin, service = make_plugin(mocker) + # As under the internal pool after connect. + service.driver_dialect = mocker.MagicMock(dialect_code="generic") + cur, raw = cursor(plugin) + call(cur, "execute", INSERT, (marker(),)) + assert len(raw.calls[0][1][1][0]) >= 65 + + +@pytest.mark.parametrize("driver", ["generic", "sqlalchemy"]) +def test_unsupported_driver_refused_at_plugin_start(mocker, env, driver): + service = _service(mocker.MagicMock()) + service.driver_dialect = DriverDialect(Properties()) if driver == "generic" else \ + SqlAlchemyDriverDialect(PgDriverDialect(Properties()), Properties()) + service.current_host_info = HostInfo("localhost", 5432) + with pytest.raises(EncryptionConfigError) as info: + KmsEncryptionPluginFactory.get_instance(service, Properties(PROPS)) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnsupportedDriver", + service.driver_dialect.driver_name) + assert env.metadata.call_count == 0 + + +def test_nothing_read_at_connect_build_once_under_lock(mocker, env): + plugin, service = make_plugin(mocker) + assert (env.metadata.call_count, env.cache.call_count, env.session.call_count) == (0, 0, 0) + held: List[bool] = [] + env.on_start = lambda metadata: held.append(plugin._lock.locked()) + cur, _ = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + call(cur, "execute", SELECT, (1,)) + assert held == [True] + assert env.metadata.call_count == 1 + assert env.cache.call_count == 1 + # The KMS client comes from create_kms_client, which installs the botocore filters. + env.session.assert_called_once_with(service.current_host_info, plugin._props, "us-east-1") + env.keys.create_kms_client.assert_called_once_with(env.session.return_value, plugin._config) + assert env.keys.call_args.args[0] is env.keys.create_kms_client.return_value + + +class _SpyLock: + """A lock that reports each thread arriving at it, so the test needs no sleeps.""" + + def __init__(self) -> None: + self._lock = threading.Lock() + self.arrivals = threading.Semaphore(0) + self.held = False + + def __enter__(self) -> _SpyLock: + self.arrivals.release() + self._lock.acquire() + self.held = True + return self + + def __exit__(self, *exc: Any) -> None: + self.held = False + self._lock.release() + + +class _Guarded: + """Forwards to a container, recording each use of it and each use made while ``lock`` is not held.""" + + def __init__(self, inner: Any, lock: _SpyLock) -> None: + self._inner, self._spy = inner, lock + self.uses: List[str] = [] + self.unlocked: List[str] = [] + + def _use(self, what: str) -> None: + self.uses.append(what) + if not self._spy.held: + self.unlocked.append(what) + + def __getattr__(self, name: str) -> Any: + self._use(name) + return getattr(self._inner, name) + + def __contains__(self, key: Any) -> bool: + self._use("in") + return key in self._inner + + def __len__(self) -> int: + self._use("len") + return len(self._inner) + + def __getitem__(self, key: Any) -> Any: + self._use("getitem") + return self._inner[key] + + def __setitem__(self, key: Any, value: Any) -> None: + self._use("setitem") + self._inner[key] = value + + def __delitem__(self, key: Any) -> None: + self._use("delitem") + del self._inner[key] + + +def test_read_state_under_state_lock(mocker, env): + old = replace(KEY_ROW, id=9, key_id="k9", hmac_key=OLD_HMAC) + env.keys.return_value.key_metadata_by_id.return_value = old + plugin, _ = make_plugin(mocker, DriverDialectCodes.MYSQL_CONNECTOR_PYTHON, encryption_fail_on_unmapped_parameter=False) + spy = _SpyLock() + # Set directly: the plugin is this test's own, and mocker would probe the guards. + plugin._state_lock = spy + guards = {name: _Guarded(getattr(plugin, name), spy) for name in ("_results", "_old_keys", "_warned")} + for name, guard in guards.items(): + setattr(plugin, name, guard) + cur, raw = cursor(plugin) + secret = marker() + # A gap write (clears the cursor's state, records a warning), a read of a value under a rotated-out key, then a + # nextset() past a multi-statement string's first set (forgets the cursor's state). + call(cur, "execute", "UPDATE users u JOIN accounts a ON a.id = u.id SET ssn = %s WHERE a.id = %s", (marker(), 1)) + call(cur, "execute", SELECT, (1,)) + raw.description = [("ssn",)] + raw.rows = [(EncryptionService.encrypt(secret, DATA_KEY, OLD_HMAC, key_id=old.id),)] + assert call(cur, "fetchall") == [(secret,)] + call(cur, "execute", "SELECT ssn FROM users; SELECT name FROM users") + raw.sets = [([("name",)], [])] + assert call(cur, "nextset") is True + plugin.release_resources() + assert {name: bool(guard.uses) for name, guard in guards.items()} == dict.fromkeys(guards, True) + assert {name: guard.unlocked for name, guard in guards.items()} == dict.fromkeys(guards, []) + + +def test_concurrent_first_statements_build_once(mocker, env): + plugin, _ = make_plugin(mocker) + entered, release = threading.Event(), threading.Event() + env.on_start = lambda metadata: (entered.set(), release.wait(5)) + spy = _SpyLock() + mocker.patch.object(plugin, "_lock", spy) + results: Dict[int, Any] = {} + first = threading.Thread(target=lambda: results.__setitem__(1, plugin._components())) + first.start() + assert entered.wait(5) + # The first thread is inside start(), holding the lock. + assert spy.arrivals.acquire(timeout=5) + second = threading.Thread(target=lambda: results.__setitem__(2, plugin._components())) + second.start() + # The second thread waits for the lock. + assert spy.arrivals.acquire(timeout=5) + release.set() + first.join(5) + second.join(5) + assert not first.is_alive() + assert not second.is_alive() + assert env.metadata.call_count == 1 + assert results[1] is results[2] + + +def test_failed_build_raises_and_is_retried(mocker, env): + plugin, _ = make_plugin(mocker) + boom = MetadataError("test: metadata unreadable") + failures = [boom] + + def fail_once(metadata): + if failures: + raise failures.pop() + + env.on_start = fail_once + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "execute", INSERT, (marker(),)) + assert info.value is boom + assert boom.__cause__ is None + assert boom.__context__ is None + assert raw.calls == [] + # The cache, whose constructor starts a thread, comes last. + assert env.cache.call_count == 0 + call(cur, "execute", INSERT, (marker(),)) + assert env.metadata.call_count == 2 + assert [m.starts for m in env.built] == [1, 1] + assert plugin._metadata is env.built[1] + assert len(raw.calls) == 1 + + +def test_cache_start_failure_stops_metadata_refresh(mocker, env): + plugin, _ = make_plugin(mocker) + boom = RuntimeError("can't start new thread") + env.cache.side_effect = [boom, mocker.DEFAULT] + cur, raw = cursor(plugin) + with pytest.raises(RuntimeError) as info: + call(cur, "execute", SELECT, (1,)) + assert info.value is boom + assert env.built[0].closes == 1 + assert raw.calls == [] + call(cur, "execute", SELECT, (1,)) + assert env.metadata.call_count == 2 + assert len(raw.calls) == 1 + + +@pytest.fixture +def aws_env(monkeypatch, tmp_path): + """No ambient AWS profile or credentials, and no credential lookup that leaves the process.""" + config = tmp_path / "config" + config.write_text("[profile other]\nregion = us-east-1\n") + for name in ("AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", + "AWS_ROLE_ARN", "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", + "AWS_CONTAINER_CREDENTIALS_FULL_URI"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("AWS_CONFIG_FILE", str(config)) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", os.devnull) + monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") + AwsCredentialsManager.release_resources() + yield + AwsCredentialsManager.release_resources() + + +@pytest.mark.parametrize("arm", ["profile", "endpoint"]) +def test_setup_failure_is_raised_unwrapped(mocker, env, aws_env, arm): + mocker.patch.object(km_module, "_install_botocore_filters") + env.keys.create_kms_client.side_effect = REAL_CREATE_KMS_CLIENT + if arm == "profile": + env.session.side_effect = REAL_GET_SESSION + plugin, _ = make_plugin(mocker, aws_profile="test-no-such-profile") + expected: type = ProfileNotFound + else: + env.session.return_value = boto3.Session(region_name="us-east-1", aws_access_key_id="test-fake", + aws_secret_access_key="test-fake") + plugin, _ = make_plugin(mocker, encryption_kms_endpoint="not a url") + expected = ValueError + cur, raw = cursor(plugin) + # Raised again at the next statement, which builds again. + for _ in range(2): + with pytest.raises(expected) as info: + call(cur, "execute", INSERT, (marker(),)) + assert type(info.value) is expected + assert raw.calls == [] + assert env.metadata.call_count == 0 + + +_METADATA_COLUMNS = ("table_name", "column_name", "encryption_algorithm", "key_id", "created_at", "updated_at", "ks_id", + "ks_key_id", "ks_name", "ks_master_key_arn", "ks_encrypted_data_key", "ks_hmac_key", "ks_key_spec", + "ks_created_at", "ks_last_used_at") + + +def _metadata_row(config: ColumnEncryptionConfig) -> Tuple[Any, ...]: + key = config.key_metadata + assert key is not None + return (config.table_name, config.column_name, config.algorithm, config.key_id, None, None, key.id, key.key_id, + "test-key", key.master_key_arn, key.encrypted_data_key, key.hmac_key, "AES_256", None, None) + + +class _MetadataCursor(FakeDriverCursor): + """Answers the metadata manager's joined query with the rows of SSN and DOB that have the table and column it + binds: every row for a full load, the table's for ``table_configs``, the column's for ``column_config``.""" + + configs: Sequence[ColumnEncryptionConfig] = (SSN, DOB) + + def execute(self, *args: Any, **kwargs: Any) -> _MetadataCursor: + super().execute(*args, **kwargs) + bound = tuple(args[1]) + self.description = [(name,) for name in _METADATA_COLUMNS] + self.rows = [row for row in map(_metadata_row, self.configs) if row[:len(bound)] == bound] + return self + + def close(self) -> None: + pass + + +class _MetadataConnection: + """One of the plugin's own connections: its cursors answer the metadata queries, and it records its close.""" + + def __init__(self) -> None: + self.closed = False + + def cursor(self) -> _MetadataCursor: + return _MetadataCursor() + + def close(self) -> None: + self.closed = True + + +def _cache_off_plugin(mocker: Any) -> Tuple[Any, List[_MetadataConnection]]: + """A plugin with the metadata cache off, over the real MetadataManager and PluginConnectionSource in place of the + env fixture's patches, and the connections its service's ``force_connect`` opened, in order.""" + mocker.patch.object(plugin_module, "MetadataManager", MetadataManager) + mocker.patch.object(plugin_module, "PluginConnectionSource", PluginConnectionSource) + plugin, service = make_plugin(mocker, encryption_metadata_cache_enabled=False) + opened: List[_MetadataConnection] = [] + + def connect(*args: Any) -> _MetadataConnection: + opened.append(_MetadataConnection()) + return opened[-1] + + service.props = {} + service.force_connect.side_effect = connect + # So a close reaches the fake. + service.driver_dialect.execute.side_effect = lambda name, func, *args, **kwargs: func() + service.driver_dialect.set_autocommit = MagicMock() + return plugin, opened + + +@pytest.mark.parametrize("sql, params, names", [ + pytest.param(INSERT, ("v",), None, id="insert"), + pytest.param("INSERT INTO users (ssn, dob) VALUES (%s, %s)", ("v", "w"), None, id="insert-two-columns"), + pytest.param(SELECT, (1,), ["ssn"], id="select-and-fetch"), + pytest.param("SELECT u.ssn, n.note FROM users u JOIN notes n ON n.user_id = u.id WHERE u.id = %s", (1,), + ["ssn", "note"], id="join"), +]) +def test_cache_off_statement_opens_one_metadata_connection(mocker, env, sql, params, names): + plugin, opened = _cache_off_plugin(mocker) + closed_at_driver: List[List[bool]] = [] + + class _Checking(FakeDriverCursor): + def execute(self, *args: Any, **kwargs: Any) -> FakeDriverCursor: + closed_at_driver.append([c.closed for c in opened]) + return super().execute(*args, **kwargs) + + cur, raw = cursor(plugin, _Checking()) + call(cur, "execute", sql, params) + # No plugin connection is open while the driver runs the statement. + assert closed_at_driver == [[True]] + # Every lookup of the statement on one connection, closed by now. + assert [c.closed for c in opened] == [True] + if names is not None: + secret = marker() + raw.description = [(n,) for n in names] + raw.rows = [tuple(payload(secret) if n == "ssn" else f"test-{n}" for n in names)] + assert call(cur, "fetchall") == [tuple(secret if n == "ssn" else f"test-{n}" for n in names)] + assert len(opened) == 1 # the fetch opens none + + +@pytest.mark.parametrize("sql, names", [ + pytest.param(SELECT, ["ssn"], id="known-column"), + pytest.param("SELECT * FROM users WHERE id = %s", ["id", "ssn"], id="by-name"), +]) +def test_a_fetch_looks_nothing_up(mocker, env, sql, names): + plugin, _ = _cache_off_plugin(mocker) + cur, raw = cursor(plugin) + call(cur, "execute", sql, (1,)) + lookups = [mocker.spy(plugin._metadata, "column_config"), mocker.spy(plugin._metadata, "table_configs")] + secret = marker() + raw.description = [(n,) for n in names] + raw.rows = [tuple(payload(secret) if n == "ssn" else 1 for n in names)] + assert call(cur, "fetchall") == [tuple(secret if n == "ssn" else 1 for n in names)] + assert [s.call_count for s in lookups] == [0, 0] + + +def test_cache_on_statement_enters_no_scope(plugin, env): + cur, raw = cursor(plugin) + call(cur, "execute", INSERT, (marker(),)) + call(cur, "execute", SELECT, (1,)) + secret = marker() + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + assert call(cur, "fetchall") == [(secret,)] + # The INSERT's value went to the driver encrypted. + assert len(raw.calls[0][1][1][0]) >= 65 + # The snapshot answers every lookup. + plugin_module.PluginConnectionSource.return_value.statement.assert_not_called() + + +@pytest.mark.parametrize("kind", ["list", "generator"]) +def test_empty_batch_untouched(plugin, env, caplog, kind): + cur, raw = cursor(plugin) + rows: Any = [] if kind == "list" else (r for r in ()) + plugin._results[raw] = "stale" + with caplog.at_level(logging.DEBUG): + assert call(cur, "executemany", INSERT, rows) is None + assert raw.calls == [("executemany", (INSERT, []), {})] + assert kind == "generator" or raw.calls[0][1][1] is rows + assert raw not in plugin._results + assert env.metadata.call_count == 0 + assert own_records(caplog) == [] + + +def test_empty_batch_of_unanalyzed_sql_logs_nothing(plugin, env, caplog): + cur, raw = cursor(plugin) + sql, rows = _OpaqueSql(INSERT), [] + with caplog.at_level(logging.DEBUG): + call(cur, "executemany", sql, rows) + assert raw.calls == [("executemany", (sql, []), {})] + assert env.metadata.call_count == 0 + assert own_records(caplog) == [] + + +@pytest.mark.parametrize("kind", ["list", "generator"]) +def test_non_empty_batch_is_encrypted_row_by_row(plugin, kind): + cur, raw = cursor(plugin) + rows = [(marker(),), (marker(),)] + snapshot = list(rows) + call(cur, "executemany", INSERT, rows if kind == "list" else (r for r in rows)) + sent = raw.calls[0][1][1] + assert rows == snapshot + assert [EncryptionService.decrypt(r[0], DATA_KEY, HMAC_KEY) for r in sent] == [r[0] for r in rows] + + +def test_executemany_with_none_passes_none(plugin): + cur, raw = cursor(plugin) + call(cur, "executemany", "INSERT INTO audit (note) VALUES (%s)", None) + assert raw.calls == [("executemany", ("INSERT INTO audit (note) VALUES (%s)", None), {})] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("args, kwargs", [((), {}), ((None,), {}), (((),), {}), (([],), {}), (({},), {}), + ((), {"params": {}})], + ids=["absent", "none", "tuple", "list", "dict", "keyword-dict"]) +def test_unbound_write_names_column(mocker, env, dialect, args, kwargs): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + secret = marker() + sql = f"INSERT INTO users (ssn) VALUES ('{secret}')" + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "execute", sql, *args, **kwargs) + assert raw.calls == [] + assert (info.value.table_name, info.value.column_name) == ("users", "ssn") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnboundWrite", "users.ssn") + _clean(info.value, secret) + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +def test_literal_write_in_later_statement_refused(mocker, env, dialect): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + secret = marker() + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "execute", f"SELECT 1; INSERT INTO users (name, ssn) VALUES ('test-name', '{secret}')") + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnboundWrite", "users.ssn") + _clean(info.value, secret) + + +def test_row_factory_refused_before_any_row(plugin): + cur, raw = cursor(plugin, _posing_as(psycopg.Cursor)()) + raw.row_factory = pg_rows.class_row(dict) + call(cur, "execute", SELECT, (1,)) + secret = marker() + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + with pytest.raises(MetadataError) as info: + call(cur, "fetchall") + assert raw.fetches == 0 + _clean(info.value, secret) + + +@pytest.mark.parametrize("factory, shape", [(pg_rows.tuple_row, lambda i, s: (i, s)), + (pg_rows.dict_row, lambda i, s: {"id": i, "ssn": s}), + (pg_rows.namedtuple_row, _Row)], + ids=["tuple_row", "dict_row", "namedtuple_row"]) +def test_allowed_row_factory_decrypts_encrypted_column(plugin, factory, shape): + cur, raw = cursor(plugin, _posing_as(psycopg.Cursor)()) + raw.row_factory = factory + secret = marker() + call(cur, "execute", "SELECT id, ssn FROM users WHERE id = %s", (1,)) + # The tables only, never the statement or its values. + assert repr(plugin._results[raw]) == "_Result(['users'])" + raw.description, raw.rows = [("id",), ("ssn",)], [shape(1, payload(secret))] + row = call(cur, "fetchone") + assert row == shape(1, secret) + assert type(row) is type(shape(1, secret)) + assert call(cur, "fetchone") is None + + +@pytest.mark.parametrize("configs", [[SSN], [SSN, ARCHIVE_SSN]], ids=["one-encrypted", "both-encrypted"]) +def test_dict_row_repeated_name_decodes_held_value(mocker, env, configs): + env.configs = configs + plugin, _ = make_plugin(mocker) + cur, raw = cursor(plugin) + archive = marker() + archive_stored = payload(archive) if ARCHIVE_SSN in configs else archive.encode() + call(cur, "execute", "SELECT u.ssn, a.ssn FROM users u JOIN archive a ON a.id = u.id WHERE u.id = %s", (1,)) + # The drivers build a dict row from the names in order, so it holds the last ssn column's value. + raw.description, raw.rows = [("ssn",), ("ssn",)], [{"ssn": archive_stored}] + assert call(cur, "fetchall") == [{"ssn": archive if ARCHIVE_SSN in configs else archive_stored}] + + +@pytest.mark.parametrize("lenient", [False, True], ids=["strict", "lenient"]) +@pytest.mark.parametrize("path", ["write", "read"]) +@pytest.mark.parametrize("row", [None, replace(KEY_ROW, master_key_arn="")], ids=["missing", "unusable"]) +def test_unusable_own_key_row(mocker, env, row, path, lenient): + # Missing: the LEFT JOIN found no key_storage row. + env.configs = [replace(SSN, key_metadata=row)] + plugin, _ = make_plugin(mocker, encryption_return_unverified_data=lenient) + cur, raw = cursor(plugin) + secret = marker() + if path == "read": + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + with pytest.raises(InvalidKeyMetadataError) as info: + call(cur, "execute", INSERT, (secret,)) if path == "write" else call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnusableColumn", "users.ssn") + assert env.keys.return_value.decrypt_data_key.call_count == 0 + assert len(raw.calls) == (1 if path == "read" else 0) + _clean(info.value, secret) + + +@pytest.mark.parametrize("name", ["AES-512-GCM", "aes-256-gcm", "AES-256-GCM "], ids=["AES-512-GCM", "aes-256-gcm", "trailing-space"]) +@pytest.mark.parametrize("lenient", [False, True], ids=["strict", "lenient"]) +@pytest.mark.parametrize("path", ["write", "read", "read-rotated", "read-kept"]) +def test_unsupported_algorithm_message(mocker, env, path, lenient, name): + env.configs = [replace(SSN, algorithm=name)] + old = replace(KEY_ROW, id=1802201963, key_id="k-old", encrypted_data_key="b2xk", hmac_key=OLD_HMAC) + # A usable row of an earlier key, for read-rotated. + env.keys.return_value.key_metadata_by_id.return_value = old + plugin, _ = make_plugin(mocker, encryption_return_unverified_data=lenient) + cur, raw = cursor(plugin) + secret = marker() + if path != "write": + call(cur, "execute", SELECT, (1,)) + stored = payload(secret) if path == "read" else EncryptionService.encrypt(secret, DATA_KEY, OLD_HMAC, key_id=old.id) + raw.description, raw.rows = [("ssn",)], [(stored,)] + if path == "read-kept": + # As an earlier read of a value under that key leaves it. + plugin._old_keys[old.id] = old + with pytest.raises(InvalidAlgorithmError) as info: + call(cur, "execute", INSERT, (secret,)) if path == "write" else call(cur, "fetchall") + keys = env.keys.return_value + # No key row, no KMS call. + assert (keys.key_metadata_by_id.call_count, keys.decrypt_data_key.call_count) == (0, 0) + # A write reaches no driver call. + assert len(raw.calls) == (0 if path == "write" else 1) + assert str(info.value) == Messages.get_formatted( + "KmsEncryptionPlugin.UnsupportedAlgorithm", "users.ssn", repr(name), "AES-256-GCM, AES-128-GCM") + assert info.value.algorithm == name + _clean(info.value, secret) + + +@pytest.mark.parametrize("lenient", [False, True, "False", "true"], + ids=["strict", "lenient", "strict-url-string", "lenient-url-string"]) +@pytest.mark.parametrize("kind", ["payload", "legacy-plaintext"]) +def test_foreign_key_id_without_row(mocker, env, caplog, kind, lenient): + # A SQLAlchemy URL passes the setting as a string, and reading "False" as truthy would make strict mode lenient. + plugin, _ = make_plugin(mocker, encryption_return_unverified_data=lenient) + lenient = lenient in (True, "true") + secret = marker() + stored = payload(secret, key_id=1802201963) if kind == "payload" else secret.encode() + stored_id = int.from_bytes(stored[32:36], "big") + assert stored_id != SSN.key_id + cur, raw = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(stored,)] + with caplog.at_level(logging.DEBUG): + if lenient: + assert call(cur, "fetchall") == [(stored,)] + else: + with pytest.raises(IntegrityCheckError) as info: + call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnknownKey", "users.ssn") + assert str(stored_id) not in str(info.value) + _clean(info.value, secret) + env.keys.return_value.key_metadata_by_id.assert_called_once_with(stored_id) + assert env.keys.return_value.decrypt_data_key.call_count == 0 + assert plugin_records(caplog) == [] + + +@pytest.mark.parametrize("lenient", [False, True], ids=["strict", "lenient"]) +def test_tampered_value(mocker, env, lenient): + plugin, _ = make_plugin(mocker, encryption_return_unverified_data=lenient) + secret = marker() + tampered = bytearray(payload(secret)) + tampered[-1] ^= 1 + stored = bytes(tampered) + cur, raw = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(stored,)] + if lenient: + assert call(cur, "fetchall") == [(stored,)] + else: + with pytest.raises(IntegrityCheckError) as info: + call(cur, "fetchall") + _clean(info.value, secret) + + +def test_rotated_key_row_decrypts_and_is_kept(mocker, env): + old = replace(KEY_ROW, id=1802201963, key_id="k-old", encrypted_data_key="b2xk", hmac_key=OLD_HMAC) + env.keys.return_value.key_metadata_by_id.return_value = old + plugin, _ = make_plugin(mocker) + secret = marker() + cur, raw = cursor(plugin) + for _ in range(2): + call(cur, "execute", SELECT, (1,)) + raw.description = [("ssn",)] + raw.rows = [(EncryptionService.encrypt(secret, DATA_KEY, OLD_HMAC, key_id=old.id),)] + assert call(cur, "fetchall") == [(secret,)] + env.keys.return_value.key_metadata_by_id.assert_called_once_with(old.id) + env.keys.return_value.decrypt_data_key.assert_called_with("b2xk", ARN) + + +@pytest.mark.parametrize("row", [None, replace(KEY_ROW, master_key_arn="")], ids=["missing", "unusable"]) +def test_rotated_value_with_unusable_own_key_reads(mocker, env, row): + # A value written under an earlier key decrypts with that key's row, whatever the state of the column's own key row. + # Missing: the LEFT JOIN found no key_storage row. + env.configs = [replace(SSN, key_metadata=row)] + old = replace(KEY_ROW, id=1802201963, key_id="k-old", encrypted_data_key="b2xk", hmac_key=OLD_HMAC) + env.keys.return_value.key_metadata_by_id.return_value = old + plugin, _ = make_plugin(mocker) + secret = marker() + cur, raw = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + raw.description = [("ssn",)] + raw.rows = [(EncryptionService.encrypt(secret, DATA_KEY, OLD_HMAC, key_id=old.id),)] + assert call(cur, "fetchall") == [(secret,)] + env.keys.return_value.key_metadata_by_id.assert_called_once_with(old.id) + env.keys.return_value.decrypt_data_key.assert_called_with("b2xk", ARN) + + +# Statement shapes, with users.ssn and users.dob the encrypted columns. Each outcome is the key of the refusal (naming +# users.ssn), or the ordinals encrypted (every other value is sent as written). +NOT_ENCRYPTED = "KmsEncryptionPlugin.AnnotationNotEncrypted" +NO_TABLE = "KmsEncryptionPlugin.UnknownColumnTable" +D = "SELECT s.ssn FROM (SELECT id, ssn FROM users) s JOIN archive a ON a.id = s.id WHERE s.ssn = " +W = "SELECT s.ssn FROM (SELECT id, ssn FROM archive) s JOIN users u ON u.id = s.id WHERE s.ssn = " +CTE = "WITH w AS (SELECT id, ssn FROM users) SELECT w.ssn FROM w JOIN archive a ON a.id = w.id WHERE w.ssn = " +JOIN = "SELECT u.id FROM users u JOIN audit x ON x.id = u.id WHERE " +ALONE = "SELECT s.ssn FROM (SELECT id, ssn FROM users) s WHERE s.ssn = " +IN_DERIVED = "UPDATE archive SET note = %s WHERE id IN (SELECT s.id FROM (SELECT id, ssn FROM users) s WHERE s.ssn = " +SA_SELECT = ("SELECT anon_1.id, anon_1.name, anon_1.ssn, addresses.id AS id_1, addresses.user_id, addresses.email \n" + "FROM (SELECT users.id AS id, users.name AS name, users.ssn AS ssn \nFROM users \nWHERE users.name = ") +SHAPES: List[Tuple[str, Sequence[str], str, Any]] = [ + ("R1", ["pg"], "INSERT INTO users (name, ssn) VALUES (%s, /*@encrypt:users.name*/ %s)", NOT_ENCRYPTED), + ("R2", ["mysql"], "INSERT INTO users (name, ssn) VALUES (%s, /*@encrypt:nosuch.col*/ %s)", NOT_ENCRYPTED), + ("R3", ["pg"], "INSERT INTO users (name, ssn) VALUES (%s, /*@encrypt:users.snn*/ %s)", NOT_ENCRYPTED), + ("R4", ["mysql"], "UPDATE users SET ssn = /*@encrypt:users.name*/ %s WHERE id = %s", NOT_ENCRYPTED), + ("R5", ["pg"], "SELECT id FROM users WHERE ssn = /*@encrypt:users.name*/ %s", NOT_ENCRYPTED), + ("R6", ["mysql"], "UPDATE users SET name = %s WHERE ssn = /*@encrypt:users.name*/ %s", NOT_ENCRYPTED), + ("C1", ["pg"], "INSERT INTO users (name, ssn) VALUES (/*@encrypt:users.ssn*/ %s, %s)", {0, 1}), + ("C2", ["pg"], "INSERT INTO users (name, ssn) VALUES (%s, /*@encrypt:users.ssn*/ %s)", {1}), + ("C4", ["pg"], "UPDATE users SET ssn = upper(/*@encrypt:users.ssn*/ %s) WHERE id = %s", + "KmsEncryptionPlugin.UnboundWrite"), + ("G1", ["pg", "mysql"], D + "%s", NO_TABLE), + ("G2", ["pg", "mysql"], CTE + "%s", NO_TABLE), + ("G3", ["pg", "mysql"], IN_DERIVED + "%s)", NO_TABLE), + ("G3a", ["pg", "mysql"], IN_DERIVED + "/*@encrypt:users.ssn*/ %s)", {1}), + ("G4", ["pg", "mysql"], JOIN + "ssn = %s", NO_TABLE), + ("G5", ["pg", "mysql"], ALONE + "%s", {0}), + ("G9", ["pg", "mysql"], "SELECT s.name FROM (SELECT id, name FROM users) s JOIN archive a ON a.id = s.id " + "WHERE s.name = %s", set()), + ("G10", ["pg", "mysql"], W + "%s", NO_TABLE), + ("G10a", ["pg", "mysql"], W + "/*@encrypt:archive.ssn*/ %s", set()), + ("G11", ["pg", "mysql"], D + "/*@encrypt:users.ssn*/ %s", {0}), + ("G12", ["pg", "mysql"], "SELECT u.id FROM users u JOIN archive a ON a.id = u.id WHERE u.ssn = %s", {0}), + ("G13", ["pg", "mysql"], JOIN + "note = %s", set()), + ("O2", ["pg"], "SELECT anon_1.id, anon_1.ssn, addresses.email \nFROM (SELECT users.id AS id, users.ssn AS ssn \n" + "FROM users) AS anon_1 JOIN addresses ON addresses.user_id = anon_1.id \nWHERE anon_1.ssn = %(ssn_1)s", NO_TABLE), + ("O2", ["mysql"], "SELECT anon_1.id, anon_1.ssn, addresses.email \nFROM (SELECT users.id AS id, users.ssn AS ssn \n" + "FROM users) AS anon_1 INNER JOIN addresses ON addresses.user_id = anon_1.id \nWHERE anon_1.ssn = %s", + NO_TABLE), + ("O4", ["pg"], SA_SELECT + "%(name_1)s::VARCHAR) AS anon_1 JOIN addresses ON addresses.user_id = anon_1.id \n" + "WHERE anon_1.ssn = %(ssn_1)s", NO_TABLE), + ("O4", ["mysql"], SA_SELECT + "%s) AS anon_1 INNER JOIN addresses ON addresses.user_id = anon_1.id \n" + "WHERE anon_1.ssn = %s", NO_TABLE), + ("X1", ["pg", "mysql"], D + "/*@encrypt:ssn*/ %s", NO_TABLE), + ("X2", ["pg", "mysql"], D + "/*@encrypt:s.ssn*/ %s", NO_TABLE), + ("X3", ["pg", "mysql"], JOIN + "ssn = /*@encrypt:ssn*/ %s", NO_TABLE), + ("X4", ["pg", "mysql"], CTE + "/*@encrypt:w.ssn*/ %s", NO_TABLE), + ("X5", ["pg", "mysql"], ALONE + "/*@encrypt:ssn*/ %s", {0}), + ("N1", ["pg", "mysql"], ALONE + "/*@encrypt:s.ssn*/ %s", NOT_ENCRYPTED), + ("N4", ["pg", "mysql"], D + "/*@encrypt:nosuch.ssn*/ %s", NO_TABLE), + ("N5", ["pg", "mysql"], W + "/*@encrypt:public.archive.ssn*/ %s", set()), + ("N6", ["pg", "mysql"], W + "/*@encrypt:ARCHIVE.ssn*/ %s", set()), + ("C3", ["pg", "mysql"], JOIN + "x.id = upper(/*@encrypt:ssn*/ %s)", set()), + # Literals and expressions ahead of the parameters still leave only ssn's value encrypted. + ("J1", ["pg", "mysql"], "INSERT INTO users (name, email, ssn) VALUES ('lit', %s, %s)", {1}), + ("J2", ["pg", "mysql"], "INSERT INTO users (name, ssn, email) VALUES (%s, %s, %s)", {1}), + ("J3", ["pg", "mysql"], "UPDATE users SET name = 'lit', ssn = %s WHERE id = %s", {0}), + ("J4", ["pg", "mysql"], "UPDATE users SET updated_at = NOW(), ssn = %s WHERE id = %s", {0}), + ("J5", ["pg", "mysql"], "SELECT name FROM users WHERE name = 'lit' AND ssn = %s", {0}), + ("COPY", ["pg"], "COPY users (id, ssn) FROM PROGRAM 'printf \"1,x\\n\"' WITH (FORMAT csv)", + "KmsEncryptionPlugin.UnboundWrite"), +] + + +@pytest.mark.parametrize("dialect, sql, outcome", [pytest.param(d, sql, outcome, id=f"{label}-{d}") + for label, dialects, sql, outcome in SHAPES for d in dialects]) +def test_statement_shapes_are_encrypted_sent_or_refused(mocker, env, dialect, sql, outcome): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + names = re.findall(r"%\((\w+)\)s", sql) + params: Any = {n: marker() for n in names} if names else tuple(marker() for _ in range(sql.count("%s"))) + cur, raw = cursor(plugin) + if isinstance(outcome, str): + with pytest.raises(MetadataError) as info: + call(cur, "execute", sql, params) + assert raw.calls == [] + assert (info.value.table_name, info.value.column_name) == ("users", "ssn") + assert str(info.value) == Messages.get_formatted(outcome, "users.ssn") + _clean(info.value, *(params.values() if names else params)) + return + call(cur, "execute", sql, params) + sent = raw.calls[0][1][1] + assert outcome or sent is params + for ordinal, value in enumerate(params): + assert (len(sent[ordinal]) >= 65) if ordinal in outcome else (sent[ordinal] is value) + + +@pytest.mark.parametrize("dialect, sql, gap", [ + ("pg", "INSERT INTO users (name, ssn) SELECT name, ssn FROM users WHERE ssn = /*@encrypt:users.name*/ %s", + AnalysisGap.VALUES_FROM_QUERY), + ("pg", "INSERT INTO users (name, ssn) SELECT a.name, a.ssn FROM archive a JOIN audit x ON x.id = a.id WHERE ssn = %s", + AnalysisGap.VALUES_FROM_QUERY), + ("mysql", "UPDATE users u JOIN accounts a ON a.id = u.id SET ssn = %s WHERE a.id = %s", AnalysisGap.AMBIGUOUS_TABLE), +], ids=["annotated", "table-less", "multi-table-update"]) +def test_gap_write_passes_with_one_warning(mocker, env, caplog, dialect, sql, gap): + # Each statement has a shape a refusal would catch without its gap; the gap rule comes first. + plugin, _ = make_plugin(mocker, DIALECTS[dialect], encryption_fail_on_unmapped_parameter=False) + cur, raw = cursor(plugin) + params = tuple(marker() for _ in range(sql.count("%s"))) + with caplog.at_level(logging.DEBUG): + for _ in range(2): + call(cur, "execute", sql, params) + assert [c[1][1] is params for c in raw.calls] == [True, True] + warnings = plugin_records(caplog) + assert len(warnings) == 1 + assert warnings[0].levelno == logging.WARNING + message = warnings[0].getMessage() + assert message.startswith("[KmsEncryptionPlugin] A statement writing table(s) 'users'") + assert f"({gap.value})" in message + assert not [r for r in caplog.records for p in params if p in r.getMessage()] + + +UNMAPPED = "KmsEncryptionPlugin.UnmappedParameters" + + +def _refused_unmapped(mocker: Any, dialect: str, method: str, sql: str, params: Any, gap: AnalysisGap) -> None: + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, method, sql, params) + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted(UNMAPPED, "users", gap.value) + _clean(info.value, *(p for row in (params if method == "executemany" else [params]) for p in row)) + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, gap", [ + ("INSERT INTO users VALUES (%s, %s)", AnalysisGap.NO_COLUMN_LIST), + ("INSERT INTO users (name, ssn) SELECT name, ssn FROM archive WHERE id = %s", AnalysisGap.VALUES_FROM_QUERY), +], ids=["no-column-list", "insert-select"]) +def test_unmapped_write_refused_by_default(mocker, env, dialect, sql, gap): + _refused_unmapped(mocker, dialect, "execute", sql, tuple(marker() for _ in range(sql.count("%s"))), gap) + + +def test_unqualified_multi_table_set_refused(mocker, env): + sql = "UPDATE users u JOIN accounts a ON a.id = u.id SET ssn = %s WHERE a.id = %s" + _refused_unmapped(mocker, "mysql", "execute", sql, (marker(), marker()), AnalysisGap.AMBIGUOUS_TABLE) + + +def test_unmappable_multi_statement_string_refused(mocker, env): + sql = "SELECT 1; INSERT INTO users VALUES (%s, %s)" + _refused_unmapped(mocker, "mysql", "execute", sql, (marker(), marker()), AnalysisGap.NO_COLUMN_LIST) + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +def test_unmapped_executemany_refused_by_default(mocker, env, dialect): + sql = "INSERT INTO users VALUES (%s, %s)" + _refused_unmapped(mocker, dialect, "executemany", sql, [(marker(), marker()) for _ in range(2)], + AnalysisGap.NO_COLUMN_LIST) + + +@pytest.mark.parametrize("sql", [ + "SELECT * FROM users WHERE name = 'a\\' AND ssn = %s", + "SELECT * FROM users WHERE ssn = %s LIMIT 1,,", +], ids=["unterminated-literal", "parse-failure"]) +def test_unparseable_read_with_parameter_refused(mocker, env, sql): + _refused_unmapped(mocker, "mysql", "execute", sql, (marker(),), AnalysisGap.UNPARSEABLE) + + +@pytest.mark.parametrize("dialect, sql", [ + ("pg", "INSERT INTO users VALUES (%s, %s)"), + ("mysql", "UPDATE users u JOIN accounts a ON a.id = u.id SET ssn = %s WHERE a.id = %s"), +], ids=["no-column-list", "multi-table-update"]) +def test_unmapped_write_runs_unchanged_when_opted_out(mocker, env, caplog, dialect, sql): + plugin, _ = make_plugin(mocker, DIALECTS[dialect], encryption_fail_on_unmapped_parameter=False) + cur, raw = cursor(plugin) + params = tuple(marker() for _ in range(sql.count("%s"))) + with caplog.at_level(logging.DEBUG): + call(cur, "execute", sql, params) + assert raw.calls[0][1][1] is params + assert len(plugin_records(caplog)) == 1 + + +def test_unmapped_write_without_parameters_warns(mocker, env, caplog): + plugin, _ = make_plugin(mocker) + cur, raw = cursor(plugin) + with caplog.at_level(logging.DEBUG): + call(cur, "execute", "INSERT INTO users (name, ssn) SELECT name, ssn FROM archive") + assert len(raw.calls) == 1 + assert len(plugin_records(caplog)) == 1 + + +def _refused_unread(mocker: Any, dialect: str, sql: str, key: str, *args: str) -> None: + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + params = tuple(marker() for _ in range(sql.count("%s"))) + with pytest.raises(MetadataError) as info: + call(cur, "execute", sql, params or None) + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted(key, "users", *args) + _clean(info.value, *params) + + +@pytest.mark.parametrize("sql", [ + "UPDATE plain_t /*! JOIN users ON users.id = plain_t.id */ SET users.ssn = %s", + "UPDATE plain_t /*!50000 JOIN users USING (id) */ SET ssn = %s", + "SELECT plain_t.a FROM plain_t /*!50000 , users */ WHERE users.ssn = %s", + "INSERT INTO plain_t (a) VALUES (/*@encrypt:users.ssn*/ %s) /*!50000 */", +], ids=["join", "join-using", "comma", "annotation"]) +def test_executable_comment_naming_encrypted_table_refused(mocker, env, sql): + _refused_unread(mocker, "mysql", sql, "KmsEncryptionPlugin.ExecutableComment") + + +@pytest.mark.parametrize("sql", [ + "INSERT /*!50000 LOW_PRIORITY */ INTO users (ssn) VALUES (%s)", + "SELECT id FROM users WHERE ssn /*! = */ %s", + "SELECT /*!40001 SQL_NO_CACHE */ * FROM users", +], ids=["modifier", "operator", "parameterless-read"]) +def test_keyword_only_executable_comment_refused(mocker, env, sql): + _refused_unread(mocker, "mysql", sql, "KmsEncryptionPlugin.ExecutableComment") + + +@pytest.mark.parametrize("dialect, sql, encrypted", [ + ("pg", "INSERT /*! IGNORE */ INTO users (ssn) VALUES (%s)", True), + ("mysql", "INSERT /*!50000 LOW_PRIORITY */ INTO audit (note) VALUES (%s)", False), +], ids=["pg-plain-comment", "mysql-plain-table"]) +def test_executable_comment_on_plain_table_or_pg_runs(mocker, env, dialect, sql, encrypted): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql, (secret,)) + sent = raw.calls[0][1][1][0] + if encrypted: + assert EncryptionService.decrypt(sent, DATA_KEY, HMAC_KEY) == secret + else: + assert sent == secret + + +@pytest.mark.parametrize("sql", [ + "UPDATE (users u) SET u.ssn = %s", + "UPDATE (`users` u) SET u.ssn = %s", + "DELETE u FROM (users u) WHERE u.ssn = %s", +], ids=["update", "update-quoted", "delete"]) +def test_parenthesized_table_list_with_encrypted_column_refused(mocker, env, sql): + _refused_unread(mocker, "mysql", sql, UNMAPPED, AnalysisGap.UNPARSEABLE.value) + + +@pytest.mark.parametrize("dialect, sql", [ + ("pg", 'UPDATE "users" SET ssn = %s WHERE id = %s,,'), + ("mysql", "INSERT INTO `users` (ssn) VALUES (%s) ON DUPLICATE KEY,"), +], ids=["pg", "mysql"]) +def test_quoted_table_in_unreadable_statement_refused(mocker, env, dialect, sql): + _refused_unread(mocker, dialect, sql, UNMAPPED, AnalysisGap.UNPARSEABLE.value) + + +@pytest.mark.parametrize("sql, key, args", [ + ("INSERT INTO users (name, ssn) VALUES ('a\\', %s)", UNMAPPED, (AnalysisGap.UNPARSEABLE.value,)), + # With NO_BACKSLASH_ESCAPES the server ends the literal at the backslash and binds both values. + ("INSERT INTO users (name, note, ssn) VALUES (%s, 'a\\', %s) /* ' */", "KmsEncryptionPlugin.HiddenPlaceholder", ()), +], ids=["unterminated", "no-backslash-escapes"]) +def test_backslash_literal_before_placeholder_refused(mocker, env, sql, key, args): + _refused_unread(mocker, "mysql", sql, key, *args) + + +def test_closed_backslash_literal_is_encrypted(mocker, env): + plugin, _ = make_plugin(mocker, DIALECTS["mysql"]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", "INSERT INTO users (name, ssn) VALUES ('it\\'s', %s)", (secret,)) + assert EncryptionService.decrypt(raw.calls[0][1][1][0], DATA_KEY, HMAC_KEY) == secret + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +def test_hidden_placeholder_without_named_table_refused(mocker, env, dialect): + # The statement doesn't parse, so only its words name the table. + _refused_unread(mocker, dialect, "UPDATE users SET ssn = %s /* %s */ WHERE id = %s,,", + "KmsEncryptionPlugin.HiddenPlaceholder") + + +@pytest.mark.parametrize("sql", [ + "COPY users (name, ssn) FROM STDIN", + "COPY public.users (ssn) FROM STDIN WITH (FORMAT csv)", + "COPY users (id, ssn) FROM STDIN (FORMAT csv, HEADER true)", +], ids=["column-list", "qualified", "options-without-with"]) +def test_copy_from_naming_encrypted_column_refused(plugin, sql): + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "copy", sql) + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.CopyRefused", "users.ssn") + + +@pytest.mark.parametrize("sql, warnings", [ + ("COPY audit (note) FROM STDIN", 0), + ("COPY users TO STDOUT", 0), + ("COPY (SELECT ssn FROM users) TO STDOUT", 0), + ("COPY users FROM STDIN", 1), + ("COPY users TO STDOUT (FORMAT csv)", 0), + ("COPY (SELECT id FROM users) TO STDOUT (FORMAT csv)", 0), + ("COPY (SELECT ssn FROM users) TO STDOUT (FORMAT binary)", 0), + ("COPY users (id) FROM STDIN (FORMAT binary)", 0), + ("COPY users FROM STDIN (FORMAT csv)", 1), +], ids=["plain-table", "to", "query-to", "no-column-list", "options-to", "query-to-options", "query-to-binary", + "plain-column-options", "no-column-list-options"]) +def test_copy_without_encrypted_column_list_runs(plugin, caplog, sql, warnings): + cur, raw = cursor(plugin) + with caplog.at_level(logging.DEBUG): + copy = call(cur, "copy", sql) + assert raw.calls == [("copy", (sql,), {})] + assert copy is not None + assert len(plugin_records(caplog)) == warnings + + +@pytest.mark.parametrize("sql", [ + "COPY users (id, ssn) FROM STDIN WHERE id > 0", + "COPY (INSERT INTO users (ssn) VALUES ('x') RETURNING id) TO STDOUT", + "COPY (UPDATE users SET ssn = 'x' RETURNING id) TO STDOUT", +], ids=["where", "insert-returning", "update-returning"]) +def test_unparsed_copy_that_writes_encrypted_table_refused(plugin, sql): + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "copy", sql) + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted( + "KmsEncryptionPlugin.CopyUnread", "users", AnalysisGap.UNPARSEABLE.value) + + +@pytest.mark.parametrize("sql", [ + "COPY (SELECT id FROM users WHERE ssn = %s) TO STDOUT", + "COPY (SELECT id FROM users WHERE ssn IN (%s)) TO STDOUT", + "COPY (SELECT id FROM users WHERE ssn = %s) TO STDOUT (FORMAT csv)", +], ids=["equals", "in", "options"]) +def test_copy_with_parameters_on_encrypted_table_refused(plugin, sql): + cur, raw = cursor(plugin) + params = (marker(),) + with pytest.raises(MetadataError) as info: + call(cur, "copy", sql, params) + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.CopyParameters", "users") + _clean(info.value, *params) + + +@pytest.mark.parametrize("sql, props", [ + ("COPY (SELECT id FROM users WHERE ssn = %s) TO STDOUT", {"encryption_fail_on_unmapped_parameter": False}), + ("COPY (SELECT id FROM users WHERE ssn = %s) TO STDOUT (FORMAT csv)", + {"encryption_fail_on_unmapped_parameter": False}), + ("COPY (SELECT note FROM audit WHERE id = %s) TO STDOUT", {}), +], ids=["opted-out", "opted-out-options", "plain-table"]) +def test_copy_with_parameters_runs_unchanged(mocker, env, caplog, sql, props): + plugin, _ = make_plugin(mocker, **props) + cur, raw = cursor(plugin) + params = (marker(),) + with caplog.at_level(logging.DEBUG): + call(cur, "copy", sql, params) + assert raw.calls == [("copy", (sql, params), {})] + assert plugin_records(caplog) == [] + + +@pytest.mark.parametrize("sql, props", [ + ("COPY (WITH users AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM users) TO STDOUT", {}), + ("COPY (WITH a AS (SELECT id FROM users WHERE ssn = %s), users AS (SELECT id FROM a) SELECT id FROM users) TO STDOUT", + {}), + ("COPY (WITH users AS (SELECT ssn FROM users) SELECT ssn FROM users) TO STDOUT", {}), + ("COPY (WITH users AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM users) TO STDOUT", + {"encryption_fail_on_unmapped_parameter": False}), +], ids=["self-reference", "forward-reference", "no-parameters", "opted-out"]) +def test_copy_with_cte_named_like_encrypted_table_refused(mocker, env, sql, props): + plugin, _ = make_plugin(mocker, **props) + cur, raw = cursor(plugin) + params = tuple(marker() for _ in range(sql.count("%s"))) + with pytest.raises(MetadataError) as info: + call(cur, "copy", sql, params or None) + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.CteShadowsTable", "users") + _clean(info.value, *params) + + +def test_copy_of_sql_object_not_analyzed_runs_with_one_warning(env, plugin, caplog): + env.configs = [] + cur, raw = cursor(plugin) + sql = _OpaqueSql("COPY users (ssn) FROM STDIN") + with caplog.at_level(logging.DEBUG): + for _ in range(2): + call(cur, "copy", sql) + assert raw.calls == [("copy", (sql,), {})] * 2 + assert len(plugin_records(caplog)) == 1 + + +# A %s the driver still binds, hidden beside the real placeholders: where it hides, the kind of statement, and the SQL +# (on MySQL with backticks for the double quotes). +HIDDEN = [ + ("literal", "write", "INSERT INTO users (name, ssn) VALUES ('x%s', %s)"), + ("literal", "select", "SELECT ssn FROM users WHERE name <> 'x%s' AND id = %s"), + ("identifier", "write", 'UPDATE users AS "u%s" SET ssn = %s WHERE id = %s'), + ("identifier", "select", 'SELECT ssn AS "x%s" FROM users WHERE id = %s'), + ("comment", "write", "UPDATE users SET ssn = %s /* %s */ WHERE id = %s"), + ("comment", "select", "SELECT ssn FROM users WHERE id = %s -- %s"), +] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("method, sql, refused", + [pytest.param("execute", sql, True, id=f"{where}-{kind}") for where, kind, sql in HIDDEN] + + [pytest.param("executemany", "INSERT INTO users (name, ssn) VALUES ('x%s', %s)", True, id="literal-write-many"), + pytest.param("execute", "INSERT INTO audit (note) VALUES (%s) /* %s */", False, id="plain-table")]) +def test_hidden_placeholder_on_encrypted_table_refused(mocker, env, dialect, method, sql, refused): + # The driver's count of placeholders decides which value lands in which column, and the analysis can't follow it. + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + sql = sql.replace('"', "`") if dialect == "mysql" else sql + sets = [tuple(marker() for _ in range(sql.count("%s"))) for _ in range(2)] + params = sets if method == "executemany" else sets[0] + cur, raw = cursor(plugin) + # No encrypted column to protect: sent as given. + if not refused: + call(cur, method, sql, params) + assert len(raw.calls) == 1 + assert raw.calls[0][1][0] is sql + assert raw.calls[0][1][1] is params + return + with pytest.raises(MetadataError) as info: + call(cur, method, sql, params) + assert raw.calls == [] + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.HiddenPlaceholder", "users") + _clean(info.value, *sets[0], *sets[1]) + + +@pytest.mark.parametrize("dialect, kind", [("mysql", "gap"), ("pg", "not-analyzed")]) +def test_pass_through_warnings_quote_no_literal(mocker, env, caplog, dialect, kind): + plugin, _ = make_plugin(mocker, DIALECTS[dialect], encryption_fail_on_unmapped_parameter=False) + cur, raw = cursor(plugin) + secret = marker() + sql: Any = (f"UPDATE users u JOIN accounts a ON a.id = u.id SET ssn = '{secret}'" if kind == "gap" + else _OpaqueSql(f"INSERT INTO users (ssn) VALUES ('{secret}')")) + with caplog.at_level(logging.DEBUG): + call(cur, "execute", sql) + assert raw.calls[0][1][0] is sql + assert len(plugin_records(caplog)) == 1 + assert not [r for r in caplog.records if secret in r.getMessage()] + + +def test_pass_through_warnings_stop_at_256_shapes(mocker, env, caplog): + env.configs = [ColumnEncryptionConfig(f"t{i}", "ssn", key_id=7, key_metadata=KEY_ROW) for i in range(300)] + plugin, _ = make_plugin(mocker, DriverDialectCodes.MYSQL_CONNECTOR_PYTHON, encryption_fail_on_unmapped_parameter=False) + cur, raw = cursor(plugin) + with caplog.at_level(logging.DEBUG): + # An unqualified SET in a multi-table UPDATE is a gap write, passed through with one warning per shape. + for i in range(300): + call(cur, "execute", f"UPDATE t{i} u JOIN accounts a ON a.id = u.id SET ssn = %s WHERE a.id = %s", + (marker(), 1)) + assert len(raw.calls) == 300 + assert len(plugin_records(caplog)) == 256 + assert len(plugin._warned) == 256 + + +UNSAFE = "KmsEncryptionPlugin.UnsafeComparison" +# Conditions on users.ssn that an encrypted value, which equals no stored value, makes true for every row or for +# arbitrary rows, with the dialects each is valid on. +UNSAFE_CONDITIONS: List[Tuple[str, Sequence[str], str]] = [ + ("neq", ["pg", "mysql"], "ssn <> %s"), + ("bang-neq", ["pg", "mysql"], "ssn != %s"), + ("gt", ["pg", "mysql"], "ssn > %s"), + ("lte", ["pg", "mysql"], "ssn <= %s"), + ("between", ["pg", "mysql"], "ssn BETWEEN %s AND %s"), + ("not-in", ["pg", "mysql"], "ssn NOT IN (%s, %s)"), + ("not-like", ["pg", "mysql"], "ssn NOT LIKE %s"), + ("not", ["pg", "mysql"], "NOT (ssn = %s)"), + ("is-distinct-from", ["pg"], "ssn IS DISTINCT FROM %s"), +] +UNSAFE_STATEMENTS = {"select": "SELECT id FROM users WHERE {}", "update": "UPDATE users SET name = %s WHERE {}", + "delete": "DELETE FROM users WHERE {}"} +UNSAFE_SHAPES: List[Tuple[str, Sequence[str], str]] = [ + ("not-in-sub-select", ["pg", "mysql"], "DELETE FROM users WHERE id NOT IN (SELECT id FROM users WHERE ssn = %s)"), + ("not-exists", ["pg", "mysql"], + "DELETE FROM orders WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id = orders.uid AND u.ssn = %s)"), + ("left-join-anti-join", ["pg", "mysql"], + "SELECT o.id FROM orders o LEFT JOIN users u ON u.id = o.uid AND u.ssn = %s WHERE u.id IS NULL"), + ("inner-join-before-right-join", ["pg"], + "SELECT i.id FROM users u JOIN orders o ON o.uid = u.id AND u.ssn = %s RIGHT JOIN items i ON i.oid = o.id"), + ("inner-join-before-right-join", ["mysql"], + "DELETE i FROM users u JOIN orders o ON o.uid = u.id AND u.ssn = %s RIGHT JOIN items i ON i.oid = o.id"), + ("aggregating-sub-select", ["pg", "mysql"], "DELETE FROM orders WHERE (SELECT COUNT(*) FROM users WHERE ssn = %s) = 0"), + ("named-equal-or-not-equal", ["pg", "mysql"], "SELECT id FROM users WHERE ssn = %(v)s OR ssn <> %(v)s"), + # Refused as an unsafe comparison before the unbound write is seen. + ("unsafe-before-unbound-write", ["pg", "mysql"], "UPDATE users SET ssn = upper(%s) WHERE ssn <> %s"), + # An unsafe comparison on a plain column doesn't end the check. + ("plain-then-encrypted", ["pg", "mysql"], "UPDATE users SET note = %s WHERE name <> %s AND ssn <> %s"), +] + + +def _refused_as_unsafe(mocker: Any, env: Any, dialect: str, sql: str, params: Any, secrets: Sequence[str]) -> None: + """``sql`` is refused naming users.ssn before KMS or the driver is called, leaving no result to decode, and the + error shows no secret.""" + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "execute", sql, params) + assert str(info.value) == Messages.get_formatted(UNSAFE, "users.ssn") + assert (info.value.table_name, info.value.column_name) == ("users", "ssn") + assert raw.calls == [] + assert raw not in plugin._results + assert env.keys.return_value.decrypt_data_key.call_count == 0 + _clean(info.value, *secrets) + + +@pytest.mark.parametrize("dialect, sql, as_list", [ + *(pytest.param(d, statement.format(condition), False, id=f"{d}-{kind}-{label}") + for label, dialects, condition in UNSAFE_CONDITIONS for kind, statement in UNSAFE_STATEMENTS.items() + for d in dialects), + *(pytest.param(d, sql, False, id=f"{d}-{label}") for label, dialects, sql in UNSAFE_SHAPES for d in dialects), + # A list has no exact stored form; the comparison is refused before the list reaches the encryption service. + pytest.param("pg", "SELECT id FROM users WHERE ssn <> ALL(%s)", True, id="pg-all-list")]) +def test_unsafe_comparison_refused(mocker, env, dialect, sql, as_list): + names = list(dict.fromkeys(re.findall(r"%\((\w+)\)s", sql))) + secrets = [marker() for _ in range(2 if as_list else len(names) or sql.count("%s"))] + if as_list: + params: Any = (secrets,) + elif names: + params = dict(zip(names, secrets)) + else: + params = tuple(secrets) + _refused_as_unsafe(mocker, env, dialect, sql, params, secrets) + + +@pytest.mark.parametrize("dialect, sql", [ + ("pg", "INSERT INTO users (name, ssn) SELECT name, ssn FROM users WHERE ssn <> %s"), + ("mysql", "INSERT INTO users (name, ssn) SELECT name, ssn FROM users WHERE ssn <> %s"), + ("mysql", "UPDATE users u JOIN orders o ON o.uid = u.id SET note = %s WHERE u.ssn <> %s"), + ("mysql", "UPDATE users u JOIN orders o ON o.uid = u.id SET note = %s WHERE ssn <> %s"), +], ids=["pg-insert-select", "mysql-insert-select", "mysql-multi-table-update", "mysql-multi-table-update-table-less"]) +def test_unsafe_comparison_in_passed_through_write_refused(mocker, env, caplog, dialect, sql): + # Each is a write the plugin can't fully analyze, which it would otherwise pass through with a warning. + params = tuple(marker() for _ in range(sql.count("%s"))) + with caplog.at_level(logging.DEBUG): + _refused_as_unsafe(mocker, env, dialect, sql, params, params) + assert plugin_records(caplog) == [] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql", [ + "SELECT id FROM users WHERE name <> /*@encrypt:users.ssn*/ %s", + "SELECT u.id FROM users u JOIN audit x ON x.id = u.id WHERE ssn <> /*@encrypt:users.ssn*/ %s", + "INSERT INTO users (name, ssn) SELECT name, ssn FROM users WHERE ssn <> /*@encrypt:users.name*/ %s", + "SELECT u.id FROM users u JOIN orders o ON o.uid = u.id WHERE ssn <> /*@encrypt:nowhere.ssn*/ %s", + "SELECT u.id FROM users u JOIN orders o ON o.uid = u.id WHERE u.ssn <> /*@encrypt:orders.note*/ %s", + "SELECT s.ssn FROM (SELECT id, ssn FROM users) s WHERE s.ssn <> /*@encrypt:users.name*/ %s", +], ids=["plain-column", "join", "gap-write-plain-annotation", "untrusted-annotation", "tied-compared-column", + "single-table-plain-annotation"]) +def test_unsafe_comparison_annotated_value_refused(mocker, env, dialect, sql): + # Refused when either the column the annotation names or the column compared is encrypted. + secret = marker() + _refused_as_unsafe(mocker, env, dialect, sql, (secret,), [secret]) + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql", [ + "SELECT u.id FROM users u JOIN archive a ON a.id = u.id WHERE ssn <> /*@encrypt:archive.ssn*/ %s", + "SELECT s.ssn FROM (SELECT id, ssn FROM archive) s JOIN users u ON u.id = s.id WHERE s.ssn <> /*@encrypt:archive.ssn*/ %s", + "WITH w AS (SELECT id, ssn FROM archive) SELECT w.ssn FROM w JOIN users u ON u.id = w.id " + "WHERE w.ssn <> /*@encrypt:archive.ssn*/ %s", + "SELECT u.id FROM users u JOIN orders o ON o.uid = u.id WHERE ssn <> /*@encrypt:orders.note*/ %s", + "SELECT u.id FROM users u JOIN orders o ON o.uid = u.id WHERE ssn <> /*@encrypt:users.snn*/ %s", +], ids=["unqualified", "derived", "cte", "wrong-column", "misspelled-column"]) +def test_trusted_annotation_unsafe_comparison_untied_column_runs(mocker, env, dialect, sql): + # An annotation that names a table the statement reads says which column the value is for (B-SQL-13, B-SQL-14). + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql, (secret,)) + assert raw.calls[0][1][1][0] is secret + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, key", [ + ("SELECT u.id FROM archive a JOIN users u ON u.id = a.id WHERE dob <> %s", UNSAFE), + ("SELECT u.id FROM archive a JOIN users u ON u.id = a.id WHERE dob = %s", NO_TABLE), +], ids=["unsafe", "unmapped"]) +def test_table_less_column_second_encrypted_table_refused(mocker, env, dialect, sql, key): + # archive comes first and has an encrypted column, but not dob, so the dob named without its table is users.dob. + env.configs = [ARCHIVE_SSN, SSN, DOB] + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + with pytest.raises(MetadataError) as info: + call(cur, "execute", sql, (secret,)) + assert str(info.value) == Messages.get_formatted(key, "users.dob") + assert raw.calls == [] + assert (info.value.table_name, info.value.column_name) == ("users", "dob") + _clean(info.value, secret) + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql", [ + "SELECT id FROM users WHERE name <> %s", + "DELETE FROM users WHERE id > %s", + "UPDATE users SET name = %s WHERE name <> %s AND id > %s", + "SELECT u.id FROM users u JOIN audit x ON x.id = u.id WHERE note <> %s", +], ids=["select", "delete", "update-two-comparisons", "join-table-less"]) +def test_unsafe_comparison_plain_column_runs(mocker, env, dialect, sql): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + params = tuple(marker() for _ in range(sql.count("%s"))) + call(cur, "execute", sql, params) + assert len(raw.calls) == 1 + assert raw.calls[0][1][0] is sql + assert raw.calls[0][1][1] is params + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, encrypted", [ + ("SELECT id FROM users WHERE ssn = %s", {0}), + ("SELECT id FROM users WHERE ssn IN (%s, %s)", {0, 1}), + ("SELECT id FROM users WHERE ssn LIKE %s", {0}), + ("WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w", {0}), + ("UPDATE users SET name = %s WHERE ssn = %s", {1}), + # With the opt-out, a write whose values come from a query is passed through, its compared value included. + ("INSERT INTO users (name, ssn) SELECT name, ssn FROM users WHERE ssn = %s", set()), +], ids=["eq", "in", "like", "cte", "update", "insert-select-passed-through"]) +def test_safe_comparison_is_still_encrypted(mocker, env, dialect, sql, encrypted): + plugin, _ = make_plugin(mocker, DIALECTS[dialect], encryption_fail_on_unmapped_parameter=False) + seen = spy_crypto(mocker, plugin) + cur, raw = cursor(plugin) + params = tuple(marker() for _ in range(sql.count("%s"))) + call(cur, "execute", sql, params) + sent = raw.calls[0][1][1] + assert [name for name, *_ in seen] == ["encrypt"] * len(encrypted) + for ordinal, value in enumerate(params): + if ordinal in encrypted: + assert EncryptionService.decrypt(sent[ordinal], DATA_KEY, HMAC_KEY) == value + else: + assert sent[ordinal] is value + + +class _Shade(enum.Enum): + DARK = "dark" + + +class _Level(enum.IntEnum): + HIGH = 3 + + +class _Color(str, enum.Enum): + RED = "red" + + +NO_EXACT_FORM: Dict[str, Callable[[str], Any]] = { + "uuid": lambda m: uuid.uuid4(), "dict": lambda m: {"ssn": m}, "list": lambda m: [m], "tuple": lambda m: (m,), + "ipv4": lambda m: ipaddress.IPv4Address("192.0.2.1"), "timedelta": lambda m: timedelta(days=1), + "enum": lambda m: _Shade.DARK, "jsonb": lambda m: Jsonb({"ssn": m}), "json": lambda m: Json([m]), + "psycopg-binary": lambda m: psycopg.Binary(m.encode())} + + +@pytest.mark.parametrize("dialect, sql", [ + ("pg", INSERT), ("mysql", INSERT), ("mysql", "SELECT id FROM users WHERE ssn = %s"), + ("pg", "SELECT id FROM users WHERE ssn = ANY(%s)"), +], ids=["pg-insert", "mysql-insert", "mysql-compare", "pg-any"]) +@pytest.mark.parametrize("kind", NO_EXACT_FORM) +def test_value_with_no_exact_stored_form_is_refused(mocker, env, dialect, sql, kind): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + value = NO_EXACT_FORM[kind](secret) + with pytest.raises(EncryptionFailedError) as info: + call(cur, "execute", sql, (value,)) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NoExactForm", "1", type(value).__name__, + "users.ssn") + assert info.value.data_type == "GENERIC" + assert raw.calls == [] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + _clean(info.value, secret) + + +@pytest.mark.parametrize("value", [lambda m: io.BytesIO(m.encode()), lambda m: (c for c in m)], ids=["stream", "generator"]) +@pytest.mark.parametrize("sql, params, parameter", [ + ("INSERT INTO users (name, ssn) VALUES (%s, %s)", lambda v: ("a", v), "2"), + ("INSERT INTO users (name, ssn) VALUES (%(name)s, %(ssn)s)", lambda v: {"name": "a", "ssn": v}, "ssn"), +], ids=["positional", "named"]) +def test_value_without_exact_form_refusal_names_parameter(plugin, sql, params, parameter, value): + cur, raw = cursor(plugin) + secret = marker() + bound = value(secret) + with pytest.raises(EncryptionFailedError) as info: + call(cur, "execute", sql, params(bound)) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NoExactForm", parameter, type(bound).__name__, + "users.ssn") + assert raw.calls == [] + _clean(info.value, secret) + + +def test_batch_refused_late_value_sends_nothing(plugin, env): + cur, raw = cursor(plugin) + with pytest.raises(EncryptionFailedError): + call(cur, "executemany", INSERT, [(marker(),), (marker(),), (uuid.uuid4(),)]) + assert raw.calls == [] + # Once per value sealed before it. + assert env.keys.return_value.decrypt_data_key.call_count == 2 + + +def test_lenient_mode_no_exact_form_refused(mocker, env): + # Lenient mode covers reads only. + plugin, _ = make_plugin(mocker, encryption_return_unverified_data=True) + cur, raw = cursor(plugin) + with pytest.raises(EncryptionFailedError) as info: + call(cur, "execute", INSERT, (uuid.uuid4(),)) + assert info.value.data_type == "GENERIC" + assert raw.calls == [] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +@pytest.mark.parametrize("value", [_Level.HIGH, Decimal("1.10"), _Color.RED, mysql.connector.Binary(b"test-bytes")], + ids=["intenum", "decimal", "str-enum", "mysql-binary"]) +def test_exact_form_values_encrypt(plugin, value): + cur, raw = cursor(plugin) + call(cur, "execute", INSERT, (value,)) + sent = raw.calls[0][1][1][0] + assert len(sent) >= 65 + assert EncryptionService.decrypt(sent, DATA_KEY, HMAC_KEY) == value + + +def test_stored_generic_payload_reads_back_as_text(plugin): + cur, raw = cursor(plugin) + value = uuid.uuid4() + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(value),)] + assert call(cur, "fetchall") == [(str(value),)] + + +@pytest.mark.parametrize("lenient", [False, True], ids=["strict", "lenient"]) +@pytest.mark.parametrize("kind", ["marker", "hex-text"]) +@pytest.mark.parametrize("read", ["fetchone", "fetchall", "iteration"]) +def test_non_binary_stored_value_not_payload(mocker, env, caplog, read, kind, lenient): + plugin, _ = make_plugin(mocker, encryption_return_unverified_data=lenient) + secret = marker() + # A text column holding a payload's hex. + stored = secret if kind == "marker" else "\\x" + payload(secret).hex() + cur, raw = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(stored,)] + fetch = (lambda: list(cur)) if read == "iteration" else (lambda: call(cur, read)) + with caplog.at_level(logging.DEBUG): + if lenient: + assert fetch() == ((stored,) if read == "fetchone" else [(stored,)]) + else: + with pytest.raises(IntegrityCheckError) as info: + fetch() + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NotAPayload", "users.ssn") + assert info.value.algorithm == SSN.algorithm + _clean(info.value, secret, stored) + assert env.keys.return_value.key_metadata_by_id.call_count == 0 + assert plugin_records(caplog) == [] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +@pytest.mark.parametrize("form", [bytearray, memoryview], ids=["bytearray", "memoryview"]) +def test_binary_stored_forms_decrypt(plugin, form): + # mysql-connector's C-extension prepared cursor returns bytearray for a binary column. + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(form(payload(secret)),)] + assert call(cur, "fetchall") == [(secret,)] + + +def test_int_stored_value_not_payload(plugin, env): + cur, raw = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + # Bytes(10**6) would be a megabyte of zeros. + raw.description, raw.rows = [("ssn",)], [(10 ** 6,)] + with pytest.raises(IntegrityCheckError) as info: + call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NotAPayload", "users.ssn") + assert env.keys.return_value.key_metadata_by_id.call_count == 0 + + +@pytest.mark.parametrize("dialect, conn, codec", [ + ("pg", SimpleNamespace(info=SimpleNamespace(encoding="iso8859-1")), "latin-1"), + # Utf8mb4 is no Python codec. + ("mysql", SimpleNamespace(python_charset="utf8", charset="utf8mb4"), "utf-8"), +], ids=["pg-latin1", "mysql-utf8mb4"]) +def test_bytes_sql_analyzed_in_connection_encoding(mocker, env, caplog, dialect, conn, codec): + plugin, service = make_plugin(mocker, DIALECTS[dialect]) + service.driver_dialect.get_connection_from_obj.return_value = conn + # Latin-1's 0xE9 isn't UTF-8; MySQL analyzes only ASCII bytes SQL. + literal = "caf\xe9" if dialect == "pg" else "cafe" + sql = f"INSERT INTO users (name, ssn) VALUES ('{literal}', %s)".encode(codec) + secret = marker() + cur, raw = cursor(plugin) + with caplog.at_level(logging.DEBUG): + call(cur, "execute", sql, (secret,)) + call(cur, "execute", SELECT.encode(codec), (1,)) + sent_sql, sent = raw.calls[0][1] + raw.description, raw.rows = [("ssn",)], [(sent[0],)] + assert call(cur, "fetchall") == [(secret,)] + # The driver gets the caller's bytes, with only _binary inserted on MySQL. + assert sent_sql is sql if dialect == "pg" else sent_sql == sql.replace(b"', %s", b"', _binary %s") + assert len(sent[0]) >= 65 + assert plugin_records(caplog) == [] + + +@pytest.mark.parametrize("dialect, conn, sql", [ + ("pg", SimpleNamespace(info=SimpleNamespace(encoding="utf-8")), None), # None: _undecodable's statement + ("pg", None, INSERT.encode()), + ("pg", SimpleNamespace(info=SimpleNamespace(encoding="shift_jis_2004")), b"UPDATE users SET ssn = %s WHERE name ~ '^O'"), + ("pg", SimpleNamespace(info=SimpleNamespace(encoding="big5")), b"INSERT INTO users (name, ssn) VALUES ('\xa1\xfe', %s)"), + ("mysql", SimpleNamespace(python_charset="utf8", charset="utf8mb4"), b"UPDATE users SET name = '\xc4\x81\x5c', ssn = %s"), + ("mysql", SimpleNamespace(python_charset="latin1", charset="latin1"), b"UPDATE users SET name = 'caf\xe9', ssn = %s"), + ("mysql", SimpleNamespace(python_charset="cp932", charset="cp932"), b"UPDATE users SET name = '\x93\xfa\x96{', ssn = %s"), +], ids=["undecodable", "no-connection", "shift-jis-2004", "not-reversible", "mysql-stale-charset", "mysql-latin1", + "mysql-cp932"]) +def test_bytes_sql_it_cannot_decode_refused_with_encrypted_columns(mocker, env, caplog, dialect, conn, sql): + # shift_jis_2004 reads 0x7E as an overline, where the server reads "~"; big5 re-encodes 0xA1FE as 0xA241. On MySQL any + # non-ASCII byte is enough: after SET NAMES sent as SQL the connection still reports the character set it negotiated, + # and sjis 0xC4 0x815C, read as UTF-8, is U+0101 and a backslash that escapes the closing quote. + plugin, service = make_plugin(mocker, DIALECTS[dialect]) + service.driver_dialect.get_connection_from_obj.return_value = conn + secret = marker() + sql = _undecodable(secret) if sql is None else sql + params = (secret,) if b"%s" in sql else None + cur, raw = cursor(plugin) + with caplog.at_level(logging.DEBUG): + with pytest.raises(MetadataError) as info: + call(cur, "execute", sql, params) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NotAnalysedRefused", "bytes") + assert raw.calls == [] + assert plugin_records(caplog) == [] + _clean(info.value, secret) + + +@pytest.mark.parametrize("configs, props, builds", [ + pytest.param([], {}, 1, id="no-encrypted-column"), + pytest.param([SSN], {"encryption_fail_on_unmapped_parameter": False}, 0, id="refusal-off"), +]) +def test_bytes_sql_it_cannot_decode_runs_unanalyzed(mocker, env, caplog, configs, props, builds): + env.configs = configs + plugin, service = make_plugin(mocker, **props) + service.driver_dialect.get_connection_from_obj.return_value = SimpleNamespace(info=SimpleNamespace(encoding="utf-8")) + secret = marker() + sql = _undecodable(secret) + cur, raw = cursor(plugin) + with caplog.at_level(logging.DEBUG): + for _ in range(2): + call(cur, "execute", sql) + warnings = [(r.levelno, r.getMessage()) for r in plugin_records(caplog)] + assert warnings == [(logging.WARNING, Messages.get_formatted("KmsEncryptionPlugin.NotAnalysed", "bytes"))] + assert [c[1][0] is sql for c in raw.calls] == [True, True] + assert _carrying(caplog, secret) == [] + assert env.metadata.call_count == builds + _plant_controls(secret) + assert len(_carrying(caplog, secret)) == 3 + + +@pytest.mark.parametrize("sql", [INSERT.encode(), "UPDATE users SET name = '\u0436', ssn = %s".encode("koi8_r")], + ids=["ascii", "non-ascii"]) +def test_bytes_sql_unknown_charset_raises(mocker, env, sql): + # The codec lookup comes before MySQL's ASCII check, so a non-ASCII statement raises too. + plugin, service = make_plugin(mocker, DriverDialectCodes.MYSQL_CONNECTOR_PYTHON) + service.driver_dialect.get_connection_from_obj.return_value = SimpleNamespace(python_charset="koi8r", charset="koi8r") + cur, raw = cursor(plugin) + # As mysql-connector itself raises for str SQL there. + with pytest.raises(LookupError) as info: + call(cur, "execute", sql, (marker(),)) + assert raw.calls == [] + assert info.value.__cause__ is None + assert info.value.__context__ is None + + +MYSQL_INSERT = "INSERT INTO users (name, ssn, dob) VALUES (%s, %s, %s)" + + +@pytest.mark.parametrize("form", ["positional", "operation"]) +@pytest.mark.parametrize("method", ["execute", "executemany"]) +def test_mysql_binary_prefix_goes_before_encrypted_placeholders(mocker, env, method, form): + plugin, _ = make_plugin(mocker, DriverDialectCodes.MYSQL_CONNECTOR_PYTHON) + cur, raw = cursor(plugin) + sets = [("test-name", marker(), marker()) for _ in range(3)] + params = sets if method == "executemany" else sets[0] + snapshot = list(sets) + slot = "seq_params" if method == "executemany" else "params" + if form == "positional": + call(cur, method, MYSQL_INSERT, params) + else: + call(cur, method, operation=MYSQL_INSERT, **{slot: params}) + _, args, kwargs = raw.calls[0] + sent_sql, sent = args if form == "positional" else (kwargs["operation"], kwargs[slot]) + assert sent_sql == "INSERT INTO users (name, ssn, dob) VALUES (%s, _binary %s, _binary %s)" + assert sets == snapshot + for row, sent_row in zip(sets, sent if method == "executemany" else [sent]): + assert sent_row[0] == "test-name" + assert [EncryptionService.decrypt(v, DATA_KEY, HMAC_KEY) for v in sent_row[1:]] == list(row[1:]) + + +_BINARY_PREFIX_CASES = [ + pytest.param("mysql", FakeDriverCursor, INSERT, True, id="none"), + # As Django's BinaryField. + pytest.param("mysql", FakeDriverCursor, "INSERT INTO users (ssn) VALUES (_binary %s)", False, id="introducer"), + pytest.param("mysql", _posing_as(mysql_cursor.MySQLCursorPrepared), INSERT, False, id="MySQLCursorPrepared"), + pytest.param("mysql", _posing_as(mysql_cursor.MySQLCursorPreparedDict), INSERT, False, id="MySQLCursorPreparedDict"), +] +if CMYSQL_ENABLED: + _BINARY_PREFIX_CASES += [ + pytest.param("mysql", _posing_as(CMySQLCursorPrepared), INSERT, False, id="CMySQLCursorPrepared"), + pytest.param("mysql", _posing_as(CMySQLCursorPreparedDict), INSERT, False, id="CMySQLCursorPreparedDict"), + ] +_BINARY_PREFIX_CASES.append(pytest.param("pg", FakeDriverCursor, INSERT, False, id="pg")) + + +@pytest.mark.parametrize("dialect, cls, sql, null", _BINARY_PREFIX_CASES) +def test_mysql_binary_prefix_is_left_out(mocker, env, dialect, cls, sql, null): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin, cls()) + secret = marker() + call(cur, "execute", sql, (None if null else secret,)) + sent_sql, sent = raw.calls[0][1] + assert sent_sql is sql + assert sent == (None,) if null else EncryptionService.decrypt(sent[0], DATA_KEY, HMAC_KEY) == secret + + +@pytest.mark.parametrize("named", [False, True], ids=["positional", "named"]) +def test_mysql_binary_prefix_none_in_any_set_left_out(mocker, env, named): + plugin, _ = make_plugin(mocker, DriverDialectCodes.MYSQL_CONNECTOR_PYTHON) + cur, raw = cursor(plugin) + sql = "INSERT INTO users (ssn, dob) VALUES (%(s)s, %(d)s)" if named else "INSERT INTO users (ssn, dob) VALUES (%s, %s)" + # Every set shares one SQL text. + rows = [(marker(), marker()), (None, marker()), (marker(), marker())] + call(cur, "executemany", sql, [{"s": s, "d": d} for s, d in rows] if named else rows) + sent_sql, sent = raw.calls[0][1] + assert sent_sql == sql.replace(", %", ", _binary %") + assert (sent[1]["s"] if named else sent[1][0]) is None + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, names, at", [ + ("SELECT ssn AS s FROM users", ["s"], 0), + ("SELECT users.id AS users_id, users.ssn AS users_ssn FROM users WHERE users.id = %(pk_1)s", ["users_id", "users_ssn"], 1), + # By name: the result columns aren't known. + ("SELECT * FROM users", ["id", "name", "ssn"], 2), + # A table that declares the column in another case. + ("SELECT * FROM users", ["id", "name", "SSN"], 2), +], ids=["alias", "legacy-query", "star", "star-other-case"]) +def test_reads_decrypt_by_position_or_unique_name(mocker, env, dialect, sql, names, at): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql, {"pk_1": 1} if "%(" in sql else None) + row = [f"test-{n}" for n in names] + expected = tuple(row[:at] + [secret] + row[at + 1:]) + row[at] = payload(secret) + raw.description, raw.rows = [(n,) for n in names], [tuple(row)] + assert call(cur, "fetchall") == [expected] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +def test_star_column_in_other_case_decrypts(mocker, env, dialect): + # A quoted "SSN" on PostgreSQL, or registered as SSN on MySQL. + env.configs = [replace(SSN, column_name="SSN")] + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", "SELECT * FROM users", None) + raw.description, raw.rows = [("id",), ("SSN",)], [(1, payload(secret))] + assert call(cur, "fetchall") == [(1, secret)] + + +@pytest.mark.parametrize("sql, registered", [ + pytest.param("SELECT ssn FROM USERS WHERE id = %s", "ssn", id="table-case"), + pytest.param("SELECT SSN FROM users WHERE id = %s", "ssn", id="column-case"), + pytest.param("SELECT ssn FROM users WHERE id = %s", "SSN", id="registered-case"), +]) +def test_mysql_known_column_named_in_another_letter_case_decrypts(mocker, env, sql, registered): + # The analysis keeps MySQL names as written and the metadata matches them in any letter case, so the + # configurations kept at execute are found by metadata key. + env.configs = [replace(SSN, column_name=registered)] + plugin, _ = make_plugin(mocker, DriverDialectCodes.MYSQL_CONNECTOR_PYTHON) + cur, raw = cursor(plugin) + call(cur, "execute", sql, (1,)) + secret = marker() + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + assert call(cur, "fetchall") == [(secret,)] + + +@pytest.mark.parametrize("second", ["ssn", "SSN"]) +@pytest.mark.parametrize("configs", [[SSN], [SSN, ARCHIVE_SSN]], ids=["one-encrypted", "both-encrypted"]) +def test_shared_column_name_under_select_star_refused(mocker, env, configs, second): + # MySQL reports a column's name as its table declares it, and PostgreSQL a quoted name's case. + env.configs = configs + plugin, _ = make_plugin(mocker) + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT * FROM users u JOIN archive a ON a.id = u.id WHERE u.id = %s", (1,)) + raw.description, raw.rows = [("id",), ("ssn",), ("id",), (second,)], [(1, payload(marker()), 1, payload(marker()))] + with pytest.raises(MetadataError) as info: + call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", "ssn") + assert raw.fetches == 0 + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +def test_column_name_of_two_encrypted_tables_refused(mocker, env): + env.configs = [SSN, ARCHIVE_SSN] + plugin, _ = make_plugin(mocker) + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT ssn FROM users UNION SELECT ssn FROM archive") + raw.description, raw.rows = [("ssn",)], [(payload(marker()),)] + with pytest.raises(MetadataError): + call(cur, "fetchall") + assert raw.fetches == 0 + + +def test_star_over_one_table_name_in_two_schemas_decrypts_by_name(plugin): + # The metadata names a table without its schema, so a.users and b.users share users.ssn's configuration, and the + # result's one ssn column is that column. + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT * FROM a.users WHERE id IN (SELECT id FROM b.users)", None) + secret = marker() + raw.description, raw.rows = [("id",), ("ssn",)], [(1, payload(secret))] + assert call(cur, "fetchall") == [(1, secret)] + + +def test_broken_iteration_resumes_and_decrypts_each_value_once(plugin, env): + cur, raw = cursor(plugin) + secrets = [marker() for _ in range(3)] + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(s),) for s in secrets] + for row in cur: + assert row == (secrets[0],) + break + assert list(cur) == [(s,) for s in secrets[1:]] + assert env.keys.return_value.decrypt_data_key.call_count == 3 + + +def test_composable_insert_encrypted_sent_as_object(plugin): + cur, raw = cursor(plugin) + sql = pg_sql.SQL("INSERT INTO {} (ssn) VALUES (%s)").format(pg_sql.Identifier("users")) + secret = marker() + call(cur, "execute", sql, (secret,)) + sent_sql, sent = raw.calls[0][1] + assert sent_sql is sql + assert EncryptionService.decrypt(sent[0], DATA_KEY, HMAC_KEY) == secret + + +@pytest.mark.parametrize("read", ["fetchone", "fetchmany", "fetchall", "iterate"]) +def test_later_result_set_not_decoded_with_first_mapping(plugin, env, read): + cur, raw = cursor(plugin) + secret, name = marker(), marker() + call(cur, "execute", "SELECT ssn FROM users; SELECT name FROM users") + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + raw.sets = [([("name",)], [(name,)])] + # Matched by name: a multi-statement string has no result columns. + assert _read_rows(cur, read, 1) == [(secret,)] + assert call(cur, "nextset") is True + assert _read_rows(cur, read, 1) == [(name,)] + assert call(cur, "nextset") is None + assert env.keys.return_value.decrypt_data_key.call_count == 1 + + +@pytest.mark.parametrize("sql", [ + "SELECT ssn FROM users; SELECT name, ssn FROM users", + "SELECT ssn FROM users; SELECT name, ssn FROM plain_t", + "SELECT ssn FROM users; SELECT name FROM users; SELECT name, ssn FROM users", +], ids=["same-table", "plain-table", "third-set"]) +def test_later_result_set_with_encrypted_name_refused(plugin, env, sql): + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql) + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + raw.sets = [([("name",)], [(marker(),)]) for _ in range(sql.count(";") - 1)] + raw.sets.append(([("name",), ("ssn",)], [(marker(), payload(marker()))])) + assert call(cur, "fetchall") == [(secret,)] + while raw.sets: + assert call(cur, "nextset") is True + fetches = raw.fetches + # The plugin can't tell which statement produced the set. + with pytest.raises(MetadataError) as info: + call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", "ssn") + assert raw.fetches == fetches + assert env.keys.return_value.decrypt_data_key.call_count == 1 + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql", [ + "WITH RECURSIVE a AS (SELECT id, ssn FROM users), users AS (SELECT id, ssn FROM a) SELECT ssn FROM users", + "WITH users AS (SELECT 1 AS x) INSERT INTO users (ssn) VALUES (%s)", + "WITH users AS (SELECT 1 AS x) UPDATE users SET ssn = %s", + "WITH users AS (SELECT 1 AS x) DELETE FROM users WHERE ssn = %s", + "WITH users AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM users", +], ids=["recursive-read", "insert-target", "update-target", "delete-target", "self-reference"]) +def test_cte_named_like_encrypted_table_refused(mocker, env, dialect, sql): + _refused_unread(mocker, dialect, sql, "KmsEncryptionPlugin.CteShadowsTable") + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +def test_nextset_at_last_set_keeps_decoding(plugin): + cur, raw = cursor(plugin) + secrets = [marker(), marker()] + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(s),) for s in secrets] + assert call(cur, "fetchone") == (secrets[0],) + # Psycopg stays on its last set, so its other rows are still to read. + assert call(cur, "nextset") is None + assert call(cur, "fetchall") == [(secrets[1],)] + + +def test_executemany_result_sets_are_each_decrypted(plugin): + cur, raw = cursor(plugin) + secrets = [marker() for _ in range(3)] + call(cur, "executemany", "INSERT INTO users (ssn) VALUES (%s) RETURNING ssn", [(s,) for s in secrets], returning=True) + stored = [payload(s) for s in secrets] + raw.description, raw.rows = [("ssn",)], [(stored[0],)] + raw.sets = [([("ssn",)], [(value,)]) for value in stored[1:]] + rows = [call(cur, "fetchone")] + while call(cur, "nextset"): + rows.append(call(cur, "fetchone")) + # Psycopg's executemany(..., returning=True): one set per parameter set. + assert rows == [(s,) for s in secrets] + + +def test_executemany_later_set_matched_by_own_columns(plugin): + # mysql-connector runs such a string through execute() for its one parameter set, and nextset() moves to the next + # statement's set, whose columns differ from the first set's. + cur, raw = cursor(plugin) + secret, name, inner = marker(), marker(), marker() + call(cur, "executemany", "SELECT ssn FROM users WHERE id = %s; SELECT name, ssn FROM users WHERE id = %s", [(1, 1)]) + raw.description, raw.rows = [("ssn",)], [(payload(secret),)] + raw.sets = [([("name",), ("ssn",)], [(name, payload(inner))])] + assert call(cur, "fetchall") == [(secret,)] + assert call(cur, "nextset") is True + # Matched by name in the set's own columns, as the first set is. + assert call(cur, "fetchall") == [(name, inner)] + + +# No table with an encrypted column: nothing remembered. +@pytest.mark.parametrize("sql", ["SELECT name FROM accounts; SELECT ssn FROM accounts"], ids=["plain-tables"]) +def test_nextset_with_no_remembered_result_moves_and_decodes_nothing(plugin, sql): + cur, raw = cursor(plugin) + stored = payload(marker()) + call(cur, "execute", sql) + raw.description, raw.rows = [("name",)], [(marker(),)] + raw.sets = [([("name",)], [(marker(),)]) for _ in range(sql.count(";") - 1)] + [([("ssn",)], [(stored,)])] + call(cur, "fetchall") + while raw.sets: + assert call(cur, "nextset") is True + rows = call(cur, "fetchall") + assert rows == [(stored,)] + # As the driver returned it. + assert rows[0][0] is stored + + +def test_nextset_raises_keeps_mapping(mocker, plugin): + cur, raw = cursor(plugin) + secrets = [marker(), marker()] + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(payload(s),) for s in secrets] + assert call(cur, "fetchone") == (secrets[0],) + # As mysql-connector's pure build raises while the current set has unread rows; it stays on that set. + mocker.patch.object(raw, "nextset", side_effect=mysql.connector.InternalError("Unread result found")) + with pytest.raises(mysql.connector.InternalError): + call(cur, "nextset") + # The driver didn't move to another set. + assert call(cur, "fetchall") == [(secrets[1],)] + + +@pytest.mark.parametrize("setting", [True, False, None, "False", "true"], + ids=["True", "False", "unset", "url-False", "url-true"]) +def test_audit_logging_warns_once_at_creation(mocker, env, caplog, setting): + props = {} if setting is None else {"encryption_audit_logging_enabled": setting} + warns = setting in (True, "true") + expected = [(logging.WARNING, Messages.get("KmsEncryptionPlugin.AuditNotWritten"))] if warns else [] + with caplog.at_level(logging.DEBUG): + plugin, _ = make_plugin(mocker, **props) + assert [(r.levelno, r.getMessage()) for r in plugin_records(caplog)] == expected + cur, _ = cursor(plugin) + call(cur, "execute", INSERT, (marker(),)) + # Nothing more at the first statement. + assert len(plugin_records(caplog)) == len(expected) + + +def _handed_out_keys(env: Any) -> List[bytearray]: + """Record every data key the key manager hands out.""" + handed: List[bytearray] = [] + + def decrypt(edk: Any, arn: Any) -> bytearray: + handed.append(bytearray(DATA_KEY)) + return handed[-1] + env.keys.return_value.decrypt_data_key.side_effect = decrypt + return handed + + +@pytest.mark.parametrize("method", ["execute", "executemany"]) +def test_cache_off_decrypts_each_data_key_once_per_execute(mocker, env, method): + handed = _handed_out_keys(env) + plugin, _ = make_plugin(mocker, encryption_data_key_cache_enabled=False) + cur, raw = cursor(plugin) + sql = "INSERT INTO users (name, ssn) VALUES (%s, %s)" if method == "executemany" else \ + "INSERT INTO users (ssn) VALUES (%s), (%s), (%s)" + params: Any = [(marker(), marker()) for _ in range(3)] if method == "executemany" else (marker(), marker(), marker()) + call(cur, method, sql, params) + assert env.keys.return_value.decrypt_data_key.call_count == 1 + assert handed[0] == bytearray(len(DATA_KEY)) + + +@pytest.mark.parametrize("method", ["fetchall", "fetchmany", "fetchone", "__next__"]) +def test_cache_off_decrypts_each_data_key_once_per_fetch_call(mocker, env, method): + handed = _handed_out_keys(env) + env.configs = [SSN, replace(DOB, key_metadata=replace(KEY_ROW, id=8, encrypted_data_key="ZWRrMg=="))] + plugin, _ = make_plugin(mocker, encryption_data_key_cache_enabled=False) + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT ssn, dob FROM users WHERE id = %s", (1,)) + secrets = [marker() for _ in range(3)] + raw.description = [("ssn",), ("dob",)] + raw.rows = [(payload(s), payload(s, key_id=8)) for s in secrets] + raw.arraysize = 3 + rows = [call(cur, method)] if method in ("fetchone", "__next__") else call(cur, method) + assert rows[0] == (secrets[0], secrets[0]) + # One data key per key row: ssn's and dob's. + assert env.keys.return_value.decrypt_data_key.call_count == 2 + assert all(k == bytearray(len(DATA_KEY)) for k in handed) + + +def test_cache_off_keys_wiped_on_decrypt_failure(mocker, env): + handed = _handed_out_keys(env) + env.configs = [SSN, replace(DOB, key_metadata=replace(KEY_ROW, id=8, encrypted_data_key="ZWRrMg=="))] + plugin, _ = make_plugin(mocker, encryption_data_key_cache_enabled=False) + decrypt = env.keys.return_value.decrypt_data_key.side_effect + env.keys.return_value.decrypt_data_key.side_effect = [decrypt(None, None), errors.EncryptionFailedError("kms")] + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT ssn, dob FROM users WHERE id = %s", (1,)) + raw.description, raw.rows = [("ssn",), ("dob",)], [(payload(marker()), payload(marker(), key_id=8))] + with pytest.raises(EncryptionFailedError): + call(cur, "fetchall") + assert handed[0] == bytearray(len(DATA_KEY)) + + +def test_cache_off_loop_decodes_every_row(mocker, env): + plugin, _ = make_plugin(mocker, encryption_data_key_cache_enabled=False) + cur, raw = cursor(plugin) + call(cur, "execute", SELECT, (1,)) + secrets = [marker() for _ in range(3)] + raw.description, raw.rows = [("ssn",)], [(payload(s),) for s in secrets] + assert list(cur) == [(s,) for s in secrets] + + +@pytest.mark.parametrize("setting, enabled", [("False", False), ("true", True)], ids=["url-False", "url-true"]) +def test_data_key_cache_enabled_string_setting(mocker, env, setting, enabled): + plugin, _ = make_plugin(mocker, encryption_data_key_cache_enabled=setting) + cur, _ = cursor(plugin) + call(cur, "execute", INSERT, (marker(),)) + assert env.cache.call_args.kwargs["enabled"] is enabled + + +@pytest.mark.parametrize("dialect, chain", [("pg", WrapperProperties.DEFAULT_PLUGINS), + ("mysql", WrapperProperties.MYSQL_CONNECTOR_DEFAULT_PLUGINS)], + ids=["pg", "mysql"]) +def test_default_chain_logs_no_bound_value(mocker, env, caplog, dialect, chain): + # The plugins before kms_encryption get the caller's values, the plugins after it and the driver the payloads. + conn, raw = _chain(f"{chain},kms_encryption,execute_time", DIALECTS[dialect]) + secret = marker() + with caplog.at_level(logging.DEBUG): + conn.cursor().execute(INSERT, (secret,)) + assert len(raw.calls[0][1][1][0]) >= 65 + assert any(r.getMessage().startswith("[ExecuteTimePlugin] Executed") for r in caplog.records) + assert _carrying(caplog, secret) == [] + _plant_controls(secret) + assert len(_carrying(caplog, secret)) == 3 + + +@pytest.mark.parametrize("arm, calls", [("write", 2), ("write-raises", 1), ("read", 2), ("read-tampered", 1)], + ids=["write", "write-raises", "read", "read-tampered"]) +def test_key_copies_are_wiped_after_each_value(mocker, env, arm, calls): + plugin, _ = make_plugin(mocker) + cur, raw = cursor(plugin) + stored = [payload(marker()) for _ in range(calls)] + if arm == "read-tampered": + stored[0] = stored[0][:-1] + bytes([stored[0][-1] ^ 1]) + seen = spy_crypto(mocker, plugin) + if arm == "write": + call(cur, "executemany", INSERT, [(marker(),), (marker(),)]) + elif arm == "write-raises": + with pytest.raises(EncryptionFailedError): # raised inside EncryptionService.encrypt + call(cur, "execute", INSERT, (2 ** 70,)) + else: + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(s,) for s in stored] + if arm == "read": + call(cur, "fetchall") + else: + with pytest.raises(IntegrityCheckError): + call(cur, "fetchall") + assert [s[0] for s in seen] == ["encrypt" if arm.startswith("write") else "decrypt"] * calls + for _, data_key, hmac_key, size, algorithm in seen: + assert type(data_key) is bytearray + assert type(hmac_key) is bytearray + assert (size, algorithm) == (32, SSN.algorithm) + assert not any(data_key) + assert not any(hmac_key) + # A fresh data-key copy for each value. + assert len({id(s[1]) for s in seen}) == calls + + +def test_aes_128_gcm_round_trip_16_byte_key(mocker, env): + env.configs = [replace(SSN, algorithm="AES-128-GCM", key_metadata=replace(KEY_ROW, key_spec="AES_128"))] + env.keys.return_value.decrypt_data_key.side_effect = lambda edk, arn: bytearray(DATA_KEY[:16]) + plugin, _ = make_plugin(mocker) + seen = spy_crypto(mocker, plugin) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", INSERT, (secret,)) + stored = raw.calls[0][1][1][0] + call(cur, "execute", SELECT, (1,)) + raw.description, raw.rows = [("ssn",)], [(stored,)] + assert len(stored) >= 65 + assert call(cur, "fetchall") == [(secret,)] + assert [(s[0], s[3], s[4]) for s in seen] == [("encrypt", 16, "AES-128-GCM"), ("decrypt", 16, "AES-128-GCM")] + + +def test_open_without_key_manager_raises_metadata_error(plugin): + plugin._keys = None + with pytest.raises(MetadataError): + plugin._open(payload(marker()), SSN, None) + + +def test_seal_without_key_manager_raises_metadata_error(plugin): + plugin._keys = None + with pytest.raises(MetadataError): + plugin._seal(marker(), SSN, 0, None) + + +def test_unbound_write_message_quotes_column(plugin): + cur, _ = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "execute", "INSERT INTO users (ssn) VALUES ('123-45-6789')") + assert "'users.ssn'" in str(info.value) + + +def test_metadata_table_name_control_characters_replaced_in_message(env, plugin): + env.configs = [ColumnEncryptionConfig("users\x1b[2J", "s\u200bsn\u0378", key_id=7, key_metadata=KEY_ROW)] + cur, _ = cursor(plugin) + with pytest.raises(MetadataError) as info: + call(cur, "execute", 'INSERT INTO "users\x1b[2J" ("s\u200bsn\u0378") VALUES (\'123-45-6789\')') + assert "'users?[2J.s?sn?'" in str(info.value) + + +def test_callproc_with_args_refused_with_encrypted_columns(plugin): + cur, raw = cursor(plugin) + raw.callproc = MagicMock(return_value=()) + secret = marker() + with pytest.raises(MetadataError) as info: + cur.callproc("sp", (secret,)) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.CallprocRefused", "Cursor.callproc") + raw.callproc.assert_not_called() + _clean(info.value, secret) + + +@pytest.mark.parametrize("configs, props, args", [ + pytest.param([SSN], {}, (), id="no-arguments"), + pytest.param([], {}, (1,), id="no-encrypted-column"), + pytest.param([SSN], {"encryption_fail_on_unmapped_parameter": False}, (1,), id="refusal-off"), +]) +def test_callproc_runs_when_nothing_to_refuse(mocker, env, configs, props, args): + env.configs = configs + plugin, _ = make_plugin(mocker, **props) + cur, raw = cursor(plugin) + raw.callproc = MagicMock(return_value=args) + assert cur.callproc("sp", args) == args + raw.callproc.assert_called_once_with("sp", args) + + +def test_stream_refused_while_plugin_enabled(plugin): + cur, raw = cursor(plugin) + raw.description, raw.rows = [("ssn",)], [(payload("123-45-6789"),)] + with pytest.raises(MetadataError, match="'Cursor.stream'"): + cur.stream("SELECT ssn FROM users") + assert raw.calls == [] + + +@pytest.mark.parametrize("method, args", [ + ("results", ()), ("set_result", (0,)), ("fetchsets", ()), ("stored_results", ())]) +def test_unwrapped_result_set_methods_refused_while_plugin_enabled(plugin, method, args): + cur, raw = cursor(plugin) + with pytest.raises(MetadataError, match=f"'Cursor.{method}'"): + getattr(cur, method)(*args) + assert raw.calls == [] + + +def test_sql_it_cannot_analyze_refused_with_encrypted_columns(plugin, caplog): + cur, raw = cursor(plugin) + secret = marker() + with caplog.at_level(logging.DEBUG): + with pytest.raises(MetadataError) as info: + call(cur, "execute", _OpaqueSql(f"INSERT INTO users (ssn) VALUES ('{secret}')")) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NotAnalysedRefused", "_OpaqueSql") + assert raw.calls == [] + assert plugin_records(caplog) == [] + _clean(info.value, secret) + + +def test_sql_it_cannot_analyze_refused_with_metadata_cache_off(mocker, env): + plugin, _ = _cache_off_plugin(mocker) + mocker.patch.object(_MetadataCursor, "configs", ()) + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT 1") + # Registered after the connection's first statement, so only a fresh read of the metadata tables finds it. + mocker.patch.object(_MetadataCursor, "configs", (SSN,)) + with pytest.raises(MetadataError) as info: + call(cur, "executemany", _OpaqueSql(INSERT), [(marker(),)]) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.NotAnalysedRefused", "_OpaqueSql") + assert raw.calls == [("execute", ("SELECT 1",), {})] + + +@pytest.mark.parametrize("refusal", [True, False], ids=["refusal-on", "refusal-off"]) +@pytest.mark.parametrize("opaque", [False, True], ids=["bytes", "sql-object"]) +def test_copy_sql_it_cannot_decode_refused_with_option_off(mocker, env, refusal, opaque): + plugin, service = make_plugin(mocker, encryption_fail_on_unmapped_parameter=refusal) + service.driver_dialect.get_connection_from_obj.return_value = SimpleNamespace(info=SimpleNamespace(encoding="utf-8")) + cur, raw = cursor(plugin) + sql = _OpaqueSql("COPY users (ssn) FROM STDIN") if opaque else _undecodable(marker()) + with pytest.raises(MetadataError) as info: + call(cur, "copy", sql) + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.CopyNotAnalysed", type(sql).__name__) + assert raw.calls == [] + + +def test_metadata_load_failure_refuses_unanalyzed_statement(mocker, env): + plugin, _ = _cache_off_plugin(mocker) + mocker.patch.object(_MetadataCursor, "execute", side_effect=RuntimeError("db down")) + cur, raw = cursor(plugin) + with pytest.raises(MetadataError, match="RuntimeError"): + call(cur, "execute", _OpaqueSql(INSERT), (marker(),)) + assert raw.calls == [] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql", ["SELECT x FROM (SELECT ssn FROM users) AS t(x)", + "WITH c(x) AS (SELECT ssn FROM users) SELECT x FROM c"], ids=["derived", "cte"]) +def test_derived_table_column_list_decrypts(mocker, env, dialect, sql): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql) + raw.description, raw.rows = [("x",)], [(payload(secret),)] + assert call(cur, "fetchall") == [(secret,)] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, names", [ + ("SELECT *, ssn AS x FROM users", ["id", "ssn", "x"]), + ("SELECT ssn AS x, * FROM users", ["x", "id", "ssn"]), +], ids=["after-star", "before-star"]) +def test_alias_beside_select_star_decrypts(mocker, env, dialect, sql, names): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql) + raw.description = [(n,) for n in names] + raw.rows = [tuple(1 if n == "id" else payload(secret) for n in names)] + assert call(cur, "fetchall") == [tuple(1 if n == "id" else secret for n in names)] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("select", ["ssn, name", "*"], ids=["listed", "star"]) +def test_swapped_cte_column_list_decrypts_or_raises(mocker, env, dialect, select): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", f"WITH c(ssn, name) AS (SELECT name, ssn FROM users) SELECT {select} FROM c") + raw.description, raw.rows = [("ssn",), ("name",)], [("Ann", payload(secret))] + assert call(cur, "fetchall") == [("Ann", secret)] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +def test_star_over_renaming_derived_table_decrypts(mocker, env, dialect): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", "SELECT * FROM (SELECT ssn AS x FROM users) s") + raw.description, raw.rows = [("x",)], [(payload(secret),)] + assert call(cur, "fetchall") == [(secret,)] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, names", [ + ("SELECT name AS ssn FROM users", ["ssn"]), + ("SELECT *, name AS x FROM users", ["id", "x"]), + ("SELECT * FROM (SELECT name AS ssn FROM users) s", ["ssn"]), +], ids=["alias-of-plain", "plain-beside-star", "star-over-plain-alias"]) +def test_renamed_plain_column_returned_as_is(mocker, env, dialect, sql, names): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + call(cur, "execute", sql) + raw.description, raw.rows = [(n,) for n in names], [tuple(f"plain-{n}" for n in names)] + assert call(cur, "fetchall") == [tuple(f"plain-{n}" for n in names)] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +def test_name_from_encrypted_and_plain_derived_tables_refused(mocker, env, dialect): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + call(cur, "execute", "SELECT * FROM (SELECT ssn AS x FROM users) a JOIN (SELECT name AS x FROM people) b ON TRUE") + raw.description, raw.rows = [("x",), ("x",)], [(payload(marker()), "plain")] + with pytest.raises(MetadataError) as info: + call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", "x") + assert raw.fetches == 0 + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, names", [ + ("SELECT u.*, d.y FROM users u JOIN (SELECT name AS ssn, name AS y FROM people) d ON TRUE", ["id", "ssn", "y"]), + ("WITH r AS (SELECT id, ssn FROM people) SELECT u.* FROM users u JOIN r ON r.id = u.id", ["id", "ssn"]), + ("SELECT u.*, d.id FROM users u JOIN (SELECT id, name AS ssn FROM plain) d ON u.id = d.id", ["id", "ssn", "id"]), + ("WITH d AS (SELECT id, name AS ssn FROM plain) SELECT users.* FROM users JOIN d ON users.id = d.id", + ["id", "ssn"]), + ("SELECT u.* FROM users u JOIN (SELECT name AS ssn FROM users) d ON d.ssn = u.name", ["id", "ssn"]), + ("WITH d AS (SELECT name AS ssn FROM users) SELECT u.* FROM users u JOIN d ON d.ssn = u.name", ["id", "ssn"]), +], ids=["derived-beside-qualified-star", "cte-joined-to-filter", "derived-joined-on-id", "cte-beside-table-star", + "derived-joined-on-name", "cte-joined-on-name"]) +def test_star_over_table_joined_to_derived_source_decrypts(mocker, env, dialect, sql, names): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql) + raw.description = [(n,) for n in names] + raw.rows = [tuple(payload(secret) if n == "ssn" else f"plain-{n}" for n in names)] + assert call(cur, "fetchall") == [tuple(secret if n == "ssn" else f"plain-{n}" for n in names)] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql", [ + "SELECT 'lit' AS x FROM (SELECT ssn AS x FROM users) t", + "SELECT 'lit' AS x FROM users JOIN (SELECT ssn AS x FROM users) t ON TRUE", +], ids=["derived", "table-and-derived"]) +def test_literal_named_like_derived_item_returned_as_is(mocker, env, dialect, sql): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + call(cur, "execute", sql) + raw.description, raw.rows = [("x",)], [("lit",)] + assert call(cur, "fetchall") == [("lit",)] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, name", [ + ("SELECT y FROM (SELECT name AS x FROM people) b JOIN (SELECT ssn AS y FROM users) a ON TRUE", "y"), + ("SELECT y AS z FROM (SELECT name AS x FROM people) b JOIN (SELECT ssn AS y FROM users) a ON TRUE", "z"), +], ids=["column", "aliased-column"]) +def test_column_read_from_one_of_two_derived_tables_decrypts(mocker, env, dialect, sql, name): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", sql) + raw.description, raw.rows = [(name,)], [(payload(secret),)] + assert call(cur, "fetchall") == [(secret,)] + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, names", [ + ("SELECT * FROM users u LEFT JOIN (SELECT id, photo AS ssn FROM people) d USING (ssn)", ["ssn", "id", "id"]), + ("SELECT ssn FROM users u LEFT JOIN (SELECT id, photo AS ssn FROM people) d USING (ssn)", ["ssn"]), +], ids=["star", "column"]) +def test_table_merged_with_plain_derived_column_refused(mocker, env, dialect, sql, names): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + call(cur, "execute", sql) + raw.description, raw.rows = [(n,) for n in names], [tuple(payload(marker()) if n == "ssn" else 1 for n in names)] + with pytest.raises(MetadataError) as info: + call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", "ssn") + assert raw.fetches == 0 + + +_DERIVED_STAR_MERGES = [ + ("derived-star-left-using", + "SELECT * FROM (SELECT * FROM users) s LEFT JOIN (SELECT id, photo AS ssn FROM people) d USING (ssn)", + ["ssn", "id", "id"]), + ("derived-star-column", + "SELECT ssn FROM (SELECT * FROM users) s LEFT JOIN (SELECT id, photo AS ssn FROM people) d USING (ssn)", + ["ssn"]), + ("derived-star-natural-left", + "SELECT * FROM (SELECT * FROM users) s NATURAL LEFT JOIN (SELECT id, photo AS ssn FROM people) d", ["id", "ssn"]), + ("cte-star-natural-left", + "WITH s AS (SELECT * FROM users) SELECT * FROM s NATURAL LEFT JOIN (SELECT id, photo AS ssn FROM people) d", + ["id", "ssn"]), + ("qualified-star-right-using", + "SELECT * FROM (SELECT id, photo AS ssn FROM people) a RIGHT JOIN (SELECT u.* FROM users u) b USING (ssn)", + ["ssn", "id", "id"]), + ("column-list-left-using", + "SELECT * FROM (SELECT * FROM users) AS s(k, ssn) LEFT JOIN (SELECT id, photo AS ssn FROM people) d USING (ssn)", + ["ssn", "k", "id"]), +] + + +@pytest.mark.parametrize("dialect, sql, names", [ + *(pytest.param(dialect, sql, names, id=f"{shape}-{dialect}") + for shape, sql, names in _DERIVED_STAR_MERGES for dialect in ("pg", "mysql")), + pytest.param( + "pg", "SELECT * FROM (SELECT id, photo AS ssn FROM people) a RIGHT JOIN (SELECT id, ssn::bytea FROM users) b " + "USING (ssn)", ["ssn", "id", "id"], id="cast-right-using-pg"), +]) +def test_derived_star_source_merged_with_plain_derived_column_refused(mocker, env, dialect, sql, names): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + call(cur, "execute", sql) + raw.description, raw.rows = [(n,) for n in names], [tuple(payload(marker()) if n == "ssn" else 1 for n in names)] + with pytest.raises(MetadataError) as info: + call(cur, "fetchall") + assert str(info.value) == Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", "ssn") + assert raw.fetches == 0 + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +@pytest.mark.parametrize("sql, names", [ + ("SELECT * FROM (SELECT *, photo AS ssn FROM people) d WHERE id IN (SELECT id FROM users)", ["id", "ssn"]), + ("SELECT * FROM (SELECT id, photo AS ssn FROM people) a JOIN (SELECT id, name FROM users) b USING (id)", + ["id", "ssn", "name"]), +], ids=["one-derived-source-with-star", "two-listed-derived-sources"]) +def test_plain_derived_column_without_unlisted_source_returned_as_is(mocker, env, dialect, sql, names): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + call(cur, "execute", sql) + raw.description, raw.rows = [(n,) for n in names], [tuple(f"plain-{n}" for n in names)] + assert call(cur, "fetchall") == [tuple(f"plain-{n}" for n in names)] + assert env.keys.return_value.decrypt_data_key.call_count == 0 + + +@pytest.mark.parametrize("dialect", ["pg", "mysql"]) +def test_named_item_beside_qualified_star_in_derived_table_decrypts(mocker, env, dialect): + plugin, _ = make_plugin(mocker, DIALECTS[dialect]) + cur, raw = cursor(plugin) + secret = marker() + call(cur, "execute", "SELECT * FROM (SELECT u.*, ssn AS x FROM users u) s") + raw.description, raw.rows = [("id",), ("ssn",), ("x",)], [(1, payload(secret), payload(secret))] + assert call(cur, "fetchall") == [(1, secret, secret)] + + +def test_column_config_without_table_is_none(): + assert plugin_module._column_config({"users": (SSN,)}, None, "ssn", str.lower) is None diff --git a/tests/unit/test_kms_trigger_sql.py b/tests/unit/test_kms_trigger_sql.py new file mode 100644 index 000000000..91d0c140d --- /dev/null +++ b/tests/unit/test_kms_trigger_sql.py @@ -0,0 +1,64 @@ +# 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. + +"""The trigger SQL in ``aws_advanced_python_wrapper/encryption/sql``, which the KMS Encryption Plugin guide tells +administrators to run. The integration tests run it against real servers; these checks only read the files.""" + +import re +from importlib.resources import files + +import pytest + +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService + +_SQL = files("aws_advanced_python_wrapper.encryption") / "sql" +_FILES = pytest.mark.parametrize("name", ["trigger_pg.sql", "trigger_mysql.sql"]) + + +def _read(name: str) -> str: + return (_SQL / name).read_text(encoding="utf-8") + + +@pytest.mark.parametrize("name, version", [("trigger_pg.sql", "2"), ("trigger_mysql.sql", "1")]) +def test_trigger_file_version_matches_guide(name: str, version: str) -> None: + assert re.findall(r"'aws-advanced-python-wrapper kms_encryption trigger v(\d+)'", _read(name)) == [version] + + +@_FILES +def test_trigger_file_rejects_short_value(name: str) -> None: + assert re.findall(r"(?i)length\((?:col_value|data)\) < (\d+)", _read(name)) == \ + [str(EncryptionService.MIN_ENCRYPTED_LENGTH)] + + +def test_mysql_file_reads_metadata_from_schema_token() -> None: + sql = _read("trigger_mysql.sql") + assert "SCHEMA_NAME.encryption_metadata" in sql + assert "SCHEMA_NAME.key_storage" in sql + + +def test_pg_file_reads_metadata_from_schema_token() -> None: + sql = _read("trigger_pg.sql") + assert "SCHEMA_NAME.encryption_metadata" in sql + assert "SCHEMA_NAME.key_storage" in sql + + +@_FILES +def test_schema_token_replace_leaves_no_hardcoded_schema(name: str) -> None: + sql = _read(name).replace("SCHEMA_NAME", "other_schema") + assert "SCHEMA_NAME" not in sql + assert "other_schema.encryption_metadata" in sql + assert "other_schema.key_storage" in sql + # no schema left hardcoded outside the comments + assert "encrypt." not in re.sub(r"--.*", "", sql) diff --git a/tests/unit/test_metadata_manager.py b/tests/unit/test_metadata_manager.py index 768a516a1..9cf48d71a 100644 --- a/tests/unit/test_metadata_manager.py +++ b/tests/unit/test_metadata_manager.py @@ -13,6 +13,7 @@ # limitations under the License. import gc +import logging import threading import weakref from contextlib import contextmanager @@ -25,8 +26,13 @@ from aws_advanced_python_wrapper.encryption.config import EncryptionConfig from aws_advanced_python_wrapper.encryption.metadata_manager import \ MetadataManager -from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG from aws_advanced_python_wrapper.errors import MetadataError +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.utils.properties import Properties + +PG = PgDriverDialect(Properties()) +MYSQL = MySQLDriverDialect(Properties()) ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" @@ -62,7 +68,8 @@ def execute(self, sql, params=()): db.executed.append((sql, tuple(params))) if db.error is not None: raise db.error - self.description = [(c.upper(),) for c in COLUMNS] # upper case, as some MySQL versions report + # Upper case, as some MySQL versions report. + self.description = [(c.upper(),) for c in COLUMNS] rows = db.rows if "WHERE em.table_name" in sql: rows = [r for r in rows if r[0] == params[0] and (len(params) < 2 or r[1] == params[1])] @@ -104,15 +111,19 @@ def managers(): def config(**overrides): - values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), - metadata_cache_refresh_interval_sec=0.0, metadata_cache_expiration_sec=60.0) + values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), kms_endpoint=None, + metadata_schema="encrypt", metadata_cache_enabled=True, metadata_cache_expiration_sec=60.0, + metadata_cache_refresh_interval_sec=0.0, data_key_cache_enabled=True, + data_key_cache_max_size=1000, data_key_cache_expiration_sec=300.0, key_management_max_retries=3, + key_management_retry_backoff_base_sec=0.1, audit_logging_enabled=False, + return_unverified_data=False) values.update(overrides) return EncryptionConfig(**values) # type: ignore[arg-type] -def test_joined_query_is_a_left_join_on_the_integer_id(): +def test_joined_query_left_joins_on_integer_id(): db = FakeDb() - MetadataManager(db, PG, config()).load_metadata() + MetadataManager(db, PG, PG, config()).load_metadata() sql = db.executed[0][0] assert "FROM encrypt.encryption_metadata em LEFT JOIN encrypt.key_storage ks" in sql assert "ON em.key_id OPERATOR(pg_catalog.=) ks.id" in sql @@ -121,22 +132,26 @@ def test_joined_query_is_a_left_join_on_the_integer_id(): def test_mysql_uses_plain_equals(): db = FakeDb() - MetadataManager(db, MYSQL, config(metadata_schema="app_enc")).load_metadata() + MetadataManager(db, MYSQL, MYSQL, config(metadata_schema="app_enc")).load_metadata() assert "ON em.key_id = ks.id" in db.executed[0][0] assert "app_enc.encryption_metadata" in db.executed[0][0] -def test_start_loads_snapshot_and_lookups_hit_the_cache(clock): +def test_start_loads_snapshot_lookups_hit_cache(clock): db = FakeDb([row("users", "ssn"), row("users", "dob", 2), row("orders", "card", 3)]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) mm.start() - assert mm.cache_size == 3 and db.opened == 1 + assert mm.cache_size == 3 + assert db.opened == 1 assert mm.is_column_encrypted("users", "ssn") assert not mm.is_column_encrypted("users", "name") assert not mm.is_column_encrypted(None, "ssn") config_ = mm.column_config("users", "dob") - assert config_ is not None and config_.key_id == 2 and config_.key_metadata.id == 2 - assert config_.key_metadata.hmac_key == b"h" * 32 and config_.is_usable + assert config_ is not None + assert config_.key_id == 2 + assert config_.key_metadata.id == 2 + assert config_.key_metadata.hmac_key == b"h" * 32 + assert config_.is_usable assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} assert mm.table_configs("nope") == () assert db.opened == 1 @@ -144,11 +159,12 @@ def test_start_loads_snapshot_and_lookups_hit_the_cache(clock): def test_column_with_missing_key_row_still_reads_as_encrypted(clock): db = FakeDb([row("users", "ssn", key_id=7, with_key=False)]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) mm.start() config_ = mm.column_config("users", "ssn") assert config_ is not None - assert config_.key_id == 7 and config_.key_metadata is None + assert config_.key_id == 7 + assert config_.key_metadata is None assert not config_.is_usable assert mm.is_column_encrypted("users", "ssn") @@ -156,25 +172,26 @@ def test_column_with_missing_key_row_still_reads_as_encrypted(clock): def _expired_with_background_refresh(clock, managers, db): # A background refresh is configured but hasn't run yet when the snapshot # expires, so the next lookup is what reloads it. - mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0, - metadata_cache_refresh_interval_sec=3600.0)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_expiration_sec=10.0, + metadata_cache_refresh_interval_sec=3600.0)) managers.append(mm) mm.start() clock.now += 10.0 return mm -def test_expired_snapshot_is_reloaded_with_the_background_refresh_on(clock, managers): +def test_expired_snapshot_reloaded_with_background_refresh(clock, managers): db = FakeDb([row("users", "ssn")]) mm = _expired_with_background_refresh(clock, managers, db) assert mm.is_column_encrypted("users", "ssn") assert mm.column_config("users", "ssn") is not None - assert db.opened == 2 # start() plus one reload, not a query per lookup + # Start() plus one reload, not a query per lookup. + assert db.opened == 2 assert "WHERE" not in db.executed[-1][0] assert mm._fresh(mm._snapshot) is not None -def test_expired_snapshot_reload_sees_a_column_added_since(clock, managers): +def test_expired_snapshot_reload_sees_added_column(clock, managers): # A column encrypted after the snapshot was taken must show up once the # snapshot expires; serving the stale snapshot would let a write store # plaintext. @@ -182,20 +199,22 @@ def test_expired_snapshot_reload_sees_a_column_added_since(clock, managers): mm = _expired_with_background_refresh(clock, managers, db) db.rows = [row("users", "ssn"), row("users", "dob", 2)] assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} - assert mm.cache_size == 2 # the reload cached the new column + # The reload cached the new column. + assert mm.cache_size == 2 assert mm.is_column_encrypted("users", "dob") assert db.opened == 2 def test_expired_snapshot_is_reloaded_when_there_is_no_background_refresh(clock): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # refresh interval 0 + mm = MetadataManager(db, PG, PG, config(metadata_cache_expiration_sec=10.0)) # refresh interval 0 mm.start() clock.now += 10.0 db.rows = [row("users", "ssn"), row("users", "dob", 2)] assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} assert mm.is_column_encrypted("users", "dob") - assert db.opened == 2 # one reload, then served from the new snapshot + # One reload, then served from the new snapshot. + assert db.opened == 2 assert "WHERE" not in db.executed[-1][0] @@ -203,25 +222,27 @@ def test_manager_that_was_never_started_always_queries(clock): # The admin utility relies on this: it never starts its manager, so every # lookup sees the caller's own transaction. db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) assert mm.is_column_encrypted("users", "ssn") assert mm.is_column_encrypted("users", "ssn") - assert db.opened == 2 and not mm.is_cache_loaded + assert db.opened == 2 + assert not mm.is_cache_loaded def test_disabled_cache_always_queries(clock): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_enabled=False)) mm.start() - assert db.opened == 0 and not mm.is_cache_loaded + assert db.opened == 0 + assert not mm.is_cache_loaded assert mm.is_column_encrypted("users", "ssn") assert [c.column_name for c in mm.table_configs("users")] == ["ssn"] assert db.opened == 2 -def test_refresh_replaces_the_snapshot_atomically(clock): +def test_refresh_replaces_snapshot_atomically(clock): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) mm.start() db.rows = [row("users", "dob")] assert mm.refresh() == 1 @@ -229,27 +250,87 @@ def test_refresh_replaces_the_snapshot_atomically(clock): assert mm.is_column_encrypted("users", "dob") -def test_failed_refresh_keeps_the_previous_snapshot(clock): +def test_failed_refresh_keeps_previous_snapshot(clock): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) mm.start() db.error = RuntimeError("db down") - with pytest.raises(MetadataError, match="db down"): + with pytest.raises(MetadataError, match="RuntimeError"): mm.refresh() assert mm.is_column_encrypted("users", "ssn") +class DriverError(Exception): + sqlstate = "22021" + + +def _chained_errors(error: BaseException) -> List[BaseException]: + errors: List[BaseException] = [] + pending: List[Optional[BaseException]] = [error] + while pending: + current = pending.pop() + if current is None or any(current is seen for seen in errors): + continue + errors.append(current) + pending.extend((current.__cause__, current.__context__)) + return errors + + +def test_load_failure_chains_no_driver_error(caplog): + db = FakeDb() + db.error = DriverError("invalid byte sequence near 'SECRET-ROW-BYTES'") + mm = MetadataManager(db, PG, PG, config()) + with pytest.raises(MetadataError) as err: + mm.start() + summary = "[MetadataManager] Failed to read the kms_encryption metadata: DriverError, sqlstate 22021" + assert str(err.value) == summary + assert err.value.args == (summary,) + assert _chained_errors(err.value) == [err.value] + assert "SECRET" not in repr(err.value) + + stop = threading.Event() + original = mm.refresh + + def refresh_once(): + stop.set() + return original() + + mm.refresh = refresh_once # type: ignore[method-assign] + with caplog.at_level(logging.WARNING, logger=module.__name__): + MetadataManager._refresh_loop(weakref.ref(mm), stop, 0) + warnings = [r.getMessage() for r in caplog.records if r.name == module.__name__ and r.levelno == logging.WARNING] + assert warnings == [f"[MetadataManager] Failed to refresh the kms_encryption metadata cache: {summary}"] + + +@pytest.mark.parametrize("cache_enabled", [True, False], ids=["cache-on", "cache-off"]) +def test_has_encrypted_columns(clock, cache_enabled): + db = FakeDb() + mm = MetadataManager(db, PG, PG, config(metadata_cache_enabled=cache_enabled)) + mm.start() + assert mm.has_encrypted_columns() is False + db.rows = [row("users", "ssn")] + # A fresh snapshot answers until it expires; without the cache, every call reads the tables. + assert mm.has_encrypted_columns() is (not cache_enabled) + clock.now += 61 + assert mm.has_encrypted_columns() is True + + +def test_has_encrypted_columns_unstarted_manager_reads_tables(): + db = FakeDb([row("users", "ssn")]) + assert MetadataManager(db, PG, PG, config()).has_encrypted_columns() is True + + def test_initial_load_failure_raises_metadata_error(): db = FakeDb() db.error = RuntimeError("no such schema") with pytest.raises(MetadataError): - MetadataManager(db, PG, config()).start() + MetadataManager(db, PG, PG, config()).start() def test_lookup_failure_carries_table_and_column(clock): db = FakeDb() db.error = RuntimeError("x") - mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_enabled=False)) with pytest.raises(MetadataError) as err: mm.column_config("users", "ssn") assert (err.value.table_name, err.value.column_name) == ("users", "ssn") @@ -258,7 +339,7 @@ def test_lookup_failure_carries_table_and_column(clock): def test_background_refresh_thread_runs_and_stops(managers): db = FakeDb([row("users", "ssn")]) refreshed = threading.Event() - mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_refresh_interval_sec=0.01)) managers.append(mm) original = mm.refresh @@ -271,7 +352,8 @@ def counting_refresh(): mm.refresh = counting_refresh # type: ignore[method-assign] mm.start() thread = mm._refresh_thread - assert thread is not None and thread.daemon + assert thread is not None + assert thread.daemon assert refreshed.wait(5) mm.close() assert not thread.is_alive() @@ -281,7 +363,7 @@ def counting_refresh(): def test_background_refresh_survives_errors(managers): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_refresh_interval_sec=0.01)) managers.append(mm) mm.start() db.error = RuntimeError("blip") @@ -291,7 +373,8 @@ def test_background_refresh_survives_errors(managers): break threading.Event().wait(0.01) assert len(db.executed) > attempts + 2 # the loop kept trying - assert mm._refresh_thread is not None and mm._refresh_thread.is_alive() + assert mm._refresh_thread is not None + assert mm._refresh_thread.is_alive() class BlockingDb(FakeDb): @@ -313,9 +396,9 @@ def connection(self): self.release.wait(5) -def test_refresh_finishing_after_close_does_not_repopulate_the_cache(managers): +def test_refresh_after_close_keeps_cache_empty(managers): db = BlockingDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) managers.append(mm) mm.start() db.block = True @@ -331,15 +414,18 @@ def test_refresh_finishing_after_close_does_not_repopulate_the_cache(managers): db.block = False opened = db.opened assert mm.is_column_encrypted("users", "ssn") - assert db.opened == opened + 1 and not mm.is_cache_loaded + assert db.opened == opened + 1 + assert not mm.is_cache_loaded def test_start_after_close_does_nothing(): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_refresh_interval_sec=0.01)) mm.close() mm.start() - assert db.opened == 0 and mm._refresh_thread is None and not mm.is_cache_loaded + assert db.opened == 0 + assert mm._refresh_thread is None + assert not mm.is_cache_loaded def test_concurrent_refreshes_cannot_publish_older_data(): @@ -347,7 +433,7 @@ def test_concurrent_refreshes_cannot_publish_older_data(): # the data changes and a second refresh starts. Refreshes are serialized, # so the second one's newer data is published last. db = BlockingDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) db.block = True first = threading.Thread(target=mm.refresh, daemon=True) first.start() @@ -357,11 +443,13 @@ def test_concurrent_refreshes_cannot_publish_older_data(): second = threading.Thread(target=mm.refresh, daemon=True) second.start() second.join(0.2) - assert second.is_alive() # waits for the first refresh + # Waits for the first refresh. + assert second.is_alive() db.release.set() first.join(5) second.join(5) - assert not first.is_alive() and not second.is_alive() + assert not first.is_alive() + assert not second.is_alive() assert mm.is_column_encrypted("users", "dob") assert not mm.is_column_encrypted("users", "ssn") @@ -370,7 +458,7 @@ def test_unclosed_manager_stops_its_thread_when_collected(): # A long interval, so the thread stops because the finalizer wakes it, # not because its next wait happened to time out. db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=60.0)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_refresh_interval_sec=60.0)) mm.start() thread = mm._refresh_thread ref = weakref.ref(mm) @@ -386,7 +474,7 @@ def test_unclosed_manager_stops_its_thread_when_collected(): assert not thread.is_alive() -def test_finalizer_does_not_set_the_event_from_the_refresh_thread_itself(): +def test_finalizer_on_refresh_thread_skips_event(): # On the refresh thread the collection can run inside Event.wait, which # holds the event's lock, so stop.set() there would deadlock. stop = threading.Event() @@ -396,7 +484,7 @@ def test_finalizer_does_not_set_the_event_from_the_refresh_thread_itself(): assert stop.is_set() -def test_close_from_the_refresh_thread_does_not_fail(managers): +def test_close_from_refresh_thread_succeeds(managers): # Only the refresh thread reports; start()'s initial refresh runs on the # calling thread and must not satisfy the test. errors: List[BaseException] = [] @@ -415,7 +503,7 @@ def connection(self): with super().connection() as conn: yield conn - mm = MetadataManager(ClosingDb([row("users", "ssn")]), PG, config(metadata_cache_refresh_interval_sec=0.01)) + mm = MetadataManager(ClosingDb([row("users", "ssn")]), PG, PG, config(metadata_cache_refresh_interval_sec=0.01)) managers.append(mm) mm.start() assert done.wait(5) @@ -423,18 +511,18 @@ def connection(self): assert mm._stop.is_set() -def test_finalizer_is_given_the_refresh_thread(managers): +def test_finalizer_gets_refresh_thread(managers): # The _finalize test passes the holder by hand; this pins the wiring. - mm = MetadataManager(FakeDb([row("users", "ssn")]), PG, config(metadata_cache_refresh_interval_sec=60.0)) + mm = MetadataManager(FakeDb([row("users", "ssn")]), PG, PG, config(metadata_cache_refresh_interval_sec=60.0)) managers.append(mm) mm.start() assert mm._refresh_thread is not None assert mm._thread_holder == [mm._refresh_thread] -def test_failed_reload_from_table_configs_names_the_table(clock): +def test_failed_table_configs_reload_names_table(clock): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_expiration_sec=10.0)) mm.start() clock.now += 10.0 db.error = RuntimeError("db down") @@ -443,35 +531,39 @@ def test_failed_reload_from_table_configs_names_the_table(clock): assert (err.value.table_name, err.value.column_name) == ("users", None) -def test_snapshot_age_counts_from_the_start_of_the_load(clock, managers): +def test_snapshot_age_counts_from_load_start(clock, managers): # A slow load must not stretch how long its data is trusted. class SlowDb(FakeDb): @contextmanager def connection(self): with super().connection() as conn: yield conn - clock.now += 5.0 # the load takes 5 s + # The load takes 5 s. + clock.now += 5.0 db = SlowDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0, - metadata_cache_refresh_interval_sec=3600.0)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_expiration_sec=10.0, + metadata_cache_refresh_interval_sec=3600.0)) managers.append(mm) mm.start() - clock.now += 5.0 # 10 s after the data was read, 5 s after the query returned + # 10 s after the data was read, 5 s after the query returned. + clock.now += 5.0 opened = db.opened mm.column_config("users", "ssn") - assert db.opened == opened + 1 # expired: read from the database + # Expired: read from the database. + assert db.opened == opened + 1 def test_lookups_that_expire_together_share_one_reload(clock): db = BlockingDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh + mm = MetadataManager(db, PG, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh mm.start() clock.now += 10.0 db.block = True first = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) first.start() - assert db.entered.wait(5) # the first lookup's reload is inside its read + # The first lookup's reload is inside its read. + assert db.entered.wait(5) db.block = False others = [threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) for _ in range(4)] for t in others: @@ -480,12 +572,13 @@ def test_lookups_that_expire_together_share_one_reload(clock): for t in [first] + others: t.join(5) assert not any(t.is_alive() for t in [first] + others) - assert db.opened == 2 # start() plus a single reload + # Start() plus a single reload. + assert db.opened == 2 def test_lookups_queued_when_close_runs_do_not_reload(clock): db = BlockingDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh + mm = MetadataManager(db, PG, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh mm.start() clock.now += 10.0 db.block = True @@ -496,19 +589,22 @@ def test_lookups_queued_when_close_runs_do_not_reload(clock): queued = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) queued.start() queued.join(0.2) - assert queued.is_alive() # waiting for the first reload + # Waiting for the first reload. + assert queued.is_alive() mm.close() db.release.set() first.join(5) queued.join(5) - assert not first.is_alive() and not queued.is_alive() + assert not first.is_alive() + assert not queued.is_alive() full_loads = [sql for sql, _ in db.executed if "WHERE" not in sql] - assert len(full_loads) == 2 # start() and the first lookup's reload; the queued one only queries its column + # Start() and the first lookup's reload; the queued one only queries its column. + assert len(full_loads) == 2 -def test_failed_reload_names_the_lookup(clock): +def test_failed_reload_names_lookup(clock): db = FakeDb([row("users", "ssn")]) - mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_expiration_sec=10.0)) mm.start() clock.now += 10.0 db.error = RuntimeError("db down") @@ -517,12 +613,10 @@ def test_failed_reload_names_the_lookup(clock): assert (err.value.table_name, err.value.column_name) == ("users", "ssn") -# ---- name matching ---- - def test_postgresql_lookups_are_exact(clock): # Names are stored as the catalog has them; "Users" and users differ. db = FakeDb([row("users", "ssn"), row("Users", "SSN", 2)]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) mm.start() assert mm.column_config("users", "ssn").key_id == 1 assert mm.column_config("Users", "SSN").key_id == 2 @@ -534,19 +628,20 @@ def test_mysql_lookups_ignore_case(clock): # MySQL compares these names case-insensitively, as the uncached query's # WHERE does under the metadata table's collation. db = FakeDb([row("Users", "SSN")]) - mm = MetadataManager(db, MYSQL, config()) + mm = MetadataManager(db, MYSQL, MYSQL, config()) mm.start() found = mm.column_config("users", "ssn") - assert found is not None and (found.table_name, found.column_name) == ("Users", "SSN") + assert found is not None + assert (found.table_name, found.column_name) == ("Users", "SSN") assert mm.is_column_encrypted("USERS", "Ssn") assert [c.column_name for c in mm.table_configs("users")] == ["SSN"] assert [c.column_name for c in mm.table_configs("USERS")] == ["SSN"] assert db.opened == 1 # all from the cache -def test_load_metadata_keeps_the_stored_names(): +def test_load_metadata_keeps_stored_names(): db = FakeDb([row("Users", "SSN")]) - assert list(MetadataManager(db, MYSQL, config()).load_metadata()) == [("Users", "SSN")] + assert list(MetadataManager(db, MYSQL, MYSQL, config()).load_metadata()) == [("Users", "SSN")] @pytest.mark.parametrize("raw", [b"users", bytearray(b"users"), memoryview(b"users")]) @@ -555,7 +650,7 @@ def test_bytes_names_are_decoded(clock, raw): # use_unicode=False, returns text as bytes. Undecoded, the snapshot would # be keyed by bytes and no str lookup would find the encrypted column. db = FakeDb([row(raw, b"ssn")]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) mm.start() assert mm.is_column_encrypted("users", "ssn") assert mm.column_config("users", "ssn").table_name == "users" @@ -564,14 +659,37 @@ def test_bytes_names_are_decoded(clock, raw): @pytest.mark.parametrize("raw", [b"\xff\xfe", 42, None]) def test_names_that_are_not_text_are_refused(clock, raw): db = FakeDb([row(raw, "ssn")]) - mm = MetadataManager(db, PG, config()) + mm = MetadataManager(db, PG, PG, config()) with pytest.raises(MetadataError, match="table_name") as info: mm.start() assert info.value.__context__ is None -def test_names_that_are_not_text_are_refused_on_an_uncached_lookup(): +def test_non_text_names_uncached_lookup_raises(): db = FakeDb([row("users", 7)]) - mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + mm = MetadataManager(db, PG, PG, config(metadata_cache_enabled=False)) with pytest.raises(MetadataError, match="column_name"): mm.column_config("users", 7) # type: ignore[arg-type] + + +def test_column_config_without_name_returns_none(): + db = FakeDb() + mm = MetadataManager(db, PG, PG, config()) + assert mm.column_config(None, "ssn") is None + assert mm.column_config("users", None) is None + assert db.executed == [] + + +def test_table_configs_without_table_returns_empty(): + db = FakeDb() + assert MetadataManager(db, PG, PG, config()).table_configs(None) == () + assert db.executed == [] + + +def test_refresh_loop_collected_manager_returns(mocker): + stop = mocker.MagicMock() + stop.wait.return_value = False + collected = weakref.ref(MetadataManager(FakeDb(), PG, PG, config())) + assert collected() is None + MetadataManager._refresh_loop(collected, stop, 0.0) + stop.wait.assert_called_once_with(0.0) diff --git a/tests/unit/test_models.py b/tests/unit/test_models.py new file mode 100644 index 000000000..7c2e6787f --- /dev/null +++ b/tests/unit/test_models.py @@ -0,0 +1,89 @@ +# 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. + +import pytest + +from aws_advanced_python_wrapper.encryption.models import (mask_arn, + mask_error_text, + mask_key_id) + +ACCOUNT_ARN_PREFIX = "arn:aws:kms:us-east-1:123456789012:" +# U+0378 is unassigned on every supported Python version. +CONTROL_CHARACTERS = ["\n", "\x1b", "\u2028", "\u2029", "\u202e", "\u0378"] + + +def test_mask_key_id_none_returns_none(): + assert mask_key_id(None) is None + + +def test_mask_arn_none_returns_none(): + assert mask_arn(None) is None + + +@pytest.mark.parametrize("character", CONTROL_CHARACTERS) +def test_mask_arn_replaces_control_characters(character): + arn = f"{ACCOUNT_ARN_PREFIX}key/1234abcd-12ab-34cd-56ef-1234567890{character}b" + assert mask_arn(arn) == "arn:aws:kms:***:***:key/1234***90?b" + + +def test_mask_key_id_replaces_bidi_override(): + assert mask_key_id("\u202e234abcd-12ab-34cd-56ef-1234567890ab") == "?234***90ab" + + +@pytest.mark.parametrize("alias", [ + f"{ACCOUNT_ARN_PREFIX}alias/aws-advanced-python-wrapper/integration-tests", + "alias/application-data-key", + "ALIAS/application-data-key", + f"{ACCOUNT_ARN_PREFIX}alias/key", +]) +def test_mask_arn_masks_alias_whole(alias): + assert mask_arn(alias) == "arn:aws:kms:***:***:alias/***" + + +def test_kms_error_summary_cut_at_200_characters(): + assert mask_error_text("x" * 200) == "x" * 200 + assert mask_error_text("x" * 500) == "x" * 197 + "..." + + +def test_kms_error_text_masks_url_user_info(): + text = 'Could not connect to the endpoint URL: "https://admin:pa@ss@kms.example.com:4566/"' + assert mask_error_text(text) == 'Could not connect to the endpoint URL: "https://***@kms.example.com:4566/"' + + +def test_mask_error_text_masks_arns_then_replaces_control_characters(): + text = f"{ACCOUNT_ARN_PREFIX}key/1234abcd-12ab-34cd-56ef-1234567890ab is disabled.\nforged line" + assert mask_error_text(text) == "arn:aws:kms:***:***:key/1234***90ab is disabled.?forged line" + + +def test_mask_error_text_masks_user_info_before_replacing_control_characters(): + assert mask_error_text("https://admin\x00:secret@kms.example.com/") == "https://***@kms.example.com/" + + +@pytest.mark.parametrize("text, masked", [ + ("aws_secret_access_key=MARK-1 user=postgres", "aws_secret_access_key=*** user=postgres"), + ("Error: password=MARK-1 for user=postgres", "Error: password=*** for user=postgres"), + ('Could not connect to "https://kms.example.com/?a=1&token=MARK-1"', + 'Could not connect to "https://kms.example.com/?a=1&token=***'), + ("key=MARK-1 KeyId=1234 keys=1", "key=*** KeyId=1234 keys=1"), + ("a=b=password=MARK-1=", "a=b=password=***"), + ("password= user=postgres", "password= user=postgres"), + ('connect failed: password="MARK-1 x" host=db', "connect failed: password=*** host=db"), + ("password='MARK-1' host=db", "password=*** host=db"), + ("api_key=MARK-1 refused", "api_key=*** refused"), + ("password=MA&RK-1 x", "password=*** x"), + ("password=MA\xa0RK-1 x", "password=*** x"), +], ids=["secret-name", "password", "url-parameter", "key", "after-other-pairs", "empty-value", "quoted-double", + "quoted-single", "name-ending-in-key", "ampersand-in-value", "nbsp-in-value"]) +def test_mask_error_text_masks_secret_pair_values(text, masked): + assert mask_error_text(text) == masked diff --git a/tests/unit/test_mysql_driver_dialect.py b/tests/unit/test_mysql_driver_dialect.py index 93b2837ce..f86d51a14 100644 --- a/tests/unit/test_mysql_driver_dialect.py +++ b/tests/unit/test_mysql_driver_dialect.py @@ -13,13 +13,16 @@ # limitations under the License. import socket +import threading import psycopg import pytest from mysql.connector import MySQLConnection +from mysql.connector import cursor as mysql_cursor from mysql.connector.cursor import MySQLCursor from aws_advanced_python_wrapper.errors import (AwsWrapperError, + QueryTimeoutError, UnsupportedOperationError) from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect @@ -174,3 +177,83 @@ def test_abort_connection_swallows_shutdown_oserror(dialect, mock_conn, mocker): def test_abort_connection_rejects_non_mysql_connection(dialect, mock_invalid_conn): with pytest.raises(UnsupportedOperationError): dialect.abort_connection(mock_invalid_conn) + + +def test_metadata_key_lower_cases(dialect): + assert dialect.metadata_key("Users") == "users" + + +def test_fold_identifier_keeps_case(dialect): + assert dialect.fold_identifier("Users", quoted=False) == "Users" + + +def test_upsert_clause(dialect): + assert dialect.upsert_clause(["id"], ["name"], ["updated_at = NOW()"]) == \ + "ON DUPLICATE KEY UPDATE name = VALUES(name), updated_at = NOW()" + + +def test_insert_returning_id(dialect, mocker): + conn = mocker.MagicMock() + cursor = conn.cursor.return_value + cursor.lastrowid = 7 + assert dialect.insert_returning_id(conn, "INSERT INTO t (name) VALUES (%s)", ("a",)) == 7 + cursor.execute.assert_called_once_with("INSERT INTO t (name) VALUES (%s)", ("a",)) + + +def test_analyzable_sql_bytes(dialect, mocker, mock_conn): + mock_conn.python_charset = "utf8" + cursor = mocker.MagicMock(spec=MySQLCursor) + cursor._connection = mock_conn + assert dialect.analyzable_sql(b"SELECT 1", cursor) == ("SELECT 1", "utf8") + assert dialect.analyzable_sql("SELECT 'é'".encode("utf-8"), cursor) == (None, "utf8") + assert dialect.analyzable_sql("SELECT 1", cursor) == ("SELECT 1", None) + + +def test_analyzable_sql_bytes_unknown_charset(dialect, mocker, mock_conn): + mock_conn.python_charset = "swe7" + cursor = mocker.MagicMock(spec=MySQLCursor) + cursor._connection = mock_conn + with pytest.raises(LookupError): + dialect.analyzable_sql(b"SELECT 1", cursor) + + +def test_analyzable_sql_bytes_without_connection(dialect, mocker): + assert dialect.analyzable_sql(b"SELECT 1", mocker.MagicMock()) == (None, None) + + +def test_binary_placeholder_prefix_none_on_prepared_cursors(mocker, dialect): + prepared = {"MySQLCursorPrepared", "MySQLCursorPreparedDict", "CMySQLCursorPrepared", "CMySQLCursorPreparedDict"} + + def check(module, prefix): + classes = [getattr(module, n) for n in dir(module) if n.startswith(prefix) and isinstance(getattr(module, n), type)] + assert len(classes) > 2 + for cls in classes: + expected = None if cls.__name__ in prepared else "_binary " + assert dialect.binary_placeholder_prefix(mocker.MagicMock(spec=cls)) == expected + + check(mysql_cursor, "MySQLCursor") + check(pytest.importorskip("mysql.connector.cursor_cext"), "CMySQLCursor") + + +def test_insert_returning_id_times_out_with_socket_timeout(mocker): + dialect = MySQLDriverDialect(Properties({WrapperProperties.SOCKET_TIMEOUT_SEC.name: "0.05"})) + event = threading.Event() + # The abort ends the cursor call that waits, so no worker is left running. + mocker.patch.object(dialect, "abort_connection", side_effect=lambda conn: event.set()) + conn = mocker.MagicMock() + conn.cursor.return_value.execute.side_effect = lambda *args: event.wait(timeout=1) and None + conn.cursor.return_value.lastrowid = 7 + with pytest.raises(QueryTimeoutError): + dialect.insert_returning_id(conn, "INSERT INTO t (name) VALUES (%s)", ("a",)) + + +@pytest.mark.parametrize("params, binds", [ + (None, False), ({}, False), ([], False), ((), False), ({"a": 1}, True), ([1], True)]) +def test_binds_parameters_non_empty_dict_list_or_tuple(params, binds): + assert MySQLDriverDialect.binds_parameters(params) is binds + + +def test_reencrypt_sql_members(): + assert MySQLDriverDialect.greater_than_operator == ">" + assert MySQLDriverDialect.quote_identifier("users") == "`users`" + assert MySQLDriverDialect.key_column_type_sql is None diff --git a/tests/unit/test_pg_driver_dialect.py b/tests/unit/test_pg_driver_dialect.py index b19e99a5a..26eabd12a 100644 --- a/tests/unit/test_pg_driver_dialect.py +++ b/tests/unit/test_pg_driver_dialect.py @@ -12,12 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. +import re + import psycopg import pytest from mysql.connector import MySQLConnection from sqlalchemy import PoolProxiedConnection -from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.errors import (AwsWrapperError, + QueryTimeoutError) from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect from aws_advanced_python_wrapper.utils.properties import (Properties, @@ -186,3 +189,99 @@ def test_prepare_connect_info(dialect): result = dialect.prepare_connect_info(host_info, original_props) assert result == expected_props + + +def test_fold_identifier(dialect): + assert dialect.fold_identifier("Users", quoted=False) == "users" + assert dialect.fold_identifier("Users", quoted=True) == "Users" + assert dialect.fold_identifier("ÉTÉ", quoted=False) == "ÉtÉ" + + +def test_metadata_key_keeps_case(dialect): + assert dialect.metadata_key("Users") == "Users" + + +def test_upsert_clause(dialect): + assert dialect.upsert_clause(["id"], ["name", "age"], ["updated_at = NOW()"]) == \ + "ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, age = EXCLUDED.age, updated_at = NOW()" + + +@pytest.mark.parametrize("row", [(7,), {"id": 7}]) +def test_insert_returning_id(dialect, mocker, row): + conn = mocker.MagicMock() + cursor = conn.cursor.return_value + cursor.fetchone.return_value = row + assert dialect.insert_returning_id(conn, "INSERT INTO t (name) VALUES (%s)", ("a",)) == 7 + cursor.execute.assert_called_once_with("INSERT INTO t (name) VALUES (%s) RETURNING id", ("a",)) + + +def test_analyzable_sql_composable(dialect, mocker): + cursor = mocker.MagicMock() + composed = mocker.MagicMock(spec=psycopg.sql.Composed) + composed.as_string.return_value = "SELECT ssn FROM users" + assert dialect.analyzable_sql(composed, cursor) == ("SELECT ssn FROM users", None) + composed.as_string.assert_called_once_with(cursor) + + +def test_analyzable_sql_bytes(dialect, mocker, mock_conn): + mock_conn.info.encoding = "utf-8" + cursor = mocker.MagicMock(spec=psycopg.Cursor) + cursor.connection = mock_conn + assert dialect.analyzable_sql(b"SELECT 1", cursor) == ("SELECT 1", "utf-8") + assert dialect.analyzable_sql("SELECT 1", cursor) == ("SELECT 1", None) + + +def test_analyzable_sql_bytes_without_connection(dialect, mocker): + assert dialect.analyzable_sql(b"SELECT 1", mocker.MagicMock()) == (None, None) + + +@pytest.mark.parametrize("codec", ["shift_jis_2004", "ascii"]) +def test_analyzable_sql_bytes_codec_mismatch(dialect, mocker, mock_conn, codec): + mock_conn.info.encoding = codec + cursor = mocker.MagicMock(spec=psycopg.Cursor) + cursor.connection = mock_conn + assert dialect.analyzable_sql("SELECT 'é'".encode("utf-8"), cursor) == (None, codec) + + +def test_unsupported_row_factory(dialect, mocker): + cursor = mocker.MagicMock(spec=psycopg.Cursor) + for factory in (psycopg.rows.tuple_row, psycopg.rows.dict_row, psycopg.rows.namedtuple_row): + cursor.row_factory = factory + assert dialect.unsupported_row_factory(cursor) is None + + cursor.row_factory = psycopg.rows.class_row + assert dialect.unsupported_row_factory(cursor) is psycopg.rows.class_row + assert dialect.unsupported_row_factory(mocker.MagicMock()) is None + + +def test_insert_returning_id_times_out_with_socket_timeout(mocker, timeout_dialect, wait_then_return): + dialect, event = timeout_dialect + conn = mocker.MagicMock() + conn.cursor.return_value.fetchone.side_effect = wait_then_return(event, (7,)) + with pytest.raises(QueryTimeoutError): + dialect.insert_returning_id(conn, "INSERT INTO t (name) VALUES (%s)", ("a",)) + + +@pytest.mark.parametrize("params, binds", [ + (None, False), ({}, True), ([], True), ((), True), ({"a": 1}, True), ([1], True)]) +def test_binds_parameters_any_parameters(params, binds): + assert PgDriverDialect.binds_parameters(params) is binds + + +def test_reencrypt_sql_pins_pg_catalog_operators(): + assert PgDriverDialect.greater_than_operator == "OPERATOR(pg_catalog.>)" + assert PgDriverDialect.quote_identifier("users") == '"users"' + sql = PgDriverDialect.key_column_type_sql + assert sql is not None + assert re.findall(r"(?]", sql.replace("OPERATOR(pg_catalog.=)", "")) == [] + assert "OPERATOR(pg_catalog.=)" in sql + + +@pytest.mark.parametrize("name", ["schema_table_sql", "schema_columns_sql", "schema_key_constraints_sql", + "schema_foreign_keys_sql"]) +def test_schema_check_sql_pins_pg_catalog(name): + sql = getattr(PgDriverDialect, name) + pinned = sql.replace("OPERATOR(pg_catalog.=)", "") + assert re.findall(r"[=<>]", pinned) == [] + assert re.findall(r"(? None: + target = MagicMock() + wrapper = _sync_wrapper(target) + wrapper._plugin_manager.execute = MagicMock( # type: ignore[method-assign] + side_effect=lambda obj, method, func, *a, **k: func()) + target_cursor = target.cursor.return_value + + copy = wrapper.cursor().copy("COPY t FROM STDIN", ("p",)) + + assert copy is target_cursor.copy.return_value + target_cursor.copy.assert_called_once_with("COPY t FROM STDIN", ("p",)) + method = wrapper._plugin_manager.execute.call_args.args[1] + assert method.method_name == "Cursor.copy" + + +def test_cursor_stream_goes_through_plugins() -> None: + target = MagicMock() + wrapper = _sync_wrapper(target) + wrapper._plugin_manager.execute = MagicMock( # type: ignore[method-assign] + side_effect=lambda obj, method, func, *a, **k: func()) + target_cursor = target.cursor.return_value + + rows = wrapper.cursor().stream("SELECT %s", ("p",), size=10) + + assert rows is target_cursor.stream.return_value + target_cursor.stream.assert_called_once_with("SELECT %s", ("p",), size=10) + method = wrapper._plugin_manager.execute.call_args.args[1] + assert method.method_name == "Cursor.stream" + + +@pytest.mark.parametrize("name, args, method_name", [ + ("results", (), "Cursor.results"), + ("set_result", (1,), "Cursor.set_result"), +]) +def test_cursor_results_and_set_result_go_through_plugins(name, args, method_name) -> None: + target = MagicMock() + wrapper = _sync_wrapper(target) + wrapper._plugin_manager.execute = MagicMock( # type: ignore[method-assign] + side_effect=lambda obj, method, func, *a, **k: func()) + target_method = getattr(target.cursor.return_value, name) + + result = getattr(wrapper.cursor(), name)(*args) + + assert result is target_method.return_value + target_method.assert_called_once_with(*args) + method = wrapper._plugin_manager.execute.call_args.args[1] + assert method.method_name == method_name + + def test_sync_wrapper_wait_delegates() -> None: target = MagicMock() wrapper = _sync_wrapper(target) diff --git a/tests/unit/test_sql_alchemy_driver_dialect.py b/tests/unit/test_sql_alchemy_driver_dialect.py index 4be7a11f8..997d2efb7 100644 --- a/tests/unit/test_sql_alchemy_driver_dialect.py +++ b/tests/unit/test_sql_alchemy_driver_dialect.py @@ -123,7 +123,7 @@ def test_transfer_session_states_with_null_connection(underlying_dialect, sqlalc sqlalchemy_dialect.set_read_only(sqlalchemy_mock_conn, False) -def test_loop_start_runs_on_the_calling_thread_with_socket_timeout(sqlalchemy_mock_conn): +def test_loop_start_runs_on_calling_thread_with_socket_timeout(sqlalchemy_mock_conn): props = Properties({"socket_timeout": "5"}) sqlalchemy_dialect = SqlAlchemyDriverDialect(PgDriverDialect(props), props) threads = [] @@ -135,7 +135,7 @@ def test_loop_start_runs_on_the_calling_thread_with_socket_timeout(sqlalchemy_mo @pytest.mark.parametrize("method", [DbApiMethod.CURSOR_FETCHONE, DbApiMethod.CURSOR_NEXT], ids=["fetchone", "next"]) -def test_fetch_still_runs_on_the_timeout_worker_with_socket_timeout(method, sqlalchemy_mock_conn): +def test_fetch_runs_on_timeout_worker_with_socket_timeout(method, sqlalchemy_mock_conn): props = Properties({"socket_timeout": "5"}) sqlalchemy_dialect = SqlAlchemyDriverDialect(PgDriverDialect(props), props) threads = [] @@ -143,4 +143,5 @@ def test_fetch_still_runs_on_the_timeout_worker_with_socket_timeout(method, sqla sqlalchemy_dialect.execute( method.method_name, lambda: threads.append(threading.current_thread()), conn=sqlalchemy_mock_conn) - assert len(threads) == 1 and threads[0] is not threading.current_thread() + assert len(threads) == 1 + assert threads[0] is not threading.current_thread() diff --git a/tests/unit/test_sql_analyzer.py b/tests/unit/test_sql_analyzer.py index 89250d59d..2938bc88a 100644 --- a/tests/unit/test_sql_analyzer.py +++ b/tests/unit/test_sql_analyzer.py @@ -26,10 +26,14 @@ StatementKind, TableRef, analyze) -from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG from aws_advanced_python_wrapper.encryption.sql_tokenizer import (ColumnRef, ParamStyle, tokenize) +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect + +PG = PgDriverDialect +MYSQL = MySQLDriverDialect @pytest.fixture(autouse=True) @@ -70,14 +74,16 @@ def on(both=(), pg=(), mysql=()): """Parametrizes ``dialect, sql``: each of ``both`` on PostgreSQL and on MySQL, then each of ``pg`` and ``mysql`` on its own dialect.""" cases = [(d, s) for s in both for d in (PG, MYSQL)] + [(PG, s) for s in pg] + [(MYSQL, s) for s in mysql] - return pytest.mark.parametrize("dialect, sql", cases, ids=[f"{d.name}: {s}" for d, s in cases]) + return pytest.mark.parametrize("dialect, sql", cases, ids=[f"{d.sqlglot_dialect}: {s}" for d, s in cases]) class TestInsert: @BOTH def test_columns_pair_with_their_placeholders(self, dialect): a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s)", dialect, P) - assert a.kind is StatementKind.INSERT and a.writes and a.complete + assert a.kind is StatementKind.INSERT + assert a.writes + assert a.complete assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] assert names(a.written_tables) == ["users"] assert a.parameter_columns() == {0: ColumnRef("name", "users"), 1: ColumnRef("ssn", "users")} @@ -121,7 +127,8 @@ def test_casts_are_outermost_first(self): @BOTH def test_no_column_list(self, dialect): a = analyze("INSERT INTO users VALUES (%s, %s)", dialect, P) - assert a.writes and a.gap is AnalysisGap.NO_COLUMN_LIST + assert a.writes + assert a.gap is AnalysisGap.NO_COLUMN_LIST assert assigned(a) == [] def test_default_values(self): @@ -133,7 +140,8 @@ def test_insert_select(self, dialect): assert a.gap is AnalysisGap.VALUES_FROM_QUERY assert assigned(a) == [] assert compared(a) == [(0, "staging.id")] - assert names(a.tables) == ["users", "staging"] and names(a.written_tables) == ["users"] + assert names(a.tables) == ["users", "staging"] + assert names(a.written_tables) == ["users"] @BOTH def test_row_length_mismatch(self, dialect): @@ -161,7 +169,7 @@ def test_on_conflict_assignments(self): assert unbound(a) == ["users.note"] assert compared(a) == [(3, "users.age")] - def test_excluded_copy_of_the_same_column_is_not_a_write(self): + def test_excluded_same_column_is_not_write(self): a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT (id) DO UPDATE SET ssn = EXCLUDED.ssn", PG, P) assert unbound(a) == [] @@ -173,7 +181,8 @@ def test_excluded_copy_of_another_column_is(self): def test_on_conflict_do_nothing(self): a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT DO NOTHING", PG, P) - assert assigned(a) == [(0, "users.ssn")] and a.complete + assert assigned(a) == [(0, "users.ssn")] + assert a.complete def test_on_duplicate_key_update(self): a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " @@ -214,7 +223,9 @@ class TestUpdate: @BOTH def test_set_and_where(self, dialect): a = analyze("UPDATE users SET ssn = %s, name = 'x' WHERE id = %s", dialect, P) - assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert a.kind is StatementKind.UPDATE + assert a.writes + assert a.complete assert assigned(a) == [(0, "users.ssn")] assert unbound(a) == ["users.name"] assert compared(a) == [(1, "users.id")] @@ -244,14 +255,15 @@ def test_mysql_multi_table_qualified(self): def test_mysql_multi_table_comma(self): a = analyze("UPDATE users, orders SET users.ssn = %s WHERE users.id = orders.uid", MYSQL, P) - assert assigned(a) == [(0, "users.ssn")] and a.complete + assert assigned(a) == [(0, "users.ssn")] + assert a.complete def test_mysql_multi_table_unqualified_is_ambiguous(self): a = analyze("UPDATE users u JOIN orders o ON o.uid = u.id SET ssn = %s", MYSQL, P) assert a.gap is AnalysisGap.AMBIGUOUS_TABLE assert assigned(a) == [(0, "ssn")] - def test_postgresql_from_does_not_add_a_written_table(self): + def test_postgresql_from_adds_no_written_table(self): a = analyze("UPDATE users SET ssn = %s FROM other o WHERE o.id = users.id AND o.ssn = %s", PG, P) assert names(a.written_tables) == ["users"] assert assigned(a) == [(0, "users.ssn")] @@ -276,7 +288,9 @@ def test_merge(self): "WHEN MATCHED AND s.flag = %s THEN UPDATE SET ssn = %s " "WHEN MATCHED THEN DELETE " "WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (%s, s.ssn)", PG, P) - assert a.kind is StatementKind.MERGE and a.writes and a.complete + assert a.kind is StatementKind.MERGE + assert a.writes + assert a.complete assert assigned(a) == [(1, "users.ssn"), (2, "users.id")] assert unbound(a) == ["users.ssn"] assert compared(a) == [(0, "src.flag")] @@ -289,23 +303,30 @@ def test_merge_insert_without_columns(self): def test_merge_that_only_deletes(self): a = analyze("MERGE INTO users u USING src s ON u.id = s.id WHEN MATCHED THEN DELETE", PG) - assert a.writes and a.complete and assigned(a) == [] and unbound(a) == [] + assert a.writes + assert a.complete + assert assigned(a) == [] + assert unbound(a) == [] def test_data_modifying_cte(self): a = analyze("WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", PG, P) - assert a.kind is StatementKind.SELECT and a.writes + assert a.kind is StatementKind.SELECT + assert a.writes assert assigned(a) == [(0, "users.ssn")] - assert names(a.tables) == ["users"] # w is a CTE, not a table + # The CTE w is not a table. + assert names(a.tables) == ["users"] def test_update_cte(self): a = analyze("WITH w AS (UPDATE users SET ssn = %s WHERE id = %s RETURNING id) SELECT id FROM w", PG, P) - assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "users.id")] - def test_read_only_cte_is_a_read(self): + def test_read_only_cte_is_read(self): a = analyze("WITH w AS (SELECT ssn FROM users) SELECT ssn FROM w WHERE ssn = %s", PG, P) assert not a.writes assert names(a.tables) == ["users"] - assert compared(a) == [(0, "ssn")] # a CTE column has no table + # A CTE column has no table. + assert compared(a) == [(0, "ssn")] assert a.result_columns == (ColumnRef("ssn", "users"),) def test_cte_insert_select(self): @@ -314,33 +335,61 @@ def test_cte_insert_select(self): def test_copy_from_names_unbound_columns(self): a = analyze("COPY users (name, ssn) FROM STDIN", PG) - assert a.kind is StatementKind.COPY_FROM and a.writes and a.complete + assert a.kind is StatementKind.COPY_FROM + assert a.writes + assert a.complete assert unbound(a) == ["users.name", "users.ssn"] def test_copy_from_without_columns(self): assert analyze("COPY users FROM STDIN WITH (FORMAT csv)", PG).gap is AnalysisGap.NO_COLUMN_LIST - def test_copy_to_is_a_read(self): + def test_copy_to_is_read(self): a = analyze("COPY users TO STDOUT", PG) - assert a.kind is StatementKind.COPY_TO and not a.writes + assert a.kind is StatementKind.COPY_TO + assert not a.writes assert names(a.tables) == ["users"] def test_copy_query_to(self): a = analyze("COPY (SELECT ssn FROM users) TO STDOUT", PG) - assert not a.writes and names(a.tables) == ["users"] + assert not a.writes + assert names(a.tables) == ["users"] + + def test_copy_from_options_without_with(self): + a = analyze("COPY users (id) FROM STDIN (FORMAT binary)", PG) + assert a.kind is StatementKind.COPY_FROM + assert a.gap is None + assert unbound(a) == ["users.id"] + + def test_copy_query_to_options_without_with(self): + a = analyze("COPY (SELECT ssn FROM users) TO STDOUT (FORMAT csv)", PG) + assert a.kind is StatementKind.COPY_TO + assert not a.writes + assert a.gap is None + + @pytest.mark.parametrize("sql", [ + "COPY (INSERT INTO users (ssn) VALUES ('x') RETURNING id) TO STDOUT", + "COPY (UPDATE users SET ssn = 'x' RETURNING id) TO STDOUT", + ]) + def test_copy_of_writing_query_may_write(self, sql): + a = analyze(sql, PG) + assert a.writes + assert a.gap is not None def test_several_statements_are_all_read(self): # The ordinals run across the whole string, so each statement's # placeholders still map to the right parameters. a = analyze("UPDATE t SET a = %s; INSERT INTO users (name, ssn) VALUES (%s, %s)", MYSQL, P) - assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert a.kind is StatementKind.UPDATE + assert a.writes + assert a.complete assert assigned(a) == [(0, "t.a"), (1, "users.name"), (2, "users.ssn")] assert a.result_columns is None @BOTH def test_delete(self, dialect): a = analyze("DELETE FROM users WHERE ssn = %s", dialect, P) - assert a.kind is StatementKind.DELETE and not a.writes + assert a.kind is StatementKind.DELETE + assert not a.writes assert compared(a) == [(0, "users.ssn")] def test_mysql_multi_table_delete(self): @@ -362,7 +411,7 @@ def test_a_parenthesized_column_is_paired_with_its_value(self, dialect): (4, "users.ssn"), (5, "users.ssn")] @BOTH - def test_a_sub_selects_only_column_is_paired_with_the_value(self, dialect): + def test_sub_select_only_column_paired_with_value(self, dialect): # The sub-select's rows hold that column's values, and its column is resolved in the sub-select, not in t. a = analyze("SELECT name FROM t WHERE %s IN (SELECT ssn FROM users) AND %s = ANY (SELECT u.dob FROM users u) " "AND %s = SOME (SELECT ssn AS s FROM users) AND %s <> ALL (SELECT ((ssn)) FROM users) " @@ -390,7 +439,7 @@ def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_paired(self, d assert not any(u.array for u in a.comparisons) @BOTH - def test_all_or_some_over_anything_but_a_sub_select_of_the_column_is_not_paired(self, dialect): + def test_all_or_some_without_column_sub_select_not_paired(self, dialect): # The last two compare the value with the elements of an array column, not with the column. a = analyze("SELECT name FROM t WHERE %s <> ALL ((SELECT ssn FROM users UNION SELECT ssn FROM archive)) " "AND %s = SOME ((SELECT lower(ssn) FROM users)) " @@ -427,20 +476,21 @@ def test_subquery_scope(self): PG, P) assert compared(a) == [(0, "orders.total"), (1, "users.ssn")] - def test_correlated_qualifier_from_an_outer_query(self): + def test_correlated_qualifier_from_outer_query(self): a = analyze("SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.uid = u.id AND u.ssn = %s)", PG, P) assert compared(a) == [(0, "users.ssn")] - def test_column_against_column_is_not_a_parameter(self): + def test_column_against_column_is_not_parameter(self): assert compared(analyze("SELECT * FROM t WHERE a = b", PG)) == [] def test_jsonb_question_mark_operator(self): # "?" is an operator on PostgreSQL, not a placeholder. a = analyze("SELECT ssn FROM users WHERE data ? 'k' AND id = %s", PG, P) - assert a.complete and compared(a) == [(0, "users.id")] + assert a.complete + assert compared(a) == [(0, "users.id")] - def test_unknown_qualifier_is_taken_as_a_table(self): + def test_unknown_qualifier_taken_as_table(self): assert compared(analyze("SELECT * FROM users WHERE other.ssn = %s", PG, P)) == [(0, "other.ssn")] @@ -464,7 +514,8 @@ class TestComparisonSafety: "SELECT id FROM users WHERE ssn <=> %s"]) def test_safe_operators(self, dialect, sql): flags = safety(sql, dialect) - assert flags and all(flags) + assert flags + assert all(flags) @on(both=["SELECT id FROM users WHERE ssn <> %s", "SELECT id FROM users WHERE %s <> ssn", @@ -487,17 +538,18 @@ def test_safe_operators(self, dialect, sql): "SELECT id FROM users WHERE ssn NOT LIKE ANY(%s)"]) def test_unsafe_operators(self, dialect, sql): flags = safety(sql, dialect) - assert flags and not any(flags) + assert flags + assert not any(flags) @BOTH - def test_a_parenthesized_column_is_judged_like_the_column(self, dialect): + def test_parenthesized_column_judged_like_column(self, dialect): # sqlglot keeps the parentheses as a Paren node around the column. assert safety("SELECT id FROM users WHERE (ssn) = %s OR ((ssn)) LIKE %s", dialect) == [True, True] assert safety("DELETE FROM users WHERE (ssn) <> %s", dialect) == [False] assert safety("DELETE FROM users WHERE %s <> (ssn) OR ((ssn)) NOT LIKE %s", dialect) == [False, False] @BOTH - def test_a_sub_selects_only_column_is_judged_like_the_column(self, dialect): + def test_sub_select_only_column_judged_like_column(self, dialect): assert safety("SELECT id FROM t WHERE %s IN (SELECT ssn FROM users) OR %s = ANY (SELECT ssn FROM users) " "OR %s = (SELECT ssn FROM users LIMIT 1)", dialect) == [True] * 3 # = ALL over no rows is true, so only ALL itself makes it unsafe. @@ -508,7 +560,7 @@ def test_a_sub_selects_only_column_is_judged_like_the_column(self, dialect): assert safety("SELECT %s IN (SELECT ssn FROM users) FROM t", dialect) == [False] @BOTH - def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_judged_like_the_column(self, dialect): + def test_all_or_some_doubled_parentheses_sub_select_judged_like_column(self, dialect): assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users)) " "OR %s = some (((select ssn from users)))", dialect) == [True, True] unsafe = ["%s <> ALL ((SELECT ssn FROM users))", "%s = ALL ((SELECT ssn FROM users))", @@ -525,7 +577,7 @@ def test_a_sub_select_read_by_some_in_doubled_parentheses_is_judged_like_any(sel assert safety("DELETE FROM orders WHERE uid <> SOME ((SELECT id FROM users WHERE ssn = %s))", dialect) == [False] @BOTH - def test_a_sub_select_with_order_by_or_limit_after_its_parentheses_is_judged_like_the_column(self, dialect): + def test_sub_select_order_by_or_limit_after_parentheses_judged_like_column(self, dialect): assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users) LIMIT 5)", dialect) == [True] unsafe = ["%s <> ALL ((SELECT ssn FROM users) ORDER BY 1)", "%s <> ALL ((SELECT ssn FROM users) LIMIT 5)", "%s = all ((select ssn from users) order by 1 limit 5)"] @@ -543,12 +595,14 @@ def test_a_read_sub_select_with_order_by_or_limit_after_its_parentheses_is_judge assert [safety(f"DELETE FROM orders WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) @BOTH - def test_not_like_is_unsafe_without_a_not_node(self, dialect): + def test_not_like_unsafe_without_not_node(self, dialect): sql = "SELECT id FROM users WHERE ssn NOT LIKE %s" trees, _ = sql_analyzer._parse(tokenize(sql, dialect, ParamStyle.of(P, dialect)).normalized, dialect) # sqlglot sets the LIKE's negate flag rather than adding a NOT node, # so only the operator check can see the negation. - assert trees and trees[0].find(exp.Not) is None and trees[0].find(exp.Like).args.get("negate") + assert trees + assert trees[0].find(exp.Not) is None + assert trees[0].find(exp.Like).args.get("negate") assert safety(sql, dialect) == [False] @on(both=["SELECT id FROM users WHERE (ssn = %s)", @@ -606,7 +660,8 @@ def test_not_like_is_unsafe_without_a_not_node(self, dialect): "WITH users AS (SELECT id FROM mydb.users WHERE ssn = %s) SELECT id FROM users"]) def test_safe_positions(self, dialect, sql): flags = safety(sql, dialect) - assert flags and all(flags) + assert flags + assert all(flags) @on(both=["SELECT id FROM users WHERE NOT ssn = %s", "SELECT id FROM users WHERE NOT (ssn = %s OR id = 1)", @@ -666,7 +721,8 @@ def test_safe_positions(self, dialect, sql): "UPDATE users u LEFT JOIN orders o ON o.uid = u.id AND u.ssn = %s SET u.note = 'x' WHERE o.uid IS NULL"]) def test_unsafe_positions(self, dialect, sql): flags = safety(sql, dialect) - assert flags and not any(flags) + assert flags + assert not any(flags) @pytest.mark.parametrize("dialect, sql, column", [ (PG, "SELECT i.id FROM users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", @@ -703,7 +759,7 @@ def test_unsafe_positions(self, dialect, sql): "mysql-parenthesized-under-left", "pg-right-inside-parentheses", "pg-right-inside-a-joined-parenthesis", "mysql-right-inside-a-joined-parenthesis", "pg-update-from", "pg-delete-using", "mysql-update", "mysql-delete-using", "pg-right-around-nested-parentheses", "mysql-delete-right-around-nested-parentheses"]) - def test_inner_join_in_a_query_with_an_outer_join_is_unsafe(self, dialect, sql, column): + def test_inner_join_with_outer_join_is_unsafe(self, dialect, sql, column): # A later RIGHT or FULL join keeps every row of its side when the # earlier join matches nothing, and so does a LEFT join around a # parenthesized join. A WHERE filters the joined rows. @@ -721,7 +777,7 @@ def test_inner_join_in_a_query_with_an_outer_join_is_unsafe(self, dialect, sql, "RIGHT JOIN refs r ON r.iid = items.id)"), ], ids=["pg-update-from-derived-table", "pg-delete-using-derived-table", "mysql-update-derived-table", "pg-derived-table-in-nested-parentheses"]) - def test_outer_join_after_a_parenthesized_source_is_seen(self, dialect, sql): + def test_outer_join_after_parenthesized_source_is_seen(self, dialect, sql): # sqlglot hangs the joins that follow a derived table or a # parenthesized join on its Subquery. When the derived table d matches # nothing, the sided join there still keeps every row of its other side. @@ -756,7 +812,7 @@ def test_aggregating_sub_select_is_unsafe(self, dialect, sql, safe): (PG, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s WINDOW w AS (ORDER BY COUNT(*)))"), ], ids=["pg-jsonb-agg", "mysql-json-arrayagg", "pg-user-defined", "mysql-user-defined", "pg-order-by", "mysql-order-by", "pg-distinct-on", "pg-window-clause"]) - def test_possible_aggregate_in_a_sub_select_is_unsafe(self, dialect, sql): + def test_possible_aggregate_in_sub_select_is_unsafe(self, dialect, sql): # An aggregate without GROUP BY returns a row for no input row, so the # EXISTS holds and every order is deleted. sqlglot reads some built-in # aggregates and every user-defined one as a function it doesn't know, @@ -783,7 +839,7 @@ def test_long_cte_chain_is_followed_without_recursion(self, dialect): assert safety("WITH " + ", ".join(ctes) + " SELECT id FROM c1999", dialect) == [True] @BOTH - def test_assignments_and_annotations_keep_the_default(self, dialect): + def test_assignments_and_annotations_keep_default(self, dialect): a = analyze("UPDATE users SET ssn = %s WHERE id <> /*@encrypt:users.ssn*/ %s", dialect, P) assert [(u.ordinal, u.safe) for u in a.assignments] == [(0, True)] assert [(u.ordinal, u.safe) for u in a.annotations] == [(1, True)] @@ -792,19 +848,21 @@ def test_assignments_and_annotations_keep_the_default(self, dialect): == [True, True] @pytest.mark.timeout(10) - def test_comparison_safety_is_time_bounded_in_a_long_or_chain(self): + def test_comparison_safety_long_or_chain_is_time_bounded(self): # Without the memo, each comparison climbs the rest of the chain: far # past the timeout at this length. sql = "SELECT id FROM users WHERE " + " OR ".join(["ssn = %s"] * 40000) flags = safety(sql, PG) - assert len(flags) == 40000 and all(flags) + assert len(flags) == 40000 + assert all(flags) class TestReads: @BOTH def test_tables_and_result_columns(self, dialect): a = analyze("SELECT u.ssn AS s, o.ssn, name, 1 FROM users u JOIN orders o ON o.uid = u.id", dialect) - assert a.kind is StatementKind.SELECT and not a.writes + assert a.kind is StatementKind.SELECT + assert not a.writes assert names(a.tables) == ["users", "orders"] assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("ssn", "orders"), None, None) @@ -880,25 +938,79 @@ def test_self_shadowing_cte_stays_unknown(self, dialect): ("WITH users AS (SELECT addr AS ssn FROM homes) SELECT z.ssn FROM (WITH RECURSIVE c AS (SELECT ssn FROM users), " "users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c) z", (None,)), ], ids=["forward", "forward_qualified", "forward_in_derived", "backward", "nested_outer", "nested_outer_recursive"]) - def test_a_cte_sees_only_the_ctes_before_it(self, dialect, sql, expected): + def test_cte_sees_only_earlier_ctes(self, dialect, sql, expected): assert analyze(sql, dialect).result_columns == expected @BOTH + @pytest.mark.parametrize("sql, expected", [ + ("WITH c(ssn, name) AS (SELECT name, ssn FROM users) SELECT c.ssn, c.name FROM c", + (ColumnRef("name", "users"), ColumnRef("ssn", "users"))), + ("SELECT x.ssn, x.name FROM (SELECT name, ssn FROM users) AS x(ssn, name)", + (ColumnRef("name", "users"), ColumnRef("ssn", "users"))), + ("SELECT x FROM (SELECT ssn FROM users) AS t(x)", (ColumnRef("ssn", "users"),)), + ("WITH c(x) AS (SELECT ssn FROM users) SELECT x FROM c", (ColumnRef("ssn", "users"),)), + ], ids=["cte", "derived", "derived_renamed", "cte_renamed"]) + def test_derived_table_column_list_traced_by_position(self, dialect, sql, expected): + assert analyze(sql, dialect).result_columns == expected + + @BOTH + def test_cte_column_list_traced_by_position(self, dialect): + a = analyze("WITH c(x, y) AS (SELECT ssn, name FROM users) SELECT y, x FROM c", dialect) + assert a.result_columns == (ColumnRef("name", "users"), ColumnRef("ssn", "users")) + + def test_partial_cte_column_list_traced(self): + # PostgreSQL renames the first columns only. + a = analyze("WITH c(x) AS (SELECT ssn, name FROM users) SELECT x, name FROM c", PG) + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("name", "users")) + + def test_items_past_column_list_keep_their_names(self): + a = analyze("SELECT x, name FROM (SELECT ssn, name FROM users) AS t(x)", PG) + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("name", "users")) + + @BOTH + @pytest.mark.parametrize("sql", [ + "SELECT x FROM (SELECT ssn FROM users UNION ALL SELECT name FROM people) AS d(x)", + "SELECT x FROM (SELECT name FROM people UNION ALL SELECT ssn FROM users) AS d(x)", + "WITH RECURSIVE c(x) AS (SELECT ssn FROM users UNION ALL SELECT x FROM c) SELECT x FROM c", + "SELECT x FROM (SELECT *, ssn FROM users) AS t(x)", + "SELECT y FROM (SELECT ssn FROM users) AS t(x, y)", + "SELECT ssn FROM (SELECT ssn, name FROM users) AS t(x)", + ], ids=["union", "union_reversed", "recursive_cte", "star", "more_names_than_items", "renamed_away"]) + def test_column_list_over_untraceable_query_stays_unknown(self, dialect, sql): + assert analyze(sql, dialect).result_columns == (None,) + + def test_values_with_column_list_stays_unknown(self): + assert analyze("SELECT x FROM (VALUES (1)) AS v(x)", PG).result_columns == (None,) + @pytest.mark.parametrize("sql", [ - "WITH c(ssn, name) AS (SELECT name, ssn FROM users) SELECT c.ssn, c.name FROM c", - "SELECT x.ssn, x.name FROM (SELECT name, ssn FROM users) AS x(ssn, name)", - ], ids=["cte", "derived"]) - def test_a_source_with_a_column_list_stays_unknown(self, dialect, sql): - # The list renames the columns by position (here c.ssn is users.name), - # which the trace doesn't follow. - assert analyze(sql, dialect).result_columns == (None, None) + "SELECT x FROM (SELECT ssn FROM users) AS t(x int)", + "WITH c(a) AS (SELECT ssn FROM users) SELECT y FROM c AS x(y)", + "WITH c AS (SELECT ssn FROM users) SELECT x FROM c AS t(x int)", + ], ids=["typed_list", "cte_and_alias_lists", "typed_list_on_cte"]) + def test_column_list_that_cannot_be_read_stays_unknown(self, sql): + assert analyze(sql, PG).result_columns == (None,) + + @BOTH + @pytest.mark.parametrize("sql, expected", [ + ("SELECT *, ssn AS x FROM users", (("x", ColumnRef("ssn", "users")),)), + ("SELECT *, upper(name) AS x FROM users", (("x", None),)), + ("SELECT * FROM (SELECT ssn AS x FROM users) s", (("x", ColumnRef("ssn", "users")),)), + ("SELECT * FROM (SELECT ssn FROM users) AS t(x)", (("x", ColumnRef("ssn", "users")),)), + ("SELECT x FROM (SELECT ssn AS x FROM users) a JOIN (SELECT name AS x FROM people) b ON a.x = b.x", + (("x", ColumnRef("ssn", "users")), ("x", ColumnRef("name", "people")))), + ("SELECT ssn FROM users", ()), + ("SELECT users.* AS x FROM users", (("x", None),)), + ], ids=["beside_star", "expression_beside_star", "star_over_derived", "star_over_column_list", "two_derived", + "plain", "aliased_star"]) + def test_named_columns_give_traced_sources(self, dialect, sql, expected): + assert analyze(sql, dialect).named_columns == expected @pytest.mark.parametrize("sql, expected", [ - ("WITH c AS (SELECT name, ssn FROM users) SELECT x.ssn FROM c AS x(ssn, name)", (None,)), + ("WITH c AS (SELECT name, ssn FROM users) SELECT x.ssn FROM c AS x(ssn, name)", (ColumnRef("name", "users"),)), ("SELECT d.ssn FROM users AS u(a, b) JOIN (SELECT id, ssn FROM archive) d ON d.id = u.a", (ColumnRef("ssn", "archive"),)), ], ids=["cte_renamed_where_read", "other_source_renamed"]) - def test_only_a_column_list_on_the_traced_source_matters(self, sql, expected): + def test_column_list_only_on_traced_source_matters(self, sql, expected): assert analyze(sql, PG).result_columns == expected def test_returning_list_is_not_traced(self): @@ -934,7 +1046,7 @@ def test_union_tables(self): assert names(analyze("SELECT ssn FROM users UNION ALL SELECT ssn FROM archive", PG).tables) == [ "users", "archive"] - def test_for_update_is_not_a_write(self): + def test_for_update_is_not_write(self): assert not analyze("SELECT * FROM users WHERE id = %s FOR UPDATE", PG, P).writes @@ -960,7 +1072,8 @@ def test_mysql_keeps_case_and_strips_backticks(self): def test_mysql_alias_match_is_case_insensitive(self): a = analyze("UPDATE users U SET u.ssn = %s WHERE U.id = %s", MYSQL, P) - assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "users.id")] def test_quoted_alias(self): a = analyze('SELECT "U".ssn FROM users "U" WHERE "U".id = %s', PG, P) @@ -977,12 +1090,12 @@ def test_alias_qualifier_is_resolved(self): a = analyze("UPDATE users u SET note = /*@encrypt:u.ssn*/ %s", PG, P) assert [str(u.column) for u in a.annotations] == ["users.ssn"] - def test_annotations_survive_an_unparseable_statement(self): + def test_annotations_survive_unparseable_statement(self): a = analyze("INSERT INTO t OVERRIDING SYSTEM VALUE VALUES (/*@encrypt:t.ssn*/ %s)", PG, P) assert a.gap is AnalysisGap.UNPARSEABLE assert [str(u.column) for u in a.annotations] == ["t.ssn"] - def test_annotations_survive_an_unsupported_statement(self): + def test_annotations_survive_unsupported_statement(self): a = analyze("EXPLAIN ANALYZE INSERT INTO t (a) VALUES (/*@encrypt:t.a*/ %s)", PG, P) assert [str(u.column) for u in a.annotations] == ["t.a"] @@ -1007,8 +1120,11 @@ class TestNotEstablished: ]) def test_writes_not_established(self, dialect, sql, params, gap): a = analyze(sql, dialect, params) - assert a.writes and a.gap is gap and not a.complete - assert a.assignments == () and a.unbound_writes == () + assert a.writes + assert a.gap is gap + assert not a.complete + assert a.assignments == () + assert a.unbound_writes == () @pytest.mark.parametrize("dialect, sql, tables", [ (PG, "INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), @@ -1033,25 +1149,54 @@ def test_writes_not_established(self, dialect, sql, params, gap): ], ids=["pg_literal", "pg_identifier_select", "pg_comment", "pg_join", "pg_cte", "pg_prepare", "mysql_literal", "mysql_identifier_select", "mysql_comment", "mysql_identifier", "mysql_join", "mysql_qualified_columns", "pg_set_then_insert", "pg_create_table_as", "mysql_explain_insert", "mysql_describe_select"]) - def test_hidden_placeholder_gap_still_lists_the_tables(self, dialect, sql, tables): + def test_hidden_placeholder_gap_lists_tables(self, dialect, sql, tables): # The tables are what lets a caller refuse such a statement when one # of them has encrypted columns; the placeholders still can't be # paired with columns, so nothing else is reported. a = analyze(sql, dialect, P) - assert a.gap is AnalysisGap.HIDDEN_PLACEHOLDER and a.kind is StatementKind.UNKNOWN - assert a.tables == tables - assert a.assignments == () and a.comparisons == () and a.annotations == () and a.result_columns is None + assert a.gap is AnalysisGap.HIDDEN_PLACEHOLDER + assert a.kind is StatementKind.UNKNOWN + # The parsed tables first, then the other names that could be tables. + assert a.tables[:len(tables)] == tables + assert a.assignments == () + assert a.comparisons == () + assert a.annotations == () + assert a.result_columns is None + + @pytest.mark.parametrize("dialect, sql, gap, tables", [ + (MYSQL, "UPDATE plain_t /*! JOIN users ON users.id = plain_t.id */ SET users.ssn = %s", + AnalysisGap.EXECUTABLE_COMMENT, ["plain_t", "users"]), + (MYSQL, "INSERT INTO plain_t (a) VALUES (/*@encrypt:users.ssn*/ %s) /*!50000 */", + AnalysisGap.EXECUTABLE_COMMENT, ["plain_t", "users"]), + (MYSQL, "UPDATE (`users` u) SET u.ssn = %s", AnalysisGap.UNPARSEABLE, ["users"]), + (MYSQL, "DELETE u FROM (users u) WHERE u.ssn = %s", AnalysisGap.UNPARSEABLE, ["users"]), + (MYSQL, "INSERT INTO users (name, ssn) VALUES ('a\\', %s)", AnalysisGap.UNPARSEABLE, ["users"]), + (PG, 'UPDATE "Users" SET ssn = %s WHERE id = %s,,', AnalysisGap.UNPARSEABLE, ["Users"]), + (PG, "SELECT * FROM users WHERE ssn = %s LIMIT 1,,", AnalysisGap.UNPARSEABLE, ["users"]), + ], ids=["mysql-comment-join", "mysql-comment-annotation", "mysql-paren-update", "mysql-paren-delete", + "mysql-backslash", "pg-quoted", "pg-parse-failure"]) + def test_unreadable_statement_reports_named_tables(self, dialect, sql, gap, tables): + a = analyze(sql, dialect, P) + assert a.gap is gap + assert set(tables) <= set(names(a.tables)) - def test_unparseable_read_is_not_a_write(self): + def test_driver_error_lists_no_tables(self): + a = analyze("INSERT INTO t (a) VALUES (%s, %(x)s)", PG, P) + assert a.gap is AnalysisGap.DRIVER_ERROR + assert a.tables == () + + def test_unparseable_read_is_not_write(self): a = analyze("SELECT FROM WHERE %s", PG, P) - assert a.kind is StatementKind.UNKNOWN and not a.writes + assert a.kind is StatementKind.UNKNOWN + assert not a.writes @pytest.mark.parametrize("sql", ["CREATE TABLE t (a int)", "BEGIN", "CALL p(1)", "", " -- just a comment"]) def test_statements_that_write_no_column(self, sql): a = analyze(sql, PG) - assert not a.writes and a.complete + assert not a.writes + assert a.complete - def test_placeholder_text_in_the_sql_is_a_mismatch(self): + def test_placeholder_text_in_sql_is_mismatch(self): # Something that looks like a normalized placeholder must not be # taken for one. a = analyze("INSERT INTO t (a, b) VALUES (%s, :_kms_p0)", PG, P) @@ -1062,12 +1207,14 @@ def boom(*_args, **_kwargs): raise RecursionError("too deep") monkeypatch.setattr(sql_analyzer.sqlglot, "parse", boom) a = sql_analyzer._analysis("INSERT INTO t (a) VALUES (%s)", PG, sql_analyzer.ParamStyle.POSITIONAL) - assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "RecursionError" + assert a.gap is AnalysisGap.UNPARSEABLE + assert a.detail == "RecursionError" def test_mysql_without_params_leaves_percent_s(self): # Connector/Python sends %s as written when there are no parameters. a = analyze("INSERT INTO t (a) VALUES (%s)", MYSQL, ()) - assert a.placeholders == () and a.gap is AnalysisGap.UNPARSEABLE + assert a.placeholders == () + assert a.gap is AnalysisGap.UNPARSEABLE class TestApi: @@ -1087,7 +1234,8 @@ def test_long_sql_is_not_cached(self): sql = f"INSERT INTO users (name, ssn) VALUES {rows}" assert len(sql) > sql_analyzer.CACHEABLE_SQL_LENGTH a = analyze(sql, MYSQL, P) - assert len(a.assignments) == 4000 and a.assignments[-1].ordinal == 3999 + assert len(a.assignments) == 4000 + assert a.assignments[-1].ordinal == 3999 assert analyze(sql, MYSQL, P) is not a def test_short_sql_with_many_placeholders_is_not_cached(self): @@ -1123,7 +1271,7 @@ def flaky(sql, read): assert analyze(sql, PG, P).gap is AnalysisGap.UNPARSEABLE assert analyze(sql, PG, P).gap is None - def test_deep_nesting_from_a_deep_stack_is_a_gap(self): + def test_deep_nesting_from_deep_stack_is_gap(self): sql = "UPDATE users SET ssn = " + "(" * 40 + "%s" + ")" * 40 result = [] @@ -1135,7 +1283,8 @@ def deep(n): thread = threading.Thread(target=deep, args=(sys.getrecursionlimit() - 200,)) thread.start() thread.join() - assert result and result[0].gap is AnalysisGap.UNPARSEABLE + assert result + assert result[0].gap is AnalysisGap.UNPARSEABLE def test_type_error_for_non_str(self): with pytest.raises(TypeError): @@ -1165,7 +1314,7 @@ def test_the_applications_own_sqlglot_logging_is_untouched(self, caplog): (MYSQL, "INSERT INTO t (c) VALUES (%(ssn 123-45-6789)d)", {"a": 1}), (PG, "INSERT INTO t (secret_col) VALUES ('top secret', %s", P), ]) - def test_detail_never_quotes_the_sql(self, dialect, sql, params): + def test_detail_never_quotes_sql(self, dialect, sql, params): a = analyze(sql, dialect, params) assert a.gap is not None assert a.detail is not None or a.gap is AnalysisGap.UNPARSEABLE @@ -1177,8 +1326,6 @@ class TestReviewRegressions: """Regression tests for statements the analysis once got wrong: annotation scopes, MySQL syntax, ORM-rendered SQL and statement kinds.""" - # ---- annotations resolve in the placeholder's own scope ---- - @pytest.mark.parametrize("dialect, sql, expected", [ (MYSQL, "UPDATE accounts u SET x = %s WHERE id = 1; UPDATE users u SET ssn = /*@encrypt:u.ssn*/ %s", {0: "accounts.x", 1: "users.ssn"}), @@ -1192,15 +1339,15 @@ class TestReviewRegressions: (PG, "SELECT 1 FROM accounts u UNION SELECT 1 FROM users u WHERE u.ssn = /*@encrypt:u.ssn*/ %s", {0: "users.ssn"}), ]) - def test_annotation_alias_is_resolved_where_the_placeholder_is(self, dialect, sql, expected): + def test_annotation_alias_resolved_at_placeholder(self, dialect, sql, expected): a = analyze(sql, dialect, P) assert {k: str(v) for k, v in a.parameter_columns().items()} == expected - def test_bare_annotation_keeps_the_table_the_analysis_found(self): + def test_bare_annotation_keeps_found_table(self): a = analyze("UPDATE users SET ssn = /*@encrypt:ssn*/ %s", PG, P) assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} - def test_bare_annotation_naming_another_column_takes_the_only_table(self): + def test_bare_annotation_other_column_takes_only_table(self): a = analyze("INSERT INTO users (note) VALUES (/*@encrypt:ssn*/ %s)", PG, P) assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} @@ -1217,8 +1364,6 @@ def test_annotations_survive_every_gap(self, sql): assert a.gap is not None assert [str(u.column) for u in a.annotations] == ["t.a"] - # ---- MySQL executable comments run on the server ---- - @pytest.mark.parametrize("sql", [ "INSERT INTO users (/*!80000 ssn, */ name) VALUES (%s /*!80000 , DEFAULT*/)", "INSERT INTO users (name, ssn) VALUES (%s, %s) /*! ON DUPLICATE KEY UPDATE ssn = 'plain' */", @@ -1233,28 +1378,31 @@ def test_executable_comment_is_not_established(self, sql): def test_executable_comment_write_keyword_counts(self): assert analyze("SELECT 1 /*! ; INSERT INTO t (a) VALUES (1) */", MYSQL).writes - def test_optimizer_hint_is_an_ordinary_comment(self): + def test_optimizer_hint_is_ordinary_comment(self): a = analyze("UPDATE /*+ NO_INDEX_MERGE(users) */ users SET ssn = %s", MYSQL, P) - assert a.complete and assigned(a) == [(0, "users.ssn")] - - # ---- MySQL charset introducers (Django renders binary values as _binary %s) ---- + assert a.complete + assert assigned(a) == [(0, "users.ssn")] + # Django renders a binary value as _binary %s. def test_binary_introducer_in_insert(self): a = analyze("INSERT INTO `Person` (`name`, `ssn`, `note`) VALUES (%s, _binary %s, %s), (%s, _binary %s, %s)", MYSQL, P) - assert a.complete and unbound(a) == [] + assert a.complete + assert unbound(a) == [] assert assigned(a) == [(0, "Person.name"), (1, "Person.ssn"), (2, "Person.note"), (3, "Person.name"), (4, "Person.ssn"), (5, "Person.note")] assert [p.introducer for p in a.placeholders] == [None, "_binary", None] * 2 def test_binary_introducer_in_update_and_upsert(self): a = analyze("UPDATE `Person` SET `ssn` = _binary %s, `name` = %s WHERE `Person`.`id` = %s", MYSQL, P) - assert a.complete and assigned(a) == [(0, "Person.ssn"), (1, "Person.name")] + assert a.complete + assert assigned(a) == [(0, "Person.ssn"), (1, "Person.name")] a = analyze("INSERT INTO `Person` (`ssn`) VALUES (_binary %s) AS new ON DUPLICATE KEY UPDATE `ssn` = new.`ssn`", MYSQL, P) - assert a.complete and unbound(a) == [] + assert a.complete + assert unbound(a) == [] - def test_introducer_needs_a_known_charset(self): + def test_introducer_needs_known_charset(self): # "_x %s" is not an introducer, so the statement reads as written. a = analyze("SELECT _x %s", MYSQL, P) assert [p.introducer for p in a.placeholders] == [None] @@ -1262,8 +1410,6 @@ def test_introducer_needs_a_known_charset(self): def test_introducer_only_on_mysql(self): assert analyze("SELECT _binary %s", PG, P).placeholders[0].introducer is None - # ---- MySQL row alias with a column list renames by position ---- - def test_row_alias_columns_copy_by_position(self): a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new(n, s) ON DUPLICATE KEY UPDATE ssn = new.s", MYSQL, P) @@ -1275,17 +1421,13 @@ def test_row_alias_column_naming_another_insert_column_is_unbound(self): "ON DUPLICATE KEY UPDATE ssn = new.ssn", MYSQL, P) assert unbound(a) == ["users.ssn"] - # ---- copies from another table ---- - @pytest.mark.parametrize("dialect, sql", [ (MYSQL, "UPDATE users u JOIN orders o ON o.uid = u.id SET u.ssn = o.ssn"), (PG, "UPDATE users SET ssn = o.ssn FROM other o WHERE o.id = users.id"), ]) - def test_copy_of_another_tables_column_of_the_same_name_is_unbound(self, dialect, sql): + def test_copy_of_other_tables_same_name_column_is_unbound(self, dialect, sql): assert unbound(analyze(sql, dialect)) == ["users.ssn"] - # ---- SQLAlchemy's multi-row ORM insert on PostgreSQL ---- - def test_insert_select_from_values_list(self): sql = ("INSERT INTO users (name, ssn) SELECT p0::VARCHAR, p1::BYTEA FROM " "(VALUES (%(name__0)s::VARCHAR, %(ssn__0)s, 0), (%(name__1)s::VARCHAR, %(ssn__1)s, 1)) " @@ -1306,25 +1448,25 @@ def test_insert_select_from_values_list(self): def test_other_insert_selects_are_values_from_query(self, sql): assert analyze(sql, PG, P).gap is AnalysisGap.VALUES_FROM_QUERY - # ---- statements that run a stored statement ---- - def test_execute_may_write(self): a = analyze("EXECUTE ins_user(%s, %s)", PG, P) - assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + assert a.writes + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT def test_prepare_body_is_read(self): a = analyze("PREPARE ins (text, text) AS INSERT INTO users (name, ssn) VALUES ($1, '123-45-6789')", PG) - assert a.kind is StatementKind.INSERT and a.writes + assert a.kind is StatementKind.INSERT + assert a.writes assert a.gap is AnalysisGap.PREPARED_PARAMETERS # The literal is reported as an unbound write; $1 is bound by a later # EXECUTE. assert unbound(a) == ["users.ssn"] - def test_prepare_of_a_read(self): + def test_prepare_of_read(self): a = analyze('PREPARE "q" AS SELECT ssn FROM users WHERE id = $1', PG) - assert a.kind is StatementKind.SELECT and not a.writes and a.complete - - # ---- DELETE ... USING ---- + assert a.kind is StatementKind.SELECT + assert not a.writes + assert a.complete def test_delete_using_aliases_are_in_scope(self): a = analyze("DELETE FROM users USING accounts a WHERE a.uid = users.id AND a.secret = %s RETURNING a.secret", @@ -1332,16 +1474,12 @@ def test_delete_using_aliases_are_in_scope(self): assert compared(a) == [(0, "accounts.secret")] assert a.result_columns == (ColumnRef("secret", "accounts"),) - # ---- ALL / SOME ---- - @pytest.mark.parametrize("sql", ["SELECT * FROM t WHERE c <> ALL(%s)", "SELECT * FROM t WHERE c = SOME(%s)", "SELECT * FROM t WHERE c = ANY(%s::text[])"]) def test_all_some_and_any_are_array_comparisons(self, sql): a = analyze(sql, PG, P) assert [(u.ordinal, str(u.column), u.array) for u in a.comparisons] == [(0, "t.c", True)] - # ---- MySQL qualified INSERT column lists ---- - @pytest.mark.parametrize("sql, expected", [ ("INSERT INTO users (users.name, users.ssn) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn")]), ("INSERT INTO mydb.users (mydb.users.ssn) VALUES (%s)", [(0, "users.ssn")]), @@ -1349,47 +1487,45 @@ def test_all_some_and_any_are_array_comparisons(self, sql): ]) def test_mysql_qualified_insert_columns(self, sql, expected): a = analyze(sql, MYSQL, P) - assert a.complete and assigned(a) == expected - - # ---- names that are not plain identifiers ---- + assert a.complete + assert assigned(a) == expected - def test_subscripted_column_is_not_a_column_name(self): + def test_subscripted_column_is_not_column_name(self): a = analyze("MERGE INTO t USING s ON 1=1 WHEN NOT MATCHED THEN INSERT (ssn[1]) VALUES (%s)", PG, P) assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT assert assigned(a) == [] - # ---- keyword fallback ---- - @pytest.mark.parametrize("sql", [ "SET search_path TO app; WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", "SET search_path TO app; COPY users (ssn) FROM STDIN", ]) - def test_unparsed_statement_before_a_write_is_not_complete(self, sql): + def test_unparsed_statement_before_write_is_not_complete(self, sql): a = analyze(sql, PG, P) - assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT - - # ---- parse-trust guards ---- + assert a.writes + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT - def test_placeholder_missing_from_the_parse_is_a_mismatch(self, monkeypatch): + def test_placeholder_missing_from_parse_is_mismatch(self, monkeypatch): real = sqlglot.parse monkeypatch.setattr(sql_analyzer.sqlglot, "parse", lambda _sql, read: real("INSERT INTO users (name, ssn) VALUES (:_kms_p0, 'x')", read=read)) a = sql_analyzer._analysis("INSERT INTO users (name, ssn) VALUES (%s, %s)", PG, ParamStyle.POSITIONAL) - assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH and a.assignments == () + assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH + assert a.assignments == () def test_command_fallback_is_unparseable(self, monkeypatch): monkeypatch.setattr(sql_analyzer.sqlglot, "parse", lambda _sql, read: [exp.Command(this="INSERT")]) a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES ('x')", PG, ParamStyle.NONE) - assert a.writes and a.gap is AnalysisGap.UNPARSEABLE + assert a.writes + assert a.gap is AnalysisGap.UNPARSEABLE - def test_unterminated_is_unparseable_even_if_the_parser_accepts_it(self, monkeypatch): + def test_unterminated_parsed_sql_is_unparseable(self, monkeypatch): real = sqlglot.parse monkeypatch.setattr(sql_analyzer.sqlglot, "parse", lambda _sql, read: real("INSERT INTO users (ssn) VALUES (:_kms_p0)", read=read)) a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES (%s) /* a /* b */", PG, ParamStyle.POSITIONAL) - assert a.writes and a.gap is AnalysisGap.UNPARSEABLE and a.assignments == () - - # ---- row lengths ---- + assert a.writes + assert a.gap is AnalysisGap.UNPARSEABLE + assert a.assignments == () @pytest.mark.parametrize("sql", [ "INSERT INTO users (a) VALUES (%s, %s)", @@ -1402,20 +1538,17 @@ def test_row_length_mismatch_both_ways(self, sql): def test_several_selects_have_no_result_columns(self): assert analyze("SELECT ssn FROM users; SELECT name FROM accounts", PG).result_columns is None - # ---- performance ---- - def test_long_boolean_chain_is_linear(self): sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 3000) a = analyze(sql, PG, P) - assert len(a.comparisons) == 6000 and a.comparisons[-1].column == ColumnRef("ssn", "users") + assert len(a.comparisons) == 6000 + assert a.comparisons[-1].column == ColumnRef("ssn", "users") class TestReviewRegressionsRound2: """Regression tests: annotations across tables, SQLAlchemy's multi-row insert, regex cost, caching and the logging filter.""" - # ---- annotations ---- - @pytest.mark.parametrize("sql, expected", [ ("UPDATE users u SET name = %s WHERE id IN (SELECT uid FROM accounts a WHERE a.x = /*@encrypt:u.ssn*/ %s)", {0: "users.name", 1: "users.ssn"}), @@ -1449,12 +1582,10 @@ def test_bare_annotation_with_several_tables(self, dialect, sql, expected): (PG, "INSERT INTO users (name, ssn) SELECT name, /*@encrypt:ssn*/ %s FROM accounts", ColumnRef("ssn", "users")), (PG, "UPDATE users SET ssn = (SELECT /*@encrypt:ssn*/ %s FROM accounts)", ColumnRef("ssn", "users")), ]) - def test_bare_annotation_in_a_query_feeding_a_write_names_the_written_table(self, dialect, sql, expected): + def test_bare_annotation_in_write_source_names_written_table(self, dialect, sql, expected): # The value goes to the write's target, even though the subquery reads another table. assert analyze(sql, dialect, P).parameter_columns()[0] == expected - # ---- SQLAlchemy's multi-row insert ---- - def test_insert_select_from_values_maps_select_items_by_name(self): a = analyze("INSERT INTO users (name, ssn) SELECT p1, p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", PG, P) assert a.complete @@ -1464,10 +1595,11 @@ def test_insert_select_from_values_maps_select_items_by_name(self): "INSERT INTO users (ssn, note) SELECT p0, p0 FROM (VALUES (%s)) AS v(p0)", "INSERT INTO users (name, ssn) SELECT v.p0, p0::text FROM (VALUES (%s, %s)) AS v(p0, p1)", ]) - def test_insert_select_from_values_using_a_column_twice_is_not_read(self, sql): + def test_insert_select_from_values_column_twice_is_not_read(self, sql): # One value would fill two columns, and could be encrypted for only one. a = analyze(sql, PG, P) - assert a.gap is AnalysisGap.VALUES_FROM_QUERY and a.assignments == () + assert a.gap is AnalysisGap.VALUES_FROM_QUERY + assert a.assignments == () @pytest.mark.parametrize("sql, gap", [ ("INSERT INTO users (name, ssn) SELECT p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", AnalysisGap.VALUES_FROM_QUERY), @@ -1479,8 +1611,6 @@ def test_insert_select_from_values_using_a_column_twice_is_not_read(self, sql): def test_insert_select_from_values_widths_and_extras(self, sql, gap): assert analyze(sql, PG, P).gap is gap - # ---- regex cost on indented SQL ---- - @pytest.mark.timeout(10) @pytest.mark.parametrize("dialect, sql", [ (MYSQL, "\n" + " " * 60 + "\n" + " " * 60 + "UPDATE users SET ssn = %s WHERE id = %s AND (name = 'x'"), @@ -1494,20 +1624,21 @@ def test_leading_whitespace_and_comments_do_not_backtrack(self, dialect, sql): def test_indented_prepare_and_qualified_insert_are_still_read(self): a = analyze("\n PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ('x')", PG) - assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] + assert a.gap is AnalysisGap.PREPARED_PARAMETERS + assert unbound(a) == ["users.ssn"] a = analyze("\n INSERT INTO users (users.ssn) VALUES (%s)", MYSQL, P) - assert a.complete and assigned(a) == [(0, "users.ssn")] - - # ---- MySQL qualified INSERT columns with dotted back-quoted names ---- + assert a.complete + assert assigned(a) == [(0, "users.ssn")] @pytest.mark.parametrize("sql, expected", [ ("INSERT INTO users (users.name, `x.ssn`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.x.ssn")]), ("INSERT INTO users (users.name, `ssn.v2`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn.v2")]), ("INSERT INTO users (`users`.`ssn`, name) VALUES (%s, %s)", [(0, "users.ssn"), (1, "users.name")]), ]) - def test_back_quoted_name_with_a_dot_is_one_name(self, sql, expected): + def test_back_quoted_name_with_dot_is_one_name(self, sql, expected): a = analyze(sql, MYSQL, P) - assert a.complete and assigned(a) == expected + assert a.complete + assert assigned(a) == expected def test_qualifier_retry_only_for_inserts(self, monkeypatch): calls = [] @@ -1517,8 +1648,6 @@ def test_qualifier_retry_only_for_inserts(self, monkeypatch): analyze("UPDATE users SET ssn = %s WHERE (", MYSQL, P) assert calls == [] - # ---- keyword fallback ---- - @pytest.mark.parametrize("dialect, sql", [ (PG, "SET search_path TO app; PREPARE p AS INSERT INTO users (ssn) VALUES ('123-45-6789')"), (PG, "EXPLAIN ANALYZE EXECUTE p(%s)"), @@ -1526,21 +1655,21 @@ def test_qualifier_retry_only_for_inserts(self, monkeypatch): ]) def test_more_statements_that_may_write(self, dialect, sql): a = analyze(sql, dialect, P) - assert a.writes and a.gap is not None - - # ---- names that are not plain identifiers ---- + assert a.writes + assert a.gap is not None def test_subscripted_update_target_is_unsupported(self): a = analyze("UPDATE users SET ssn[1] = %s", PG, P) - assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT and a.assignments == () - - # ---- TABLE is not parsed (sqlglot reads it as an alias) ---- + assert a.writes + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + assert a.assignments == () + # sqlglot reads TABLE as an alias. def test_table_statement_is_not_parsed(self): a = analyze("TABLE users", PG) - assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () - - # ---- scopes ---- + assert a.kind is StatementKind.SELECT + assert not a.writes + assert a.tables == () def test_nearest_query_memo_does_not_cross_queries(self): a = analyze("SELECT * FROM users u WHERE EXISTS " @@ -1552,14 +1681,12 @@ def test_long_boolean_chain_is_time_bounded(self): sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 12000) assert len(analyze(sql, PG, P).comparisons) == 24000 - # ---- caching ---- - def test_long_sql_with_few_placeholders_is_not_cached(self): sql = "UPDATE users SET ssn = %s WHERE note = '" + "x" * sql_analyzer.CACHEABLE_SQL_LENGTH + "'" assert sql.count("%") <= sql_analyzer.CACHEABLE_PERCENT_SIGNS assert analyze(sql, PG, P) is not analyze(sql, PG, P) - def test_recursion_error_wrapped_by_the_tokenizer_is_not_cached(self, monkeypatch): + def test_recursion_error_wrapped_by_tokenizer_is_not_cached(self, monkeypatch): real = sqlglot.parse calls = [] @@ -1575,11 +1702,10 @@ def flaky(sql, read): monkeypatch.setattr(sql_analyzer.sqlglot, "parse", flaky) sql = "SELECT a FROM users WHERE ssn = %s" first = analyze(sql, PG, P) - assert first.gap is AnalysisGap.UNPARSEABLE and first.detail == "RecursionError" + assert first.gap is AnalysisGap.UNPARSEABLE + assert first.detail == "RecursionError" assert analyze(sql, PG, P).gap is None - # ---- the logging filter is per thread ---- - def test_quiet_filter_does_not_silence_other_threads(self, caplog): entered, release = threading.Event(), threading.Event() @@ -1604,10 +1730,9 @@ class TestReviewRegressionsRound3: """Regression tests: regexes that fail after a long gap, and which table a bare annotation gets.""" - # ---- regexes that fail after a long run of whitespace or comments ---- - _BAD_PREPARE = "PREPARE p (int AS INSERT INTO users (ssn) VALUES ($1)" # unbalanced header - _PARTITION = "INSERT INTO users PARTITION (p0) (users.ssn) VALUES (%s)" # valid MySQL neither read can parse + # Valid MySQL neither read can parse. + _PARTITION = "INSERT INTO users PARTITION (p0) (users.ssn) VALUES (%s)" @pytest.mark.timeout(10) @pytest.mark.parametrize("dialect, sql, gap", [ @@ -1624,14 +1749,13 @@ class TestReviewRegressionsRound3: (MYSQL, "-- c \n" * 40 + "INSERT INTO users SET ssn = %s, note = 'a' 'b' garbage(", AnalysisGap.UNPARSEABLE), ], ids=["pg-spaces", "pg-comments", "pg-dash-banner", "pg-dashes", "pg-crlf", "pg-crlf-header", "my-spaces", "my-comments", "my-dash-banner", "my-dashed-prose", "my-trailing-space"]) - def test_a_regex_that_fails_after_a_long_gap_fails_fast(self, dialect, sql, gap): + def test_regex_failing_after_long_gap_fails_fast(self, dialect, sql, gap): assert analyze(sql, dialect, P).gap is gap - def test_line_comments_in_a_prepare_header(self): + def test_line_comments_in_prepare_header(self): a = analyze("-- c\r\n PREPARE -- x\r\n p (int) -- y \r\n AS INSERT INTO users (ssn) VALUES ('x')", PG) - assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] - - # ---- bare annotations: written vs compared values ---- + assert a.gap is AnalysisGap.PREPARED_PARAMETERS + assert unbound(a) == ["users.ssn"] @pytest.mark.parametrize("dialect, sql, ordinal, expected", [ # A filter value gets the table it is compared in, even in a statement that writes. @@ -1661,7 +1785,7 @@ def test_line_comments_in_a_prepare_header(self): (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id " "SET u.note = (SELECT /*@encrypt:ssn*/ %s FROM temp), a.x = 1", 0, ColumnRef("ssn")), ]) - def test_bare_annotation_by_where_the_value_goes(self, dialect, sql, ordinal, expected): + def test_bare_annotation_by_value_position(self, dialect, sql, ordinal, expected): assert analyze(sql, dialect, P).parameter_columns()[ordinal] == expected @pytest.mark.parametrize("dialect, sql, expected", [ @@ -1692,7 +1816,7 @@ def test_bare_annotation_by_where_the_value_goes(self, dialect, sql, ordinal, ex (PG, "INSERT INTO t (a) SELECT s.v FROM (SELECT /*@encrypt:ssn*/ %s AS v) s", ColumnRef("ssn")), ], ids=["case-when", "boolean-item", "mysql-if", "simple-case", "set-subquery-item", "set-case-two-sources", "case-then", "param-cte-update", "param-cte-insert", "mysql-param-cte", "join-source", "from-source"]) - def test_bare_annotation_on_a_compared_or_source_value(self, dialect, sql, expected): + def test_bare_annotation_on_compared_or_source_value(self, dialect, sql, expected): assert analyze(sql, dialect, P).parameter_columns()[0] == expected @pytest.mark.parametrize("dialect, sql, expected", [ @@ -1736,13 +1860,13 @@ def test_bare_annotation_on_a_compared_or_source_value(self, dialect, sql, expec ], ids=["then", "else", "mysql-if-true", "in", "between", "regex", "jsonb-contains", "mysql-regexp", "mysql-match", "simple-case-operand", "partition-by", "join-source-reads", "from-source-reads", "cte-reads", "merge-using-reads", "cross-join-lateral-reads", "comma-lateral-reads", "set-with-from"]) - def test_bare_annotation_written_tested_or_from_a_source(self, dialect, sql, expected): + def test_bare_annotation_written_tested_or_from_source(self, dialect, sql, expected): assert analyze(sql, dialect, P).parameter_columns()[0] == expected # A value tested by any of these operators resolves to the table it is tested against on # every supported sqlglot, though the operators are Predicates only from 30.16. @pytest.mark.parametrize("op", ["~*", "!~*", "<@", "&&", "?", "?|", "?&", "-|-", "&<", "&>"]) - def test_bare_annotation_tested_by_an_operator(self, op): + def test_bare_annotation_tested_by_operator(self, op): sql = f"UPDATE audit SET flag = (SELECT ssn {op} /*@encrypt:ssn*/ %s FROM users LIMIT 1)" assert analyze(sql, PG, P).parameter_columns()[0] == ColumnRef("ssn", "users") @@ -1766,7 +1890,7 @@ def test_bare_annotation_tested_by_overlaps(self): (PG, "MERGE INTO users t USING cards c ON t.id = c.uid " "WHEN MATCHED AND starts_with(c.pan, /*@encrypt:pan*/ %s) THEN UPDATE SET flag = true", ColumnRef("pan")), ], ids=["where", "mysql-where", "having", "update-from-where", "merge-on", "merge-when-condition"]) - def test_bare_annotation_in_a_condition_slot(self, dialect, sql, expected): + def test_bare_annotation_in_condition_slot(self, dialect, sql, expected): assert analyze(sql, dialect, P).parameter_columns()[0] == expected @pytest.mark.parametrize("sql, ordinal, expected", [ @@ -1790,18 +1914,17 @@ def test_bare_annotation_in_a_condition_slot(self, dialect, sql, expected): def test_bare_annotation_slots(self, sql, ordinal, expected): assert analyze(sql, PG, P).parameter_columns()[ordinal] == expected - # ---- one-dialect gaps ---- - def test_replace_with_qualified_columns_is_read(self): a = analyze("REPLACE INTO users (users.ssn) VALUES (%s)", MYSQL, P) - assert a.complete and assigned(a) == [(0, "users.ssn")] + assert a.complete + assert assigned(a) == [(0, "users.ssn")] @BOTH def test_table_statement_is_not_parsed_on_either_dialect(self, dialect): a = analyze("TABLE users", dialect) - assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () - - # ---- a cyclic exception chain ends ---- + assert a.kind is StatementKind.SELECT + assert not a.writes + assert a.tables == () @pytest.mark.timeout(10) def test_cyclic_exception_chain_does_not_hang(self, monkeypatch): @@ -1812,4 +1935,68 @@ def cyclic(sql, read): monkeypatch.setattr(sql_analyzer.sqlglot, "parse", cyclic) a = sql_analyzer._analysis("SELECT 1", PG, ParamStyle.NONE) - assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "ParseError" + assert a.gap is AnalysisGap.UNPARSEABLE + assert a.detail == "ParseError" + + +def test_unparsed_hidden_placeholder_lists_its_words(): + a = analyze("INSERT INTO t VALUES ('%s'", PG, P) + assert a.gap is AnalysisGap.HIDDEN_PLACEHOLDER + assert names(a.tables) == ["insert", "into", "t", "values"] + + +def test_default_values_after_column_list_has_no_column_list(): + assert analyze("INSERT INTO t (a) DEFAULT VALUES", PG, P).gap is AnalysisGap.NO_COLUMN_LIST + + +def test_upsert_bare_column_assignment_unsupported(): + a = analyze("INSERT INTO t (a) VALUES (%s) ON DUPLICATE KEY UPDATE a = 1, b", MYSQL, P) + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + + +def test_update_row_from_subquery_with_subscript_unsupported(): + a = analyze("UPDATE t SET (a[1], b) = (SELECT x, y FROM u WHERE z = %s)", PG, P) + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + assert compared(a) == [(0, "u.z")] + + +@pytest.mark.parametrize("sql", [ + "PREPARE p AS INSERT INTO t (a) VALUES (CAST($1 AS text))", + "PREPARE p AS INSERT INTO t (a) VALUES (($1))", + "PREPARE p AS INSERT INTO t (a) VALUES ($1::text)", +]) +def test_prepare_wrapped_parameter_has_prepared_parameters_gap(sql): + assert analyze(sql, PG, P).gap is AnalysisGap.PREPARED_PARAMETERS + + +@pytest.mark.parametrize("dialect, sql", [ + (PG, "INSERT INTO t (a) VALUES (%s) ON CONFLICT (a) DO UPDATE SET a = other.a"), + (PG, "INSERT INTO t (a) VALUES (%s) ON CONFLICT (a) DO UPDATE SET a = t.a"), + (MYSQL, "INSERT INTO t (a) VALUES (%s) ON DUPLICATE KEY UPDATE a = o.a"), +]) +def test_upsert_from_other_row_is_unbound_write(dialect, sql): + a = analyze(sql, dialect, P) + assert a.gap is None + assert unbound(a) == ["t.a"] + + +def test_update_row_from_one_placeholder_is_unbound_write(): + a = analyze("UPDATE t SET (a, b) = (%s)", PG, P) + assert a.gap is None + assert unbound(a) == ["t.a", "t.b"] + + +def test_upsert_row_from_one_excluded_column_is_unbound_write(): + a = analyze("INSERT INTO t (a) VALUES (%s) ON CONFLICT (a) DO UPDATE SET (a, b) = (EXCLUDED.a)", PG, P) + assert a.gap is None + assert unbound(a) == ["t.a", "t.b"] + + +@pytest.mark.parametrize("dialect, sql", [ + (PG, "SELECT /*@encrypt:a*/ %s"), + (PG, "VALUES (/*@encrypt:a*/ %s)"), + (MYSQL, "SELECT /*@encrypt:a*/ %s"), +]) +def test_annotation_without_written_table_keeps_column(dialect, sql): + a = analyze(sql, dialect, P) + assert [str(u.column) for u in a.annotations] == ["a"] diff --git a/tests/unit/test_sql_tokenizer.py b/tests/unit/test_sql_tokenizer.py index 032217c2c..1f2bcc17b 100644 --- a/tests/unit/test_sql_tokenizer.py +++ b/tests/unit/test_sql_tokenizer.py @@ -17,9 +17,14 @@ import pytest -from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG from aws_advanced_python_wrapper.encryption.sql_tokenizer import ( - ColumnRef, ParamStyle, normalized_ordinal, tokenize) + ColumnRef, ParamStyle, _lex, normalized_ordinal, tokenize) +from aws_advanced_python_wrapper.errors import EncryptionPluginError +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect + +PG = PgDriverDialect +MYSQL = MySQLDriverDialect POS, NAMED, NONE = ParamStyle.POSITIONAL, ParamStyle.NAMED, ParamStyle.NONE @@ -65,10 +70,11 @@ def test_named_may_repeat(self): assert keys(t) == ["v", "v", "id"] assert [p.ordinal for p in t.placeholders] == [0, 1, 2] - def test_double_percent_is_a_percent_sign(self): + def test_double_percent_is_percent_sign(self): t = tokenize("SELECT 7 %% 2, a FROM t WHERE b LIKE 'x%%' AND c = %s", PG, POS) assert keys(t) == [0] - assert "7 % 2" in t.normalized and "'x%'" in t.normalized + assert "7 % 2" in t.normalized + assert "'x%'" in t.normalized def test_placeholders_inside_literals_and_comments_are_still_bound(self): # psycopg does not skip quotes or comments, so neither may we: the @@ -89,11 +95,11 @@ def test_deeply_nested_comments_stay_linear(self): t = tokenize("SELECT /*" + " /*" * depth + " */" * (depth + 1) + " %s", PG, POS) assert hidden(t) == [False] - def test_dollar_number_is_not_a_dollar_quote(self): + def test_dollar_number_is_not_dollar_quote(self): t = tokenize("SELECT $1, %s", PG, POS) assert hidden(t) == [False] - def test_identifier_with_dollar_is_not_a_dollar_quote(self): + def test_identifier_with_dollar_is_not_dollar_quote(self): t = tokenize("SELECT a$b$, %s", PG, POS) assert hidden(t) == [False] @@ -123,20 +129,21 @@ def test_driver_rejects_other_percent_sequences(self, sql, rejected): ("SELECT '4111-1111-1111-1111 %d'", POS), ("VALUES (%s, %(4111-1111)s)", NAMED), ]) - def test_driver_error_never_quotes_the_sql(self, sql, style): + def test_driver_error_never_quotes_sql(self, sql, style): error = tokenize(sql, PG, style).driver_error - assert error is not None and "4111" not in error + assert error is not None + assert "4111" not in error def test_percent_before_newline_is_left_alone(self): # psycopg's pattern does not match a newline after %. assert tokenize("SELECT 1 %\n2", PG, POS).driver_error is None @pytest.mark.parametrize("style", [POS, NAMED]) - def test_mixed_styles_are_a_driver_error(self, style): + def test_mixed_styles_are_driver_error(self, style): assert tokenize("VALUES (%s, %(a)s)", PG, style).driver_error is not None @pytest.mark.parametrize("sql, style", [("VALUES (%s)", NAMED), ("VALUES (%(a)s)", POS)]) - def test_style_mismatch_is_a_driver_error(self, sql, style): + def test_style_mismatch_is_driver_error(self, sql, style): assert tokenize(sql, PG, style).driver_error is not None def test_no_params_means_no_placeholders(self): @@ -155,7 +162,7 @@ class TestMySqlPlaceholders: def test_positional(self): assert keys(tokenize("INSERT INTO t (a, b) VALUES (%s, %s)", MYSQL, POS)) == [0, 1] - def test_double_percent_is_not_an_escape(self): + def test_double_percent_is_not_escape(self): # Connector/Python replaces every "%s" substring, including in "%%s". t = tokenize("SELECT 5 %% 2, %%s", MYSQL, POS) assert keys(t) == [0] @@ -166,18 +173,19 @@ def test_any_other_percent_sequence_is_left_alone(self): assert keys(t) == [0] assert t.driver_error is None - def test_named_only_with_a_dict(self): + def test_named_only_with_dict(self): assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, NAMED)) == ["a"] assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, POS)) == [0] - def test_named_percent_conversion_is_a_percent_sign(self): + def test_named_percent_conversion_is_percent_sign(self): t = tokenize("SELECT %(a)s, 5 %(x)% 2", MYSQL, NAMED) assert keys(t) == ["a"] assert "5 % 2" in t.normalized - def test_named_other_conversion_is_a_driver_error(self): + def test_named_other_conversion_is_driver_error(self): error = tokenize("SELECT '%(123-45-6789)d'", MYSQL, NAMED).driver_error - assert error is not None and "123-45" not in error + assert error is not None + assert "123-45" not in error def test_no_params_means_no_placeholders(self): assert tokenize("SELECT %s", MYSQL, NONE).placeholders == () @@ -191,7 +199,7 @@ def test_backslash_escapes_in_strings(self): t = tokenize("SELECT 'a\\'b', \"c\\\"d\", %s", MYSQL, POS) assert hidden(t) == [False] - def test_double_dash_needs_whitespace_to_start_a_comment(self): + def test_double_dash_comment_needs_whitespace(self): t = tokenize("SELECT 1--%s", MYSQL, POS) assert hidden(t) == [False] assert hidden(tokenize("SELECT 1-- %s", MYSQL, POS)) == [True] @@ -210,7 +218,7 @@ def test_block_comments_do_not_nest(self): def test_executable_comments(self, sql, executable): assert tokenize(sql, MYSQL, NONE).executable_comment is executable - def test_executable_comment_is_only_a_mysql_notion(self): + def test_executable_comment_only_on_mysql(self): assert not tokenize("SELECT /*! 1 */", PG, NONE).executable_comment def test_executable_comment_keywords(self): @@ -229,7 +237,7 @@ def test_charset_introducers(self, sql, introducers): if introducers[0]: assert "_binary" not in t.normalized.lower() - def test_introducer_inside_a_comment_is_ignored(self): + def test_introducer_inside_comment_is_ignored(self): t = tokenize("VALUES (-- _binary\n%s)", MYSQL, POS) assert [p.introducer for p in t.placeholders] == [None] assert "_binary" in t.normalized @@ -259,6 +267,17 @@ def test_type_error_for_non_str(self): with pytest.raises(TypeError): tokenize(b"SELECT 1", PG, NONE) # type: ignore[arg-type] + @pytest.mark.parametrize("dialect, sql, names", [ + (PG, 'UPDATE "My""T" SET a = %s -- t2', [("UPDATE", False), ("SET", False), ("a", False), ('My"T', True)]), + (MYSQL, "UPDATE t /*!50000 JOIN Users USING (id) */ SET a = 'b c' WHERE `x``y` = %s", + [("UPDATE", False), ("t", False), ("SET", False), ("a", False), ("WHERE", False), ("JOIN", False), + ("Users", False), ("USING", False), ("id", False), ("x`y", True)]), + (PG, "SELECT a FROM t WHERE b = %s AND a = %s", + [("SELECT", False), ("a", False), ("FROM", False), ("t", False), ("WHERE", False), ("b", False), ("AND", False)]), + ], ids=["pg-quoted", "mysql-executable-comment", "no-duplicates"]) + def test_names_hold_words_and_quoted_identifiers(self, dialect, sql, names): + assert list(tokenize(sql, dialect, POS).names) == names + class TestNormalized: def test_placeholders_carry_their_ordinal(self): @@ -302,7 +321,7 @@ def test_postgresql_keeps_modifier_words(self): class TestAnnotations: - def test_annotation_before_a_placeholder(self): + def test_annotation_before_placeholder(self): t = tokenize("INSERT INTO t (a, b) VALUES (%s, /*@encrypt:users.ssn*/ %s)", PG, POS) assert [p.annotation for p in t.placeholders] == [None, ColumnRef("ssn", "users")] assert t.stray_annotations == () @@ -326,7 +345,7 @@ def test_empty_and_extra_parts(self, ref, expected): t = tokenize(f"VALUES (/*@encrypt:{ref}*/ %s)", PG, POS) assert t.placeholders[0].annotation == expected - def test_doubled_quote_in_a_quoted_part(self): + def test_doubled_quote_in_quoted_part(self): t = tokenize('VALUES (/*@encrypt:"a""b".ssn*/ %s)', PG, POS) assert t.placeholders[0].annotation == ColumnRef("ssn", 'a"b') @@ -340,35 +359,36 @@ def test_mysql_backtick_parts(self): @pytest.mark.parametrize("sql", [ "VALUES (%s /*@encrypt:users.ssn*/)", # after, not before - "VALUES (/*@encrypt:users.ssn*/ 'x', %s)", # not followed by a placeholder + # Not followed by a placeholder. + "VALUES (/*@encrypt:users.ssn*/ 'x', %s)", "VALUES (/*@encrypt:users.*/ %s)", # no column "VALUES (/*@encrypt:users ssn*/ %s)", - "VALUES (/*@encrypt:users.ssn*/ '%s')", # a literal, not a placeholder, follows + # A literal, not a placeholder, follows. + "VALUES (/*@encrypt:users.ssn*/ '%s')", ]) def test_stray_annotations(self, sql): t = tokenize(sql, PG, POS) assert all(p.annotation is None for p in t.placeholders) assert len(t.stray_annotations) == 1 - def test_annotation_before_a_hidden_placeholder_is_stray(self): + def test_annotation_before_hidden_placeholder_is_stray(self): # psycopg reads %("x")s as one placeholder that starts outside a # quoted identifier and ends inside it. t = tokenize('VALUES (/*@encrypt:t.a*/ %("x")s)', PG, NAMED) assert hidden(t) == [True] - assert t.placeholders[0].annotation is None and len(t.stray_annotations) == 1 + assert t.placeholders[0].annotation is None + assert len(t.stray_annotations) == 1 - def test_space_after_comment_opener_is_not_an_annotation(self): + def test_space_after_comment_opener_is_not_annotation(self): t = tokenize("VALUES (/* @encrypt:users.ssn*/ %s)", PG, POS) assert t.placeholders[0].annotation is None assert t.stray_annotations == () - def test_annotation_inside_a_literal_is_text(self): + def test_annotation_inside_literal_is_text(self): t = tokenize("VALUES ('/*@encrypt:users.ssn*/', %s)", PG, POS) assert t.placeholders[0].annotation is None -# ---- the drivers themselves as the oracle ---- -# # These call the drivers' own placeholder scanning, so a driver upgrade that # changes what it binds fails here rather than silently shifting which value # the plugin encrypts. @@ -413,3 +433,16 @@ def test_matches_mysql_connector_named(sql): expected = [m.group("mapping_key").decode() for m in cursor.RE_PY_MAPPING_PARAM.finditer(sql.encode()) if m.group("conversion_type") == b"s"] assert keys(tokenize(sql, MYSQL, NAMED)) == expected + + +class _NoMatchDialect(PgDriverDialect): + sql_token_pattern = re.compile(r"x") + + +def test_lex_pattern_without_match_raises(): + with pytest.raises(EncryptionPluginError, match="matched no token"): + _lex("y", _NoMatchDialect) + + +def test_annotation_with_rejected_part_is_stray(): + assert tokenize("SELECT /*@encrypt:-c*/ %s", PG, POS).stray_annotations == ("/*@encrypt:-c*/",) diff --git a/tests/unit/test_type_marker.py b/tests/unit/test_type_marker.py index a925f42f3..cbeb7785d 100644 --- a/tests/unit/test_type_marker.py +++ b/tests/unit/test_type_marker.py @@ -28,7 +28,8 @@ class TestFromObject: (memoryview(b"x"), TypeMarker.BYTE_ARRAY), (True, TypeMarker.BOOLEAN), # must win over int (False, TypeMarker.BOOLEAN), - (5, TypeMarker.LONG), # every Python int but bool -> LONG + # Every Python int but bool is LONG. + (5, TypeMarker.LONG), (5.0, TypeMarker.DOUBLE), (Decimal("1.5"), TypeMarker.BIG_DECIMAL), (datetime(2020, 1, 1), TypeMarker.LOCAL_DATE_TIME), # must win over date From 5ca97af8e3a004653438fe215349c8e8604de007 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Wed, 2 Dec 2026 10:53:44 -0700 Subject: [PATCH 4/6] fix: satisfy main's stricter lint checks in the kms code Main's #1401 turned on mypy's warn_unused_ignores and strict_equality and ruff's B905, which the kms code predates. - Drop 18 type: ignore comments in unannotated test functions, whose bodies mypy does not check. - Pass strict=False to 13 zip() calls, as #1401 did, so behaviour stays the same. - Cast the driver iterator to object in AwsWrapperCursor.__next__: a driver cursor can be its own iterator, which the Cursor type does not show. --- .../encryption/connection_source.py | 2 +- aws_advanced_python_wrapper/encryption/sql_analyzer.py | 6 +++--- .../encryption/sql_tokenizer.py | 2 +- aws_advanced_python_wrapper/plugin_service.py | 2 +- aws_advanced_python_wrapper/wrapper.py | 4 ++-- tests/integration/test_kms_encryption_live.py | 2 +- tests/unit/test_data_key_cache.py | 4 ++-- tests/unit/test_encryption_config.py | 2 +- tests/unit/test_encryption_driver_dialect.py | 2 +- tests/unit/test_key_management_utility.py | 2 +- tests/unit/test_key_manager.py | 10 +++++----- tests/unit/test_kms_encryption_plugin.py | 8 ++++---- tests/unit/test_metadata_manager.py | 8 ++++---- tests/unit/test_sql_analyzer.py | 10 +++++----- tests/unit/test_sql_tokenizer.py | 2 +- 15 files changed, 33 insertions(+), 33 deletions(-) diff --git a/aws_advanced_python_wrapper/encryption/connection_source.py b/aws_advanced_python_wrapper/encryption/connection_source.py index 6f5e75287..7d783e08f 100644 --- a/aws_advanced_python_wrapper/encryption/connection_source.py +++ b/aws_advanced_python_wrapper/encryption/connection_source.py @@ -146,7 +146,7 @@ def fetch_rows(dialect: DriverDialect, conn: Connection, sql: str, params: Seque 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)) + 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] diff --git a/aws_advanced_python_wrapper/encryption/sql_analyzer.py b/aws_advanced_python_wrapper/encryption/sql_analyzer.py index d9b0de3c8..f0f043917 100644 --- a/aws_advanced_python_wrapper/encryption/sql_analyzer.py +++ b/aws_advanced_python_wrapper/encryption/sql_analyzer.py @@ -482,7 +482,7 @@ def _without_insert_column_qualifiers(text: str) -> Optional[str]: 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): + 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: @@ -779,7 +779,7 @@ def _upsert(self, conflict: exp.OnConflict, table: Optional[str], columns: Optio 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 ()): + 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 @@ -866,7 +866,7 @@ def _assign(self, assignment: exp.Expression, table_of: _TableOf, same_row: Opti continue self._unbound.append(ColumnRef(name, table_of(self._fold(column.args.get("table"))))) return - pairs = list(zip(target.expressions, values)) + pairs = list(zip(target.expressions, values, strict=False)) else: pairs = [(target, value)] for column, v in pairs: diff --git a/aws_advanced_python_wrapper/encryption/sql_tokenizer.py b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py index 8f1b255da..af479844d 100644 --- a/aws_advanced_python_wrapper/encryption/sql_tokenizer.py +++ b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py @@ -543,7 +543,7 @@ def _copy_option_rewrites(sql: str, words: List[Tuple[str, int, int]], bounds: L 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]): + 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 diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index 1b133e3af..dcf707365 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -912,7 +912,7 @@ def holds(self, args: Tuple[Any, ...], kwargs: Mapping[str, Any]) -> bool: :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)) + 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())) diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 7f04e1561..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) @@ -486,7 +486,7 @@ def __next__(self) -> Any: # other driver cursor gives it with fetchone. target = self.target_cursor rows = iter(target) - if rows is not 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 diff --git a/tests/integration/test_kms_encryption_live.py b/tests/integration/test_kms_encryption_live.py index 530f69382..e8a42a98a 100644 --- a/tests/integration/test_kms_encryption_live.py +++ b/tests/integration/test_kms_encryption_live.py @@ -480,7 +480,7 @@ def stored(self, name: str) -> List[Any]: def check(self, name: str, expected: List[Any]) -> None: stored = self.stored(name) assert len(stored) == len(expected) - for value, want in zip(stored, expected): + for value, want in zip(stored, expected, strict=False): if want is None: assert value is None continue diff --git a/tests/unit/test_data_key_cache.py b/tests/unit/test_data_key_cache.py index 5ec3e31c2..ef727feb2 100644 --- a/tests/unit/test_data_key_cache.py +++ b/tests/unit/test_data_key_cache.py @@ -245,7 +245,7 @@ def set(self): raise RuntimeError("cannot stop") with pytest.raises(RuntimeError): - DataKeyCache._release(cache._entries, cache._lock, BrokenStop(), [None]) # type: ignore[arg-type] + DataKeyCache._release(cache._entries, cache._lock, BrokenStop(), [None]) assert stored == bytearray(4) @@ -294,7 +294,7 @@ def test_finalizer_holds_cleanup_thread(): try: assert cache._cleanup_thread is not None assert cache._thread_holder == [cache._cleanup_thread] - assert any(arg is cache._thread_holder for arg in cache._finalizer.peek()[2]) # type: ignore[index] + assert any(arg is cache._thread_holder for arg in cache._finalizer.peek()[2]) finally: cache.close() diff --git a/tests/unit/test_encryption_config.py b/tests/unit/test_encryption_config.py index 0d579f938..59375bc41 100644 --- a/tests/unit/test_encryption_config.py +++ b/tests/unit/test_encryption_config.py @@ -218,7 +218,7 @@ def test_match_is_exact(self): def test_direct_construction_normalizes_too(self): config = EncryptionConfig( - kms_region="us-east-1", allowed_master_key_arns=f"{ARN}, ", # type: ignore[arg-type] + kms_region="us-east-1", allowed_master_key_arns=f"{ARN}, ", kms_endpoint=None, metadata_schema="encrypt", metadata_cache_enabled=True, metadata_cache_expiration_sec=3600.0, metadata_cache_refresh_interval_sec=300.0, data_key_cache_enabled=True, data_key_cache_max_size=1000, data_key_cache_expiration_sec=300.0, key_management_max_retries=3, diff --git a/tests/unit/test_encryption_driver_dialect.py b/tests/unit/test_encryption_driver_dialect.py index 9bd19c638..b5730de7a 100644 --- a/tests/unit/test_encryption_driver_dialect.py +++ b/tests/unit/test_encryption_driver_dialect.py @@ -41,7 +41,7 @@ def dialect(): def test_encryption_driver_dialect_is_abstract(): with pytest.raises(TypeError, match="abstract"): - EncryptionDriverDialect() # type: ignore[abstract] + EncryptionDriverDialect() def test_analyzable_sql_bytes_runs_unanalyzed(dialect, mocker): diff --git a/tests/unit/test_key_management_utility.py b/tests/unit/test_key_management_utility.py index db70790ea..74d7ca08e 100644 --- a/tests/unit/test_key_management_utility.py +++ b/tests/unit/test_key_management_utility.py @@ -925,7 +925,7 @@ def test_pg_statements_pin_built_in_equals_operator(conn): def test_columns_using_key_with_dict_rows(conn): - conn.rows = [{"table_name": "users", "column_name": "ssn"}] # type: ignore[list-item] + conn.rows = [{"table_name": "users", "column_name": "ssn"}] u, _ = utility(conn) assert u.columns_using_key(3) == ["users.ssn"] diff --git a/tests/unit/test_key_manager.py b/tests/unit/test_key_manager.py index 87063f9ce..3a39677b2 100644 --- a/tests/unit/test_key_manager.py +++ b/tests/unit/test_key_manager.py @@ -145,7 +145,7 @@ def no_filters(mocker): lg.filters = [f for f in lg.filters if not isinstance(f, OUR_FILTERS)] mocker.patch.object(km_module, "_filters_installed", False) yield - for lg, filters in zip(loggers, saved): + for lg, filters in zip(loggers, saved, strict=False): lg.filters = filters @@ -499,7 +499,7 @@ def create_key(**kwargs): raise EndpointConnectionError(endpoint_url="https://kms") return {"KeyMetadata": {"KeyId": "k", "Arn": ARN}} - client.create_key = create_key # type: ignore[method-assign] + client.create_key = create_key assert km.create_master_key("d") == ARN assert len(calls) == 2 @@ -517,7 +517,7 @@ def create_key(**kwargs): raise ConnectTimeoutError(endpoint_url="https://kms") return {"KeyMetadata": {"KeyId": "k", "Arn": ARN}} - client.create_key = create_key # type: ignore[method-assign] + client.create_key = create_key assert km.create_master_key("d") == ARN assert len(calls) == 2 @@ -619,7 +619,7 @@ class DictCursor(FakeCursor): def fetchone(self): return {"id": 42} - db.cursor = lambda: DictCursor(db) # type: ignore[method-assign] + db.cursor = lambda: DictCursor(db) db.result = (["id"], []) assert manager(kms[0], db).store_key_metadata(self._key()).id == 42 @@ -886,7 +886,7 @@ def test_filters_are_installed_once_on_their_loggers_only(self): KeyManager.create_kms_client(_session(), config(kms_endpoint=UNREACHABLE)) after = {name: _state(name) for name in LOGGERS} finally: - for lg, (level, propagate) in zip(loggers, saved): + for lg, (level, propagate) in zip(loggers, saved, strict=False): lg.setLevel(level) lg.propagate = propagate added = {} diff --git a/tests/unit/test_kms_encryption_plugin.py b/tests/unit/test_kms_encryption_plugin.py index a0fc24252..2b09df8f1 100644 --- a/tests/unit/test_kms_encryption_plugin.py +++ b/tests/unit/test_kms_encryption_plugin.py @@ -537,7 +537,7 @@ def test_chain_order_payloads_after_plaintext_before(env, recorders): assert many == snapshot sent = [args for _, args, _ in raw.calls] assert [args for _, args, _ in after.seen] == sent - assert all(a[1] is b[1] for (_, a, _), b in zip(after.seen, sent)) + assert all(a[1] is b[1] for (_, a, _), b in zip(after.seen, sent, strict=False)) assert type(sent[0][1]) is tuple assert sent[0][1] is not one assert [EncryptionService.decrypt(sent[0][1][0], DATA_KEY, HMAC_KEY)] == list(one) @@ -721,7 +721,7 @@ def test_plain_columns_known_only_at_fetch_are_returned_as_given(plugin, env, re raw.arriving = ([("name",)], list(rows)) read_back = _read_rows(cur, read, 2) assert read_back == rows - assert all(got is given for got, given in zip(read_back, rows)) + assert all(got is given for got, given in zip(read_back, rows, strict=False)) assert env.keys.return_value.decrypt_data_key.call_count == 0 @@ -2216,7 +2216,7 @@ def test_unsafe_comparison_refused(mocker, env, dialect, sql, as_list): if as_list: params: Any = (secrets,) elif names: - params = dict(zip(names, secrets)) + params = dict(zip(names, secrets, strict=False)) else: params = tuple(secrets) _refused_as_unsafe(mocker, env, dialect, sql, params, secrets) @@ -2584,7 +2584,7 @@ def test_mysql_binary_prefix_goes_before_encrypted_placeholders(mocker, env, met sent_sql, sent = args if form == "positional" else (kwargs["operation"], kwargs[slot]) assert sent_sql == "INSERT INTO users (name, ssn, dob) VALUES (%s, _binary %s, _binary %s)" assert sets == snapshot - for row, sent_row in zip(sets, sent if method == "executemany" else [sent]): + for row, sent_row in zip(sets, sent if method == "executemany" else [sent], strict=False): assert sent_row[0] == "test-name" assert [EncryptionService.decrypt(v, DATA_KEY, HMAC_KEY) for v in sent_row[1:]] == list(row[1:]) diff --git a/tests/unit/test_metadata_manager.py b/tests/unit/test_metadata_manager.py index 9cf48d71a..6d871e6e6 100644 --- a/tests/unit/test_metadata_manager.py +++ b/tests/unit/test_metadata_manager.py @@ -118,7 +118,7 @@ def config(**overrides): key_management_retry_backoff_base_sec=0.1, audit_logging_enabled=False, return_unverified_data=False) values.update(overrides) - return EncryptionConfig(**values) # type: ignore[arg-type] + return EncryptionConfig(**values) def test_joined_query_left_joins_on_integer_id(): @@ -295,7 +295,7 @@ def refresh_once(): stop.set() return original() - mm.refresh = refresh_once # type: ignore[method-assign] + mm.refresh = refresh_once with caplog.at_level(logging.WARNING, logger=module.__name__): MetadataManager._refresh_loop(weakref.ref(mm), stop, 0) warnings = [r.getMessage() for r in caplog.records if r.name == module.__name__ and r.levelno == logging.WARNING] @@ -349,7 +349,7 @@ def counting_refresh(): refreshed.set() return n - mm.refresh = counting_refresh # type: ignore[method-assign] + mm.refresh = counting_refresh mm.start() thread = mm._refresh_thread assert thread is not None @@ -669,7 +669,7 @@ def test_non_text_names_uncached_lookup_raises(): db = FakeDb([row("users", 7)]) mm = MetadataManager(db, PG, PG, config(metadata_cache_enabled=False)) with pytest.raises(MetadataError, match="column_name"): - mm.column_config("users", 7) # type: ignore[arg-type] + mm.column_config("users", 7) def test_column_config_without_name_returns_none(): diff --git a/tests/unit/test_sql_analyzer.py b/tests/unit/test_sql_analyzer.py index 2938bc88a..7f6731054 100644 --- a/tests/unit/test_sql_analyzer.py +++ b/tests/unit/test_sql_analyzer.py @@ -1222,7 +1222,7 @@ def test_cached_and_immutable(self): a = analyze("SELECT * FROM t WHERE a = %s", PG, P) assert analyze("SELECT * FROM t WHERE a = %s", PG, [2]) is a with pytest.raises(AttributeError): - a.writes = True # type: ignore[misc] + a.writes = True def test_cache_is_per_dialect_and_style(self): sql = "SELECT * FROM t WHERE a = %s" @@ -1248,11 +1248,11 @@ def test_short_sql_with_many_placeholders_is_not_cached(self): def test_nested_results_are_frozen(self): a = analyze("INSERT INTO users (ssn) VALUES (%s)", PG, P) with pytest.raises(dataclasses.FrozenInstanceError): - a.assignments[0].column = ColumnRef("x") # type: ignore[misc] + a.assignments[0].column = ColumnRef("x") with pytest.raises(dataclasses.FrozenInstanceError): - a.assignments[0].column.table = "x" # type: ignore[misc] + a.assignments[0].column.table = "x" with pytest.raises(dataclasses.FrozenInstanceError): - a.placeholders[0].key = 5 # type: ignore[misc] + a.placeholders[0].key = 5 def test_recursion_error_is_not_cached(self, monkeypatch): # How deep sqlglot can recurse depends on the caller's stack, so a @@ -1288,7 +1288,7 @@ def deep(n): def test_type_error_for_non_str(self): with pytest.raises(TypeError): - analyze(b"SELECT 1", PG) # type: ignore[arg-type] + analyze(b"SELECT 1", PG) @pytest.mark.parametrize("dialect, sql, params", [ (MYSQL, "CALL p(%s)", P), diff --git a/tests/unit/test_sql_tokenizer.py b/tests/unit/test_sql_tokenizer.py index 1f2bcc17b..04aacf55e 100644 --- a/tests/unit/test_sql_tokenizer.py +++ b/tests/unit/test_sql_tokenizer.py @@ -265,7 +265,7 @@ def test_keywords_ignore_literals_comments_and_placeholder_names(self): def test_type_error_for_non_str(self): with pytest.raises(TypeError): - tokenize(b"SELECT 1", PG, NONE) # type: ignore[arg-type] + tokenize(b"SELECT 1", PG, NONE) @pytest.mark.parametrize("dialect, sql, names", [ (PG, 'UPDATE "My""T" SET a = %s -- t2', [("UPDATE", False), ("SET", False), ("a", False), ('My"T', True)]), From 1abdc418b6957b8e8442fb5e074a0190e682831c Mon Sep 17 00:00:00 2001 From: JuanLeee Date: Wed, 2 Dec 2026 14:13:20 -0700 Subject: [PATCH 5/6] test: add kms encryption plugin integration tests (#1349) --- .../kms_encryption_integration_tests.yml | 264 +++ docs/development-guide/IntegrationTests.md | 178 +- .../UsingTheKmsEncryptionPlugin.md | 3 + tests/integration/container/conftest.py | 12 +- .../django/test_django_kms_encryption.py | 151 ++ .../test_sqlalchemy_kms_encryption.py | 302 +++ .../container/test_kms_encryption_aurora.py | 380 ++++ .../test_kms_encryption_key_management.py | 722 +++++++ .../container/test_kms_encryption_kms.py | 522 +++++ .../test_kms_encryption_lifecycle.py | 493 +++++ .../container/test_kms_encryption_real_kms.py | 587 +++++ .../test_kms_encryption_round_trip.py | 683 ++++++ .../test_kms_encryption_server_logs.py | 479 +++++ .../test_kms_encryption_statements.py | 638 ++++++ .../container/test_kms_encryption_triggers.py | 541 +++++ .../container/utils/connection_utils.py | 22 +- .../container/utils/driver_helper.py | 5 +- .../container/utils/kms_encryption_helper.py | 846 ++++++++ .../container/utils/kms_encryption_schema.py | 83 + .../container/utils/test_environment.py | 2 +- .../utils/test_environment_features.py | 3 + .../container/utils/test_timings.py | 43 +- tests/integration/host/build.gradle.kts | 70 + .../integration/TestEnvironmentFeatures.java | 5 +- .../integration/host/TestEnvironment.java | 63 +- .../host/TestEnvironmentConfiguration.java | 15 + .../host/TestEnvironmentProvider.java | 93 +- .../integration/util/AuroraTestUtility.java | 9 +- .../integration/util/ContainerHelper.java | 38 +- .../java/integration/util/KmsTestUtility.java | 465 ++++ tests/integration/kms_local/compose.yaml | 28 + tests/integration/kms_local/run.sh | 170 ++ tests/integration/test_kms_encryption_live.py | 1914 ----------------- tests/unit/test_aio_plugin_factory.py | 26 + tests/unit/test_kms_encryption_plugin.py | 33 + ...est_kms_encryption_schema_matches_guide.py | 68 + tests/unit/test_kms_trigger_sql.py | 7 + 37 files changed, 8024 insertions(+), 1939 deletions(-) create mode 100644 .github/workflows/kms_encryption_integration_tests.yml create mode 100644 tests/integration/container/django/test_django_kms_encryption.py create mode 100644 tests/integration/container/sqlalchemy/test_sqlalchemy_kms_encryption.py create mode 100644 tests/integration/container/test_kms_encryption_aurora.py create mode 100644 tests/integration/container/test_kms_encryption_key_management.py create mode 100644 tests/integration/container/test_kms_encryption_kms.py create mode 100644 tests/integration/container/test_kms_encryption_lifecycle.py create mode 100644 tests/integration/container/test_kms_encryption_real_kms.py create mode 100644 tests/integration/container/test_kms_encryption_round_trip.py create mode 100644 tests/integration/container/test_kms_encryption_server_logs.py create mode 100644 tests/integration/container/test_kms_encryption_statements.py create mode 100644 tests/integration/container/test_kms_encryption_triggers.py create mode 100644 tests/integration/container/utils/kms_encryption_helper.py create mode 100644 tests/integration/container/utils/kms_encryption_schema.py create mode 100644 tests/integration/host/src/test/java/integration/util/KmsTestUtility.java create mode 100644 tests/integration/kms_local/compose.yaml create mode 100755 tests/integration/kms_local/run.sh delete mode 100644 tests/integration/test_kms_encryption_live.py create mode 100644 tests/unit/test_kms_encryption_schema_matches_guide.py 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/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