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..cbaa177c7 100644 --- a/aws_advanced_python_wrapper/encryption/config.py +++ b/aws_advanced_python_wrapper/encryption/config.py @@ -17,7 +17,7 @@ import math import os import re -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Type, TypeVar) @@ -60,19 +60,20 @@ 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(): @@ -132,6 +133,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: @@ -173,6 +175,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..559be7e58 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,50 @@ 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 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..23aa56a97 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,8 +179,6 @@ 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 serialize_value(cls, value: Any, marker: Optional[int] = None) -> bytes: """Serialize a value to the bytes that get encrypted. @@ -200,7 +191,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 +202,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 +224,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 +236,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 +245,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 +264,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 +305,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 +321,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 +337,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 +366,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 +383,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 +403,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 +440,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 +456,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..9e7343bff 100644 --- a/aws_advanced_python_wrapper/encryption/key_management_utility.py +++ b/aws_advanced_python_wrapper/encryption/key_management_utility.py @@ -15,29 +15,35 @@ from __future__ import annotations import time -from typing import TYPE_CHECKING, Any, List, Optional, cast +from typing import TYPE_CHECKING, Any, Dict, List, Optional, 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.connection_source import ( + CallerConnectionSource, 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.metadata_manager import \ MetadataManager from aws_advanced_python_wrapper.encryption.models import (KeyMetadata, + KeyOperation, 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_driver_dialect import \ + EncryptionDriverDialect +from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + 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 +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 logger = Logger(__name__) @@ -69,7 +75,9 @@ class KeyManagementUtility: 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. + 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, @@ -89,24 +97,48 @@ class KeyManagementUtility: ALIAS_PREFIX = "alias/python-kms-encryption-" 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._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: @@ -136,7 +168,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, @@ -155,9 +187,9 @@ def generate_and_store_data_key(self, table_name: str, column_name: str, master_ 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 @@ -182,20 +214,20 @@ def rotate_data_key(self, table_name: str, column_name: str, new_master_key_arn: 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) 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 @@ -208,8 +240,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,14 +250,14 @@ 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 is_master_key_valid(self, master_key_arn: str) -> bool: @@ -235,8 +267,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 +285,13 @@ 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 execute(conn, sql, params) + return run_statement(self._driver_dialect, conn, sql, params) except Exception as e: - raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", operation, e), - operation=operation) from e + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", operation.value, e), + operation=operation.value) from e @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..2e5f4da35 100644 --- a/aws_advanced_python_wrapper/encryption/key_manager.py +++ b/aws_advanced_python_wrapper/encryption/key_manager.py @@ -34,12 +34,13 @@ 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 ( + 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) from aws_advanced_python_wrapper.errors import (InvalidKeyMetadataError, KeyManagementError, UnauthorizedMasterKeyError) @@ -50,12 +51,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 +97,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 @@ -132,6 +136,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 +169,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 +208,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. @@ -213,7 +220,7 @@ def decrypt_data_key(self, encrypted_data_key: Optional[str], master_key_arn: Op 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") + 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 +235,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 +244,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 @@ -253,7 +260,7 @@ def generate_data_key(self, master_key_arn: str, 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)) + 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 +269,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 +283,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 +294,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 +306,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 +322,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,7 +334,7 @@ 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 @@ -340,40 +343,39 @@ def store_key_metadata(self, key_metadata: KeyMetadata) -> KeyMetadata: failure = self._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") 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("KeyManager.ReadKeyMetadataFailed", e), - operation="GET_KEY_METADATA") from e + operation=KeyOperation.GET_KEY_METADATA.value) 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") + 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) - # ---- 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") + operation=KeyOperation.AUTHORIZE_MASTER_KEY.value) @staticmethod def _describe_failure(error: Exception) -> str: @@ -386,7 +388,7 @@ def _describe_failure(error: Exception) -> str: 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 @@ -402,11 +404,11 @@ def _call_kms(self, operation: str, call: Callable[[], T], # 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, + Messages.get_formatted("KeyManager.KmsCallFailed", operation.value, attempt + 1, mask_arns_in_text(str(e))), - operation=operation) from e + operation=operation.value) from e delay = self._backoff_sec(attempt) - logger.debug("KeyManager.Retrying", operation, attempt + 1, max_retries + 1, delay, + logger.debug("KeyManager.Retrying", operation.value, attempt + 1, max_retries + 1, round(delay, 3), mask_arns_in_text(str(e))) 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..67d717745 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/kms_encryption_plugin.py @@ -0,0 +1,775 @@ +# 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 functools import partial +from typing import (TYPE_CHECKING, Any, Callable, Dict, 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 +_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} + + 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 == _NEXTSET: + return self._next_set(target, 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 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 == _ITER: + # Per row: the loop has received no row yet. + return map(partial(self._decode_late, target), result) + 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 + if method_name == _ITER: + # Once per loop: the driver's iterator still fetches the rows, a page at a time. + return map(decode, 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, run unanalyzed. + if text is None: + 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.""" + 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._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 _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: + table, column = ref.table or only, key(ref.column) + config = None if table is None else next( + (c for c in configs.get(key(table), ()) if key(c.column_name) == column), None) + else: + # Left to name matching in any letter case: a unique encrypted column of that name, named once in the result. + 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. + if found and (state.later or len(found) > 1 or lowered.count(lowered[i]) > 1): + raise MetadataError(Messages.get_formatted("KmsEncryptionPlugin.UnplacedColumn", names[i])) + config = found[0] if found else None + 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 _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 _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 _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..c2dd2b76e 100644 --- a/aws_advanced_python_wrapper/encryption/metadata_manager.py +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -23,18 +23,20 @@ from aws_advanced_python_wrapper.encryption.algorithm import \ EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.connection_source import 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 +44,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 +64,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 +80,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 +100,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 +154,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 +168,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,8 +183,8 @@ 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) @@ -195,8 +197,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 +220,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,7 +252,7 @@ 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 @@ -271,7 +271,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..68fbe0f41 100644 --- a/aws_advanced_python_wrapper/encryption/models.py +++ b/aws_advanced_python_wrapper/encryption/models.py @@ -19,6 +19,7 @@ import re from dataclasses import dataclass, field +from enum import Enum from typing import TYPE_CHECKING, Any, Mapping, Optional, cast from aws_advanced_python_wrapper.encryption.algorithm import \ @@ -30,6 +31,25 @@ 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" + 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" + + # 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 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..8c7d067c1 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, ...] = () @@ -196,6 +199,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 +224,7 @@ def parameter_columns(self) -> Dict[int, ColumnRef]: CACHEABLE_PERCENT_SIGNS = 64 -def analyze(sql: str, dialect: SqlDialect, params: Any = None) -> StatementAnalysis: +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 +252,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 +261,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 +319,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 +338,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 +362,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 +377,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 +395,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 +409,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 +429,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 +463,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 +485,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 +495,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 +551,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 +585,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): @@ -616,9 +644,8 @@ 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 ---- + 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 +720,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 +739,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 +827,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 +862,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 +887,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 +912,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 +922,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 +937,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 +999,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 +1057,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 +1139,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 +1172,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 +1194,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 +1259,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 +1283,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 +1382,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 @@ -1433,8 +1463,10 @@ 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 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..c0447fc56 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption_driver_dialect.py @@ -0,0 +1,180 @@ +# 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 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 + + @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..d6a0e94cd 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,41 @@ 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] = "`" + # 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 +268,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..b50948133 100644 --- a/aws_advanced_python_wrapper/pep249_methods.py +++ b/aws_advanced_python_wrapper/pep249_methods.py @@ -56,6 +56,7 @@ 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 properties and attributes CURSOR_CONNECTION = (28, "Cursor.connection", False) @@ -74,7 +75,7 @@ class DbApiMethod(Enum): ACCEPTS_STRATEGY = (39, "accepts_strategy", True) # Special marker for all methods - ALL = (40, "*", False) + ALL = (41, "*", 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..7abee97e7 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,41 @@ 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.=)" + 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 +216,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..a4ac51dee 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 @@ -552,10 +552,31 @@ 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 {}. +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.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 {}.{}. @@ -564,19 +585,54 @@ KeyManagementUtility.RotatedDataKey=[KeyManagementUtility] Rotated the data key 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 {}. +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. 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.Closed=[KmsEncryptionPlugin] The connection is closed, so the plugin refuses to analyze statements or results on it. +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.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.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.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..2c203165f 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." diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 1a10d88a1..9f745f40d 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -422,6 +422,12 @@ 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) + 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..71b95f8ab --- /dev/null +++ b/docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md @@ -0,0 +1,623 @@ +# 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. + Nothing validates the schema: a missing table or column makes the plugin's metadata reads raise `MetadataError`, and a missing primary key, unique constraint or foreign key goes unnoticed. +- 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) 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) 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`. +- 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 +utility.rotate_data_key("users", "ssn", master_key_arn) +conn.commit() +``` + +`rotate_data_key(table_name, column_name, new_master_key_arn=None)` gives the column a new data key, encrypted by `new_master_key_arn`. +Values written before keep decrypting with the key they were written with, and new writes use the new key. +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), and keep the old ARN listed while values written under it remain. + +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 `AWS_REGION` or `AWS_DEFAULT_REGION` is set | AWS region of the KMS calls. When it isn't set, the plugin uses the `AWS_REGION`, then the `AWS_DEFAULT_REGION` environment variable. A region set only in the AWS config file, for the default profile or the one `aws_profile` names, isn't read: connecting raises `EncryptionConfigError` ("[EncryptionConfig] No KMS region configured: set encryption_kms_region, or the AWS_REGION or AWS_DEFAULT_REGION environment variable."), so set `encryption_kms_region` as well. | `None` | +| `encryption_kms_endpoint` | String | No | KMS endpoint URL override. | `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 (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, 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. +A `bytes` statement that the connection's encoding doesn't decode exactly passes through with the same warning as other SQL the plugin can't analyze: with PostgreSQL's `SHIFT_JIS_2004`, whose Python codec reads the bytes of `\` and `~` as a yen sign and an overline, every `bytes` statement does. +On MySQL only `bytes` SQL that is all ASCII is analyzed, and other `bytes` SQL passes through with that warning. +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. +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, pass through in the same way; what the driver then does with them 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; an expression, a set operation's column and a select list with `*` are matched by name only (see [What the plugin does not see](#what-the-plugin-does-not-see)). +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. +If you don't, 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`. +Its message quotes KMS's error with the ARNs in it masked; so do the `DEBUG` record logged before each retry and the warning that `create_master_key` logs when it can't create an alias. +The AWS SDK's own error, kept as its `__cause__`, quotes KMS in full. +That can include 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, and a traceback that prints the cause shows them. +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. +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 instead of the plugin's. +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()` (to stream large results, use a named cursor with `fetchmany`), `cursor.results()` and `cursor.set_result()`. + Read each set from the cursor that `results()` yields or `set_result()` returns, which returns stored bytes. + A fetch from the cursor you called them on decodes each set it reads after its first with the columns of that first set, so a value can come back as stored bytes, and the fetch can raise `IntegrityCheckError`, `IndexError` or `KeyError`. +- 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()`, mysql-connector `stored_results()` and `fetchsets()`; SQL `PREPARE` and `EXECUTE` (on PostgreSQL, a `PREPARE` of a write gets the pass-through warning); `LOAD DATA`; stored routines and triggers. +- 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`. +- 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`). + The column comes back as stored bytes under an alias or a derived table's new name (`SELECT *, ssn AS x FROM users`, `SELECT * FROM (SELECT ssn AS x FROM users) s`), and 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"}]} + ``` + +- **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. +- 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: unknown encoding: koi8r"). 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..b40618c5b 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,7 @@ 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_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 +349,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 +361,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 +370,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 +451,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 +465,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 +473,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 +483,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 +504,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 +512,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 +539,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 +555,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 +572,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 +583,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..036c296c9 100644 --- a/tests/unit/test_encryption_config.py +++ b/tests/unit/test_encryption_config.py @@ -40,7 +40,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 @@ -82,7 +82,7 @@ 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): + def test_blank_region_falls_back_to_environment(self, monkeypatch): monkeypatch.setenv("AWS_REGION", "eu-west-1") assert EncryptionConfig.from_props(props(encryption_kms_region=" ")).kms_region == "eu-west-1" @@ -123,7 +123,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,12 +135,41 @@ 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)) @@ -164,7 +193,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}) @@ -245,7 +279,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..6741b8783 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,8 +228,6 @@ 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 TestMarkerCoverage: def test_generic_falls_back_to_str(self): class Thing: @@ -287,11 +271,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 +283,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 +303,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 +347,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 +408,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 +444,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 +490,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 +501,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 +509,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,31 +597,28 @@ 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")) 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) - + 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 +626,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 +653,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 +683,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 +726,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 +733,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 +769,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 +782,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 +821,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 +833,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..75a594486 100644 --- a/tests/unit/test_key_management_utility.py +++ b/tests/unit/test_key_management_utility.py @@ -13,13 +13,21 @@ # limitations under the License. import logging +import threading +import time from typing import Any, List, 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 @@ -30,17 +38,22 @@ 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.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 +94,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 +119,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 +128,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 +142,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, _ = utility(conn, driver=DriverDialectCodes.MYSQL_CONNECTOR_PYTHON) 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): + 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"): @@ -162,12 +180,12 @@ 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") assert u.rotate_data_key("users", "ssn") == 11 @@ -176,7 +194,7 @@ def test_rotate_keeping_the_current_master_key(self, conn): 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") @@ -204,7 +222,7 @@ def test_rotate_fails_if_no_row_was_updated(self, conn): 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 +268,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_masks_arns(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 +281,11 @@ 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 "could not create an alias" in warnings[0] + assert f"({code})" in warnings[0] + assert 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"): + 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 +304,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..0f72d8ec6 100644 --- a/tests/unit/test_key_manager.py +++ b/tests/unit/test_key_manager.py @@ -33,11 +33,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 +50,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:***:***:***" @@ -94,8 +99,12 @@ def connection(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 = 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 +144,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 +155,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 +171,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 +229,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 +248,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 +275,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 @@ -290,7 +305,7 @@ class TestQuotedKmsErrorsAreMasked: "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): + def test_decrypt_failure_masks_quoted_arns(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: @@ -305,7 +320,7 @@ def test_decrypt_failure_masks_the_arns_kms_quotes(self, kms, db, code, text): 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): + def test_decrypt_failure_without_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) @@ -323,7 +338,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_masks_quoted_arns(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 +346,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 f"({code})" in retries[0] + assert 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): + def test_validation_warning_masks_quoted_arns(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") @@ -343,7 +359,8 @@ def test_validation_warning_masks_the_arns_kms_quotes(self, kms, db, caplog): 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 "(AccessDeniedException)" in warnings[0] + assert MASKED_ROLE_SESSION_ARN in warnings[0] assert mask_arn(ARN) in warnings[0] _assert_names_no_identifier(warnings[0]) @@ -351,17 +368,19 @@ def test_validation_warning_masks_the_arns_kms_quotes(self, kms, db, caplog): 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 +398,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 +414,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 +424,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 +439,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 +457,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 +507,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 +526,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 +536,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 +545,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 +564,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,) @@ -561,15 +589,14 @@ def test_touch_key_swallows_errors(self, kms, db): 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 +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 +644,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 +683,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 +734,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 +748,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 +764,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 +785,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 +846,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 +877,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..01ef41d59 --- /dev/null +++ b/tests/unit/test_kms_encryption_plugin.py @@ -0,0 +1,2953 @@ +# 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] + + +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 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,) + + +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)} + + +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", "Closed", "CopyParameters", "CopyRefused", + "CopyUnread", "CteShadowsTable", "ExecutableComment", "HiddenPlaceholder", "MetadataNotLoaded", "NoExactForm", + "NoResultDescription", "NotAnalysed", "NotAPayload", "PassedThrough", "ReleaseFailed", "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``.""" + + 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, (SSN, DOB)) 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(plugin, caplog): + 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]) + 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_runs_unanalyzed(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): + for _ in range(2): + call(cur, "execute", sql, params) + 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 and c[1][1] is params for c in raw.calls] == [True, True] + assert _carrying(caplog, secret) == [] + assert env.metadata.call_count == 0 + _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) 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..ce9fc42c5 100644 --- a/tests/unit/test_metadata_manager.py +++ b/tests/unit/test_metadata_manager.py @@ -25,8 +25,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 +67,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 +110,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 +131,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 +158,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 +171,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 +198,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 +221,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,9 +249,9 @@ 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"): @@ -243,13 +263,13 @@ 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 +278,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 +291,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 +302,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 +312,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 +335,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 +353,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 +372,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 +382,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 +397,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 +413,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 +423,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 +442,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 +450,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 +470,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 +511,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 +528,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 +552,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 +567,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 +589,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 +598,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..0a5df5295 --- /dev/null +++ b/tests/unit/test_models.py @@ -0,0 +1,24 @@ +# 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 aws_advanced_python_wrapper.encryption.models import mask_arn, mask_key_id + + +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 diff --git a/tests/unit/test_mysql_driver_dialect.py b/tests/unit/test_mysql_driver_dialect.py index 93b2837ce..408b364a7 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,77 @@ 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 diff --git a/tests/unit/test_pg_driver_dialect.py b/tests/unit/test_pg_driver_dialect.py index b19e99a5a..04484eecc 100644 --- a/tests/unit/test_pg_driver_dialect.py +++ b/tests/unit/test_pg_driver_dialect.py @@ -17,7 +17,8 @@ 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 +187,80 @@ 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 diff --git a/tests/unit/test_plugin_manager.py b/tests/unit/test_plugin_manager.py index 804cad3a0..433e97ce4 100644 --- a/tests/unit/test_plugin_manager.py +++ b/tests/unit/test_plugin_manager.py @@ -15,6 +15,7 @@ from __future__ import annotations import contextvars +import copy import logging import threading from concurrent.futures import ThreadPoolExecutor @@ -799,7 +800,7 @@ def _call_context_manager(mocker, container, mock_telemetry_factory, plugins: Li return manager -def test_call_context_replacement_reaches_later_plugins_and_the_driver(mocker, container, mock_telemetry_factory, mock_conn): +def test_call_context_replacement_reaches_later_plugins_and_driver(mocker, container, mock_telemetry_factory, mock_conn): service = _call_context_service() seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] driver_calls = [] @@ -822,7 +823,7 @@ def test_call_context_replacement_reaches_later_plugins_and_the_driver(mocker, c @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( +def test_cursor_driver_method_receives_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() @@ -835,7 +836,7 @@ def test_cursor_driver_method_receives_the_replacement_as_written( 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): +def test_call_context_without_replacement_passes_caller_arguments(mocker, container, mock_telemetry_factory, mock_conn): driver_calls = [] params = ["v"] manager = _call_context_manager(mocker, container, mock_telemetry_factory, []) @@ -857,7 +858,7 @@ def test_without_a_replacement_the_driver_gets_the_callers_arguments(mocker, con 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( +def test_call_context_outer_rerun_starts_from_outer_arguments( mocker, container, mock_telemetry_factory, mock_conn): service = _call_context_service() seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] @@ -872,7 +873,7 @@ def test_call_context_outer_rerun_starts_from_the_arguments_the_outer_plugin_saw assert driver_calls == [("q", ("ENC",))] * 2 -def test_call_context_outer_retry_after_an_error_starts_from_the_arguments_the_outer_plugin_saw( +def test_call_context_outer_retry_after_error_starts_from_outer_arguments( 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. @@ -903,7 +904,7 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg 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): +def test_current_call_context_none_outside_call_and_after_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",)), {}))]) @@ -919,7 +920,7 @@ def failing_driver(*args, **kwargs): assert service.current_call_context is None -def test_only_execute_and_executemany_get_a_call_context(mocker, container, mock_telemetry_factory, mock_conn): +def test_call_context_only_for_execute_and_executemany(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] @@ -937,14 +938,15 @@ def test_only_execute_and_executemany_get_a_call_context(mocker, container, mock (DbApiMethod.CURSOR_FETCHMANY.method_name, None)] -def test_nested_execute_has_its_own_call_context_and_restores_the_enclosing_one( +def test_nested_execute_own_call_context_restores_enclosing( mocker, container, mock_telemetry_factory, mock_conn): service = _call_context_service() observed: List[Any] = [] def nested_execute(): + # Only the enclosing call makes a nested one. if observed: - return # only the enclosing call makes a nested one + return enclosing = service.current_call_context observed.append(("enclosing", None if enclosing is None else enclosing.args)) manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, @@ -959,7 +961,7 @@ def nested_execute(): 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): +def test_other_method_inside_execute_sees_enclosing_call_context(mocker, container, mock_telemetry_factory, mock_conn): service = _call_context_service() observed: List[Tuple[str, Optional[Tuple[Any, ...]]]] = [] @@ -1001,7 +1003,7 @@ def run(sql: str): assert mismatches == [] -def test_late_socket_timeout_worker_sends_the_replacement(mocker, container, mock_telemetry_factory, mock_conn): +def test_late_socket_timeout_worker_sends_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() @@ -1014,7 +1016,8 @@ def driver(*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 + # An earlier operation that is stuck holds the only worker. + pool.submit(release.wait, 10) container.plugin_service.driver_dialect.execute.side_effect = \ lambda method_name, func, *args, **kwargs: timeout(pool, 0.05)(func)() @@ -1029,7 +1032,7 @@ def driver(*args, **kwargs): assert sent in ([], [(("q", ("ENC",)), {})]) -def test_socket_timeout_worker_sends_the_replacement(mocker, container, mock_telemetry_factory, mock_conn): +def test_socket_timeout_worker_sends_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() @@ -1037,7 +1040,8 @@ def test_socket_timeout_worker_sends_the_replacement(mocker, container, mock_tel 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 + # Start the worker before the call, so it can't inherit the call's context. + pool.submit(lambda: None).result(5) 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",)) @@ -1046,7 +1050,7 @@ def test_socket_timeout_worker_sends_the_replacement(mocker, container, mock_tel @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): +def test_context_copied_during_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] = [] @@ -1086,17 +1090,36 @@ def test_call_context_repr_and_str_show_no_argument(): assert CALL_CONTEXT_MARKER not in format(context) -def test_call_context_rejects_an_unknown_attribute(): +def test_call_context_rejects_unknown_attribute(): context = PluginCallContext((), {}) with pytest.raises(AttributeError): - context.kwarg = {} # a misspelt kwargs fails instead of never reaching the driver + # A misspelt kwargs fails instead of never reaching the driver. + context.kwarg = {} context.args, context.kwargs = ("q",), {"params": ()} assert context.args == ("q",) assert context.kwargs == {"params": ()} +def test_call_context_holds_same_arguments(): + params = ["value"] + options = {"flag": True} + context = PluginCallContext(("q", params), {"options": options}) + + assert context.holds(("q", params), {"options": options}) is True + assert context.holds(tuple(context.args), dict(context.kwargs)) is True + + +def test_call_context_holds_rejects_copied_arguments(): + params = ["value"] + options = {"flag": True} + context = PluginCallContext(("q", params), {"options": options}) + + assert context.holds(copy.deepcopy(context.args), context.kwargs) is False + assert context.holds(context.args, copy.deepcopy(context.kwargs)) is False + + class CMySQLCursor: """Stands in for a mysql-connector cursor, whose str() quotes the start of its last statement with the values.""" @@ -1118,3 +1141,9 @@ def test_execute_against_old_connection_omits_statement_text(mocker, container, assert "secret-literal" not in str(e.value) assert "'CMySQLCursor'" in str(e.value) + + +def test_db_api_method_ids_are_unique_and_all_is_last(): + ids = [method.id for method in DbApiMethod] + assert len(set(ids)) == len(ids) + assert DbApiMethod.ALL.id == max(ids) diff --git a/tests/unit/test_psycopg3_parity_passthroughs.py b/tests/unit/test_psycopg3_parity_passthroughs.py index 7afe740b4..9d20127c2 100644 --- a/tests/unit/test_psycopg3_parity_passthroughs.py +++ b/tests/unit/test_psycopg3_parity_passthroughs.py @@ -295,6 +295,21 @@ async def _pm_execute(obj, method, func, *a, **k): "SELECT 1", prepare=None, binary=False) +def test_cursor_copy_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 + + 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_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..d3d6cf0ae 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,7 +938,7 @@ 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 @@ -888,7 +946,7 @@ def test_a_cte_sees_only_the_ctes_before_it(self, dialect, sql, expected): "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): + def test_source_with_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) @@ -898,7 +956,7 @@ def test_a_source_with_a_column_list_stays_unknown(self, dialect, sql): ("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 +992,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 +1018,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 +1036,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 +1066,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 +1095,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 +1153,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 +1180,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 +1217,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 +1229,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 +1260,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 +1272,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 +1285,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 +1310,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 +1324,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 +1356,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 +1367,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 +1394,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 +1420,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 +1433,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 +1484,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 +1528,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 +1541,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 +1557,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 +1570,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 +1594,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 +1601,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 +1627,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 +1648,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 +1676,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 +1695,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 +1731,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 +1762,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 +1806,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 +1836,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 +1860,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 +1881,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