diff --git a/CHANGELOG.md b/CHANGELOG.md index 03eec8a12..74d6db5f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] ### :magic_wand: Added +* Synchronous plugins can replace the arguments that `Cursor.execute` and `Cursor.executemany` pass to the plugins after them and to the target driver, without modifying the caller's objects, by assigning new `args` and `kwargs` to the plugin service's `current_call_context`. See [The Call Context](./docs/development-guide/PluginService.md#the-call-context). ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) * The `failover` and `failover_v2` plugins currently rewraps all errors to an AwsWrapperError even when the errors do not trigger failover. Set the `preserve_driver_exception_type` configuration parameter to `True` to re-raise the target driver errors as-is for the failover plugins. Failover errors are unaffected and are still raised as `FailoverSuccessError`, `FailoverFailedError` or `TransactionResolutionUnknownError`. This is useful for ORMs to properly classify the errors. ([Issue #1275](https://github.com/aws/aws-advanced-python-wrapper/issues/1275)) +### :bug: Fixed +* With psycopg's synchronous cursor, a fetch chained onto `cursor.execute()` (`cursor.execute(query).fetchone()`) skipped every plugin, the failover and host monitoring plugins included, because `execute()` returned the driver's cursor. It now returns the wrapper's cursor, so `isinstance(cursor.execute(query), psycopg.Cursor)` is now `False`. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) +* `next(cursor)` on a synchronous cursor raised `TypeError`. It now returns the next row through the plugins subscribed to `Cursor.__next__`. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) +* Loops over a synchronous cursor (`for row in cursor`) skipped every plugin. A loop now calls the plugins subscribed to `Cursor.__iter__`, and those subscribed to every method, such as `execute_time`, once per loop, not once per row. A loop over a cursor whose connection is no longer the current one now raises `AwsWrapperError` where `fetchone` does. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330)) + ## [3.1.0] - 2026-08-24 ### :magic_wand: Added * Python 3.14 support. ([PR #1252](https://github.com/aws/aws-advanced-python-wrapper/pull/1252)) diff --git a/aws_advanced_python_wrapper/driver_dialect.py b/aws_advanced_python_wrapper/driver_dialect.py index c667316b5..03fa09304 100644 --- a/aws_advanced_python_wrapper/driver_dialect.py +++ b/aws_advanced_python_wrapper/driver_dialect.py @@ -131,7 +131,9 @@ def execute( exec_timeout: Optional[float] = None, conn: Optional[Connection] = None, **kwargs: Any) -> Cursor: - if DbApiMethod.ALL.method_name not in self.network_bound_methods and method_name not in self.network_bound_methods: + # Cursor.__iter__ only creates the driver's iterator; the rows are fetched outside this call. + if method_name == DbApiMethod.CURSOR_ITER.method_name or ( + DbApiMethod.ALL.method_name not in self.network_bound_methods and method_name not in self.network_bound_methods): return exec_func() if exec_timeout is None: diff --git a/aws_advanced_python_wrapper/encryption/__init__.py b/aws_advanced_python_wrapper/encryption/__init__.py new file mode 100644 index 000000000..bd4acb2bf --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/__init__.py @@ -0,0 +1,13 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/aws_advanced_python_wrapper/encryption/algorithm.py b/aws_advanced_python_wrapper/encryption/algorithm.py new file mode 100644 index 000000000..c3ae42fcb --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/algorithm.py @@ -0,0 +1,68 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Dict, Optional, Tuple + +from aws_advanced_python_wrapper.errors import InvalidAlgorithmError + + +class EncryptionAlgorithm: + """The symmetric algorithms the plugin can use to encrypt column values. + + These names are stored in the ``encryption_metadata.encryption_algorithm`` + column of the metadata tables. + """ + + AES_256_GCM: str = "AES-256-GCM" + AES_128_GCM: str = "AES-128-GCM" + DEFAULT: str = AES_256_GCM + + # Expected data key length in bytes for each algorithm. + _KEY_LENGTHS: Dict[str, int] = { + AES_256_GCM: 32, + AES_128_GCM: 16, + } + + ALL: Tuple[str, ...] = tuple(_KEY_LENGTHS.keys()) + + @classmethod + def data_key_spec(cls, name: str) -> str: + """Return the KMS ``GenerateDataKey`` key spec (``AES_256`` / + ``AES_128``) that yields a data key of the right length for ``name``. + This is also the value stored in ``key_storage.key_spec``.""" + return f"AES_{cls.key_length(name) * 8}" + + @classmethod + def key_length(cls, name: str) -> int: + """Return the required data key length in bytes for ``name``.""" + try: + return cls._KEY_LENGTHS[name] + except KeyError: + # ``from None`` drops the KeyError from the dict lookup; + # unsupported() already explains the failure. + raise cls.unsupported(name) from None + + @classmethod + def is_supported(cls, name: Optional[str]) -> bool: + return name in cls._KEY_LENGTHS + + @classmethod + def unsupported(cls, name: Optional[str]) -> InvalidAlgorithmError: + return InvalidAlgorithmError( + f"Unsupported kms_encryption algorithm: {name!r}. " + f"Supported algorithms: {', '.join(cls.ALL)}", + algorithm=name, + ) diff --git a/aws_advanced_python_wrapper/encryption/buffers.py b/aws_advanced_python_wrapper/encryption/buffers.py new file mode 100644 index 000000000..c9b63bf2a --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/buffers.py @@ -0,0 +1,34 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Helpers for buffers holding key material. + +Kept free of third-party imports, so the key and metadata layer can be +imported without the ``encryption`` extra (``cryptography``) installed. +""" + +from __future__ import annotations + +from typing import Any, Union + +BytesLike = Union[bytes, bytearray, memoryview] + + +def wipe(buffer: Any) -> None: + """Overwrite a mutable ``bytearray`` with zeros, in place. Best effort: + immutable ``bytes`` cannot be zeroed, so hold key material in + ``bytearray`` where wiping matters. CPython may still leave copies + elsewhere.""" + if isinstance(buffer, bytearray): + buffer[:] = bytes(len(buffer)) diff --git a/aws_advanced_python_wrapper/encryption/config.py b/aws_advanced_python_wrapper/encryption/config.py new file mode 100644 index 000000000..ac3638591 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/config.py @@ -0,0 +1,179 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +import os +import re +from dataclasses import dataclass, field +from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Type, + TypeVar) + +from aws_advanced_python_wrapper.errors import EncryptionConfigError +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import (WrapperProperties, + WrapperProperty) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.utils.properties import Properties + +# Schema names cannot be bound as statement parameters, so they are +# interpolated into the plugin's own SQL. Only plain identifiers are accepted, +# which rules out quoting, whitespace, comments, and statement separators. +_SCHEMA_NAME_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + +T = TypeVar("T", int, float) + + +def validate_schema_name(name: Any) -> str: + """Return ``name`` if it is a plain SQL identifier, else raise + :class:`EncryptionConfigError`.""" + if not isinstance(name, str) or not _SCHEMA_NAME_PATTERN.fullmatch(name): + raise EncryptionConfigError( + Messages.get_formatted("EncryptionConfig.InvalidSchemaName", repr(name))) + return name + + +def _normalize_arns(value: Any) -> FrozenSet[str]: + """Accept ``None``, a comma-separated string, or an iterable of strings.""" + if value is None: + return frozenset() + entries: Iterable[Any] = value.split(",") if isinstance(value, str) else value + return frozenset(s for s in (str(e).strip() for e in entries) if s) + + +@dataclass(frozen=True) +class EncryptionConfig: + """The plugin's configuration, resolved once from the connection + properties. Build it with :meth:`from_props`; the constructor validates.""" + + kms_region: str + allowed_master_key_arns: FrozenSet[str] = field(default_factory=frozenset) + kms_endpoint: Optional[str] = None + metadata_schema: str = "encrypt" + metadata_cache_enabled: bool = True + metadata_cache_expiration_sec: float = 3600.0 + metadata_cache_refresh_interval_sec: float = 300.0 + data_key_cache_enabled: bool = True + data_key_cache_max_size: int = 1000 + data_key_cache_expiration_sec: float = 300.0 + key_management_max_retries: int = 3 + key_management_retry_backoff_base_sec: float = 0.1 + audit_logging_enabled: bool = False + return_unverified_data: bool = False + + def __post_init__(self) -> None: + if not self.kms_region or not self.kms_region.strip(): + raise EncryptionConfigError(Messages.get("EncryptionConfig.MissingRegion")) + # Normalize here too, so a directly constructed config gets the same + # exact-match semantics as one built from properties. + object.__setattr__(self, "allowed_master_key_arns", _normalize_arns(self.allowed_master_key_arns)) + validate_schema_name(self.metadata_schema) + + wp = WrapperProperties + # Durations must be finite: an infinite interval or TTL reaches + # Event.wait(), which rejects it and kills the background thread, and + # an infinite expiry or backoff is never what was meant. + self._require(_finite(self.metadata_cache_expiration_sec) and self.metadata_cache_expiration_sec > 0, + wp.ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC, "a finite number > 0") + self._require(_finite(self.metadata_cache_refresh_interval_sec) and self.metadata_cache_refresh_interval_sec >= 0, + wp.ENCRYPTION_METADATA_CACHE_REFRESH_INTERVAL_SEC, "a finite number >= 0") + self._require(self.data_key_cache_max_size > 0, wp.ENCRYPTION_DATA_KEY_CACHE_MAX_SIZE, "> 0") + self._require(_finite(self.data_key_cache_expiration_sec) and self.data_key_cache_expiration_sec > 0, + wp.ENCRYPTION_DATA_KEY_CACHE_EXPIRATION_SEC, "a finite number > 0") + self._require(self.key_management_max_retries >= 0, wp.ENCRYPTION_KEY_MANAGEMENT_MAX_RETRIES, ">= 0") + self._require(_finite(self.key_management_retry_backoff_base_sec) + and self.key_management_retry_backoff_base_sec > 0, + wp.ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC, "a finite number > 0") + + @classmethod + def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = True) -> EncryptionConfig: + """Build the configuration from connection properties. + + :param require_allowed_master_keys: the plugin refuses to run without + ``encryption_allowed_master_key_arns``. Only administrative setup + code that builds a config for :class:`KeyManagementUtility` should + pass ``False``, so a new master key can be created and used in the + same setup script. + :raises EncryptionConfigError: if a value is missing or out of range. + """ + wp = WrapperProperties + # A blank value at one level falls through to the next. + region = (_stripped(wp.ENCRYPTION_KMS_REGION.get(props)) + or _stripped(os.environ.get("AWS_REGION")) + or _stripped(os.environ.get("AWS_DEFAULT_REGION"))) + config = cls( + kms_region=region, + kms_endpoint=wp.ENCRYPTION_KMS_ENDPOINT.get(props), + # Read directly: the value may be a list, which WrapperProperty.get + # (typed Optional[str]) does not model. + allowed_master_key_arns=_normalize_arns(props.get(wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)), + metadata_schema=wp.ENCRYPTION_METADATA_SCHEMA.get(props) or "", + metadata_cache_enabled=wp.ENCRYPTION_METADATA_CACHE_ENABLED.get_bool(props), + metadata_cache_expiration_sec=_number(wp.ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC, props, float), + metadata_cache_refresh_interval_sec=_number(wp.ENCRYPTION_METADATA_CACHE_REFRESH_INTERVAL_SEC, props, float), + data_key_cache_enabled=wp.ENCRYPTION_DATA_KEY_CACHE_ENABLED.get_bool(props), + data_key_cache_max_size=_number(wp.ENCRYPTION_DATA_KEY_CACHE_MAX_SIZE, props, int), + data_key_cache_expiration_sec=_number(wp.ENCRYPTION_DATA_KEY_CACHE_EXPIRATION_SEC, props, float), + key_management_max_retries=_number(wp.ENCRYPTION_KEY_MANAGEMENT_MAX_RETRIES, props, int), + key_management_retry_backoff_base_sec=_number( + wp.ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC, props, float), + audit_logging_enabled=wp.ENCRYPTION_AUDIT_LOGGING_ENABLED.get_bool(props), + return_unverified_data=wp.ENCRYPTION_RETURN_UNVERIFIED_DATA.get_bool(props), + ) + + if require_allowed_master_keys and not config.restricts_master_keys: + raise EncryptionConfigError( + Messages.get_formatted("EncryptionConfig.MissingAllowedMasterKeys", + wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)) + return config + + @property + def restricts_master_keys(self) -> bool: + """``True`` when only the listed master keys may be used.""" + return bool(self.allowed_master_key_arns) + + @property + def background_refresh_enabled(self) -> bool: + return self.metadata_cache_enabled and self.metadata_cache_refresh_interval_sec > 0 + + def is_master_key_allowed(self, master_key_arn: Optional[str]) -> bool: + """Exact-match check against the allow-list. With no allow-list + configured (administrative use only) every key is allowed.""" + if not self.restricts_master_keys: + return True + return master_key_arn is not None and master_key_arn in self.allowed_master_key_arns + + @staticmethod + def _require(condition: bool, prop: WrapperProperty, requirement: str) -> None: + if not condition: + raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.OutOfRange", prop.name, requirement)) + + +def _stripped(value: Optional[str]) -> str: + return (value or "").strip() + + +def _finite(value: float) -> bool: + return isinstance(value, (int, float)) and math.isfinite(value) + + +def _number(prop: WrapperProperty, props: Properties, kind: Type[T]) -> T: + """Read a numeric property, naming it if the value is not a number. + Property values are configuration, not secrets, so chaining is fine.""" + try: + return prop.get_type(props, kind) + except (TypeError, ValueError) as e: + raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.InvalidValue", prop.name, e)) from e diff --git a/aws_advanced_python_wrapper/encryption/connection_source.py b/aws_advanced_python_wrapper/encryption/connection_source.py new file mode 100644 index 000000000..78c382f10 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/connection_source.py @@ -0,0 +1,113 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Where the key and metadata layer gets a connection to run its SQL on.""" + +from __future__ import annotations + +from contextlib import contextmanager +from threading import local +from typing import (TYPE_CHECKING, Any, ContextManager, Iterator, Optional, + Protocol) + +from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.retry_util import RetryUtil + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.plugin import Plugin + from aws_advanced_python_wrapper.plugin_service import PluginService + + +class ConnectionSource(Protocol): + def connection(self) -> ContextManager[Any]: + """Return a context manager that yields a DB-API connection.""" + ... + + +class CallerConnectionSource: + """Runs every operation on a connection the caller owns. + + The connection is never closed, committed, or rolled back here, so a + multi-step administrative operation stays inside the caller's transaction. + """ + + def __init__(self, conn: Any): + self._conn = conn + + @contextmanager + def connection(self) -> Iterator[Any]: + yield self._conn + + +class PluginConnectionSource: + """Opens a short-lived connection through the wrapper's connect pipeline + and closes it: one per :meth:`connection` call, or one per + :meth:`statement` scope on the thread. + + Metadata and key reads therefore never use the application's connection, + and cannot block on or join the application's transaction. The connection + runs in autocommit mode so a read never leaves a session idle in a + transaction and a ``last_used_at`` update is not lost on close. + """ + + def __init__(self, plugin_service: PluginService, plugin_to_skip: Optional[Plugin] = None): + self._plugin_service = plugin_service + self._plugin_to_skip = plugin_to_skip + self._scope = local() + + @contextmanager + def statement(self) -> Iterator[None]: + """Share one connection among the lookups of one statement on this thread. + + The connection opens at the first lookup inside the scope and closes when + the outermost scope ends, also when a lookup fails, so a statement uses at + most one short-lived connection. A scope that looks nothing up opens + nothing. + """ + depth = getattr(self._scope, "depth", 0) + self._scope.depth = depth + 1 + if depth == 0: + self._scope.conn = None + try: + yield + finally: + self._scope.depth = depth + if depth == 0: + conn, self._scope.conn = self._scope.conn, None + if conn is not None: + RetryUtil.close_connection(self._plugin_service, conn) + + @contextmanager + def connection(self) -> Iterator[Any]: + if getattr(self._scope, "depth", 0): + if self._scope.conn is None: + self._scope.conn = self._open() + yield self._scope.conn + return + conn = self._open() + try: + yield conn + finally: + RetryUtil.close_connection(self._plugin_service, conn) + + def _open(self) -> Any: + service = self._plugin_service + conn = service.force_connect( + service.current_host_info, Properties(service.props.copy()), self._plugin_to_skip) + try: + service.driver_dialect.set_autocommit(conn, True) + except BaseException: # noqa: BLE001 - close the half-opened connection, then re-raise it as is + RetryUtil.close_connection(service, conn) + raise + return conn diff --git a/aws_advanced_python_wrapper/encryption/data_key_cache.py b/aws_advanced_python_wrapper/encryption/data_key_cache.py new file mode 100644 index 000000000..8aeb7eb0b --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/data_key_cache.py @@ -0,0 +1,228 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import time +import weakref +from collections import OrderedDict +from dataclasses import dataclass +from threading import Event, Lock, Thread, current_thread +from typing import List, Optional + +from aws_advanced_python_wrapper.encryption.buffers import BytesLike, wipe +from aws_advanced_python_wrapper.utils.log import Logger + +logger = Logger(__name__) + + +@dataclass(frozen=True) +class DataKeyCacheStats: + size: int + hits: int + misses: int + evictions: int + + @property + def hit_rate(self) -> float: + """Percentage of lookups served from the cache.""" + total = self.hits + self.misses + return 100.0 * self.hits / total if total else 0.0 + + +class _Entry: + __slots__ = ("data_key", "expires_at") + + def __init__(self, data_key: bytearray, expires_at: float): + self.data_key = data_key + self.expires_at = expires_at + + def __repr__(self) -> str: + return f"_Entry(data_key='[REDACTED]', expires_at={self.expires_at!r})" + + +class DataKeyCache: + """An in-memory cache of plaintext data keys, so reading an encrypted + column does not need a KMS ``Decrypt`` call per statement. + + The wrapper's shared storage service is not used here, because data keys + need a bounded size with oldest-first eviction. Their bytes are zeroed when + they leave the cache. Each ``get`` returns a fresh ``bytearray`` copy, so a + caller wiping its copy cannot corrupt the cached one. An expired entry is + never returned, even before the cleanup thread removes it. + + Call :meth:`close` when done with the cache. After ``close`` the cache + stores nothing. A cache dropped without ``close`` still stops its cleanup + thread and wipes its keys once it is garbage-collected, because the thread + holds only a weak reference to it. + + Wiping is best effort: CPython may hold other copies of the key bytes. + """ + + MIN_CLEANUP_INTERVAL_SEC = 30.0 + SHUTDOWN_TIMEOUT_SEC = 5.0 + + def __init__(self, max_size: int, ttl_sec: float, enabled: bool = True, + *, start_cleanup_thread: bool = True): + self._max_size = max_size + self._ttl_sec = ttl_sec + self._enabled = enabled + self._entries: OrderedDict[str, _Entry] = OrderedDict() + self._lock = Lock() + self._hits = 0 + self._misses = 0 + self._evictions = 0 + self._closed = False + self._stop = Event() + self._cleanup_thread: Optional[Thread] = None + # Holds the cleanup thread for the finalizer, which must not refer to + # self, or the cache would never be collected. + self._thread_holder: List[Optional[Thread]] = [None] + # Runs at close() or when the cache is collected, whichever is first. + self._finalizer = weakref.finalize( + self, DataKeyCache._release, self._entries, self._lock, self._stop, self._thread_holder) + if enabled and start_cleanup_thread: + self._cleanup_thread = Thread( + target=DataKeyCache._cleanup_loop, args=(weakref.ref(self), self._stop, self.cleanup_interval_sec), + name="kms-encryption-data-key-cache-cleanup", daemon=True) + self._thread_holder[0] = self._cleanup_thread + self._cleanup_thread.start() + + @property + def enabled(self) -> bool: + return self._enabled + + @property + def cleanup_interval_sec(self) -> float: + return max(self._ttl_sec / 4, self.MIN_CLEANUP_INTERVAL_SEC) + + def get(self, key: str) -> Optional[bytearray]: + """Return a copy of the cached data key, or ``None`` on a miss. The + caller owns the copy and should wipe it once used.""" + if not self._enabled: + return None + with self._lock: + if self._closed: + return None + entry = self._entries.get(key) + if entry is None: + self._misses += 1 + return None + if entry.expires_at <= time.monotonic(): + del self._entries[key] + wipe(entry.data_key) + self._misses += 1 + return None + self._hits += 1 + return bytearray(entry.data_key) + + def put(self, key: str, data_key: BytesLike) -> None: + """Store a copy of ``data_key``, evicting the oldest entry when full. + The caller keeps ownership of the buffer it passed in. A closed cache + stores nothing.""" + if not self._enabled: + return + entry = _Entry(bytearray(data_key), time.monotonic() + self._ttl_sec) + with self._lock: + if self._closed: + wipe(entry.data_key) + return + self._discard(key) + while len(self._entries) >= self._max_size: + _, oldest = self._entries.popitem(last=False) + wipe(oldest.data_key) + self._evictions += 1 + self._entries[key] = entry + + def remove(self, key: str) -> None: + with self._lock: + self._discard(key) + + def clear(self) -> None: + """Zero and drop every cached data key.""" + DataKeyCache._wipe_all(self._entries, self._lock) + + def remove_expired(self) -> int: + """Drop every expired entry. Returns the number removed.""" + now = time.monotonic() + with self._lock: + expired = [k for k, e in self._entries.items() if e.expires_at <= now] + for k in expired: + self._discard(k) + return len(expired) + + def stats(self) -> DataKeyCacheStats: + with self._lock: + return DataKeyCacheStats(len(self._entries), self._hits, self._misses, self._evictions) + + def __len__(self) -> int: + with self._lock: + return len(self._entries) + + def close(self) -> None: + """Stop the cleanup thread and zero every cached key. Later ``put`` + calls store nothing. Idempotent. + + Call it from ordinary code, not from a finalizer or ``__del__``: a + garbage collection on the cleanup thread can run inside its wait, where + stopping the thread would deadlock. + """ + with self._lock: + self._closed = True + self._stop.set() + self._finalizer() + thread = self._cleanup_thread + if thread is not None and thread is not current_thread(): + thread.join(self.SHUTDOWN_TIMEOUT_SEC) + self._cleanup_thread = None + + def _discard(self, key: str) -> None: + # Callers hold the lock. + entry = self._entries.pop(key, None) + if entry is not None: + wipe(entry.data_key) + + @staticmethod + def _wipe_all(entries: OrderedDict[str, _Entry], lock: Lock) -> None: + with lock: + for entry in entries.values(): + wipe(entry.data_key) + entries.clear() + + @staticmethod + def _release(entries: OrderedDict[str, _Entry], lock: Lock, stop: Event, + thread_holder: List[Optional[Thread]]) -> None: + # Runs at close() or when an unclosed cache is collected. Wipe first, + # so the keys are zeroed whatever happens next. A collection can run + # on the cleanup thread itself, inside Event.wait while it holds the + # event's lock, where stop.set() would deadlock; that thread exits on + # its own, finding the cache gone as soon as wait returns. + DataKeyCache._wipe_all(entries, lock) + if thread_holder[0] is not current_thread(): + stop.set() + + @staticmethod + def _cleanup_loop(cache_ref: weakref.ref[DataKeyCache], stop: Event, interval_sec: float) -> None: + # Holds the cache only weakly between runs, so an unclosed cache can + # still be collected. Event.wait returns as soon as close() (or the + # finalizer) sets the event, so shutdown does not wait out an interval. + while not stop.wait(interval_sec): + cache = cache_ref() + if cache is None: + return + try: + cache.remove_expired() + except Exception as e: # pragma: no cover - defensive + logger.debug("DataKeyCache.CleanupFailed", type(e).__name__) + del cache diff --git a/aws_advanced_python_wrapper/encryption/encryption_service.py b/aws_advanced_python_wrapper/encryption/encryption_service.py new file mode 100644 index 000000000..8738e49ad --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/encryption_service.py @@ -0,0 +1,529 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import hashlib +import hmac +import operator +import os +import struct +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal, InvalidOperation +from typing import TYPE_CHECKING, Any, Optional, Union + +try: + from cryptography.exceptions import InvalidTag + from cryptography.hazmat.primitives.ciphers.aead import AESGCM +except ModuleNotFoundError as e: # pragma: no cover - exercised by the import-guard test + # Only a missing package gets the install hint. An installed but broken + # cryptography raises its own ImportError, which is clearer as it is. + if (e.name or "").partition(".")[0] != "cryptography": + raise + raise ImportError( + "The KMS encryption plugin needs the 'cryptography' package. " + "Install it with: pip install 'aws-advanced-python-wrapper[encryption]'") from e + +from aws_advanced_python_wrapper.encryption import buffers +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker +from aws_advanced_python_wrapper.errors import (DecryptionError, + EncryptionFailedError, + IntegrityCheckError, + InvalidKeyError, + TypeConversionError) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.buffers import BytesLike + +_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) +_MICROSECOND = timedelta(microseconds=1) +_MILLISECOND = timedelta(milliseconds=1) +# The epoch-millis range a datetime can be read back into. +_MIN_MILLIS = -((_EPOCH - datetime.min.replace(tzinfo=timezone.utc)) // _MILLISECOND) +_MAX_MILLIS = (datetime.max.replace(tzinfo=timezone.utc) - _EPOCH) // _MILLISECOND + + +class EncryptionService: + """Encrypts and decrypts single column values with AES-GCM, signed with a + separate HMAC-SHA256 key. + + The payload has this layout. The database-side trigger checks its minimum + length and its HMAC tag:: + + [ HMAC-SHA256 tag : 32 ][ key id : 4 ][ type marker : 1 ][ GCM IV : 12 ][ ciphertext ][ GCM tag : 16 ] + + The HMAC covers everything after itself, so the database can detect a + tampered payload (the ``verify_encrypted_data_hmac`` SQL function) without + holding the data key. The key id is the ``key_storage`` row the value was + encrypted with, which keeps the value decryptable after its column's data + key is rotated. It sits inside the HMAC-covered region, so tampering with + it is detected too. The type marker records how the plaintext was + serialized, so the original Python type can be restored on read. + + Errors never quote plaintext. Several standard-library failures do quote + their input (``UnicodeEncodeError.object``, ``int("...")``, + ``datetime.fromisoformat``), and an exception raised inside an ``except`` + block keeps the caught one as ``__context__`` even with ``from None``. So + where such a failure is caught, the wrapper error is raised after the + ``except`` block, with nothing chained. + """ + + HMAC_TAG_LENGTH = 32 + KEY_ID_LENGTH = 4 + TYPE_MARKER_LENGTH = 1 + GCM_IV_LENGTH = 12 + GCM_TAG_LENGTH = 16 + MIN_ENCRYPTED_LENGTH = ( + HMAC_TAG_LENGTH + KEY_ID_LENGTH + TYPE_MARKER_LENGTH + GCM_IV_LENGTH + GCM_TAG_LENGTH + ) + + #: Zero a ``bytearray`` in place; see :func:`buffers.wipe`. + wipe = staticmethod(buffers.wipe) + + # ---- public API ---- + + @classmethod + def encrypt(cls, value: Any, data_key: BytesLike, hmac_key: BytesLike, + algorithm: str = EncryptionAlgorithm.DEFAULT, *, key_id: int) -> Optional[bytes]: + """Encrypt a single value. + + :param value: the plaintext value; ``None`` is returned unchanged. + :param data_key: the plaintext data key, binary. + :param hmac_key: the HMAC-SHA256 key, binary. + :param algorithm: an :class:`EncryptionAlgorithm` name. + :param key_id: the ``key_storage`` id of the data key, recorded in the + payload so the value stays decryptable after the column's key is + rotated. + :return: the binary payload to store, or ``None`` when value is ``None``. + :raises EncryptionError: if the key, algorithm, or key id is unusable, + or the value cannot be serialized. + """ + if value is None: + return None + + cls._validate_key(data_key, algorithm) + cls._validate_hmac_key(hmac_key) + cls._validate_key_id(key_id) + + marker = TypeMarker.from_object(value) + # The buffer handed to AES-GCM is the one wiped afterwards. + plaintext = bytearray(cls.serialize_value(value, marker)) + try: + # body = [ key id : 4 ][ type marker : 1 ][ IV : 12 ][ ciphertext ][ GCM tag : 16 ] + body = struct.pack(">I", key_id) + cls._seal(plaintext, marker, data_key, algorithm) + tag = hmac.new(cls._hmac_key(hmac_key), body, hashlib.sha256).digest() + return tag + body + finally: + cls.wipe(plaintext) + + @classmethod + def key_id_from_payload(cls, encrypted: Optional[BytesLike]) -> Optional[int]: + """Read the key id recorded in a payload, without verifying or + decrypting it. A payload with no key id (too short) yields ``None``. + """ + if encrypted is None: + return None + data = cls._to_bytes(encrypted) + if len(data) < cls.HMAC_TAG_LENGTH + cls.KEY_ID_LENGTH: + return None + return struct.unpack(">I", data[cls.HMAC_TAG_LENGTH:cls.HMAC_TAG_LENGTH + cls.KEY_ID_LENGTH])[0] + + @classmethod + def decrypt(cls, encrypted: Optional[BytesLike], data_key: BytesLike, hmac_key: BytesLike, + algorithm: str = EncryptionAlgorithm.DEFAULT, *, target_type: Optional[type] = None) -> Any: + """Decrypt a payload produced by :meth:`encrypt`. + + :param target_type: the type to coerce the result to; defaults to the + type recorded by the payload's marker. + :raises IntegrityCheckError: if the payload is too short or its HMAC + does not verify: it was modified, was never encrypted, or was + signed with a different HMAC key. + :raises EncryptionError: if the payload cannot be decrypted with the + given key or its value cannot be restored. + """ + if encrypted is None: + return None + + data = cls._to_bytes(encrypted) + if len(data) < cls.MIN_ENCRYPTED_LENGTH: + raise IntegrityCheckError( + f"Encrypted data is too short: {len(data)} bytes, " + f"expected at least {cls.MIN_ENCRYPTED_LENGTH}", + algorithm=algorithm, + ) + + cls._validate_key(data_key, algorithm) + cls._validate_hmac_key(hmac_key) + + # The HMAC covers the key id and everything after it. + body = data[cls.HMAC_TAG_LENGTH:] + expected = data[:cls.HMAC_TAG_LENGTH] + actual = hmac.new(cls._hmac_key(hmac_key), body, hashlib.sha256).digest() + if not hmac.compare_digest(expected, actual): + raise IntegrityCheckError( + "Integrity check failed: the value was modified, was never encrypted, " + "or was signed with a different HMAC key", + algorithm=algorithm, + ) + + payload = body[cls.KEY_ID_LENGTH:] + marker = cls._read_marker(payload) + # The recovered value is returned to the caller as a Python object, so + # there is no buffer here worth wiping. + plaintext = cls._unseal(payload, data_key, algorithm, marker) + return cls._convert_to_target_type(cls.deserialize_value(plaintext, marker), target_type) + + # ---- serialization ---- + + @classmethod + def serialize_value(cls, value: Any, marker: Optional[int] = None) -> bytes: + """Serialize a value to the bytes that get encrypted. + + :param marker: the marker to write; defaults to the one + :meth:`TypeMarker.from_object` picks for ``value``. + :raises EncryptionFailedError: if ``value`` cannot be written with + that marker. + """ + if marker is None: + marker = TypeMarker.from_object(value) + if not TypeMarker.is_known(marker): + raise EncryptionFailedError(f"Unsupported type marker: {marker!r}") + try: + return cls._serialize(value, marker) + except (TypeError, ValueError, AttributeError, ArithmeticError, struct.error): + # Mostly a value that does not fit an explicitly requested marker + # (or a GENERIC value whose __str__ fails). The caught message may + # quote the value, so it is not chained, and the error is raised + # below, outside the handler. ArithmeticError covers OverflowError + # and decimal.InvalidOperation. + pass + raise EncryptionFailedError( + f"Cannot write a value of type {type(value).__name__} as {TypeMarker.name_for(marker)}", + data_type=TypeMarker.name_for(marker)) + + @classmethod + def _serialize(cls, value: Any, marker: int) -> bytes: + if marker == TypeMarker.STRING and issubclass(type(value), str): + # Store the string's own text: str() of a (str, Enum) member is + # 'Color.RED', and a subclass may override __str__. The check is + # on type(), not isinstance(), because str.__str__ needs a real + # str and proxies can fake __class__. + return cls._utf8_bytes(str.__str__(value)) + if marker in (TypeMarker.STRING, TypeMarker.GENERIC): + return cls._utf8_bytes(str(value)) + if marker == TypeMarker.LOCAL_TIME: + # LOCAL_TIME is ISO text on the wire; TIME is the epoch-millis form. + if isinstance(value, time): + cls._require_naive(value, "LOCAL_TIME") + return cls._utf8_bytes(value.isoformat()) + return cls._utf8_bytes(str(value)) + if marker == TypeMarker.BYTE_ARRAY: + # bytes(7) would be seven zero bytes, so only bytes-like values. + if not isinstance(value, (bytes, bytearray, memoryview)): + raise TypeError("BYTE_ARRAY needs a bytes-like value") + return cls._to_bytes(value) + if marker == TypeMarker.INTEGER: + return struct.pack(">i", value) + if marker == TypeMarker.LONG: + # Every Python int but bool defaults to LONG, so an out-of-range + # one gets its own message rather than the generic one. + # operator.index accepts what INTEGER's struct packing accepts + # (int, bool, other integer types) and raises TypeError for a + # float or Decimal. + value = operator.index(value) + if not (-(2 ** 63) <= value <= 2 ** 63 - 1): + raise EncryptionFailedError( + "Integer value exceeds the signed 64-bit range", data_type="LONG" + ) + return struct.pack(">q", value) + if marker == TypeMarker.DOUBLE: + return struct.pack(">d", value) + if marker == TypeMarker.FLOAT: + return struct.pack(">f", value) + if marker == TypeMarker.BOOLEAN: + # Not truthiness: "false" must not be written as True. + if not isinstance(value, bool): + raise TypeError("BOOLEAN needs a bool") + return b"\x01" if value else b"\x00" + if marker == TypeMarker.BIG_DECIMAL: + # Plain (non-scientific) notation, so Decimal("1E+2") and + # Decimal("100") give the same bytes. The scale is kept: + # Decimal("1.0") is written as "1.0". + if not value.is_finite(): + raise EncryptionFailedError( + "Cannot encrypt a non-finite Decimal", data_type="BIG_DECIMAL") + return cls._utf8_bytes(format(value, "f")) + if marker in (TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP): + return struct.pack(">q", cls._to_millis(value, TypeMarker.name_for(marker) or "")) + if marker == TypeMarker.LOCAL_DATE: + # isoformat always writes a 4-digit year; strftime("%Y") does not + # on every platform. A datetime is cut to its own (wall-clock) + # date, as a local date has no offset to keep. + return cls._utf8_bytes(date(value.year, value.month, value.day).isoformat()) + if marker == TypeMarker.LOCAL_DATE_TIME: + if not isinstance(value, datetime): + raise EncryptionFailedError( + f"Cannot write a value of type {type(value).__name__} as LOCAL_DATE_TIME", + data_type="LOCAL_DATE_TIME") + cls._require_naive(value, "LOCAL_DATE_TIME") + return cls._utf8_bytes(value.isoformat()) + raise EncryptionFailedError( # pragma: no cover - serialize_value checks the marker first + f"Unsupported type marker: {marker!r}") + + @classmethod + def deserialize_value(cls, data: bytes, marker: int) -> Any: + """Turn decrypted bytes back into a Python value.""" + try: + if marker in (TypeMarker.STRING, TypeMarker.GENERIC, TypeMarker.LOCAL_TIME): + return cls._utf8(data) + if marker == TypeMarker.BYTE_ARRAY: + return bytes(data) + if marker == TypeMarker.INTEGER: + return struct.unpack(">i", cls._expect_length(data, 4, marker))[0] + if marker == TypeMarker.LONG: + return struct.unpack(">q", cls._expect_length(data, 8, marker))[0] + if marker == TypeMarker.DOUBLE: + return struct.unpack(">d", cls._expect_length(data, 8, marker))[0] + if marker == TypeMarker.FLOAT: + return struct.unpack(">f", cls._expect_length(data, 4, marker))[0] + if marker == TypeMarker.BOOLEAN: + return cls._expect_length(data, 1, marker)[0] != 0 + if marker == TypeMarker.BIG_DECIMAL: + return Decimal(cls._utf8(data)) + if marker == TypeMarker.DATE: + return cls._from_millis(struct.unpack(">q", cls._expect_length(data, 8, marker))[0]).date() + if marker in (TypeMarker.TIME, TypeMarker.TIMESTAMP): + return cls._from_millis(struct.unpack(">q", cls._expect_length(data, 8, marker))[0]) + if marker == TypeMarker.LOCAL_DATE: + return date.fromisoformat(cls._utf8(data)) + if marker == TypeMarker.LOCAL_DATE_TIME: + return cls._parse_local_datetime(cls._utf8(data)) + except (ValueError, struct.error, InvalidOperation, OverflowError): + # The text markers' parse errors quote the decrypted plaintext, so + # the error reports only the marker and is raised below, outside + # the handler (see the class docstring). + failed_marker = marker + else: + raise DecryptionError( + f"Unsupported type marker: {marker!r}", data_type=str(marker) + ) + raise TypeConversionError( + f"Failed to deserialize {TypeMarker.name_for(failed_marker) or failed_marker}", + data_type=TypeMarker.name_for(failed_marker), + ) + + # ---- AES-GCM ---- + + @classmethod + def _seal(cls, plaintext: BytesLike, marker: int, data_key: BytesLike, algorithm: str) -> bytes: + try: + iv = os.urandom(cls.GCM_IV_LENGTH) + # AESGCM appends the 16-byte tag to the ciphertext, giving the + # [ciphertext][GCM tag] tail the wire format expects. AESGCM keeps + # its own copy of the key, which wiping the caller's bytearray + # doesn't reach, so key wiping is best effort. + sealed = AESGCM(data_key).encrypt(iv, plaintext, None) + return bytes([marker]) + iv + sealed + except Exception as e: # pragma: no cover - cryptography rarely fails here + raise EncryptionFailedError( + f"Failed to encrypt value: {type(e).__name__}", + algorithm=algorithm, data_type=TypeMarker.name_for(marker), + ) from e + + @classmethod + def _unseal(cls, payload: bytes, data_key: BytesLike, algorithm: str, marker: int) -> bytes: + iv = payload[cls.TYPE_MARKER_LENGTH:cls.TYPE_MARKER_LENGTH + cls.GCM_IV_LENGTH] + sealed = payload[cls.TYPE_MARKER_LENGTH + cls.GCM_IV_LENGTH:] + try: + return AESGCM(data_key).decrypt(iv, sealed, None) + except InvalidTag as e: + # The HMAC has already been checked, so a GCM failure here means the + # data key is wrong rather than the data being corrupt. + raise DecryptionError( + "Failed to decrypt value: the authentication tag does not match this data key", + algorithm=algorithm, data_type=TypeMarker.name_for(marker), + ) from e + + # ---- helpers ---- + + @classmethod + def _convert_to_target_type(cls, value: Any, target_type: Optional[type]) -> Any: + if target_type is None or value is None or isinstance(value, target_type): + return value + source_name = type(value).__name__ + try: + if target_type is str: + return str(value) + if target_type is int: + return int(value) + if target_type is float: + return float(value) + if target_type is Decimal: + return Decimal(str(value)) + if target_type is bool: + return cls._truthy(value) + except (ValueError, TypeError, ArithmeticError): + # `value` is the recovered plaintext and int()/float()/Decimal() + # quote their input, so nothing is interpolated or chained, and the + # error is raised below, outside the handler (see the class + # docstring). ArithmeticError covers OverflowError (int of an + # infinite float or Decimal) and decimal.InvalidOperation. + pass + # Reached after a caught conversion failure, or when target_type + # matched no branch above. + raise TypeConversionError( + f"Cannot convert {source_name} to {target_type}", + data_type=str(target_type), + ) + + @classmethod + def _read_marker(cls, payload: bytes) -> int: + try: + return TypeMarker.from_value(payload[0]) + except ValueError as e: + raise DecryptionError(str(e)) from e + + @classmethod + def _validate_key(cls, data_key: BytesLike, algorithm: str) -> None: + expected = EncryptionAlgorithm.key_length(algorithm) + if not isinstance(data_key, (bytes, bytearray, memoryview)) or len(data_key) != expected: + got = len(data_key) if isinstance(data_key, (bytes, bytearray, memoryview)) else None + raise InvalidKeyError( + f"Data key must be {expected} bytes for {algorithm}, got {got!r}", + algorithm=algorithm, + ) + + @classmethod + def _validate_hmac_key(cls, hmac_key: BytesLike) -> None: + if not isinstance(hmac_key, (bytes, bytearray, memoryview)) or len(hmac_key) == 0: + raise InvalidKeyError("An HMAC key is required to protect encrypted values") + + @classmethod + def _validate_key_id(cls, key_id: int) -> None: + # Packed as an unsigned 32-bit integer. bool is excluded (it is an int subclass). + if isinstance(key_id, bool) or not isinstance(key_id, int) or not (0 <= key_id <= 0xFFFFFFFF): + raise EncryptionFailedError( + f"A valid key id is required to tag an encrypted value, got {key_id!r}" + ) + + @staticmethod + def _require_naive(value: Any, marker_name: str) -> None: + # A local date-time or time of day has no UTC offset on the wire, so an + # aware value would silently lose it. Aware datetimes are written as + # TIMESTAMP instead (see TypeMarker.from_object). + if isinstance(value, (datetime, time)) and value.utcoffset() is not None: + raise EncryptionFailedError( + f"Cannot write a timezone-aware value as {marker_name}", data_type=marker_name) + + @classmethod + def _expect_length(cls, data: bytes, length: int, marker: int) -> bytes: + if len(data) != length: + raise TypeConversionError( + f"Expected {length} bytes for {TypeMarker.name_for(marker)}, got {len(data)}", + data_type=TypeMarker.name_for(marker), + ) + return data + + @staticmethod + def _hmac_key(key: BytesLike) -> Union[bytes, bytearray]: + # hmac takes bytes or bytearray but not memoryview, so a memoryview key + # is copied to bytes (which cannot be wiped). A bytearray key is passed + # as is, so no immutable copy of it is made. + return key if isinstance(key, (bytes, bytearray)) else bytes(key) + + @staticmethod + def _to_bytes(value: BytesLike) -> bytes: + return value if isinstance(value, bytes) else bytes(value) + + @staticmethod + def _utf8(data: bytes) -> str: + return bytes(data).decode("utf-8") + + @classmethod + def _utf8_bytes(cls, string: str) -> bytes: + """Encode the string as UTF-8. A str with no UTF-8 form (lone + surrogates) is refused, and the error does not quote the offending + character, since that character is plaintext.""" + try: + return string.encode("utf-8") + except UnicodeEncodeError: + # UnicodeEncodeError holds the full plaintext in `.object`; raised + # below, outside the handler (see the class docstring). + pass + raise EncryptionFailedError( + "Cannot encrypt a string with no UTF-8 form", data_type="str" + ) + + @classmethod + def _to_millis(cls, value: Any, marker_name: str) -> int: + """Milliseconds since the Unix epoch, rounded half away from zero, + except at the very end of the datetime range, which keeps its last + millisecond rather than rounding past it. + + Integer arithmetic, so the result is exact for any datetime; a float + ``timestamp()`` loses microseconds far from the epoch. + """ + if isinstance(value, datetime): + dt = value if value.utcoffset() is not None else value.replace(tzinfo=timezone.utc) + elif isinstance(value, date): + dt = datetime(value.year, value.month, value.day, tzinfo=timezone.utc) + else: + raise TypeError(f"{marker_name} needs a date or datetime") + micros = (dt - _EPOCH) // _MICROSECOND + millis, remainder = divmod(abs(micros), 1000) + if remainder >= 500: + millis += 1 + millis = millis if micros >= 0 else -millis + if micros // 1000 == _MAX_MILLIS: + # Rounding up past the last representable millisecond (for example + # an aware datetime.max, a common "never" value) keeps that + # millisecond. + millis = _MAX_MILLIS + if not _MIN_MILLIS <= millis <= _MAX_MILLIS: + # A UTC offset put the instant outside what a datetime can hold, + # so it could not be read back. + raise EncryptionFailedError( + "In UTC, the value is outside the range a datetime can represent", data_type=marker_name) + return millis + + @classmethod + def _from_millis(cls, millis: int) -> datetime: + return _EPOCH + millis * _MILLISECOND + + @staticmethod + def _parse_local_datetime(text: str) -> datetime: + """Parse an ISO-8601 local date-time. + + This wrapper writes ``YYYY-MM-DDTHH:MM:SS``, with 6 fractional digits + when the microseconds aren't 0. It also accepts a time without seconds + (``...THH:MM``) and with 3, 6, or 9 fractional digits. + ``datetime.fromisoformat`` accepts the no-seconds, 3-digit, and + 6-digit forms, but on Python 3.10 (the support floor) it rejects 9 + digits, so the fraction is cut to microseconds, the finest unit + ``datetime`` can hold. Anything after the digits is kept as is. + """ + head, dot, rest = text.partition(".") + if dot: + digits = len(rest) - len(rest.lstrip("0123456789")) + if digits > 6: + text = f"{head}.{rest[:6]}{rest[digits:]}" + return datetime.fromisoformat(text) + + @staticmethod + def _truthy(value: Any) -> bool: + if isinstance(value, bool): + return value + return str(value).strip().lower() in ("t", "true", "y", "yes", "1") diff --git a/aws_advanced_python_wrapper/encryption/key_management_utility.py b/aws_advanced_python_wrapper/encryption/key_management_utility.py new file mode 100644 index 000000000..89017e1c2 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/key_management_utility.py @@ -0,0 +1,270 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING, Any, List, Optional, cast + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.buffers import wipe +from aws_advanced_python_wrapper.encryption.connection_source import \ + CallerConnectionSource +from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache +from aws_advanced_python_wrapper.encryption.key_manager import KeyManager +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.models import (KeyMetadata, + mask_arn, + mask_arns_in_text) +from aws_advanced_python_wrapper.encryption.sql_dialect import (SqlDialect, + execute, + fetch_rows) +from aws_advanced_python_wrapper.errors import KeyManagementError +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import WrapperProperties + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + +logger = Logger(__name__) + + +class KeyManagementUtility: + """Administrative operations for the kms_encryption plugin: create master + keys, turn encryption on or off for a column, and rotate data keys. + + Nothing here runs during normal query execution. Call it from a migration + or setup script on a plain psycopg / mysql-connector connection (or an + ``AwsWrapperConnection``) that you own:: + + import boto3 + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.key_management_utility import KeyManagementUtility + from aws_advanced_python_wrapper.encryption.key_manager import KeyManager + + config = EncryptionConfig.from_props( + {"encryption_kms_region": "us-east-1"}, require_allowed_master_keys=False) + # create_kms_client turns off botocore's own retries, which would + # otherwise multiply with the utility's. + kms = KeyManager.create_kms_client(boto3.Session(), config) + utility = KeyManagementUtility(conn, kms, config) + arn = utility.create_master_key("users.ssn encryption") + utility.initialize_encryption_for_column("users", "ssn", arn) + conn.commit() + + The connection is never closed, committed, or rolled back here. Each + operation's statements run inside your transaction, so a failed setup can + be rolled back as a unit, and nothing is stored until you commit. A KMS + master key created before a rollback is not deleted. + + Unlike the plugin, the utility works without + ``encryption_allowed_master_key_arns``. When the allow-list is configured, + it gates every data-key operation here too (not :meth:`create_master_key` + or :meth:`is_master_key_valid`). Add every master key a column uses to the + application's allow-list, or the plugin refuses that column. + + After a change here, running applications pick it up at their next + metadata refresh, or once their cached metadata expires if that comes + first (``encryption_metadata_cache_refresh_interval_sec``, + ``encryption_metadata_cache_expiration_sec``). + + This does not create the database-side HMAC-validation trigger, which is + required on every encrypted column. + """ + + ALIAS_PREFIX = "alias/python-kms-encryption-" + + def __init__(self, connection: Any, kms_client: Any, config: EncryptionConfig, + *, engine: Optional[str] = None): + """ + :param engine: ``"postgresql"`` or ``"mysql"``. Inferred from + ``connection`` when omitted. + """ + if connection is None or kms_client is None or config is None: + raise ValueError(Messages.get("KeyManagementUtility.MissingArgument")) + self._sql = SqlDialect.for_name(engine) if engine else SqlDialect.for_connection(connection) + self._connections = CallerConnectionSource(connection) + self._kms = kms_client + self._config = config + self._schema = config.metadata_schema # interpolated into every statement below + # The utility never decrypts a data key, so there is nothing to cache. + self._key_manager = KeyManager(kms_client, self._connections, self._sql, config, + DataKeyCache(1, 1.0, enabled=False)) + # Never started, so every lookup reads the database through the + # caller's connection and sees this transaction's own changes. + self._metadata = MetadataManager(self._connections, self._sql, config) + + def create_master_key(self, description: str, *, policy: Optional[str] = None, + create_alias: bool = True) -> str: + """Create a symmetric KMS master key and return its ARN. A failure to + create the alias is logged, not raised: the key works by ARN.""" + if description is None: + raise ValueError(Messages.get_formatted("KeyManagementUtility.RequiredArgument", "description")) + arn = self._key_manager.create_master_key(description, policy=policy) + if create_alias: + alias = f"{self.ALIAS_PREFIX}{int(time.time() * 1000)}" + try: + self._kms.create_alias(AliasName=alias, TargetKeyId=arn) + except Exception as e: + logger.warning("KeyManagementUtility.CreateAliasFailed", mask_arn(arn), mask_arns_in_text(str(e))) + logger.info("KeyManagementUtility.CreatedMasterKey", mask_arn(arn)) + return arn + + def initialize_encryption_for_column(self, table_name: str, column_name: str, master_key_arn: str, + algorithm: str = EncryptionAlgorithm.DEFAULT) -> int: + """Set up encryption for a column that is not encrypted yet. + + :return: the ``key_storage.id`` of the new data key. + :raises KeyManagementError: if the column is already encrypted or the + setup fails. + """ + self._require(table_name=table_name, column_name=column_name, master_key_arn=master_key_arn) + if self._metadata.is_column_encrypted(table_name, column_name): + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.AlreadyEncrypted", table_name, column_name), + operation="INITIALIZE_COLUMN") + return self.generate_and_store_data_key(table_name, column_name, master_key_arn, algorithm) + + def generate_and_store_data_key(self, table_name: str, column_name: str, master_key_arn: str, + algorithm: str = EncryptionAlgorithm.DEFAULT) -> int: + """Generate a data key for a column and record it, replacing any + configuration the column already has (an upsert, so a setup script can + be re-run). + + :return: the ``key_storage.id`` of the new data key. + """ + self._require(table_name=table_name, column_name=column_name, master_key_arn=master_key_arn) + algorithm = algorithm or EncryptionAlgorithm.DEFAULT + if not EncryptionAlgorithm.is_supported(algorithm): + raise EncryptionAlgorithm.unsupported(algorithm) + + key_storage_id = self._store_new_data_key(table_name, column_name, master_key_arn, algorithm) + sql = (f"INSERT INTO {self._schema}.encryption_metadata " + "(table_name, column_name, encryption_algorithm, key_id) VALUES (%s, %s, %s, %s) " + + self._sql.upsert_clause(("table_name", "column_name"), ("encryption_algorithm", "key_id"), + extra_assignments=("updated_at = CURRENT_TIMESTAMP",))) + self._run("STORE_ENCRYPTION_METADATA", sql, (table_name, column_name, algorithm, key_storage_id)) + logger.info("KeyManagementUtility.StoredDataKey", table_name, column_name, key_storage_id) + return key_storage_id + + def rotate_data_key(self, table_name: str, column_name: str, new_master_key_arn: Optional[str] = None) -> int: + """Give an encrypted column a new data key. New writes use it; values + written with the previous key stay readable, because each payload + records its ``key_storage.id`` and the old row is kept. + + Omitting ``new_master_key_arn`` keeps the master key recorded in + ``key_storage``. That is only allowed with an allow-list configured to + check it against, since otherwise a row repointed at another key would + be trusted. + + :return: the ``key_storage.id`` of the new data key. + """ + self._require(table_name=table_name, column_name=column_name) + if new_master_key_arn is None and not self._config.restricts_master_keys: + raise ValueError(Messages.get_formatted( + "KeyManagementUtility.RotateNeedsMasterKey", WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)) + + current = self._metadata.column_config(table_name, column_name) + if current is None: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NotEncrypted", table_name, column_name), + operation="ROTATE_DATA_KEY") + master_key_arn = new_master_key_arn or (current.key_metadata.master_key_arn if current.key_metadata else None) + if not master_key_arn: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NoCurrentMasterKey", table_name, column_name), + operation="ROTATE_DATA_KEY") + + key_storage_id = self._store_new_data_key(table_name, column_name, master_key_arn, current.algorithm) + sql = (f"UPDATE {self._schema}.encryption_metadata SET key_id = %s, updated_at = CURRENT_TIMESTAMP " + f"WHERE table_name {self._sql.equals} %s AND column_name {self._sql.equals} %s") + if self._run("UPDATE_ENCRYPTION_METADATA", sql, (key_storage_id, table_name, column_name)) == 0: + raise KeyManagementError( + Messages.get_formatted("KeyManagementUtility.NotEncrypted", table_name, column_name), + operation="ROTATE_DATA_KEY") + logger.info("KeyManagementUtility.RotatedDataKey", table_name, column_name, current.key_id, key_storage_id) + return key_storage_id + + def remove_encryption_for_column(self, table_name: str, column_name: str) -> bool: + """Stop encrypting a column by deleting its ``encryption_metadata`` + row. The key stays in ``key_storage`` so values already written can + still be decrypted. + + :return: ``True`` when a configuration row was removed. + """ + self._require(table_name=table_name, column_name=column_name) + sql = (f"DELETE FROM {self._schema}.encryption_metadata " + f"WHERE table_name {self._sql.equals} %s AND column_name {self._sql.equals} %s") + removed = self._run("DELETE_ENCRYPTION_METADATA", sql, (table_name, column_name)) > 0 + if not removed: + logger.warning("KeyManagementUtility.NothingToRemove", table_name, column_name) + return removed + + def columns_using_key(self, key_storage_id: int) -> List[str]: + """The ``"table.column"`` names that use a ``key_storage.id``, to see + what rotating or retiring that key would affect.""" + sql = (f"SELECT table_name, column_name FROM {self._schema}.encryption_metadata " + f"WHERE key_id {self._sql.equals} %s ORDER BY table_name, column_name") + try: + with self._connections.connection() as conn: + rows = fetch_rows(conn, sql, (key_storage_id,)) + except Exception as e: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", + "SELECT_COLUMNS_USING_KEY", e), + operation="SELECT_COLUMNS_USING_KEY") from e + return [f"{r['table_name']}.{r['column_name']}" for r in rows] + + def is_master_key_valid(self, master_key_arn: str) -> bool: + """``True`` when the master key exists, is enabled, and can encrypt + and decrypt. ``False`` also covers "could not check"; see + :meth:`KeyManager.is_master_key_valid`.""" + self._require(master_key_arn=master_key_arn) + return self._key_manager.is_master_key_valid(master_key_arn) + + # ---- internals ---- + + def _store_new_data_key(self, table_name: str, column_name: str, master_key_arn: str, + algorithm: str) -> int: + """Generate a data key, store it, and return its ``key_storage.id``.""" + generated = self._key_manager.generate_data_key(master_key_arn, algorithm) + try: + # Nothing here encrypts with the plaintext key; only its + # KMS-encrypted form is stored. + stored = self._key_manager.store_key_metadata(KeyMetadata( + key_name=f"key-{table_name}-{column_name}-{int(time.time() * 1000)}", + master_key_arn=master_key_arn, + encrypted_data_key=generated.encrypted_data_key, + hmac_key=generated.hmac_key, + key_spec=generated.key_spec, + )) + return cast("int", stored.id) + finally: + wipe(generated.plaintext) + + def _run(self, operation: str, sql: str, params: Any) -> int: + try: + with self._connections.connection() as conn: + return execute(conn, sql, params) + except Exception as e: + raise KeyManagementError(Messages.get_formatted("KeyManagementUtility.StatementFailed", operation, e), + operation=operation) from e + + @staticmethod + def _require(**arguments: Any) -> None: + for name, value in arguments.items(): + if value is None or (isinstance(value, str) and not value.strip()): + raise ValueError(Messages.get_formatted("KeyManagementUtility.RequiredArgument", name)) diff --git a/aws_advanced_python_wrapper/encryption/key_manager.py b/aws_advanced_python_wrapper/encryption/key_manager.py new file mode 100644 index 000000000..6c6934d0c --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/key_manager.py @@ -0,0 +1,445 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import base64 +import hashlib +import logging +import os +import random +import threading +import time +import uuid +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, TypeVar + +from botocore.config import Config +from botocore.exceptions import ClientError +from botocore.exceptions import ConnectionError as BotoConnectionError +from botocore.exceptions import (ConnectTimeoutError, EndpointConnectionError, + HTTPClientError) + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.buffers import wipe +from aws_advanced_python_wrapper.encryption.models import (DEFAULT_KEY_SPEC, + KeyMetadata, + mask_arn, + mask_arns_in_text) +from aws_advanced_python_wrapper.encryption.sql_dialect import (execute, + fetch_rows) +from aws_advanced_python_wrapper.errors import (InvalidKeyMetadataError, + KeyManagementError, + UnauthorizedMasterKeyError) +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import WrapperProperties + +if TYPE_CHECKING: + from boto3 import Session + + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.connection_source import \ + ConnectionSource + from aws_advanced_python_wrapper.encryption.data_key_cache import \ + DataKeyCache + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + +logger = Logger(__name__) + +T = TypeVar("T") + + +class _NoKmsPlaintext(logging.Filter): + """Drops botocore's DEBUG records of a response body that holds the + bytes ``"Plaintext"``, as every KMS response with a plaintext data key + does. Another service's response body that holds them is dropped too.""" + + def filter(self, record: logging.LogRecord) -> bool: + args = record.args if isinstance(record.args, tuple) else () + return not any(isinstance(a, (bytes, bytearray)) and b'"Plaintext"' in a for a in args) + + +class _NoKmsRequestCredentials(logging.Filter): + """Drops botocore's DEBUG records of each signed KMS request, which + carry its access key id, session token and signature. ``TrentService.`` is + the target prefix of every KMS operation, so other services' signed + requests keep these records. The separate signature record is dropped for + every service: it doesn't name its service, and other services' sent + requests keep their signatures in their other request records.""" + + def filter(self, record: logging.LogRecord) -> bool: + try: + message = record.getMessage() + except Exception: # noqa: BLE001 - a filter must never raise; a record that can't be formatted passes unchanged + return True + if message.startswith("Signature:\n"): + return False + if "TrentService." not in message: + return True + lowered = message.lower() + return "authorization" not in lowered and "x-amz-security-token" not in lowered + + +# A logger's filters don't see its children's records, so each filter goes on +# the logger that emits the records. They are installed once per process, so a +# filter that was removed on purpose stays removed. +_FILTER_LOCK = threading.Lock() +_filters_installed = False + + +def _install_botocore_filters() -> None: + global _filters_installed + with _FILTER_LOCK: + if _filters_installed: + return + logging.getLogger("botocore.parsers").addFilter(_NoKmsPlaintext()) + request_filter = _NoKmsRequestCredentials() + logging.getLogger("botocore.endpoint").addFilter(request_filter) + logging.getLogger("botocore.auth").addFilter(request_filter) + _filters_installed = True + + +@dataclass(frozen=True, eq=False) +class GeneratedDataKey: + """A data key fresh from KMS. ``plaintext`` is a ``bytearray`` so the + caller can wipe it once used; ``repr`` never shows key material.""" + + plaintext: bytearray = field(repr=False) + encrypted_data_key: str = field(repr=False) + hmac_key: bytes = field(repr=False) + key_spec: str = DEFAULT_KEY_SPEC + + +class KeyManager: + """Owns the data keys: generates them through KMS, stores them in + ``key_storage``, and decrypts them again, caching the plaintext keys. + + The data-key operations (``GenerateDataKey`` and ``Decrypt``) are gated on + ``encryption_allowed_master_key_arns`` before KMS is contacted, including + on a data-key cache hit. :meth:`create_master_key` and + :meth:`is_master_key_valid` are not gated: they use no data key. Plaintext + data keys never reach the database. + """ + + HMAC_KEY_LENGTH = 32 + MASTER_KEY_SPEC = "SYMMETRIC_DEFAULT" + KEY_USAGE = "ENCRYPT_DECRYPT" + MAX_BACKOFF_SEC = 20.0 + JITTER_RATIO = 0.25 + # botocore defaults both to 60 s. A KMS call normally takes milliseconds, + # so an unreachable or hung endpoint fails an attempt in seconds rather + # than a minute. + CONNECT_TIMEOUT_SEC = 5.0 + READ_TIMEOUT_SEC = 10.0 + _CACHE_KEY_PREFIX = "datakey_" + + # KMS error codes worth retrying, in addition to any 5xx or 429 response. + RETRYABLE_ERROR_CODES = frozenset({ + "ThrottlingException", + "LimitExceededException", + "KMSInternalException", + "KeyUnavailableException", + "DependencyTimeoutException", + "RequestTimeout", + "ServiceUnavailable", + "InternalFailure", + }) + + # Errors that mean KMS did not act on the request, so even a call that is + # not idempotent (CreateKey) can be retried without creating a duplicate. + NOT_PROCESSED_ERROR_CODES = frozenset({"ThrottlingException"}) + + def __init__(self, kms_client: Any, connection_source: ConnectionSource, sql_dialect: SqlDialect, + config: EncryptionConfig, data_key_cache: DataKeyCache, + *, sleep: Callable[[float], None] = time.sleep): + self._kms = kms_client + self._connections = connection_source + self._sql = sql_dialect + self._config = config + self._cache = data_key_cache + self._sleep = sleep + + @staticmethod + def create_kms_client(session: Session, config: EncryptionConfig) -> Any: + """Build a KMS client for ``config``. + + botocore's own retries are turned off because :class:`KeyManager` + retries itself. botocore cannot be given the configured backoff base + (``encryption_key_management_retry_backoff_base_sec``), and leaving + both on would multiply the attempt count. Connect and read timeouts + are short, so an unreachable KMS endpoint fails in seconds rather than + minutes. + + The first call in a process also filters botocore's DEBUG records of + KMS calls, which would otherwise carry the data keys in response + bodies and the access key id, session token and signature of each + request. It changes no logger's level, handlers or propagation, and no + formatter. The filters it installs also drop, for every AWS service, + botocore's separate record of each request's signature and any + response body that holds the bytes ``"Plaintext"``. + """ + _install_botocore_filters() + client_config = Config(region_name=config.kms_region, retries={"total_max_attempts": 1}, + connect_timeout=KeyManager.CONNECT_TIMEOUT_SEC, + read_timeout=KeyManager.READ_TIMEOUT_SEC) + if config.kms_endpoint: + return session.client("kms", endpoint_url=config.kms_endpoint, config=client_config) + return session.client("kms", config=client_config) + + # ---- data keys ---- + + def decrypt_data_key(self, encrypted_data_key: Optional[str], master_key_arn: Optional[str]) -> bytearray: + """Return the plaintext of a stored data key, from the cache when + possible. The caller owns the returned buffer and should wipe it. + + :raises UnauthorizedMasterKeyError: the master key is not allowed; + KMS is not called. + :raises InvalidKeyMetadataError: there is no usable encrypted data key. + :raises KeyManagementError: KMS rejected the request. + """ + self._authorize(master_key_arn) + if encrypted_data_key is None or not encrypted_data_key.strip(): + raise InvalidKeyMetadataError( + Messages.get("KeyManager.MissingEncryptedDataKey"), operation="DECRYPT_DATA_KEY") + + cache_key = self.data_key_cache_key(encrypted_data_key) + cached = self._cache.get(cache_key) + if cached is not None: + return cached + + try: + ciphertext = base64.b64decode("".join(encrypted_data_key.split()), validate=True) + except ValueError: + # Catches binascii.Error (bad base64) and the plain ValueError + # b64decode raises for a non-ASCII string, as in a hand-edited row. + ciphertext = None + if not ciphertext: + raise InvalidKeyMetadataError( + Messages.get("KeyManager.MalformedEncryptedDataKey"), operation="DECRYPT_DATA_KEY") + + # KeyId is passed as defense in depth: a data key wrapped under a + # different master key than its row names fails inside KMS too. With + # no ARN (only possible without an allow-list), KMS reads the key from + # the ciphertext. + request: Dict[str, Any] = {"CiphertextBlob": ciphertext} + if master_key_arn: + request["KeyId"] = master_key_arn + response = self._call_kms("DECRYPT_DATA_KEY", lambda: self._kms.decrypt(**request)) + plaintext = bytearray(response["Plaintext"]) + self._cache.put(cache_key, plaintext) + return plaintext + + def generate_data_key(self, master_key_arn: str, + algorithm: str = EncryptionAlgorithm.DEFAULT) -> GeneratedDataKey: + """Ask KMS for a new data key sized for ``algorithm``, plus a random + HMAC key. + + :raises UnauthorizedMasterKeyError: the master key is not allowed. + :raises KeyManagementError: KMS rejected the request. + """ + self._authorize(master_key_arn) + key_spec = EncryptionAlgorithm.data_key_spec(algorithm) + response = self._call_kms( + "GENERATE_DATA_KEY", lambda: self._kms.generate_data_key(KeyId=master_key_arn, KeySpec=key_spec)) + plaintext = bytearray(response["Plaintext"]) + if len(plaintext) != EncryptionAlgorithm.key_length(algorithm): + # Catch a mis-sized key now, at setup, rather than on the first + # write to the column. (Some KMS emulators ignore KeySpec.) + length = len(plaintext) + wipe(plaintext) + raise KeyManagementError( + Messages.get_formatted("KeyManager.WrongDataKeyLength", length, key_spec, algorithm), + operation="GENERATE_DATA_KEY") + return GeneratedDataKey( + plaintext=plaintext, + encrypted_data_key=base64.b64encode(response["CiphertextBlob"]).decode("ascii"), + hmac_key=os.urandom(self.HMAC_KEY_LENGTH), + key_spec=key_spec, + ) + + @classmethod + def data_key_cache_key(cls, encrypted_data_key: str) -> str: + """Hash the encrypted data key so it never appears as a cache key.""" + digest = hashlib.sha256(encrypted_data_key.encode("utf-8")).digest() + return cls._CACHE_KEY_PREFIX + base64.b64encode(digest).decode("ascii") + + # ---- master keys ---- + + def create_master_key(self, description: str, *, policy: Optional[str] = None) -> str: + """Create a symmetric KMS key and return its ARN. Not gated on the + allow-list: the new key cannot be listed before it exists. + + Only failures that mean KMS did not act are retried: throttling, and + a connection that was never made. After a timeout or a server error + the key may already exist, and a retry would create a second one. + """ + request = {"Description": description, "KeyUsage": self.KEY_USAGE, "KeySpec": self.MASTER_KEY_SPEC} + if policy and policy.strip(): + request["Policy"] = policy + response = self._call_kms("CREATE_MASTER_KEY", lambda: self._kms.create_key(**request), + retryable=self._is_not_processed) + return response["KeyMetadata"]["Arn"] + + def is_master_key_valid(self, master_key_arn: str) -> bool: + """``True`` when the key exists, is enabled, and can encrypt/decrypt. + + ``False`` also covers "could not check" (no ``kms:DescribeKey`` + permission, KMS unreachable); the reason is logged as a warning. + """ + try: + metadata = self._call_kms( + "DESCRIBE_MASTER_KEY", lambda: self._kms.describe_key(KeyId=master_key_arn))["KeyMetadata"] + except KeyManagementError as e: + logger.warning("KeyManager.MasterKeyValidationFailed", mask_arn(master_key_arn), e) + return False + return (bool(metadata.get("Enabled")) and metadata.get("KeyState") == "Enabled" + and metadata.get("KeyUsage") == self.KEY_USAGE) + + # ---- key_storage ---- + + def store_key_metadata(self, key_metadata: KeyMetadata) -> KeyMetadata: + """Insert a ``key_storage`` row and return it with ``id`` (and a + generated ``key_id`` UUID, if none was given) filled in. + + Timestamps come from the database's ``CURRENT_TIMESTAMP`` defaults, so + the stored values follow the database's own time zone handling. + """ + if not key_metadata.is_usable: + raise InvalidKeyMetadataError( + Messages.get("KeyManager.RefusingUnusableKeyMetadata"), operation="STORE_KEY_METADATA") + + to_store = key_metadata if key_metadata.key_id else replace(key_metadata, key_id=str(uuid.uuid4())) + sql = (f"INSERT INTO {self._config.metadata_schema}.key_storage " + "(key_id, name, master_key_arn, encrypted_data_key, hmac_key, key_spec) " + "VALUES (%s, %s, %s, %s, %s, %s)") + params = (to_store.key_id, to_store.key_name, to_store.master_key_arn, + to_store.encrypted_data_key, to_store.hmac_key, to_store.key_spec) + + failure: Optional[str] = None + try: + with self._connections.connection() as conn: + new_id = self._sql.insert_returning_id(conn, sql, params) + except Exception as e: + # The bound HMAC key is a secret, and some driver errors quote the + # interpolated statement. Keep only the exception type and the + # driver's error codes, and raise outside this block so the driver + # error is not even chained as __context__. + failure = self._describe_failure(e) + if failure is not None: + raise KeyManagementError( + Messages.get_formatted("KeyManager.StoreKeyMetadataFailed", failure), operation="STORE_KEY_METADATA") + return replace(to_store, id=new_id) + + def key_metadata_by_id(self, key_storage_id: int) -> Optional[KeyMetadata]: + """Read one ``key_storage`` row by its integer ``id``.""" + sql = ("SELECT id, key_id, name, master_key_arn, encrypted_data_key, hmac_key, key_spec, " + f"created_at, last_used_at FROM {self._config.metadata_schema}.key_storage WHERE id {self._sql.equals} %s") + try: + with self._connections.connection() as conn: + rows = fetch_rows(conn, sql, (key_storage_id,)) + except Exception as e: + raise KeyManagementError( + Messages.get_formatted("KeyManager.ReadKeyMetadataFailed", e), + operation="GET_KEY_METADATA") from e + return KeyMetadata.from_row(rows[0]) if rows else None + + def touch_key(self, key_uuid: str) -> None: + """Stamp ``last_used_at``. Bookkeeping only: failures are logged.""" + sql = (f"UPDATE {self._config.metadata_schema}.key_storage SET last_used_at = CURRENT_TIMESTAMP " + f"WHERE key_id {self._sql.equals} %s") + try: + with self._connections.connection() as conn: + execute(conn, sql, (key_uuid,)) + except Exception as e: + logger.debug("KeyManager.TouchKeyFailed", key_uuid, e) + + # ---- internals ---- + + def _authorize(self, master_key_arn: Optional[str]) -> None: + if not self._config.is_master_key_allowed(master_key_arn): + raise UnauthorizedMasterKeyError( + Messages.get_formatted("KeyManager.UnauthorizedMasterKey", mask_arn(master_key_arn), + WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name), + operation="AUTHORIZE_MASTER_KEY") + + @staticmethod + def _describe_failure(error: Exception) -> str: + """The exception type plus any SQLSTATE / errno the driver reports. + Neither carries statement text, unlike the error message.""" + details = [type(error).__name__] + for attribute in ("sqlstate", "errno"): + value = getattr(error, attribute, None) + if isinstance(value, (str, int)) and not isinstance(value, bool): + details.append(f"{attribute} {value}") + return ", ".join(details) + + def _call_kms(self, operation: str, call: Callable[[], T], + retryable: Optional[Callable[[Exception], bool]] = None) -> T: + """Run a KMS call, retrying throttling and transient failures with + exponential backoff and jitter. ``retryable`` decides which failures + are retried; it defaults to :meth:`_is_retryable`.""" + is_retryable = retryable or self._is_retryable + max_retries = self._config.key_management_max_retries + attempt = 0 + while True: + try: + return call() + except Exception as e: + # KMS's error text can name the master key and the caller's + # role session. The error, kept as __cause__, keeps that text. + if attempt >= max_retries or not is_retryable(e): + raise KeyManagementError( + Messages.get_formatted("KeyManager.KmsCallFailed", operation, attempt + 1, + mask_arns_in_text(str(e))), + operation=operation) from e + delay = self._backoff_sec(attempt) + logger.debug("KeyManager.Retrying", operation, attempt + 1, max_retries + 1, delay, + mask_arns_in_text(str(e))) + self._sleep(delay) + attempt += 1 + + @classmethod + def _is_retryable(cls, error: Exception) -> bool: + if isinstance(error, (BotoConnectionError, HTTPClientError)): + return True + if isinstance(error, ClientError): + status = error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") + if status is not None and (status >= 500 or status == 429): + return True + return error.response.get("Error", {}).get("Code") in cls.RETRYABLE_ERROR_CODES + return False + + @classmethod + def _is_not_processed(cls, error: Exception) -> bool: + # EndpointConnectionError and ConnectTimeoutError are raised before the + # request is sent. + if isinstance(error, (EndpointConnectionError, ConnectTimeoutError)): + return True + if isinstance(error, ClientError): + status = error.response.get("ResponseMetadata", {}).get("HTTPStatusCode") + code = error.response.get("Error", {}).get("Code") + return status == 429 or code in cls.NOT_PROCESSED_ERROR_CODES + return False + + def _backoff_sec(self, attempt: int) -> float: + """``base * 2**attempt`` +/- 25%, at least ``base``, at most 20 s. + + The cap wins over the floor when the configured base exceeds it. + """ + base = self._config.key_management_retry_backoff_base_sec + exponential = base * (2 ** attempt) + jitter = exponential * self.JITTER_RATIO * random.uniform(-1.0, 1.0) + return min(max(exponential + jitter, base), self.MAX_BACKOFF_SEC) diff --git a/aws_advanced_python_wrapper/encryption/metadata_manager.py b/aws_advanced_python_wrapper/encryption/metadata_manager.py new file mode 100644 index 000000000..1b2934988 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -0,0 +1,302 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import time +import weakref +from threading import Event, Lock, Thread, current_thread +from types import MappingProxyType +from typing import (TYPE_CHECKING, Any, Dict, List, Mapping, NamedTuple, + Optional, Sequence, Tuple) + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata) +from aws_advanced_python_wrapper.encryption.sql_dialect import fetch_rows +from aws_advanced_python_wrapper.errors import MetadataError +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.config import EncryptionConfig + from aws_advanced_python_wrapper.encryption.connection_source import \ + ConnectionSource + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + +logger = Logger(__name__) + +_KS_PREFIX = "ks_" + + +class _Snapshot(NamedTuple): + columns: Mapping[Tuple[str, str], ColumnEncryptionConfig] + by_table: Mapping[str, Tuple[ColumnEncryptionConfig, ...]] + loaded_at: float # time.monotonic() + + +class MetadataManager: + """Reads ``encryption_metadata`` (joined to ``key_storage``) and caches + which columns are encrypted. + + The cache is one immutable snapshot of the whole table, replaced + atomically on each refresh, so a lookup never sees a half-loaded state. It + is loaded by :meth:`start`, refreshed on a background thread every + ``encryption_metadata_cache_refresh_interval_sec``, and answers lookups + only while younger than ``encryption_metadata_cache_expiration_sec``. + The first lookup after expiry reloads it, whether or not the background + refresh is on. Before :meth:`start`, after :meth:`close`, or with the cache + disabled, each lookup queries the database. + + Call :meth:`close` when done. The refresh thread holds the manager only + weakly, so a manager dropped without ``close`` still stops its thread once + it is garbage-collected. + + The wrapper's shared storage service is not used: its entries are not + checked for expiry on read, and it caches per key rather than one + consistent snapshot. + """ + + SHUTDOWN_TIMEOUT_SEC = 5.0 + + def __init__(self, connection_source: ConnectionSource, sql_dialect: SqlDialect, config: EncryptionConfig): + self._connections = connection_source + self._sql = sql_dialect + self._config = config + self._snapshot: Optional[_Snapshot] = None + self._started = False + # Guards _started, _snapshot publication and the thread handle against + # close(). Never held across a database call. + self._lifecycle_lock = Lock() + # Serializes refreshes, so an older load cannot overwrite a newer one. + self._refresh_lock = Lock() + self._stop = Event() + self._refresh_thread: Optional[Thread] = None + # Holds the refresh thread for the finalizer, which must not refer to + # self, or the manager would never be collected. + self._thread_holder: List[Optional[Thread]] = [None] + weakref.finalize(self, MetadataManager._finalize, self._stop, self._thread_holder) + + # ---- lifecycle ---- + + def start(self) -> None: + """Load the cache and start the background refresh, as configured. + + :raises MetadataError: if the initial load fails. + """ + with self._lifecycle_lock: + if self._stop.is_set(): + return + self._started = True + if self._config.metadata_cache_enabled: + self.refresh() + if not self._config.background_refresh_enabled: + return + with self._lifecycle_lock: + if self._refresh_thread is None and not self._stop.is_set(): + self._refresh_thread = Thread( + target=MetadataManager._refresh_loop, + args=(weakref.ref(self), self._stop, self._config.metadata_cache_refresh_interval_sec), + name="kms-encryption-metadata-refresh", daemon=True) + self._thread_holder[0] = self._refresh_thread + self._refresh_thread.start() + + def close(self) -> None: + """Stop the background refresh and drop the cache. A refresh still + running is discarded when it finishes. Idempotent. + + Call it from ordinary code, not from a finalizer or ``__del__``: a + garbage collection on the refresh thread can run inside its wait, where + stopping the thread would deadlock. + """ + with self._lifecycle_lock: + self._stop.set() + thread, self._refresh_thread = self._refresh_thread, None + self._snapshot = None + # Joining the current thread raises; close() can run on the refresh + # thread if a caller releases the manager from inside a refresh. + if thread is not None and thread is not current_thread(): + thread.join(self.SHUTDOWN_TIMEOUT_SEC) + + def refresh(self) -> int: + """Reload every column configuration and replace the cache. After + :meth:`close` the result is not cached. + + :return: the number of encrypted columns. + :raises MetadataError: if the load fails; the previous snapshot is kept. + """ + with self._refresh_lock: + return self._load_snapshot() + + def load_metadata(self) -> Dict[Tuple[str, str], ColumnEncryptionConfig]: + """Read every column configuration from the database, bypassing the + cache. Keyed by ``(table_name, column_name)``.""" + return self._load_all() + + # ---- lookups ---- + + def is_column_encrypted(self, table_name: Optional[str], column_name: Optional[str]) -> bool: + if table_name is None or column_name is None: + return False + return self.column_config(table_name, column_name) is not None + + def column_config(self, table_name: Optional[str], column_name: Optional[str]) -> Optional[ColumnEncryptionConfig]: + """The column's configuration, or ``None`` when it is not encrypted. + + A configured column whose ``key_storage`` row is missing is still + returned, with ``key_metadata=None``, so the caller fails closed. + """ + if table_name is None or column_name is None: + return None + snapshot = self._usable_snapshot(table_name, column_name) + if snapshot is not None: + return snapshot.columns.get((table_name, column_name)) + rows = self._query( + f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s AND em.column_name {self._sql.equals} %s", + (table_name, column_name), table_name=table_name, column_name=column_name) + return self._to_column_config(rows[0]) if rows else None + + def table_configs(self, table_name: Optional[str]) -> Sequence[ColumnEncryptionConfig]: + """Every encrypted column of one table; empty when there are none.""" + if table_name is None: + return () + snapshot = self._usable_snapshot(table_name) + if snapshot is not None: + return snapshot.by_table.get(table_name, ()) + rows = self._query(f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s", + (table_name,), table_name=table_name) + return tuple(self._to_column_config(row) for row in rows) + + @property + def cache_size(self) -> int: + snapshot = self._snapshot + return 0 if snapshot is None else len(snapshot.columns) + + @property + def is_cache_loaded(self) -> bool: + return self._snapshot is not None + + # ---- internals ---- + + def _usable_snapshot(self, table_name: Optional[str] = None, + column_name: Optional[str] = None) -> Optional[_Snapshot]: + if not self._config.metadata_cache_enabled: + return None + snapshot = self._fresh(self._snapshot) + if snapshot is None and self._started and not self._stop.is_set(): + # An expired snapshot is reloaded here, whether or not the + # background refresh is on, so a statement reads the tables once + # instead of at every lookup. Lookups that find it expired at the + # same time wait for one reload; if that reload fails, each of them + # then tries its own, one at a time. + with self._refresh_lock: + if not self._stop.is_set() and self._fresh(self._snapshot) is None: + self._load_snapshot(table_name=table_name, column_name=column_name) + snapshot = self._fresh(self._snapshot) + return snapshot + + def _load_snapshot(self, *, table_name: Optional[str] = None, column_name: Optional[str] = None) -> int: + # Callers hold _refresh_lock. Stamped before the query, so expiry + # counts from when the data was read rather than when the query + # returned. + loaded_at = time.monotonic() + columns = self._load_all(table_name=table_name, column_name=column_name) + by_table: Dict[str, List[ColumnEncryptionConfig]] = {} + for config in columns.values(): + by_table.setdefault(config.table_name, []).append(config) + snapshot = _Snapshot( + MappingProxyType(dict(columns)), + MappingProxyType({t: tuple(c) for t, c in by_table.items()}), + loaded_at) + with self._lifecycle_lock: + if not self._stop.is_set(): + self._snapshot = snapshot + logger.debug("MetadataManager.Refreshed", len(columns)) + return len(columns) + + def _load_all(self, *, table_name: Optional[str] = None, + column_name: Optional[str] = None) -> Dict[Tuple[str, str], ColumnEncryptionConfig]: + # table_name / column_name only label a failure: the lookup that + # triggered a reload. + rows = self._query(f"{self._joined_sql()} ORDER BY em.table_name, em.column_name", (), + table_name=table_name, column_name=column_name) + configs = (self._to_column_config(row) for row in rows) + return {(c.table_name, c.column_name): c for c in configs} + + def _fresh(self, snapshot: Optional[_Snapshot]) -> Optional[_Snapshot]: + if snapshot is None or time.monotonic() - snapshot.loaded_at >= self._config.metadata_cache_expiration_sec: + return None + return snapshot + + def _query(self, sql: str, params: Sequence[Any], *, table_name: Optional[str] = None, + column_name: Optional[str] = None) -> List[Dict[str, Any]]: + try: + with self._connections.connection() as conn: + return fetch_rows(conn, sql, params) + except Exception as e: + raise MetadataError(Messages.get_formatted("MetadataManager.LoadFailed", e), + table_name=table_name, column_name=column_name) from e + + def _joined_sql(self) -> str: + # A LEFT join, so a column whose key_storage row is missing still reads + # as encrypted (with no key) and a write to it fails instead of storing + # plaintext. An inner join would make it look like an ordinary column. + # em.key_id is the integer FK to ks.id; ks.key_id is the key's UUID. + schema = self._config.metadata_schema + p = _KS_PREFIX + return ("SELECT em.table_name, em.column_name, em.encryption_algorithm, em.key_id, " + "em.created_at, em.updated_at, " + f"ks.id AS {p}id, ks.key_id AS {p}key_id, ks.name AS {p}name, " + f"ks.master_key_arn AS {p}master_key_arn, ks.encrypted_data_key AS {p}encrypted_data_key, " + f"ks.hmac_key AS {p}hmac_key, ks.key_spec AS {p}key_spec, " + f"ks.created_at AS {p}created_at, ks.last_used_at AS {p}last_used_at " + f"FROM {schema}.encryption_metadata em " + f"LEFT JOIN {schema}.key_storage ks ON em.key_id {self._sql.equals} ks.id") + + @staticmethod + def _to_column_config(row: Mapping[str, Any]) -> ColumnEncryptionConfig: + key_metadata = None if row.get(f"{_KS_PREFIX}id") is None else KeyMetadata.from_row(row, _KS_PREFIX) + return ColumnEncryptionConfig( + table_name=row["table_name"], + column_name=row["column_name"], + algorithm=row.get("encryption_algorithm") or EncryptionAlgorithm.DEFAULT, + key_id=None if row.get("key_id") is None else int(row["key_id"]), + key_metadata=key_metadata, + created_at=row.get("created_at"), + updated_at=row.get("updated_at"), + ) + + @staticmethod + def _finalize(stop: Event, thread_holder: List[Optional[Thread]]) -> None: + # Runs when an unclosed manager is collected. The collection can happen + # on the refresh thread itself, inside Event.wait while it holds the + # event's lock, where stop.set() would deadlock. That thread exits on + # its own anyway: it finds the manager gone as soon as wait returns. + if thread_holder[0] is not current_thread(): + stop.set() + + @staticmethod + def _refresh_loop(manager_ref: weakref.ref[MetadataManager], stop: Event, interval_sec: float) -> None: + # Holds the manager only weakly between runs, so an unclosed manager + # can still be collected. + while not stop.wait(interval_sec): + manager = manager_ref() + if manager is None: + return + try: + manager.refresh() + except Exception as e: + logger.warning("MetadataManager.RefreshFailed", e) + del manager diff --git a/aws_advanced_python_wrapper/encryption/models.py b/aws_advanced_python_wrapper/encryption/models.py new file mode 100644 index 000000000..f33d9a1fa --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/models.py @@ -0,0 +1,158 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Value objects for rows of the ``key_storage`` and ``encryption_metadata`` +tables. Their ``repr`` never shows key material, so they are safe to log.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Mapping, Optional, cast + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm + +if TYPE_CHECKING: + from datetime import datetime + +REDACTED = "[REDACTED]" +DEFAULT_KEY_SPEC = "AES_256" + +# An ARN as AWS quotes it in an error message, in any partition. It must name +# an account, so text that is already masked doesn't match. Punctuation that +# ends a sentence or a list is left out of the match; inside the ARN (a role +# session name can hold '.' and ',') it is kept. +_ARN_IN_TEXT = re.compile( + r"arn:(?Paws(?:-[a-z]+)*):(?P[a-z0-9-]+):[a-z0-9-]*:\d{12}:" + r"(?P[^\s'\"]*[^\s'\".,;:!?)\]])") + + +def mask_key_id(value: Optional[str]) -> Optional[str]: + """Keep the first and last four characters of an identifier; one of 8 + characters or fewer becomes ``***``.""" + if value is None: + return None + return f"{value[:4]}***{value[-4:]}" if len(value) > 8 else "***" + + +def mask_arn(value: Optional[str]) -> Optional[str]: + """Mask the region and account of a KMS key ARN, and the middle of its key + id, for the wrapper's own log and error messages. ARNs are identifiers, + not secrets: the messages that quote a KMS error mask the ARNs in its text + with :func:`mask_arns_in_text`, but the KMS error itself, kept as the + ``__cause__``, still shows them.""" + if value is None: + return None + _, sep, key = value.rpartition("/") + return f"arn:aws:kms:***:***:key/{mask_key_id(key) if sep and key else '***'}" + + +def mask_arns_in_text(text: str) -> str: + """Mask the ARNs in ``text`` that name an account, such as those in a + failed KMS call's error message: the master key and, for an access denial, + the caller's role session. A KMS key ARN is masked as :func:`mask_arn` + does; any other ARN keeps only its partition and service. Text without + such an ARN comes back unchanged.""" + return _ARN_IN_TEXT.sub(_mask_matched_arn, text) + + +def _mask_matched_arn(match: re.Match[str]) -> str: + if match["service"] == "kms" and match["resource"].startswith("key/"): + return cast("str", mask_arn(match[0])) + return f"arn:{match['partition']}:{match['service']}:***:***:***" + + +def _blank(value: Optional[str]) -> bool: + return value is None or not value.strip() + + +@dataclass(frozen=True) +class KeyMetadata: + """One ``key_storage`` row. + + ``id`` is the integer surrogate key, which encrypted payloads record and + ``encryption_metadata.key_id`` references. ``key_id`` is a separate UUID + string. ``encrypted_data_key`` is the base64 text of the KMS ciphertext + blob; ``hmac_key`` is raw bytes. The plaintext data key is never held here. + """ + + id: Optional[int] = None + key_id: Optional[str] = None + key_name: Optional[str] = None + master_key_arn: Optional[str] = None + encrypted_data_key: Optional[str] = field(default=None, repr=False) + hmac_key: Optional[bytes] = field(default=None, repr=False) + key_spec: str = DEFAULT_KEY_SPEC + created_at: Optional[datetime] = None + last_used_at: Optional[datetime] = None + + @property + def is_usable(self) -> bool: + """``True`` once the row names a master key and carries an encrypted + data key, an HMAC key, and a key spec.""" + return (not _blank(self.master_key_arn) and not _blank(self.encrypted_data_key) + and bool(self.hmac_key) and not _blank(self.key_spec)) + + @classmethod + def from_row(cls, row: Mapping[str, Any], prefix: str = "") -> KeyMetadata: + """Build from a ``key_storage`` row whose columns may carry ``prefix``.""" + hmac_key = row.get(f"{prefix}hmac_key") + return cls( + id=None if row.get(f"{prefix}id") is None else int(row[f"{prefix}id"]), + key_id=row.get(f"{prefix}key_id"), + key_name=row.get(f"{prefix}name"), + master_key_arn=row.get(f"{prefix}master_key_arn"), + encrypted_data_key=row.get(f"{prefix}encrypted_data_key"), + hmac_key=None if hmac_key is None else bytes(hmac_key), + key_spec=row.get(f"{prefix}key_spec") or DEFAULT_KEY_SPEC, + created_at=row.get(f"{prefix}created_at"), + last_used_at=row.get(f"{prefix}last_used_at"), + ) + + def __repr__(self) -> str: + return (f"KeyMetadata(id={self.id!r}, key_id={self.key_id!r}, key_name={self.key_name!r}, " + f"master_key_arn={mask_arn(self.master_key_arn)!r}, encrypted_data_key={REDACTED!r}, " + f"hmac_key={None if self.hmac_key is None else REDACTED!r}, key_spec={self.key_spec!r}, " + f"created_at={self.created_at!r}, last_used_at={self.last_used_at!r})") + + __str__ = __repr__ + + +@dataclass(frozen=True) +class ColumnEncryptionConfig: + """One ``encryption_metadata`` row joined to the key it references. + + ``key_metadata`` is ``None`` when the referenced ``key_storage`` row is + missing. The column still counts as encrypted, so a write fails closed + instead of storing plaintext. + """ + + table_name: str + column_name: str + algorithm: str = EncryptionAlgorithm.DEFAULT + key_id: Optional[int] = None + key_metadata: Optional[KeyMetadata] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + + @property + def column_identifier(self) -> str: + return f"{self.table_name}.{self.column_name}" + + @property + def is_usable(self) -> bool: + """``True`` when the algorithm is supported and the key row is usable.""" + return (EncryptionAlgorithm.is_supported(self.algorithm) + and self.key_metadata is not None and self.key_metadata.is_usable) diff --git a/aws_advanced_python_wrapper/encryption/sql_dialect.py b/aws_advanced_python_wrapper/encryption/sql_dialect.py new file mode 100644 index 000000000..6b28721d8 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_dialect.py @@ -0,0 +1,162 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Runs the plugin's own ``encryption_metadata`` / ``key_storage`` SQL. + +Both supported drivers (psycopg and MySQL Connector/Python) use the +``pyformat`` paramstyle, so the SQL is written once with ``%s`` placeholders. +Only a few grammar details differ by engine, and :class:`SqlDialect` holds +them. The wrapper's driver dialects manage connection lifecycle only, which is +why this module exists. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from contextlib import closing +from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Sequence + +from aws_advanced_python_wrapper.driver_dialect_codes import DriverDialectCodes +from aws_advanced_python_wrapper.errors import EncryptionConfigError +from aws_advanced_python_wrapper.utils.messages import Messages + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + +Row = Dict[str, Any] + + +class SqlDialect(ABC): + """Engine-specific grammar for the plugin's own statements.""" + + name: str = "" + + #: Equality operator used in every comparison the plugin writes. + equals: str = "=" + + @abstractmethod + def upsert_clause(self, conflict_columns: Sequence[str], update_columns: Sequence[str], + extra_assignments: Sequence[str] = ()) -> str: + """The trailing upsert clause for an ``INSERT``: on a conflict over + ``conflict_columns``, overwrite ``update_columns`` from the incoming + row and apply any literal ``extra_assignments``.""" + ... + + @abstractmethod + def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int: + """Run an ``INSERT`` (without ``RETURNING``) and return the generated + ``id``.""" + ... + + @staticmethod + def for_driver_dialect(driver_dialect: DriverDialect) -> SqlDialect: + code = driver_dialect.dialect_code + if code == DriverDialectCodes.PSYCOPG: + return PG + if code == DriverDialectCodes.MYSQL_CONNECTOR_PYTHON: + return MYSQL + raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", code)) + + @staticmethod + def for_connection(conn: Any) -> SqlDialect: + """Infer the engine from a raw psycopg / mysql-connector connection or + an ``AwsWrapperConnection`` wrapping one.""" + target = getattr(conn, "target_connection", conn) + module = type(target).__module__ + if module.startswith("psycopg"): + return PG + if module.startswith("mysql.connector") or module.startswith("_mysql_connector"): + return MYSQL + raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", type(target).__qualname__)) + + @staticmethod + def for_name(name: str) -> SqlDialect: + lowered = name.lower() + if lowered in ("pg", "postgres", "postgresql", "psycopg"): + return PG + if lowered in ("mysql", "mysql-connector", "mysql-connector-python"): + return MYSQL + raise EncryptionConfigError(Messages.get_formatted("SqlDialect.UnsupportedDriver", name)) + + def __repr__(self) -> str: + return f"{type(self).__name__}()" + + +class PgSqlDialect(SqlDialect): + name = "postgresql" + # An unqualified operator resolves through search_path, where a + # user-defined "=" with a closer type match would win. Pin the built-in. + equals = "OPERATOR(pg_catalog.=)" + + def upsert_clause(self, conflict_columns: Sequence[str], update_columns: Sequence[str], + extra_assignments: Sequence[str] = ()) -> str: + assignments = ", ".join([f"{c} = EXCLUDED.{c}" for c in update_columns] + list(extra_assignments)) + return f"ON CONFLICT ({', '.join(conflict_columns)}) DO UPDATE SET {assignments}" + + def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int: + with closing(conn.cursor()) as cursor: + cursor.execute(f"{sql} RETURNING id", params) + row = cursor.fetchone() + # A connection opened with a dict-like row factory returns a mapping. + return int(next(iter(row.values())) if isinstance(row, Mapping) else row[0]) + + +class MySqlSqlDialect(SqlDialect): + name = "mysql" + # MySQL has no user-defined operators. + equals = "=" + + def upsert_clause(self, conflict_columns: Sequence[str], update_columns: Sequence[str], + extra_assignments: Sequence[str] = ()) -> str: + # VALUES(col) rather than a row alias, which needs MySQL 8.0.19+. + assignments = ", ".join([f"{c} = VALUES({c})" for c in update_columns] + list(extra_assignments)) + return f"ON DUPLICATE KEY UPDATE {assignments}" + + def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int: + with closing(conn.cursor()) as cursor: + cursor.execute(sql, params) + return int(cursor.lastrowid) + + +PG = PgSqlDialect() +MYSQL = MySqlSqlDialect() + + +def fetch_rows(conn: Any, sql: str, params: Sequence[Any] = ()) -> List[Row]: + """Run a query and return its rows as dicts keyed by lower-cased column + name. MySQL reports ``information_schema`` names in upper case on some + versions, so callers never depend on result-key case. + + Rows may come back as tuples or, on a connection opened with a dict-like + row factory (for example psycopg's ``row_factory=dict_row``), as + mappings; both are handled. + """ + with closing(conn.cursor()) as cursor: + cursor.execute(sql, params) + if cursor.description is None: + return [] + names = [_lower(d[0]) for d in cursor.description] + return [{_lower(k): v for k, v in row.items()} if isinstance(row, Mapping) else dict(zip(names, row)) + for row in cursor.fetchall()] + + +def _lower(name: Any) -> Any: + return name.lower() if isinstance(name, str) else name + + +def execute(conn: Any, sql: str, params: Sequence[Any] = ()) -> int: + """Run a statement and return the affected-row count.""" + with closing(conn.cursor()) as cursor: + cursor.execute(sql, params) + return max(cursor.rowcount, 0) diff --git a/aws_advanced_python_wrapper/encryption/type_marker.py b/aws_advanced_python_wrapper/encryption/type_marker.py new file mode 100644 index 000000000..597825718 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/type_marker.py @@ -0,0 +1,113 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from datetime import date, datetime, time +from decimal import Decimal +from typing import Any, Dict, Optional + + +class TypeMarker: + """The single byte written ahead of the ciphertext recording how the + plaintext was serialized, so a decrypted payload can be turned back into a + Python value. + + The marker numbers are stored in every payload, so they can't change + without breaking values already written. Python has a single unbounded + ``int`` type, so integers are always written as :data:`LONG` (8 bytes, + big-endian); :data:`INTEGER` (4 bytes) is still understood on read. + """ + + STRING = 1 + INTEGER = 2 + LONG = 3 + DOUBLE = 4 + FLOAT = 5 + BOOLEAN = 6 + BIG_DECIMAL = 7 + DATE = 8 + TIME = 9 + TIMESTAMP = 10 + LOCAL_DATE = 11 + LOCAL_TIME = 12 + LOCAL_DATE_TIME = 13 + BYTE_ARRAY = 14 + GENERIC = 99 + + _NAMES: Dict[int, str] = { + STRING: "STRING", + INTEGER: "INTEGER", + LONG: "LONG", + DOUBLE: "DOUBLE", + FLOAT: "FLOAT", + BOOLEAN: "BOOLEAN", + BIG_DECIMAL: "BIG_DECIMAL", + DATE: "DATE", + TIME: "TIME", + TIMESTAMP: "TIMESTAMP", + LOCAL_DATE: "LOCAL_DATE", + LOCAL_TIME: "LOCAL_TIME", + LOCAL_DATE_TIME: "LOCAL_DATE_TIME", + BYTE_ARRAY: "BYTE_ARRAY", + GENERIC: "GENERIC", + } + + @classmethod + def from_value(cls, value: int) -> int: + """Validate a marker byte read from a payload and return it unchanged.""" + if value not in cls._NAMES: + raise ValueError(f"Unknown type marker: {value!r}") + return value + + @classmethod + def from_object(cls, value: Any) -> int: + """Pick the marker used to serialize a Python value. + + Unknown types fall back to :data:`GENERIC`, serialized through ``str``. + Order matters: ``bool`` is a subclass of ``int`` and ``datetime`` a + subclass of ``date``, so the narrower types are checked first. + + A naive ``datetime`` is a local date-time (:data:`LOCAL_DATE_TIME`, + ISO text). A timezone-aware one names an instant, so it is written as + :data:`TIMESTAMP` (epoch milliseconds), which keeps the instant and + reads back as an aware UTC ``datetime``. + """ + if isinstance(value, (bytes, bytearray, memoryview)): + return cls.BYTE_ARRAY + if isinstance(value, str): + return cls.STRING + if isinstance(value, bool): + return cls.BOOLEAN + if isinstance(value, int): + return cls.LONG + if isinstance(value, float): + return cls.DOUBLE + if isinstance(value, Decimal): + return cls.BIG_DECIMAL + if isinstance(value, datetime): + return cls.LOCAL_DATE_TIME if value.utcoffset() is None else cls.TIMESTAMP + if isinstance(value, date): + return cls.LOCAL_DATE + if isinstance(value, time): + return cls.LOCAL_TIME + return cls.GENERIC + + @classmethod + def name_for(cls, marker: int) -> Optional[str]: + return cls._NAMES.get(marker) + + @classmethod + def is_known(cls, marker: int) -> bool: + return marker in cls._NAMES diff --git a/aws_advanced_python_wrapper/errors.py b/aws_advanced_python_wrapper/errors.py index 7af9a752e..2355d36c1 100644 --- a/aws_advanced_python_wrapper/errors.py +++ b/aws_advanced_python_wrapper/errors.py @@ -14,7 +14,8 @@ from typing import Optional -from .pep249 import Error, InterfaceError, NotSupportedError, OperationalError +from .pep249 import (Error, IntegrityError, InterfaceError, NotSupportedError, + OperationalError) class AwsWrapperError(Error): @@ -73,3 +74,119 @@ class ReadWriteSplittingError(AwsWrapperError, InterfaceError): class AwsConnectError(AwsWrapperError, OperationalError): __module__ = "aws_advanced_python_wrapper" + + +# -- KMS encryption plugin errors -- +# +# Callers branch on the exception type. For example, the read path's lenient +# ``encryption_return_unverified_data`` mode will catch ``IntegrityCheckError`` +# and let every other failure propagate. +# +# Each class derives from ``AwsWrapperError`` for the wrapper's own error +# handling and mixes in a PEP 249 type, which is what SQLAlchemy uses to +# classify errors at the DB-API boundary. SQLAlchemy picks the first PEP 249 +# class in the MRO, so a class whose mix-in should win lists it first. Django +# does not translate these errors: its backends look error classes up on the +# native driver module, which these do not derive from, so they reach Django +# code as raised. The optional ``algorithm`` and ``data_type`` attributes help +# with diagnostics. +# +# The class hierarchy is specific to this wrapper. + +class EncryptionPluginError(AwsWrapperError): + __module__ = "aws_advanced_python_wrapper" + + +class EncryptionError(EncryptionPluginError, OperationalError): + __module__ = "aws_advanced_python_wrapper" + + def __init__(self, message: str = "", *, algorithm: Optional[str] = None, + data_type: Optional[str] = None): + super().__init__(message) + self.algorithm = algorithm + self.data_type = data_type + + +class IntegrityCheckError(IntegrityError, EncryptionError): + """The payload is not a valid encrypted value: too short to hold the + framing, or its HMAC tag does not match. + + ``IntegrityError`` is listed first so SQLAlchemy classifies it as an + integrity error rather than through ``EncryptionError``'s + ``OperationalError``. Lenient mode (``encryption_return_unverified_data``) + will swallow this read-side failure and no other. A value that verifies + but will not decrypt raises ``DecryptionError``, which lenient mode always + lets through. + """ + __module__ = "aws_advanced_python_wrapper" + + +class DecryptionError(EncryptionError): + """A verified payload could not be decrypted, usually because the data key + is wrong (the GCM authentication tag does not match) or the marker is bad. + """ + __module__ = "aws_advanced_python_wrapper" + + +class EncryptionFailedError(EncryptionError): + """A value could not be encrypted or serialized.""" + __module__ = "aws_advanced_python_wrapper" + + +class InvalidKeyError(EncryptionError): + """A data key or HMAC key is missing or the wrong length.""" + __module__ = "aws_advanced_python_wrapper" + + +class InvalidAlgorithmError(EncryptionError): + """An unsupported encryption algorithm was requested.""" + __module__ = "aws_advanced_python_wrapper" + + +class TypeConversionError(EncryptionError): + """A decrypted value could not be coerced to its declared or requested type.""" + __module__ = "aws_advanced_python_wrapper" + + +class EncryptionConfigError(EncryptionPluginError, InterfaceError): + """The ``encryption_*`` connection properties are missing or invalid.""" + __module__ = "aws_advanced_python_wrapper" + + +class KeyManagementError(EncryptionPluginError, OperationalError): + """A data key or master key could not be created, read, decrypted, or + stored. + + ``operation`` names the failing step (for example ``"DECRYPT_DATA_KEY"``) + for diagnostics. It is not part of any cross-wrapper contract. + """ + __module__ = "aws_advanced_python_wrapper" + + def __init__(self, message: str = "", *, operation: Optional[str] = None): + super().__init__(message) + self.operation = operation + + +class UnauthorizedMasterKeyError(KeyManagementError): + """The master key named by a ``key_storage`` row is not listed in + ``encryption_allowed_master_key_arns``. Raised before KMS is called. + """ + __module__ = "aws_advanced_python_wrapper" + + +class InvalidKeyMetadataError(KeyManagementError): + """A ``key_storage`` row is unusable: it names no master key, or its + encrypted data key, HMAC key, or key spec is missing or malformed. + """ + __module__ = "aws_advanced_python_wrapper" + + +class MetadataError(EncryptionPluginError, OperationalError): + """The ``encryption_metadata`` / ``key_storage`` tables could not be read.""" + __module__ = "aws_advanced_python_wrapper" + + def __init__(self, message: str = "", *, table_name: Optional[str] = None, + column_name: Optional[str] = None): + super().__init__(message) + self.table_name = table_name + self.column_name = column_name diff --git a/aws_advanced_python_wrapper/mysql_driver_dialect.py b/aws_advanced_python_wrapper/mysql_driver_dialect.py index 4b6f28215..e265b934d 100644 --- a/aws_advanced_python_wrapper/mysql_driver_dialect.py +++ b/aws_advanced_python_wrapper/mysql_driver_dialect.py @@ -69,6 +69,7 @@ class MySQLDriverDialect(DriverDialect): DbApiMethod.CURSOR_CLOSE.method_name, DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_FETCHONE.method_name, + DbApiMethod.CURSOR_NEXT.method_name, DbApiMethod.CURSOR_FETCHMANY.method_name, DbApiMethod.CURSOR_FETCHALL.method_name } diff --git a/aws_advanced_python_wrapper/pep249_methods.py b/aws_advanced_python_wrapper/pep249_methods.py index 0406c1d43..c1d656176 100644 --- a/aws_advanced_python_wrapper/pep249_methods.py +++ b/aws_advanced_python_wrapper/pep249_methods.py @@ -61,19 +61,20 @@ class DbApiMethod(Enum): CURSOR_CONNECTION = (28, "Cursor.connection", False) CURSOR_ROWNUMBER = (29, "Cursor.rownumber", False) CURSOR_NEXT = (30, "Cursor.__next__", False) - CURSOR_LASTROWID = (31, "Cursor.lastrowid", False) + CURSOR_ITER = (31, "Cursor.__iter__", False) + CURSOR_LASTROWID = (32, "Cursor.lastrowid", False) # AWS Advanced Python Wrapper Methods for the execution pipelines. - CONNECT = (32, "connect", True) - FORCE_CONNECT = (33, "force_connect", True) - INIT_HOST_PROVIDER = (34, "init_host_provider", True) - NOTIFY_CONNECTION_CHANGED = (35, "notify_connection_changed", True) - NOTIFY_HOST_LIST_CHANGED = (36, "notify_host_list_changed", True) - GET_HOST_INFO_BY_STRATEGY = (37, "get_host_info_by_strategy", True) - ACCEPTS_STRATEGY = (38, "accepts_strategy", True) + CONNECT = (33, "connect", True) + FORCE_CONNECT = (34, "force_connect", True) + INIT_HOST_PROVIDER = (35, "init_host_provider", True) + NOTIFY_CONNECTION_CHANGED = (36, "notify_connection_changed", True) + NOTIFY_HOST_LIST_CHANGED = (37, "notify_host_list_changed", True) + GET_HOST_INFO_BY_STRATEGY = (38, "get_host_info_by_strategy", True) + ACCEPTS_STRATEGY = (39, "accepts_strategy", True) # Special marker for all methods - ALL = (39, "*", False) + ALL = (40, "*", False) def __init__(self, id: int, method_name: str, always_use_pipeline: bool): self.id = id diff --git a/aws_advanced_python_wrapper/pg_driver_dialect.py b/aws_advanced_python_wrapper/pg_driver_dialect.py index 415011344..63d86dc74 100644 --- a/aws_advanced_python_wrapper/pg_driver_dialect.py +++ b/aws_advanced_python_wrapper/pg_driver_dialect.py @@ -59,6 +59,7 @@ class PgDriverDialect(DriverDialect): DbApiMethod.CURSOR_CALLPROC.method_name, DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_FETCHONE.method_name, + DbApiMethod.CURSOR_NEXT.method_name, DbApiMethod.CURSOR_FETCHMANY.method_name, DbApiMethod.CURSOR_FETCHALL.method_name } diff --git a/aws_advanced_python_wrapper/plugin.py b/aws_advanced_python_wrapper/plugin.py index 7706364c5..feefb08ee 100644 --- a/aws_advanced_python_wrapper/plugin.py +++ b/aws_advanced_python_wrapper/plugin.py @@ -93,6 +93,18 @@ def force_connect( return force_connect_func() def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + """ + Handles a call to a method this plugin subscribes to, such as `Cursor.execute`. Calling `execute_func` runs the plugins after this one, + then the target driver method. To send different `Cursor.execute` or `Cursor.executemany` arguments to them, assign a new tuple to the + `args` and a new mapping to the `kwargs` of :py:attr:`PluginService.current_call_context` before calling `execute_func`. + + :param target: the target driver object the method is called on, such as the driver's cursor or connection. + :param method_name: the name of the method, such as `Cursor.execute`. + :param execute_func: the function to call to continue the call down the pipeline. + :param args: the method's positional arguments, as they are when this plugin's turn comes. + :param kwargs: the method's keyword arguments, as they are when this plugin's turn comes. + :return: the result of the call, usually the value `execute_func` returns. + """ return execute_func() def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index 469303799..a97f723cc 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -45,7 +45,10 @@ from abc import abstractmethod from concurrent.futures import TimeoutError -from typing import Any, Callable, Dict, Optional, Protocol, Set, Tuple +from contextvars import ContextVar +from functools import partial +from typing import (Any, Callable, Dict, FrozenSet, Mapping, Optional, + Protocol, Set, Tuple) from aws_advanced_python_wrapper.allowed_and_blocked_hosts import \ AllowedAndBlockedHosts @@ -241,6 +244,23 @@ def network_bound_methods(self) -> Set[str]: def props(self) -> Properties: ... + @property + @abstractmethod + def current_call_context(self) -> Optional[PluginCallContext]: + """ + The context of the ``Cursor.execute`` or ``Cursor.executemany`` call this thread is running through the plugins. + + Read it only while handling one of those two methods. Each of those calls has its own context, a call made + from inside a plugin included, and the enclosing one is current again once it returns. Other methods get no + context of their own, so while one of them runs inside such a call, this still returns the enclosing call's + context. ``None`` when no such call is running on this thread. + + The value belongs to the calling thread, not to this connection's plugin service. Another thread sees it only + through a copy of this thread's context taken during the call (``contextvars.copy_context()``, or a thread + that inherits its creator's context), and such a copy holds no arguments once the call has returned. + """ + ... + def is_network_bound_method(self, method_name: str) -> bool: ... @@ -573,6 +593,10 @@ def network_bound_methods(self) -> Set[str]: def props(self) -> Properties: return self._props + @property + def current_call_context(self) -> Optional[PluginCallContext]: + return _CURRENT_CALL_CONTEXT.get() + def update_in_transaction(self, is_in_transaction: Optional[bool] = None): if is_in_transaction is not None: self._is_in_transaction = is_in_transaction @@ -861,6 +885,36 @@ def get_status(self, clazz: Type[StatusType], key: str) -> Optional[StatusType]: return status +class PluginCallContext: + """The arguments of the ``Cursor.execute`` or ``Cursor.executemany`` call the plugins are handling. + + Each plugin's ``execute`` receives the arguments as they are when its turn comes. A plugin that needs to hand + different ones to the plugins after it and to the target driver method assigns a new tuple to ``args`` and a new + mapping to ``kwargs`` before it calls its ``execute_func``. Changing either object in place is not allowed, and + the caller's own objects must never be modified. The target driver method receives exactly what is assigned, even + when it is empty. A replacement lasts until the plugin that made it returns, so a plugin before it that calls its + ``execute_func`` again starts from the arguments it saw. + + Reached through :py:attr:`PluginService.current_call_context`. + """ + + __slots__ = ("args", "kwargs") + + def __init__(self, args: Tuple[Any, ...], kwargs: Mapping[str, Any]): + self.args = args + self.kwargs = kwargs + + +# The methods whose call gets a PluginCallContext. Their target driver functions (in AwsWrapperCursor) take the +# context's arguments. +_CALL_CONTEXT_METHODS: FrozenSet[DbApiMethod] = frozenset({DbApiMethod.CURSOR_EXECUTE, DbApiMethod.CURSOR_EXECUTEMANY}) + +# The current call's context belongs to the calling thread, not to a plugin service, so it is a ContextVar. Resetting +# its token in PluginManager.execute makes the enclosing call's context current again after a nested call. +_CURRENT_CALL_CONTEXT: ContextVar[Optional[PluginCallContext]] = ContextVar( + "aws_advanced_python_wrapper_plugin_call_context", default=None) + + class PluginChainCallableInfo: """Container for plugin chain callable and subscription information.""" def __init__(self, func: Callable, is_subscribed: bool): @@ -1067,13 +1121,18 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla if context is not None: context.set_attribute("python_call", method.method_name) + call_context = PluginCallContext(args, kwargs) if method in _CALL_CONTEXT_METHODS else None + token = None if call_context is None else _CURRENT_CALL_CONTEXT.set(call_context) try: - result = self._execute_with_subscribed_plugins( - method, - # next_plugin_func is defined later in make_pipeline - lambda plugin, next_plugin_func: plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs), - target_driver_func, - None) + if call_context is None: + result = self._execute_with_subscribed_plugins( + method, + # next_plugin_func is defined later in make_pipeline + lambda plugin, next_plugin_func: plugin.execute(target, method.method_name, next_plugin_func, *args, **kwargs), + target_driver_func, + None) + else: + result = self._execute_with_call_context(target, method, target_driver_func, call_context) if context is not None: context.set_success(True) @@ -1083,9 +1142,47 @@ def execute(self, target: object, method: DbApiMethod, target_driver_func: Calla context.set_success(False) raise e finally: + if token is not None: + _CURRENT_CALL_CONTEXT.reset(token) + if call_context is not None: + # A copy of this thread's context taken during the call (one a plugin passes to a thread it starts, say) + # still holds this object, so it must not keep the call's arguments once the call has returned. + call_context.args, call_context.kwargs = (), {} if context is not None: context.close_context() + def _execute_with_call_context( + self, target: Any, method: DbApiMethod, target_driver_func: Callable, call_context: PluginCallContext) -> Any: + # The target driver function is always called with the context's arguments, so a replacement reaches the + # driver as written: an empty one fails there instead of running the caller's arguments. + return self._execute_with_subscribed_plugins( + method, + lambda plugin, next_plugin_func: PluginManager._execute_plugin( + plugin, target, method.method_name, next_plugin_func, call_context, target_driver_func), + lambda: target_driver_func(*call_context.args, **call_context.kwargs), + None) + + @staticmethod + def _execute_plugin( + plugin: Plugin, + target: Any, + method_name: str, + next_plugin_func: Callable, + call_context: PluginCallContext, + target_driver_func: Callable) -> Any: + # Each plugin gets the arguments as they are when its turn comes, so a replacement made before it is honoured. + # A replacement lasts until the plugin that made it returns: a plugin before it that calls its execute_func + # again starts from the arguments it saw, so nothing is replaced twice. + args, kwargs = call_context.args, call_context.kwargs + if isinstance(plugin, DefaultPlugin): + # DefaultPlugin may run the driver call on a socket_timeout worker that starts only after this call has + # timed out and every replacement has been undone, so the driver function gets these arguments bound now. + next_plugin_func = partial(target_driver_func, *args, **kwargs) + try: + return plugin.execute(target, method_name, next_plugin_func, *args, **kwargs) + finally: + call_context.args, call_context.kwargs = args, kwargs + def _execute_with_telemetry(self, plugin_name: str, func: Callable): context = self._telemetry_factory.open_telemetry_context(plugin_name, TelemetryTraceLevel.NESTED) try: diff --git a/aws_advanced_python_wrapper/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/read_write_splitting_plugin.py index a166a12b5..d99708d40 100644 --- a/aws_advanced_python_wrapper/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/read_write_splitting_plugin.py @@ -60,6 +60,7 @@ class AbstractReadWriteSplittingPlugin(Plugin): DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_FETCHONE.method_name, + DbApiMethod.CURSOR_NEXT.method_name, DbApiMethod.CURSOR_FETCHMANY.method_name, DbApiMethod.CURSOR_FETCHALL.method_name } diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index 3c5726725..a30656b4c 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -545,3 +545,37 @@ MonitorService.ErrorDisposingMonitor=[MonitorService] Error disposing monitor: { MonitorService.ErrorPropagatingEvent=[MonitorService] Error propagating event: {} MonitorService.StuckMonitorDetected=[MonitorService] Stuck monitor detected for type '{}' with key '{}'. MonitorService.ErrorDuringCleanup=[MonitorService] Error during cleanup: {} + +DataKeyCache.CleanupFailed=[DataKeyCache] Removing expired data keys failed: {} +EncryptionConfig.InvalidSchemaName=[EncryptionConfig] Invalid encryption_metadata_schema {}: a schema name must start with a letter or underscore and contain only letters, digits, and underscores. +EncryptionConfig.InvalidValue=[EncryptionConfig] Invalid value for {}: {} +EncryptionConfig.MissingAllowedMasterKeys=[EncryptionConfig] {} is required: list the KMS master key ARNs the kms_encryption plugin may use. +EncryptionConfig.MissingRegion=[EncryptionConfig] No KMS region configured: set encryption_kms_region, or the AWS_REGION or AWS_DEFAULT_REGION environment variable. +EncryptionConfig.OutOfRange=[EncryptionConfig] The value of {} is out of range: it must be {}. +KeyManagementUtility.AlreadyEncrypted=[KeyManagementUtility] Column {}.{} is already encrypted. +KeyManagementUtility.CreateAliasFailed=[KeyManagementUtility] Created master key {} but could not create an alias for it: {} +KeyManagementUtility.CreatedMasterKey=[KeyManagementUtility] Created KMS master key {}. +KeyManagementUtility.MissingArgument=[KeyManagementUtility] connection, kms_client, and config are required. +KeyManagementUtility.NoCurrentMasterKey=[KeyManagementUtility] Column {}.{} has no current master key to rotate onto; pass new_master_key_arn. +KeyManagementUtility.NotEncrypted=[KeyManagementUtility] No kms_encryption configuration exists for {}.{}. +KeyManagementUtility.NothingToRemove=[KeyManagementUtility] No kms_encryption configuration existed for {}.{}. +KeyManagementUtility.RequiredArgument=[KeyManagementUtility] {} is required. +KeyManagementUtility.RotatedDataKey=[KeyManagementUtility] Rotated the data key for {}.{} from key {} to {}. +KeyManagementUtility.RotateNeedsMasterKey=[KeyManagementUtility] Pass the master key ARN to rotate onto, or configure {} so the current one can be checked. +KeyManagementUtility.StatementFailed=[KeyManagementUtility] {} failed: {} +KeyManagementUtility.StoredDataKey=[KeyManagementUtility] Stored a data key for {}.{} as key_storage id {}. +KeyManager.KmsCallFailed=[KeyManager] KMS {} failed after {} attempt(s): {} +KeyManager.MalformedEncryptedDataKey=[KeyManager] The stored encrypted data key is not valid base64. +KeyManager.MasterKeyValidationFailed=[KeyManager] Could not validate master key {}: {} +KeyManager.MissingEncryptedDataKey=[KeyManager] The stored key metadata has no encrypted data key. +KeyManager.ReadKeyMetadataFailed=[KeyManager] Failed to read a key_storage row: {} +KeyManager.RefusingUnusableKeyMetadata=[KeyManager] Refusing to store key metadata that names no master key or lacks an encrypted data key, HMAC key, or key spec. +KeyManager.Retrying=[KeyManager] KMS {} failed (attempt {}/{}), retrying in {:.3f}s: {} +KeyManager.StoreKeyMetadataFailed=[KeyManager] Failed to store key metadata ({}). +KeyManager.TouchKeyFailed=[KeyManager] Failed to update last_used_at for key {}: {} +KeyManager.UnauthorizedMasterKey=[KeyManager] Master key {} is not listed in {}; refusing to use it. +KeyManager.WrongDataKeyLength=[KeyManager] KMS returned a {}-byte data key for key spec {}, which {} cannot use. +MetadataManager.LoadFailed=[MetadataManager] Failed to read the kms_encryption metadata: {} +MetadataManager.RefreshFailed=[MetadataManager] Failed to refresh the kms_encryption metadata cache: {} +MetadataManager.Refreshed=[MetadataManager] Refreshed the kms_encryption metadata cache with {} column configuration(s). +SqlDialect.UnsupportedDriver=[SqlDialect] The kms_encryption plugin does not support driver {}; use psycopg or mysql-connector-python. diff --git a/aws_advanced_python_wrapper/utils/properties.py b/aws_advanced_python_wrapper/utils/properties.py index f84b8fbe0..a7e53f67b 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -218,6 +218,81 @@ class WrapperProperties: 60 * 60 * 24 * 365, ) + # KMS encryption plugin. + ENCRYPTION_KMS_REGION = WrapperProperty( + "encryption_kms_region", + "AWS region for KMS calls made by the kms_encryption plugin. Falls back to the AWS_REGION, then " + "AWS_DEFAULT_REGION environment variable; the connection is rejected if none is set.", + ) + ENCRYPTION_KMS_ENDPOINT = WrapperProperty( + "encryption_kms_endpoint", "Endpoint URL override for KMS." + ) + ENCRYPTION_ALLOWED_MASTER_KEY_ARNS = WrapperProperty( + "encryption_allowed_master_key_arns", + "The KMS master keys the kms_encryption plugin may use, as a comma-separated string or a list. Required by " + "the plugin. Each entry must match a key_storage.master_key_arn value exactly; a data key naming any other " + "master key, or none, is refused before KMS is called.", + ) + ENCRYPTION_METADATA_SCHEMA = WrapperProperty( + "encryption_metadata_schema", + "Schema (database, on MySQL) holding the encryption_metadata and key_storage tables.", + "encrypt", + ) + ENCRYPTION_METADATA_CACHE_ENABLED = WrapperProperty( + "encryption_metadata_cache_enabled", + "Cache the kms_encryption metadata in memory instead of querying it per statement.", + True, + ) + ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC = WrapperProperty( + "encryption_metadata_cache_expiration_sec", + "How long cached kms_encryption metadata stays valid, in seconds.", + 3600.0, + ) + ENCRYPTION_METADATA_CACHE_REFRESH_INTERVAL_SEC = WrapperProperty( + "encryption_metadata_cache_refresh_interval_sec", + "How often the kms_encryption metadata is refreshed in the background, in seconds. 0 disables it.", + 300.0, + ) + ENCRYPTION_DATA_KEY_CACHE_ENABLED = WrapperProperty( + "encryption_data_key_cache_enabled", + "Cache decrypted data keys in memory to avoid a KMS Decrypt call for every encrypted value written or read.", + True, + ) + ENCRYPTION_DATA_KEY_CACHE_MAX_SIZE = WrapperProperty( + "encryption_data_key_cache_max_size", + "Maximum number of decrypted data keys held in memory.", + 1000, + ) + ENCRYPTION_DATA_KEY_CACHE_EXPIRATION_SEC = WrapperProperty( + "encryption_data_key_cache_expiration_sec", + "How long a decrypted data key stays cached, in seconds.", + 300.0, + ) + ENCRYPTION_KEY_MANAGEMENT_MAX_RETRIES = WrapperProperty( + "encryption_key_management_max_retries", + "Maximum number of retries for throttled or failed KMS calls. Creating a master key is retried only " + "when KMS did not act on the request.", + 3, + ) + ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC = WrapperProperty( + "encryption_key_management_retry_backoff_base_sec", + "Base delay in seconds for the exponential backoff between KMS retries.", + 0.1, + ) + ENCRYPTION_AUDIT_LOGGING_ENABLED = WrapperProperty( + "encryption_audit_logging_enabled", + "Log an audit record for every key-management, encryption, and decryption operation " + "(used by the kms_encryption plugin).", + False, + ) + ENCRYPTION_RETURN_UNVERIFIED_DATA = WrapperProperty( + "encryption_return_unverified_data", + "Do not enable in production. On read, return a value as stored instead of raising when it cannot be " + "confirmed to be this column's encrypted data: too short to be a payload, or a failed HMAC. Intended " + "only for reading data written before the column was encrypted (used by the kms_encryption plugin).", + False, + ) + DIALECT = WrapperProperty( "wrapper_dialect", "A unique identifier for the supported database dialect." ) diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 8ad8e7eb4..1a10d88a1 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -405,8 +405,13 @@ def execute( *args: Any, **kwargs: Any ) -> AwsWrapperCursor: - return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTE, - lambda: self.target_cursor.execute(*args, **kwargs), *args, **kwargs) + # The plugin manager calls the driver with the statement's arguments, + # which a plugin may have replaced. + result = self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: self.target_cursor.execute(*a, **kw), *args, **kwargs) + # psycopg returns the driver cursor itself; return this cursor instead, + # so a chained fetch goes through the plugins. + return self if result is self.target_cursor else result def executemany( self, @@ -414,7 +419,7 @@ def executemany( **kwargs: Any ) -> None: self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_EXECUTEMANY, - lambda: self.target_cursor.executemany(*args, **kwargs), + lambda *a, **kw: self.target_cursor.executemany(*a, **kw), *args, **kwargs) def nextset(self) -> bool: @@ -434,7 +439,44 @@ def fetchall(self) -> List[Any]: lambda: self.target_cursor.fetchall()) def __iter__(self) -> Iterator[Any]: - return self.target_cursor.__iter__() + # The plugins subscribed to Cursor.__iter__ run once per loop, not once + # per row: such a plugin returns an iterator over the driver's (one that + # changes each row, say). The driver's iterator still fetches the rows, + # so a server-side cursor keeps fetching a page at a time. + return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_ITER, + lambda: iter(self.target_cursor)) + + def __next__(self) -> Any: + # A loop doesn't call this method: __iter__ returns the driver's iterator. + # The plugins subscribed to Cursor.__next__ run for each row. A driver cursor + # that is its own iterator (psycopg 3.3 and later) gives the row with its own + # next(), so a server-side cursor continues the page a loop read ahead; any + # other driver cursor gives it with fetchone. + target = self.target_cursor + rows = iter(target) + if rows is not target: + row = self._plugin_manager.execute(target, DbApiMethod.CURSOR_NEXT, lambda: target.fetchone()) + if row is None: + raise StopIteration + return row + # A row can itself be None (psycopg's scalar_row on a NULL), so the rows end + # only when the driver's next() ends them or a plugin returns None without + # reading a row. The plugins see the end as None, as from fetchone. + read = False + + def next_row() -> Any: + nonlocal read + try: + row = next(rows) + except StopIteration: + return None + read = True + return row + + row = self._plugin_manager.execute(target, DbApiMethod.CURSOR_NEXT, next_row) + if row is None and not read: + raise StopIteration + return row def setinputsizes(self, sizes: Any) -> None: return self._plugin_manager.execute(self.target_cursor, DbApiMethod.CURSOR_SETINPUTSIZES, diff --git a/docs/development-guide/LoadablePlugins.md b/docs/development-guide/LoadablePlugins.md index 7ea35af0a..30c529f61 100644 --- a/docs/development-guide/LoadablePlugins.md +++ b/docs/development-guide/LoadablePlugins.md @@ -59,6 +59,15 @@ Plugins can also subscribe to specific [pipelines](./Pipelines.md) by including | [Connection changed notification pipeline](./Pipelines.md#connection-changed-notification-pipeline) | notify_connection_changed | | [Host list changed notification pipeline](./Pipelines.md#host-list-changed-notification-pipeline) | notify_host_list_changed | +A loop over a cursor (`for row in cursor`) calls the plugins subscribed to `Cursor.__iter__` once per loop, not once per row. +Such a plugin calls `execute_func()` to get the target driver's iterator and returns an iterator over it, for example a generator that changes each row. +The driver's iterator fetches the rows after the plugins have returned, so a server-side cursor still fetches a page at a time, and an error raised while fetching a row does not pass through the plugins' `execute` methods. +The asynchronous cursor sends each row of a loop through the plugins as `Cursor.fetchone` instead. + +With psycopg, `cursor.execute()` returns the wrapper's cursor, so a fetch chained onto it, such as `cursor.execute(query).fetchone()`, goes through the plugins as well. +On the synchronous cursor, `next(cursor)` returns the next row through the plugins subscribed to `Cursor.__next__`, once per row. +Such a plugin also runs on the call that ends the rows, where `execute_func()` returns `None`, and should return that `None` unchanged so that `next(cursor)` raises `StopIteration`. + ### Tips on Creating a Custom Plugin A custom plugin can subscribe to all Python methods being executed by setting the Plugin's `subscribed_methods` attribute to `{"*"}`. In this case, the plugin will be active in every workflow. We recommend that you be aware of the performance impact of subscribing to all Python methods, especially if your plugin regularly performs demanding tasks for common Python method calls. @@ -122,6 +131,9 @@ When creating custom plugins, it is important to **avoid** the following bad pra - the plugin should always call the pipeline lambdas (i.e. `connect_func: Callable` or `force_connect_func: Callable`) 4. Running long tasks synchronously: - the Python method calls are executed by all subscribed plugins synchronously; if one plugin runs a long task during the execution it blocks the execution for the other plugins +5. Modifying the arguments a method is called with: + - the objects passed to a plugin's `execute` belong to the caller (its query parameters, for example) and must not be changed + - to send different arguments to the plugins after it and to the target driver, a plugin assigns new ones to the [call context](./PluginService.md#the-call-context) See the following examples for more details: diff --git a/docs/development-guide/PluginService.md b/docs/development-guide/PluginService.md index 3f5eee7e3..60a40a1ae 100644 --- a/docs/development-guide/PluginService.md +++ b/docs/development-guide/PluginService.md @@ -27,6 +27,44 @@ The value belongs to a single connect. `PluginService.connect()` clears it on entry and `set_current_connection()` clears it once a host has been adopted, so a plugin never reads a host left over from an earlier connect. +## The Call Context + +A plugin may need to change the arguments that `Cursor.execute` or `Cursor.executemany` passes to the target driver, for example to replace a parameter value or to rewrite the statement. +The call context covers these two methods only. + +While one of them runs through the plugins, `PluginService.current_call_context` holds the call's arguments as a `PluginCallContext` with two attributes, `args` (a tuple) and `kwargs` (a mapping). +A plugin that changes them **assigns** a new tuple to `args` and a new mapping to `kwargs` before it calls `execute_func`: + +```python +def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + context = self._plugin_service.current_call_context + if context is not None: + context.args, context.kwargs = self._rewrite(args, kwargs) # a new tuple and a new dict + return execute_func() +``` + +The plugins after it in the chain, and the target driver, receive exactly the new arguments, even when they are empty; the plugins before it keep theirs. +Changing `args` or `kwargs` in place is not allowed, and the caller's own objects must never be modified. + +`current_call_context` is set whenever a plugin handles one of these two methods through the wrapper. +A plugin that must change the arguments, rather than one that may, should raise when it finds `None` instead of calling `execute_func` with the arguments unchanged. + +A replacement lasts until the plugin that made it returns. +A plugin before it that calls `execute_func` again starts again from the arguments it saw, so the replacement is made once per run. +The arguments the target driver receives are fixed when the call reaches `DefaultPlugin`, the last plugin in the chain, so a driver call that `socket_timeout` runs on a worker thread sends them even if it starts late. +That covers `DefaultPlugin` only: a plugin that runs `execute_func` on a thread of its own must wait for that call before it returns, since a call that reaches `DefaultPlugin` after the plugin that made a replacement has returned sends the arguments without it. +Such a plugin must also run `execute_func` in a copy of the calling thread's context, for example `executor.submit(contextvars.copy_context().run, execute_func)`, because the plugins after it read `current_call_context` on the thread they run on and find `None` otherwise. + +Each `Cursor.execute` and `Cursor.executemany` call has its own context, a call made from inside a plugin included, and the enclosing call's context is current again when it returns. +Other methods get no context of their own: during a `Cursor.fetchone` called from inside an `execute`, for example, `current_call_context` still returns the enclosing call's context. +So read it only while handling `Cursor.execute` or `Cursor.executemany`. +It is `None` when no such call is running on the thread. + +The context belongs to the calling thread, not to the connection's plugin service. +Another thread sees it only through a copy of the thread's context taken during the call (`contextvars.copy_context()`, or a thread that inherits its creator's context), and such a copy holds no arguments once the call has returned. + +The call context is available to synchronous plugins only. + ## Host List Providers The plugin service uses the host list provider to retrieve the most recent host information or topology information about the database. diff --git a/poetry.lock b/poetry.lock index 2364d9b3b..ab2f45c8c 100644 --- a/poetry.lock +++ b/poetry.lock @@ -841,6 +841,120 @@ files = [ {file = "certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae"}, ] +[[package]] +name = "cffi" +version = "2.1.1" +description = "Foreign Function Interface for Python calling C code." +optional = false +python-versions = ">=3.10" +groups = ["main", "dev"] +files = [ + {file = "cffi-2.1.1-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be"}, + {file = "cffi-2.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9"}, + {file = "cffi-2.1.1-cp310-cp310-win32.whl", hash = "sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41"}, + {file = "cffi-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1"}, + {file = "cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12"}, + {file = "cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa"}, + {file = "cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3"}, + {file = "cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0"}, + {file = "cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455"}, + {file = "cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0"}, + {file = "cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf"}, + {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517"}, + {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735"}, + {file = "cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e"}, + {file = "cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a"}, + {file = "cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80"}, + {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e"}, + {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c"}, + {file = "cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6"}, + {file = "cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2"}, + {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b"}, + {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7"}, + {file = "cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac"}, + {file = "cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d"}, + {file = "cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973"}, + {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c"}, + {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb"}, + {file = "cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54"}, + {file = "cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96"}, + {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527"}, + {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13"}, + {file = "cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c"}, + {file = "cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48"}, + {file = "cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836"}, + {file = "cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3"}, + {file = "cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676"}, + {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e"}, + {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f"}, + {file = "cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4"}, + {file = "cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e"}, + {file = "cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5"}, + {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d"}, + {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b"}, + {file = "cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4"}, + {file = "cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399"}, + {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688"}, + {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7"}, + {file = "cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac"}, + {file = "cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960"}, + {file = "cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1"}, + {file = "cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc"}, + {file = "cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6"}, + {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94"}, + {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5"}, + {file = "cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66"}, + {file = "cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3"}, + {file = "cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692"}, + {file = "cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be"}, +] +markers = {main = "extra == \"encryption\" and platform_python_implementation != \"PyPy\"", dev = "platform_python_implementation != \"PyPy\""} + +[package.dependencies] +pycparser = {version = "*", markers = "implementation_name != \"PyPy\""} + [[package]] name = "charset-normalizer" version = "3.4.0" @@ -1115,6 +1229,83 @@ files = [ [package.extras] toml = ["tomli ; python_full_version <= \"3.11.0a6\""] +[[package]] +name = "cryptography" +version = "50.0.2" +description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." +optional = false +python-versions = "!=3.9.0,!=3.9.1,>=3.9" +groups = ["main", "dev"] +files = [ + {file = "cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079"}, + {file = "cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51"}, + {file = "cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93"}, + {file = "cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c"}, + {file = "cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05"}, + {file = "cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e"}, + {file = "cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e"}, + {file = "cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c"}, + {file = "cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c"}, + {file = "cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e"}, + {file = "cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94"}, + {file = "cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452"}, + {file = "cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5"}, +] +markers = {main = "extra == \"encryption\""} + +[package.dependencies] +cffi = {version = ">=2.0.0", markers = "platform_python_implementation != \"PyPy\""} +typing-extensions = {version = ">=4.13.2", markers = "python_full_version < \"3.11.0\""} + +[package.extras] +ssh = ["bcrypt (>=3.1.5)"] + [[package]] name = "debugpy" version = "1.8.22" @@ -2742,6 +2933,32 @@ files = [ {file = "pycodestyle-2.15.0.tar.gz", hash = "sha256:318f5db083869b4c4dad922d0b11124fb27ab181b6730b93371da671e31bd50e"}, ] +[[package]] +name = "pycparser" +version = "3.11" +description = "C parser in Python" +optional = false +python-versions = ">=3.10" +groups = ["main", "dev"] +files = [ + {file = "pycparser-3.11-py3-none-any.whl", hash = "sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80"}, + {file = "pycparser-3.11.tar.gz", hash = "sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc"}, +] +markers = {main = "extra == \"encryption\" and platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version < \"3.13\"", dev = "platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version < \"3.13\""} + +[[package]] +name = "pycparser" +version = "3.12" +description = "C parser in Python" +optional = false +python-versions = ">=3.11" +groups = ["main", "dev"] +files = [ + {file = "pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e"}, + {file = "pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6"}, +] +markers = {main = "extra == \"encryption\" and platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version >= \"3.13\"", dev = "platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\" and python_version >= \"3.13\""} + [[package]] name = "pydevd-pycharm" version = "263.7307.206" @@ -3965,7 +4182,10 @@ idna = ">=2.0" multidict = ">=4.0" propcache = ">=0.2.1" +[extras] +encryption = ["cryptography"] + [metadata] lock-version = "2.1" python-versions = "^3.10.0" -content-hash = "ef1d83160e6b4eacd82c37e91fa1c66ca9c0a21ac85b476bfbf0972c5d9791c5" +content-hash = "7cd044243bd145b872f30416b3db964cb7cfe39d37c44ad1a3df05b1abe9a88e" diff --git a/pyproject.toml b/pyproject.toml index 4ded4d606..48ad28a84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -46,6 +46,16 @@ aws-xray-sdk = "^2.15.0" opentelemetry-api = "^1.22.0" opentelemetry-sdk = "^1.22.0" requests = "^2.33.1" +# The KMS Encryption plugin needs this for AES-GCM, which the stdlib lacks. +# It is installed only with the `encryption` extra, so users who don't use the +# plugin don't pick up a native dependency: +# pip install "aws-advanced-python-wrapper[encryption]" +# The import is lazy as well: nothing on the core import path imports it. +cryptography = { version = ">=42.0.0", optional = true } + +[tool.poetry.extras] +# `pip install "aws-advanced-python-wrapper[encryption]"` to use the KMS Encryption plugin. +encryption = ["cryptography"] [tool.poetry.group.dev.dependencies] mypy = "^1.20.2" @@ -63,6 +73,9 @@ aiomysql = ">=0.2" aiohttp = ">=3" boto3-stubs = "^1.43.0" types_aws_xray_sdk = "^2.13.0" +# Non-optional in the dev group so the encryption unit tests run without needing +# to install the `encryption` extra explicitly. +cryptography = ">=42.0.0" [tool.poetry.group.test.dependencies] boto3 = "^1.42.95" diff --git a/tests/unit/resources/encryption/conformance_vectors.json b/tests/unit/resources/encryption/conformance_vectors.json new file mode 100644 index 000000000..75c31c328 --- /dev/null +++ b/tests/unit/resources/encryption/conformance_vectors.json @@ -0,0 +1,122 @@ +{ + "data_key_b64": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=", + "hmac_key_b64": "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj8=", + "key_id": 7, + "vectors": [ + { + "name": "string", + "marker": 1, + "ciphertext_b64": "XslAWGOdcN33t9PGj/Ad5P2qduJW98IIcAO9D35GFO8AAAAHAQAAAAAAAAAAAAAAAGbZ2bLaDgxGefOoJST14EmSceFvMA==", + "expect": "hello" + }, + { + "name": "unicode", + "marker": 1, + "ciphertext_b64": "r7RX2BhwDQ3/4ji+pOzRQupCqxDM9QEpUhV/L5bNJqIAAAAHAQEBAQEBAQEBAQEBARSig/bBqI7adrHKj2d74NVpKj+1BpQ7PUtA0bg=", + "expect": "café-漢字" + }, + { + "name": "long", + "marker": 3, + "ciphertext_b64": "WtKO+JQ/tvljs2m6wN/20mtP0RjxSgOL9OQ+/AtWav4AAAAHAwICAgICAgICAgICApsoGKTIIjWQjDIWKCI17OeKddqJp0Xvgw==", + "expect": 1234567890123 + }, + { + "name": "double", + "marker": 4, + "ciphertext_b64": "B4A5M6ZEJQZhnd/k0/LgE74ZEkxhxi7r1AiK0AJuwoIAAAAHBAMDAwMDAwMDAwMDA65CHS/7idR4htDh6LqJIRV4KrT1LPgvWg==", + "expect": 3.14159 + }, + { + "name": "bool_t", + "marker": 6, + "ciphertext_b64": "0QKYtGKWTimUZeF5rFkGpcuwB6mRzUyNm713I+0rYacAAAAHBgQEBAQEBAQEBAQEBGUFno4Yz+nLDktDMtW6jjZK", + "expect": true + }, + { + "name": "bool_f", + "marker": 6, + "ciphertext_b64": "Fd2/bfeCseuDMNlQ4wBzKmtZDKAnzpa+be/TPBd7fhMAAAAHBgkJCQkJCQkJCQkJCbOAaSswGIgGR2DJzfBb9MbL", + "expect": false + }, + { + "name": "bytes", + "marker": 14, + "ciphertext_b64": "4qouGFi5vlgvx7Rr7VLCeesTvPJgLaBP1ABPORv0V4cAAAAHDgUFBQUFBQUFBQUFBUw32o7IuuK9V+EU923mD2KtAiyc", + "expect_b64": "AAEC/w==" + }, + { + "name": "decimal", + "marker": 7, + "ciphertext_b64": "EmpCpu9th4vd3tEf2qu5tGBxSZTnWfm/e7kMV3D/JFMAAAAHBwYGBgYGBgYGBgYGBg1q3r1Mm5um410VyuIP4OFlsM5NmnsY75E6", + "expect": "12345.6789" + }, + { + "name": "local_date_time_no_seconds", + "marker": 13, + "ciphertext_b64": "1BOLaYntqR3/P5GfqTTB6HsTEhxZRJgQJJnrcCB3uOwAAAAHDQcHBwcHBwcHBwcHBz1almtCPuXZ9q5HsbBrxa7tcVb6A5KNZFPMDTj2EitF", + "expect_datetime_iso": "2007-12-03T10:15:00" + }, + { + "name": "local_date_time_nanos", + "marker": 13, + "ciphertext_b64": "UTa3QSMzLg1ZyYUYUrL4UimhX3cbz6cHc5wjtJIMvkAAAAAHDQgICAgICAgICAgICBhz6OHAtQTb4GQPqbCnQQ3ZJjOBpPBKW3AgPhnEX+JmSXag1k5jcXP4ga5VPw==", + "expect_datetime_iso": "2007-12-03T10:15:30.123456" + }, + { + "name": "integer", + "marker": 2, + "ciphertext_b64": "eOjLIF5tb1OCcnBTi+h7nxvFOtVd+NmtCGtZU6IxifYAAAAHAgoKCgoKCgoKCgoKCqkiX7oSxf4sLsV4FSb1y5CTV/oI", + "expect": 42 + }, + { + "name": "float", + "marker": 5, + "ciphertext_b64": "/ulkKAJhrDor0stkZ16KM2KKCOd3XQk4t+zX/teATxMAAAAHBQsLCwsLCwsLCwsLC5dOEqHZRC4CFhC5avX7u2WdDKWC", + "expect": 1.5 + }, + { + "name": "date", + "marker": 8, + "ciphertext_b64": "p+uSc2TNIcaP5ruV+NEvf4xjE3RCnApAyQTYDmfn6xEAAAAHCAwMDAwMDAwMDAwMDPSzGmawBxpvykNLvDWPv/5UtW5bmBoPsg==", + "expect_date_iso": "2026-08-11" + }, + { + "name": "time", + "marker": 9, + "ciphertext_b64": "EftLwzjMHEUhv76vaVgWILaZtg9goKRutGtb5+KwC9AAAAAHCQ0NDQ0NDQ0NDQ0NDaKnfgiMSltx4lDj1WEzScuM4/WBYNaOwg==", + "expect_datetime_iso": "1970-01-01T12:30:45.123000+00:00" + }, + { + "name": "timestamp", + "marker": 10, + "ciphertext_b64": "mfjc/A2m/fQoq1EWSSLklbT6uGR9ZvXKP7ClrrXtW1UAAAAHCg4ODg4ODg4ODg4ODrelf6h+tOq93dfcMl1rsXo8Qm9wX/NIww==", + "expect_datetime_iso": "2026-08-11T12:30:45.123000+00:00" + }, + { + "name": "local_date", + "marker": 11, + "ciphertext_b64": "7eeSdnDrnok30SucUVN6pvDCYC6BhA5htaxCRGty5ecAAAAHCw8PDw8PDw8PDw8PD0ckPqE9KQ1scV6pfRRfC+MmsXUEC64BcbUr", + "expect_date_iso": "2007-12-03" + }, + { + "name": "local_time_no_seconds", + "marker": 12, + "ciphertext_b64": "bx61rRIToPxvhAq481GeumDtezr7aFFxQrTVpE9vQrMAAAAHDBAQEBAQEBAQEBAQEKjdzfbcFmPEIYNw6BYON9f9PaeG+w==", + "expect": "10:15" + }, + { + "name": "generic", + "marker": 99, + "ciphertext_b64": "76Xi1+ZYD8ulCnru9AZ0KW3m/kanQLPF6zCHdyNYMfEAAAAHYxEREREREREREREREfQI/dHfxQZ/gEzVTDKr9oQIYpRGSw==", + "expect": "thing" + }, + { + "name": "key_id_high_bit", + "marker": 1, + "key_id": 2147483649, + "ciphertext_b64": "mmb5W6w+PE/QCKtTbxqrVJZNpNJVa6vxVPyecF4rg3CAAAABARISEhISEhISEhISErf4IQifpVL7RuZxPZ6Kthpa8Q==", + "expect": "hi" + } + ] +} diff --git a/tests/unit/resources/encryption/generate_conformance_vectors.py b/tests/unit/resources/encryption/generate_conformance_vectors.py new file mode 100644 index 000000000..8de7bc4da --- /dev/null +++ b/tests/unit/resources/encryption/generate_conformance_vectors.py @@ -0,0 +1,123 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Reference encoder for ``conformance_vectors.json``. + +Builds each payload straight from the wire-format spec with raw +``cryptography`` and the standard library. It imports nothing from +``aws_advanced_python_wrapper``, so decrypting its output tests +the wrapper against the spec rather than against itself. + +Each vector uses a fixed IV made of one repeated byte, unique per vector, so +the output is deterministic and can never come from the wrapper's own +encrypt (which draws a random IV). Add a vector with the next unused IV byte, +then regenerate:: + + python tests/unit/resources/encryption/generate_conformance_vectors.py > \\ + tests/unit/resources/encryption/conformance_vectors.json + +``test_encryption_conformance.py`` checks that the committed file matches +this script's output. +""" + +import base64 +import hashlib +import hmac +import json +import struct +import sys +from datetime import datetime, timedelta, timezone +from typing import Any, Dict, List, NamedTuple + +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +DATA_KEY = bytes(range(32)) +HMAC_KEY = bytes(range(32, 64)) +KEY_ID = 7 + +STRING, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, BIG_DECIMAL = 1, 2, 3, 4, 5, 6, 7 +DATE, TIME, TIMESTAMP, LOCAL_DATE, LOCAL_TIME, LOCAL_DATE_TIME, BYTE_ARRAY = 8, 9, 10, 11, 12, 13, 14 +GENERIC = 99 + + +def _millis(iso: str) -> bytes: + instant = datetime.fromisoformat(iso).replace(tzinfo=timezone.utc) + return struct.pack(">q", (instant - datetime(1970, 1, 1, tzinfo=timezone.utc)) // timedelta(milliseconds=1)) + + +class Vector(NamedTuple): + name: str + marker: int + plaintext: bytes + iv_byte: int + expected: Dict[str, Any] + key_id: int = KEY_ID + + +VECTORS: List[Vector] = [ + Vector("string", STRING, b"hello", 0x00, {"expect": "hello"}), + Vector("unicode", STRING, "café-漢字".encode(), 0x01, {"expect": "café-漢字"}), + Vector("long", LONG, struct.pack(">q", 1234567890123), 0x02, {"expect": 1234567890123}), + Vector("double", DOUBLE, struct.pack(">d", 3.14159), 0x03, {"expect": 3.14159}), + Vector("bool_t", BOOLEAN, b"\x01", 0x04, {"expect": True}), + Vector("bool_f", BOOLEAN, b"\x00", 0x09, {"expect": False}), + Vector("bytes", BYTE_ARRAY, b"\x00\x01\x02\xff", 0x05, {"expect_b64": "AAEC/w=="}), + Vector("decimal", BIG_DECIMAL, b"12345.6789", 0x06, {"expect": "12345.6789"}), + Vector("local_date_time_no_seconds", LOCAL_DATE_TIME, b"2007-12-03T10:15", 0x07, + {"expect_datetime_iso": "2007-12-03T10:15:00"}), + Vector("local_date_time_nanos", LOCAL_DATE_TIME, b"2007-12-03T10:15:30.123456789", 0x08, + {"expect_datetime_iso": "2007-12-03T10:15:30.123456"}), + # Markers this wrapper reads but never writes. + Vector("integer", INTEGER, struct.pack(">i", 42), 0x0A, {"expect": 42}), + Vector("float", FLOAT, struct.pack(">f", 1.5), 0x0B, {"expect": 1.5}), + Vector("date", DATE, _millis("2026-08-11T00:00:00"), 0x0C, {"expect_date_iso": "2026-08-11"}), + Vector("time", TIME, _millis("1970-01-01T12:30:45.123"), 0x0D, + {"expect_datetime_iso": "1970-01-01T12:30:45.123000+00:00"}), + Vector("timestamp", TIMESTAMP, _millis("2026-08-11T12:30:45.123"), 0x0E, + {"expect_datetime_iso": "2026-08-11T12:30:45.123000+00:00"}), + Vector("local_date", LOCAL_DATE, b"2007-12-03", 0x0F, {"expect_date_iso": "2007-12-03"}), + Vector("local_time_no_seconds", LOCAL_TIME, b"10:15", 0x10, {"expect": "10:15"}), + Vector("generic", GENERIC, b"thing", 0x11, {"expect": "thing"}), + # The key id is an unsigned 32-bit integer. + Vector("key_id_high_bit", STRING, b"hi", 0x12, {"expect": "hi"}, 0x80000001), +] + + +def build() -> Dict[str, Any]: + vectors = [] + for v in VECTORS: + iv = bytes([v.iv_byte]) * 12 + body = struct.pack(">I", v.key_id) + bytes([v.marker]) + iv + AESGCM(DATA_KEY).encrypt(iv, v.plaintext, None) + payload = hmac.new(HMAC_KEY, body, hashlib.sha256).digest() + body + vector: Dict[str, Any] = {"name": v.name, "marker": v.marker} + if v.key_id != KEY_ID: + vector["key_id"] = v.key_id + vector["ciphertext_b64"] = base64.b64encode(payload).decode("ascii") + vector.update(v.expected) + vectors.append(vector) + return { + "data_key_b64": base64.b64encode(DATA_KEY).decode("ascii"), + "hmac_key_b64": base64.b64encode(HMAC_KEY).decode("ascii"), + "key_id": KEY_ID, + "vectors": vectors, + } + + +def render() -> str: + return json.dumps(build(), indent=2, ensure_ascii=False) + "\n" + + +if __name__ == "__main__": + # Written as UTF-8 bytes, so the non-ASCII vector works on any console. + sys.stdout.buffer.write(render().encode("utf-8")) diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py index 8e5f20684..ebdd9f07c 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -14,7 +14,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Callable, Iterator, List, Optional, Set from unittest.mock import MagicMock, patch import psycopg @@ -23,9 +23,18 @@ if TYPE_CHECKING: from aws_advanced_python_wrapper.pep249 import Connection +from aws_advanced_python_wrapper.default_plugin import DefaultPlugin +from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.mysql_driver_dialect import MySQLDriverDialect +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect +from aws_advanced_python_wrapper.plugin import Plugin from aws_advanced_python_wrapper.plugin_service import ( - PluginServiceImpl, PluginServiceManagerContainer) + PluginManager, PluginServiceImpl, PluginServiceManagerContainer) +from aws_advanced_python_wrapper.read_write_splitting_plugin import \ + AbstractReadWriteSplittingPlugin +from aws_advanced_python_wrapper.utils.properties import Properties from aws_advanced_python_wrapper.wrapper import (AwsWrapperConnection, AwsWrapperCursor) @@ -218,3 +227,365 @@ def test_connection_prepare_threshold_and_prepared_max_forward(): wrapper.prepared_max = 100 assert target.prepare_threshold == 99 assert target.prepared_max == 100 + + +class UpperRowsPlugin(Plugin): + """Upper-cases the rows of the methods it subscribes to, and records the methods it handles.""" + + def __init__(self, methods: Set[str], calls: List[str]): + self._methods = methods + self._calls = calls + + @property + def subscribed_methods(self) -> Set[str]: + return self._methods + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + self._calls.append(method_name) + if method_name == "Cursor.__iter__": + return (row.upper() for row in execute_func()) + return execute_func().upper() + + +def _cursor_with_plugins(driver_cursor: Any, plugins: List[Plugin], current_connection: Any = None) -> AwsWrapperCursor: + """A wrapper cursor over driver_cursor whose plugin manager runs the given plugins, then DefaultPlugin.""" + plugin_service = MagicMock() + plugin_service.current_connection = driver_cursor.connection if current_connection is None else current_connection + plugin_service.driver_dialect.get_connection_from_obj.side_effect = lambda obj: obj.connection + plugin_service.driver_dialect.unwrap_connection.side_effect = lambda conn: conn + plugin_service.driver_dialect.execute.side_effect = lambda method_name, func, *args, **kwargs: func() + container = MagicMock() + container.plugin_service = plugin_service + manager = PluginManager.__new__(PluginManager) + manager._container = container + manager._telemetry_factory = MagicMock() + manager._telemetry_in_use = False + manager._function_cache = [None] * (DbApiMethod.ALL.id + 1) + manager._plugins = plugins + [DefaultPlugin(plugin_service, MagicMock())] + return AwsWrapperCursor(MagicMock(), plugin_service, manager, driver_cursor) + + +def test_cursor_loop_runs_the_iter_subscribers_once_per_loop(): + calls: List[str] = [] + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) + # So a route that fetches row by row ends (and fails) instead of looping forever. + driver_cursor.fetchone.return_value = None + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({"Cursor.__iter__"}, calls)]) + + assert [row for row in cursor] == ["A", "B", "C"] + assert calls == ["Cursor.__iter__"] + + +def test_cursor_loop_does_not_run_the_next_subscribers(): + plugin = MagicMock(spec=Plugin) + plugin.subscribed_methods = {"Cursor.__next__"} + plugin.execute.side_effect = lambda target, method_name, execute_func, *args, **kwargs: execute_func() + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) + driver_cursor.fetchone.return_value = None + cursor = _cursor_with_plugins(driver_cursor, [plugin]) + + assert [row for row in cursor] == ["a", "b", "c"] + plugin.execute.assert_not_called() + + +@pytest.mark.parametrize("network_bound", [True, False]) +def test_cursor_loop_without_subscribers_returns_the_driver_iterator(network_bound): + # A method the dialect doesn't count as network-bound skips the pipeline when nothing subscribes to it. + rows = iter(["a", "b"]) + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = rows + cursor = _cursor_with_plugins(driver_cursor, []) + cursor._plugin_service.is_network_bound_method.return_value = network_bound + + assert iter(cursor) is rows + assert list(cursor) == ["a", "b"] + + +def test_cursor_loop_after_a_break_continues_with_the_next_row(): + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a", "b", "c"]) + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({"Cursor.__iter__"}, [])]) + + for first in cursor: + break + + assert first == "A" + assert list(cursor) == ["B", "C"] + assert list(cursor) == [] + + +def test_cursor_loop_over_a_cursor_of_an_old_connection_raises(): + # After failover, say: the connection the driver cursor belongs to is no longer the current one. + driver_cursor = MagicMock() + driver_cursor.__iter__.return_value = iter(["a"]) + cursor = _cursor_with_plugins(driver_cursor, [], current_connection=MagicMock()) + + with pytest.raises(AwsWrapperError): + for _ in cursor: + pass + + +def test_cursor_execute_returns_the_wrapper_cursor_when_the_driver_returns_its_own(): + # psycopg's Cursor.execute returns the cursor, so a fetch chained onto it must go through the plugins too. + calls: List[str] = [] + driver_cursor = MagicMock() + driver_cursor.execute.return_value = driver_cursor + driver_cursor.fetchone.return_value = "row" + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({DbApiMethod.CURSOR_FETCHONE.method_name}, calls)]) + + assert cursor.execute("SELECT 1") is cursor + assert cursor.execute("SELECT 1").fetchone() == "ROW" + assert calls == [DbApiMethod.CURSOR_FETCHONE.method_name] + + +@pytest.mark.parametrize("driver_result", [None, object()]) +def test_cursor_execute_passes_any_other_driver_result_through(driver_result): + # mysql-connector's Cursor.execute returns None. + driver_cursor = MagicMock() + driver_cursor.execute.return_value = driver_result + + assert _cursor_with_plugins(driver_cursor, []).execute("SELECT 1") is driver_result + + +def test_next_on_the_cursor_returns_the_next_row_through_the_next_subscribers(): + # psycopg's Cursor.execute returns the cursor, which is an iterator, so next(cursor.execute(query)) is the first row. + calls: List[str] = [] + driver_cursor = MagicMock() + driver_cursor.execute.return_value = driver_cursor + driver_cursor.fetchone.return_value = "row" + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({DbApiMethod.CURSOR_NEXT.method_name}, calls)]) + + assert next(cursor.execute("SELECT 1")) == "ROW" + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +def test_next_on_an_exhausted_cursor_raises_stop_iteration(): + driver_cursor = MagicMock() + driver_cursor.fetchone.return_value = None + cursor = _cursor_with_plugins(driver_cursor, []) + + with pytest.raises(StopIteration): + next(cursor) + + +def test_next_on_the_cursor_returns_an_empty_row(): + # A query with no columns (SELECT FROM t on PostgreSQL) has empty rows; only None ends the rows. + driver_cursor = MagicMock() + driver_cursor.fetchone.return_value = () + cursor = _cursor_with_plugins(driver_cursor, []) + + assert next(cursor) == () + + +class _ServerSideRows: + """A server-side cursor's result of five rows; each read is a round trip that returns the rows after the server's position.""" + + def __init__(self) -> None: + self.connection = MagicMock() + self.fetches = 0 + self._rows = ["a", "b", "c", "d", "e"] + self._position = 0 + + def _fetch(self, size: int) -> List[str]: + self.fetches += 1 + rows = self._rows[self._position:self._position + size] + self._position += len(rows) + return rows + + def fetchone(self) -> Optional[str]: + rows = self._fetch(1) + return rows[0] if rows else None + + +class _SelfIteratingServerCursor(_ServerSideRows): + """Shaped like psycopg 3.3's ServerCursor: it is its own iterator, and its next() serves a page of 3 rows it read ahead.""" + + def __init__(self) -> None: + super().__init__() + self._page: List[str] = [] + + def __iter__(self) -> _SelfIteratingServerCursor: + return self + + def __next__(self) -> str: + if not self._page: + self._page = self._fetch(3) + if not self._page: + raise StopIteration + return self._page.pop(0) + + +class _GeneratorServerCursor(_ServerSideRows): + """Shaped like psycopg 3.2's ServerCursor: each iter() starts a generator that reads a page of 3 rows at a time; no next().""" + + def __iter__(self) -> Iterator[str]: + while True: + page = self._fetch(3) + yield from page + if len(page) < 3: + return + + +class _LostConnectionError(Exception): + pass + + +class _FetchoneIteratingCursor: + """Shaped like mysql-connector's cursor: iter() calls fetchone for each row, and next() turns a driver error into the end of the rows.""" + + def __init__(self) -> None: + self.connection = MagicMock() + + def fetchone(self) -> Any: + raise _LostConnectionError("Lost connection to the server during query") + + def __iter__(self) -> Iterator[Any]: + return iter(self.fetchone, None) + + def __next__(self) -> Any: + try: + return self.fetchone() + except _LostConnectionError: + raise StopIteration from None + + +def test_next_after_a_partial_loop_returns_the_row_after_the_loop_row(): + # The loop read a page ahead, so the server is already past the row after the loop's. + calls: List[str] = [] + driver_cursor = _SelfIteratingServerCursor() + cursor = _cursor_with_plugins(driver_cursor, [UpperRowsPlugin({DbApiMethod.CURSOR_NEXT.method_name}, calls)]) + + for first in cursor: + break + + assert first == "a" + assert next(cursor) == "B" + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +def test_next_reads_a_cursor_that_is_its_own_iterator_a_page_at_a_time(): + driver_cursor = _SelfIteratingServerCursor() + cursor = _cursor_with_plugins(driver_cursor, []) + + assert [next(cursor) for _ in range(5)] == ["a", "b", "c", "d", "e"] + assert driver_cursor.fetches == 2 + + +def test_next_passes_a_driver_error_to_the_next_subscribers(): + # A lost connection must reach the plugins (failover, say) instead of ending the rows. + calls: List[str] = [] + cursor = _cursor_with_plugins(_FetchoneIteratingCursor(), [UpperRowsPlugin({DbApiMethod.CURSOR_NEXT.method_name}, calls)]) + + with pytest.raises(_LostConnectionError): + next(cursor) + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +def test_next_on_a_cursor_with_a_generator_iterator_keeps_every_row(): + # Each iter() on this cursor starts a generator that reads a page, so next() must not take its row from a new one. + cursor = _cursor_with_plugins(_GeneratorServerCursor(), []) + + assert [next(cursor) for _ in range(5)] == ["a", "b", "c", "d", "e"] + + +class _SelfIteratingRowsCursor: + """Shaped like psycopg 3.3's Cursor with a row factory that can return None (scalar_row on a NULL): it is its own iterator.""" + + def __init__(self, rows: List[Optional[str]]) -> None: + self.connection = MagicMock() + self._rows = iter(rows) + + def __iter__(self) -> _SelfIteratingRowsCursor: + return self + + def __next__(self) -> Optional[str]: + return next(self._rows) + + +def test_next_on_a_cursor_that_is_its_own_iterator_returns_a_none_row(): + cursor = _cursor_with_plugins(_SelfIteratingRowsCursor(["a", None, "c"]), []) + + assert [next(cursor) for _ in range(3)] == ["a", None, "c"] + with pytest.raises(StopIteration): + next(cursor) + + +def test_next_when_a_next_plugin_returns_none_without_reading_raises_stop_iteration(): + # A plugin that answers None without reading a row ends the rows; else next() would return None forever. + plugin = MagicMock(spec=Plugin) + plugin.subscribed_methods = {DbApiMethod.CURSOR_NEXT.method_name} + plugin.execute.return_value = None + driver_cursor = _SelfIteratingServerCursor() + cursor = _cursor_with_plugins(driver_cursor, [plugin]) + + with pytest.raises(StopIteration): + next(cursor) + assert driver_cursor.fetches == 0 + + +class _WrapErrorsPlugin(Plugin): + """Raises AwsWrapperError from any error of Cursor.__next__, as failover does with an error that isn't a lost connection.""" + + @property + def subscribed_methods(self) -> Set[str]: + return {DbApiMethod.CURSOR_NEXT.method_name} + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + try: + return execute_func() + except Exception as e: + raise AwsWrapperError(str(e)) from e + + +def test_next_at_the_end_of_a_cursor_that_is_its_own_iterator_raises_stop_iteration(): + # The driver's end of rows must not reach the plugins as an error: failover would raise AwsWrapperError from it. + cursor = _cursor_with_plugins(_SelfIteratingServerCursor(), [_WrapErrorsPlugin()]) + + assert [next(cursor) for _ in range(5)] == ["a", "b", "c", "d", "e"] + with pytest.raises(StopIteration): + next(cursor) + + +def _fetchone_rows_cursor() -> MagicMock: + """A driver cursor that isn't its own iterator, so next() takes its row from fetchone.""" + driver_cursor = MagicMock() + driver_cursor.fetchone.return_value = "row" + return driver_cursor + + +def test_next_at_the_end_of_a_fetchone_cursor_raises_stop_iteration(): + driver_cursor = _fetchone_rows_cursor() + driver_cursor.fetchone.side_effect = ["row", None] + cursor = _cursor_with_plugins(driver_cursor, [_WrapErrorsPlugin()]) + + assert next(cursor) == "row" + with pytest.raises(StopIteration): + next(cursor) + + +@pytest.mark.parametrize("new_driver_cursor", [_fetchone_rows_cursor, lambda: _SelfIteratingRowsCursor(["row"])], ids=["fetchone", "own_iterator"]) +@pytest.mark.parametrize( + "methods", + [PgDriverDialect(Properties()).network_bound_methods, + MySQLDriverDialect(Properties()).network_bound_methods, + AbstractReadWriteSplittingPlugin._SUBSCRIBED_METHODS], + ids=["pg", "mysql", "read_write_splitting"]) +def test_next_runs_the_plugins_subscribed_through_the_network_bound_methods(methods, new_driver_cursor): + # Failover, host monitoring and the connection tracker subscribe to the dialect's network-bound methods, and read/write + # splitting to its own list, so each must hold Cursor.__next__ for those plugins to see next(). + calls: List[str] = [] + cursor = _cursor_with_plugins(new_driver_cursor(), [UpperRowsPlugin(methods, calls)]) + + assert next(cursor) == "ROW" + assert calls == [DbApiMethod.CURSOR_NEXT.method_name] + + +@pytest.mark.parametrize("new_driver_cursor", [_fetchone_rows_cursor, lambda: _SelfIteratingRowsCursor(["row"])], ids=["fetchone", "own_iterator"]) +def test_next_does_not_run_the_fetchone_subscribers(new_driver_cursor): + calls: List[str] = [] + cursor = _cursor_with_plugins(new_driver_cursor(), [UpperRowsPlugin({DbApiMethod.CURSOR_FETCHONE.method_name}, calls)]) + + assert next(cursor) == "row" + assert calls == [] diff --git a/tests/unit/test_connection_source.py b/tests/unit/test_connection_source.py new file mode 100644 index 000000000..16591f8b3 --- /dev/null +++ b/tests/unit/test_connection_source.py @@ -0,0 +1,154 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import threading +from typing import Any, List +from unittest.mock import MagicMock + +import pytest + +from aws_advanced_python_wrapper.encryption.connection_source import ( + CallerConnectionSource, PluginConnectionSource) + + +@pytest.fixture +def conn(): + # The caller's connection: a source that commits, rolls back or closes it fails the test. + raw = MagicMock() + for name in ("commit", "rollback", "close"): + getattr(raw, name).side_effect = AssertionError(f"the caller source must not {name}") + return raw + + +class TestConnectionSources: + def test_caller_source_yields_the_same_connection(self, conn): + with CallerConnectionSource(conn).connection() as c: + assert c is conn + + def test_plugin_source_opens_an_independent_autocommit_connection_and_closes_it(self): + service = MagicMock() + service.props = {"plugins": "kms_encryption", "user": "u"} + raw = MagicMock() + service.force_connect.return_value = raw + plugin = object() + with PluginConnectionSource(service, plugin).connection() as c: + assert c is raw + host, props, skip = service.force_connect.call_args.args + assert host is service.current_host_info and skip is plugin + assert props == service.props and props is not service.props + service.driver_dialect.set_autocommit.assert_called_once_with(raw, True) + service.driver_dialect.execute.assert_called_once() # close routed through the dialect + + def test_plugin_source_closes_on_error(self): + service = MagicMock() + service.props = {} + with pytest.raises(RuntimeError): + with PluginConnectionSource(service).connection(): + raise RuntimeError("query failed") + service.driver_dialect.execute.assert_called_once() + + +@pytest.fixture +def raws(): + return [MagicMock(name="first"), MagicMock(name="second")] + + +@pytest.fixture +def service(raws): + service = MagicMock() + service.props = {} + service.force_connect.side_effect = raws + # Run the close the source routes through the dialect, so each connection records its own. + service.driver_dialect.execute.side_effect = lambda method_name, func, **kwargs: func() + return service + + +@pytest.fixture +def source(service): + return PluginConnectionSource(service) + + +class TestStatementScope: + def test_statement_shares_one_connection_and_closes_it_at_the_end(self, service, raws, source): + with source.statement(): + for _ in range(3): + with source.connection() as c: + assert c is raws[0] + raws[0].close.assert_not_called() + raws[0].close.assert_called_once() + assert service.force_connect.call_count == 1 + service.driver_dialect.set_autocommit.assert_called_once_with(raws[0], True) + + def test_statement_closes_its_connection_when_a_lookup_fails(self, raws, source): + with pytest.raises(RuntimeError, match="query failed"): + with source.statement(): + with source.connection(): + raise RuntimeError("query failed") + raws[0].close.assert_called_once() + # The failed scope has ended, so a lookup gets a connection of its own again. + with source.connection() as c: + assert c is raws[1] + raws[1].close.assert_called_once() + + def test_statement_without_a_lookup_opens_nothing(self, service, source): + with source.statement(): + pass + service.force_connect.assert_not_called() + service.driver_dialect.execute.assert_not_called() + + def test_statement_is_per_thread(self, raws, source): + seen: List[Any] = [] + + def lookup(): + with source.connection() as c: + seen.append(c) + + with source.statement(): + with source.connection(): + pass + other = threading.Thread(target=lookup, daemon=True) + other.start() + other.join(5) + assert not other.is_alive() + assert seen == [raws[1]] + raws[1].close.assert_called_once() + raws[0].close.assert_not_called() + raws[0].close.assert_called_once() + + def test_nested_statement_keeps_the_outer_connection(self, service, raws, source): + with source.statement(): + with source.connection() as outer: + pass + with source.statement(): + with source.connection() as inner: + assert inner is outer + raws[0].close.assert_not_called() + with source.connection() as after: + assert after is outer + raws[0].close.assert_called_once() + assert service.force_connect.call_count == 1 + + def test_autocommit_failure_in_a_statement_closes_the_half_opened_connection(self, service, raws, source): + service.driver_dialect.set_autocommit.side_effect = [RuntimeError("autocommit failed"), None] + with source.statement(): + with pytest.raises(RuntimeError, match="autocommit failed"): + with source.connection(): + pass + raws[0].close.assert_called_once() + with source.connection() as c: + assert c is raws[1] + raws[1].close.assert_not_called() + raws[1].close.assert_called_once() diff --git a/tests/unit/test_data_key_cache.py b/tests/unit/test_data_key_cache.py new file mode 100644 index 000000000..23b6d3c40 --- /dev/null +++ b/tests/unit/test_data_key_cache.py @@ -0,0 +1,275 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import time +import weakref +from types import SimpleNamespace + +import pytest + +from aws_advanced_python_wrapper.encryption import data_key_cache as module +from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache + + +class Clock: + def __init__(self): + self.now = 1000.0 + + def __call__(self): + return self.now + + +@pytest.fixture +def clock(monkeypatch): + # Replace the module's view of `time` only, so no other thread in the + # process sees a frozen clock. + c = Clock() + monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=c)) + return c + + +def make(max_size=3, ttl=60.0, enabled=True): + return DataKeyCache(max_size, ttl, enabled, start_cleanup_thread=False) + + +def test_get_returns_a_copy_the_caller_can_wipe(clock): + cache = make() + cache.put("k", b"\x01" * 32) + first = cache.get("k") + assert first == bytearray(b"\x01" * 32) + first[:] = b"\x00" * 32 + assert cache.get("k") == bytearray(b"\x01" * 32) + + +def test_put_copies_so_the_caller_keeps_ownership(clock): + cache = make() + key = bytearray(b"\x02" * 32) + cache.put("k", key) + key[:] = b"\x00" * 32 + assert cache.get("k") == bytearray(b"\x02" * 32) + + +def test_oldest_entry_is_evicted_and_wiped(clock): + cache = make(max_size=2) + cache.put("a", b"a" * 4) + entry_a = cache._entries["a"].data_key + cache.put("b", b"b" * 4) + cache.put("c", b"c" * 4) + assert cache.get("a") is None + assert entry_a == bytearray(4) + assert len(cache) == 2 + assert cache.stats().evictions == 1 + + +def test_replacing_a_key_wipes_the_old_value_and_does_not_evict(clock): + cache = make(max_size=2) + cache.put("a", b"1111") + cache.put("b", b"2222") + old = cache._entries["a"].data_key + cache.put("a", b"3333") + assert old == bytearray(4) + assert cache.get("a") == bytearray(b"3333") + assert cache.get("b") == bytearray(b"2222") + assert cache.stats().evictions == 0 + + +def test_expired_entry_is_never_returned_and_is_wiped(clock): + cache = make(ttl=10) + cache.put("k", b"kkkk") + stored = cache._entries["k"].data_key + clock.now += 9.9 + assert cache.get("k") is not None + clock.now += 0.1 + assert cache.get("k") is None + assert stored == bytearray(4) + assert len(cache) == 0 + + +def test_remove_expired(clock): + cache = make(ttl=10) + cache.put("old", b"o") + clock.now += 5 + cache.put("new", b"n") + clock.now += 5 + assert cache.remove_expired() == 1 + assert cache.get("new") is not None + + +def test_clear_and_close_wipe_everything(clock): + cache = make() + cache.put("a", b"aa") + stored = cache._entries["a"].data_key + cache.close() + assert stored == bytearray(2) + assert len(cache) == 0 + cache.close() # idempotent + + +def test_disabled_cache_never_stores(clock): + cache = make(enabled=False) + cache.put("k", b"x") + assert cache.get("k") is None + assert len(cache) == 0 + assert cache.stats().misses == 0 + + +def test_stats(clock): + cache = make() + cache.put("k", b"x") + cache.get("k") + cache.get("missing") + stats = cache.stats() + assert (stats.size, stats.hits, stats.misses) == (1, 1, 1) + assert stats.hit_rate == 50.0 + + +def test_repr_does_not_show_key_material(clock): + cache = make() + cache.put("k", b"SECRET") + assert "SECRET" not in repr(cache._entries["k"]) + + +def test_cleanup_interval_has_a_floor(): + assert make(ttl=40).cleanup_interval_sec == DataKeyCache.MIN_CLEANUP_INTERVAL_SEC + assert make(ttl=400).cleanup_interval_sec == 100.0 + + +def test_cleanup_thread_stops_promptly_on_close(): + cache = DataKeyCache(10, 3600.0) + try: + thread = cache._cleanup_thread + assert thread is not None and thread.daemon and thread.is_alive() + started = time.monotonic() + cache.close() + assert not thread.is_alive() + assert time.monotonic() - started < 2.0 + finally: + cache.close() + + +def test_closed_cache_stores_nothing(clock): + # A KMS round trip that finishes after close() must not leave a plaintext + # key in a cache nobody will wipe. + cache = make() + cache.close() + key = bytearray(b"\x05" * 32) + cache.put("k", key) + assert cache.get("k") is None + assert len(cache) == 0 + assert key == bytearray(b"\x05" * 32) # the caller's buffer is left alone + + +def test_finalizer_wipes_first_and_never_sets_the_event_from_the_cleanup_thread(clock): + # A collection on the cleanup thread can run inside Event.wait, which + # holds the event's lock, so stop.set() there would deadlock. The keys + # are wiped regardless. + import threading + cache = make() + cache.put("k", b"\x09" * 4) + stored = cache._entries["k"].data_key + stop = threading.Event() + DataKeyCache._release(cache._entries, cache._lock, stop, [threading.current_thread()]) + assert stored == bytearray(4) and len(cache) == 0 + assert not stop.is_set() + DataKeyCache._release(cache._entries, cache._lock, stop, [None]) + assert stop.is_set() + + +def test_close_on_the_cleanup_thread_stops_it_without_joining_itself(): + # There the finalizer leaves the event alone, so close() must set it, and + # it must not join its own thread. + import threading + cache = DataKeyCache(10, 3600.0, start_cleanup_thread=False) + errors = [] + + def run(): + try: + cache.close() + except BaseException as e: + errors.append(e) + + t = threading.Thread(target=run, daemon=True) + cache._thread_holder[0] = t + cache._cleanup_thread = t + t.start() + t.join(5) + assert not t.is_alive() + assert errors == [] + assert cache._stop.is_set() + + +def test_finalizer_wipes_the_keys_even_if_stopping_the_thread_fails(clock): + cache = make() + cache.put("k", b"\x09" * 4) + stored = cache._entries["k"].data_key + + class BrokenStop: + def set(self): + raise RuntimeError("cannot stop") + + with pytest.raises(RuntimeError): + DataKeyCache._release(cache._entries, cache._lock, BrokenStop(), [None]) # type: ignore[arg-type] + assert stored == bytearray(4) + + +def test_a_cache_hit_does_not_protect_an_entry_from_eviction(clock): + # Eviction is oldest-first by insertion, not least recently used. + cache = make(max_size=2) + cache.put("a", b"aaaa") + cache.put("b", b"bbbb") + assert cache.get("a") == bytearray(b"aaaa") + cache.put("c", b"cccc") + assert cache.get("a") is None + assert cache.get("b") == bytearray(b"bbbb") + + +def test_put_after_close_wipes_the_copy_it_refuses(clock, monkeypatch): + wiped = [] + real = module.wipe + monkeypatch.setattr(module, "wipe", lambda buf: (wiped.append(buf), real(buf))) + cache = make() + cache.close() + cache.put("k", b"\x07" * 4) + assert len(cache) == 0 + assert wiped == [bytearray(4)] + + +def test_finalizer_is_given_the_cleanup_thread(): + cache = DataKeyCache(10, 3600.0) + try: + assert cache._cleanup_thread is not None + assert cache._thread_holder == [cache._cleanup_thread] + assert any(arg is cache._thread_holder for arg in cache._finalizer.peek()[2]) # type: ignore[index] + finally: + cache.close() + + +def test_unclosed_cache_is_wiped_and_its_thread_stops_when_collected(): + cache = DataKeyCache(10, 3600.0) + cache.put("k", b"\x07" * 32) + stored = cache._entries["k"].data_key + thread = cache._cleanup_thread + ref = weakref.ref(cache) + del cache + for _ in range(100): + gc.collect() + if ref() is None: + break + time.sleep(0.01) + assert ref() is None + assert stored == bytearray(32) + assert thread is not None + thread.join(5) + assert not thread.is_alive() diff --git a/tests/unit/test_encryption_config.py b/tests/unit/test_encryption_config.py new file mode 100644 index 000000000..0300df9eb --- /dev/null +++ b/tests/unit/test_encryption_config.py @@ -0,0 +1,253 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import pytest + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.config import ( + EncryptionConfig, validate_schema_name) +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata, mask_arn, mask_arns_in_text) +from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + InterfaceError) +from aws_advanced_python_wrapper.utils.properties import Properties + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" + + +@pytest.fixture(autouse=True) +def no_region_env(monkeypatch): + monkeypatch.delenv("AWS_REGION", raising=False) + monkeypatch.delenv("AWS_DEFAULT_REGION", raising=False) + + +def props(**kwargs) -> Properties: + base = {"encryption_kms_region": "us-east-1", "encryption_allowed_master_key_arns": ARN} + base.update(kwargs) + return Properties({k: v for k, v in base.items() if v is not None}) + + +class TestFromProps: + def test_defaults_match_the_shared_spec(self): + config = EncryptionConfig.from_props(props()) + assert config.kms_region == "us-east-1" + assert config.kms_endpoint is None + assert config.metadata_schema == "encrypt" + assert config.metadata_cache_enabled is True + assert config.metadata_cache_expiration_sec == 3600.0 + assert config.metadata_cache_refresh_interval_sec == 300.0 + assert config.data_key_cache_enabled is True + assert config.data_key_cache_max_size == 1000 + assert config.data_key_cache_expiration_sec == 300.0 + assert config.key_management_max_retries == 3 + assert config.key_management_retry_backoff_base_sec == 0.1 + assert config.audit_logging_enabled is False + assert config.return_unverified_data is False + + def test_string_values_are_parsed(self): + config = EncryptionConfig.from_props(props( + encryption_metadata_cache_enabled="false", + encryption_metadata_cache_refresh_interval_sec="0", + encryption_data_key_cache_max_size="5", + encryption_key_management_retry_backoff_base_sec="0.25", + )) + assert config.metadata_cache_enabled is False + assert config.metadata_cache_refresh_interval_sec == 0.0 + assert config.background_refresh_enabled is False + assert config.data_key_cache_max_size == 5 + assert config.key_management_retry_backoff_base_sec == 0.25 + + def test_region_falls_back_to_aws_region_then_default_region(self, monkeypatch): + monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "eu-west-1" + monkeypatch.setenv("AWS_REGION", "ap-south-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "ap-south-1" + + @pytest.mark.parametrize("env", ["AWS_REGION", "AWS_DEFAULT_REGION"]) + def test_region_property_beats_environment(self, monkeypatch, env): + # On Lambda, ECS, or EC2 AWS_REGION is usually set; an explicit + # encryption_kms_region must still win. + monkeypatch.setenv(env, "eu-west-1") + assert EncryptionConfig.from_props(props()).kms_region == "us-east-1" + + def test_blank_region_property_falls_back_to_the_environment(self, monkeypatch): + monkeypatch.setenv("AWS_REGION", "eu-west-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=" ")).kms_region == "eu-west-1" + + @pytest.mark.parametrize("name", [ + "encryption_metadata_cache_expiration_sec", + "encryption_metadata_cache_refresh_interval_sec", + "encryption_data_key_cache_expiration_sec", + "encryption_key_management_retry_backoff_base_sec", + ]) + def test_infinite_durations_are_refused(self, name): + # Event.wait() rejects an infinite timeout, which would kill the + # background threads. + with pytest.raises(EncryptionConfigError, match=name): + EncryptionConfig.from_props(props(**{name: "inf"})) + + def test_blank_aws_region_falls_back_to_aws_default_region(self, monkeypatch): + monkeypatch.setenv("AWS_REGION", " ") + monkeypatch.setenv("AWS_DEFAULT_REGION", "eu-west-1") + assert EncryptionConfig.from_props(props(encryption_kms_region=None)).kms_region == "eu-west-1" + + def test_region_is_stripped(self): + assert EncryptionConfig.from_props(props(encryption_kms_region=" us-east-1 ")).kms_region == "us-east-1" + + def test_missing_region_is_rejected(self): + with pytest.raises(EncryptionConfigError, match="region"): + EncryptionConfig.from_props(props(encryption_kms_region=None)) + + def test_allow_list_is_required_by_default(self): + with pytest.raises(EncryptionConfigError, match="encryption_allowed_master_key_arns"): + EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=None)) + with pytest.raises(EncryptionConfigError): + EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=" , ")) + + def test_allow_list_can_be_waived_for_admin_use(self): + config = EncryptionConfig.from_props( + props(encryption_allowed_master_key_arns=None), require_allowed_master_keys=False) + assert not config.restricts_master_keys + assert config.is_master_key_allowed(ARN) + assert config.is_master_key_allowed(None) + + def test_non_numeric_value_is_a_config_error_naming_the_property(self): + with pytest.raises(EncryptionConfigError, match="encryption_data_key_cache_max_size"): + EncryptionConfig.from_props(props(encryption_data_key_cache_max_size="lots")) + + @pytest.mark.parametrize("name, value", [ + ("encryption_metadata_cache_expiration_sec", "0"), + ("encryption_metadata_cache_refresh_interval_sec", "-1"), + ("encryption_data_key_cache_max_size", "0"), + ("encryption_data_key_cache_expiration_sec", "-5"), + ("encryption_key_management_max_retries", "-1"), + ("encryption_key_management_retry_backoff_base_sec", "0"), + ]) + def test_out_of_range_values_name_the_property(self, name, value): + with pytest.raises(EncryptionConfigError, match=name) as err: + EncryptionConfig.from_props(props(**{name: value})) + assert ">" in str(err.value).partition("must be")[2] + + def test_config_error_is_an_interface_error(self): + with pytest.raises(InterfaceError): + EncryptionConfig.from_props(props(encryption_kms_region=None)) + + +class TestAllowList: + def test_string_list_is_split_trimmed_and_deduplicated(self): + other = ARN.replace("1234abcd", "9999ffff") + config = EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=f" {ARN} ,{other},{ARN},")) + assert config.allowed_master_key_arns == frozenset({ARN, other}) + + def test_python_list_is_accepted(self): + config = EncryptionConfig.from_props(props(encryption_allowed_master_key_arns=[ARN, " "])) + assert config.allowed_master_key_arns == frozenset({ARN}) + + def test_match_is_exact(self): + config = EncryptionConfig.from_props(props()) + assert config.is_master_key_allowed(ARN) + assert not config.is_master_key_allowed(ARN.upper()) + assert not config.is_master_key_allowed(ARN + " ") + assert not config.is_master_key_allowed("alias/whatever") + assert not config.is_master_key_allowed(None) + + def test_direct_construction_normalizes_too(self): + config = EncryptionConfig(kms_region="us-east-1", allowed_master_key_arns=f"{ARN}, ") # type: ignore[arg-type] + assert config.allowed_master_key_arns == frozenset({ARN}) + + +class TestSchemaName: + @pytest.mark.parametrize("name", ["encrypt", "_x", "App_Encrypt2"]) + def test_plain_identifiers_are_accepted(self, name): + assert validate_schema_name(name) == name + + @pytest.mark.parametrize("name", ["", " ", "1abc", "a-b", "a b", "a;drop", "a.b", '"q"', "a/*c*/", None, 5]) + def test_anything_else_is_rejected(self, name): + with pytest.raises(EncryptionConfigError): + validate_schema_name(name) + + def test_props_schema_is_validated(self): + with pytest.raises(EncryptionConfigError): + EncryptionConfig.from_props(props(encryption_metadata_schema="x; DROP TABLE y")) + + +class TestModels: + def test_key_metadata_repr_redacts_key_material(self): + km = KeyMetadata(id=1, key_id="uuid", master_key_arn=ARN, encrypted_data_key="SECRET-EDK", + hmac_key=b"SECRET-HMAC-KEY-BYTES") + for text in (repr(km), str(km), repr(ColumnEncryptionConfig("t", "c", key_metadata=km))): + assert "SECRET" not in text + assert "123456789012" not in text + assert "[REDACTED]" in text + + def test_mask_arn(self): + assert mask_arn(ARN) == "arn:aws:kms:***:***:key/1234***90ab" + assert mask_arn("short/abc") == "arn:aws:kms:***:***:key/***" + assert mask_arn("no-slash") == "arn:aws:kms:***:***:key/***" + assert mask_arn(None) is None + + @pytest.mark.parametrize("partition", ["aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b", "aws-iso-f"]) + def test_mask_arns_in_text_covers_every_partition(self, partition): + key = f"arn:{partition}:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" + session = f"arn:{partition}:sts::123456789012:assumed-role/app-role/app-session" + text = f"User: {session} is not authorized to perform: kms:Decrypt on resource: {key}" + assert mask_arns_in_text(text) == (f"User: arn:{partition}:sts:***:***:*** is not authorized to perform: " + "kms:Decrypt on resource: arn:aws:kms:***:***:key/1234***90ab") + + @pytest.mark.parametrize("text, expected", [ + pytest.param("arn:aws:kms:us-east-1:123456789012:alias/app-key is not found.", + "arn:aws:kms:***:***:*** is not found.", id="alias"), + pytest.param("arn:aws:iam::123456789012:role/app-role", "arn:aws:iam:***:***:***", id="iam-role"), + pytest.param(f"{ARN} and arn:aws:kms:us-east-1:123456789012:key/ffffffff-12ab-34cd-56ef-1234567890ab", + "arn:aws:kms:***:***:key/1234***90ab and arn:aws:kms:***:***:key/ffff***90ab", id="two-arns"), + pytest.param(f"{ARN} is disabled.", "arn:aws:kms:***:***:key/1234***90ab is disabled.", id="space"), + pytest.param(f"key {ARN}.", "key arn:aws:kms:***:***:key/1234***90ab.", id="period"), + pytest.param(f"{ARN}, then", "arn:aws:kms:***:***:key/1234***90ab, then", id="comma"), + pytest.param(f"{ARN}; then", "arn:aws:kms:***:***:key/1234***90ab; then", id="semicolon"), + pytest.param(f"'{ARN}'", "'arn:aws:kms:***:***:key/1234***90ab'", id="single-quotes"), + pytest.param(f'"{ARN}"', '"arn:aws:kms:***:***:key/1234***90ab"', id="double-quotes"), + pytest.param(f"key {ARN}", "key arn:aws:kms:***:***:key/1234***90ab", id="end-of-text"), + # A role session name may hold '.', ',' and '@'; none of it is left. + pytest.param("arn:aws:sts::123456789012:assumed-role/app-role/first.last@example.com.", + "arn:aws:sts:***:***:***.", id="dots-in-session-name"), + pytest.param("arn:aws:sts::123456789012:assumed-role/app-role/a,b is not authorized", + "arn:aws:sts:***:***:*** is not authorized", id="comma-in-session-name"), + pytest.param("Invalid arn us-east-1", "Invalid arn us-east-1", id="no-arn"), + pytest.param("", "", id="empty"), + pytest.param("arn:aws:kms:***:***:key/1234***90ab is disabled.", + "arn:aws:kms:***:***:key/1234***90ab is disabled.", id="already-masked"), + ]) + def test_mask_arns_in_text(self, text, expected): + assert mask_arns_in_text(text) == expected + + def test_usability(self): + good = KeyMetadata(master_key_arn=ARN, encrypted_data_key="e", hmac_key=b"h") + assert good.is_usable + assert not KeyMetadata(master_key_arn=" ", encrypted_data_key="e", hmac_key=b"h").is_usable + assert not KeyMetadata(master_key_arn=ARN, encrypted_data_key=None, hmac_key=b"h").is_usable + assert not KeyMetadata(master_key_arn=ARN, encrypted_data_key="e", hmac_key=b"").is_usable + assert ColumnEncryptionConfig("t", "c", key_metadata=good).is_usable + assert not ColumnEncryptionConfig("t", "c", key_metadata=None).is_usable + assert not ColumnEncryptionConfig("t", "c", algorithm="DES", key_metadata=good).is_usable + + def test_from_row_normalizes_binary_and_prefix(self): + row = {"ks_id": "7", "ks_key_id": "u", "ks_hmac_key": memoryview(b"hk"), "ks_key_spec": None} + km = KeyMetadata.from_row(row, "ks_") + assert km.id == 7 and km.key_id == "u" and km.hmac_key == b"hk" and km.key_spec == "AES_256" + + +def test_data_key_spec_matches_algorithm_key_length(): + assert EncryptionAlgorithm.data_key_spec(EncryptionAlgorithm.AES_256_GCM) == "AES_256" + assert EncryptionAlgorithm.data_key_spec(EncryptionAlgorithm.AES_128_GCM) == "AES_128" diff --git a/tests/unit/test_encryption_conformance.py b/tests/unit/test_encryption_conformance.py new file mode 100644 index 000000000..8ac7fee4c --- /dev/null +++ b/tests/unit/test_encryption_conformance.py @@ -0,0 +1,126 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Byte-format conformance tests for the KMS encryption wire format. + +These check that Python matches the payload layout shown below. The +database-side trigger checks its minimum length and its HMAC tag. + +The vectors in ``resources/encryption/conformance_vectors.json`` come from +the reference encoder next to them, ``generate_conformance_vectors.py``, which +builds each payload from the spec with raw ``cryptography`` and the stdlib, +without importing the wrapper, so decrypting them tests the code against the +spec. The encrypt->decrypt round trips in test_encryption_service.py can't do +that by themselves, because they would still pass if the whole format were +wrong. + +The format under test:: + + [ HMAC-SHA256 : 32 ][ key id : 4 ][ marker : 1 ][ IV : 12 ][ ciphertext ][ GCM tag : 16 ] +""" + +import base64 +import hashlib +import hmac +import importlib.util +import json +from datetime import date, datetime +from decimal import Decimal +from pathlib import Path + +import pytest + +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService + +_RESOURCES = Path(__file__).parent / "resources" / "encryption" +_VECTORS_PATH = _RESOURCES / "conformance_vectors.json" +_IV_OFFSET = EncryptionService.HMAC_TAG_LENGTH + EncryptionService.KEY_ID_LENGTH + EncryptionService.TYPE_MARKER_LENGTH + + +def _load(): + data = json.loads(_VECTORS_PATH.read_text(encoding="utf-8")) + dk = base64.b64decode(data["data_key_b64"]) + hk = base64.b64decode(data["hmac_key_b64"]) + return dk, hk, data["key_id"], data["vectors"] + + +DK, HK, KEY_ID, VECTORS = _load() +_IDS = [v["name"] for v in VECTORS] + + +@pytest.mark.parametrize("vec", VECTORS, ids=_IDS) +def test_decrypts_independent_reference_payload(vec): + """Python decrypts a payload it did not produce to the expected value.""" + ciphertext = base64.b64decode(vec["ciphertext_b64"]) + result = EncryptionService.decrypt(ciphertext, DK, HK) + + if "expect_b64" in vec: + assert result == base64.b64decode(vec["expect_b64"]) + elif "expect_datetime_iso" in vec: + # LOCAL_DATE_TIME vectors include the no-seconds and nanosecond forms + # the reader accepts. Python must read them to the microsecond. + assert result == datetime.fromisoformat(vec["expect_datetime_iso"]) + elif "expect_date_iso" in vec: + assert result == date.fromisoformat(vec["expect_date_iso"]) + elif vec["name"] == "decimal": + assert Decimal(result) == Decimal(vec["expect"]) + else: + # The type matters too: INTEGER must read as int, not 42.0. + assert result == vec["expect"] + assert type(result) is type(vec["expect"]) + + +@pytest.mark.parametrize("vec", VECTORS, ids=_IDS) +def test_reference_payload_carries_expected_key_id(vec): + ciphertext = base64.b64decode(vec["ciphertext_b64"]) + assert EncryptionService.key_id_from_payload(ciphertext) == vec.get("key_id", KEY_ID) + + +@pytest.mark.parametrize("vec", VECTORS, ids=_IDS) +def test_our_encrypt_output_passes_the_db_trigger_hmac(vec): + """Check our output the way the DB-side trigger does: the HMAC over + everything after the 32-byte tag, computed with the stored HMAC key, must + match the tag. The trigger would reject any write that fails this. + """ + # Re-encrypt the decrypted value, then recompute the HMAC. + value = EncryptionService.decrypt(base64.b64decode(vec["ciphertext_b64"]), DK, HK) + payload = EncryptionService.encrypt(value, DK, HK, key_id=vec.get("key_id", KEY_ID)) + assert len(payload) >= EncryptionService.MIN_ENCRYPTED_LENGTH + stored_tag = payload[:EncryptionService.HMAC_TAG_LENGTH] + body = payload[EncryptionService.HMAC_TAG_LENGTH:] + recomputed = hmac.new(HK, body, hashlib.sha256).digest() + assert hmac.compare_digest(stored_tag, recomputed) + + +def test_vectors_use_distinct_fixed_ivs(): + """Each vector's IV is one repeated byte, unique per vector. The wrapper's + encrypt draws a random IV, so it could not have produced these payloads.""" + ivs = [] + for vec in VECTORS: + iv = base64.b64decode(vec["ciphertext_b64"])[_IV_OFFSET:_IV_OFFSET + EncryptionService.GCM_IV_LENGTH] + assert len(set(iv)) == 1, vec["name"] + ivs.append(iv) + assert len(set(ivs)) == len(ivs) + + +def test_committed_vectors_match_the_reference_encoder(): + """The JSON file is exactly what the reference encoder produces, so the + vectors can be regenerated and reviewed from source.""" + spec = importlib.util.spec_from_file_location("generate_conformance_vectors", + _RESOURCES / "generate_conformance_vectors.py") + assert spec is not None and spec.loader is not None + generator = importlib.util.module_from_spec(spec) + spec.loader.exec_module(generator) + assert _VECTORS_PATH.read_text(encoding="utf-8") == generator.render() diff --git a/tests/unit/test_encryption_import_guard.py b/tests/unit/test_encryption_import_guard.py new file mode 100644 index 000000000..666917176 --- /dev/null +++ b/tests/unit/test_encryption_import_guard.py @@ -0,0 +1,132 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""``cryptography`` is an optional extra (``encryption``). The wrapper must +import without it, and only the module that encrypts may need it. + +Each check runs in a fresh interpreter, most with ``cryptography`` blocked, +since the test environment always has it installed.""" + +import subprocess +import sys +import textwrap + +import pytest + +_BLOCKER = textwrap.dedent(""" + import sys + + class _Block: + def find_spec(self, name, path=None, target=None): + if name == "cryptography" or name.startswith("cryptography."): + raise ModuleNotFoundError(f"No module named {name!r}", name=name) + return None + + sys.meta_path.insert(0, _Block()) +""") + + +def _run(code: str, block: bool = True) -> subprocess.CompletedProcess: + script = (_BLOCKER if block else "import sys\n") + textwrap.dedent(code) + return subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120) + + +_CORE_MODULES = [ + "aws_advanced_python_wrapper", + "aws_advanced_python_wrapper.aio", + "aws_advanced_python_wrapper.psycopg", + "aws_advanced_python_wrapper.mysql_connector", + "aws_advanced_python_wrapper.sqlalchemy_dialects.pg", + "aws_advanced_python_wrapper.sqlalchemy_dialects.mysql", + "aws_advanced_python_wrapper.sqlalchemy_dialects.pg_async", + "aws_advanced_python_wrapper.sqlalchemy_dialects.mysql_async", + "aws_advanced_python_wrapper.django.backends.mysql_connector.base", +] + + +_KEY_LAYER_MODULES = [ + # The key and metadata layer, including the admin utility, does no + # encryption itself. + "aws_advanced_python_wrapper.encryption.config", + "aws_advanced_python_wrapper.encryption.data_key_cache", + "aws_advanced_python_wrapper.encryption.key_manager", + "aws_advanced_python_wrapper.encryption.metadata_manager", + "aws_advanced_python_wrapper.encryption.key_management_utility", +] + + +@pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) +def test_imports_without_cryptography(module): + result = _run(f""" + import importlib + importlib.import_module({module!r}) + """) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) +def test_does_not_load_cryptography_even_when_installed(module): + # With cryptography available, importing these must still not load it, + # so users who never encrypt don't pay its import cost. + result = _run(f""" + import importlib + importlib.import_module({module!r}) + assert "cryptography" not in sys.modules, "cryptography was imported" + """, block=False) + assert result.returncode == 0, result.stderr + + +def test_encryption_service_names_the_extra_when_cryptography_is_missing(): + result = _run(""" + try: + import aws_advanced_python_wrapper.encryption.encryption_service + except ImportError as e: + print(e) + else: + raise SystemExit("imported without cryptography") + """) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" in result.stdout + + +_BROKEN = textwrap.dedent(""" + import sys + + class _Broken: + def find_spec(self, name, path=None, target=None): + if name == "cryptography": + raise {error} + return None + + sys.meta_path.insert(0, _Broken()) +""") + + +@pytest.mark.parametrize("error", [ + 'ImportError("DLL load failed while importing _rust")', + 'ModuleNotFoundError("No module named \'_cffi_backend\'", name="_cffi_backend")', +], ids=["ImportError", "other-module-missing"]) +def test_a_broken_cryptography_is_not_reported_as_missing(error): + # Only a missing cryptography package gets the install hint; an installed + # but broken one surfaces its own error. + code = _BROKEN.format(error=error) + textwrap.dedent(""" + try: + import aws_advanced_python_wrapper.encryption.encryption_service + except ImportError as e: + print(e) + """) + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" not in result.stdout + assert ("DLL load failed" in result.stdout) or ("_cffi_backend" in result.stdout) diff --git a/tests/unit/test_encryption_service.py b/tests/unit/test_encryption_service.py new file mode 100644 index 000000000..66ef481bf --- /dev/null +++ b/tests/unit/test_encryption_service.py @@ -0,0 +1,864 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import hashlib +import hmac +import struct +from datetime import date, datetime, time, timedelta, timezone +from decimal import Decimal +from enum import Enum + +import pytest + +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.encryption_service import \ + EncryptionService +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker +from aws_advanced_python_wrapper.errors import (DecryptionError, + EncryptionError, + EncryptionFailedError, + IntegrityCheckError, + InvalidAlgorithmError, + InvalidKeyError, + TypeConversionError) + +DATA_KEY = bytes(range(32)) # 32 bytes +HMAC_KEY = bytes(range(32, 64)) # 32 bytes +KEY_ID = 7 + + +class Color(str, Enum): + RED = "red" + + +class Masked(str): + def __str__(self): + return "***" + + +def enc(value, key_id=KEY_ID, dk=DATA_KEY, hk=HMAC_KEY, algorithm=EncryptionAlgorithm.DEFAULT): + return EncryptionService.encrypt(value, dk, hk, algorithm, key_id=key_id) + + +def dec(payload, dk=DATA_KEY, hk=HMAC_KEY, algorithm=EncryptionAlgorithm.DEFAULT, target_type=None): + return EncryptionService.decrypt(payload, dk, hk, algorithm, target_type=target_type) + + +# ---- payload layout ---- + +class TestPayloadLayout: + def test_min_length_is_65(self): + assert EncryptionService.MIN_ENCRYPTED_LENGTH == 65 + + def test_layout_sizes(self): + payload = enc("hello") + assert len(payload) == 32 + 4 + 1 + 12 + len(b"hello") + 16 + + def test_hmac_covers_everything_after_itself(self): + import hashlib + import hmac + payload = enc("hello") + expected = hmac.new(HMAC_KEY, payload[32:], hashlib.sha256).digest() + assert payload[:32] == expected + + def test_key_id_recorded_before_marker(self): + payload = enc("hello", key_id=12345) + assert struct.unpack(">I", payload[32:36])[0] == 12345 + + def test_marker_recorded_after_key_id(self): + payload = enc("hello") + assert payload[36] == TypeMarker.STRING + + def test_key_id_from_payload(self): + assert EncryptionService.key_id_from_payload(enc("x", key_id=999)) == 999 + assert EncryptionService.key_id_from_payload(None) is None + assert EncryptionService.key_id_from_payload(b"\x00" * 10) is None # too short + + +# ---- round trips for every supported type ---- + +class TestRoundTrip: + @pytest.mark.parametrize("value", [ + "hello", "", "café-ümlaut-漢字", "a" * 10000, + ]) + def test_string(self, value): + assert dec(enc(value)) == value + + def test_bytes(self): + payload = enc(b"\x00\x01\x02\xff") + out = dec(payload) + assert out == b"\x00\x01\x02\xff" + assert isinstance(out, bytes) + + @pytest.mark.parametrize("value", [0, 1, -1, 1234567890123, -1234567890123, 2 ** 62]) + def test_int(self, value): + assert dec(enc(value)) == value + + @pytest.mark.parametrize("value", [0.0, 3.141592653589793, -2.5, 1e300]) + def test_float(self, value): + assert dec(enc(value)) == value + + @pytest.mark.parametrize("value", [True, False]) + def test_bool(self, value): + assert dec(enc(value)) is value + + def test_decimal(self): + value = Decimal("12345.6789") + assert dec(enc(value)) == value + + def test_local_date(self): + value = date(2023, 6, 15) + assert dec(enc(value)) == value + + def test_local_datetime(self): + value = datetime(2023, 6, 15, 13, 45, 30) + assert dec(enc(value)) == value + + def test_none_passthrough(self): + assert enc(None) is None + assert dec(None) is None + + +# ---- target type coercion ---- + +class TestTargetType: + def test_coerce_to_str(self): + assert dec(enc(123), target_type=str) == "123" + + def test_coerce_to_int(self): + assert dec(enc("42"), target_type=int) == 42 + + def test_coerce_to_bool(self): + assert dec(enc("yes"), target_type=bool) is True + assert dec(enc("no"), target_type=bool) is False + + +# ---- fail-closed behavior ---- + +class TestFailClosed: + def test_too_short_raises_integrity(self): + with pytest.raises(IntegrityCheckError): + dec(b"\x00" * 10) + + def test_tampered_body_fails_hmac(self): + payload = bytearray(enc("hello")) + payload[-1] ^= 0xFF # flip a ciphertext/tag byte + with pytest.raises(IntegrityCheckError): + dec(bytes(payload)) + + def test_tampered_key_id_fails_hmac(self): + payload = bytearray(enc("hello")) + payload[34] ^= 0xFF # key id is inside the HMAC-covered region + with pytest.raises(IntegrityCheckError): + dec(bytes(payload)) + + @pytest.mark.parametrize("body", [ + b"", # tag only + struct.pack(">I", 7), # tag + key id + struct.pack(">I", 7) + bytes([TypeMarker.STRING]), # + marker, no IV + ]) + def test_signed_but_too_short_payload_is_an_integrity_error(self, body): + # Signed with the right HMAC key, so only the length check refuses it; + # without it the framing would fail with a bare IndexError/ValueError. + payload = hmac.new(HMAC_KEY, body, hashlib.sha256).digest() + body + with pytest.raises(IntegrityCheckError, match="too short"): + dec(payload) + + def test_wrong_data_key_fails_gcm_not_hmac(self): + # Decrypt with a different data key. The HMAC still matches (same HMAC + # key and body), so this has to fail at GCM with DecryptionError, never + # with IntegrityCheckError. + import hashlib + import hmac + payload = enc("hello") + wrong_dk = bytes([(b + 1) % 256 for b in DATA_KEY]) + with pytest.raises(DecryptionError): + dec(payload, dk=wrong_dk) + _ = (hashlib, hmac) + + def test_bad_data_key_length(self): + with pytest.raises(InvalidKeyError): + EncryptionService.encrypt("x", b"short", HMAC_KEY, key_id=1) + + def test_empty_hmac_key(self): + with pytest.raises(InvalidKeyError): + EncryptionService.encrypt("x", DATA_KEY, b"", key_id=1) + + @pytest.mark.parametrize("bad", [-1, 2 ** 32, True, "7", 1.5]) + def test_bad_key_id(self, bad): + with pytest.raises(EncryptionError): + EncryptionService.encrypt("x", DATA_KEY, HMAC_KEY, key_id=bad) + + +# ---- key rotation: value carries the id it was written with ---- + +class TestKeyId: + def test_payload_carries_write_key_id(self): + for kid in (0, 1, 7, 2 ** 32 - 1): + assert EncryptionService.key_id_from_payload(enc("v", key_id=kid)) == kid + + +# ---- randomized IV ---- + +def test_iv_is_random_per_call(): + a = enc("same-value") + b = enc("same-value") + assert a != b # fresh IV each time + assert dec(a) == dec(b) == "same-value" + + +# ---- AES-128 ---- + +def test_aes_128_round_trip(): + dk16 = bytes(range(16)) + payload = EncryptionService.encrypt("x", dk16, HMAC_KEY, EncryptionAlgorithm.AES_128_GCM, key_id=1) + assert EncryptionService.decrypt(payload, dk16, HMAC_KEY, EncryptionAlgorithm.AES_128_GCM) == "x" + + +# ---- wipe ---- + +def test_wipe_zeroes_bytearray(): + buf = bytearray(b"secret-key-material") + EncryptionService.wipe(buf) + assert buf == bytearray(len(buf)) + + +def test_datetime_tz_normalization_matches_millis_contract(): + # Under the TIMESTAMP marker, a timezone-naive datetime is taken as UTC. + naive = datetime(2023, 1, 1, 0, 0, 0) + millis = EncryptionService._to_millis(naive, "TIMESTAMP") + assert millis == int(datetime(2023, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) + + +# ---- marker coverage: generic, time, and reading an externally-written INTEGER ---- + +class TestMarkerCoverage: + def test_generic_falls_back_to_str(self): + class Thing: + def __str__(self): + return "thing-repr" + assert dec(enc(Thing())) == "thing-repr" + + def test_time_round_trips_as_iso_text(self): + from datetime import time + value = time(13, 45, 30) + # LOCAL_TIME is written as ISO text and read back as that text. + assert dec(enc(value)) == value.isoformat() + + def test_reads_externally_written_integer_marker(self): + # This wrapper writes integers as LONG; the 4-byte INTEGER marker (2) is still understood on read. + import hashlib + import hmac + import struct + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + iv = b"\x09" * 12 + sealed = AESGCM(DATA_KEY).encrypt(iv, struct.pack(">i", 42), None) + body = struct.pack(">I", KEY_ID) + bytes([TypeMarker.INTEGER]) + iv + sealed + payload = hmac.new(HMAC_KEY, body, hashlib.sha256).digest() + body + assert dec(payload) == 42 + + def test_decimal_plain_not_scientific(self): + # The wire contract requires plain notation for a Decimal that would + # otherwise print in scientific notation. A round trip can't catch a + # scientific-notation serializer, because "1E+2" decodes back equal to + # 100 (str(Decimal("1E+2")) == "1E+2"), so assert the bytes. + value = Decimal("1E+2") + assert EncryptionService.serialize_value(value, TypeMarker.BIG_DECIMAL) == b"100" + out = dec(enc(value)) + assert out == value + + +class TestAlgorithm: + def test_unsupported_algorithm_raises(self): + with pytest.raises(InvalidAlgorithmError): + EncryptionService.encrypt("x", DATA_KEY, HMAC_KEY, "AES-999-XYZ", key_id=1) + + +# ===================================================================== +# Edge cases, plus tests that pin behavior specific to Python. +# ===================================================================== + + +def _resign(payload: bytes, hmac_key: bytes) -> bytes: + """Re-sign a payload whose body was edited, so a test can get past the + integrity check and exercise the decryption path itself.""" + body = payload[ES_TAG:] + return hmac.new(hmac_key, body, hashlib.sha256).digest() + body + + +ES_TAG = 32 # HMAC_TAG_LENGTH +ES_KEYID = 4 # KEY_ID_LENGTH +MARKER_OFFSET = ES_TAG + ES_KEYID + + +# ---- serialize_value: markers it can/can't write ---- + +class TestSerializeValue: + def test_raises_for_unknown_marker(self): + # 12345 is no marker at all, so any value is refused. + with pytest.raises(EncryptionFailedError, match="Unsupported type marker: 12345"): + EncryptionService.serialize_value("x", 12345) + + def test_long_overflow_raises_without_leaking_the_value(self): + # Every Python int but bool uses the LONG marker, so one outside the + # signed 64-bit range must be refused. The error must not expose the + # integer through its message, __cause__, or __context__. + too_big = 2 ** 63 # one past the signed 64-bit max + with pytest.raises(EncryptionFailedError) as ei: + enc(too_big) + err = ei.value + assert err.data_type == "LONG" + assert str(too_big) not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + def test_long_underflow_raises_without_leaking_the_value(self): + # The lower half of the range check, held to the same no-leak rule as + # the upper half. (test_long_out_of_range_keeps_its_own_message pins + # the message.) + too_small = -(2 ** 63) - 1 + with pytest.raises(EncryptionFailedError) as ei: + enc(too_small) + err = ei.value + assert err.data_type == "LONG" + assert str(too_small) not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + @pytest.mark.parametrize("value", [Decimal("NaN"), Decimal("Infinity"), Decimal("-Infinity"), Decimal("sNaN")]) + def test_non_finite_decimal_is_refused(self, value): + with pytest.raises(EncryptionFailedError): + enc(value) + + def test_aware_time_is_refused(self): + # A local time of day has no offset on the wire; writing one would drop it. + with pytest.raises(EncryptionFailedError): + enc(time(10, 30, tzinfo=timezone.utc)) + + def test_aware_datetime_cannot_be_forced_into_local_date_time(self): + with pytest.raises(EncryptionFailedError): + EncryptionService.serialize_value(datetime(2024, 1, 1, tzinfo=timezone.utc), TypeMarker.LOCAL_DATE_TIME) + + @pytest.mark.parametrize("value,expected", [ + (date(999, 1, 2), b"0999-01-02"), + (datetime(999, 1, 2, 3, 4, 5, 678), b"0999-01-02T03:04:05.000678"), + ]) + def test_years_before_1000_keep_four_digits(self, value, expected): + # strftime("%Y") does not zero-pad on every platform; the reader needs + # four digits. + assert EncryptionService.serialize_value(value) == expected + assert dec(enc(value)) == value + + @pytest.mark.parametrize("micros,expected_millis", [ + (1500, 2), (2500, 3), (2499, 2), (-1500, -2), (-2500, -3), + ]) + def test_millis_round_half_away_from_zero(self, micros, expected_millis): + value = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(microseconds=micros) + assert EncryptionService._to_millis(value, "TIMESTAMP") == expected_millis + + def test_millis_are_exact_far_from_the_epoch(self): + value = datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=timezone.utc) + expected = (value - datetime(1970, 1, 1, tzinfo=timezone.utc)) // timedelta(milliseconds=1) + assert EncryptionService._to_millis(value, "TIMESTAMP") == expected + + @pytest.mark.parametrize("value,marker", [ + (date(2024, 1, 2), TypeMarker.LOCAL_DATE_TIME), # a date is not a date-time + ("not a date", TypeMarker.LOCAL_DATE), + ("SECRET-123", TypeMarker.LONG), + ("SECRET-123", TypeMarker.INTEGER), + (2 ** 40, TypeMarker.INTEGER), # out of the 32-bit range + ("SECRET-123", TypeMarker.DOUBLE), + ("SECRET-123", TypeMarker.TIMESTAMP), + ("SECRET-123", TypeMarker.DATE), + (Decimal("NaN"), TypeMarker.LONG), # TypeError: a Decimal is not an integer + (7, TypeMarker.BYTE_ARRAY), # bytes(7) would be 7 zero bytes + ("false", TypeMarker.BOOLEAN), # not truthiness + (1e300, TypeMarker.FLOAT), # OverflowError: too large for a 32-bit float + (time(3, 4, 5), TypeMarker.LOCAL_DATE_TIME), # a time of day is not a date-time + ]) + def test_value_that_does_not_fit_an_explicit_marker(self, value, marker): + # Mostly reachable only with an explicit marker. The error is a wrapper + # error, names the marker, and quotes nothing of the value. + with pytest.raises(EncryptionFailedError) as ei: + EncryptionService.serialize_value(value, marker) + err = ei.value + assert "SECRET" not in str(err) + assert err.__cause__ is None and err.__context__ is None + assert err.data_type == TypeMarker.name_for(marker) + + @pytest.mark.parametrize("marker", [TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP]) + def test_out_of_range_instant_is_refused_naming_its_marker(self, marker): + value = datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))) # after year 9999 in UTC + with pytest.raises(EncryptionFailedError, match="outside the range") as ei: + EncryptionService.serialize_value(value, marker) + assert ei.value.data_type == TypeMarker.name_for(marker) + + @pytest.mark.parametrize("value", [bytearray(b"\x00\x01\xff"), memoryview(b"\x00\x01\xff")], + ids=["bytearray", "memoryview"]) + def test_bytes_like_values_round_trip_as_byte_array(self, value): + # bytearray and memoryview (bytes is covered above) are accepted as + # BYTE_ARRAY, and the caller's buffer is left alone. + assert EncryptionService.serialize_value(value) == b"\x00\x01\xff" + assert dec(enc(value)) == b"\x00\x01\xff" + assert bytes(value) == b"\x00\x01\xff" + + @pytest.mark.parametrize("value", [1, 0]) + def test_int_is_not_written_as_boolean(self, value): + with pytest.raises(EncryptionFailedError) as ei: + EncryptionService.serialize_value(value, TypeMarker.BOOLEAN) + assert ei.value.data_type == "BOOLEAN" + + @pytest.mark.parametrize("value", [1e300, Decimal("1E+30"), 1.5]) + def test_non_int_as_long_gets_the_generic_message(self, value): + with pytest.raises(EncryptionFailedError, match="Cannot write a value of type") as ei: + EncryptionService.serialize_value(value, TypeMarker.LONG) + assert ei.value.data_type == "LONG" + + def test_instant_just_past_the_last_millisecond_is_refused(self): + # The clamp only undoes rounding: the first millisecond after year + # 9999 in UTC (no sub-millisecond part to round) is still refused. + value = datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-1))) # 10000-01-01T00:00Z + with pytest.raises(EncryptionFailedError, match="outside the range"): + EncryptionService.serialize_value(value) + + def test_int_subclass_is_written_as_long(self): + # TypeMarker.from_object sends any int but bool (an IntEnum, say) + # to LONG. + from enum import IntEnum + + class Level(IntEnum): + HIGH = 7 + + assert EncryptionService.serialize_value(Level.HIGH) == EncryptionService.serialize_value(7) + assert dec(enc(Level.HIGH)) == 7 + + def test_integer_like_value_is_accepted_as_long(self): + # Anything with __index__ (numpy integer types, for example) is + # accepted as LONG, as it is as INTEGER. + class Index: + def __index__(self): + return 5 + + assert EncryptionService.serialize_value(Index(), TypeMarker.LONG) == struct.pack(">q", 5) + + def test_value_whose_str_fails_is_refused(self): + # str() of a huge int raises ValueError (the int-digit limit). + with pytest.raises(EncryptionFailedError) as ei: + EncryptionService.serialize_value(10 ** 5000, TypeMarker.STRING) + assert ei.value.__cause__ is None and ei.value.__context__ is None + + @pytest.mark.parametrize("value", [2 ** 63, -(2 ** 63) - 1]) + def test_long_out_of_range_keeps_its_own_message(self, value): + with pytest.raises(EncryptionFailedError, match="signed 64-bit range"): + EncryptionService.serialize_value(value) + + def test_datetime_written_as_local_date_keeps_only_the_date(self): + data = EncryptionService.serialize_value(datetime(2024, 1, 2, 3, 4, 5), TypeMarker.LOCAL_DATE) + assert data == b"2024-01-02" + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_DATE) == date(2024, 1, 2) + + @pytest.mark.parametrize("value", [ + datetime(1, 1, 1, 0, 30, tzinfo=timezone(timedelta(hours=1))), # before year 1 in UTC + datetime(9999, 12, 31, 23, 0, tzinfo=timezone(timedelta(hours=-2))), # after year 9999 in UTC + ]) + def test_timestamp_that_could_not_be_read_back_is_refused(self, value): + with pytest.raises(EncryptionFailedError): + enc(value) + + def test_timestamp_at_the_edges_of_the_range_round_trips(self): + for value in (datetime(9999, 12, 31, 23, 59, 59, 999000, tzinfo=timezone.utc), + datetime(1, 1, 1, tzinfo=timezone.utc)): + assert dec(enc(value)) == value + + def test_aware_datetime_max_keeps_its_last_millisecond(self): + # A common "never" value: rounding .999999 up would pass the end of + # the range, so it keeps the last representable millisecond instead. + value = datetime.max.replace(tzinfo=timezone.utc) + assert dec(enc(value)) == value.replace(microsecond=999000) + + def test_long_boundary_values_round_trip(self): + # The signed 64-bit edges serialize and decrypt back exactly. + for value in (2 ** 63 - 1, -(2 ** 63)): + assert dec(enc(value)) == value + + @pytest.mark.parametrize("value", [Color.RED, Masked("red")], ids=["str_enum", "overridden_str"]) + def test_str_subclass_is_stored_as_its_own_text(self, value): + # str() gives 'Color.RED' for the member and '***' for Masked. + assert EncryptionService.serialize_value(value) == b"red" + + def test_str_subclass_reads_back_as_plain_str(self): + out = dec(enc(Color.RED)) + assert out == "red" and type(out) is str + + @pytest.mark.parametrize("value,marker,expected", [ + (Color.RED, TypeMarker.GENERIC, b"Color.RED"), + (42, TypeMarker.STRING, b"42"), + (Decimal("1.5"), TypeMarker.STRING, b"1.5"), + ]) + def test_generic_and_non_str_under_string_keep_str_of_value(self, value, marker, expected): + assert EncryptionService.serialize_value(value, marker) == expected + + def test_object_that_only_claims_to_be_a_str_keeps_str_of_value(self, mocker): + # isinstance() trusts a faked __class__ (proxies, mocks) and picks + # STRING, but str.__str__ needs a real str, so the check is on type(). + proxy = mocker.MagicMock(spec=str) + proxy.__str__.return_value = "red" + assert EncryptionService.serialize_value(proxy) == b"red" + + +# ---- deserialize_value: reading every marker ---- + +class TestDeserializeExternalMarkers: + """This wrapper never writes some of these markers or forms, but it must + read every one.""" + + def test_reads_32bit_integer(self): + assert EncryptionService.deserialize_value(struct.pack(">i", 42), TypeMarker.INTEGER) == 42 + + def test_reads_32bit_float(self): + assert EncryptionService.deserialize_value(struct.pack(">f", 1.5), TypeMarker.FLOAT) == 1.5 + + def test_reads_date_marker_as_date(self): + millis = int(datetime(2026, 8, 11, tzinfo=timezone.utc).timestamp() * 1000) + out = EncryptionService.deserialize_value(struct.pack(">q", millis), TypeMarker.DATE) + assert out == date(2026, 8, 11) + + def test_reads_time_marker_as_datetime(self): + millis = int(datetime(2026, 8, 11, 12, 30, 45, tzinfo=timezone.utc).timestamp() * 1000) + out = EncryptionService.deserialize_value(struct.pack(">q", millis), TypeMarker.TIME) + assert abs(out.timestamp() - millis / 1000.0) < 0.001 + + def test_reads_local_time_as_string(self): + data = EncryptionService.serialize_value("12:30:45", TypeMarker.LOCAL_TIME) + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_TIME) == "12:30:45" + + @pytest.mark.parametrize("text,expected", [ + # The local date-time forms the reader accepts: with or without seconds, + # and with 3, 6, or 9 fractional digits. A naive fromisoformat fails on + # the 9-digit (nanosecond) form on the Python 3.10 floor, so that form + # needs coverage. + ("2007-12-03T10:15", datetime(2007, 12, 3, 10, 15)), + ("2007-12-03T10:15:30", datetime(2007, 12, 3, 10, 15, 30)), + ("2007-12-03T10:15:30.123", datetime(2007, 12, 3, 10, 15, 30, 123000)), + ("2007-12-03T10:15:30.123456", datetime(2007, 12, 3, 10, 15, 30, 123456)), + # nanoseconds truncated to microseconds (datetime has no finer precision) + ("2007-12-03T10:15:30.123456789", datetime(2007, 12, 3, 10, 15, 30, 123456)), + # a suffix after the fraction is kept, whatever the fraction's length + ("2007-12-03T10:15:30.123456789+00:00", datetime(2007, 12, 3, 10, 15, 30, 123456, tzinfo=timezone.utc)), + ("2007-12-03T10:15:30.123+00:00", datetime(2007, 12, 3, 10, 15, 30, 123000, tzinfo=timezone.utc)), + ]) + def test_reads_every_accepted_local_date_time_form(self, text, expected): + data = text.encode("utf-8") + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_DATE_TIME) == expected + + def test_reads_own_local_date_time_write_form(self): + # Round-trip the form this wrapper writes for a whole-second value, + # which has no fraction. + value = datetime(2023, 6, 15, 13, 45, 30) + data = EncryptionService.serialize_value(value, TypeMarker.LOCAL_DATE_TIME) + assert EncryptionService.deserialize_value(data, TypeMarker.LOCAL_DATE_TIME) == value + + def test_unparseable_local_date_time(self): + with pytest.raises(TypeConversionError): + EncryptionService.deserialize_value(b"not a datetime", TypeMarker.LOCAL_DATE_TIME) + + def test_wrong_width_for_marker(self): + with pytest.raises(EncryptionError) as ei: + EncryptionService.deserialize_value(b"ab", TypeMarker.INTEGER) + assert "Expected 4 bytes for INTEGER, got 2" in str(ei.value) + + def test_unparseable_big_decimal(self): + with pytest.raises(TypeConversionError): + EncryptionService.deserialize_value(b"not a number", TypeMarker.BIG_DECIMAL) + + def test_unparseable_local_date(self): + with pytest.raises(TypeConversionError): + EncryptionService.deserialize_value(b"not a date", TypeMarker.LOCAL_DATE) + + @pytest.mark.parametrize("marker,data", [ + (TypeMarker.LOCAL_DATE, b"SECRET-ssn-123-45-6789"), + (TypeMarker.LOCAL_DATE_TIME, b"SECRET-ssn-123-45-6789"), + (TypeMarker.BIG_DECIMAL, b"SECRET-ssn-123-45-6789"), + # UnicodeDecodeError.object holds the raw plaintext bytes. + (TypeMarker.STRING, b"SECRET-ssn-\xff"), + ]) + def test_deserialize_error_does_not_leak_plaintext(self, marker, data): + # A value that passes HMAC and GCM but doesn't parse as its declared + # type must not leak its plaintext through the error message, + # __cause__, or __context__. This is the read-side counterpart of the + # encrypt-side leak tests. + with pytest.raises(TypeConversionError) as ei: + EncryptionService.deserialize_value(data, marker) + err = ei.value + assert "SECRET" not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + @pytest.mark.parametrize("marker", [TypeMarker.DATE, TypeMarker.TIME, TypeMarker.TIMESTAMP]) + @pytest.mark.parametrize("millis", [2 ** 63 - 1, -(2 ** 63), 10 ** 15]) + def test_out_of_range_epoch_millis_is_a_type_conversion_error(self, marker, millis): + # Another writer can store epoch millis no datetime can hold; the + # resulting OverflowError must surface as the wrapper's error. + with pytest.raises(TypeConversionError) as ei: + EncryptionService.deserialize_value(struct.pack(">q", millis), marker) + assert ei.value.__cause__ is None and ei.value.__context__ is None + + def test_unknown_marker_on_read(self): + with pytest.raises(EncryptionError) as ei: + EncryptionService.deserialize_value(b"x", 12345) + assert "Unsupported type marker: 12345" in str(ei.value) + + +# ---- decrypt path: unknown marker inside a (re-signed) payload ---- + +def test_decrypt_rejects_unknown_marker_in_payload(): + payload = bytearray(enc("123-45-6789")) + payload[MARKER_OFFSET] = 77 # overwrite the marker byte + resigned = _resign(bytes(payload), HMAC_KEY) + with pytest.raises(DecryptionError) as ei: + dec(resigned) + assert "Unknown type marker: 77" in str(ei.value) + + +# ---- decrypt-path data-key validation (past length check, before GCM) ---- + +def test_decrypt_rejects_wrong_length_data_key(): + payload = enc("123-45-6789") + with pytest.raises(InvalidKeyError): + EncryptionService.decrypt(payload, bytes(range(16)), HMAC_KEY) + + +# ---- missing data key / hmac key messages ---- + +def test_missing_data_key_message(): + with pytest.raises(EncryptionError) as ei: + EncryptionService.encrypt("x", None, HMAC_KEY, key_id=1) + assert "got None" in str(ei.value) + + +# ---- target-type coercion edge cases ---- + +class TestTargetTypeEdges: + def test_boolean_db_spellings_true(self): + for v in ("t", "true", "TRUE", "y", "yes", "1"): + assert dec(enc(v), target_type=bool) is True + + def test_boolean_db_spellings_false(self): + for v in ("f", "false", "n", "no", "0", ""): + assert dec(enc(v), target_type=bool) is False + + def test_already_target_type_passes_through(self): + assert dec(enc("42"), target_type=str) == "42" + + def test_unknown_target_type_raises(self): + with pytest.raises(TypeConversionError): + dec(enc("abc"), target_type=list) + + def test_uncoercible_value_raises(self): + with pytest.raises(TypeConversionError): + dec(enc("abc"), target_type=int) + + @pytest.mark.parametrize("value", [float("inf"), float("nan"), Decimal("Infinity")]) + def test_non_finite_to_int_is_a_type_conversion_error(self, value): + # int() raises OverflowError / ValueError here, outside the PEP 249 + # hierarchy unless it is converted. + with pytest.raises(TypeConversionError) as ei: + EncryptionService._convert_to_target_type(value, int) + assert ei.value.__cause__ is None + assert ei.value.__context__ is None + + @pytest.mark.parametrize("target_type", [int, float, Decimal]) + def test_target_type_coercion_failure_does_not_leak_plaintext(self, target_type): + # A value that decrypts but can't be coerced to the requested + # target_type must not leak its plaintext through the error message, + # __cause__, or __context__. int() and float() quote their input + # ("invalid literal for int() ... 'SECRET...'"), so this path needs its + # own test alongside the deserialize and encrypt leak tests. + secret = "SECRET-ssn-123-45-6789" + with pytest.raises(TypeConversionError) as ei: + dec(enc(secret), target_type=target_type) + err = ei.value + assert "SECRET" not in str(err) + assert err.__cause__ is None + assert err.__context__ is None + + def test_float_to_int_target_truncates_python_difference(self): + # int(1.5) truncates to 1 rather than raising. target_type is an + # explicit opt-in and default reads return strings, so Python keeps its + # native semantics. The test pins this so any change gets noticed. + assert dec(enc(1.5), target_type=int) == 1 + + +# ---- key and plaintext buffers ---- + +def test_encrypt_wipes_the_buffer_aes_gcm_saw_and_copies_no_key(monkeypatch): + # The keys reach AES-GCM and HMAC as given (no immutable copy of a + # bytearray key), and the plaintext buffer AES-GCM read is the one wiped. + from types import SimpleNamespace + + from cryptography.hazmat.primitives.ciphers.aead import AESGCM + + from aws_advanced_python_wrapper.encryption import encryption_service + seen = {} + + class SpyAESGCM: + def __init__(self, key): + seen["data_key"] = key + self._real = AESGCM(key) + + def encrypt(self, iv, plaintext, aad): + seen["plaintext"] = plaintext + return self._real.encrypt(iv, plaintext, aad) + + def spy_hmac_new(key, msg, digestmod): + seen["hmac_key"] = key + return hmac.new(key, msg, digestmod) + + monkeypatch.setattr(encryption_service, "AESGCM", SpyAESGCM) + monkeypatch.setattr(encryption_service, "hmac", SimpleNamespace(new=spy_hmac_new, compare_digest=hmac.compare_digest)) + data_key, hmac_key = bytearray(DATA_KEY), bytearray(HMAC_KEY) + EncryptionService.encrypt("secret", data_key, hmac_key, key_id=1) + assert seen["data_key"] is data_key + assert seen["hmac_key"] is hmac_key + assert isinstance(seen["plaintext"], bytearray) + assert seen["plaintext"] == bytearray(len(seen["plaintext"])) + + +@pytest.mark.parametrize("dk_type,hk_type", [ + (memoryview, memoryview), (bytearray, memoryview), (memoryview, bytes)]) +def test_memoryview_keys_are_accepted(dk_type, hk_type): + # BytesLike includes memoryview; hmac does not accept one directly. + dk, hk = dk_type(DATA_KEY), hk_type(HMAC_KEY) + payload = EncryptionService.encrypt("v", dk, hk, key_id=1) + assert EncryptionService.decrypt(payload, dk, hk) == "v" + assert EncryptionService.decrypt(payload, DATA_KEY, HMAC_KEY) == "v" + + +# ---- immutability: the caller's value is not mutated ---- + +def test_encrypt_does_not_mutate_caller_bytes(): + value = bytearray(b"123-45-6789") + snapshot = bytes(value) + enc(bytes(value)) + assert bytes(value) == snapshot + + +# ---- precision contract ---- + +class TestPrecision: + def test_timestamp_marker_keeps_millisecond(self): + # A value read via the TIMESTAMP marker keeps millisecond precision + # (epoch-millis storage). + millis = int(datetime(2026, 8, 11, 12, 30, 45, 123000, tzinfo=timezone.utc).timestamp() * 1000) + out = EncryptionService.deserialize_value(struct.pack(">q", millis), TypeMarker.TIMESTAMP) + assert abs(out.timestamp() * 1000 - millis) < 1.0 + + def test_aware_datetime_keeps_its_instant(self): + # An aware datetime is written as TIMESTAMP (epoch millis), so the + # instant survives and it reads back as aware UTC, to the millisecond. + v = datetime(2024, 1, 1, 12, 0, 0, 123456, tzinfo=timezone(timedelta(hours=5))) + payload = enc(v) + assert payload[MARKER_OFFSET] == TypeMarker.TIMESTAMP + out = dec(payload) + assert out == v.replace(microsecond=123000) + assert out.utcoffset() == timedelta(0) + + def test_naive_datetime_keeps_microseconds(self): + # A naive datetime is written as LOCAL_DATE_TIME (ISO text) with its + # fraction, so it reads back equal, to the microsecond. + v = datetime(2026, 8, 11, 12, 30, 45, 123456) + payload = enc(v) + assert payload[MARKER_OFFSET] == TypeMarker.LOCAL_DATE_TIME + out = dec(payload) + assert out == v + assert out.microsecond == 123456 + + def test_whole_second_naive_datetime_text_is_unchanged(self): + # isoformat() leaves out a zero fraction, so a whole-second value is + # still written as YYYY-MM-DDTHH:MM:SS and its stored text stays the + # same. + v = datetime(2026, 8, 11, 12, 30, 45) + assert EncryptionService.serialize_value(v) == b"2026-08-11T12:30:45" + + +# ---- no-UTF-8-form string is refused without quoting the plaintext ---- + +def test_lone_surrogate_string_refused_without_quoting_plaintext(): + secret = "secret-\ud800-value" # lone surrogate: no valid UTF-8 form + with pytest.raises(EncryptionError) as ei: + enc(secret) + # UnicodeEncodeError holds the plaintext in .object. The production code + # raises outside the except block so that error isn't attached as + # __cause__ or __context__. Check the plaintext isn't reachable at all. + assert "secret" not in str(ei.value) + assert ei.value.__cause__ is None + assert ei.value.__context__ is None + + +# ---- GCM auth independence from HMAC ---- + +def test_gcm_auth_tag_bound_to_data_key(): + # A payload encrypted+signed under a different data key (same HMAC key) must + # pass the HMAC check but fail GCM when decrypted with the original data key. + other_dk = bytes([(b + 7) % 256 for b in DATA_KEY]) + other = EncryptionService.encrypt("v", other_dk, HMAC_KEY, key_id=KEY_ID) + with pytest.raises(DecryptionError): + dec(other) # HMAC matches (HMAC_KEY), data key wrong for DATA_KEY decrypt + + +# ---- exception hierarchy: lenient read mode relies on this ---- + +class TestExceptionHierarchy: + """The read path's lenient mode (encryption_return_unverified_data) will + catch IntegrityCheckError and let every other failure through. These tests + pin the class hierarchy that makes `except IntegrityCheckError` work. + """ + + def test_integrity_check_error_classifies_as_integrity_error(self): + # SQLAlchemy takes the first PEP 249 class in the MRO, so + # IntegrityError has to come before EncryptionError's OperationalError. + from aws_advanced_python_wrapper.pep249 import (IntegrityError, + OperationalError) + mro = IntegrityCheckError.__mro__ + assert mro.index(IntegrityError) < mro.index(OperationalError) + sqlalchemy_exc = pytest.importorskip("sqlalchemy.exc") + wrapped = sqlalchemy_exc.DBAPIError.instance("SELECT 1", {}, IntegrityCheckError("x"), Exception) + assert isinstance(wrapped, sqlalchemy_exc.IntegrityError) + + def test_integrity_and_decryption_are_distinct_subclasses(self): + assert issubclass(IntegrityCheckError, EncryptionError) + assert issubclass(DecryptionError, EncryptionError) + assert not issubclass(DecryptionError, IntegrityCheckError) + + def test_tampered_value_is_catchable_as_integrity_only(self): + payload = bytearray(enc("hello")) + payload[-1] ^= 0xFF + # Lenient mode would swallow this... + with pytest.raises(IntegrityCheckError): + dec(bytes(payload)) + + def test_wrong_key_is_not_an_integrity_error(self): + # ...but it must not swallow a wrong-key failure. That raises + # DecryptionError, which is not an IntegrityCheckError. + wrong_dk = bytes([(b + 1) % 256 for b in DATA_KEY]) + with pytest.raises(DecryptionError): + dec(enc("hello"), dk=wrong_dk) + try: + dec(enc("hello"), dk=wrong_dk) + except IntegrityCheckError: # pragma: no cover - must not happen + pytest.fail("wrong-key failure must not be an IntegrityCheckError") + except DecryptionError: + pass diff --git a/tests/unit/test_key_management_utility.py b/tests/unit/test_key_management_utility.py new file mode 100644 index 000000000..f8ae7bf05 --- /dev/null +++ b/tests/unit/test_key_management_utility.py @@ -0,0 +1,320 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import logging +from typing import Any, List, Tuple +from unittest.mock import MagicMock, create_autospec + +import boto3 +import pytest +from botocore.stub import Stubber + +from aws_advanced_python_wrapper.encryption import \ + key_management_utility as kmu_module +from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +from aws_advanced_python_wrapper.encryption.key_management_utility import \ + KeyManagementUtility +from aws_advanced_python_wrapper.encryption.key_manager import ( + GeneratedDataKey, KeyManager) +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.models import ( + ColumnEncryptionConfig, KeyMetadata, mask_arn) +from aws_advanced_python_wrapper.encryption.sql_dialect import (MYSQL, PG, + SqlDialect, + fetch_rows) +from aws_advanced_python_wrapper.errors import (EncryptionConfigError, + InvalidAlgorithmError, + KeyManagementError) + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" +ALIAS_ARN = "arn:aws:kms:us-east-1:123456789012:alias/python-kms-encryption-1700000000000" +ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/kiro-admin-role/kiro-admin-session" + + +class RecordingConnection: + """A raw-driver-shaped connection that records SQL and must never be + committed, rolled back, or closed by the utility.""" + + def __init__(self): + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + self.rowcount = 1 + self.rows: List[Tuple[Any, ...]] = [] + self.commit = MagicMock(side_effect=AssertionError("utility must not commit")) + self.rollback = MagicMock(side_effect=AssertionError("utility must not roll back")) + self.close = MagicMock(side_effect=AssertionError("utility must not close")) + + def cursor(self): + conn = self + + class Cursor: + description = [("table_name",), ("column_name",)] + + def execute(self, sql, params=()): + conn.executed.append((sql, tuple(params))) + self.rowcount = conn.rowcount + + def fetchall(self): + return conn.rows + + def close(self): + pass + + return Cursor() + + +@pytest.fixture +def conn(): + return RecordingConnection() + + +def config(restricted=False): + return EncryptionConfig(kms_region="us-east-1", + allowed_master_key_arns=frozenset({ARN}) if restricted else frozenset()) + + +def utility(conn, restricted=False, engine="postgresql"): + kms = MagicMock() + u = KeyManagementUtility(conn, kms, config(restricted), engine=engine) + # Autospec, so a misspelled method fails here as it would in production. + u._key_manager = create_autospec(KeyManager, instance=True) + u._key_manager.generate_data_key.return_value = GeneratedDataKey( + bytearray(b"P" * 32), "ZWRr", b"h" * 32, "AES_256") + u._key_manager.store_key_metadata.side_effect = lambda km: KeyMetadata(**{**km.__dict__, "id": 11}) + u._metadata = create_autospec(MetadataManager, instance=True) + u._metadata.is_column_encrypted.return_value = False + return u, kms + + +class TestInitialize: + def test_generates_stores_and_upserts_metadata(self, conn): + u, _ = utility(conn) + assert u.initialize_encryption_for_column("users", "ssn", ARN) == 11 + stored = u._key_manager.store_key_metadata.call_args[0][0] + assert stored.master_key_arn == ARN and stored.key_spec == "AES_256" + assert stored.key_name.startswith("key-users-ssn-") + sql, params = conn.executed[-1] + assert sql.startswith("INSERT INTO encrypt.encryption_metadata") + assert "ON CONFLICT (table_name, column_name) DO UPDATE SET encryption_algorithm = " \ + "EXCLUDED.encryption_algorithm, key_id = EXCLUDED.key_id, updated_at = CURRENT_TIMESTAMP" in sql + assert params == ("users", "ssn", "AES-256-GCM", 11) + + def test_wipes_the_generated_plaintext(self, conn): + u, _ = utility(conn) + u.initialize_encryption_for_column("users", "ssn", ARN) + generated = u._key_manager.generate_data_key.return_value + assert generated.plaintext == bytearray(32) + + def test_wipes_the_plaintext_even_when_storing_fails(self, conn): + u, _ = utility(conn) + u._key_manager.store_key_metadata.side_effect = KeyManagementError("x") + with pytest.raises(KeyManagementError): + u.initialize_encryption_for_column("users", "ssn", ARN) + assert u._key_manager.generate_data_key.return_value.plaintext == bytearray(32) + + def test_mysql_upsert_grammar(self, conn): + u, _ = utility(conn, engine="mysql") + u.initialize_encryption_for_column("users", "ssn", ARN, "AES-128-GCM") + sql = conn.executed[-1][0] + assert "ON DUPLICATE KEY UPDATE encryption_algorithm = VALUES(encryption_algorithm), " \ + "key_id = VALUES(key_id), updated_at = CURRENT_TIMESTAMP" in sql + u._key_manager.generate_data_key.assert_called_with(ARN, "AES-128-GCM") + + def test_refuses_an_already_encrypted_column(self, conn): + u, _ = utility(conn) + u._metadata.is_column_encrypted.return_value = True + with pytest.raises(KeyManagementError, match="already encrypted"): + u.initialize_encryption_for_column("users", "ssn", ARN) + u._key_manager.generate_data_key.assert_not_called() + + def test_unsupported_algorithm(self, conn): + u, _ = utility(conn) + with pytest.raises(InvalidAlgorithmError): + u.initialize_encryption_for_column("users", "ssn", ARN, "DES") + + @pytest.mark.parametrize("args", [(None, "c", ARN), ("t", "", ARN), ("t", "c", None)]) + def test_required_arguments(self, conn, args): + u, _ = utility(conn) + with pytest.raises(ValueError): + u.initialize_encryption_for_column(*args) + + def test_statement_failure_is_wrapped(self, conn): + u, _ = utility(conn) + conn.cursor = MagicMock(side_effect=RuntimeError("fk violation")) + with pytest.raises(KeyManagementError, match="fk violation"): + u.initialize_encryption_for_column("users", "ssn", ARN) + + +class TestRotate: + def _current(self, u, arn=ARN, algorithm="AES-256-GCM"): + km = KeyMetadata(id=4, master_key_arn=arn, encrypted_data_key="e", hmac_key=b"h") + u._metadata.column_config.return_value = ColumnEncryptionConfig( + "users", "ssn", algorithm, 4, km if arn else None) + + def test_rotate_onto_the_current_master_key_needs_the_allow_list(self, conn): + u, _ = utility(conn, restricted=False) + with pytest.raises(ValueError, match="encryption_allowed_master_key_arns"): + u.rotate_data_key("users", "ssn") + + def test_rotate_keeping_the_current_master_key(self, conn): + u, _ = utility(conn, restricted=True) + self._current(u, algorithm="AES-128-GCM") + assert u.rotate_data_key("users", "ssn") == 11 + u._key_manager.generate_data_key.assert_called_with(ARN, "AES-128-GCM") + sql, params = conn.executed[-1] + assert sql.startswith("UPDATE encrypt.encryption_metadata SET key_id = %s") + assert params == (11, "users", "ssn") + + def test_rotate_onto_a_new_master_key(self, conn): + u, _ = utility(conn) + self._current(u) + other = ARN.replace("1234abcd", "eeeeeeee") + u.rotate_data_key("users", "ssn", other) + u._key_manager.generate_data_key.assert_called_with(other, "AES-256-GCM") + + def test_rotate_unknown_column(self, conn): + u, _ = utility(conn) + u._metadata.column_config.return_value = None + with pytest.raises(KeyManagementError, match="No kms_encryption configuration"): + u.rotate_data_key("users", "ssn", ARN) + + def test_rotate_with_missing_key_row_and_no_new_arn(self, conn): + u, _ = utility(conn, restricted=True) + self._current(u, arn=None) + with pytest.raises(KeyManagementError, match="no current master key"): + u.rotate_data_key("users", "ssn") + + def test_rotate_fails_if_no_row_was_updated(self, conn): + u, _ = utility(conn) + self._current(u) + conn.rowcount = 0 + with pytest.raises(KeyManagementError): + u.rotate_data_key("users", "ssn", ARN) + + +class TestRemoveAndQuery: + def test_remove_deletes_only_the_metadata_row(self, conn): + u, _ = utility(conn) + assert u.remove_encryption_for_column("users", "ssn") is True + assert len(conn.executed) == 1 + sql, params = conn.executed[0] + assert sql.startswith("DELETE FROM encrypt.encryption_metadata ") + assert "key_storage" not in sql + assert params == ("users", "ssn") + + def test_remove_reports_nothing_removed(self, conn): + u, _ = utility(conn) + conn.rowcount = 0 + assert u.remove_encryption_for_column("users", "ssn") is False + + def test_columns_using_key(self, conn): + u, _ = utility(conn) + conn.rows = [("orders", "card"), ("users", "ssn")] + assert u.columns_using_key(4) == ["orders.card", "users.ssn"] + assert conn.executed[0][1] == (4,) + + +class TestMasterKeys: + def test_create_master_key_with_alias(self, conn): + u, kms = utility(conn) + u._key_manager.create_master_key.return_value = ARN + assert u.create_master_key("d") == ARN + alias = kms.create_alias.call_args.kwargs + assert alias["AliasName"].startswith("alias/python-kms-encryption-") + assert alias["TargetKeyId"] == ARN + + def test_alias_failure_is_not_fatal(self, conn): + u, kms = utility(conn) + u._key_manager.create_master_key.return_value = ARN + kms.create_alias.side_effect = RuntimeError("AlreadyExists") + assert u.create_master_key("d") == ARN + + # AWS KMS's own texts: they name the alias, and an access denial names + # the caller's role session. + @pytest.mark.parametrize("code, text", [ + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:CreateAlias on resource: " + f"{ALIAS_ARN} because no identity-based policy allows the kms:CreateAlias action", + id="access-denied"), + pytest.param("AlreadyExistsException", f"An alias with the name {ALIAS_ARN} already exists", + id="already-exists"), + ]) + def test_alias_failure_warning_masks_the_arns_kms_quotes(self, conn, caplog, code, text): + kms = boto3.client("kms", region_name="us-east-1", aws_access_key_id="x", aws_secret_access_key="x") + u = KeyManagementUtility(conn, kms, config(), engine="postgresql") + u._key_manager = create_autospec(KeyManager, instance=True) + u._key_manager.create_master_key.return_value = ARN + with Stubber(kms) as stubber, caplog.at_level(logging.WARNING, logger=kmu_module.__name__): + stubber.add_client_error("create_alias", code, service_message=text, http_status_code=400) + assert u.create_master_key("d") == ARN + stubber.assert_no_pending_responses() + # By logger name: threads other tests leave behind also log into caplog. + warnings = [r.getMessage() for r in caplog.records + if r.name == kmu_module.__name__ and r.levelno == logging.WARNING] + assert len(warnings) == 1 + assert f"({code})" in warnings[0] and mask_arn(ARN) in warnings[0] + assert "arn:aws:kms:***:***:***" in warnings[0] + for identifier in (ARN, ALIAS_ARN, ROLE_SESSION_ARN, "123456789012", "kiro-admin-role", "kiro-admin-session"): + assert identifier not in warnings[0] + + def test_no_alias(self, conn): + u, kms = utility(conn) + u._key_manager.create_master_key.return_value = ARN + u.create_master_key("d", create_alias=False) + kms.create_alias.assert_not_called() + + +class TestEngineInference: + def test_requires_arguments(self, conn): + with pytest.raises(ValueError): + KeyManagementUtility(None, MagicMock(), config()) + + def test_unknown_driver(self, conn): + with pytest.raises(EncryptionConfigError): + KeyManagementUtility(conn, MagicMock(), config()) + + def test_infers_from_driver_module_and_wrapper_connection(self): + pg_conn = type("Connection", (), {"__module__": "psycopg"})() + mysql_conn = type("CMySQLConnection", (), {"__module__": "mysql.connector.connection_cext"})() + wrapper = type("AwsWrapperConnection", (), {"target_connection": mysql_conn})() + assert SqlDialect.for_connection(pg_conn) is PG + assert SqlDialect.for_connection(mysql_conn) is MYSQL + assert SqlDialect.for_connection(wrapper) is MYSQL + assert SqlDialect.for_name("PostgreSQL") is PG + + def test_from_driver_dialect(self): + assert SqlDialect.for_driver_dialect(MagicMock(dialect_code="psycopg")) is PG + assert SqlDialect.for_driver_dialect(MagicMock(dialect_code="mysql-connector-python")) is MYSQL + with pytest.raises(EncryptionConfigError): + SqlDialect.for_driver_dialect(MagicMock(dialect_code="generic")) + + +def test_fetch_rows_lower_cases_keys_and_handles_no_result(): + conn = RecordingConnection() + conn.rows = [("t", "c")] + assert fetch_rows(conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] + + +def test_fetch_rows_accepts_dict_rows(): + # A connection opened with a dict-like row factory (psycopg dict_row) + # returns mappings; their keys are lower-cased like tuple rows' names. + conn = RecordingConnection() + conn.rows = [{"TABLE_NAME": "t", "column_name": "c"}] # type: ignore[list-item] + assert fetch_rows(conn, "SELECT") == [{"table_name": "t", "column_name": "c"}] + + +def test_columns_using_key_with_dict_rows(conn): + conn.rows = [{"table_name": "users", "column_name": "ssn"}] # type: ignore[list-item] + u, _ = utility(conn) + assert u.columns_using_key(3) == ["users.ssn"] diff --git a/tests/unit/test_key_manager.py b/tests/unit/test_key_manager.py new file mode 100644 index 000000000..0c660535e --- /dev/null +++ b/tests/unit/test_key_manager.py @@ -0,0 +1,847 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import base64 +import json +import logging +import threading +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack, contextmanager +from typing import Any, List, Optional, Tuple + +import boto3 +import pytest +from botocore.awsrequest import AWSResponse +from botocore.exceptions import ClientError, EndpointConnectionError +from botocore.stub import Stubber + +from aws_advanced_python_wrapper.encryption import key_manager as km_module +from aws_advanced_python_wrapper.encryption.algorithm import \ + EncryptionAlgorithm +from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +from aws_advanced_python_wrapper.encryption.data_key_cache import DataKeyCache +from aws_advanced_python_wrapper.encryption.key_manager import KeyManager +from aws_advanced_python_wrapper.encryption.models import KeyMetadata, mask_arn +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.errors import (InvalidKeyMetadataError, + KeyManagementError, + OperationalError, + UnauthorizedMasterKeyError) + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" +OTHER_ARN = "arn:aws:kms:us-east-1:123456789012:key/ffffffff-12ab-34cd-56ef-1234567890ab" +DATA_KEY = bytes(range(32)) +BLOB = b"kms-ciphertext-blob" +EDK = base64.b64encode(BLOB).decode() +# The caller's identity, as KMS names it when it denies a call. +ROLE_SESSION_ARN = "arn:aws:sts::123456789012:assumed-role/kiro-app-role/kiro-app-session" +MASKED_ROLE_SESSION_ARN = "arn:aws:sts:***:***:***" + + +class FakeCursor: + def __init__(self, db: "FakeDb"): + self._db = db + self.description: Optional[List[Tuple[str]]] = None + self.rowcount = -1 + self.lastrowid = None + self._rows: List[Tuple[Any, ...]] = [] + + def execute(self, sql, params=()): + self._db.executed.append((sql, tuple(params))) + if self._db.error is not None: + raise self._db.error + names, rows = self._db.result + self.description = [(n,) for n in names] if names else None + self._rows = list(rows) + self.rowcount = self._db.rowcount + self.lastrowid = self._db.lastrowid + + def fetchone(self): + return self._rows[0] if self._rows else None + + def fetchall(self): + return self._rows + + def close(self): + pass + + +class FakeDb: + def __init__(self): + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + self.result: Tuple[List[str], List[Tuple[Any, ...]]] = ([], []) + self.rowcount = 1 + self.lastrowid: Optional[int] = None + self.error: Optional[Exception] = None + + def cursor(self): + return FakeCursor(self) + + @contextmanager + def connection(self): + yield self + + +def config(**overrides) -> EncryptionConfig: + values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), + key_management_retry_backoff_base_sec=0.1) + values.update(overrides) + return EncryptionConfig(**values) # type: ignore[arg-type] + + +@pytest.fixture +def kms(): + client = boto3.client("kms", region_name="us-east-1", + aws_access_key_id="x", aws_secret_access_key="x") + with Stubber(client) as stubber: + yield client, stubber + stubber.assert_no_pending_responses() + + +@pytest.fixture +def db(): + return FakeDb() + + +LOGGERS = ("", "botocore", "botocore.parsers", "botocore.endpoint", "botocore.auth") +OUR_FILTERS = (km_module._NoKmsPlaintext, km_module._NoKmsRequestCredentials) + + +@pytest.fixture(autouse=True) +def no_filters(mocker): + """Neither filter installed when the test starts; every logger's filters + as they were when it ends. Every test in this module uses it, so the + module leaves the process's loggers and install flag as it found them.""" + loggers = [logging.getLogger(name) for name in LOGGERS] + saved = [list(lg.filters) for lg in loggers] + for lg in loggers: + lg.filters = [f for f in lg.filters if not isinstance(f, OUR_FILTERS)] + mocker.patch.object(km_module, "_filters_installed", False) + yield + for lg, filters in zip(loggers, saved): + lg.filters = filters + + +def manager(kms_client, db, cfg=None, cache=None, sleeps=None, sql=PG): + sleeps = sleeps if sleeps is not None else [] + return KeyManager(kms_client, db, sql, cfg or config(), + cache or DataKeyCache(10, 60, start_cleanup_thread=False), sleep=sleeps.append) + + +class TestDecryptDataKey: + def test_decrypts_with_key_id_and_caches(self, kms, db): + client, stubber = kms + stubber.add_response("decrypt", {"Plaintext": DATA_KEY, "KeyId": ARN}, + {"CiphertextBlob": BLOB, "KeyId": ARN}) + km = manager(client, db) + first = km.decrypt_data_key(EDK, ARN) + assert isinstance(first, bytearray) and first == DATA_KEY + # Second call is served from the cache: no further stubbed response. + first[:] = bytes(32) + assert km.decrypt_data_key(EDK, ARN) == DATA_KEY + + def test_unlisted_master_key_is_refused_before_kms(self, kms, db): + client, _ = kms # no stubbed responses: any KMS call would fail + km = manager(client, db) + with pytest.raises(UnauthorizedMasterKeyError) as err: + km.decrypt_data_key(EDK, OTHER_ARN) + assert "123456789012" not in str(err.value) + with pytest.raises(UnauthorizedMasterKeyError): + km.decrypt_data_key(EDK, None) + + def test_allow_list_is_checked_even_on_a_cache_hit(self, kms, db): + client, _ = kms + cache = DataKeyCache(10, 60, start_cleanup_thread=False) + cache.put(KeyManager.data_key_cache_key(EDK), DATA_KEY) + with pytest.raises(UnauthorizedMasterKeyError): + manager(client, db, cache=cache).decrypt_data_key(EDK, OTHER_ARN) + + @pytest.mark.parametrize("edk", [None, "", " "]) + def test_missing_encrypted_data_key(self, kms, db, edk): + with pytest.raises(InvalidKeyMetadataError): + manager(kms[0], db).decrypt_data_key(edk, ARN) + + @pytest.mark.parametrize("edk", ["not base64!!", "ZWRr\u200b==", "Y\u00e9=="], + ids=["bad-chars", "zero-width-space", "non-ascii"]) + def test_malformed_base64(self, kms, db, edk): + # A non-ASCII string makes b64decode raise a plain ValueError rather + # than binascii.Error; it must still be InvalidKeyMetadataError. + with pytest.raises(InvalidKeyMetadataError): + manager(kms[0], db).decrypt_data_key(edk, ARN) + + def test_base64_with_line_breaks_is_accepted(self, kms, db): + client, stubber = kms + stubber.add_response("decrypt", {"Plaintext": DATA_KEY}, {"CiphertextBlob": BLOB, "KeyId": ARN}) + wrapped = EDK[:8] + "\n" + EDK[8:] + assert manager(client, db).decrypt_data_key(wrapped, ARN) == DATA_KEY + + def test_no_master_key_arn_leaves_key_id_to_kms(self, kms, db): + # Only possible without an allow-list. KMS reads the key from the + # ciphertext; passing KeyId=None would fail boto3's validation. + client, stubber = kms + stubber.add_response("decrypt", {"Plaintext": DATA_KEY, "KeyId": ARN}, {"CiphertextBlob": BLOB}) + km = manager(client, db, config(allowed_master_key_arns=frozenset())) + assert km.decrypt_data_key(EDK, None) == bytearray(DATA_KEY) + + def test_non_retryable_kms_error_fails_immediately(self, kms, db): + client, stubber = kms + stubber.add_client_error("decrypt", "IncorrectKeyException", http_status_code=400) + sleeps: List[float] = [] + with pytest.raises(KeyManagementError) as err: + manager(client, db, sleeps=sleeps).decrypt_data_key(EDK, ARN) + assert sleeps == [] + assert err.value.operation == "DECRYPT_DATA_KEY" + assert isinstance(err.value, OperationalError) + assert not isinstance(err.value, UnauthorizedMasterKeyError) + + +class TestRetries: + def test_throttling_is_retried_with_backoff(self, kms, db): + client, stubber = kms + stubber.add_client_error("decrypt", "ThrottlingException", http_status_code=400) + stubber.add_client_error("decrypt", "KMSInternalException", http_status_code=500) + stubber.add_response("decrypt", {"Plaintext": DATA_KEY}, {"CiphertextBlob": BLOB, "KeyId": ARN}) + sleeps: List[float] = [] + assert manager(client, db, sleeps=sleeps).decrypt_data_key(EDK, ARN) == DATA_KEY + assert len(sleeps) == 2 + assert 0.1 <= sleeps[0] <= 0.125 + assert 0.15 <= sleeps[1] <= 0.25 + + def test_retries_stop_at_the_configured_maximum(self, kms, db): + client, stubber = kms + for _ in range(3): + stubber.add_client_error("decrypt", "ServiceUnavailable", http_status_code=503) + sleeps: List[float] = [] + cfg = config(key_management_max_retries=2) + with pytest.raises(KeyManagementError, match="3 attempt"): + manager(client, db, cfg, sleeps=sleeps).decrypt_data_key(EDK, ARN) + assert len(sleeps) == 2 + + def test_429_and_network_errors_are_retryable(self): + from botocore.exceptions import ClientError + throttled = ClientError({"Error": {"Code": "Other"}, "ResponseMetadata": {"HTTPStatusCode": 429}}, "Decrypt") + assert KeyManager._is_retryable(throttled) + assert KeyManager._is_retryable(EndpointConnectionError(endpoint_url="https://kms")) + bad = ClientError({"Error": {"Code": "NotFoundException"}, "ResponseMetadata": {"HTTPStatusCode": 400}}, "D") + assert not KeyManager._is_retryable(bad) + assert not KeyManager._is_retryable(ValueError("x")) + + @pytest.mark.parametrize("status", [500, 502, 503, 504]) + def test_any_5xx_is_retryable_even_with_an_unlisted_code(self, status): + # A load balancer or VPC endpoint in front of KMS can answer with a + # code outside RETRYABLE_ERROR_CODES. + from botocore.exceptions import ClientError + err = ClientError({"Error": {"Code": "SomethingNew"}, "ResponseMetadata": {"HTTPStatusCode": status}}, "D") + assert KeyManager._is_retryable(err) + + def test_backoff_is_capped_and_floored(self, kms, db): + km = manager(kms[0], db, config(key_management_retry_backoff_base_sec=1.0)) + assert all(1.0 <= km._backoff_sec(0) <= 1.25 for _ in range(50)) + assert km._backoff_sec(10) == KeyManager.MAX_BACKOFF_SEC + huge = manager(kms[0], db, config(key_management_retry_backoff_base_sec=60.0)) + assert huge._backoff_sec(0) == KeyManager.MAX_BACKOFF_SEC + + def test_kms_client_has_botocore_retries_disabled(self): + session = boto3.Session(aws_access_key_id="x", aws_secret_access_key="x") + client = KeyManager.create_kms_client(session, config(kms_endpoint="http://localhost:4566")) + assert client.meta.region_name == "us-east-1" + assert client.meta.endpoint_url == "http://localhost:4566" + assert client.meta.config.retries["total_max_attempts"] == 1 + # botocore's 60 s defaults would let one blackholed call take minutes. + assert client.meta.config.connect_timeout == KeyManager.CONNECT_TIMEOUT_SEC + assert client.meta.config.read_timeout == KeyManager.READ_TIMEOUT_SEC + assert client.meta.config.connect_timeout < 60 and client.meta.config.read_timeout < 60 + + +def _assert_names_no_identifier(text: str) -> None: + for identifier in (ARN, ARN.rpartition("/")[2], ROLE_SESSION_ARN, "123456789012", "kiro-app-role", + "kiro-app-session"): + assert identifier not in text + + +def _key_manager_messages(caplog, level: int) -> List[str]: + # By logger name: threads other tests leave behind also log into caplog. + return [r.getMessage() for r in caplog.records if r.name == km_module.__name__ and r.levelno == level] + + +class TestQuotedKmsErrorsAreMasked: + # AWS KMS's own texts: they name the master key, and an access denial + # names the caller's role session. + @pytest.mark.parametrize("code, text", [ + pytest.param("DisabledException", f"{ARN} is disabled.", id="disabled"), + pytest.param("KMSInvalidStateException", f"{ARN} is pending deletion.", id="pending-deletion"), + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on resource: {ARN} " + "with an explicit deny in a resource-based policy", id="explicit-deny"), + pytest.param("AccessDeniedException", + f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:Decrypt on the resource " + "associated with this ciphertext because the resource does not exist in this Region, no " + "resource-based policies allow access, or a resource-based policy explicitly denies access", + id="wrong-region"), + ]) + def test_decrypt_failure_masks_the_arns_kms_quotes(self, kms, db, code, text): + client, stubber = kms + stubber.add_client_error("decrypt", code, service_message=text, http_status_code=400) + with pytest.raises(KeyManagementError) as err: + manager(client, db).decrypt_data_key(EDK, ARN) + message = str(err.value) + assert message.startswith("[KeyManager] KMS DECRYPT_DATA_KEY failed after 1 attempt(s): ") + assert f"An error occurred ({code}) when calling the Decrypt operation: " in message + assert (mask_arn(ARN) in message) == (ARN in text) + assert (MASKED_ROLE_SESSION_ARN in message) == (ROLE_SESSION_ARN in text) + _assert_names_no_identifier(message) + # The SDK's error keeps KMS's full text, with its code and response. + assert isinstance(err.value.__cause__, ClientError) + assert text in str(err.value.__cause__) + + def test_decrypt_failure_without_an_arn_quotes_kms_unchanged(self, kms, db): + client, stubber = kms + stubber.add_client_error("decrypt", "NotFoundException", service_message="Invalid arn us-east-1", + http_status_code=400) + with pytest.raises(KeyManagementError) as err: + manager(client, db).decrypt_data_key(EDK, ARN) + assert isinstance(err.value.__cause__, ClientError) + assert str(err.value) == ("[KeyManager] KMS DECRYPT_DATA_KEY failed after 1 attempt(s): " + f"{err.value.__cause__}") + assert str(err.value).endswith(": Invalid arn us-east-1") + + # KeyUnavailableException's text names the key as DisabledException's does. + # Throttling's text names none today; this one does, so the test doesn't + # depend on which retryable error quotes an ARN. + @pytest.mark.parametrize("code, text, status", [ + pytest.param("ThrottlingException", f"Rate exceeded for {ARN}.", 400, id="throttling"), + pytest.param("KeyUnavailableException", f"{ARN} is unavailable.", 500, id="key-unavailable"), + ]) + def test_retry_record_masks_the_arns_kms_quotes(self, kms, db, caplog, code, text, status): + client, stubber = kms + stubber.add_client_error("decrypt", code, service_message=text, http_status_code=status) + stubber.add_response("decrypt", {"Plaintext": DATA_KEY}, {"CiphertextBlob": BLOB, "KeyId": ARN}) + with caplog.at_level(logging.DEBUG, logger=km_module.__name__): + assert manager(client, db).decrypt_data_key(EDK, ARN) == DATA_KEY + retries = [m for m in _key_manager_messages(caplog, logging.DEBUG) if "retrying in" in m] + assert len(retries) == 1 + assert f"({code})" in retries[0] and mask_arn(ARN) in retries[0] + _assert_names_no_identifier(retries[0]) + + def test_validation_warning_masks_the_arns_kms_quotes(self, kms, db, caplog): + client, stubber = kms + text = (f"User: {ROLE_SESSION_ARN} is not authorized to perform: kms:DescribeKey on resource: {ARN} " + "because no identity-based policy allows the kms:DescribeKey action") + stubber.add_client_error("describe_key", "AccessDeniedException", service_message=text, http_status_code=400) + with caplog.at_level(logging.WARNING, logger=km_module.__name__): + assert manager(client, db).is_master_key_valid(ARN) is False + warnings = _key_manager_messages(caplog, logging.WARNING) + assert len(warnings) == 1 + assert "(AccessDeniedException)" in warnings[0] and MASKED_ROLE_SESSION_ARN in warnings[0] + assert mask_arn(ARN) in warnings[0] + _assert_names_no_identifier(warnings[0]) + + +class TestGenerateAndCreate: + @pytest.mark.parametrize("algorithm, spec", [ + (EncryptionAlgorithm.AES_256_GCM, "AES_256"), (EncryptionAlgorithm.AES_128_GCM, "AES_128")]) + def test_generate_data_key_sizes_the_key_for_the_algorithm(self, kms, db, algorithm, spec): + client, stubber = kms + key = DATA_KEY[:EncryptionAlgorithm.key_length(algorithm)] + stubber.add_response("generate_data_key", {"Plaintext": key, "CiphertextBlob": BLOB}, + {"KeyId": ARN, "KeySpec": spec}) + generated = manager(client, db).generate_data_key(ARN, algorithm) + assert generated.plaintext == key and isinstance(generated.plaintext, bytearray) + assert base64.b64decode(generated.encrypted_data_key) == BLOB + assert len(generated.hmac_key) == 32 + assert generated.key_spec == spec + assert "bytearray" not in repr(generated) and str(BLOB) not in repr(generated) + + def test_mis_sized_data_key_is_rejected_at_setup(self, kms, db): + client, stubber = kms + stubber.add_response("generate_data_key", {"Plaintext": DATA_KEY, "CiphertextBlob": BLOB}, + {"KeyId": ARN, "KeySpec": "AES_128"}) + with pytest.raises(KeyManagementError, match="32-byte"): + manager(client, db).generate_data_key(ARN, EncryptionAlgorithm.AES_128_GCM) + + def test_mis_sized_data_key_is_wiped(self, kms, db, monkeypatch): + wiped: List[bytearray] = [] + real = km_module.wipe + monkeypatch.setattr(km_module, "wipe", lambda buf: (wiped.append(buf), real(buf))) + client, stubber = kms + stubber.add_response("generate_data_key", {"Plaintext": DATA_KEY, "CiphertextBlob": BLOB}, + {"KeyId": ARN, "KeySpec": "AES_128"}) + with pytest.raises(KeyManagementError): + manager(client, db).generate_data_key(ARN, EncryptionAlgorithm.AES_128_GCM) + assert len(wiped) == 1 and wiped[0] == bytearray(len(DATA_KEY)) + + def test_generate_is_gated_on_the_allow_list(self, kms, db): + with pytest.raises(UnauthorizedMasterKeyError): + manager(kms[0], db).generate_data_key(OTHER_ARN) + + def test_create_master_key_is_not_retried_after_an_ambiguous_failure(self, kms, db): + # After a 5xx the key may already exist; retrying would create a second one. + client, stubber = kms + stubber.add_client_error("create_key", "KMSInternalException", http_status_code=500) + sleeps: List[float] = [] + with pytest.raises(KeyManagementError, match="1 attempt"): + manager(client, db, sleeps=sleeps).create_master_key("d") + assert sleeps == [] + + def test_create_master_key_is_not_retried_on_a_quota_error(self, kms, db): + # LimitExceededException on CreateKey is the key-count quota; retrying + # only delays the same failure. + client, stubber = kms + stubber.add_client_error("create_key", "LimitExceededException", http_status_code=400) + sleeps: List[float] = [] + with pytest.raises(KeyManagementError, match="1 attempt"): + manager(client, db, sleeps=sleeps).create_master_key("d") + assert sleeps == [] + + def test_create_master_key_retries_a_connection_that_was_never_made(self, kms, db): + client, stubber = kms + km = manager(client, db) + calls = [] + + def create_key(**kwargs): + calls.append(kwargs) + if len(calls) == 1: + raise EndpointConnectionError(endpoint_url="https://kms") + return {"KeyMetadata": {"KeyId": "k", "Arn": ARN}} + + client.create_key = create_key # type: ignore[method-assign] + assert km.create_master_key("d") == ARN + assert len(calls) == 2 + + def test_create_master_key_retries_a_connect_timeout(self, kms, db): + # ConnectTimeoutError does not derive from EndpointConnectionError, so + # it needs its own guard. + from botocore.exceptions import ConnectTimeoutError + client, _ = kms + km = manager(client, db) + calls = [] + + def create_key(**kwargs): + calls.append(kwargs) + if len(calls) == 1: + raise ConnectTimeoutError(endpoint_url="https://kms") + return {"KeyMetadata": {"KeyId": "k", "Arn": ARN}} + + client.create_key = create_key # type: ignore[method-assign] + assert km.create_master_key("d") == ARN + assert len(calls) == 2 + + def test_create_master_key_retries_a_429(self, kms, db): + # A 429 means KMS did not act, whatever error code comes with it. + client, stubber = kms + stubber.add_client_error("create_key", "TooManyRequestsException", http_status_code=429) + stubber.add_response("create_key", {"KeyMetadata": {"KeyId": "k", "Arn": ARN}}, + {"Description": "d", "KeyUsage": "ENCRYPT_DECRYPT", "KeySpec": "SYMMETRIC_DEFAULT"}) + assert manager(client, db).create_master_key("d") == ARN + + def test_create_master_key_retries_throttling(self, kms, db): + client, stubber = kms + stubber.add_client_error("create_key", "ThrottlingException", http_status_code=400) + stubber.add_response("create_key", {"KeyMetadata": {"KeyId": "k", "Arn": ARN}}, + {"Description": "d", "KeyUsage": "ENCRYPT_DECRYPT", "KeySpec": "SYMMETRIC_DEFAULT"}) + sleeps: List[float] = [] + assert manager(client, db, sleeps=sleeps).create_master_key("d") == ARN + assert len(sleeps) == 1 + + def test_create_master_key(self, kms, db): + client, stubber = kms + stubber.add_response("create_key", {"KeyMetadata": {"KeyId": "k", "Arn": ARN}}, + {"Description": "d", "KeyUsage": "ENCRYPT_DECRYPT", "KeySpec": "SYMMETRIC_DEFAULT", + "Policy": "{}"}) + assert manager(client, db).create_master_key("d", policy="{}") == ARN + + @pytest.mark.parametrize("metadata, expected", [ + ({"KeyId": "k", "Enabled": True, "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT"}, True), + ({"KeyId": "k", "Enabled": False, "KeyState": "Disabled", "KeyUsage": "ENCRYPT_DECRYPT"}, False), + ({"KeyId": "k", "Enabled": True, "KeyState": "Enabled", "KeyUsage": "SIGN_VERIFY"}, False), + ]) + def test_is_master_key_valid(self, kms, db, metadata, expected): + client, stubber = kms + stubber.add_response("describe_key", {"KeyMetadata": metadata}, {"KeyId": ARN}) + assert manager(client, db).is_master_key_valid(ARN) is expected + + def test_is_master_key_valid_is_false_on_error(self, kms, db): + client, stubber = kms + stubber.add_client_error("describe_key", "NotFoundException", http_status_code=400) + assert manager(client, db).is_master_key_valid(ARN) is False + + +class TestKeyStorage: + def _key(self, **kw) -> KeyMetadata: + values = dict(key_name="n", master_key_arn=ARN, encrypted_data_key=EDK, hmac_key=b"H" * 32) + values.update(kw) + return KeyMetadata(**values) # type: ignore[arg-type] + + def test_store_on_postgres_uses_returning(self, kms, db): + db.result = (["id"], [(42,)]) + stored = manager(kms[0], db).store_key_metadata(self._key()) + assert stored.id == 42 + assert stored.key_id and len(stored.key_id) == 36 # generated UUID + sql, params = db.executed[0] + assert sql.startswith("INSERT INTO encrypt.key_storage ") and sql.endswith(" RETURNING id") + assert params[4] == b"H" * 32 and params[5] == "AES_256" + + def test_store_on_mysql_uses_lastrowid_and_keeps_given_uuid(self, kms, db): + db.lastrowid = 9 + stored = manager(kms[0], db, sql=MYSQL).store_key_metadata(self._key(key_id="given")) + assert (stored.id, stored.key_id) == (9, "given") + assert "RETURNING" not in db.executed[0][0] + + def test_unusable_metadata_is_refused(self, kms, db): + with pytest.raises(InvalidKeyMetadataError): + manager(kms[0], db).store_key_metadata(self._key(encrypted_data_key=None)) + assert db.executed == [] + + def test_store_failure_does_not_leak_the_hmac_key(self, kms, db): + secret = b"SECRET-HMAC-" + b"x" * 20 + db.error = RuntimeError(f"syntax error near '{secret!r}'") + with pytest.raises(KeyManagementError) as err: + manager(kms[0], db).store_key_metadata(self._key(hmac_key=secret)) + assert "SECRET-HMAC" not in str(err.value) + assert err.value.__cause__ is None + assert err.value.__context__ is None + assert "RuntimeError" in str(err.value) + + def test_store_failure_reports_the_driver_error_codes(self, kms, db): + # SQLSTATE and errno carry no statement text, so they can be shown. + class DriverError(Exception): + sqlstate = "42P01" + errno = 1146 + + db.error = DriverError("relation key_storage does not exist: 'SECRET-HMAC'") + with pytest.raises(KeyManagementError) as err: + manager(kms[0], db).store_key_metadata(self._key()) + assert "DriverError" in str(err.value) and "sqlstate 42P01" in str(err.value) + assert "errno 1146" in str(err.value) and "SECRET" not in str(err.value) + + def test_store_on_postgres_reads_the_id_from_a_dict_row(self, kms, db): + class DictCursor(FakeCursor): + def fetchone(self): + return {"id": 42} + + db.cursor = lambda: DictCursor(db) # type: ignore[method-assign] + db.result = (["id"], []) + assert manager(kms[0], db).store_key_metadata(self._key()).id == 42 + + def test_key_metadata_by_id(self, kms, db): + db.result = (["ID", "KEY_ID", "NAME", "MASTER_KEY_ARN", "ENCRYPTED_DATA_KEY", "HMAC_KEY", "KEY_SPEC", + "CREATED_AT", "LAST_USED_AT"], + [(3, "u", "n", ARN, EDK, memoryview(b"hk"), "AES_256", None, None)]) + km = manager(kms[0], db).key_metadata_by_id(3) + assert km is not None and km.id == 3 and km.hmac_key == b"hk" and km.master_key_arn == ARN + assert "WHERE id OPERATOR(pg_catalog.=) %s" in db.executed[0][0] + assert db.executed[0][1] == (3,) + + def test_key_metadata_by_id_missing(self, kms, db): + db.result = (["id"], []) + assert manager(kms[0], db).key_metadata_by_id(3) is None + + def test_key_metadata_by_id_failure(self, kms, db): + # The plugin passes ids read from stored values, which may be four + # bytes of legacy plaintext, so the message leaves the id out. + db.error = RuntimeError("boom") + with pytest.raises(KeyManagementError, match="boom") as err: + manager(kms[0], db).key_metadata_by_id(1802201963) + assert "1802201963" not in str(err.value) + + def test_touch_key_swallows_errors(self, kms, db): + db.error = RuntimeError("boom") + manager(kms[0], db).touch_key("u") + assert "last_used_at = CURRENT_TIMESTAMP" in db.executed[0][0] + + +# ---- botocore log filters ---- + +B64_KEY = base64.b64encode(DATA_KEY).decode() +# Distinctive fake credentials: easy to search for, and no test signs with the +# ambient credential chain. +FAKE_KEY_ID = "KIROUNITFAKEKEYID0001" +FAKE_SECRET = "kiro-unit-fake-secret-key" +FAKE_TOKEN = "kiro-unit-fake-session-token" +UNREACHABLE = "http://127.0.0.1:9" # never contacted: the canned answer comes first +KMS_OPERATIONS = ["TrentService.GenerateDataKey", "TrentService.Decrypt"] + + +class _Body: + """The raw stream botocore reads a canned response from.""" + + def __init__(self, body: bytes): + self._body = body + + def stream(self, **kwargs): + yield self._body + + +def _session(): + return boto3.Session(aws_access_key_id=FAKE_KEY_ID, aws_secret_access_key=FAKE_SECRET, + aws_session_token=FAKE_TOKEN) + + +def _answer_kms(client) -> Tuple[List[str], List[str]]: + """Answer each KMS request just before it would be sent, so botocore's + real signer and parser run and nothing leaves the host. Returns the + operations answered and the signatures of their requests.""" + answered: List[str] = [] + signatures: List[str] = [] + + def answer(request, **kwargs): + target = request.headers.get("X-Amz-Target", b"") + target = target.decode() if isinstance(target, bytes) else target + answered.append(target) + auth = request.headers.get("Authorization", b"") + auth = auth.decode() if isinstance(auth, bytes) else auth + signatures.append(auth.rpartition("Signature=")[2]) + body = {"KeyId": ARN, "Plaintext": B64_KEY} + if target.endswith("GenerateDataKey"): + body["CiphertextBlob"] = EDK + return AWSResponse(request.url, 200, {"Content-Type": "application/x-amz-json-1.1"}, + _Body(json.dumps(body).encode())) + + client.meta.events.register("before-send.kms.*", answer) + return answered, signatures + + +def _call_kms(client) -> int: + """GenerateDataKey then Decrypt; returns the id of the thread that called.""" + # A fresh manager and cache, so Decrypt reaches KMS instead of the cache. + cache = DataKeyCache(10, 60, start_cleanup_thread=False) + try: + km = KeyManager(client, FakeDb(), PG, config(), cache) + km.generate_data_key(ARN) + km.decrypt_data_key(EDK, ARN) + finally: + cache.close() + return threading.get_ident() + + +def _run(client, on_thread: bool) -> None: + if not on_thread: + _call_kms(client) + return + with ThreadPoolExecutor(max_workers=1) as pool: + worker = pool.submit(_call_kms, client).result(timeout=30) + assert worker != threading.get_ident() + + +@contextmanager +def _debug_log(caplog): + """Root and botocore's loggers at DEBUG for the block: the setup that leaks.""" + with ExitStack() as stack: + for name in LOGGERS: + stack.enter_context(caplog.at_level(logging.DEBUG, logger=name)) + yield caplog.records + + +def _holding(records, text: str) -> List[logging.LogRecord]: + return [r for r in records if text in r.getMessage()] + + +def _records(records, logger: str, msg: str) -> List[logging.LogRecord]: + return [r for r in records if r.name == logger and r.msg == msg] + + +def _state(name: str): + lg = logging.getLogger(name) + return lg.level, list(lg.handlers), lg.propagate, list(lg.filters) + + +class TestBotocoreLogFilters: + @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) + def test_botocore_logs_kms_secrets_at_debug(self, caplog, on_thread): + # The canaries: if botocore changes one of these records, the filter + # rules need another look. + client = _session().client("kms", region_name="us-east-1") + answered, signatures = _answer_kms(client) + with _debug_log(caplog) as records: + _run(client, on_thread) + assert answered == KMS_OPERATIONS + bodies = _records(records, "botocore.parsers", "Response body:\n%r") + assert len(bodies) == 2 and len(_holding(records, B64_KEY)) == 2 + assert all(isinstance(r.args, tuple) and isinstance(r.args[0], bytes) and b'"Plaintext"' in r.args[0] + for r in bodies) + sent = _records(records, "botocore.endpoint", "Sending http request: %s") + canonical = _records(records, "botocore.auth", "CanonicalRequest:\n%s") + assert len(sent) == 2 and len(canonical) == 2 + assert all(FAKE_KEY_ID in r.getMessage() and FAKE_TOKEN in r.getMessage() for r in sent) + assert all(FAKE_TOKEN in r.getMessage() for r in canonical) + signed = _records(records, "botocore.auth", "Signature:\n%s") + assert [r.getMessage() for r in signed] == [f"Signature:\n{s}" for s in signatures] + assert len(signatures) == 2 and all(len(s) == 64 for s in signatures) + + @pytest.mark.parametrize("endpoint", [None, UNREACHABLE], ids=["kms", "endpoint"]) + @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) + def test_create_kms_client_keeps_data_keys_out_of_the_log(self, caplog, on_thread, endpoint): + client = KeyManager.create_kms_client(_session(), config(kms_endpoint=endpoint)) + answered, signatures = _answer_kms(client) + with _debug_log(caplog) as records: + _run(client, on_thread) + assert answered == KMS_OPERATIONS + assert _holding(records, B64_KEY) == [] + assert _holding(records, '"Plaintext"') == [] + assert len(_records(records, "botocore.parsers", "Response headers: %r")) == 2 + assert _records(records, "botocore.auth", "Signature:\n%s") == [] + assert len(signatures) == 2 and all(_holding(records, s) == [] for s in signatures) + + @pytest.mark.parametrize("endpoint", [None, UNREACHABLE], ids=["kms", "endpoint"]) + @pytest.mark.parametrize("on_thread", [False, True], ids=["caller", "worker"]) + def test_create_kms_client_keeps_request_credentials_out_of_the_log(self, caplog, on_thread, endpoint): + client = KeyManager.create_kms_client(_session(), config(kms_endpoint=endpoint)) + answered, signatures = _answer_kms(client) + with _debug_log(caplog) as records: + _run(client, on_thread) + assert answered == KMS_OPERATIONS + for secret in (FAKE_KEY_ID, FAKE_SECRET, FAKE_TOKEN): + assert _holding(records, secret) == [] + assert _records(records, "botocore.auth", "Signature:\n%s") == [] + assert len(signatures) == 2 and all(_holding(records, s) == [] for s in signatures) + # The unsigned record names the KMS target but carries no credential, + # so it stays: the rule needs both parts. + making = _records(records, "botocore.endpoint", "Making request for %s with params: %s") + assert len(making) == 2 and all("TrentService." in r.getMessage() for r in making) + + def test_other_services_lose_only_the_signature_record(self, caplog): + session = _session() + sts = session.client("sts", region_name="us-east-1") + body = (b'' + b"arn:aws:iam::123456789012:user/u") + sts.meta.events.register( + "before-send.sts.GetCallerIdentity", + lambda request, **kwargs: AWSResponse(request.url, 200, {"Content-Type": "text/xml"}, _Body(body))) + sts.get_caller_identity() # warm up, so both captures see the same records + + def capture() -> List[logging.LogRecord]: + caplog.clear() + with _debug_log(caplog) as records: + sts.get_caller_identity() + # botocore's records only: a thread another test left running can log while the root logger is at DEBUG + return [r for r in records if r.name.split(".")[0] == "botocore"] + + without = capture() + KeyManager.create_kms_client(session, config()) + with_filters = capture() + # The signature also sits in the Authorization header of the request + # record, which other services keep. + expected = [(r.name, r.msg) for r in without] + assert expected.count(("botocore.auth", "Signature:\n%s")) == 1 + expected.remove(("botocore.auth", "Signature:\n%s")) + assert [(r.name, r.msg) for r in with_filters] == expected + sent = _records(with_filters, "botocore.endpoint", "Sending http request: %s") + canonical = _records(with_filters, "botocore.auth", "CanonicalRequest:\n%s") + assert len(sent) == 1 and FAKE_KEY_ID in sent[0].getMessage() and FAKE_TOKEN in sent[0].getMessage() + assert "Signature=" in sent[0].getMessage() + assert len(canonical) == 1 and FAKE_TOKEN in canonical[0].getMessage() + + def test_filters_are_installed_once_on_their_loggers_only(self): + # Pin a level and propagate flag first, so a change the install makes + # shows even if an earlier install in this process made it already. + loggers = [logging.getLogger(name) for name in LOGGERS] + saved = [(lg.level, lg.propagate) for lg in loggers] + try: + for lg in loggers: + lg.setLevel(logging.ERROR + 1) + lg.propagate = True + before = {name: _state(name) for name in LOGGERS} + KeyManager.create_kms_client(_session(), config()) + KeyManager.create_kms_client(_session(), config(kms_endpoint=UNREACHABLE)) + after = {name: _state(name) for name in LOGGERS} + finally: + for lg, (level, propagate) in zip(loggers, saved): + lg.setLevel(level) + lg.propagate = propagate + added = {} + for name in LOGGERS: + level, handlers, propagate, filters = after[name] + assert (level, handlers, propagate) == before[name][:3] + added[name] = [type(f) for f in filters if f not in before[name][3]] + assert added == {"": [], "botocore": [], "botocore.parsers": [km_module._NoKmsPlaintext], + "botocore.endpoint": [km_module._NoKmsRequestCredentials], + "botocore.auth": [km_module._NoKmsRequestCredentials]} + + def test_a_removed_filter_stays_removed(self): + # The filters are installed once per process, so a positive control + # that removes a filter and builds a new client sees the leak. + KeyManager.create_kms_client(_session(), config()) + for name in LOGGERS: + lg = logging.getLogger(name) + lg.filters = [f for f in lg.filters if not isinstance(f, OUR_FILTERS)] + KeyManager.create_kms_client(_session(), config()) + assert not any(isinstance(f, OUR_FILTERS) for name in LOGGERS for f in logging.getLogger(name).filters) + + def test_concurrent_first_installs_add_each_filter_once(self, mocker): + # Thread A's first addFilter call waits until thread B has had time to + # run its own first install. The lock holds B until A is done, so B + # finds the filters installed and adds none. + entered, release = threading.Event(), threading.Event() + real_add_filter = logging.Logger.addFilter + + def add_filter(lg: logging.Logger, flt: logging.Filter) -> None: + if lg.name == "botocore.parsers" and not entered.is_set(): + entered.set() + release.wait(5) + real_add_filter(lg, flt) + + mocker.patch.object(logging.Logger, "addFilter", add_filter) + a = threading.Thread(target=km_module._install_botocore_filters, daemon=True) + b = threading.Thread(target=km_module._install_botocore_filters, daemon=True) + a.start() + try: + assert entered.wait(5), "thread A never reached addFilter" + b.start() + b.join(0.2) + finally: + # Release A and join both threads on every path, so neither thread + # is still adding filters when no_filters restores the loggers. + release.set() + for thread in (a, b): + if thread.is_alive(): + thread.join(5) + installed = {name: [type(f) for f in logging.getLogger(name).filters if isinstance(f, OUR_FILTERS)] + for name in ("botocore.parsers", "botocore.endpoint", "botocore.auth")} + assert installed == {"botocore.parsers": [km_module._NoKmsPlaintext], + "botocore.endpoint": [km_module._NoKmsRequestCredentials], + "botocore.auth": [km_module._NoKmsRequestCredentials]} + + +def _record(name: str, msg: str, args) -> logging.LogRecord: + return logging.LogRecord(name, logging.DEBUG, __file__, 0, msg, args, None) + + +class TestBotocoreLogFilterRules: + @pytest.mark.parametrize("msg, args, kept", [ + ("Response body:\n%r", (b'{"KeyId": "k", "Plaintext": "x"}',), False), + ("Response body:\n%r", (bytearray(b'{"Plaintext": "x"}'),), False), + ("%s %r", ("Response body", b'{"Plaintext": "x"}'), False), + ("Response body:\n%r", ('{"Plaintext": "x"}',), True), + ("Response body:\n%r", (b'{"KeyId": "k"}',), True), + ("Response headers: %r", None, True), + ("%(body)s", ({"body": b'{"Plaintext": "x"}'},), True), + ]) + def test_plaintext_filter_drops_only_bytes_carrying_a_plaintext_field(self, msg, args, kept): + assert km_module._NoKmsPlaintext().filter(_record("botocore.parsers", msg, args)) is kept + + @pytest.mark.parametrize("msg, args, kept", [ + ("Sending http request: %s", ("{'X-Amz-Target': b'TrentService.Decrypt', 'Authorization': b'AWS4'}",), False), + ("CanonicalRequest:\n%s", ("x-amz-security-token:t\nx-amz-target:TrentService.Decrypt",), False), + ("CanonicalRequest:\n%s", ("X-AMZ-SECURITY-TOKEN:t\nx-amz-target:TrentService.Decrypt",), False), + ("Signature:\n%s", ("0f3a" * 16,), False), + ("Signature:\n%s", ("TrentService.Decrypt " + "0f3a" * 16,), False), + ("Making request for %s with params: %s", ("Decrypt", "{'X-Amz-Target': 'TrentService.Decrypt'}"), True), + ("Sending http request: %s", ("{'X-Amz-Target': b'Other.Op', 'Authorization': b'AWS4'}",), True), + ("Calculating signature using v4 auth.", None, True), + ("StringToSign:\n%s", ("AWS4-HMAC-SHA256\nSignature:\n" + "0f3a" * 16,), True), + ("Signature: %s", ("0f3a" * 16,), True), + ("TrentService. Authorization %s %s", ("only one argument",), True), + ]) + def test_request_filter_drops_only_signed_kms_records(self, msg, args, kept): + assert km_module._NoKmsRequestCredentials().filter(_record("botocore.endpoint", msg, args)) is kept diff --git a/tests/unit/test_metadata_manager.py b/tests/unit/test_metadata_manager.py new file mode 100644 index 000000000..70a53b99d --- /dev/null +++ b/tests/unit/test_metadata_manager.py @@ -0,0 +1,517 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import threading +import weakref +from contextlib import contextmanager +from types import SimpleNamespace +from typing import Any, List, Optional, Tuple + +import pytest + +from aws_advanced_python_wrapper.encryption import metadata_manager as module +from aws_advanced_python_wrapper.encryption.config import EncryptionConfig +from aws_advanced_python_wrapper.encryption.metadata_manager import \ + MetadataManager +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.errors import MetadataError + +ARN = "arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" + +COLUMNS = ["table_name", "column_name", "encryption_algorithm", "key_id", "created_at", "updated_at", + "ks_id", "ks_key_id", "ks_name", "ks_master_key_arn", "ks_encrypted_data_key", "ks_hmac_key", + "ks_key_spec", "ks_created_at", "ks_last_used_at"] + + +def row(table, column, key_id=1, with_key=True, algorithm="AES-256-GCM"): + key = (key_id, "uuid", "n", ARN, "ZWRr", b"h" * 32, "AES_256", None, None) if with_key else (None,) * 9 + return (table, column, algorithm, key_id, None, None) + key + + +class FakeDb: + def __init__(self, rows=()): + self.rows: List[Tuple[Any, ...]] = list(rows) + self.executed: List[Tuple[str, Tuple[Any, ...]]] = [] + self.error: Optional[Exception] = None + self.opened = 0 + + @contextmanager + def connection(self): + self.opened += 1 + yield self + + def cursor(self): + db = self + + class Cursor: + description = None + + def execute(self, sql, params=()): + db.executed.append((sql, tuple(params))) + if db.error is not None: + raise db.error + self.description = [(c.upper(),) for c in COLUMNS] # upper case, as some MySQL versions report + rows = db.rows + if "WHERE em.table_name" in sql: + rows = [r for r in rows if r[0] == params[0] and (len(params) < 2 or r[1] == params[1])] + self._rows = rows + + def fetchall(self): + return self._rows + + def close(self): + pass + + return Cursor() + + +class Clock: + now = 100.0 + + def __call__(self): + return self.now + + +@pytest.fixture +def clock(monkeypatch): + # Replace the module's view of `time` only, so no other thread in the + # process sees a frozen clock. + c = Clock() + monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=c)) + return c + + +@pytest.fixture +def managers(): + """Collects managers and closes them even when a test fails, so no + refresh thread outlives its test.""" + created: List[MetadataManager] = [] + yield created + for mm in created: + mm.close() + + +def config(**overrides): + values = dict(kms_region="us-east-1", allowed_master_key_arns=frozenset({ARN}), + metadata_cache_refresh_interval_sec=0.0, metadata_cache_expiration_sec=60.0) + values.update(overrides) + return EncryptionConfig(**values) # type: ignore[arg-type] + + +def test_joined_query_is_a_left_join_on_the_integer_id(): + db = FakeDb() + MetadataManager(db, PG, config()).load_metadata() + sql = db.executed[0][0] + assert "FROM encrypt.encryption_metadata em LEFT JOIN encrypt.key_storage ks" in sql + assert "ON em.key_id OPERATOR(pg_catalog.=) ks.id" in sql + assert "ks.key_id AS ks_key_id" in sql + + +def test_mysql_uses_plain_equals(): + db = FakeDb() + MetadataManager(db, MYSQL, config(metadata_schema="app_enc")).load_metadata() + assert "ON em.key_id = ks.id" in db.executed[0][0] + assert "app_enc.encryption_metadata" in db.executed[0][0] + + +def test_start_loads_snapshot_and_lookups_hit_the_cache(clock): + db = FakeDb([row("users", "ssn"), row("users", "dob", 2), row("orders", "card", 3)]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.cache_size == 3 and db.opened == 1 + assert mm.is_column_encrypted("users", "ssn") + assert not mm.is_column_encrypted("users", "name") + assert not mm.is_column_encrypted(None, "ssn") + config_ = mm.column_config("users", "dob") + assert config_ is not None and config_.key_id == 2 and config_.key_metadata.id == 2 + assert config_.key_metadata.hmac_key == b"h" * 32 and config_.is_usable + assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} + assert mm.table_configs("nope") == () + assert db.opened == 1 + + +def test_column_with_missing_key_row_still_reads_as_encrypted(clock): + db = FakeDb([row("users", "ssn", key_id=7, with_key=False)]) + mm = MetadataManager(db, PG, config()) + mm.start() + config_ = mm.column_config("users", "ssn") + assert config_ is not None + assert config_.key_id == 7 and config_.key_metadata is None + assert not config_.is_usable + assert mm.is_column_encrypted("users", "ssn") + + +def _expired_with_background_refresh(clock, managers, db): + # A background refresh is configured but hasn't run yet when the snapshot + # expires, so the next lookup is what reloads it. + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0, + metadata_cache_refresh_interval_sec=3600.0)) + managers.append(mm) + mm.start() + clock.now += 10.0 + return mm + + +def test_expired_snapshot_is_reloaded_with_the_background_refresh_on(clock, managers): + db = FakeDb([row("users", "ssn")]) + mm = _expired_with_background_refresh(clock, managers, db) + assert mm.is_column_encrypted("users", "ssn") + assert mm.column_config("users", "ssn") is not None + assert db.opened == 2 # start() plus one reload, not a query per lookup + assert "WHERE" not in db.executed[-1][0] + assert mm._fresh(mm._snapshot) is not None + + +def test_expired_snapshot_reload_sees_a_column_added_since(clock, managers): + # A column encrypted after the snapshot was taken must show up once the + # snapshot expires; serving the stale snapshot would let a write store + # plaintext. + db = FakeDb([row("users", "ssn")]) + mm = _expired_with_background_refresh(clock, managers, db) + db.rows = [row("users", "ssn"), row("users", "dob", 2)] + assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} + assert mm.cache_size == 2 # the reload cached the new column + assert mm.is_column_encrypted("users", "dob") + assert db.opened == 2 + + +def test_expired_snapshot_is_reloaded_when_there_is_no_background_refresh(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # refresh interval 0 + mm.start() + clock.now += 10.0 + db.rows = [row("users", "ssn"), row("users", "dob", 2)] + assert {c.column_name for c in mm.table_configs("users")} == {"ssn", "dob"} + assert mm.is_column_encrypted("users", "dob") + assert db.opened == 2 # one reload, then served from the new snapshot + assert "WHERE" not in db.executed[-1][0] + + +def test_manager_that_was_never_started_always_queries(clock): + # The admin utility relies on this: it never starts its manager, so every + # lookup sees the caller's own transaction. + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + assert mm.is_column_encrypted("users", "ssn") + assert mm.is_column_encrypted("users", "ssn") + assert db.opened == 2 and not mm.is_cache_loaded + + +def test_disabled_cache_always_queries(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + mm.start() + assert db.opened == 0 and not mm.is_cache_loaded + assert mm.is_column_encrypted("users", "ssn") + assert [c.column_name for c in mm.table_configs("users")] == ["ssn"] + assert db.opened == 2 + + +def test_refresh_replaces_the_snapshot_atomically(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + mm.start() + db.rows = [row("users", "dob")] + assert mm.refresh() == 1 + assert not mm.is_column_encrypted("users", "ssn") + assert mm.is_column_encrypted("users", "dob") + + +def test_failed_refresh_keeps_the_previous_snapshot(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + mm.start() + db.error = RuntimeError("db down") + with pytest.raises(MetadataError, match="db down"): + mm.refresh() + assert mm.is_column_encrypted("users", "ssn") + + +def test_initial_load_failure_raises_metadata_error(): + db = FakeDb() + db.error = RuntimeError("no such schema") + with pytest.raises(MetadataError): + MetadataManager(db, PG, config()).start() + + +def test_lookup_failure_carries_table_and_column(clock): + db = FakeDb() + db.error = RuntimeError("x") + mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + with pytest.raises(MetadataError) as err: + mm.column_config("users", "ssn") + assert (err.value.table_name, err.value.column_name) == ("users", "ssn") + + +def test_background_refresh_thread_runs_and_stops(managers): + db = FakeDb([row("users", "ssn")]) + refreshed = threading.Event() + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + managers.append(mm) + original = mm.refresh + + def counting_refresh(): + n = original() + if db.opened >= 3: + refreshed.set() + return n + + mm.refresh = counting_refresh # type: ignore[method-assign] + mm.start() + thread = mm._refresh_thread + assert thread is not None and thread.daemon + assert refreshed.wait(5) + mm.close() + assert not thread.is_alive() + assert not mm.is_cache_loaded + mm.close() # idempotent + + +def test_background_refresh_survives_errors(managers): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + managers.append(mm) + mm.start() + db.error = RuntimeError("blip") + attempts = len(db.executed) + for _ in range(500): + if len(db.executed) > attempts + 2: + break + threading.Event().wait(0.01) + assert len(db.executed) > attempts + 2 # the loop kept trying + assert mm._refresh_thread is not None and mm._refresh_thread.is_alive() + + +class BlockingDb(FakeDb): + """A FakeDb that, while ``block`` is set, holds the next query's + connection open after the query ran, until released.""" + + def __init__(self, rows=()): + super().__init__(rows) + self.block = False + self.entered = threading.Event() + self.release = threading.Event() + + @contextmanager + def connection(self): + with super().connection() as conn: + yield conn + if self.block: + self.entered.set() + self.release.wait(5) + + +def test_refresh_finishing_after_close_does_not_repopulate_the_cache(managers): + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + managers.append(mm) + mm.start() + db.block = True + worker = threading.Thread(target=mm.refresh, daemon=True) + worker.start() + assert db.entered.wait(5) + mm.close() + db.release.set() + worker.join(5) + assert not worker.is_alive() + assert not mm.is_cache_loaded + # ...and a lookup after close reads the database instead of a cache. + db.block = False + opened = db.opened + assert mm.is_column_encrypted("users", "ssn") + assert db.opened == opened + 1 and not mm.is_cache_loaded + + +def test_start_after_close_does_nothing(): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=0.01)) + mm.close() + mm.start() + assert db.opened == 0 and mm._refresh_thread is None and not mm.is_cache_loaded + + +def test_concurrent_refreshes_cannot_publish_older_data(): + # The first refresh has read the old rows but not yet published them when + # the data changes and a second refresh starts. Refreshes are serialized, + # so the second one's newer data is published last. + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config()) + db.block = True + first = threading.Thread(target=mm.refresh, daemon=True) + first.start() + assert db.entered.wait(5) + db.block = False + db.rows = [row("users", "dob")] + second = threading.Thread(target=mm.refresh, daemon=True) + second.start() + second.join(0.2) + assert second.is_alive() # waits for the first refresh + db.release.set() + first.join(5) + second.join(5) + assert not first.is_alive() and not second.is_alive() + assert mm.is_column_encrypted("users", "dob") + assert not mm.is_column_encrypted("users", "ssn") + + +def test_unclosed_manager_stops_its_thread_when_collected(): + # A long interval, so the thread stops because the finalizer wakes it, + # not because its next wait happened to time out. + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_refresh_interval_sec=60.0)) + mm.start() + thread = mm._refresh_thread + ref = weakref.ref(mm) + del mm + for _ in range(100): + gc.collect() + if ref() is None: + break + threading.Event().wait(0.01) + assert ref() is None + assert thread is not None + thread.join(2) + assert not thread.is_alive() + + +def test_finalizer_does_not_set_the_event_from_the_refresh_thread_itself(): + # On the refresh thread the collection can run inside Event.wait, which + # holds the event's lock, so stop.set() there would deadlock. + stop = threading.Event() + MetadataManager._finalize(stop, [threading.current_thread()]) + assert not stop.is_set() + MetadataManager._finalize(stop, [None]) + assert stop.is_set() + + +def test_close_from_the_refresh_thread_does_not_fail(managers): + # Only the refresh thread reports; start()'s initial refresh runs on the + # calling thread and must not satisfy the test. + errors: List[BaseException] = [] + done = threading.Event() + + class ClosingDb(FakeDb): + @contextmanager + def connection(self): + if threading.current_thread().name == "kms-encryption-metadata-refresh": + try: + mm.close() + except BaseException as e: + errors.append(e) + finally: + done.set() + with super().connection() as conn: + yield conn + + mm = MetadataManager(ClosingDb([row("users", "ssn")]), PG, config(metadata_cache_refresh_interval_sec=0.01)) + managers.append(mm) + mm.start() + assert done.wait(5) + assert errors == [] + assert mm._stop.is_set() + + +def test_finalizer_is_given_the_refresh_thread(managers): + # The _finalize test passes the holder by hand; this pins the wiring. + mm = MetadataManager(FakeDb([row("users", "ssn")]), PG, config(metadata_cache_refresh_interval_sec=60.0)) + managers.append(mm) + mm.start() + assert mm._refresh_thread is not None + assert mm._thread_holder == [mm._refresh_thread] + + +def test_failed_reload_from_table_configs_names_the_table(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) + mm.start() + clock.now += 10.0 + db.error = RuntimeError("db down") + with pytest.raises(MetadataError) as err: + mm.table_configs("users") + assert (err.value.table_name, err.value.column_name) == ("users", None) + + +def test_snapshot_age_counts_from_the_start_of_the_load(clock, managers): + # A slow load must not stretch how long its data is trusted. + class SlowDb(FakeDb): + @contextmanager + def connection(self): + with super().connection() as conn: + yield conn + clock.now += 5.0 # the load takes 5 s + + db = SlowDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0, + metadata_cache_refresh_interval_sec=3600.0)) + managers.append(mm) + mm.start() + clock.now += 5.0 # 10 s after the data was read, 5 s after the query returned + opened = db.opened + mm.column_config("users", "ssn") + assert db.opened == opened + 1 # expired: read from the database + + +def test_lookups_that_expire_together_share_one_reload(clock): + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh + mm.start() + clock.now += 10.0 + db.block = True + first = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) + first.start() + assert db.entered.wait(5) # the first lookup's reload is inside its read + db.block = False + others = [threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) for _ in range(4)] + for t in others: + t.start() + db.release.set() + for t in [first] + others: + t.join(5) + assert not any(t.is_alive() for t in [first] + others) + assert db.opened == 2 # start() plus a single reload + + +def test_lookups_queued_when_close_runs_do_not_reload(clock): + db = BlockingDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) # no background refresh + mm.start() + clock.now += 10.0 + db.block = True + first = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) + first.start() + assert db.entered.wait(5) + db.block = False + queued = threading.Thread(target=mm.column_config, args=("users", "ssn"), daemon=True) + queued.start() + queued.join(0.2) + assert queued.is_alive() # waiting for the first reload + mm.close() + db.release.set() + first.join(5) + queued.join(5) + assert not first.is_alive() and not queued.is_alive() + full_loads = [sql for sql, _ in db.executed if "WHERE" not in sql] + assert len(full_loads) == 2 # start() and the first lookup's reload; the queued one only queries its column + + +def test_failed_reload_names_the_lookup(clock): + db = FakeDb([row("users", "ssn")]) + mm = MetadataManager(db, PG, config(metadata_cache_expiration_sec=10.0)) + mm.start() + clock.now += 10.0 + db.error = RuntimeError("db down") + with pytest.raises(MetadataError) as err: + mm.column_config("users", "ssn") + assert (err.value.table_name, err.value.column_name) == ("users", "ssn") diff --git a/tests/unit/test_plugin_manager.py b/tests/unit/test_plugin_manager.py index 6408825a2..804cad3a0 100644 --- a/tests/unit/test_plugin_manager.py +++ b/tests/unit/test_plugin_manager.py @@ -14,6 +14,11 @@ from __future__ import annotations +import contextvars +import logging +import threading +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import TimeoutError as FuturesTimeoutError from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -21,7 +26,7 @@ from aws_advanced_python_wrapper.pep249 import Connection from enum import Enum -from typing import Any, Callable, Dict, List, Optional, Set +from typing import Any, Callable, Dict, List, Optional, Set, Tuple import psycopg import pytest @@ -37,10 +42,14 @@ from aws_advanced_python_wrapper.iam_plugin import IamAuthPlugin from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.plugin import Plugin -from aws_advanced_python_wrapper.plugin_service import PluginManager +from aws_advanced_python_wrapper.plugin_service import (PluginCallContext, + PluginManager, + PluginServiceImpl) +from aws_advanced_python_wrapper.utils.decorators import timeout from aws_advanced_python_wrapper.utils.notifications import ( ConnectionEvent, HostEvent, OldConnectionSuggestedAction) from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.wrapper import AwsWrapperCursor class DbApiMethodTest(Enum): @@ -714,6 +723,380 @@ def test_must_use_pipeline(mocker, container, mock_telemetry_factory): assert manager.must_use_pipeline(DbApiMethod.CURSOR_LASTROWID) +# A value the call-context tests look for where no argument may appear. +CALL_CONTEXT_MARKER = "call-context-marker-7f3a" + + +class CallContextPlugin(Plugin): + """Records the arguments it is entered with. It can replace the call's arguments, run the rest of the chain more + than once, or run something while it handles the call.""" + + def __init__( + self, + plugin_service: PluginServiceImpl, + name: str, + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]], + replace_with: Optional[Tuple[Tuple[Any, ...], Dict[str, Any]]] = None, + runs: int = 1, + during: Optional[Callable[[], None]] = None): + self._plugin_service = plugin_service + self._name = name + self._seen = seen + self._replace_with = replace_with + self._runs = runs + self._during = during + + @property + def subscribed_methods(self) -> Set[str]: + return {DbApiMethod.CURSOR_EXECUTE.method_name, DbApiMethod.CURSOR_EXECUTEMANY.method_name} + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + self._seen.append((self._name, args, kwargs)) + if self._during is not None: + self._during() + context = self._plugin_service.current_call_context + if self._replace_with is not None and context is not None: + context.args, context.kwargs = self._replace_with + result = None + for _ in range(self._runs): + result = execute_func() + return result + + +class CallContextObserverPlugin(Plugin): + """Records, for each call it handles, the arguments of the call context it reads.""" + + def __init__(self, plugin_service: PluginServiceImpl, methods: Set[str], observed: List[Tuple[str, Optional[Tuple[Any, ...]]]]): + self._plugin_service = plugin_service + self._methods = methods + self._observed = observed + + @property + def subscribed_methods(self) -> Set[str]: + return self._methods + + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + context = self._plugin_service.current_call_context + self._observed.append((method_name, None if context is None else context.args)) + return execute_func() + + +def _call_context_service() -> PluginServiceImpl: + # current_call_context reads only the calling thread's context, so the service needs no set-up. + return PluginServiceImpl.__new__(PluginServiceImpl) + + +def _call_context_manager(mocker, container, mock_telemetry_factory, plugins: List[Plugin]) -> PluginManager: + container.plugin_service.driver_dialect.execute.side_effect = \ + lambda method_name, func, *args, **kwargs: func() + mocker.patch.object(PluginManager, "__init__", lambda w, x, y, z: None) + manager = PluginManager(mocker.MagicMock(), mocker.MagicMock(), mocker.MagicMock()) + manager._container = container + manager._plugins = plugins + [DefaultPlugin(container.plugin_service, mocker.MagicMock())] + manager._telemetry_factory = mock_telemetry_factory + manager._telemetry_in_use = False + manager._function_cache = [None] * (DbApiMethod.ALL.id + 1) + return manager + + +def test_call_context_replacement_reaches_later_plugins_and_the_driver(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + driver_calls = [] + caller_params = ["plain"] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + CallContextPlugin(service, "before", seen), + CallContextPlugin(service, "replacer", seen, replace_with=(("q", ("ENC",)), {"prepare": True})), + CallContextPlugin(service, "after", seen)]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: driver_calls.append((a, kw)), "q", caller_params) + + assert seen == [("before", ("q", ["plain"]), {}), + ("replacer", ("q", ["plain"]), {}), + ("after", ("q", ("ENC",)), {"prepare": True})] + assert seen[0][1][1] is caller_params + assert driver_calls == [(("q", ("ENC",)), {"prepare": True})] + assert caller_params == ["plain"] + + +@pytest.mark.parametrize("method_name", ["execute", "executemany"]) +@pytest.mark.parametrize("replacement", [((), {}), (("q", [("ENC",)]), {"prepare": True})]) +def test_cursor_driver_method_receives_the_replacement_as_written( + mocker, container, mock_telemetry_factory, mock_cursor, method_name, replacement): + # An empty replacement too: the driver then fails on it, instead of receiving the caller's arguments. + service = _call_context_service() + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=replacement)]) + cursor = AwsWrapperCursor(mocker.MagicMock(), container.plugin_service, manager, mock_cursor) + + getattr(cursor, method_name)("q", [("plain",)]) + + getattr(mock_cursor, method_name).assert_called_once_with(*replacement[0], **replacement[1]) + + +def test_without_a_replacement_the_driver_gets_the_callers_arguments(mocker, container, mock_telemetry_factory, mock_conn): + driver_calls = [] + params = ["v"] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, []) + + # Nothing subscribed and not network bound: the call bypasses the pipeline. + container.plugin_service.is_network_bound_method.return_value = False + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: driver_calls.append((a, kw)), "q", params, prepare=True) + assert container.plugin_service.driver_dialect.execute.call_count == 0 + + # Network bound: the call goes through DefaultPlugin. + container.plugin_service.is_network_bound_method.return_value = True + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: driver_calls.append((a, kw)), "q", params, prepare=True) + assert container.plugin_service.driver_dialect.execute.call_count == 1 + + assert driver_calls == [(("q", ["v"]), {"prepare": True})] * 2 + # The driver gets the caller's own objects, not copies of them. + assert all(call[0][1] is params for call in driver_calls) + + +def test_call_context_outer_rerun_starts_from_the_arguments_the_outer_plugin_saw( + mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + driver_calls = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + CallContextPlugin(service, "retrier", seen, runs=2), + CallContextPlugin(service, "replacer", seen, replace_with=(("q", ("ENC",)), {"prepare": True}))]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: driver_calls.append(a), "q", ("plain",)) + + assert [entry for entry in seen if entry[0] == "replacer"] == [("replacer", ("q", ("plain",)), {})] * 2 + assert driver_calls == [("q", ("ENC",))] * 2 + + +def test_call_context_outer_retry_after_an_error_starts_from_the_arguments_the_outer_plugin_saw( + mocker, container, mock_telemetry_factory, mock_conn): + # A plugin after the replacer fails once and a plugin before it runs the rest again: the replacement made in the + # failed run is undone, so the replacer starts again from the caller's arguments and replaces them once. + service = _call_context_service() + seen: List[Tuple[str, Tuple[Any, ...], Dict[str, Any]]] = [] + driver_calls = [] + failures = [ValueError("inner plugin failed")] + + def fail_once() -> None: + if failures: + raise failures.pop() + + class RetryPlugin(CallContextPlugin): + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + try: + return execute_func() + except ValueError: + return execute_func() + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + RetryPlugin(service, "retrier", seen), + CallContextPlugin(service, "replacer", seen, replace_with=(("q", ("ENC",)), {"prepare": True})), + CallContextPlugin(service, "failer", seen, during=fail_once)]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: driver_calls.append(a), "q", ("plain",)) + + assert [entry for entry in seen if entry[0] == "replacer"] == [("replacer", ("q", ("plain",)), {})] * 2 + assert driver_calls == [("q", ("ENC",))] + + +def test_current_call_context_is_none_outside_a_call_and_after_an_error(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=(("q", ("ENC",)), {}))]) + + def failing_driver(*args, **kwargs): + raise ValueError("driver failed") + + assert service.current_call_context is None + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("plain",)) + assert service.current_call_context is None + with pytest.raises(ValueError): + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, failing_driver, "q", ("plain",)) + assert service.current_call_context is None + + +def test_only_execute_and_executemany_get_a_call_context(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + observed: List[Tuple[str, Optional[Tuple[Any, ...]]]] = [] + methods = [DbApiMethod.CURSOR_EXECUTE, DbApiMethod.CURSOR_EXECUTEMANY, DbApiMethod.CURSOR_FETCHONE, DbApiMethod.CURSOR_FETCHMANY] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextObserverPlugin(service, {method.method_name for method in methods}, observed)]) + + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("v",)) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTEMANY, lambda *a, **kw: None, "q", [("v",)]) + manager.execute(mock_conn, DbApiMethod.CURSOR_FETCHONE, lambda: None) + manager.execute(mock_conn, DbApiMethod.CURSOR_FETCHMANY, lambda: None, 5) + + assert observed == [(DbApiMethod.CURSOR_EXECUTE.method_name, ("q", ("v",))), + (DbApiMethod.CURSOR_EXECUTEMANY.method_name, ("q", [("v",)])), + (DbApiMethod.CURSOR_FETCHONE.method_name, None), + (DbApiMethod.CURSOR_FETCHMANY.method_name, None)] + + +def test_nested_execute_has_its_own_call_context_and_restores_the_enclosing_one( + mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + observed: List[Any] = [] + + def nested_execute(): + if observed: + return # only the enclosing call makes a nested one + enclosing = service.current_call_context + observed.append(("enclosing", None if enclosing is None else enclosing.args)) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, + lambda *a, **kw: observed.append(("nested", a, service.current_call_context is not enclosing)), + "nested q", ("n",)) + observed.append(("restored", service.current_call_context is enclosing)) + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "nester", [], during=nested_execute)]) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("o",)) + + assert observed == [("enclosing", ("q", ("o",))), ("nested", ("nested q", ("n",)), True), ("restored", True)] + + +def test_other_method_inside_execute_sees_the_enclosing_call_context(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + observed: List[Tuple[str, Optional[Tuple[Any, ...]]]] = [] + + def nested_fetchone(): + manager.execute(mock_conn, DbApiMethod.CURSOR_FETCHONE, lambda: "row") + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [ + CallContextObserverPlugin(service, {DbApiMethod.CURSOR_FETCHONE.method_name}, observed), + CallContextPlugin(service, "nester", [], during=nested_fetchone)]) + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: None, "q", ("o",)) + + assert observed == [(DbApiMethod.CURSOR_FETCHONE.method_name, ("q", ("o",)))] + + +def test_call_contexts_of_concurrent_threads_are_separate(mocker, container, mock_telemetry_factory, mock_conn): + service = _call_context_service() + barrier = threading.Barrier(2) + mismatches: List[Any] = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, [CallContextPlugin(service, "plugin", [])]) + + def driver(*args, **kwargs): + # Both threads are inside a call here at the same time. + barrier.wait(timeout=5) + context = service.current_call_context + if context is None or context.args != args: + mismatches.append(args) + + def run(sql: str): + for _ in range(20): + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, sql, ()) + + threads = [threading.Thread(target=run, args=(sql,)) for sql in ("q0", "q1")] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=30) + + assert not any(thread.is_alive() for thread in threads) + assert mismatches == [] + + +def test_late_socket_timeout_worker_sends_the_replacement(mocker, container, mock_telemetry_factory, mock_conn): + # With the dialect's pool busy, the driver call is still queued when the statement times out and every + # replacement has been undone. When a worker finally runs it, it must still send the replacement. + service = _call_context_service() + release = threading.Event() + sent = [] + + def driver(*args, **kwargs): + sent.append((args, kwargs)) + + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=(("q", ("ENC",)), {}))]) + with ThreadPoolExecutor(max_workers=1) as pool: + pool.submit(release.wait, 10) # the only worker is held by an earlier operation that is stuck + container.plugin_service.driver_dialect.execute.side_effect = \ + lambda method_name, func, *args, **kwargs: timeout(pool, 0.05)(func)() + + with pytest.raises(FuturesTimeoutError): + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, "q", ("plain",)) + assert sent == [] + + release.set() + # timeout() doesn't cancel a call that is still queued, so the worker runs it now. If timeout() ever cancels it, + # nothing is sent. Either way the driver never gets the caller's arguments or the cleared ones. + + assert sent in ([], [(("q", ("ENC",)), {})]) + + +def test_socket_timeout_worker_sends_the_replacement(mocker, container, mock_telemetry_factory, mock_conn): + # With socket_timeout set, the dialect runs the driver call on a worker thread, which doesn't see this thread's + # call context. The worker must still send the replacement. + service = _call_context_service() + sent = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "replacer", [], replace_with=(("q", ("ENC",)), {}))]) + with ThreadPoolExecutor(max_workers=1) as pool: + pool.submit(lambda: None).result(5) # start the worker before the call, so it can't inherit the call's context + container.plugin_service.driver_dialect.execute.side_effect = \ + lambda method_name, func, *args, **kwargs: timeout(pool, 5)(func)() + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, lambda *a, **kw: sent.append((a, kw)), "q", ("plain",)) + + assert sent == [(("q", ("ENC",)), {})] + + +@pytest.mark.parametrize("fails", [False, True], ids=["returns", "raises"]) +def test_context_copied_during_a_call_holds_no_argument_after_it(mocker, container, mock_telemetry_factory, mock_conn, caplog, fails): + caplog.set_level(logging.DEBUG) + service = _call_context_service() + copies: List[contextvars.Context] = [] + manager = _call_context_manager(mocker, container, mock_telemetry_factory, + [CallContextPlugin(service, "copier", [], during=lambda: copies.append(contextvars.copy_context()))]) + + driver_error = ValueError("driver failed") + + def driver(*args: Any, **kwargs: Any) -> None: + if fails: + raise driver_error + + if fails: + with pytest.raises(ValueError) as excinfo: + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, "q", (CALL_CONTEXT_MARKER,), params=CALL_CONTEXT_MARKER) + # The driver's own error arrives unchanged, with nothing of the call's arguments added to it. + assert excinfo.value is driver_error + assert excinfo.value.__cause__ is None + assert excinfo.value.__context__ is None + else: + manager.execute(mock_conn, DbApiMethod.CURSOR_EXECUTE, driver, "q", (CALL_CONTEXT_MARKER,), params=CALL_CONTEXT_MARKER) + + copied = copies[0].run(lambda: service.current_call_context) + assert copied is not None + assert copied.args == () + assert copied.kwargs == {} + # The core neither logs nor traces the call's arguments. + assert [record for record in caplog.records if CALL_CONTEXT_MARKER in record.getMessage()] == [] + assert CALL_CONTEXT_MARKER not in str(mock_telemetry_factory.mock_calls) + + +def test_call_context_repr_and_str_show_no_argument(): + context = PluginCallContext(("q", (CALL_CONTEXT_MARKER,)), {"params": CALL_CONTEXT_MARKER}) + + assert CALL_CONTEXT_MARKER not in repr(context) + assert CALL_CONTEXT_MARKER not in str(context) + assert CALL_CONTEXT_MARKER not in format(context) + + +def test_call_context_rejects_an_unknown_attribute(): + context = PluginCallContext((), {}) + + with pytest.raises(AttributeError): + context.kwarg = {} # a misspelt kwargs fails instead of never reaching the driver + + context.args, context.kwargs = ("q",), {"params": ()} + assert context.args == ("q",) + assert context.kwargs == {"params": ()} + + class CMySQLCursor: """Stands in for a mysql-connector cursor, whose str() quotes the start of its last statement with the values.""" diff --git a/tests/unit/test_psycopg3_parity_passthroughs.py b/tests/unit/test_psycopg3_parity_passthroughs.py index 1ea2d55bb..7afe740b4 100644 --- a/tests/unit/test_psycopg3_parity_passthroughs.py +++ b/tests/unit/test_psycopg3_parity_passthroughs.py @@ -258,9 +258,10 @@ def test_sync_wrapper_execute_delegates_with_all_kwargs() -> None: target = MagicMock() wrapper = _sync_wrapper(target) # Route plugin_manager.execute straight to the provided callable so the - # underlying cursor work actually runs. + # underlying cursor work actually runs. Like the plugin manager, pass the + # call's arguments on: the cursor's driver function takes them. wrapper._plugin_manager.execute = MagicMock( # type: ignore[method-assign] - side_effect=lambda obj, method, func, *a, **k: func()) + side_effect=lambda obj, method, func, *a, **k: func(*a, **k)) result = wrapper.execute("SELECT 1", ("p",), prepare=True, binary=True) diff --git a/tests/unit/test_sql_alchemy_driver_dialect.py b/tests/unit/test_sql_alchemy_driver_dialect.py index 314876011..4be7a11f8 100644 --- a/tests/unit/test_sql_alchemy_driver_dialect.py +++ b/tests/unit/test_sql_alchemy_driver_dialect.py @@ -12,11 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. +import threading + import pytest import sqlalchemy from aws_advanced_python_wrapper.driver_dialect import DriverDialect from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.pg_driver_dialect import PgDriverDialect from aws_advanced_python_wrapper.sqlalchemy_driver_dialect import \ SqlAlchemyDriverDialect from aws_advanced_python_wrapper.utils.properties import Properties @@ -117,3 +121,26 @@ def test_transfer_session_states_with_null_connection(underlying_dialect, sqlalc sqlalchemy_dialect = SqlAlchemyDriverDialect(underlying_dialect, Properties()) with pytest.raises(AwsWrapperError): sqlalchemy_dialect.set_read_only(sqlalchemy_mock_conn, False) + + +def test_loop_start_runs_on_the_calling_thread_with_socket_timeout(sqlalchemy_mock_conn): + props = Properties({"socket_timeout": "5"}) + sqlalchemy_dialect = SqlAlchemyDriverDialect(PgDriverDialect(props), props) + threads = [] + + sqlalchemy_dialect.execute( + DbApiMethod.CURSOR_ITER.method_name, lambda: threads.append(threading.current_thread()), conn=sqlalchemy_mock_conn) + + assert threads == [threading.current_thread()] + + +@pytest.mark.parametrize("method", [DbApiMethod.CURSOR_FETCHONE, DbApiMethod.CURSOR_NEXT], ids=["fetchone", "next"]) +def test_fetch_still_runs_on_the_timeout_worker_with_socket_timeout(method, sqlalchemy_mock_conn): + props = Properties({"socket_timeout": "5"}) + sqlalchemy_dialect = SqlAlchemyDriverDialect(PgDriverDialect(props), props) + threads = [] + + sqlalchemy_dialect.execute( + method.method_name, lambda: threads.append(threading.current_thread()), conn=sqlalchemy_mock_conn) + + assert len(threads) == 1 and threads[0] is not threading.current_thread() diff --git a/tests/unit/test_type_marker.py b/tests/unit/test_type_marker.py new file mode 100644 index 000000000..a925f42f3 --- /dev/null +++ b/tests/unit/test_type_marker.py @@ -0,0 +1,72 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import date, datetime, time, timezone +from decimal import Decimal + +import pytest + +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker + + +class TestFromObject: + @pytest.mark.parametrize("value,expected", [ + ("s", TypeMarker.STRING), + (b"x", TypeMarker.BYTE_ARRAY), + (bytearray(b"x"), TypeMarker.BYTE_ARRAY), + (memoryview(b"x"), TypeMarker.BYTE_ARRAY), + (True, TypeMarker.BOOLEAN), # must win over int + (False, TypeMarker.BOOLEAN), + (5, TypeMarker.LONG), # every Python int but bool -> LONG + (5.0, TypeMarker.DOUBLE), + (Decimal("1.5"), TypeMarker.BIG_DECIMAL), + (datetime(2020, 1, 1), TypeMarker.LOCAL_DATE_TIME), # must win over date + (datetime(2020, 1, 1, tzinfo=timezone.utc), TypeMarker.TIMESTAMP), # aware: an instant + (date(2020, 1, 1), TypeMarker.LOCAL_DATE), + (time(1, 2, 3), TypeMarker.LOCAL_TIME), + (object(), TypeMarker.GENERIC), + ]) + def test_from_object(self, value, expected): + assert TypeMarker.from_object(value) == expected + + +class TestFromValue: + def test_known(self): + assert TypeMarker.from_value(TypeMarker.STRING) == TypeMarker.STRING + + def test_unknown_raises(self): + with pytest.raises(ValueError): + TypeMarker.from_value(200) + + +class TestNames: + def test_name_for_known(self): + assert TypeMarker.name_for(TypeMarker.LONG) == "LONG" + + def test_name_for_unknown(self): + assert TypeMarker.name_for(200) is None + + def test_is_known(self): + assert TypeMarker.is_known(TypeMarker.GENERIC) + assert not TypeMarker.is_known(200) + + +def test_marker_numbers_never_change(): + # The marker numbers are stored in every payload, so they can't change + # without breaking values already written. + assert (TypeMarker.STRING, TypeMarker.INTEGER, TypeMarker.LONG, TypeMarker.DOUBLE, + TypeMarker.FLOAT, TypeMarker.BOOLEAN, TypeMarker.BIG_DECIMAL, TypeMarker.DATE, + TypeMarker.TIME, TypeMarker.TIMESTAMP, TypeMarker.LOCAL_DATE, TypeMarker.LOCAL_TIME, + TypeMarker.LOCAL_DATE_TIME, TypeMarker.BYTE_ARRAY, TypeMarker.GENERIC) == \ + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 99)