From c1f239a08cdb90375de3fefc70239e35e23e1785 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Tue, 27 Oct 2026 19:57:47 -0700 Subject: [PATCH 1/3] feat: plugin call context for cursor execute arguments --- CHANGELOG.md | 6 + aws_advanced_python_wrapper/driver_dialect.py | 4 +- .../mysql_driver_dialect.py | 1 + aws_advanced_python_wrapper/pep249_methods.py | 19 +- .../pg_driver_dialect.py | 1 + aws_advanced_python_wrapper/plugin.py | 12 + aws_advanced_python_wrapper/plugin_service.py | 111 ++++- .../read_write_splitting_plugin.py | 1 + aws_advanced_python_wrapper/wrapper.py | 50 ++- docs/development-guide/LoadablePlugins.md | 12 + docs/development-guide/PluginService.md | 38 ++ tests/unit/test_connection.py | 375 ++++++++++++++++- tests/unit/test_plugin_manager.py | 387 +++++++++++++++++- .../unit/test_psycopg3_parity_passthroughs.py | 5 +- tests/unit/test_sql_alchemy_driver_dialect.py | 27 ++ 15 files changed, 1022 insertions(+), 27 deletions(-) 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/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 b87b44c00..db3b6da59 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 c55fdff02..a5d788135 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/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/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_plugin_manager.py b/tests/unit/test_plugin_manager.py index 97c6e88bf..6474241ec 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): @@ -712,3 +721,377 @@ def test_must_use_pipeline(mocker, container, mock_telemetry_factory): manager._function_cache[DbApiMethod.CURSOR_LASTROWID.id] = \ manager._make_pipeline(DbApiMethod.CURSOR_LASTROWID.method_name) 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": ()} 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() From 89f9130d2ada5e8127b79df2ba1f831c867f4b06 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Tue, 27 Oct 2026 19:57:47 -0700 Subject: [PATCH 2/3] feat: kms encryption crypto core and key/metadata layer --- .../encryption/__init__.py | 13 + .../encryption/algorithm.py | 68 ++ .../encryption/buffers.py | 34 + .../encryption/config.py | 179 ++++ .../encryption/connection_source.py | 113 +++ .../encryption/data_key_cache.py | 228 +++++ .../encryption/encryption_service.py | 529 +++++++++++ .../encryption/key_management_utility.py | 270 ++++++ .../encryption/key_manager.py | 445 +++++++++ .../encryption/metadata_manager.py | 302 ++++++ .../encryption/models.py | 158 ++++ .../encryption/sql_dialect.py | 162 ++++ .../encryption/type_marker.py | 113 +++ aws_advanced_python_wrapper/errors.py | 119 ++- ...dvanced_python_wrapper_messages.properties | 34 + .../utils/properties.py | 75 ++ poetry.lock | 222 ++++- pyproject.toml | 13 + .../encryption/conformance_vectors.json | 122 +++ .../generate_conformance_vectors.py | 123 +++ tests/unit/test_connection_source.py | 154 ++++ tests/unit/test_data_key_cache.py | 275 ++++++ tests/unit/test_encryption_config.py | 253 +++++ tests/unit/test_encryption_conformance.py | 126 +++ tests/unit/test_encryption_import_guard.py | 132 +++ tests/unit/test_encryption_service.py | 864 ++++++++++++++++++ tests/unit/test_key_management_utility.py | 320 +++++++ tests/unit/test_key_manager.py | 847 +++++++++++++++++ tests/unit/test_metadata_manager.py | 517 +++++++++++ tests/unit/test_type_marker.py | 72 ++ 30 files changed, 6880 insertions(+), 2 deletions(-) create mode 100644 aws_advanced_python_wrapper/encryption/__init__.py create mode 100644 aws_advanced_python_wrapper/encryption/algorithm.py create mode 100644 aws_advanced_python_wrapper/encryption/buffers.py create mode 100644 aws_advanced_python_wrapper/encryption/config.py create mode 100644 aws_advanced_python_wrapper/encryption/connection_source.py create mode 100644 aws_advanced_python_wrapper/encryption/data_key_cache.py create mode 100644 aws_advanced_python_wrapper/encryption/encryption_service.py create mode 100644 aws_advanced_python_wrapper/encryption/key_management_utility.py create mode 100644 aws_advanced_python_wrapper/encryption/key_manager.py create mode 100644 aws_advanced_python_wrapper/encryption/metadata_manager.py create mode 100644 aws_advanced_python_wrapper/encryption/models.py create mode 100644 aws_advanced_python_wrapper/encryption/sql_dialect.py create mode 100644 aws_advanced_python_wrapper/encryption/type_marker.py create mode 100644 tests/unit/resources/encryption/conformance_vectors.json create mode 100644 tests/unit/resources/encryption/generate_conformance_vectors.py create mode 100644 tests/unit/test_connection_source.py create mode 100644 tests/unit/test_data_key_cache.py create mode 100644 tests/unit/test_encryption_config.py create mode 100644 tests/unit/test_encryption_conformance.py create mode 100644 tests/unit/test_encryption_import_guard.py create mode 100644 tests/unit/test_encryption_service.py create mode 100644 tests/unit/test_key_management_utility.py create mode 100644 tests/unit/test_key_manager.py create mode 100644 tests/unit/test_metadata_manager.py create mode 100644 tests/unit/test_type_marker.py diff --git a/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/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index a87c4d285..fbc44aafe 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 9623c83fe..976091009 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -215,6 +215,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/poetry.lock b/poetry.lock index d8d207ae3..0cd125546 100644 --- a/poetry.lock +++ b/poetry.lock @@ -840,6 +840,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" @@ -1114,6 +1228,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" @@ -2741,6 +2932,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.101" @@ -3963,7 +4180,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_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_type_marker.py b/tests/unit/test_type_marker.py new file mode 100644 index 000000000..a925f42f3 --- /dev/null +++ b/tests/unit/test_type_marker.py @@ -0,0 +1,72 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import date, datetime, time, timezone +from decimal import Decimal + +import pytest + +from aws_advanced_python_wrapper.encryption.type_marker import TypeMarker + + +class TestFromObject: + @pytest.mark.parametrize("value,expected", [ + ("s", TypeMarker.STRING), + (b"x", TypeMarker.BYTE_ARRAY), + (bytearray(b"x"), TypeMarker.BYTE_ARRAY), + (memoryview(b"x"), TypeMarker.BYTE_ARRAY), + (True, TypeMarker.BOOLEAN), # must win over int + (False, TypeMarker.BOOLEAN), + (5, TypeMarker.LONG), # every Python int but bool -> LONG + (5.0, TypeMarker.DOUBLE), + (Decimal("1.5"), TypeMarker.BIG_DECIMAL), + (datetime(2020, 1, 1), TypeMarker.LOCAL_DATE_TIME), # must win over date + (datetime(2020, 1, 1, tzinfo=timezone.utc), TypeMarker.TIMESTAMP), # aware: an instant + (date(2020, 1, 1), TypeMarker.LOCAL_DATE), + (time(1, 2, 3), TypeMarker.LOCAL_TIME), + (object(), TypeMarker.GENERIC), + ]) + def test_from_object(self, value, expected): + assert TypeMarker.from_object(value) == expected + + +class TestFromValue: + def test_known(self): + assert TypeMarker.from_value(TypeMarker.STRING) == TypeMarker.STRING + + def test_unknown_raises(self): + with pytest.raises(ValueError): + TypeMarker.from_value(200) + + +class TestNames: + def test_name_for_known(self): + assert TypeMarker.name_for(TypeMarker.LONG) == "LONG" + + def test_name_for_unknown(self): + assert TypeMarker.name_for(200) is None + + def test_is_known(self): + assert TypeMarker.is_known(TypeMarker.GENERIC) + assert not TypeMarker.is_known(200) + + +def test_marker_numbers_never_change(): + # The marker numbers are stored in every payload, so they can't change + # without breaking values already written. + assert (TypeMarker.STRING, TypeMarker.INTEGER, TypeMarker.LONG, TypeMarker.DOUBLE, + TypeMarker.FLOAT, TypeMarker.BOOLEAN, TypeMarker.BIG_DECIMAL, TypeMarker.DATE, + TypeMarker.TIME, TypeMarker.TIMESTAMP, TypeMarker.LOCAL_DATE, TypeMarker.LOCAL_TIME, + TypeMarker.LOCAL_DATE_TIME, TypeMarker.BYTE_ARRAY, TypeMarker.GENERIC) == \ + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 99) From 448d68c33ae3be486ff292494d2938c4ec2bf44b Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Tue, 27 Oct 2026 19:57:48 -0700 Subject: [PATCH 3/3] feat: sql analysis --- .../encryption/metadata_manager.py | 36 +- .../encryption/sql_analyzer.py | 1448 +++++++++++++ .../encryption/sql_dialect.py | 46 + .../encryption/sql_tokenizer.py | 581 ++++++ ...dvanced_python_wrapper_messages.properties | 1 + poetry.lock | 22 +- pyproject.toml | 9 +- tests/unit/test_encryption_import_guard.py | 52 +- tests/unit/test_metadata_manager.py | 60 + tests/unit/test_sql_analyzer.py | 1815 +++++++++++++++++ tests/unit/test_sql_tokenizer.py | 415 ++++ 11 files changed, 4467 insertions(+), 18 deletions(-) create mode 100644 aws_advanced_python_wrapper/encryption/sql_analyzer.py create mode 100644 aws_advanced_python_wrapper/encryption/sql_tokenizer.py create mode 100644 tests/unit/test_sql_analyzer.py create mode 100644 tests/unit/test_sql_tokenizer.py diff --git a/aws_advanced_python_wrapper/encryption/metadata_manager.py b/aws_advanced_python_wrapper/encryption/metadata_manager.py index 1b2934988..693b08520 100644 --- a/aws_advanced_python_wrapper/encryption/metadata_manager.py +++ b/aws_advanced_python_wrapper/encryption/metadata_manager.py @@ -42,6 +42,7 @@ class _Snapshot(NamedTuple): + # Keyed by SqlDialect.metadata_key of the names. columns: Mapping[Tuple[str, str], ColumnEncryptionConfig] by_table: Mapping[str, Tuple[ColumnEncryptionConfig, ...]] loaded_at: float # time.monotonic() @@ -60,6 +61,12 @@ class MetadataManager: refresh is on. Before :meth:`start`, after :meth:`close`, or with the cache disabled, each lookup queries the database. + Lookups compare names the way the engine does + (:meth:`SqlDialect.metadata_key`): exactly on PostgreSQL, where names are + stored as the catalog has them (``users`` for an unquoted ``Users``), and + case-insensitively on MySQL. That matches what the uncached query's + ``WHERE`` does, given the default (case-insensitive) MySQL collations. + Call :meth:`close` when done. The refresh thread holds the manager only weakly, so a manager dropped without ``close`` still stops its thread once it is garbage-collected. @@ -162,7 +169,7 @@ def column_config(self, table_name: Optional[str], column_name: Optional[str]) - return None snapshot = self._usable_snapshot(table_name, column_name) if snapshot is not None: - return snapshot.columns.get((table_name, column_name)) + return snapshot.columns.get((self._sql.metadata_key(table_name), self._sql.metadata_key(column_name))) rows = self._query( f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s AND em.column_name {self._sql.equals} %s", (table_name, column_name), table_name=table_name, column_name=column_name) @@ -174,7 +181,7 @@ def table_configs(self, table_name: Optional[str]) -> Sequence[ColumnEncryptionC return () snapshot = self._usable_snapshot(table_name) if snapshot is not None: - return snapshot.by_table.get(table_name, ()) + return snapshot.by_table.get(self._sql.metadata_key(table_name), ()) rows = self._query(f"{self._joined_sql()} WHERE em.table_name {self._sql.equals} %s", (table_name,), table_name=table_name) return tuple(self._to_column_config(row) for row in rows) @@ -213,11 +220,12 @@ def _load_snapshot(self, *, table_name: Optional[str] = None, column_name: Optio # returned. loaded_at = time.monotonic() columns = self._load_all(table_name=table_name, column_name=column_name) + key = self._sql.metadata_key by_table: Dict[str, List[ColumnEncryptionConfig]] = {} for config in columns.values(): - by_table.setdefault(config.table_name, []).append(config) + by_table.setdefault(key(config.table_name), []).append(config) snapshot = _Snapshot( - MappingProxyType(dict(columns)), + MappingProxyType({(key(c.table_name), key(c.column_name)): c for c in columns.values()}), MappingProxyType({t: tuple(c) for t, c in by_table.items()}), loaded_at) with self._lifecycle_lock: @@ -269,8 +277,8 @@ def _joined_sql(self) -> str: def _to_column_config(row: Mapping[str, Any]) -> ColumnEncryptionConfig: key_metadata = None if row.get(f"{_KS_PREFIX}id") is None else KeyMetadata.from_row(row, _KS_PREFIX) return ColumnEncryptionConfig( - table_name=row["table_name"], - column_name=row["column_name"], + table_name=MetadataManager._name(row, "table_name"), + column_name=MetadataManager._name(row, "column_name"), algorithm=row.get("encryption_algorithm") or EncryptionAlgorithm.DEFAULT, key_id=None if row.get("key_id") is None else int(row["key_id"]), key_metadata=key_metadata, @@ -278,6 +286,22 @@ def _to_column_config(row: Mapping[str, Any]) -> ColumnEncryptionConfig: updated_at=row.get("updated_at"), ) + @staticmethod + def _name(row: Mapping[str, Any], field: str) -> str: + # A driver can return text as bytes (psycopg on a SQL_ASCII database, + # Connector/Python with use_unicode=False). Such a name would never + # match the str names parsed from SQL, so an encrypted column would + # look like an ordinary one: decode it, and refuse anything else. + value = row[field] + if isinstance(value, str): + return value + if isinstance(value, (bytes, bytearray, memoryview)): + try: + return bytes(value).decode("utf-8") + except UnicodeDecodeError: + pass + raise MetadataError(Messages.get_formatted("MetadataManager.InvalidName", field, type(value).__name__)) + @staticmethod def _finalize(stop: Event, thread_holder: List[Optional[Thread]]) -> None: # Runs when an unclosed manager is collected. The collection can happen diff --git a/aws_advanced_python_wrapper/encryption/sql_analyzer.py b/aws_advanced_python_wrapper/encryption/sql_analyzer.py new file mode 100644 index 000000000..e4efb1608 --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_analyzer.py @@ -0,0 +1,1448 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Works out which bind parameter of a statement fills or is compared with +which column, so values bound for an encrypted column can be encrypted. + +:func:`analyze` finds the placeholders the way the driver does +(:mod:`.sql_tokenizer`), parses the statement with ``sqlglot``, and pairs each +placeholder with a column by its position, which the normalized SQL carries in +the placeholder's name. It knows nothing about encryption metadata: the +plugin looks the reported columns up. + +The analysis is best effort, and reports where it fell short: +:attr:`StatementAnalysis.gap` is ``None`` only when every column the statement +itself writes (not one written by a routine, ``CALL`` or ``DO`` it runs) was +established, either as filled by a placeholder +(:attr:`~StatementAnalysis.assignments`) or by something else +(:attr:`~StatementAnalysis.unbound_writes`). A statement that could not be +parsed is never mistaken for one that writes nothing. +""" + +from __future__ import annotations + +import logging +import re +import threading +from contextlib import contextmanager +from dataclasses import dataclass, field +from enum import Enum +from functools import lru_cache +from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List, + Optional, Sequence, Set, Tuple) + +try: + import sqlglot + from sqlglot import exp +except ModuleNotFoundError as e: # pragma: no cover - exercised by the import-guard test + # Only a missing package gets the install hint; a broken install raises + # its own error. + if (e.name or "").partition(".")[0] != "sqlglot": + raise + raise ImportError( + "The KMS encryption plugin needs the 'sqlglot' package. " + "Install it with: pip install 'aws-advanced-python-wrapper[encryption]'") from e + +from aws_advanced_python_wrapper.encryption.sql_tokenizer import ( + ColumnRef, ParamStyle, Placeholder, TokenizedSql, normalized_ordinal, + tokenize) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + + +class StatementKind(Enum): + """What the (first) statement is.""" + + SELECT = "SELECT" + INSERT = "INSERT" # also MySQL REPLACE + UPDATE = "UPDATE" + DELETE = "DELETE" + MERGE = "MERGE" + COPY_FROM = "COPY_FROM" + COPY_TO = "COPY_TO" + #: Recognized but not one the analysis reads (DDL, SET, CALL...). + OTHER = "OTHER" + #: Not established: the statement could not be parsed, was not parsed + #: (see :attr:`StatementAnalysis.gap`), or its parse was not trusted. + UNKNOWN = "UNKNOWN" + + +class AnalysisGap(Enum): + """Why a statement's parameters or written columns could not all be + established. The values are fixed text, safe to log.""" + + #: The SQL could not be parsed (or ran out inside a quote or comment). + UNPARSEABLE = "the statement could not be parsed" + #: A placeholder sits inside a quoted literal, quoted identifier or + #: comment, where the driver still binds it. The tables the statement + #: names are still listed, but no placeholder's column is inferred. + HIDDEN_PLACEHOLDER = "a placeholder is inside a quoted literal, quoted identifier or comment" + #: The driver will reject the statement's placeholders. + DRIVER_ERROR = "the driver will reject the placeholders" + #: The parsed statement does not have exactly the placeholders the driver + #: binds, so the parse can't be trusted. + PLACEHOLDER_MISMATCH = "the parsed statement does not match its placeholders" + #: MySQL runs the body of a ``/*! ... */`` comment, which the analysis + #: can't read as SQL. + EXECUTABLE_COMMENT = "the statement has a MySQL executable comment" + #: The statement may write but is not a form the analysis reads + #: (``EXPLAIN ANALYZE INSERT``, ``EXECUTE``, ``LOAD DATA``, ...). + UNSUPPORTED_STATEMENT = "the statement is not a form the analysis reads" + #: A ``PREPARE``: its ``$n`` parameters are bound by a later ``EXECUTE``, + #: which the analysis does not see. + PREPARED_PARAMETERS = "the prepared statement's parameters arrive with a later EXECUTE" + #: An ``INSERT`` (or ``MERGE ... INSERT``, ``COPY ... FROM``) with no column + #: list, or ``DEFAULT VALUES``. + NO_COLUMN_LIST = "the statement does not name the columns it writes" + #: ``INSERT ... SELECT`` and similar: the rows come from a query, so which + #: value fills which column is not read. + VALUES_FROM_QUERY = "the values come from a query" + #: A ``VALUES`` row with more or fewer values than columns. + ROW_LENGTH_MISMATCH = "a VALUES row does not match the column list" + #: An ``UPDATE`` of several tables assigns a column whose table can't be + #: told. + AMBIGUOUS_TABLE = "an assignment's table can't be established" + + +@dataclass(frozen=True, slots=True) +class TableRef: + """A table a statement names.""" + + name: str + schema: Optional[str] = None + + def __str__(self) -> str: + return self.name if self.schema is None else f"{self.schema}.{self.name}" + + +@dataclass(frozen=True, slots=True) +class ParameterUse: + """A placeholder whose value fills, or is compared with, a column.""" + + placeholder: Placeholder + column: ColumnRef + #: Types the value is cast to, outermost first (``%s::text::bytea`` -> + #: ``("VARBINARY", "TEXT")``), as ``sqlglot`` names them. + casts: Tuple[str, ...] = () + #: Compared with ``= ANY(...)``, ``ALL(...)`` or ``SOME(...)``: the value + #: is a list. + array: bool = False + #: For a comparison: when it never matches, it can only remove rows from + #: what the statement reads or changes. Always true for an assignment or + #: an annotation. + safe: bool = True + + @property + def ordinal(self) -> int: + return self.placeholder.ordinal + + +@dataclass(frozen=True, slots=True) +class StatementAnalysis: + """What :func:`analyze` established about one SQL string.""" + + kind: StatementKind + #: The string stores values: an INSERT, UPDATE, MERGE, COPY ... FROM, a + #: data-modifying CTE, a PREPARE of one of those, or (when it could not + #: be read) a statement whose keywords say it may write. + writes: bool + placeholders: Tuple[Placeholder, ...] + #: Every table the string names, without duplicates and excluding CTE + #: names (outer queries first, not in text order). + tables: Tuple[TableRef, ...] = () + #: The tables it writes. + written_tables: Tuple[TableRef, ...] = () + #: Placeholders written into a column. + assignments: Tuple[ParameterUse, ...] = () + #: Placeholders compared with a column (``WHERE``, ``ON``, ``HAVING``...). + comparisons: Tuple[ParameterUse, ...] = () + #: Placeholders annotated with ``/*@encrypt:...*/``. These take precedence + #: over the rest. Once the statement is parsed and its placeholders + #: matched, a qualifier is resolved through the aliases in scope at the + #: placeholder, and a bare column gets a table only when the statement + #: says which: the table the value is written to, or else the only table + #: the query around it reads. Otherwise the annotation is kept as + #: written, only folded. + annotations: Tuple[ParameterUse, ...] = () + #: Columns written with something other than a placeholder (a literal, an + #: expression, ``DEFAULT``, another column, a ``COPY`` stream). ``NULL`` + #: and copying a conflicting row's own value for the same column + #: (``EXCLUDED.c`` / ``VALUES(c)`` / a row alias) are not listed. + unbound_writes: Tuple[ColumnRef, ...] = () + #: The source column of each result column, by position, when the result + #: is a plain select list or ``RETURNING`` list: an entry is ``None`` for an + #: expression, a column of a subquery or CTE, or one whose table can't be + #: told. ``None`` altogether when unknown (``*``, set operations, + #: ``VALUES``, ``PREPARE``, several statements, no result). + result_columns: Optional[Tuple[Optional[ColumnRef], ...]] = None + #: Why the analysis is incomplete: for a statement that writes, why its + #: written columns could not all be established; for any statement, a + #: placeholder or parse problem that makes its parameters untrustworthy. + #: ``None`` when complete. + gap: Optional[AnalysisGap] = None + #: ``/*@encrypt:...*/`` comments that annotate nothing or can't be read. + stray_annotations: Tuple[str, ...] = () + #: Diagnostic detail for :attr:`gap`, safe to log: it never quotes the SQL. + detail: Optional[str] = field(default=None, compare=False) + + @property + def complete(self) -> bool: + return self.gap is None + + def parameter_columns(self) -> Dict[int, ColumnRef]: + """The column each placeholder belongs to, by ordinal: comparisons, + then assignments, then annotations, each overriding the last.""" + result: Dict[int, ColumnRef] = {} + for use in (*self.comparisons, *self.assignments, *self.annotations): + result[use.ordinal] = use.column + return result + + +#: Only short statements with few ``%`` signs (an upper bound on their +#: placeholders) are cached, as psycopg does with its own query cache. Bulk +#: INSERTs differ in their row count and rarely repeat, so caching them would +#: only make the cache large. +CACHEABLE_SQL_LENGTH = 4096 +CACHEABLE_PERCENT_SIGNS = 64 + + +def analyze(sql: str, dialect: SqlDialect, params: Any = None) -> StatementAnalysis: + """Analyze ``sql`` as the driver for ``dialect`` runs it with ``params`` + (the second argument of ``execute``; for ``executemany``, one of its + parameter sets). Only the kind of ``params`` matters (none, a sequence, a + mapping, and on MySQL whether it is empty), not its values. The result is + immutable and may be shared. + + :raises TypeError: if ``sql`` is not a ``str``. + """ + style = ParamStyle.of(params, dialect) + if isinstance(sql, str) and len(sql) <= CACHEABLE_SQL_LENGTH and sql.count("%") <= CACHEABLE_PERCENT_SIGNS: + try: + return _cached_analysis(sql, dialect, style) + except _Uncacheable as e: + return e.analysis + return _analysis(sql, dialect, style) + + +class _Uncacheable(Exception): + """Carries an analysis that must not be cached (lru_cache does not cache + exceptions).""" + + def __init__(self, analysis: StatementAnalysis): + super().__init__() + self.analysis = analysis + + +@lru_cache(maxsize=1024) +def _cached_analysis(sql: str, dialect: SqlDialect, style: ParamStyle) -> StatementAnalysis: + result = _analysis(sql, dialect, style) + if result.detail == RecursionError.__name__: + # Depends on how deep the calling thread's stack already is; another + # caller may parse the same SQL. + raise _Uncacheable(result) + return result + + +# Leading words of the statements handed to the parser. Anything else is +# reported without parsing it: sqlglot falls back to an opaque "command" for +# what it doesn't support, and logs it. +_PARSED = { + "postgresql": frozenset({"SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "MERGE", "COPY", "VALUES", "PREPARE"}), + "mysql": frozenset({"SELECT", "WITH", "INSERT", "REPLACE", "UPDATE", "DELETE", "VALUES"}), +} +_SQLGLOT_DIALECT = {"postgresql": "postgres", "mysql": "mysql"} +_WRITE_LEADING = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT", "LOAD", "EXECUTE"}) +_WRITE_WORDS = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT"}) +_KINDS = {"SELECT": StatementKind.SELECT, "WITH": StatementKind.SELECT, "VALUES": StatementKind.SELECT, + "TABLE": StatementKind.SELECT, "INSERT": StatementKind.INSERT, "REPLACE": StatementKind.INSERT, + "UPDATE": StatementKind.UPDATE, "DELETE": StatementKind.DELETE, "MERGE": StatementKind.MERGE} + +# Whitespace and comments, one character or one whole comment per repetition, +# with a line comment running through its newline. If the pattern could split +# the same text two ways, a failed match would backtrack exponentially. +_GAP = r"(?:\s|--[^\n]*(?:\n|\Z)|/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)*" + +# PREPARE name [(type, ...)] AS , on the normalized SQL. +_PREPARE = re.compile(rf""" + \A{_GAP} + PREPARE{_GAP}(?:"(?:[^"]|"")+"|[^\W\d][\w$]*){_GAP} + (?:\((?:[^()]|\([^()]*\))*\){_GAP})? + AS\b +""", re.IGNORECASE | re.VERBOSE) + +# MySQL: sqlglot rejects a qualified INSERT column list ("INSERT INTO t (t.a)"); +# a qualifier there can only name the target (the server rejects any other). +_MYSQL_NAME = r"(?:`(?:[^`]|``)+`|[\w$]+)" +_MYSQL_INSERT_COLUMNS = re.compile(rf""" + \A(?P{_GAP}INSERT{_GAP}(?:INTO{_GAP})?{_MYSQL_NAME}(?:\s*\.\s*{_MYSQL_NAME})*\s*\() + (?P[^()]*)\) +""", re.IGNORECASE | re.VERBOSE) +# One name of the column list, and the dot after it when it is a qualifier. +# A back-quoted name is one token, dots and all. +_MYSQL_COLUMN_PART = re.compile(rf"(?P{_MYSQL_NAME})(?P\s*\.\s*)?") + + +class _QuietWhileAnalyzing(logging.Filter): + """Drops sqlglot's records while this module parses on the current thread. + sqlglot logs the statement text (literals included) when it falls back to + an opaque command or reports an unsupported construct; the application's + own sqlglot logging is untouched.""" + + def __init__(self) -> None: + super().__init__() + self._local = threading.local() + + def filter(self, record: logging.LogRecord) -> bool: + return not getattr(self._local, "active", False) + + @contextmanager + def active(self) -> Iterator[None]: + previous = getattr(self._local, "active", False) + self._local.active = True + try: + yield + finally: + self._local.active = previous + + +_QUIET = _QuietWhileAnalyzing() +logging.getLogger("sqlglot").addFilter(_QUIET) + + +def _analysis(sql: str, dialect: SqlDialect, style: ParamStyle) -> StatementAnalysis: + tokens = tokenize(sql, dialect, style) + annotations = tuple(ParameterUse(p, p.annotation) for p in tokens.placeholders if p.annotation is not None) + + def result(**kwargs: Any) -> StatementAnalysis: + kwargs.setdefault("annotations", annotations) + return StatementAnalysis(placeholders=tokens.placeholders, stray_annotations=tokens.stray_annotations, + **kwargs) + + early: Optional[AnalysisGap] = None + if tokens.unterminated: + early = AnalysisGap.UNPARSEABLE + elif tokens.driver_error: + early = AnalysisGap.DRIVER_ERROR + elif tokens.has_hidden_placeholders: + early = AnalysisGap.HIDDEN_PLACEHOLDER + elif tokens.executable_comment: + early = AnalysisGap.EXECUTABLE_COMMENT + if early is not None: + # The parser reads a hidden placeholder as literal or comment text, so + # the tables are still known, and a caller can refuse the statement + # when one of them has encrypted columns. + tables = _named_tables(tokens, dialect) if early is AnalysisGap.HIDDEN_PLACEHOLDER else () + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), gap=early, detail=tokens.driver_error, + tables=tables) + + if not tokens.leading_words: + return result(kind=StatementKind.OTHER, writes=False) + if any(w not in _PARSED[dialect.name] for w in tokens.leading_words): + writes = _may_write(tokens) + kind = _KINDS.get(tokens.leading_words[0], StatementKind.OTHER) if len(tokens.leading_words) == 1 \ + else StatementKind.OTHER + return result(kind=kind, writes=writes, gap=AnalysisGap.UNSUPPORTED_STATEMENT if writes else None) + + parsed = _parse_statement(tokens, dialect) + if parsed is None: + writes = _may_write(tokens) + return result(kind=StatementKind.OTHER, writes=writes, + gap=AnalysisGap.UNSUPPORTED_STATEMENT if writes else None) + trees, failure = parsed + if trees is None: + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), gap=AnalysisGap.UNPARSEABLE, + detail=failure) + + mismatch = _placeholder_mismatch(trees, tokens) + if mismatch is not None or not trees or any(isinstance(t, exp.Command) for t in trees): + return result(kind=StatementKind.UNKNOWN, writes=_may_write(tokens), + gap=AnalysisGap.PLACEHOLDER_MISMATCH if mismatch else AnalysisGap.UNPARSEABLE, detail=mismatch) + + walker = _Walker(dialect, tokens, prepared=tokens.leading_words == ("PREPARE",)) + for tree in trees: + walker.statement(tree) + return walker.result(trees, annotations, result) + + +def _parse(text: str, dialect: SqlDialect) -> Tuple[Optional[List[exp.Expression]], Optional[str]]: + try: + with _QUIET.active(): + parsed = sqlglot.parse(text, read=_SQLGLOT_DIALECT[dialect.name]) + except Exception as e: # sqlglot raises ParseError/TokenError, but must never break a statement + # sqlglot's tokenizer re-raises a RecursionError as a TokenError. + cause: Optional[BaseException] = e + seen: Set[int] = set() + while cause is not None and id(cause) not in seen: + if isinstance(cause, RecursionError): + return None, RecursionError.__name__ + seen.add(id(cause)) + cause = cause.__cause__ or cause.__context__ + return None, type(e).__name__ + return [t for t in parsed if isinstance(t, exp.Expression)], None + + +def _parse_statement(tokens: TokenizedSql, dialect: SqlDialect) -> Optional[Tuple[Optional[List[exp.Expression]], Optional[str]]]: + """Parses the normalized SQL the way the analysis reads it. A PostgreSQL + ``PREPARE name AS`` prefix is left out, and a MySQL INSERT or REPLACE + that doesn't parse is tried again without its column qualifiers. ``None`` + when a PREPARE has no such prefix.""" + text = tokens.normalized + if tokens.leading_words == ("PREPARE",): + m = _PREPARE.match(text) + if m is None: + return None + text = text[m.end():] + + trees, failure = _parse(text, dialect) + if trees is None and tokens.leading_words in (("INSERT",), ("REPLACE",)) and dialect.name == "mysql": + unqualified = _without_insert_column_qualifiers(text) + if unqualified is not None: + trees, failure = _parse(unqualified, dialect) + return trees, failure + + +def _named_tables(tokens: TokenizedSql, dialect: SqlDialect) -> Tuple[TableRef, ...]: + """The tables the statement names, read from the text the analysis + parses; none when it doesn't parse.""" + parsed = _parse_statement(tokens, dialect) + trees = parsed[0] if parsed is not None else None + if not trees: + return () + walker = _Walker(dialect, tokens) + for tree in trees: + walker.collect_tables(tree) + return walker.tables + + +def _without_insert_column_qualifiers(text: str) -> Optional[str]: + m = _MYSQL_INSERT_COLUMNS.match(text) + if m is None or "." not in m.group("columns"): + return None + columns = _MYSQL_COLUMN_PART.sub(lambda part: "" if part.group("dot") else part.group(0), m.group("columns")) + return f"{m.group('head')}{columns}){text[m.end():]}" + + +def _may_write(tokens: TokenizedSql) -> bool: + # Keywords only: what a statement that could not be read may be doing. + words = tokens.keywords + for leading in tokens.leading_words: + if leading in _WRITE_LEADING or (leading == "COPY" and "FROM" in words): + return True + if leading in ("WITH", "EXPLAIN", "PREPARE") and words & _WRITE_WORDS: + return True + if leading == "EXPLAIN" and "EXECUTE" in words: + return True # EXPLAIN ANALYZE EXECUTE runs the prepared statement + # A MySQL executable comment can turn any statement into a write. + return tokens.executable_comment and bool(words & (_WRITE_WORDS | _WRITE_LEADING)) + + +def _placeholder_mismatch(trees: List[exp.Expression], tokens: TokenizedSql) -> Optional[str]: + seen: Set[int] = set() + for tree in trees: + for node in tree.find_all(exp.Placeholder): + ordinal = normalized_ordinal(node.name) + if ordinal is None: + continue # a "?" or ":name" the driver does not bind + if ordinal in seen or ordinal >= len(tokens.placeholders): + return "a placeholder appears more than once" + seen.add(ordinal) + if len(seen) != len(tokens.placeholders): + return f"{len(tokens.placeholders) - len(seen)} placeholder(s) missing from the parse" + return None + + +# ---- the walk ---- + +def _by_ordinal(use: ParameterUse) -> int: + return use.ordinal + + +#: What an alias or table name in scope names: a table, or ``None`` for a +#: subquery, CTE or function. +_Source = Optional[TableRef] +#: Maps an assignment's qualifier (if any) to the table it writes. +_TableOf = Callable[[Optional[str]], Optional[str]] +#: For a same-row copy in an upsert: qualifier key -> {source column key -> +#: the insert column key it carries}; ``None`` maps a column to itself. +_SameRow = Dict[str, Optional[Dict[str, str]]] + +_COMPARISONS = (exp.EQ, exp.NEQ, exp.GT, exp.GTE, exp.LT, exp.LTE, exp.NullSafeEQ, exp.NullSafeNEQ, + exp.Like, exp.ILike) +# Operators under which a value that never matches leaves the comparison false, +# unless negated (sqlglot reads NOT LIKE as a negated Like, with no NOT node) +# or applied over ALL(...). +_SAFE_OPERATORS = (exp.EQ, exp.NullSafeEQ, exp.In, exp.Like, exp.ILike) +# Join kinds that keep only the rows that match. +_INNER_JOIN_KINDS = frozenset({"", "INNER", "CROSS", "STRAIGHT_JOIN"}) +# What makes a SELECT aggregate: an aggregate or window function, or a +# function sqlglot doesn't know, which may be an aggregate (PostgreSQL's +# jsonb_agg, MySQL's JSON_ARRAYAGG, any user-defined one). Each entry of a +# WINDOW clause is a Window, so any WINDOW clause matches. +_AGGREGATING = (exp.AggFunc, exp.Window, exp.Anonymous) +_QUERIES = (exp.Select, exp.Update, exp.Delete, exp.Merge, exp.Insert) +_ARRAY_FUNCTIONS = frozenset({"ALL", "SOME", "ANY"}) +_WRITES = (exp.Insert, exp.Update, exp.Merge) +# Operators that test a value rather than produce one. Most of them are +# Predicates only from sqlglot 30.16, and MATCH ... AGAINST is not one in any +# version, so they are listed by name as well. +_TESTS = (exp.Predicate, exp.RegexpLike, exp.RegexpILike, exp.RegexpFullMatch, exp.ArrayOverlaps, exp.ArrayContains, + exp.ArrayContainsAll, exp.ArrayContainedBy, exp.JSONBContains, exp.JSONBContainsAnyTopKeys, + exp.JSONBContainsAllTopKeys, exp.Overlaps, exp.Adjacent, exp.ExtendsLeft, exp.ExtendsRight, + exp.MatchAgainst) +# Slots of a query whose values are not written: conditions, grouping +# (including a window's PARTITION BY), sorting, limits and RETURNING. A value +# bound there feeds no column of the write above. +_NOT_WRITTEN_ARGS = frozenset({"where", "having", "on", "condition", "group", "partition_by", "order", "limit", + "offset", "qualify", "returning"}) +# Slots of a query that hold its sources (CTEs, FROM, JOIN, LATERAL, USING). A +# value bound in a source may feed the write, or may only be compared with +# another table's column, so the table it is written to can't be told. +_SOURCE_ARGS = frozenset({"with_", "from_", "joins", "laterals", "using"}) +# The Select args a "SELECT p0, p1 FROM (VALUES ...) AS v(p0, p1)" may set and +# still be read as plain rows (ORDER BY changes no row's values). +_PLAIN_SELECT_ARGS = frozenset({"expressions", "from_", "order"}) + +# How many derived tables or CTEs a result column is followed through. +_MAX_DEPTH = 8 + + +class _Walker: + """Collects what one or more parsed statements write, compare and read.""" + + def __init__(self, dialect: SqlDialect, tokens: TokenizedSql, prepared: bool = False): + self._dialect = dialect + self._tokens = tokens + # The body of a PREPARE: its $n parameters are bound later. + self._prepared = prepared + self._kind: Optional[StatementKind] = None + self._writes = False + self._tables: Dict[TableRef, None] = {} + self._written: Dict[TableRef, None] = {} + self._assignments: List[ParameterUse] = [] + self._comparisons: List[ParameterUse] = [] + self._unbound: List[ColumnRef] = [] + self._gap: Optional[AnalysisGap] = None + self._cte_names: Set[str] = set() + # Ids of the SET and ON CONFLICT assignments (EQ nodes), which are + # neither comparisons nor tests. + self._assignment_nodes: Set[int] = set() + self._scopes: Dict[int, Dict[str, _Source]] = {} + # Nearest enclosing query of a node, memoized so a long AND/OR chain + # is resolved in linear time. + self._nearest: Dict[int, Optional[exp.Expression]] = {} + # The query that decides whether a condition under a node (AND, OR, + # parentheses) is in a safe position, or None when it can't be (see + # _deciding_query), memoized so a long AND/OR chain is resolved in + # linear time; and whether each query's own position is safe. + self._deciders: Dict[int, Optional[exp.Expression]] = {} + self._safe: Dict[int, bool] = {} + # Per statement, its tables without a schema by name: where its CTEs + # are read. + self._tables_by_name: Dict[int, Dict[str, List[exp.Table]]] = {} + self._placeholder_nodes: Dict[int, exp.Expression] = {} + # Tables each write node (INSERT, UPDATE, MERGE) writes. + self._written_by: Dict[int, List[TableRef]] = {} + + # ---- entry ---- + + def statement(self, tree: exp.Expression) -> None: + self.collect_tables(tree) + for found in tree.find_all(exp.Placeholder): + ordinal = normalized_ordinal(found.name) + if ordinal is not None: + self._placeholder_nodes[ordinal] = found + + kind = self._statement_kind(tree) + if self._kind is None: + self._kind = kind + + # Every write, wherever it sits: the statement itself or a + # data-modifying CTE. MERGE's own WHEN ... INSERT/UPDATE are read by + # the MERGE. + for node in tree.walk(): + if isinstance(node, exp.Insert) and not isinstance(node.parent, exp.When): + self._insert(node) + elif isinstance(node, exp.Update) and not isinstance(node.parent, exp.When): + self._update(node) + elif isinstance(node, exp.Merge): + self._merge(node) + elif isinstance(node, exp.Copy): + self._copy(node) + self._collect_comparisons(tree) + + def collect_tables(self, tree: exp.Expression) -> None: + """Adds the tables ``tree`` names, leaving out its CTE names.""" + for cte in tree.find_all(exp.CTE): + alias = cte.args.get("alias") + if isinstance(alias, exp.TableAlias): + self._cte_names.add(self._key(alias.this)) + for table in tree.find_all(exp.Table): + ref = self._table_ref(table) + if ref is not None: + self._tables.setdefault(ref, None) + + @property + def tables(self) -> Tuple[TableRef, ...]: + return tuple(self._tables) + + def result(self, trees: List[exp.Expression], annotations: Tuple[ParameterUse, ...], + build: Callable[..., StatementAnalysis]) -> StatementAnalysis: + assignments = tuple(sorted(self._assignments, key=_by_ordinal)) + comparisons = tuple(sorted(self._comparisons, key=_by_ordinal)) + inferred = {use.ordinal: use.column for use in (*comparisons, *assignments)} + resolved = tuple(ParameterUse(a.placeholder, self._resolve_annotation(a.placeholder, a.column, inferred)) + for a in annotations) + if self._prepared: + self._note(AnalysisGap.PREPARED_PARAMETERS) + return build( + kind=self._kind or StatementKind.OTHER, + writes=self._writes, + tables=tuple(self._tables), + written_tables=tuple(self._written), + assignments=assignments, + comparisons=comparisons, + annotations=resolved, + unbound_writes=tuple(self._unbound), + result_columns=self._result_columns(trees[0]) if len(trees) == 1 and not self._prepared else None, + gap=self._gap if self._writes else None) + + # ---- statements ---- + + def _statement_kind(self, tree: exp.Expression) -> StatementKind: + if isinstance(tree, exp.Copy): + return StatementKind.COPY_FROM if tree.args.get("kind") else StatementKind.COPY_TO + for cls, kind in ((exp.Insert, StatementKind.INSERT), (exp.Update, StatementKind.UPDATE), + (exp.Delete, StatementKind.DELETE), (exp.Merge, StatementKind.MERGE), + (exp.Query, StatementKind.SELECT), (exp.Values, StatementKind.SELECT)): + if isinstance(tree, cls): + return kind + return StatementKind.OTHER + + def _insert(self, node: exp.Insert) -> None: + self._writes = True + target = node.this + columns: Optional[List[Optional[str]]] = None + if isinstance(target, exp.Schema): + table = target.this + columns = [self._identifier(i) for i in target.expressions] + else: + table = target + # sqlglot attaches the column list of "INSERT INTO t AS a (c)" to + # the alias. + alias = table.args.get("alias") if isinstance(table, exp.Table) else None + if alias is not None and alias.columns: + columns = [self._identifier(i) for i in alias.columns] + ref = self._written_table(table, node) + name = None if ref is None else ref.name + if ref is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + if columns is not None and any(c is None for c in columns): + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + columns = None + + source = node.expression + if columns is None: + self._note(AnalysisGap.NO_COLUMN_LIST) + elif isinstance(source, exp.Values): + self._insert_rows(columns, name, source.expressions) + elif source is None: + self._note(AnalysisGap.NO_COLUMN_LIST) # DEFAULT VALUES + elif not self._insert_from_values(columns, name, source): + self._note(AnalysisGap.VALUES_FROM_QUERY) + + conflict = node.args.get("conflict") + if isinstance(conflict, exp.OnConflict): + self._upsert(conflict, name, columns, source) + + def _insert_rows(self, columns: List[Optional[str]], table: Optional[str], rows: List[exp.Expression], + positions: Optional[List[Tuple[int, Tuple[str, ...]]]] = None) -> None: + # positions: for each insert column, the position in the row that + # fills it and the casts on the way (default: the same position). + for row in rows: + values = self._row_values(row) + width = len(columns) if positions is None else max(p for p, _ in positions) + 1 + if values is None or (len(values) != width if positions is None else len(values) < width): + self._note(AnalysisGap.ROW_LENGTH_MISMATCH) + if values is None: + continue + for i, column in enumerate(columns): + position, casts = (i, ()) if positions is None else positions[i] + if position < len(values) and column is not None: + self._write(ColumnRef(column, table), values[position], casts) + + def _insert_from_values(self, columns: List[Optional[str]], table: Optional[str], + source: exp.Expression) -> bool: + """``INSERT INTO t (a, b) SELECT x, y FROM (VALUES (...), ...) AS v(x, y)``, + the form SQLAlchemy uses for a multi-row ORM insert. When each insert + column is filled by a different column of the VALUES list (possibly + cast), it is read like an ordinary multi-row VALUES. An ORDER BY is + allowed. A join, a filter, an expression other than a cast, or one + VALUES column filling two insert columns is not.""" + if not isinstance(source, exp.Select) or len(source.expressions) != len(columns): + return False + if any(value for key, value in source.args.items() if key not in _PLAIN_SELECT_ARGS): + return False # a join, a filter, a limit, ... (or an arg this code does not know) + from_ = source.args.get("from_") + values = from_.this if isinstance(from_, exp.From) else None + alias = values.args.get("alias") if isinstance(values, exp.Values) else None + if not isinstance(alias, exp.TableAlias) or not alias.columns: + return False + names = {self._key(c): i for i, c in enumerate(alias.columns)} + alias_key = self._key(alias.this) + positions: List[Tuple[int, Tuple[str, ...]]] = [] + for item in source.expressions: + inner, casts = self._unwrap_casts(item) + qualifier = inner.args.get("table") if isinstance(inner, exp.Column) else None + if not isinstance(inner, exp.Column) or not isinstance(inner.this, exp.Identifier) \ + or (qualifier is not None and self._key(qualifier) != alias_key) \ + or self._key(inner.this) not in names: + return False + positions.append((names[self._key(inner.this)], casts)) + if len({position for position, _ in positions}) != len(positions): + return False # one value would fill two columns + assert isinstance(values, exp.Values) + self._insert_rows(columns, table, values.expressions, positions) + return True + + def _upsert(self, conflict: exp.OnConflict, table: Optional[str], columns: Optional[List[Optional[str]]], + source: Optional[exp.Expression]) -> None: + same_row: _SameRow = {} + if self._dialect.name != "mysql": + same_row[self._key("excluded")] = None + row_alias = source.args.get("alias") if isinstance(source, exp.Values) else None + if isinstance(row_alias, exp.TableAlias): + renamed: Optional[Dict[str, str]] = None + if row_alias.columns: + # AS new(c1, c2) renames the inserted columns by position. + renamed = {} + for alias_column, column in zip(row_alias.columns, columns or ()): + if column is not None: + renamed[self._key(alias_column)] = self._dialect.metadata_key(column) + same_row[self._key(row_alias.this)] = renamed + for assignment in conflict.expressions: + self._assign(assignment, lambda _q: table, same_row=same_row) + + def _update(self, node: exp.Update) -> None: + self._writes = True + target = node.this + joins = (target.args.get("joins") or []) if isinstance(target, exp.Table) else [] + targets = [target] + [j.this for j in joins] + scope = self._scope(node) + ref = self._written_table(target, node) + if ref is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + for extra in targets[1:]: + self._written_table(extra, node) + + def table_of(qualifier: Optional[str]) -> Optional[str]: + if len(targets) == 1: + # One table to write: a qualifier can only mean it. + # PostgreSQL's FROM adds tables to read, not to write. + return None if ref is None else ref.name + source = scope.get(self._dialect.metadata_key(qualifier)) if qualifier else None + if source is None: + self._note(AnalysisGap.AMBIGUOUS_TABLE) + return None + return source.name + + for assignment in node.expressions: + self._assign(assignment, table_of) + + def _merge(self, node: exp.Merge) -> None: + self._writes = True + ref = self._written_table(node.this, node) + name = None if ref is None else ref.name + whens = node.args.get("whens") + for when in (whens.expressions if whens is not None else ()): + then = when.args.get("then") + if isinstance(then, exp.Update): + for assignment in then.expressions: + self._assign(assignment, lambda _q: name) + elif isinstance(then, exp.Insert): + columns = [self._identifier(c) for c in then.this.expressions] \ + if isinstance(then.this, exp.Tuple) else None + if columns is None or any(c is None for c in columns): + self._note(AnalysisGap.NO_COLUMN_LIST if columns is None else AnalysisGap.UNSUPPORTED_STATEMENT) + continue + self._insert_rows(columns, name, [then.expression]) + + def _copy(self, node: exp.Copy) -> None: + if not node.args.get("kind"): + return # COPY ... TO reads + self._writes = True + target = node.this + table = target.this if isinstance(target, exp.Schema) else target + ref = self._written_table(table) + name = None if ref is None else ref.name + if not isinstance(target, exp.Schema) or not target.expressions: + self._note(AnalysisGap.NO_COLUMN_LIST) + return + # The rows arrive as a stream, never as bind parameters. + for identifier in target.expressions: + column = self._identifier(identifier) + if column is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + else: + self._unbound.append(ColumnRef(column, name)) + + # ---- writes ---- + + def _assign(self, assignment: exp.Expression, table_of: _TableOf, same_row: Optional[_SameRow] = None) -> None: + self._assignment_nodes.add(id(assignment)) + if not isinstance(assignment, exp.EQ): + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + return + target, value = assignment.this, assignment.expression + if isinstance(target, exp.Tuple): + # SET (a, b) = (v1, v2) / ROW(v1, v2); a subquery fills them all. + values = self._row_values(value) + if values is None or len(values) != len(target.expressions): + for column in target.expressions: + name = self._identifier(column) if isinstance(column, exp.Column) else None + if name is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + continue + self._unbound.append(ColumnRef(name, table_of(self._fold(column.args.get("table"))))) + return + pairs = list(zip(target.expressions, values)) + else: + pairs = [(target, value)] + for column, v in pairs: + name = self._identifier(column) if isinstance(column, exp.Column) else None + if name is None: + self._note(AnalysisGap.UNSUPPORTED_STATEMENT) + continue + if same_row is not None and self._copies_same_column(v, name, same_row): + continue + self._write(ColumnRef(name, table_of(self._fold(column.args.get("table")))), v) + + def _write(self, column: ColumnRef, value: exp.Expression, outer_casts: Tuple[str, ...] = ()) -> None: + param = self._param(value) + if param is not None: + ordinal, casts, _ = param + self._assignments.append(ParameterUse(self._tokens.placeholders[ordinal], column, outer_casts + casts)) + elif self._prepared and self._server_parameter(value): + pass # bound by a later EXECUTE; the statement's gap says so + elif not isinstance(value, exp.Null): + self._unbound.append(column) + + @staticmethod + def _server_parameter(value: exp.Expression) -> bool: + while isinstance(value, (exp.Paren, exp.Cast, exp.TryCast)): + value = value.this + return isinstance(value, exp.Parameter) + + def _copies_same_column(self, value: exp.Expression, column: str, same_row: _SameRow) -> bool: + # The incoming row's own value for this column, already encrypted (or + # refused) where the row was written: EXCLUDED.c, VALUES(c) on MySQL, + # or alias.c with a MySQL row alias (by position when the alias names + # its columns). + key = self._dialect.metadata_key(column) + qualifier = value.args.get("table") if isinstance(value, exp.Column) else None + if qualifier is not None: + qualifier_key = self._key(qualifier) + if qualifier_key not in same_row: + return False + renamed = same_row[qualifier_key] + source = self._key(value.this) + return (renamed.get(source) if renamed is not None else source) == key + if self._dialect.name == "mysql" and isinstance(value, exp.Anonymous) \ + and str(value.this).upper() == "VALUES" and len(value.expressions) == 1: + inner = value.expressions[0] + if isinstance(inner, exp.Column) and inner.args.get("table") is None: + inner = inner.this + return isinstance(inner, exp.Identifier) and self._key(inner) == key + return False + + def _row_values(self, row: Optional[exp.Expression]) -> Optional[List[exp.Expression]]: + if isinstance(row, exp.Paren): + return [row.this] + if isinstance(row, exp.Tuple): + items = list(row.expressions) + # MySQL's VALUES ROW(...) comes back as a one-item tuple. + if len(items) == 1 and self._is_row(items[0]): + return list(items[0].expressions) + return items + if row is not None and self._is_row(row): + return list(row.expressions) + return None + + @staticmethod + def _is_row(node: exp.Expression) -> bool: + return isinstance(node, exp.Anonymous) and str(node.this).upper() == "ROW" + + # ---- comparisons ---- + + def _collect_comparisons(self, tree: exp.Expression) -> None: + for node in tree.walk(): + if id(node) in self._assignment_nodes: + continue + if isinstance(node, _COMPARISONS): + self._compare(node, node.this, node.expression) + self._compare(node, node.expression, node.this) + elif isinstance(node, exp.In): + for item in node.expressions: + self._compare(node, node.this, item) + self._compare(node, node.args.get("query"), node.this) # %s IN (SELECT ssn FROM users) + elif isinstance(node, exp.Between): + self._compare(node, node.this, node.args.get("low")) + self._compare(node, node.this, node.args.get("high")) + + def _compare(self, node: exp.Expression, column: Optional[exp.Expression], + value: Optional[exp.Expression]) -> None: + column, every = self._compared_column(column) + if not isinstance(column, exp.Column) or not isinstance(column.this, exp.Identifier) or value is None: + return + param = self._param(value) + if param is None: + return + ordinal, casts, function = param + ref = self._column_ref(column, column) # a sub-select's column is resolved in the sub-select + if ref is not None: + safe = isinstance(node, _SAFE_OPERATORS) and not node.args.get("negate") and function != "ALL" and not every + if safe: + decider = self._deciding_query(node) + safe = decider is not None and self._query_safe(decider) + self._comparisons.append( + ParameterUse(self._tokens.placeholders[ordinal], ref, casts, function is not None, safe)) + + @staticmethod + def _compared_column(side: Optional[exp.Expression]) -> Tuple[Optional[exp.Expression], bool]: + """What one side of a comparison compares a value with, and whether + it does so under ALL. A column in parentheses is the column + (``(ssn) = %s``). A sub-select whose select list is one column, under + any alias, is that column, because its rows hold that column's + values: ``%s IN (SELECT ssn FROM users)``, ``%s = ANY (SELECT ...)``, + ``%s <> ALL (SELECT ...)`` and ``%s = (SELECT ...)``, in any number of + parentheses and with an ORDER BY or LIMIT between them + (``%s <> ALL ((SELECT ...) LIMIT 5)``). Any other side comes back with + the parentheses, aliases, ALL, SOME or ANY over a sub-select with its + ORDER BY or LIMIT, and one-item select list around it removed, for + the caller to reject.""" + every = False + if isinstance(side, (exp.Any, exp.All)) and isinstance(side.this, (exp.Subquery, exp.Select)): + # sqlglot reads ALL (SELECT ...) and SOME (SELECT ...) without a Subquery. + every, side = isinstance(side, exp.All), side.this + elif isinstance(side, exp.Anonymous) and str(side.this).upper() in _ARRAY_FUNCTIONS \ + and len(side.expressions) == 1: + # sqlglot reads ALL ((SELECT ...)) and SOME ((SELECT ...)) as functions, and an ORDER BY or LIMIT + # between the parentheses as a node over the Subquery. + query = side.expressions[0] + while isinstance(query, (exp.Order, exp.Limit)): + query = query.this + if isinstance(query, exp.Subquery): + every, side = str(side.this).upper() == "ALL", query + while True: + if isinstance(side, (exp.Paren, exp.Subquery, exp.Alias)): + side = side.this + elif isinstance(side, exp.Select) and len(side.expressions) == 1: + side = side.expressions[0] + else: + return side, every + + def _deciding_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The query whose own position (:meth:`_query_safe`) decides whether + a condition at ``node`` that never holds can only remove rows from + what the statement reads or changes; ``None`` when the condition's + place makes it unsafe in any query. The place is safe when AND, OR + and parentheses alone join the condition to the WHERE of a SELECT, + UPDATE or DELETE, the HAVING of a SELECT, or the ON of an inner join + in a query with no outer join. Anything else around it (NOT, IS, a + function, CASE, a select list, a SET value, a MERGE ...) is not.""" + path: List[int] = [] + child, parent = node, node.parent + while isinstance(parent, (exp.Paren, exp.And, exp.Or)) \ + or (isinstance(parent, exp.Escape) and child.arg_key == "this"): + if id(parent) in self._deciders: + decider = self._deciders[id(parent)] + break + path.append(id(parent)) + child, parent = parent, parent.parent + else: # reached without a memo hit: the clause the condition is in decides + query = parent.parent if parent is not None else None + if (isinstance(parent, exp.Where) and isinstance(query, (exp.Select, exp.Update, exp.Delete))) \ + or (isinstance(parent, exp.Having) and isinstance(query, exp.Select)): + decider = query + elif isinstance(parent, exp.Join) and child.arg_key == "on" and not parent.side \ + and parent.kind in _INNER_JOIN_KINDS: + decider = self._joining_query(parent) + else: + decider = None + for key in path: + self._deciders[key] = decider + return decider + + def _query_safe(self, query: exp.Expression) -> bool: + """Whether a condition of ``query`` that never holds can only remove + rows from what the statement reads or changes, memoized. Worked out + with a stack rather than by recursion, because a chain of CTEs is as + deep as it is long. A query counts as unsafe while it is worked out, + so a recursive CTE's reference to itself ends unsafe.""" + needs: Dict[int, List[exp.Expression]] = {} + todo = [query] + while todo: + top = todo[-1] + if id(top) in needs: + self._safe[id(top)] = all(self._safe[id(n)] for n in needs.pop(id(top))) + todo.pop() + elif id(top) in self._safe: + todo.pop() + else: + required = self._requirements(top) + self._safe[id(top)] = required == [] + if required: + needs[id(top)] = required + todo.extend(n for n in required if id(n) not in self._safe) + else: + todo.pop() + return self._safe[id(query)] + + def _requirements(self, query: exp.Expression) -> Optional[List[exp.Expression]]: + """The queries whose positions must all be safe for the position of + ``query`` to be, or ``None`` when it is unsafe whatever they are. What + reads its rows must only lose rows when it loses some: the statement + itself; a sub-select that doesn't group, aggregate or have a WINDOW + clause (an aggregate or window function in its select list, ORDER BY + or DISTINCT ON, where a function sqlglot doesn't know counts as an + aggregate), read (through either side of UNION or INTERSECT, the left + of EXCEPT, and an ORDER BY or LIMIT written after its parentheses) by + IN, EXISTS, a scalar ``=`` or ``= ANY`` in a safe position, or as a + FROM or JOIN source of a query with no outer join; a + CTE read only that way; or the rows of the statement's INSERT.""" + child, parent = query, query.parent + if parent is None: + return [] + if isinstance(query, exp.Select) and (query.args.get("group") or query.args.get("having") or any( + e.find(*_AGGREGATING) for e in (*query.expressions, *(query.args.get("windows") or ()), + query.args.get("order"), query.args.get("distinct")) if e)): + return None # it may return rows for no input row, such as a count of 0 + while isinstance(parent, (exp.Subquery, exp.Paren, exp.Union, exp.Intersect)) \ + or (isinstance(parent, (exp.Except, exp.Order, exp.Limit)) and child.arg_key == "this"): + child, parent = parent, parent.parent + if parent is None: + return [] # a set operation or a parenthesized query that is the statement + if isinstance(parent, exp.Insert): + # INSERT ... SELECT: a filter that never holds only inserts fewer rows. + return [] if child.arg_key == "expression" and parent.parent is None else None + if isinstance(parent, exp.CTE): + return self._cte_readers(parent) + decider: Optional[exp.Expression] = None + if isinstance(parent, exp.Exists) or (isinstance(parent, exp.In) and child.arg_key == "query") \ + or (isinstance(parent, exp.EQ) and isinstance(child, exp.Subquery)): + decider = self._deciding_query(parent) + elif (isinstance(parent, exp.Any) or (isinstance(parent, exp.Anonymous) and str(parent.this).upper() == "SOME")) \ + and isinstance(parent.parent, exp.EQ): + # sqlglot reads SOME ((SELECT ...)) as a function. + decider = self._deciding_query(parent.parent) + elif isinstance(parent, (exp.From, exp.Join)) and child.arg_key == "this": + decider = self._joining_query(parent) + return None if decider is None else [decider] + + def _cte_readers(self, cte: exp.Expression) -> Optional[List[exp.Expression]]: + """The queries that read ``cte``, each as a FROM or JOIN source with no + outer join, or ``None`` when something reads it otherwise. It is read + wherever a table without a schema has its name in the statement (as + :attr:`_cte_names` is scoped), its own body included.""" + root = cte.root() + named = self._tables_by_name.get(id(root)) + if named is None: + named = self._tables_by_name[id(root)] = {} + for table in root.find_all(exp.Table): + if table.args.get("db") is None and isinstance(table.this, exp.Identifier): + named.setdefault(self._key(table.this), []).append(table) + readers: List[exp.Expression] = [] + for table in named.get(self._key(cte.args["alias"].this), ()): + reader = self._joining_query(table.parent) \ + if isinstance(table.parent, (exp.From, exp.Join)) and table.arg_key == "this" else None + if reader is None: + return None + readers.append(reader) + return readers + + def _joining_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The query that owns ``node`` (a JOIN, or the FROM or JOIN of a + derived table or CTE) when it has no outer join, else ``None``. Joins + are evaluated left to right, so a later RIGHT or FULL join keeps the + rows of its side when an earlier one matches none.""" + owner = self._nearest_query(node) + return owner if owner is not None and not self._has_outer_join(owner) else None + + @staticmethod + def _has_outer_join(query: exp.Expression) -> bool: + """Whether ``query`` has a join with a side (LEFT, RIGHT, FULL), read + from its own joins and from the tables and ``Subquery`` nodes its FROM, + its USING and the table it writes start from, at any depth of + parentheses: sqlglot puts a multi-table UPDATE's or DELETE's joins + under a table, and the joins that follow a derived table or a + parenthesized join under its ``Subquery``. A derived table's joins are + its own query's.""" + using = query.args.get("using") + sources: List[Any] = [query.args.get("this"), query.args.get("from_"), *(query.args.get("joins") or ()), + *(using if isinstance(using, list) else [using])] + while sources: + source = sources.pop() + if isinstance(source, exp.Join): + if source.side: + return True + sources.append(source.this) + elif isinstance(source, (exp.From, exp.Subquery)): + # A Subquery around a Table is a parenthesized join. sqlglot + # hangs the joins that follow a derived table or a + # parenthesized join on its Subquery. + sources.append(source.this) + sources.extend(source.args.get("joins") or ()) + elif isinstance(source, exp.Table): + sources.extend(source.args.get("joins") or ()) + return False + + # ---- values ---- + + @staticmethod + def _unwrap_casts(value: exp.Expression) -> Tuple[exp.Expression, Tuple[str, ...]]: + casts: List[str] = [] + while True: + if isinstance(value, exp.Paren): + value = value.this + elif isinstance(value, (exp.Cast, exp.TryCast)): + to = value.args.get("to") + casts.append(to.this.name if isinstance(to, exp.DataType) else str(to)) + value = value.this + else: + return value, tuple(casts) + + def _param(self, value: exp.Expression) -> Optional[Tuple[int, Tuple[str, ...], Optional[str]]]: + """(ordinal, casts, array function) when ``value`` is a placeholder, + possibly in parentheses, casts, or ANY/ALL/SOME. The array function + is ``"ANY"``, ``"ALL"`` or ``"SOME"``, or ``None`` outside them.""" + value, casts = self._unwrap_casts(value) + function: Optional[str] = None + if isinstance(value, (exp.Any, exp.All)): + function, (value, more) = "ALL" if isinstance(value, exp.All) else "ANY", self._unwrap_casts(value.this) + casts += more + elif isinstance(value, exp.Anonymous) and str(value.this).upper() in _ARRAY_FUNCTIONS \ + and len(value.expressions) == 1: + # sqlglot reads PostgreSQL's ALL(...) and SOME(...) as functions. + function, (value, more) = str(value.this).upper(), self._unwrap_casts(value.expressions[0]) + casts += more + if isinstance(value, exp.Placeholder): + ordinal = normalized_ordinal(value.name) + if ordinal is not None: + return ordinal, casts, function + return None + + # ---- names and scopes ---- + + def _fold(self, name: Any) -> Optional[str]: + """The name an identifier resolves to, folded as the engine folds it; + ``None`` when ``name`` is not an identifier.""" + if isinstance(name, exp.Identifier): + return self._dialect.fold_identifier(name.this, quoted=bool(name.args.get("quoted"))) + if isinstance(name, str) and name: + return self._dialect.fold_identifier(name, quoted=False) + return None + + def _identifier(self, node: Any) -> Optional[str]: + """The column a node names, or ``None`` when it is not a plain name + (a subscript, a field of a composite, ...).""" + if isinstance(node, exp.Column): + node = node.this + return self._fold(node) if isinstance(node, exp.Identifier) else None + + def _key(self, name: Any) -> str: + """The form names are compared in (case-insensitive on MySQL).""" + return self._dialect.metadata_key(self._fold(name) or "") + + def _table_ref(self, table: exp.Table) -> Optional[TableRef]: + if not isinstance(table.this, exp.Identifier): + return None # a function or a subquery + name = self._fold(table.this) + assert name is not None + schema = self._fold(table.args.get("db")) + if schema is None and self._dialect.metadata_key(name) in self._cte_names: + return None + return TableRef(name, schema) + + def _written_table(self, table: Optional[exp.Expression], + write: Optional[exp.Expression] = None) -> Optional[TableRef]: + ref = self._table_ref(table) if isinstance(table, exp.Table) else None + if ref is not None: + self._written.setdefault(ref, None) + if write is not None: + self._written_by.setdefault(id(write), []).append(ref) + return ref + + def _write_targets(self, node: exp.Expression) -> Optional[Sequence[TableRef]]: + """The tables written by the INSERT, UPDATE or MERGE that the value at + ``node`` feeds. + + Returns ``None`` when the value is not written. That is the case when, + on the way up, it is compared or otherwise tested (:data:`_TESTS`), is + the condition or operand of a ``CASE`` or ``IF``, or sits in one of + :data:`_NOT_WRITTEN_ARGS`, and when it reaches no write at all. + + Returns an empty sequence when the table can't be told: the value + reaches the write through one of :data:`_SOURCE_ARGS` (a CTE, or a + ``FROM``, ``JOIN``, ``LATERAL`` or ``USING`` source), or the write's + target is not a plain table.""" + child: Any = node + parent: Any = node.parent + through_source = False + while parent is not None: + key = child.arg_key + if key in _NOT_WRITTEN_ARGS: + return None + # A SET or ON CONFLICT "c = value" is an assignment, not a test. + if isinstance(parent, _TESTS) and id(parent) not in self._assignment_nodes: + return None + if isinstance(parent, (exp.If, exp.Case)) and key == "this": + return None + through_source = through_source or key in _SOURCE_ARGS + # A MERGE's WHEN ... UPDATE / INSERT belongs to the MERGE. + if isinstance(parent, _WRITES) and not isinstance(parent.parent, exp.When): + return () if through_source else self._written_by.get(id(parent), ()) + child, parent = parent, parent.parent + return None + + def _scope(self, query: exp.Expression) -> Dict[str, _Source]: + """Alias or table name -> what it names, for the sources one query + reads directly.""" + cached = self._scopes.get(id(query)) + if cached is not None: + return cached + sources: Dict[str, _Source] = {} + + def add(node: Any) -> None: + if isinstance(node, list): + for item in node: + add(item) + return + if not isinstance(node, exp.Expression): + return # an absent arg can be None or False + if isinstance(node, (exp.From, exp.Join)): + add(node.this) + return + alias = node.args.get("alias") + alias_name = alias.this if isinstance(alias, exp.TableAlias) else None + ref = self._table_ref(node) if isinstance(node, exp.Table) else None + if alias_name is not None: + sources[self._key(alias_name)] = ref + if ref is not None: + sources.setdefault(self._dialect.metadata_key(ref.name), ref) + elif isinstance(node, exp.Table) and alias_name is None: + sources[self._key(node.this)] = None # a CTE named directly + if isinstance(node, exp.Table): + add(node.args.get("joins")) + + if isinstance(query, exp.Insert): + add(query.this.this if isinstance(query.this, exp.Schema) else query.this) + else: + if isinstance(query, (exp.Update, exp.Delete, exp.Merge)): + add(query.args.get("this")) + add(query.args.get("from_")) + add(query.args.get("joins")) + add(query.args.get("using")) # a list for DELETE ... USING + add(query.args.get("tables")) + self._scopes[id(query)] = sources + return sources + + def _nearest_query(self, node: exp.Expression) -> Optional[exp.Expression]: + """The innermost query around ``node`` (excluding ``node`` itself).""" + path: List[int] = [] + parent = node.parent + found: Optional[exp.Expression] = None + while parent is not None: + if id(parent) in self._nearest: + found = self._nearest[id(parent)] + break + if isinstance(parent, _QUERIES): + found = parent + break + path.append(id(parent)) + parent = parent.parent + for key in path: + self._nearest[key] = found + return found + + def _enclosing_queries(self, node: exp.Expression) -> Iterator[exp.Expression]: + query = self._nearest_query(node) + while query is not None: + yield query + query = self._nearest_query(query) + + def _column_ref(self, column: exp.Column, at: exp.Expression) -> Optional[ColumnRef]: + name = self._identifier(column) + if name is None: + return None + qualifier = self._fold(column.args.get("table")) + if qualifier is not None: + key = self._dialect.metadata_key(qualifier) + for query in self._enclosing_queries(at): + scope = self._scope(query) + if key in scope: + source = scope[key] + return ColumnRef(name, None if source is None else source.name) + # Not an alias in sight: taken as a table name. + return ColumnRef(name, qualifier) + nearest = self._nearest_query(at) + if nearest is not None: + sources = set(self._scope(nearest).values()) + if len(sources) == 1: + only = next(iter(sources)) + return ColumnRef(name, None if only is None else only.name) + return ColumnRef(name) + + def _resolve_annotation(self, placeholder: Placeholder, ref: ColumnRef, + inferred: Dict[int, ColumnRef]) -> ColumnRef: + """Resolve an annotation's qualifier through the aliases in scope at + its placeholder, nearest query first. A qualifier that names nothing + in scope, or names a subquery or CTE, is kept as a table name. + + A bare column gets a table only when the statement says which: + + 1. the table the analysis found for that placeholder, if it is the + same column; + 2. otherwise, for a written value (a VALUES row, a SET value, or the + select list of a query feeding an INSERT, UPDATE or MERGE; see + :meth:`_write_targets`), the table that write writes. With several + written tables, or when the value reaches the write through a CTE + or a FROM, JOIN, LATERAL or USING source, it stays bare; + 3. otherwise, for a compared or read value, the only table its + nearest query reads. + + In every other case it stays bare.""" + node = self._placeholder_nodes.get(placeholder.ordinal) + if ref.table is not None: + key = self._dialect.metadata_key(ref.table) + for query in (self._enclosing_queries(node) if node is not None else ()): + scope = self._scope(query) + if key in scope: + source = scope[key] + return ColumnRef(ref.column, ref.table if source is None else source.name) + return ref + found = inferred.get(placeholder.ordinal) + if found is not None and found.table is not None \ + and self._dialect.metadata_key(found.column) == self._dialect.metadata_key(ref.column): + return ColumnRef(ref.column, found.table) + if node is None: + return ref + targets = self._write_targets(node) + if targets is not None: + tables = {t.name: None for t in targets} + return ColumnRef(ref.column, next(iter(tables))) if len(tables) == 1 else ref + nearest = self._nearest_query(node) + if nearest is not None: + sources = set(self._scope(nearest).values()) + if len(sources) == 1: + only = next(iter(sources)) + if only is not None: + return ColumnRef(ref.column, only.name) + return ref + + # ---- results ---- + + def _result_columns(self, tree: exp.Expression) -> Optional[Tuple[Optional[ColumnRef], ...]]: + if isinstance(tree, exp.Select): + items = tree.expressions + else: + returning = tree.args.get("returning") if isinstance(tree, (exp.Insert, exp.Update, exp.Delete)) else None + if not isinstance(returning, exp.Returning): + return None + items = returning.expressions + result: List[Optional[ColumnRef]] = [] + for item in items: + inner = item.this if isinstance(item, exp.Alias) else item + if isinstance(inner, exp.Star) or (isinstance(inner, exp.Column) and isinstance(inner.this, exp.Star)): + return None + ref = self._column_ref(inner, inner) if isinstance(inner, exp.Column) else None + if (ref is None or ref.table is None) and isinstance(tree, exp.Select): + # Read through a derived table or CTE: follow it to its table. + ref = self._trace(inner, tree, 0) + result.append(ref if ref is not None and ref.table is not None else None) + return tuple(result) + + def _trace(self, node: exp.Expression, query: exp.Expression, depth: int) -> Optional[ColumnRef]: + """The table column a result column of ``query`` comes from, followed + through derived tables and CTEs; ``None`` past a set operation, ``*``, + an expression or :data:`_MAX_DEPTH` levels.""" + if depth > _MAX_DEPTH or not isinstance(node, exp.Column): + return None + ref = self._column_ref(node, node) + if ref is not None and ref.table is not None: + return ref + name = self._identifier(node) + if name is None: + return None + qualifier = self._fold(node.args.get("table")) + inner = self._derived_query(None if qualifier is None else self._dialect.metadata_key(qualifier), query) + if not isinstance(inner, exp.Select): + return None + key = self._dialect.metadata_key(name) + for item in inner.expressions: + # The alias is folded from its Identifier, so quoting counts. + out = self._fold(item.args.get("alias")) if isinstance(item, exp.Alias) else self._identifier(item) + if out is not None and self._dialect.metadata_key(out) == key: + return self._trace(item.this if isinstance(item, exp.Alias) else item, inner, depth + 1) + return None + + def _derived_query(self, qualifier: Optional[str], query: exp.Expression) -> Optional[exp.Expression]: + """The query behind the derived table or CTE that ``query`` reads as + ``qualifier``, or behind its only source when there is no qualifier. + A source whose alias lists column names is not followed: the list + renames the columns by position. A CTE sees only the CTEs written + before it, as the engines resolve a non-recursive ``WITH``. In a + ``RECURSIVE`` list, a source name no earlier CTE defines leaves the + column unknown.""" + nodes: List[exp.Expression] = [] + from_ = query.args.get("from_") + if from_ is not None: + nodes.append(from_.this) + nodes.extend(j.this for j in query.args.get("joins") or []) + if qualifier is None and len(nodes) != 1: + return None + for node in nodes: + alias = node.args.get("alias") + alias_name = self._fold(alias.this) if isinstance(alias, exp.TableAlias) else None + renamed = isinstance(alias, exp.TableAlias) and bool(alias.args.get("columns")) + if isinstance(node, exp.Subquery): + if qualifier is None or (alias_name is not None and self._dialect.metadata_key(alias_name) == qualifier): + return None if renamed else node.this + elif isinstance(node, exp.Table) and isinstance(node.this, exp.Identifier): + key = self._key(node.this) + seen = key if alias_name is None else self._dialect.metadata_key(alias_name) + if qualifier is not None and seen != qualifier: + continue + if renamed: + return None + outer: Optional[exp.Expression] = query + inside: Any = None + while outer is not None: + with_ = outer.args.get("with_") + recursive = with_ is not None and bool(with_.args.get("recursive")) + for cte in (with_.expressions if with_ is not None else ()): + if cte is inside: + if recursive: + return None # PostgreSQL lets a RECURSIVE list read later CTEs + break # a CTE sees only the CTEs before it + cte_alias = cte.args.get("alias") + if isinstance(cte_alias, exp.TableAlias) and self._key(cte_alias.this) == key: + return None if cte_alias.args.get("columns") else cte.this + inside = outer.parent + outer = self._nearest_query(outer) + return None + return None + + def _note(self, gap: AnalysisGap) -> None: + if self._gap is None: + self._gap = gap diff --git a/aws_advanced_python_wrapper/encryption/sql_dialect.py b/aws_advanced_python_wrapper/encryption/sql_dialect.py index 6b28721d8..9a8e8690f 100644 --- a/aws_advanced_python_wrapper/encryption/sql_dialect.py +++ b/aws_advanced_python_wrapper/encryption/sql_dialect.py @@ -23,6 +23,7 @@ from __future__ import annotations +import string from abc import ABC, abstractmethod from contextlib import closing from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Sequence @@ -59,6 +60,22 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int ``id``.""" ... + @abstractmethod + def fold_identifier(self, name: str, quoted: bool) -> str: + """The name the server resolves an identifier written in SQL to. + ``name`` is the identifier without its quotes (doubled quotes undone) + and ``quoted`` says whether it was quoted.""" + ... + + @abstractmethod + def metadata_key(self, name: str) -> str: + """The form a table or column name is compared in when looking it up + in ``encryption_metadata``. Names with the same key share encryption + metadata: usually because the engine treats them as the same object, + but on MySQL with ``lower_case_table_names=0`` table names that differ + only in case share a key too.""" + ... + @staticmethod def for_driver_dialect(driver_dialect: DriverDialect) -> SqlDialect: code = driver_dialect.dialect_code @@ -111,6 +128,17 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int # A connection opened with a dict-like row factory returns a mapping. return int(next(iter(row.values())) if isinstance(row, Mapping) else row[0]) + def fold_identifier(self, name: str, quoted: bool) -> str: + # PostgreSQL folds an unquoted identifier to lower case, ASCII letters + # only in a multibyte (e.g. UTF-8) database; a quoted one keeps its + # case. The result is the name in the system catalog, apart from + # PostgreSQL's truncation of names longer than 63 bytes. + return name if quoted else name.translate(_ASCII_LOWER) + + def metadata_key(self, name: str) -> str: + # Catalog names are case-sensitive: "Users" and users are two tables. + return name + class MySqlSqlDialect(SqlDialect): name = "mysql" @@ -128,6 +156,24 @@ def insert_returning_id(self, conn: Any, sql: str, params: Sequence[Any]) -> int cursor.execute(sql, params) return int(cursor.lastrowid) + def fold_identifier(self, name: str, quoted: bool) -> str: + # MySQL keeps identifiers as written (quoting only allows reserved words + # and special characters). Whether it folds table names depends on + # lower_case_table_names, which metadata_key allows for by comparing + # case-insensitively. + return name + + def metadata_key(self, name: str) -> str: + # Column names are case-insensitive in MySQL, and table names are too + # unless lower_case_table_names=0 on a case-sensitive file system, where + # two tables differing only in case would share encryption metadata. + # This agrees with the uncached lookup under the default + # (case-insensitive) collations; metadata tables created with a _bin or + # _cs collation would compare case-sensitively there. + return name.lower() + + +_ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase) PG = PgSqlDialect() MYSQL = MySqlSqlDialect() diff --git a/aws_advanced_python_wrapper/encryption/sql_tokenizer.py b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py new file mode 100644 index 000000000..8f505129d --- /dev/null +++ b/aws_advanced_python_wrapper/encryption/sql_tokenizer.py @@ -0,0 +1,581 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Finds a statement's bind parameters the way its driver does. + +Both supported drivers use the ``pyformat`` paramstyle, but they do not find +placeholders the same way, and neither skips quoted literals or comments: + +* psycopg, when given parameters (even an empty sequence), treats every ``%`` + as the start of a placeholder: ``%s``/``%b``/``%t``, ``%(name)s`` (or ``b`` + / ``t``), or ``%%`` for a literal percent sign. Anything else after a ``%`` + is a ``ProgrammingError``, and positional and named placeholders cannot be + mixed. Given ``None`` it substitutes nothing. +* MySQL Connector/Python, given a non-empty list or tuple, replaces every + ``%s`` substring and nothing else (``%%`` is left alone). Given a non-empty + dict, it replaces ``%(name)s`` and turns ``%(name)%`` into ``%``. Given an + empty value it substitutes nothing, and given any other type it raises + ``ProgrammingError``. + +So the n-th placeholder found here is the n-th value the driver binds, even +when it sits inside a quoted literal or a comment. Such a placeholder is +reported as hidden: the statement's structure says nothing about which column +it fills, and the statement is almost certainly broken anyway. + +The SQL is also lexed (quotes, comments, statement separators) for what the +driver doesn't need: spotting hidden placeholders, reading +``/*@encrypt:table.column*/`` annotations, and producing a copy of the SQL a +structural parser can read, with each placeholder replaced by a named +placeholder that carries its position. + +The lexer assumes server defaults: ``standard_conforming_strings=on`` on +PostgreSQL, and backslash escapes on and ``ANSI_QUOTES`` off on MySQL. Under +other settings a literal may end somewhere else on the server. MySQL runs the +body of an executable comment (``/*! ... */``), so a statement with one is +flagged (:attr:`TokenizedSql.executable_comment`) rather than read as if the +comment were not there. The database-side HMAC trigger, not this module, +guarantees an encrypted column never holds plaintext. + +The placeholder rules are the drivers' (psycopg, MySQL Connector/Python), not +the engines': another driver for the same engine needs its own. + +This module has no third-party dependencies. +""" + +from __future__ import annotations + +import re +from bisect import bisect_right +from collections.abc import Mapping +from dataclasses import dataclass, field, replace +from enum import Enum +from typing import TYPE_CHECKING, Any, FrozenSet, List, Optional, Tuple, Union + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.encryption.sql_dialect import SqlDialect + +#: Prefix of the named placeholders written into :attr:`TokenizedSql.normalized`: +#: ``:_kms_p3`` stands for the placeholder whose ordinal is 3. +NORMALIZED_PLACEHOLDER_PREFIX = "_kms_p" + + +class ParamStyle(Enum): + """How a statement's parameters were passed, which decides what its driver + treats as a placeholder.""" + + #: No parameters, or (MySQL) a type the driver refuses: nothing is + #: substituted. + NONE = "none" + #: A sequence: ``%s`` placeholders, bound by position. + POSITIONAL = "positional" + #: A mapping: ``%(name)s`` placeholders, bound by name. + NAMED = "named" + + @classmethod + def of(cls, params: Any, dialect: SqlDialect) -> ParamStyle: + """The style the driver for ``dialect`` applies to ``params``, the + second argument of ``execute``.""" + if dialect.name == "mysql": + # Connector/Python substitutes only for a non-empty dict, list or + # tuple. + if not params: + return cls.NONE + if isinstance(params, dict): + return cls.NAMED + return cls.POSITIONAL if isinstance(params, (list, tuple)) else cls.NONE + if params is None: + return cls.NONE + return cls.NAMED if isinstance(params, Mapping) else cls.POSITIONAL + + +@dataclass(frozen=True, slots=True) +class ColumnRef: + """A column a statement names, with names folded the way the engine folds + them (see :meth:`SqlDialect.fold_identifier`).""" + + column: str + #: The table, without any schema; ``None`` when the statement does not say + #: which of its tables the column belongs to. + table: Optional[str] = None + + def __str__(self) -> str: + return self.column if self.table is None else f"{self.table}.{self.column}" + + +@dataclass(frozen=True, slots=True) +class Placeholder: + """One bind parameter, in the order the driver binds them.""" + + #: Position among the statement's placeholders, from 0. + ordinal: int + #: What the driver binds here: the index into the parameter sequence, or + #: the key in the parameter mapping. A key may be used more than once. + key: Union[int, str] + #: Span of the placeholder in the original SQL. + start: int + end: int + #: Overlaps a quoted literal (including a dollar-quoted one), a quoted + #: identifier, or a comment. + hidden: bool = False + #: The column a ``/*@encrypt:...*/`` annotation directly before it names, + #: folded like any identifier. Its qualifier is not resolved yet: see + #: :attr:`StatementAnalysis.annotations` for what the analyzer makes of it. + annotation: Optional[ColumnRef] = None + #: A MySQL charset introducer written directly before it (``_binary`` in + #: ``_binary %s``, as Django renders binary values), lower-cased. Anything + #: in between, an annotation included, hides the introducer. + introducer: Optional[str] = None + + +@dataclass(frozen=True) +class TokenizedSql: + """What :func:`tokenize` found.""" + + style: ParamStyle + placeholders: Tuple[Placeholder, ...] + #: The SQL with every placeholder replaced by ``:_kms_p``, the + #: driver's ``%`` escapes resolved, and on MySQL ``REPLACE`` read as + #: ``INSERT``, statement modifiers such as ``LOW_PRIORITY`` dropped, and + #: charset introducers before a placeholder removed (see + #: :attr:`Placeholder.introducer`). Only for a structural parser; never + #: sent to the database. + normalized: str + #: The first word of each statement, upper-cased. + leading_words: Tuple[str, ...] + #: Which of the keywords that matter for spotting a write (``INSERT``, + #: ``UPDATE``, ``REPLACE``, ``MERGE``, ``UPSERT``, ``COPY``, ``FROM``, + #: ``EXECUTE``, ``LOAD``) appear outside literals, comments and + #: placeholders, or inside a MySQL executable comment. + keywords: FrozenSet[str] + #: A quoted literal, quoted identifier, or comment runs to the end of the + #: text. + unterminated: bool = False + #: MySQL only: a ``/*! ... */`` (or MariaDB ``/*M! ... */``) comment, whose + #: body the server runs. + executable_comment: bool = False + #: Why the driver will reject the placeholders (an unknown ``%`` sequence, + #: positional and named placeholders mixed, or a style the parameters + #: don't have); ``None`` when it won't. + driver_error: Optional[str] = None + #: ``/*@encrypt:...*/`` comments that annotate no placeholder or can't be + #: read, as written. A caller may want to warn about them. + stray_annotations: Tuple[str, ...] = () + + @property + def has_hidden_placeholders(self) -> bool: + return any(p.hidden for p in self.placeholders) + + +_KEYWORDS = frozenset({"INSERT", "UPDATE", "REPLACE", "MERGE", "UPSERT", "COPY", "FROM", "EXECUTE", "LOAD"}) + +# MySQL statement modifiers between the keyword and the table. They change how +# a statement runs and leave what it writes alone. The structural parser reads +# "UPDATE LOW_PRIORITY users" as a table named LOW_PRIORITY aliased users, so +# they are dropped from the normalized copy. All are reserved words except +# QUICK, which can only follow DELETE. +_MYSQL_MODIFIERS = { + "INSERT": frozenset({"LOW_PRIORITY", "HIGH_PRIORITY", "DELAYED", "IGNORE"}), + "REPLACE": frozenset({"LOW_PRIORITY", "DELAYED"}), + "UPDATE": frozenset({"LOW_PRIORITY", "IGNORE"}), + "DELETE": frozenset({"LOW_PRIORITY", "QUICK", "IGNORE"}), +} + +# ---- lexers ---- +# +# Alternatives are tried in order at each token boundary. The ``*_end`` groups +# capture a closing quote, empty when the literal runs to the end of the text. + +_PG_TOKEN = re.compile(r""" + (?P--[^\n]*) + | (?P/\*) + | (?P[Ee]'(?:[^'\\]|\\.|'')*(?P'?)) + | (?P'(?:[^']|'')*(?P'?)) + | (?P"(?:[^"]|"")*(?P"?)) + | (?P\$\d+) + | (?P\$(?:[^\W\d]\w*)?\$) + | (?P[^\W\d][\w$]*) + | (?P\d[\w.]*) + | (?P;) + | (?P\s+) + | (?P[^\w\s'"$;/\-]+|.) +""", re.VERBOSE | re.DOTALL) + +_MYSQL_TOKEN = re.compile(r""" + (?P(?:\#|--(?=\s|\Z))[^\n]*) + | (?P/\*.*?(?P\*/|\Z)) + | (?P'(?:[^'\\]|\\.|'')*(?P'?)) + | (?P"(?:[^"\\]|\\.|"")*(?P"?)) + | (?P`(?:[^`]|``)*(?P`?)) + | (?P[^\W\d][\w$]*) + | (?P\d[\w.]*) + | (?P;) + | (?P\s+) + | (?P[^\w\s'"`;/\-\#]+|.) +""", re.VERBOSE | re.DOTALL) + +_QUOTED_KINDS = frozenset({"estring", "string", "dqstring", "ident"}) + +# A block comment that is an annotation: /*@encrypt:*/, with no space +# after the opening delimiter. is dot-separated parts, table.column or a +# bare column; leading parts (a schema) are ignored. A part is word characters, +# or a name quoted with the engine's identifier quote. Every [\w.]+ reference +# that ends in a column is accepted, empty parts included: ".c" is the bare +# column c and "t..c" is t.c. A reference that ends in "." names no column and +# is reported as stray. +_ANNOTATION = re.compile(r"/\*@encrypt:(?P.*?)\*/\Z", re.DOTALL) +_PG_REF_PART = re.compile(r'(?P\w+)|"(?P(?:[^"]|"")+)"') +_MYSQL_REF_PART = re.compile(r"(?P\w+)|`(?P(?:[^`]|``)+)`") + +# A MySQL charset introducer (_binary, _utf8mb4, ...) and the space after it, +# directly before a placeholder. +_INTRODUCER = re.compile(r"(?[A-Za-z0-9]+)\s*\Z") +_MYSQL_CHARSETS = frozenset({ + "armscii8", "ascii", "big5", "binary", "cp1250", "cp1251", "cp1256", "cp1257", "cp850", "cp852", "cp866", + "cp932", "dec8", "eucjpms", "euckr", "gb18030", "gb2312", "gbk", "geostd8", "greek", "hebrew", "hp8", + "keybcs2", "koi8r", "koi8u", "latin1", "latin2", "latin5", "latin7", "macce", "macroman", "sjis", "swe7", + "tis620", "ucs2", "ujis", "utf16", "utf16le", "utf32", "utf8", "utf8mb3", "utf8mb4", +}) +_WORD = re.compile(r"[^\W\d][\w$]*") +_COMMENT_DELIMITER = re.compile(r"/\*|\*/") + +# The drivers' own placeholder patterns. +_PSYCOPG_PLACEHOLDER = re.compile(r"%(?:\(([^)]+)\).|.)") # no DOTALL, as in psycopg +_MYSQL_POSITIONAL = re.compile(r"%s") +_MYSQL_NAMED = re.compile(r"%\((?P[^)]+)\)(?P[diouxXeEfFgGcrs%])") + +_Edit = Tuple[int, int, str] +_FAR = 1 << 62 # past any string offset + + +@dataclass +class _Lexed: + hidden_spans: List[Tuple[int, int]] # literals, quoted identifiers, comments; sorted + block_comments: List[Tuple[int, int]] + # (UPPER word, start, end); "" stands for any other significant token, so + # that two words with something between them are not taken as adjacent. + words: List[Tuple[str, int, int]] + separators: List[int] # offsets of the ";" between statements + unterminated: bool = False + executable_comment: bool = False + # Words inside MySQL executable comments, which the server runs. + executable_words: List[str] = field(default_factory=list) + + +def tokenize(sql: str, dialect: SqlDialect, style: ParamStyle) -> TokenizedSql: + """Find the placeholders in ``sql`` as the driver for ``dialect`` does when + given parameters of ``style``. + + :raises TypeError: if ``sql`` is not a ``str``. + """ + if not isinstance(sql, str): + raise TypeError(f"sql must be a str, not {type(sql).__name__}") + mysql = dialect.name == "mysql" + lexed = _lex(sql, _MYSQL_TOKEN if mysql else _PG_TOKEN, mysql=mysql) + + edits: List[_Edit] = [] + if mysql: + placeholders, driver_error = _mysql_placeholders(sql, style, lexed, edits) + placeholders = _attach_introducers(sql, lexed, placeholders, edits) + else: + placeholders, driver_error = _psycopg_placeholders(sql, style, lexed, edits) + + stray: List[str] = [] + if "@encrypt:" in sql: + placeholders = _attach_annotations(sql, dialect, lexed, placeholders, stray) + + # A word inside a placeholder (the s of %s, a %(name)s key) is not SQL. + words = _outside(lexed.words, placeholders) + bounds = _statement_bounds(words, lexed.separators) + if mysql: + edits.extend(_mysql_rewrites(words, bounds)) + + keywords = {w for w, _, _ in words if w in _KEYWORDS} + keywords.update(w for w in lexed.executable_words if w in _KEYWORDS) + return TokenizedSql( + style=style, + placeholders=tuple(placeholders), + normalized=_apply(sql, edits), + leading_words=_leading_words(words, bounds), + keywords=frozenset(keywords), + unterminated=lexed.unterminated, + executable_comment=lexed.executable_comment, + driver_error=driver_error, + stray_annotations=tuple(stray), + ) + + +def normalized_ordinal(name: Optional[str]) -> Optional[int]: + """The ordinal of a placeholder in the normalized SQL, from the name a + parser reports for it (``_kms_p3`` -> 3); ``None`` for any other name.""" + if not name or not name.startswith(NORMALIZED_PLACEHOLDER_PREFIX): + return None + digits = name[len(NORMALIZED_PLACEHOLDER_PREFIX):] + return int(digits) if digits.isascii() and digits.isdigit() else None + + +# ---- driver placeholders ---- +# +# The error texts never quote the SQL: a rejected "%(...)x" sequence can sit +# inside a literal holding a value. + +def _psycopg_placeholders(sql: str, style: ParamStyle, lexed: _Lexed, + edits: List[_Edit]) -> Tuple[List[Placeholder], Optional[str]]: + if style is ParamStyle.NONE: + return [], None + found: List[Placeholder] = [] + error: Optional[str] = None + named = positional = False + for m in _PSYCOPG_PLACEHOLDER.finditer(sql): + text = m.group(0) + if text == "%%": + edits.append((m.start(), m.end(), "%")) + continue + if text == "%(" or text[-1] not in "sbt": + error = error or f"psycopg rejects the % sequence at offset {m.start()}" + continue + name = m.group(1) + named, positional = named or name is not None, positional or name is None + ordinal = len(found) + found.append(_placeholder(ordinal, ordinal if name is None else name, m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + if named and positional: + error = error or "positional and named placeholders are mixed" + elif (named or positional) and named != (style is ParamStyle.NAMED): + error = error or f"the placeholders don't match {style.value} parameters" + return found, error + + +def _mysql_placeholders(sql: str, style: ParamStyle, lexed: _Lexed, + edits: List[_Edit]) -> Tuple[List[Placeholder], Optional[str]]: + found: List[Placeholder] = [] + error: Optional[str] = None + if style is ParamStyle.POSITIONAL: + for m in _MYSQL_POSITIONAL.finditer(sql): + ordinal = len(found) + found.append(_placeholder(ordinal, ordinal, m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + elif style is ParamStyle.NAMED: + for m in _MYSQL_NAMED.finditer(sql): + conv = m.group("conv") + if conv == "%": + edits.append((m.start(), m.end(), "%")) + elif conv != "s": + error = error or f"MySQL Connector/Python rejects the %(...) conversion at offset {m.start()}" + else: + ordinal = len(found) + found.append(_placeholder(ordinal, m.group("key"), m, lexed)) + edits.append(_placeholder_edit(ordinal, m)) + return found, error + + +def _placeholder(ordinal: int, key: Union[int, str], m: re.Match, lexed: _Lexed) -> Placeholder: + return Placeholder(ordinal=ordinal, key=key, start=m.start(), end=m.end(), + hidden=_overlaps(lexed.hidden_spans, m.start(), m.end())) + + +def _placeholder_edit(ordinal: int, m: re.Match) -> _Edit: + # Padded so the placeholder cannot fuse with a neighboring token. + return m.start(), m.end(), f" :{NORMALIZED_PLACEHOLDER_PREFIX}{ordinal} " + + +def _overlaps(spans: List[Tuple[int, int]], start: int, end: int) -> bool: + i = bisect_right(spans, (start, _FAR)) - 1 + if i >= 0 and spans[i][1] > start: + return True + return i + 1 < len(spans) and spans[i + 1][0] < end + + +def _attach_introducers(sql: str, lexed: _Lexed, placeholders: List[Placeholder], + edits: List[_Edit]) -> List[Placeholder]: + # "_binary %s" binds the value as a binary string, which is what a + # ciphertext is. The parser misreads the pair (as an alias, or not at all), + # so the introducer is recorded on the placeholder and removed from the + # normalized copy. Only whitespace may separate the two. + if "_" not in sql: + return placeholders + result = list(placeholders) + for i, p in enumerate(placeholders): + if p.hidden: + continue + m = _INTRODUCER.search(sql, max(0, p.start - 64), p.start) + if m is None or m.group("charset").lower() not in _MYSQL_CHARSETS \ + or _overlaps(lexed.hidden_spans, m.start(), m.end()): + continue + result[i] = replace(p, introducer=f"_{m.group('charset').lower()}") + edits.append((m.start(), m.end(), " ")) + return result + + +# ---- annotations ---- + +def _attach_annotations(sql: str, dialect: SqlDialect, lexed: _Lexed, + placeholders: List[Placeholder], stray: List[str]) -> List[Placeholder]: + by_start = {p.start: i for i, p in enumerate(placeholders)} + result = list(placeholders) + for start, end in lexed.block_comments: + if not sql.startswith("/*@encrypt:", start): + continue + m = _ANNOTATION.match(sql, start, end) + ref = None if m is None else _annotation_ref(m.group("ref"), dialect) + nxt = end + while nxt < len(sql) and sql[nxt].isspace(): + nxt += 1 + index = by_start.get(nxt) + if ref is None or index is None or result[index].hidden: + stray.append(sql[start:end]) + else: + result[index] = replace(result[index], annotation=ref) + return result + + +def _annotation_ref(text: str, dialect: SqlDialect) -> Optional[ColumnRef]: + mysql = dialect.name == "mysql" + part_re, quote = (_MYSQL_REF_PART, "`") if mysql else (_PG_REF_PART, '"') + parts: List[str] = [] + pos = 0 + while pos <= len(text): + if text.startswith(".", pos) or pos == len(text): + parts.append("") # an empty part, as in ".c" or "t..c" + else: + m = part_re.match(text, pos) + if m is None: + return None + if m.group("word") is not None: + parts.append(dialect.fold_identifier(m.group("word"), quoted=False)) + else: + parts.append(dialect.fold_identifier(m.group("quoted").replace(quote * 2, quote), quoted=True)) + pos = m.end() + if pos < len(text) and text[pos] != ".": + return None + pos += 1 + if not parts[-1]: + return None # no column ("t.") + # The metadata has no schema: the table is the nearest named part before + # the column, and anything before that is ignored. + table = next((part for part in reversed(parts[:-1]) if part), None) + return ColumnRef(column=parts[-1], table=table) + + +# ---- lexing ---- + +def _lex(sql: str, token_re: re.Pattern, mysql: bool) -> _Lexed: + lexed = _Lexed([], [], [], []) + pos, n = 0, len(sql) + while pos < n: + m = token_re.match(sql, pos) + assert m is not None # "other" matches any character + kind, end = m.lastgroup, m.end() + if kind == "block_comment": + if not mysql: + end = _nested_comment_end(sql, pos) + elif not m.group("block_comment_end"): + lexed.unterminated = True + if end < 0: + end, lexed.unterminated = n, True + if mysql and (sql.startswith("/*!", pos) or sql.startswith("/*M!", pos)): + lexed.executable_comment = True + lexed.executable_words.extend(w.upper() for w in _WORD.findall(sql, pos, end)) + lexed.block_comments.append((pos, end)) + lexed.hidden_spans.append((pos, end)) + elif kind == "dollar": + close = sql.find(m.group(0), end) + if close < 0: + end, lexed.unterminated = n, True + else: + end = close + len(m.group(0)) + lexed.hidden_spans.append((pos, end)) + elif kind in _QUOTED_KINDS: + if not m.group(f"{kind}_end"): + lexed.unterminated = True + lexed.hidden_spans.append((pos, end)) + elif kind == "line_comment": + lexed.hidden_spans.append((pos, end)) + elif kind == "word": + lexed.words.append((m.group(0).upper(), pos, end)) + elif kind == "semicolon": + lexed.separators.append(pos) + elif kind != "space": + lexed.words.append(("", pos, end)) + pos = end + return lexed + + +def _nested_comment_end(sql: str, start: int) -> int: + # PostgreSQL block comments nest. Returns -1 when unterminated. One pass + # over the delimiters, so deep nesting stays linear. + depth = 0 + for m in _COMMENT_DELIMITER.finditer(sql, start): + depth += 1 if m.group(0) == "/*" else -1 + if depth == 0: + return m.end() + return -1 + + +def _outside(words: List[Tuple[str, int, int]], placeholders: List[Placeholder]) -> List[Tuple[str, int, int]]: + if not placeholders: + return words + spans = [(p.start, p.end) for p in placeholders] + return [w for w in words if not _overlaps(spans, w[1], w[2])] + + +def _statement_bounds(words: List[Tuple[str, int, int]], separators: List[int]) -> List[Tuple[int, int]]: + """(begin, end) indexes into ``words`` of each non-empty statement.""" + bounds: List[Tuple[int, int]] = [] + begin = 0 + for separator in separators + [_FAR]: + end = begin + while end < len(words) and words[end][1] < separator: + end += 1 + if end > begin: + bounds.append((begin, end)) + begin = end + return bounds + + +def _leading_words(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> Tuple[str, ...]: + # A statement's first word, skipping leading punctuation such as "("; "" + # when it has no word at all. + return tuple(next((w for w, _, _ in words[begin:end] if w), "") for begin, end in bounds) + + +def _mysql_rewrites(words: List[Tuple[str, int, int]], bounds: List[Tuple[int, int]]) -> List[_Edit]: + leading = {begin for begin, _ in bounds} + edits: List[_Edit] = [] + for i, (word, start, end) in enumerate(words): + modifiers = _MYSQL_MODIFIERS.get(word) + if modifiers is None: + continue + if word == "REPLACE": + # Only the statement keyword, not the REPLACE() string function. + if i not in leading: + continue + edits.append((start, end, "INSERT")) + j = i + 1 + while j < len(words) and words[j][0] in modifiers: + edits.append((words[j][1], words[j][2], " ")) + j += 1 + return edits + + +def _apply(sql: str, edits: List[_Edit]) -> str: + if not edits: + return sql + out: List[str] = [] + pos = 0 + for start, end, text in sorted(edits): + out.append(sql[pos:start]) + out.append(text) + pos = end + out.append(sql[pos:]) + return "".join(out) diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index fbc44aafe..2cc4ac9c5 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -575,6 +575,7 @@ KeyManager.StoreKeyMetadataFailed=[KeyManager] Failed to store key metadata ({}) KeyManager.TouchKeyFailed=[KeyManager] Failed to update last_used_at for key {}: {} KeyManager.UnauthorizedMasterKey=[KeyManager] Master key {} is not listed in {}; refusing to use it. KeyManager.WrongDataKeyLength=[KeyManager] KMS returned a {}-byte data key for key spec {}, which {} cannot use. +MetadataManager.InvalidName=[MetadataManager] encryption_metadata.{} must be UTF-8 text; the driver returned a value of type {} that is not. MetadataManager.LoadFailed=[MetadataManager] Failed to read the kms_encryption metadata: {} MetadataManager.RefreshFailed=[MetadataManager] Failed to refresh the kms_encryption metadata cache: {} MetadataManager.Refreshed=[MetadataManager] Refreshed the kms_encryption metadata cache with {} column configuration(s). diff --git a/poetry.lock b/poetry.lock index 0cd125546..bee9bbb86 100644 --- a/poetry.lock +++ b/poetry.lock @@ -3327,6 +3327,24 @@ postgresql-psycopgbinary = ["psycopg[binary] (>=3.0.7)"] pymysql = ["pymysql"] sqlcipher = ["sqlcipher3_binary"] +[[package]] +name = "sqlglot" +version = "30.25.0" +description = "An easily customizable SQL parser and transpiler" +optional = false +python-versions = ">=3.9" +groups = ["main", "dev"] +files = [ + {file = "sqlglot-30.25.0-py3-none-any.whl", hash = "sha256:7d5a292d5f61b7fc860e65a8fa41083c726db0e27fb6efb224cca63c3a5980f7"}, + {file = "sqlglot-30.25.0.tar.gz", hash = "sha256:d2d6e4d4865a210b1e33a801b105a6782ef12280cc2b6d0969bdc2634aef427a"}, +] +markers = {main = "extra == \"encryption\""} + +[package.extras] +c = ["sqlglotc (==30.25.0) ; python_version >= \"3.10\""] +dev = ["duckdb (>=0.6)", "mypy (>=2.4.0) ; python_version >= \"3.10\"", "mypy ; python_version < \"3.10\"", "pandas", "pandas-stubs", "pdoc", "pre-commit", "pyperf", "python-dateutil", "pytz", "ruff (==0.15.6)", "setuptools_scm", "types-python-dateutil", "types-pytz", "typing_extensions"] +rs = ["sqlglotc (==30.25.0) ; python_version >= \"3.10\"", "sqlglotrs (==0.13.0)"] + [[package]] name = "sqlparse" version = "0.6.0" @@ -4181,9 +4199,9 @@ multidict = ">=4.0" propcache = ">=0.2.1" [extras] -encryption = ["cryptography"] +encryption = ["cryptography", "sqlglot"] [metadata] lock-version = "2.1" python-versions = "^3.10.0" -content-hash = "7cd044243bd145b872f30416b3db964cb7cfe39d37c44ad1a3df05b1abe9a88e" +content-hash = "511c6be5d88dd7b486441f4c4099f84b00bfdb3cbb91dec4e064c60182ac5e16" diff --git a/pyproject.toml b/pyproject.toml index 48ad28a84..03d70d7ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,10 +52,16 @@ requests = "^2.33.1" # pip install "aws-advanced-python-wrapper[encryption]" # The import is lazy as well: nothing on the core import path imports it. cryptography = { version = ">=42.0.0", optional = true } +# The plugin's SQL analysis (which bind parameter fills which column) parses +# statements with this pure-Python parser. Also only in the `encryption` extra +# and imported lazily. Capped below the next major: its expression tree changes +# shape between majors, and the analysis walks that tree. The floor is the +# oldest release the analysis tests pass on. +sqlglot = { version = ">=30.14.0,<31.0.0", optional = true } [tool.poetry.extras] # `pip install "aws-advanced-python-wrapper[encryption]"` to use the KMS Encryption plugin. -encryption = ["cryptography"] +encryption = ["cryptography", "sqlglot"] [tool.poetry.group.dev.dependencies] mypy = "^1.20.2" @@ -76,6 +82,7 @@ types_aws_xray_sdk = "^2.13.0" # Non-optional in the dev group so the encryption unit tests run without needing # to install the `encryption` extra explicitly. cryptography = ">=42.0.0" +sqlglot = ">=30.14.0,<31.0.0" [tool.poetry.group.test.dependencies] boto3 = "^1.42.95" diff --git a/tests/unit/test_encryption_import_guard.py b/tests/unit/test_encryption_import_guard.py index 666917176..5a8119599 100644 --- a/tests/unit/test_encryption_import_guard.py +++ b/tests/unit/test_encryption_import_guard.py @@ -12,11 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""``cryptography`` is an optional extra (``encryption``). The wrapper must -import without it, and only the module that encrypts may need it. +"""``cryptography`` and ``sqlglot`` are installed only with the optional +``encryption`` extra. The wrapper must import without them; only the module +that encrypts needs ``cryptography`` and only the SQL analyzer needs +``sqlglot``. -Each check runs in a fresh interpreter, most with ``cryptography`` blocked, -since the test environment always has it installed.""" +Each check runs in a fresh interpreter, most with both packages blocked, +since the test environment always has them installed.""" import subprocess import sys @@ -29,7 +31,7 @@ class _Block: def find_spec(self, name, path=None, target=None): - if name == "cryptography" or name.startswith("cryptography."): + if name.partition(".")[0] in ("cryptography", "sqlglot"): raise ModuleNotFoundError(f"No module named {name!r}", name=name) return None @@ -63,11 +65,14 @@ def _run(code: str, block: bool = True) -> subprocess.CompletedProcess: "aws_advanced_python_wrapper.encryption.key_manager", "aws_advanced_python_wrapper.encryption.metadata_manager", "aws_advanced_python_wrapper.encryption.key_management_utility", + # Placeholder scanning is dependency-free; only the structural parse + # needs sqlglot. + "aws_advanced_python_wrapper.encryption.sql_tokenizer", ] @pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) -def test_imports_without_cryptography(module): +def test_imports_without_cryptography_or_sqlglot(module): result = _run(f""" import importlib importlib.import_module({module!r}) @@ -76,13 +81,14 @@ def test_imports_without_cryptography(module): @pytest.mark.parametrize("module", _CORE_MODULES + _KEY_LAYER_MODULES) -def test_does_not_load_cryptography_even_when_installed(module): - # With cryptography available, importing these must still not load it, - # so users who never encrypt don't pay its import cost. +def test_does_not_load_the_extra_even_when_installed(module): + # With the packages available, importing these must still not load them, + # so users who never encrypt don't pay their import cost. result = _run(f""" import importlib importlib.import_module({module!r}) assert "cryptography" not in sys.modules, "cryptography was imported" + assert "sqlglot" not in sys.modules, "sqlglot was imported" """, block=False) assert result.returncode == 0, result.stderr @@ -100,6 +106,20 @@ def test_encryption_service_names_the_extra_when_cryptography_is_missing(): assert "aws-advanced-python-wrapper[encryption]" in result.stdout +def test_sql_analyzer_names_the_extra_when_sqlglot_is_missing(): + result = _run(""" + try: + import aws_advanced_python_wrapper.encryption.sql_analyzer + except ImportError as e: + print(e) + else: + raise SystemExit("imported without sqlglot") + """) + assert result.returncode == 0, result.stderr + assert "'sqlglot'" in result.stdout + assert "aws-advanced-python-wrapper[encryption]" in result.stdout + + _BROKEN = textwrap.dedent(""" import sys @@ -130,3 +150,17 @@ def test_a_broken_cryptography_is_not_reported_as_missing(error): assert result.returncode == 0, result.stderr assert "aws-advanced-python-wrapper[encryption]" not in result.stdout assert ("DLL load failed" in result.stdout) or ("_cffi_backend" in result.stdout) + + +def test_a_broken_sqlglot_is_not_reported_as_missing(): + code = _BROKEN.replace('"cryptography"', '"sqlglot"').format( + error='ModuleNotFoundError("No module named \'sqlglotc\'", name="sqlglotc")') + textwrap.dedent(""" + try: + import aws_advanced_python_wrapper.encryption.sql_analyzer + except ImportError as e: + print(e) + """) + result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) + assert result.returncode == 0, result.stderr + assert "aws-advanced-python-wrapper[encryption]" not in result.stdout + assert "sqlglotc" in result.stdout diff --git a/tests/unit/test_metadata_manager.py b/tests/unit/test_metadata_manager.py index 70a53b99d..768a516a1 100644 --- a/tests/unit/test_metadata_manager.py +++ b/tests/unit/test_metadata_manager.py @@ -515,3 +515,63 @@ def test_failed_reload_names_the_lookup(clock): with pytest.raises(MetadataError) as err: mm.column_config("users", "ssn") assert (err.value.table_name, err.value.column_name) == ("users", "ssn") + + +# ---- name matching ---- + +def test_postgresql_lookups_are_exact(clock): + # Names are stored as the catalog has them; "Users" and users differ. + db = FakeDb([row("users", "ssn"), row("Users", "SSN", 2)]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.column_config("users", "ssn").key_id == 1 + assert mm.column_config("Users", "SSN").key_id == 2 + assert mm.column_config("USERS", "ssn") is None + assert [c.key_id for c in mm.table_configs("Users")] == [2] + + +def test_mysql_lookups_ignore_case(clock): + # MySQL compares these names case-insensitively, as the uncached query's + # WHERE does under the metadata table's collation. + db = FakeDb([row("Users", "SSN")]) + mm = MetadataManager(db, MYSQL, config()) + mm.start() + found = mm.column_config("users", "ssn") + assert found is not None and (found.table_name, found.column_name) == ("Users", "SSN") + assert mm.is_column_encrypted("USERS", "Ssn") + assert [c.column_name for c in mm.table_configs("users")] == ["SSN"] + assert [c.column_name for c in mm.table_configs("USERS")] == ["SSN"] + assert db.opened == 1 # all from the cache + + +def test_load_metadata_keeps_the_stored_names(): + db = FakeDb([row("Users", "SSN")]) + assert list(MetadataManager(db, MYSQL, config()).load_metadata()) == [("Users", "SSN")] + + +@pytest.mark.parametrize("raw", [b"users", bytearray(b"users"), memoryview(b"users")]) +def test_bytes_names_are_decoded(clock, raw): + # psycopg on a SQL_ASCII database, or Connector/Python with + # use_unicode=False, returns text as bytes. Undecoded, the snapshot would + # be keyed by bytes and no str lookup would find the encrypted column. + db = FakeDb([row(raw, b"ssn")]) + mm = MetadataManager(db, PG, config()) + mm.start() + assert mm.is_column_encrypted("users", "ssn") + assert mm.column_config("users", "ssn").table_name == "users" + + +@pytest.mark.parametrize("raw", [b"\xff\xfe", 42, None]) +def test_names_that_are_not_text_are_refused(clock, raw): + db = FakeDb([row(raw, "ssn")]) + mm = MetadataManager(db, PG, config()) + with pytest.raises(MetadataError, match="table_name") as info: + mm.start() + assert info.value.__context__ is None + + +def test_names_that_are_not_text_are_refused_on_an_uncached_lookup(): + db = FakeDb([row("users", 7)]) + mm = MetadataManager(db, PG, config(metadata_cache_enabled=False)) + with pytest.raises(MetadataError, match="column_name"): + mm.column_config("users", 7) # type: ignore[arg-type] diff --git a/tests/unit/test_sql_analyzer.py b/tests/unit/test_sql_analyzer.py new file mode 100644 index 000000000..89250d59d --- /dev/null +++ b/tests/unit/test_sql_analyzer.py @@ -0,0 +1,1815 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import dataclasses +import logging +import sys +import threading + +import pytest +import sqlglot +from sqlglot import exp + +from aws_advanced_python_wrapper.encryption import sql_analyzer +from aws_advanced_python_wrapper.encryption.sql_analyzer import (AnalysisGap, + StatementKind, + TableRef, + analyze) +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.encryption.sql_tokenizer import (ColumnRef, + ParamStyle, + tokenize) + + +@pytest.fixture(autouse=True) +def _fresh_cache(): + # The analysis cache is process-wide: without this a test can pass on an + # earlier test's cached result instead of the code path it names. + sql_analyzer._cached_analysis.cache_clear() + yield + sql_analyzer._cached_analysis.cache_clear() + + +BOTH = pytest.mark.parametrize("dialect", [PG, MYSQL], ids=["pg", "mysql"]) +P = (1,) # positional parameters +N = {"x": 1} # named parameters + + +def assigned(a): + return [(u.ordinal, str(u.column)) for u in a.assignments] + + +def compared(a): + return [(u.ordinal, str(u.column)) for u in a.comparisons] + + +def unbound(a): + return [str(c) for c in a.unbound_writes] + + +def names(tables): + return [str(t) for t in tables] + + +def safety(sql, dialect): + return [u.safe for u in analyze(sql, dialect, P).comparisons] + + +def on(both=(), pg=(), mysql=()): + """Parametrizes ``dialect, sql``: each of ``both`` on PostgreSQL and on + MySQL, then each of ``pg`` and ``mysql`` on its own dialect.""" + cases = [(d, s) for s in both for d in (PG, MYSQL)] + [(PG, s) for s in pg] + [(MYSQL, s) for s in mysql] + return pytest.mark.parametrize("dialect, sql", cases, ids=[f"{d.name}: {s}" for d, s in cases]) + + +class TestInsert: + @BOTH + def test_columns_pair_with_their_placeholders(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s)", dialect, P) + assert a.kind is StatementKind.INSERT and a.writes and a.complete + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + assert names(a.written_tables) == ["users"] + assert a.parameter_columns() == {0: ColumnRef("name", "users"), 1: ColumnRef("ssn", "users")} + + @BOTH + def test_multi_row_values(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s), (%s, %s)", dialect, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.name"), (3, "users.ssn")] + + @BOTH + def test_named_placeholders(self, dialect): + a = analyze("INSERT INTO users (name, ssn) VALUES (%(n)s, %(s)s)", dialect, N) + pairs = [(u.placeholder.key, str(u.column)) for u in a.assignments] + assert pairs == [("n", "users.name"), ("s", "users.ssn")] + + @BOTH + def test_expression_literal_and_default_are_unbound(self, dialect): + a = analyze("INSERT INTO users (a, b, c, d) VALUES (lower(%s), 'x', DEFAULT, %s)", dialect, P) + assert assigned(a) == [(1, "users.d")] + assert unbound(a) == ["users.a", "users.b", "users.c"] + assert a.complete + + @BOTH + def test_null_needs_no_encryption(self, dialect): + a = analyze("INSERT INTO users (a, b) VALUES (%s, NULL)", dialect, P) + assert assigned(a) == [(0, "users.a")] + assert unbound(a) == [] + + @BOTH + def test_casts_are_reported(self, dialect): + sql = ("INSERT INTO users (a, b) VALUES (%s::VARCHAR, CAST(%s AS BINARY))" if dialect is PG + else "INSERT INTO users (a, b) VALUES (CAST(%s AS CHAR), CAST(%s AS BINARY))") + a = analyze(sql, dialect, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b")] + assert all(u.casts for u in a.assignments) + + def test_casts_are_outermost_first(self): + a = analyze("INSERT INTO users (a) VALUES (CAST(%s::text AS bytea))", PG, P) + assert a.assignments[0].casts == ("VARBINARY", "TEXT") + + @BOTH + def test_no_column_list(self, dialect): + a = analyze("INSERT INTO users VALUES (%s, %s)", dialect, P) + assert a.writes and a.gap is AnalysisGap.NO_COLUMN_LIST + assert assigned(a) == [] + + def test_default_values(self): + assert analyze("INSERT INTO users DEFAULT VALUES", PG).gap is AnalysisGap.NO_COLUMN_LIST + + @BOTH + def test_insert_select(self, dialect): + a = analyze("INSERT INTO users (name, ssn) SELECT name, ssn FROM staging WHERE id = %s", dialect, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY + assert assigned(a) == [] + assert compared(a) == [(0, "staging.id")] + assert names(a.tables) == ["users", "staging"] and names(a.written_tables) == ["users"] + + @BOTH + def test_row_length_mismatch(self, dialect): + assert analyze("INSERT INTO users (a, b) VALUES (%s)", dialect, P).gap is AnalysisGap.ROW_LENGTH_MISMATCH + + def test_schema_qualified_table(self): + a = analyze("INSERT INTO app.users (ssn) VALUES (%s)", PG, P) + assert a.written_tables == (TableRef("users", "app"),) + assert assigned(a) == [(0, "users.ssn")] + + def test_alias_with_column_list(self): + a = analyze("INSERT INTO users AS u (ssn) VALUES (%s)", PG, P) + assert assigned(a) == [(0, "users.ssn")] + + def test_returning_columns(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) RETURNING id, ssn AS s, 1", PG, P) + assert a.result_columns == (ColumnRef("id", "users"), ColumnRef("ssn", "users"), None) + + +class TestUpsert: + def test_on_conflict_assignments(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON CONFLICT (id) DO UPDATE SET ssn = %s, note = 'x' WHERE users.age > %s", PG, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.ssn")] + assert unbound(a) == ["users.note"] + assert compared(a) == [(3, "users.age")] + + def test_excluded_copy_of_the_same_column_is_not_a_write(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT (id) DO UPDATE SET ssn = EXCLUDED.ssn", + PG, P) + assert unbound(a) == [] + + def test_excluded_copy_of_another_column_is(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON CONFLICT (id) DO UPDATE SET ssn = EXCLUDED.name", PG, P) + assert unbound(a) == ["users.ssn"] + + def test_on_conflict_do_nothing(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s) ON CONFLICT DO NOTHING", PG, P) + assert assigned(a) == [(0, "users.ssn")] and a.complete + + def test_on_duplicate_key_update(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) " + "ON DUPLICATE KEY UPDATE ssn = %s, name = VALUES(name), note = VALUES(ssn)", MYSQL, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn"), (2, "users.ssn")] + assert unbound(a) == ["users.note"] + + def test_on_duplicate_key_update_with_row_alias(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new " + "ON DUPLICATE KEY UPDATE ssn = new.ssn, name = new.ssn", MYSQL, P) + assert unbound(a) == ["users.name"] + + def test_replace(self): + a = analyze("REPLACE INTO users (name, ssn) VALUES (%s, %s)", MYSQL, P) + assert a.kind is StatementKind.INSERT + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + + def test_insert_set_form(self): + a = analyze("INSERT IGNORE INTO users SET name = %s, ssn = %s, note = NULL", MYSQL, P) + assert assigned(a) == [(0, "users.name"), (1, "users.ssn")] + + @pytest.mark.parametrize("sql", [ + "INSERT LOW_PRIORITY INTO users (ssn) VALUES (%s)", + "INSERT HIGH_PRIORITY IGNORE INTO users (ssn) VALUES (%s)", + "INSERT DELAYED INTO users (ssn) VALUES (%s)", + "REPLACE LOW_PRIORITY INTO users (ssn) VALUES (%s)", + "REPLACE users SET ssn = %s", + ]) + def test_mysql_modifiers(self, sql): + assert assigned(analyze(sql, MYSQL, P)) == [(0, "users.ssn")] + + def test_values_row(self): + a = analyze("INSERT INTO users (a, b) VALUES ROW(%s, %s), ROW(%s, NULL)", MYSQL, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b"), (2, "users.a")] + + +class TestUpdate: + @BOTH + def test_set_and_where(self, dialect): + a = analyze("UPDATE users SET ssn = %s, name = 'x' WHERE id = %s", dialect, P) + assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert assigned(a) == [(0, "users.ssn")] + assert unbound(a) == ["users.name"] + assert compared(a) == [(1, "users.id")] + + @BOTH + def test_alias_and_qualified_assignment(self, dialect): + a = analyze("UPDATE users u SET u.ssn = %s WHERE u.id = %s", dialect, P) + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "users.id")] + + @pytest.mark.parametrize("sql", ["UPDATE LOW_PRIORITY users SET ssn = %s", + "UPDATE IGNORE users SET ssn = %s", + "UPDATE LOW_PRIORITY IGNORE users SET ssn = %s"]) + def test_mysql_modifiers(self, sql): + # Unhandled, the parser reads LOW_PRIORITY as the table. + a = analyze(sql, MYSQL, P) + assert names(a.written_tables) == ["users"] + assert assigned(a) == [(0, "users.ssn")] + + def test_mysql_multi_table_qualified(self): + a = analyze("UPDATE users u JOIN orders o ON o.uid = u.id SET u.ssn = %s, o.total = %s WHERE o.id = %s", + MYSQL, P) + assert a.complete + assert assigned(a) == [(0, "users.ssn"), (1, "orders.total")] + assert compared(a) == [(2, "orders.id")] + assert names(a.written_tables) == ["users", "orders"] + + def test_mysql_multi_table_comma(self): + a = analyze("UPDATE users, orders SET users.ssn = %s WHERE users.id = orders.uid", MYSQL, P) + assert assigned(a) == [(0, "users.ssn")] and a.complete + + def test_mysql_multi_table_unqualified_is_ambiguous(self): + a = analyze("UPDATE users u JOIN orders o ON o.uid = u.id SET ssn = %s", MYSQL, P) + assert a.gap is AnalysisGap.AMBIGUOUS_TABLE + assert assigned(a) == [(0, "ssn")] + + def test_postgresql_from_does_not_add_a_written_table(self): + a = analyze("UPDATE users SET ssn = %s FROM other o WHERE o.id = users.id AND o.ssn = %s", PG, P) + assert names(a.written_tables) == ["users"] + assert assigned(a) == [(0, "users.ssn")] + assert compared(a) == [(1, "other.ssn")] + + def test_multi_column_assignment(self): + a = analyze("UPDATE users SET (a, b) = (%s, %s), (c, d) = ROW(%s, 'x'), (e, f) = (SELECT 1, 2)", PG, P) + assert assigned(a) == [(0, "users.a"), (1, "users.b"), (2, "users.c")] + assert unbound(a) == ["users.d", "users.e", "users.f"] + + def test_set_default(self): + assert unbound(analyze("UPDATE users SET ssn = DEFAULT", PG)) == ["users.ssn"] + + def test_returning(self): + a = analyze("UPDATE users SET ssn = %s RETURNING ssn", PG, P) + assert a.result_columns == (ColumnRef("ssn", "users"),) + + +class TestOtherWrites: + def test_merge(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id " + "WHEN MATCHED AND s.flag = %s THEN UPDATE SET ssn = %s " + "WHEN MATCHED THEN DELETE " + "WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (%s, s.ssn)", PG, P) + assert a.kind is StatementKind.MERGE and a.writes and a.complete + assert assigned(a) == [(1, "users.ssn"), (2, "users.id")] + assert unbound(a) == ["users.ssn"] + assert compared(a) == [(0, "src.flag")] + assert names(a.written_tables) == ["users"] + + def test_merge_insert_without_columns(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id " + "WHEN NOT MATCHED THEN INSERT VALUES (%s, %s)", PG, P) + assert a.gap is AnalysisGap.NO_COLUMN_LIST + + def test_merge_that_only_deletes(self): + a = analyze("MERGE INTO users u USING src s ON u.id = s.id WHEN MATCHED THEN DELETE", PG) + assert a.writes and a.complete and assigned(a) == [] and unbound(a) == [] + + def test_data_modifying_cte(self): + a = analyze("WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", PG, P) + assert a.kind is StatementKind.SELECT and a.writes + assert assigned(a) == [(0, "users.ssn")] + assert names(a.tables) == ["users"] # w is a CTE, not a table + + def test_update_cte(self): + a = analyze("WITH w AS (UPDATE users SET ssn = %s WHERE id = %s RETURNING id) SELECT id FROM w", PG, P) + assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + + def test_read_only_cte_is_a_read(self): + a = analyze("WITH w AS (SELECT ssn FROM users) SELECT ssn FROM w WHERE ssn = %s", PG, P) + assert not a.writes + assert names(a.tables) == ["users"] + assert compared(a) == [(0, "ssn")] # a CTE column has no table + assert a.result_columns == (ColumnRef("ssn", "users"),) + + def test_cte_insert_select(self): + a = analyze("WITH a AS (SELECT %s AS v) INSERT INTO users (ssn) SELECT v FROM a", PG, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY + + def test_copy_from_names_unbound_columns(self): + a = analyze("COPY users (name, ssn) FROM STDIN", PG) + assert a.kind is StatementKind.COPY_FROM and a.writes and a.complete + assert unbound(a) == ["users.name", "users.ssn"] + + def test_copy_from_without_columns(self): + assert analyze("COPY users FROM STDIN WITH (FORMAT csv)", PG).gap is AnalysisGap.NO_COLUMN_LIST + + def test_copy_to_is_a_read(self): + a = analyze("COPY users TO STDOUT", PG) + assert a.kind is StatementKind.COPY_TO and not a.writes + assert names(a.tables) == ["users"] + + def test_copy_query_to(self): + a = analyze("COPY (SELECT ssn FROM users) TO STDOUT", PG) + assert not a.writes and names(a.tables) == ["users"] + + def test_several_statements_are_all_read(self): + # The ordinals run across the whole string, so each statement's + # placeholders still map to the right parameters. + a = analyze("UPDATE t SET a = %s; INSERT INTO users (name, ssn) VALUES (%s, %s)", MYSQL, P) + assert a.kind is StatementKind.UPDATE and a.writes and a.complete + assert assigned(a) == [(0, "t.a"), (1, "users.name"), (2, "users.ssn")] + assert a.result_columns is None + + @BOTH + def test_delete(self, dialect): + a = analyze("DELETE FROM users WHERE ssn = %s", dialect, P) + assert a.kind is StatementKind.DELETE and not a.writes + assert compared(a) == [(0, "users.ssn")] + + def test_mysql_multi_table_delete(self): + a = analyze("DELETE t FROM t JOIN u ON u.id = t.id WHERE u.a = %s", MYSQL, P) + assert compared(a) == [(0, "u.a")] + + +class TestComparisons: + def test_operators(self): + a = analyze("SELECT * FROM t WHERE a = %s AND b <> %s AND c < %s AND d >= %s AND e LIKE %s " + "AND f ILIKE %s AND g IS NOT DISTINCT FROM %s AND %s = h", PG, P) + assert compared(a) == [(i, f"t.{c}") for i, c in enumerate("abcdefgh")] + + @BOTH + def test_a_parenthesized_column_is_paired_with_its_value(self, dialect): + a = analyze("SELECT * FROM users u WHERE (ssn) = %s AND ((u.dob)) IN (%s, %s) AND %s <> (ssn) " + "AND (ssn) BETWEEN %s AND %s", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.dob"), (3, "users.ssn"), + (4, "users.ssn"), (5, "users.ssn")] + + @BOTH + def test_a_sub_selects_only_column_is_paired_with_the_value(self, dialect): + # The sub-select's rows hold that column's values, and its column is resolved in the sub-select, not in t. + a = analyze("SELECT name FROM t WHERE %s IN (SELECT ssn FROM users) AND %s = ANY (SELECT u.dob FROM users u) " + "AND %s = SOME (SELECT ssn AS s FROM users) AND %s <> ALL (SELECT ((ssn)) FROM users) " + "AND %s = (SELECT ssn FROM users LIMIT 1) AND (SELECT ssn FROM users LIMIT 1) = %s " + "AND %s IN ((SELECT ssn FROM users))", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.ssn"), (3, "users.ssn"), + (4, "users.ssn"), (5, "users.ssn"), (6, "users.ssn")] + assert not any(u.array for u in a.comparisons) + + @BOTH + def test_a_sub_select_with_more_than_its_column_is_not_paired(self, dialect): + a = analyze("SELECT name FROM t WHERE %s IN (SELECT ssn FROM users UNION SELECT ssn FROM archive) " + "AND %s IN (SELECT lower(ssn) FROM users) AND %s IN (SELECT * FROM users) " + "AND (%s, %s) IN (SELECT ssn, dob FROM users) AND ssn IN (SELECT %s) " + "AND %s IN (SELECT ssn, dob FROM users)", dialect, P) + assert compared(a) == [] + + @BOTH + def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_paired(self, dialect): + # sqlglot reads ALL ((SELECT ...)) and SOME ((SELECT ...)) as functions; both servers read a sub-select. + a = analyze("SELECT name FROM t WHERE %s <> ALL ((SELECT ssn FROM users)) " + "AND %s = SOME (((SELECT u.ssn AS s FROM users u))) AND %s = some ((select dob from users))", + dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.ssn"), (2, "users.dob")] + assert not any(u.array for u in a.comparisons) + + @BOTH + def test_all_or_some_over_anything_but_a_sub_select_of_the_column_is_not_paired(self, dialect): + # The last two compare the value with the elements of an array column, not with the column. + a = analyze("SELECT name FROM t WHERE %s <> ALL ((SELECT ssn FROM users UNION SELECT ssn FROM archive)) " + "AND %s = SOME ((SELECT lower(ssn) FROM users)) " + "AND %s = SOME ((SELECT ssn FROM users), (SELECT dob FROM users)) " + "AND %s = foo((SELECT ssn FROM users)) AND %s = SOME ((ssn) ORDER BY 1) " + "AND %s = ALL (tags) AND %s = SOME (tags)", + dialect, P) + assert compared(a) == [] + + @BOTH + def test_a_sub_select_with_order_by_or_limit_after_its_parentheses_is_paired(self, dialect): + # sqlglot puts an ORDER BY or LIMIT between the parentheses of ALL ((...)) or SOME ((...)) over the Subquery. + a = analyze("SELECT name FROM t WHERE %s = SOME ((SELECT ssn FROM users) ORDER BY 1) " + "AND %s <> ALL ((SELECT dob FROM users) LIMIT 5) " + "AND %s = some ((select u.ssn as s from users u) order by 1 limit 5)", dialect, P) + assert sorted(compared(a)) == [(0, "users.ssn"), (1, "users.dob"), (2, "users.ssn")] + assert not any(u.array for u in a.comparisons) + + def test_in_between_and_any(self): + a = analyze("SELECT * FROM t WHERE a IN (%s, %s) AND b BETWEEN %s AND %s AND c = ANY(%s)", PG, P) + assert compared(a) == [(0, "t.a"), (1, "t.a"), (2, "t.b"), (3, "t.b"), (4, "t.c")] + assert [u.array for u in a.comparisons] == [False] * 4 + [True] + + def test_mysql_null_safe_equals(self): + assert compared(analyze("SELECT * FROM t WHERE a <=> %s", MYSQL, P)) == [(0, "t.a")] + + def test_join_resolves_aliases_and_leaves_unqualified_columns_open(self): + a = analyze("SELECT u.ssn FROM users u JOIN orders o ON o.uid = u.id " + "WHERE u.name = %s AND o.id = %s AND total = %s", PG, P) + assert compared(a) == [(0, "users.name"), (1, "orders.id"), (2, "total")] + + def test_subquery_scope(self): + a = analyze("SELECT * FROM users WHERE id IN (SELECT uid FROM orders WHERE total = %s) AND ssn = %s", + PG, P) + assert compared(a) == [(0, "orders.total"), (1, "users.ssn")] + + def test_correlated_qualifier_from_an_outer_query(self): + a = analyze("SELECT * FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.uid = u.id AND u.ssn = %s)", + PG, P) + assert compared(a) == [(0, "users.ssn")] + + def test_column_against_column_is_not_a_parameter(self): + assert compared(analyze("SELECT * FROM t WHERE a = b", PG)) == [] + + def test_jsonb_question_mark_operator(self): + # "?" is an operator on PostgreSQL, not a placeholder. + a = analyze("SELECT ssn FROM users WHERE data ? 'k' AND id = %s", PG, P) + assert a.complete and compared(a) == [(0, "users.id")] + + def test_unknown_qualifier_is_taken_as_a_table(self): + assert compared(analyze("SELECT * FROM users WHERE other.ssn = %s", PG, P)) == [(0, "other.ssn")] + + +class TestComparisonSafety: + """``ParameterUse.safe``: whether a comparison that never matches can only + remove rows from what the statement reads or changes.""" + + @on(both=["SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE %s = ssn", + "SELECT id FROM users WHERE ssn IN (%s, %s)", + "SELECT id FROM users WHERE ssn LIKE %s", + "SELECT id FROM users WHERE ssn LIKE %s ESCAPE '!'"], + pg=["SELECT id FROM users WHERE ssn = ANY(%s)", + "SELECT id FROM users WHERE ssn = SOME(%s)", + "SELECT id FROM users WHERE ssn ILIKE %s", + "SELECT id FROM users WHERE ssn IS NOT DISTINCT FROM %s", + "SELECT id FROM users WHERE ssn LIKE ANY(%s)", + "SELECT id FROM users WHERE ssn LIKE SOME(%s)", + "SELECT id FROM users WHERE ssn ILIKE ANY(%s)"], + mysql=["SELECT id FROM users WHERE ssn LIKE BINARY %s", + "SELECT id FROM users WHERE ssn <=> %s"]) + def test_safe_operators(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and all(flags) + + @on(both=["SELECT id FROM users WHERE ssn <> %s", + "SELECT id FROM users WHERE %s <> ssn", + "SELECT id FROM users WHERE ssn != %s", + "SELECT id FROM users WHERE ssn < %s", + "SELECT id FROM users WHERE ssn <= %s", + "SELECT id FROM users WHERE ssn > %s", + "SELECT id FROM users WHERE ssn >= %s", + "SELECT id FROM users WHERE ssn BETWEEN %s AND %s", + "SELECT id FROM users WHERE ssn NOT BETWEEN %s AND %s", + "SELECT id FROM users WHERE ssn NOT IN (%s, %s)", + "SELECT id FROM users WHERE ssn NOT LIKE %s", + "SELECT id FROM users WHERE ssn NOT LIKE %s ESCAPE '!'"], + pg=["SELECT id FROM users WHERE ssn IS DISTINCT FROM %s", + "SELECT id FROM users WHERE ssn NOT ILIKE %s", + "SELECT id FROM users WHERE ssn <> ALL(%s)", + "SELECT id FROM users WHERE ssn <> ANY(%s)", + "SELECT id FROM users WHERE ssn = ALL(%s)", + "SELECT id FROM users WHERE ssn LIKE ALL(%s)", + "SELECT id FROM users WHERE ssn NOT LIKE ANY(%s)"]) + def test_unsafe_operators(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and not any(flags) + + @BOTH + def test_a_parenthesized_column_is_judged_like_the_column(self, dialect): + # sqlglot keeps the parentheses as a Paren node around the column. + assert safety("SELECT id FROM users WHERE (ssn) = %s OR ((ssn)) LIKE %s", dialect) == [True, True] + assert safety("DELETE FROM users WHERE (ssn) <> %s", dialect) == [False] + assert safety("DELETE FROM users WHERE %s <> (ssn) OR ((ssn)) NOT LIKE %s", dialect) == [False, False] + + @BOTH + def test_a_sub_selects_only_column_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s IN (SELECT ssn FROM users) OR %s = ANY (SELECT ssn FROM users) " + "OR %s = (SELECT ssn FROM users LIMIT 1)", dialect) == [True] * 3 + # = ALL over no rows is true, so only ALL itself makes it unsafe. + unsafe = ["%s NOT IN (SELECT ssn FROM users)", "%s <> ALL (SELECT ssn FROM users)", + "%s = ALL (SELECT ssn FROM users)", "%s <> ANY (SELECT ssn FROM users)", + "%s <> (SELECT ssn FROM users LIMIT 1)", "%s > (SELECT ssn FROM users LIMIT 1)"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + assert safety("SELECT %s IN (SELECT ssn FROM users) FROM t", dialect) == [False] + + @BOTH + def test_a_sub_select_in_doubled_parentheses_under_all_or_some_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users)) " + "OR %s = some (((select ssn from users)))", dialect) == [True, True] + unsafe = ["%s <> ALL ((SELECT ssn FROM users))", "%s = ALL ((SELECT ssn FROM users))", + "%s = all (((select ssn from users)))", "%s <> SOME ((SELECT ssn FROM users))"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_a_sub_select_read_by_some_in_doubled_parentheses_is_judged_like_any(self, dialect): + assert safety("DELETE FROM orders WHERE uid = SOME ((SELECT id FROM users WHERE ssn = %s)) " + "OR uid = some (((select id from users where dob = %s)))", dialect) == [True, True] + # ALL over a sub-select whose filter never holds is true for every row. + assert safety("DELETE FROM orders WHERE uid = ALL ((SELECT id FROM users WHERE ssn = %s))", dialect) == [False] + # As under <> ANY (SELECT ...), only = reads the sub-select. + assert safety("DELETE FROM orders WHERE uid <> SOME ((SELECT id FROM users WHERE ssn = %s))", dialect) == [False] + + @BOTH + def test_a_sub_select_with_order_by_or_limit_after_its_parentheses_is_judged_like_the_column(self, dialect): + assert safety("SELECT id FROM t WHERE %s = SOME ((SELECT ssn FROM users) LIMIT 5)", dialect) == [True] + unsafe = ["%s <> ALL ((SELECT ssn FROM users) ORDER BY 1)", "%s <> ALL ((SELECT ssn FROM users) LIMIT 5)", + "%s = all ((select ssn from users) order by 1 limit 5)"] + assert [safety(f"DELETE FROM t WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_a_read_sub_select_with_order_by_or_limit_after_its_parentheses_is_judged_by_its_reader(self, dialect): + assert safety("DELETE FROM orders WHERE uid = SOME ((SELECT id FROM users WHERE ssn = %s) LIMIT 5) " + "OR uid = SOME ((SELECT id FROM users WHERE dob = %s) ORDER BY 1) " + "OR EXISTS ((SELECT 1 FROM users WHERE name = %s) ORDER BY 1 LIMIT 1)", dialect) == [True] * 3 + # ALL over a sub-select whose filter never holds is true for every row, and a LIMIT count taken from such a + # sub-select is NULL, which PostgreSQL reads as no limit. + unsafe = ["uid = ALL ((SELECT id FROM users WHERE ssn = %s) LIMIT 5)", + "uid = SOME ((SELECT id FROM t2) LIMIT (SELECT id FROM users WHERE ssn = %s))"] + assert [safety(f"DELETE FROM orders WHERE {c}", dialect) for c in unsafe] == [[False]] * len(unsafe) + + @BOTH + def test_not_like_is_unsafe_without_a_not_node(self, dialect): + sql = "SELECT id FROM users WHERE ssn NOT LIKE %s" + trees, _ = sql_analyzer._parse(tokenize(sql, dialect, ParamStyle.of(P, dialect)).normalized, dialect) + # sqlglot sets the LIKE's negate flag rather than adding a NOT node, + # so only the operator check can see the negation. + assert trees and trees[0].find(exp.Not) is None and trees[0].find(exp.Like).args.get("negate") + assert safety(sql, dialect) == [False] + + @on(both=["SELECT id FROM users WHERE (ssn = %s)", + "SELECT id FROM users WHERE id > 0 AND (name = 'a' OR (ssn = %s))", + "SELECT id FROM users WHERE ((ssn = %s) OR (id > 0 AND ssn = %s))", + "SELECT id FROM users u, orders o WHERE o.uid = u.id AND u.ssn = %s", + "SELECT name FROM users GROUP BY name, ssn HAVING ssn = %s", + "SELECT name, COUNT(*) FROM users GROUP BY name, ssn HAVING ssn = %s", + "SELECT a.name FROM users a JOIN users b ON a.id = b.id AND b.ssn = %s", + "SELECT a.id FROM users a JOIN users b ON b.ssn = %s AND a.id = b.id", + "SELECT u.id FROM users u INNER JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "SELECT name FROM users WHERE id IN (SELECT id FROM users WHERE ssn = %s)", + "SELECT id FROM users WHERE id IN ((SELECT id FROM users WHERE ssn = %s))", + "SELECT id FROM users WHERE id IN (SELECT id FROM users WHERE ssn = %s UNION SELECT id FROM users)", + "SELECT id FROM users u WHERE EXISTS (SELECT 1 FROM users v WHERE v.id = u.id AND v.ssn = %s)", + "SELECT id FROM orders WHERE EXISTS (SELECT id FROM users WHERE ssn = %s AND my_fn(id))", + "DELETE FROM orders WHERE uid = (SELECT id FROM users WHERE ssn = %s)", + "UPDATE orders SET note = 'x' WHERE (SELECT id FROM users WHERE ssn = %s) = uid", + "DELETE FROM orders WHERE uid = ANY(SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid = SOME(SELECT id FROM users WHERE ssn = %s)", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u JOIN orders o ON o.uid = u.id", + "SELECT u.id FROM orders o JOIN (SELECT id FROM users WHERE ssn = %s) u ON o.uid = u.id", + "UPDATE orders SET note = 'x' WHERE uid IN (SELECT id FROM (SELECT id FROM users WHERE ssn = %s) d)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w", + "WITH c AS (SELECT id, ssn FROM users WHERE ssn = %s) SELECT id FROM c", + "WITH c AS (SELECT id, ssn FROM users) SELECT id FROM c WHERE ssn = %s", + "WITH a AS (SELECT id FROM users WHERE ssn = %s), b AS (SELECT id FROM a) SELECT id FROM b", + "WITH a AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM users WHERE id IN (SELECT id FROM a)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT u.id FROM users u JOIN w ON w.id = u.id", + "SELECT id FROM users WHERE ssn = %s UNION SELECT id FROM users", + "SELECT id FROM users UNION ALL SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s INTERSECT SELECT id FROM users", + "SELECT id FROM users INTERSECT SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s EXCEPT SELECT id FROM users", + "(SELECT id FROM users WHERE ssn = %s)", + "((SELECT id FROM users WHERE ssn = %s) UNION (SELECT id FROM users))", + "SELECT id FROM users WHERE ssn = %s ORDER BY id LIMIT 1", + "UPDATE users SET note = 'x' WHERE ssn = %s", + "DELETE FROM users WHERE ssn = %s", + "INSERT INTO audit (uid) SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM users WHERE ssn = %s; DELETE FROM users WHERE ssn = %s"], + pg=["UPDATE users SET note = 'x' WHERE ssn = %s RETURNING id", + "DELETE FROM users WHERE ssn = %s RETURNING id", + "UPDATE users SET name = 'x' FROM users v WHERE v.id = users.id AND v.ssn = %s", + "DELETE FROM users USING users v WHERE v.id = users.id AND v.ssn = %s", + "WITH d AS (DELETE FROM users WHERE ssn = %s RETURNING id) SELECT id FROM d", + "WITH users AS (SELECT id FROM public.users WHERE ssn = %s) SELECT id FROM users"], + mysql=["UPDATE users u JOIN orders o ON o.uid = u.id AND u.ssn = %s SET o.note = 'x'", + "UPDATE users u JOIN orders o ON o.uid = u.id SET o.note = 'x' WHERE u.ssn = %s", + "DELETE u FROM users u JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "DELETE t FROM t JOIN u ON u.id = t.id WHERE u.ssn = %s", + "SELECT u.id FROM users u STRAIGHT_JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "SELECT u.id FROM users u CROSS JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "WITH users AS (SELECT id FROM mydb.users WHERE ssn = %s) SELECT id FROM users"]) + def test_safe_positions(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and all(flags) + + @on(both=["SELECT id FROM users WHERE NOT ssn = %s", + "SELECT id FROM users WHERE NOT (ssn = %s OR id = 1)", + "SELECT id FROM users WHERE (ssn = %s) IS TRUE", + "SELECT id FROM users WHERE (ssn = %s) IS NOT TRUE", + "SELECT id FROM users WHERE (ssn = %s) IS FALSE", + "SELECT id FROM users WHERE (ssn = %s) = FALSE", + "SELECT id FROM users WHERE CASE WHEN ssn = %s THEN FALSE ELSE TRUE END", + "SELECT id FROM users WHERE COALESCE(ssn = %s, FALSE)", + "SELECT ssn = %s FROM users", + "SELECT (SELECT 1 FROM users WHERE ssn = %s) FROM orders", + "SELECT id FROM users ORDER BY ssn = %s", + "SELECT COUNT(*) FROM users GROUP BY ssn = %s", + "UPDATE users SET flag = (ssn = %s)", + "UPDATE users SET note = (SELECT note FROM orders WHERE orders.ssn = %s)", + "INSERT INTO audit (uid) VALUES ((SELECT id FROM users WHERE ssn = %s))", + "SELECT u.id FROM users u LEFT JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u LEFT JOIN users v ON v.id = u.id AND u.ssn = %s", + "SELECT u.id FROM users u LEFT OUTER JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u RIGHT JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT u.id FROM users u RIGHT JOIN users v ON v.id = u.id AND u.ssn = %s", + "DELETE FROM orders WHERE uid NOT IN (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE NOT EXISTS (SELECT 1 FROM users WHERE users.id = orders.uid AND users.ssn = %s)", + "DELETE FROM orders WHERE uid <> ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid > ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid = ALL (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid <> ANY (SELECT id FROM users WHERE ssn = %s)", + "DELETE FROM orders WHERE uid <> (SELECT id FROM users WHERE ssn = %s)", + "SELECT id FROM users EXCEPT SELECT id FROM users WHERE ssn = %s", + "SELECT id FROM orders WHERE uid IN (SELECT id FROM users EXCEPT SELECT id FROM users WHERE ssn = %s)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) DELETE FROM orders WHERE uid NOT IN (SELECT id FROM w)", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT u.id FROM users u LEFT JOIN w ON w.id = u.id", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) SELECT id FROM w UNION SELECT id FROM orders " + "WHERE uid NOT IN (SELECT id FROM w)", + "SELECT v.id FROM users v LEFT JOIN (SELECT id FROM users WHERE ssn = %s) u ON v.id = u.id", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u LEFT JOIN users v ON v.id = u.id", + "SELECT u.id FROM (SELECT id FROM users WHERE ssn = %s) u JOIN orders o ON o.uid = u.id " + "RIGHT JOIN items i ON i.oid = o.id", + "SELECT id FROM orders WHERE (SELECT id FROM users WHERE ssn = %s) IN (1, 2)", + "SELECT u.id FROM users u JOIN orders o ON (SELECT TRUE FROM users v WHERE v.ssn = %s)"], + pg=["UPDATE users SET note = 'x' RETURNING ssn = %s", + "WITH x AS (INSERT INTO audit (uid) SELECT id FROM users WHERE ssn = %s RETURNING uid) SELECT uid FROM x", + "WITH w AS (SELECT id FROM users WHERE ssn = %s) INSERT INTO w (id) VALUES (1)", + "SELECT u.id FROM users u ANTI JOIN orders o ON o.uid = u.id AND u.ssn = %s", + "DELETE FROM orders WHERE uid IS DISTINCT FROM (SELECT id FROM users WHERE ssn = %s)", + "MERGE INTO users t USING src s ON t.ssn = %s WHEN MATCHED THEN DELETE", + "MERGE INTO users t USING src s ON t.id = s.id WHEN MATCHED AND t.ssn = %s THEN DELETE", + "MERGE INTO orders t USING (SELECT id FROM users WHERE ssn = %s) s ON t.uid = s.id WHEN MATCHED THEN DELETE", + "INSERT INTO users (id, ssn) VALUES (%s, %s) ON CONFLICT (id) DO UPDATE SET note = 'x' WHERE users.ssn = %s", + "SELECT u.id FROM users u FULL JOIN users v ON v.id = u.id AND v.ssn = %s", + "SELECT id FROM orders o, LATERAL (SELECT 1 FROM users v WHERE v.ssn = %s) x", + "SELECT id FROM orders o CROSS JOIN LATERAL (SELECT 1 FROM users v WHERE v.ssn = %s) x"], + mysql=["SELECT id FROM users WHERE ssn = %s XOR TRUE", + "SELECT id FROM users WHERE IF(ssn = %s, 0, 1) = 1", + "DELETE FROM orders WHERE uid <=> (SELECT id FROM users WHERE ssn = %s)", + "DELETE u FROM users u LEFT JOIN orders o ON o.uid = u.id AND u.ssn = %s WHERE o.uid IS NULL", + "UPDATE users u LEFT JOIN orders o ON o.uid = u.id AND u.ssn = %s SET u.note = 'x' WHERE o.uid IS NULL"]) + def test_unsafe_positions(self, dialect, sql): + flags = safety(sql, dialect) + assert flags and not any(flags) + + @pytest.mark.parametrize("dialect, sql, column", [ + (PG, "SELECT i.id FROM users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (MYSQL, "DELETE i FROM users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT o.id FROM users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (MYSQL, "SELECT o.id FROM users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT u.id FROM users u LEFT JOIN (orders o JOIN items i ON i.oid = o.id{on}) ON o.uid = u.id{where}", + "o.ssn"), + (MYSQL, "SELECT u.id FROM users u LEFT JOIN (orders o JOIN items i ON i.oid = o.id{on}) ON o.uid = u.id{where}", + "o.ssn"), + (PG, "SELECT i.id FROM (users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id){where}", + "u.ssn"), + (PG, "SELECT r.id FROM users u CROSS JOIN (orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id){where}", "o.ssn"), + (MYSQL, "SELECT r.id FROM users u CROSS JOIN (orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id){where}", "o.ssn"), + (PG, "UPDATE users SET note = 'x' FROM orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r " + "ON r.iid = i.id{where}", "o.ssn"), + (PG, "DELETE FROM users USING orders o JOIN items i ON i.oid = o.id{on} RIGHT JOIN refs r ON r.iid = i.id{where}", + "o.ssn"), + (MYSQL, "UPDATE users u JOIN orders o ON o.uid = u.id{on} LEFT JOIN items i ON i.oid = o.id SET u.note = 'x'{where}", + "u.ssn"), + (MYSQL, "DELETE FROM i USING users u JOIN orders o ON o.uid = u.id{on} RIGHT JOIN items i ON i.oid = o.id{where}", + "u.ssn"), + (PG, "SELECT r.id FROM ((orders JOIN items ON items.oid = orders.id{on}) RIGHT JOIN refs r ON r.iid = items.id){where}", + "orders.ssn"), + (MYSQL, "DELETE u FROM users u CROSS JOIN ((orders JOIN items ON items.oid = orders.id{on}) RIGHT JOIN refs r " + "ON r.iid = items.id){where}", "orders.ssn"), + ], ids=["pg-right", "mysql-delete-right", "pg-later-left", "mysql-later-left", "pg-parenthesized-under-left", + "mysql-parenthesized-under-left", "pg-right-inside-parentheses", "pg-right-inside-a-joined-parenthesis", + "mysql-right-inside-a-joined-parenthesis", "pg-update-from", "pg-delete-using", "mysql-update", + "mysql-delete-using", "pg-right-around-nested-parentheses", "mysql-delete-right-around-nested-parentheses"]) + def test_inner_join_in_a_query_with_an_outer_join_is_unsafe(self, dialect, sql, column): + # A later RIGHT or FULL join keeps every row of its side when the + # earlier join matches nothing, and so does a LEFT join around a + # parenthesized join. A WHERE filters the joined rows. + assert safety(sql.format(on=f" AND {column} = %s", where=""), dialect) == [False] + assert safety(sql.format(on="", where=f" WHERE {column} = %s"), dialect) == [True] + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "UPDATE users SET note = 'x' FROM (SELECT id FROM orders) o " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = o.id WHERE d.id IS NULL AND o.id = users.id"), + (PG, "DELETE FROM users USING (SELECT id FROM orders) o " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = o.id WHERE d.id IS NULL AND o.id = users.id"), + (MYSQL, "UPDATE (SELECT id FROM orders) o JOIN users u ON u.id = o.id " + "LEFT JOIN (SELECT id FROM users WHERE ssn = %s) d ON d.id = u.id SET u.note = 'x' WHERE d.id IS NULL"), + (PG, "SELECT r.id FROM users u CROSS JOIN (((SELECT id FROM users WHERE ssn = %s) d JOIN items ON items.oid = d.id) " + "RIGHT JOIN refs r ON r.iid = items.id)"), + ], ids=["pg-update-from-derived-table", "pg-delete-using-derived-table", "mysql-update-derived-table", + "pg-derived-table-in-nested-parentheses"]) + def test_outer_join_after_a_parenthesized_source_is_seen(self, dialect, sql): + # sqlglot hangs the joins that follow a derived table or a + # parenthesized join on its Subquery. When the derived table d matches + # nothing, the sided join there still keeps every row of its other side. + assert safety(sql, dialect) == [False] + + @pytest.mark.parametrize("sql, safe", [ + ("SELECT id FROM users WHERE (SELECT COUNT(*) FROM users WHERE ssn = %s) = 0", False), + ("DELETE FROM orders WHERE (SELECT COUNT(*) FROM users v WHERE v.id = orders.uid AND v.ssn = %s) = 0", False), + ("SELECT id FROM users WHERE EXISTS (SELECT COUNT(*) FROM users WHERE ssn = %s)", False), + ("SELECT id FROM orders WHERE uid = (SELECT MAX(id) FROM users WHERE ssn = %s)", False), + ("SELECT id FROM users WHERE id IN (SELECT uid FROM orders WHERE ssn = %s GROUP BY uid HAVING COUNT(*) < 2)", + False), + ("SELECT id FROM users WHERE id IN (SELECT uid FROM orders WHERE ssn = %s GROUP BY uid)", False), + ("SELECT id FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s HAVING COUNT(*) < 2)", False), + ("SELECT d.id FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM users WHERE ssn = %s) d", False), + ("WITH c AS (SELECT COUNT(*) AS n FROM users WHERE ssn = %s) SELECT n FROM c", False), + ("SELECT COUNT(*) FROM users WHERE ssn = %s", True), + ], ids=["count-equals-zero", "correlated-count", "exists-count", "max", "group-having", "group", "having", + "window", "cte", "the-statement"]) + @BOTH + def test_aggregating_sub_select_is_unsafe(self, dialect, sql, safe): + assert safety(sql, dialect) == [safe] + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "DELETE FROM orders WHERE EXISTS (SELECT jsonb_agg(id) FROM users WHERE ssn = %s)"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT JSON_ARRAYAGG(id) FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT my_agg(id) FROM users WHERE ssn = %s)"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT my_agg(id) FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s ORDER BY COUNT(*))"), + (MYSQL, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s ORDER BY COUNT(*))"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT DISTINCT ON (COUNT(*)) 1 FROM users WHERE ssn = %s)"), + (PG, "DELETE FROM orders WHERE EXISTS (SELECT 1 FROM users WHERE ssn = %s WINDOW w AS (ORDER BY COUNT(*)))"), + ], ids=["pg-jsonb-agg", "mysql-json-arrayagg", "pg-user-defined", "mysql-user-defined", "pg-order-by", + "mysql-order-by", "pg-distinct-on", "pg-window-clause"]) + def test_possible_aggregate_in_a_sub_select_is_unsafe(self, dialect, sql): + # An aggregate without GROUP BY returns a row for no input row, so the + # EXISTS holds and every order is deleted. sqlglot reads some built-in + # aggregates and every user-defined one as a function it doesn't know, + # and a query's own aggregate can also sit in ORDER BY, DISTINCT ON or + # WINDOW. + assert safety(sql, dialect) == [False] + + @pytest.mark.parametrize("sql", [ + "WITH RECURSIVE r AS (SELECT id FROM users WHERE ssn = %s " + "UNION ALL SELECT u.id FROM users u JOIN r ON u.id = r.id + 1) SELECT id FROM r", + "WITH RECURSIVE r AS (SELECT id FROM users " + "UNION ALL SELECT u.id FROM users u JOIN r ON u.id = r.id + 1 WHERE u.ssn = %s) SELECT id FROM r", + ], ids=["anchor", "recursive-part"]) + @BOTH + def test_recursive_cte_reference_is_unsafe(self, dialect, sql): + assert safety(sql, dialect) == [False] + + @pytest.mark.timeout(5) + @BOTH + def test_long_cte_chain_is_followed_without_recursion(self, dialect): + # Each CTE reads the one before it, so the statement, 2000 queries + # out, decides the comparison's position. + ctes = ["c0 AS (SELECT id FROM users WHERE ssn = %s)"] + [f"c{i} AS (SELECT id FROM c{i - 1})" for i in range(1, 2000)] + assert safety("WITH " + ", ".join(ctes) + " SELECT id FROM c1999", dialect) == [True] + + @BOTH + def test_assignments_and_annotations_keep_the_default(self, dialect): + a = analyze("UPDATE users SET ssn = %s WHERE id <> /*@encrypt:users.ssn*/ %s", dialect, P) + assert [(u.ordinal, u.safe) for u in a.assignments] == [(0, True)] + assert [(u.ordinal, u.safe) for u in a.annotations] == [(1, True)] + assert [(u.ordinal, u.safe) for u in a.comparisons] == [(1, False)] + assert [u.safe for u in analyze("INSERT INTO users (id, ssn) VALUES (%s, %s)", dialect, P).assignments] \ + == [True, True] + + @pytest.mark.timeout(10) + def test_comparison_safety_is_time_bounded_in_a_long_or_chain(self): + # Without the memo, each comparison climbs the rest of the chain: far + # past the timeout at this length. + sql = "SELECT id FROM users WHERE " + " OR ".join(["ssn = %s"] * 40000) + flags = safety(sql, PG) + assert len(flags) == 40000 and all(flags) + + +class TestReads: + @BOTH + def test_tables_and_result_columns(self, dialect): + a = analyze("SELECT u.ssn AS s, o.ssn, name, 1 FROM users u JOIN orders o ON o.uid = u.id", dialect) + assert a.kind is StatementKind.SELECT and not a.writes + assert names(a.tables) == ["users", "orders"] + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("ssn", "orders"), None, None) + + def test_single_table_unqualified(self): + a = analyze("SELECT ssn, name FROM users WHERE id = %s", PG, P) + assert a.result_columns == (ColumnRef("ssn", "users"), ColumnRef("name", "users")) + + @pytest.mark.parametrize("sql", ["SELECT * FROM users", "SELECT u.* FROM users u", + "SELECT ssn FROM users UNION SELECT ssn FROM archive"]) + def test_result_columns_unknown(self, sql): + assert analyze(sql, PG).result_columns is None + + def test_subquery_column_is_traced_to_its_table(self): + a = analyze("SELECT s.ssn FROM (SELECT ssn FROM users) s", PG) + assert a.result_columns == (ColumnRef("ssn", "users"),) + assert names(a.tables) == ["users"] + + @BOTH + @pytest.mark.parametrize("sql, params, expected", [ + ("SELECT x.ssn FROM (SELECT ssn FROM users) AS x", None, (ColumnRef("ssn", "users"),)), + ("SELECT ssn FROM (SELECT ssn FROM users) x", None, (ColumnRef("ssn", "users"),)), + ("WITH c AS (SELECT ssn FROM users) SELECT c.ssn FROM c", None, (ColumnRef("ssn", "users"),)), + ("SELECT y.ssn FROM (SELECT x.ssn FROM (SELECT ssn FROM users) x) y", None, (ColumnRef("ssn", "users"),)), + ("SELECT x.s FROM (SELECT ssn AS s FROM users) x", None, (ColumnRef("ssn", "users"),)), + ("WITH c AS (SELECT ssn FROM users) SELECT x.ssn FROM (SELECT ssn FROM c) x", None, + (ColumnRef("ssn", "users"),)), + ("SELECT u.name, d.ssn FROM users u JOIN (SELECT id, ssn FROM archive) d ON d.id = u.id", None, + (ColumnRef("name", "users"), ColumnRef("ssn", "archive"))), + ("WITH a AS (SELECT id FROM archive), c AS (SELECT ssn FROM users) SELECT c.ssn FROM c", None, + (ColumnRef("ssn", "users"),)), + ("SELECT y.ssn FROM (SELECT id FROM archive) x JOIN (SELECT id, ssn FROM users) y ON x.id = y.id", None, + (ColumnRef("ssn", "users"),)), + # SQLAlchemy's legacy Query.first() over a model with a joined eager load. + ("SELECT anon_1.users_id AS anon_1_users_id, anon_1.users_ssn AS anon_1_users_ssn, addresses_1.id AS addresses_1_id " + "FROM (SELECT users.id AS users_id, users.ssn AS users_ssn FROM users LIMIT %s) AS anon_1 " + "LEFT OUTER JOIN addresses AS addresses_1 ON anon_1.users_id = addresses_1.user_id", P, + (ColumnRef("id", "users"), ColumnRef("ssn", "users"), ColumnRef("id", "addresses"))), + ], ids=["derived", "only_source", "cte", "nested", "relabelled", "cte_behind_derived", "joined", "two_ctes", + "second_derived", "orm_first"]) + def test_derived_and_cte_columns_trace_to_their_table(self, dialect, sql, params, expected): + assert analyze(sql, dialect, params).result_columns == expected + + @BOTH + @pytest.mark.parametrize("sql", [ + "SELECT x.ssn FROM (SELECT ssn FROM users UNION SELECT ssn FROM archive) x", + "SELECT x.ssn FROM (SELECT * FROM users) x", + "SELECT x.s FROM (SELECT upper(ssn) AS s FROM users) x", + "SELECT ssn FROM (SELECT ssn FROM users) x, (SELECT ssn FROM archive) y", + "SELECT g.ssn FROM (SELECT ssn FROM users) y CROSS JOIN generate_series(1, 2) AS g", + ], ids=["set_operation", "star", "expression", "two_sources", "function_source"]) + def test_untraceable_derived_columns_stay_unknown(self, dialect, sql): + assert analyze(sql, dialect).result_columns == (None,) + + @BOTH + def test_self_shadowing_cte_stays_unknown(self, dialect): + # The inner users is the table, but every unqualified users reads as + # the CTE, and a CTE doesn't see itself, so the trace stops there. + assert analyze("WITH users AS (SELECT ssn FROM users) SELECT ssn FROM users", dialect).result_columns == (None,) + + @BOTH + @pytest.mark.parametrize("sql, expected", [ + # Inside c, users is the table: a later CTE of that name isn't seen. + ("WITH c AS (SELECT ssn FROM users), users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c", (None,)), + ("WITH c AS (SELECT u.ssn FROM users u), users AS (SELECT name AS ssn FROM people) SELECT c.ssn FROM c", (None,)), + ("WITH c AS (SELECT x.ssn FROM (SELECT ssn FROM users) x), users AS (SELECT name AS ssn FROM people) " + "SELECT ssn FROM c", (None,)), + ("WITH users AS (SELECT name AS ssn FROM people), c AS (SELECT ssn FROM users) SELECT ssn FROM c", + (ColumnRef("name", "people"),)), + # Past c, the trace takes the outer users; under RECURSIVE, PostgreSQL + # reads the later inner one instead, so the column stays unknown. + ("WITH users AS (SELECT addr AS ssn FROM homes) SELECT z.ssn FROM (WITH c AS (SELECT ssn FROM users), " + "users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c) z", (ColumnRef("addr", "homes"),)), + ("WITH users AS (SELECT addr AS ssn FROM homes) SELECT z.ssn FROM (WITH RECURSIVE c AS (SELECT ssn FROM users), " + "users AS (SELECT name AS ssn FROM people) SELECT ssn FROM c) z", (None,)), + ], ids=["forward", "forward_qualified", "forward_in_derived", "backward", "nested_outer", "nested_outer_recursive"]) + def test_a_cte_sees_only_the_ctes_before_it(self, dialect, sql, expected): + assert analyze(sql, dialect).result_columns == expected + + @BOTH + @pytest.mark.parametrize("sql", [ + "WITH c(ssn, name) AS (SELECT name, ssn FROM users) SELECT c.ssn, c.name FROM c", + "SELECT x.ssn, x.name FROM (SELECT name, ssn FROM users) AS x(ssn, name)", + ], ids=["cte", "derived"]) + def test_a_source_with_a_column_list_stays_unknown(self, dialect, sql): + # The list renames the columns by position (here c.ssn is users.name), + # which the trace doesn't follow. + assert analyze(sql, dialect).result_columns == (None, None) + + @pytest.mark.parametrize("sql, expected", [ + ("WITH c AS (SELECT name, ssn FROM users) SELECT x.ssn FROM c AS x(ssn, name)", (None,)), + ("SELECT d.ssn FROM users AS u(a, b) JOIN (SELECT id, ssn FROM archive) d ON d.id = u.a", + (ColumnRef("ssn", "archive"),)), + ], ids=["cte_renamed_where_read", "other_source_renamed"]) + def test_only_a_column_list_on_the_traced_source_matters(self, sql, expected): + assert analyze(sql, PG).result_columns == expected + + def test_returning_list_is_not_traced(self): + a = analyze("UPDATE users SET name = %s FROM (SELECT id, ssn FROM archive) x WHERE users.id = x.id " + "RETURNING x.ssn", PG, P) + assert a.result_columns == (None,) + + def test_trace_stops_after_eight_levels(self): + def nested(levels): + sql = "SELECT ssn FROM users" + for i in range(levels): + sql = f"SELECT t{i}.ssn FROM ({sql}) t{i}" + return sql + + assert analyze(nested(8), PG).result_columns == (ColumnRef("ssn", "users"),) + assert analyze(nested(9), PG).result_columns == (None,) + + @pytest.mark.parametrize("sql, expected", [ + ('SELECT x."S" FROM (SELECT ssn AS "S" FROM users) x', (ColumnRef("ssn", "users"),)), + ('SELECT x.s FROM (SELECT ssn AS "S" FROM users) x', (None,)), + ], ids=["quoted", "unquoted"]) + def test_quoted_alias_matches_as_quoted(self, sql, expected): + assert analyze(sql, PG).result_columns == expected + + @pytest.mark.parametrize("sql", [ + "SELECT x.s FROM (SELECT ssn AS `S` FROM users) x", + "SELECT X.SSN FROM (SELECT ssn FROM users) x", + ], ids=["alias", "qualifier"]) + def test_mysql_traces_names_without_case(self, sql): + assert analyze(sql, MYSQL).result_columns == (ColumnRef("ssn", "users"),) + + def test_union_tables(self): + assert names(analyze("SELECT ssn FROM users UNION ALL SELECT ssn FROM archive", PG).tables) == [ + "users", "archive"] + + def test_for_update_is_not_a_write(self): + assert not analyze("SELECT * FROM users WHERE id = %s FOR UPDATE", PG, P).writes + + +class TestIdentifiers: + def test_postgresql_folds_ascii_letters_only(self): + # As PostgreSQL does in a multibyte (UTF-8) database. + assert PG.fold_identifier("ƄBc", quoted=False) == "Ƅbc" + assert PG.fold_identifier("ƄBc", quoted=True) == "ƄBc" + assert MYSQL.fold_identifier("ƄBc", quoted=False) == "ƄBc" + assert (PG.metadata_key("Users"), MYSQL.metadata_key("Users")) == ("Users", "users") + + def test_postgresql_folds_unquoted_names(self): + a = analyze('INSERT INTO Users (Name, "SSN") VALUES (%s, %s)', PG, P) + assert assigned(a) == [(0, "users.name"), (1, "users.SSN")] + + def test_postgresql_quoted_table(self): + a = analyze('UPDATE "Users" SET ssn = %s', PG, P) + assert names(a.written_tables) == ["Users"] + + def test_mysql_keeps_case_and_strips_backticks(self): + a = analyze("INSERT INTO `Users` (`Name`, SSN) VALUES (%s, %s)", MYSQL, P) + assert assigned(a) == [(0, "Users.Name"), (1, "Users.SSN")] + + def test_mysql_alias_match_is_case_insensitive(self): + a = analyze("UPDATE users U SET u.ssn = %s WHERE U.id = %s", MYSQL, P) + assert assigned(a) == [(0, "users.ssn")] and compared(a) == [(1, "users.id")] + + def test_quoted_alias(self): + a = analyze('SELECT "U".ssn FROM users "U" WHERE "U".id = %s', PG, P) + assert compared(a) == [(0, "users.id")] + + +class TestAnnotations: + def test_annotation_overrides_inference(self): + a = analyze("INSERT INTO t (a, b) VALUES (/*@encrypt:users.ssn*/ %s, %s)", PG, P) + assert [(u.ordinal, str(u.column)) for u in a.annotations] == [(0, "users.ssn")] + assert a.parameter_columns() == {0: ColumnRef("ssn", "users"), 1: ColumnRef("b", "t")} + + def test_alias_qualifier_is_resolved(self): + a = analyze("UPDATE users u SET note = /*@encrypt:u.ssn*/ %s", PG, P) + assert [str(u.column) for u in a.annotations] == ["users.ssn"] + + def test_annotations_survive_an_unparseable_statement(self): + a = analyze("INSERT INTO t OVERRIDING SYSTEM VALUE VALUES (/*@encrypt:t.ssn*/ %s)", PG, P) + assert a.gap is AnalysisGap.UNPARSEABLE + assert [str(u.column) for u in a.annotations] == ["t.ssn"] + + def test_annotations_survive_an_unsupported_statement(self): + a = analyze("EXPLAIN ANALYZE INSERT INTO t (a) VALUES (/*@encrypt:t.a*/ %s)", PG, P) + assert [str(u.column) for u in a.annotations] == ["t.a"] + + def test_stray_annotations_are_reported(self): + a = analyze("INSERT INTO t (a) VALUES (%s) /*@encrypt:t.a*/", PG, P) + assert a.stray_annotations == ("/*@encrypt:t.a*/",) + + +class TestNotEstablished: + @pytest.mark.parametrize("dialect, sql, params, gap", [ + (PG, "INSERT INTO t (a) VALUES ('%s')", P, AnalysisGap.HIDDEN_PLACEHOLDER), + (MYSQL, "INSERT INTO t (a) VALUES (%s) -- %s", P, AnalysisGap.HIDDEN_PLACEHOLDER), + (PG, "INSERT INTO t (a) VALUES (%s, %(x)s)", P, AnalysisGap.DRIVER_ERROR), + (PG, "INSERT INTO t (a) VALUES (%s) WHERE 1 % 2", P, AnalysisGap.DRIVER_ERROR), + (PG, "INSERT INTO t (a) VALUES ('abc", P, AnalysisGap.UNPARSEABLE), + (PG, "INSERT INTO t (a VALUES (%s)", P, AnalysisGap.UNPARSEABLE), + (PG, "INSERT INTO t (a) OVERRIDING SYSTEM VALUE VALUES (%s)", P, AnalysisGap.UNPARSEABLE), + (PG, "EXPLAIN ANALYZE INSERT INTO t (a) VALUES (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "EXECUTE p (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + (MYSQL, "LOAD DATA INFILE 'x' INTO TABLE t", None, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "SET search_path TO app; INSERT INTO t (a) VALUES (%s)", P, AnalysisGap.UNSUPPORTED_STATEMENT), + ]) + def test_writes_not_established(self, dialect, sql, params, gap): + a = analyze(sql, dialect, params) + assert a.writes and a.gap is gap and not a.complete + assert a.assignments == () and a.unbound_writes == () + + @pytest.mark.parametrize("dialect, sql, tables", [ + (PG, "INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (PG, 'SELECT a AS "x%s" FROM t WHERE b = %s', (TableRef("t"),)), + (PG, "UPDATE app.t SET a = %s /* %s */ WHERE id = %s", (TableRef("t", "app"),)), + (PG, "SELECT t.a FROM t JOIN u ON u.id = t.id WHERE t.b = %s AND t.c = 'x%s'", (TableRef("t"), TableRef("u"))), + (PG, "WITH c AS (SELECT a FROM t) SELECT a FROM c WHERE a = %s -- %s", (TableRef("t"),)), + (PG, "PREPARE p AS INSERT INTO t (a, b) VALUES ($1, 'x%s')", (TableRef("t"),)), + (MYSQL, "INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (MYSQL, "SELECT a AS `x%s` FROM t WHERE b = %s", (TableRef("t"),)), + (MYSQL, "UPDATE app.t SET a = %s WHERE id = %s -- %s", (TableRef("t", "app"),)), + (MYSQL, "INSERT INTO t (a, `b%s`) VALUES (%s, %s)", (TableRef("t"),)), + (MYSQL, "SELECT t.a FROM t JOIN u ON u.id = t.id WHERE t.b = %s # %s", (TableRef("t"), TableRef("u"))), + (MYSQL, "INSERT INTO t (t.a, t.b) VALUES (%s, 'x%s')", (TableRef("t"),)), + # The main path doesn't analyze these statements, but their tables + # must still be listed, or a caller would let them reach a table with + # encrypted columns. + (PG, "SET search_path TO app; INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (PG, "CREATE TABLE u AS SELECT a FROM t WHERE b = %s AND c = 'x%s'", (TableRef("u"), TableRef("t"))), + (MYSQL, "EXPLAIN INSERT INTO t (a, b) VALUES (%s, 'x%s')", (TableRef("t"),)), + (MYSQL, "DESCRIBE SELECT a FROM t WHERE b = %s AND c = 'x%s'", (TableRef("t"),)), + ], ids=["pg_literal", "pg_identifier_select", "pg_comment", "pg_join", "pg_cte", "pg_prepare", "mysql_literal", + "mysql_identifier_select", "mysql_comment", "mysql_identifier", "mysql_join", "mysql_qualified_columns", + "pg_set_then_insert", "pg_create_table_as", "mysql_explain_insert", "mysql_describe_select"]) + def test_hidden_placeholder_gap_still_lists_the_tables(self, dialect, sql, tables): + # The tables are what lets a caller refuse such a statement when one + # of them has encrypted columns; the placeholders still can't be + # paired with columns, so nothing else is reported. + a = analyze(sql, dialect, P) + assert a.gap is AnalysisGap.HIDDEN_PLACEHOLDER and a.kind is StatementKind.UNKNOWN + assert a.tables == tables + assert a.assignments == () and a.comparisons == () and a.annotations == () and a.result_columns is None + + def test_unparseable_read_is_not_a_write(self): + a = analyze("SELECT FROM WHERE %s", PG, P) + assert a.kind is StatementKind.UNKNOWN and not a.writes + + @pytest.mark.parametrize("sql", ["CREATE TABLE t (a int)", "BEGIN", "CALL p(1)", "", " -- just a comment"]) + def test_statements_that_write_no_column(self, sql): + a = analyze(sql, PG) + assert not a.writes and a.complete + + def test_placeholder_text_in_the_sql_is_a_mismatch(self): + # Something that looks like a normalized placeholder must not be + # taken for one. + a = analyze("INSERT INTO t (a, b) VALUES (%s, :_kms_p0)", PG, P) + assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH + + def test_parser_failure_of_any_kind_is_unparseable(self, monkeypatch): + def boom(*_args, **_kwargs): + raise RecursionError("too deep") + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", boom) + a = sql_analyzer._analysis("INSERT INTO t (a) VALUES (%s)", PG, sql_analyzer.ParamStyle.POSITIONAL) + assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "RecursionError" + + def test_mysql_without_params_leaves_percent_s(self): + # Connector/Python sends %s as written when there are no parameters. + a = analyze("INSERT INTO t (a) VALUES (%s)", MYSQL, ()) + assert a.placeholders == () and a.gap is AnalysisGap.UNPARSEABLE + + +class TestApi: + def test_cached_and_immutable(self): + a = analyze("SELECT * FROM t WHERE a = %s", PG, P) + assert analyze("SELECT * FROM t WHERE a = %s", PG, [2]) is a + with pytest.raises(AttributeError): + a.writes = True # type: ignore[misc] + + def test_cache_is_per_dialect_and_style(self): + sql = "SELECT * FROM t WHERE a = %s" + assert analyze(sql, PG, P) is not analyze(sql, MYSQL, P) + assert analyze(sql, PG, P) is not analyze(sql, PG, None) + + def test_long_sql_is_not_cached(self): + rows = ", ".join(["(%s, %s)"] * 2000) + sql = f"INSERT INTO users (name, ssn) VALUES {rows}" + assert len(sql) > sql_analyzer.CACHEABLE_SQL_LENGTH + a = analyze(sql, MYSQL, P) + assert len(a.assignments) == 4000 and a.assignments[-1].ordinal == 3999 + assert analyze(sql, MYSQL, P) is not a + + def test_short_sql_with_many_placeholders_is_not_cached(self): + # A bulk INSERT under the length limit still holds an object per + # placeholder; caching every row count would grow without need. + sql = "INSERT INTO t (a) VALUES " + ",".join(["(%s)"] * (sql_analyzer.CACHEABLE_PERCENT_SIGNS + 1)) + assert len(sql) <= sql_analyzer.CACHEABLE_SQL_LENGTH + assert analyze(sql, PG, P) is not analyze(sql, PG, P) + + def test_nested_results_are_frozen(self): + a = analyze("INSERT INTO users (ssn) VALUES (%s)", PG, P) + with pytest.raises(dataclasses.FrozenInstanceError): + a.assignments[0].column = ColumnRef("x") # type: ignore[misc] + with pytest.raises(dataclasses.FrozenInstanceError): + a.assignments[0].column.table = "x" # type: ignore[misc] + with pytest.raises(dataclasses.FrozenInstanceError): + a.placeholders[0].key = 5 # type: ignore[misc] + + def test_recursion_error_is_not_cached(self, monkeypatch): + # How deep sqlglot can recurse depends on the caller's stack, so a + # failure for one caller must not be served to the next. + real = sqlglot.parse + calls = [] + + def flaky(sql, read): + calls.append(sql) + if len(calls) == 1: + raise RecursionError("too deep") + return real(sql, read=read) + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", flaky) + sql = "UPDATE users SET ssn = %s" + assert analyze(sql, PG, P).gap is AnalysisGap.UNPARSEABLE + assert analyze(sql, PG, P).gap is None + + def test_deep_nesting_from_a_deep_stack_is_a_gap(self): + sql = "UPDATE users SET ssn = " + "(" * 40 + "%s" + ")" * 40 + result = [] + + def deep(n): + if n: + return deep(n - 1) + result.append(analyze(sql, PG, P)) + + thread = threading.Thread(target=deep, args=(sys.getrecursionlimit() - 200,)) + thread.start() + thread.join() + assert result and result[0].gap is AnalysisGap.UNPARSEABLE + + def test_type_error_for_non_str(self): + with pytest.raises(TypeError): + analyze(b"SELECT 1", PG) # type: ignore[arg-type] + + @pytest.mark.parametrize("dialect, sql, params", [ + (MYSQL, "CALL p(%s)", P), + (PG, "EXPLAIN ANALYZE INSERT INTO t (a) VALUES (%s)", P), + # Parsed, but sqlglot falls back to a command (and would log the + # statement, literal included). + (PG, "COPY users (ssn) FROM STDIN WITH (FORMAT text) WHERE ssn <> '123-45-6789'", None), + (MYSQL, "SELECT JSON_EXTRACT(doc, '$[last]') FROM t WHERE ssn = '123-45-6789'", None), + ]) + def test_the_parser_never_logs_statement_text(self, caplog, dialect, sql, params): + with caplog.at_level(logging.DEBUG, logger="sqlglot"): + analyze(sql, dialect, params) + assert caplog.records == [] + + def test_the_applications_own_sqlglot_logging_is_untouched(self, caplog): + with caplog.at_level(logging.WARNING, logger="sqlglot"): + sqlglot.parse("CALL p(1)", read="mysql") + assert caplog.records + + @pytest.mark.parametrize("dialect, sql, params", [ + (PG, "INSERT INTO t (c, d) VALUES ('100%(card 4111-1111-1111-1111)x', %s)", P), + (PG, "INSERT INTO t (c, d) VALUES ('4111-1111-1111-1111 %d', %s)", P), + (MYSQL, "INSERT INTO t (c) VALUES (%(ssn 123-45-6789)d)", {"a": 1}), + (PG, "INSERT INTO t (secret_col) VALUES ('top secret', %s", P), + ]) + def test_detail_never_quotes_the_sql(self, dialect, sql, params): + a = analyze(sql, dialect, params) + assert a.gap is not None + assert a.detail is not None or a.gap is AnalysisGap.UNPARSEABLE + for secret in ("4111", "123-45", "secret"): + assert secret not in (a.detail or "") + + +class TestReviewRegressions: + """Regression tests for statements the analysis once got wrong: annotation + scopes, MySQL syntax, ORM-rendered SQL and statement kinds.""" + + # ---- annotations resolve in the placeholder's own scope ---- + + @pytest.mark.parametrize("dialect, sql, expected", [ + (MYSQL, "UPDATE accounts u SET x = %s WHERE id = 1; UPDATE users u SET ssn = /*@encrypt:u.ssn*/ %s", + {0: "accounts.x", 1: "users.ssn"}), + (PG, "WITH w AS (UPDATE users u SET ssn = /*@encrypt:u.ssn*/ %s RETURNING u.id) SELECT * FROM w", + {0: "users.ssn"}), + (PG, "WITH w AS (INSERT INTO users AS u (ssn) VALUES (/*@encrypt:u.ssn*/ %s) RETURNING id) SELECT * FROM w", + {0: "users.ssn"}), + (PG, "UPDATE users u SET name = %s WHERE id IN " + "(SELECT uid FROM accounts u WHERE u.secret = /*@encrypt:u.secret*/ %s)", + {0: "users.name", 1: "accounts.secret"}), + (PG, "SELECT 1 FROM accounts u UNION SELECT 1 FROM users u WHERE u.ssn = /*@encrypt:u.ssn*/ %s", + {0: "users.ssn"}), + ]) + def test_annotation_alias_is_resolved_where_the_placeholder_is(self, dialect, sql, expected): + a = analyze(sql, dialect, P) + assert {k: str(v) for k, v in a.parameter_columns().items()} == expected + + def test_bare_annotation_keeps_the_table_the_analysis_found(self): + a = analyze("UPDATE users SET ssn = /*@encrypt:ssn*/ %s", PG, P) + assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} + + def test_bare_annotation_naming_another_column_takes_the_only_table(self): + a = analyze("INSERT INTO users (note) VALUES (/*@encrypt:ssn*/ %s)", PG, P) + assert a.parameter_columns() == {0: ColumnRef("ssn", "users")} + + def test_mysql_annotation_alias_is_case_insensitive(self): + a = analyze("UPDATE users u SET note = /*@encrypt:U.ssn*/ %s", MYSQL, P) + assert [str(u.column) for u in a.annotations] == ["users.ssn"] + + @pytest.mark.parametrize("sql", [ + "INSERT INTO t (a, b) VALUES (/*@encrypt:t.a*/ %s, '%s')", # hidden placeholder + "INSERT INTO t (a, b) VALUES (/*@encrypt:t.a*/ %s, :_kms_p0)", # placeholder mismatch + ]) + def test_annotations_survive_every_gap(self, sql): + a = analyze(sql, PG, P) + assert a.gap is not None + assert [str(u.column) for u in a.annotations] == ["t.a"] + + # ---- MySQL executable comments run on the server ---- + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (/*!80000 ssn, */ name) VALUES (%s /*!80000 , DEFAULT*/)", + "INSERT INTO users (name, ssn) VALUES (%s, %s) /*! ON DUPLICATE KEY UPDATE ssn = 'plain' */", + "UPDATE users SET name = %s /*!, ssn = 'plain' */ WHERE id = %s", + "SELECT 1 /*M! , 2 */", + ]) + def test_executable_comment_is_not_established(self, sql): + a = analyze(sql, MYSQL, P) + assert a.gap is AnalysisGap.EXECUTABLE_COMMENT + assert a.assignments == () + + def test_executable_comment_write_keyword_counts(self): + assert analyze("SELECT 1 /*! ; INSERT INTO t (a) VALUES (1) */", MYSQL).writes + + def test_optimizer_hint_is_an_ordinary_comment(self): + a = analyze("UPDATE /*+ NO_INDEX_MERGE(users) */ users SET ssn = %s", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + # ---- MySQL charset introducers (Django renders binary values as _binary %s) ---- + + def test_binary_introducer_in_insert(self): + a = analyze("INSERT INTO `Person` (`name`, `ssn`, `note`) VALUES (%s, _binary %s, %s), (%s, _binary %s, %s)", + MYSQL, P) + assert a.complete and unbound(a) == [] + assert assigned(a) == [(0, "Person.name"), (1, "Person.ssn"), (2, "Person.note"), + (3, "Person.name"), (4, "Person.ssn"), (5, "Person.note")] + assert [p.introducer for p in a.placeholders] == [None, "_binary", None] * 2 + + def test_binary_introducer_in_update_and_upsert(self): + a = analyze("UPDATE `Person` SET `ssn` = _binary %s, `name` = %s WHERE `Person`.`id` = %s", MYSQL, P) + assert a.complete and assigned(a) == [(0, "Person.ssn"), (1, "Person.name")] + a = analyze("INSERT INTO `Person` (`ssn`) VALUES (_binary %s) AS new ON DUPLICATE KEY UPDATE `ssn` = new.`ssn`", + MYSQL, P) + assert a.complete and unbound(a) == [] + + def test_introducer_needs_a_known_charset(self): + # "_x %s" is not an introducer, so the statement reads as written. + a = analyze("SELECT _x %s", MYSQL, P) + assert [p.introducer for p in a.placeholders] == [None] + + def test_introducer_only_on_mysql(self): + assert analyze("SELECT _binary %s", PG, P).placeholders[0].introducer is None + + # ---- MySQL row alias with a column list renames by position ---- + + def test_row_alias_columns_copy_by_position(self): + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new(n, s) ON DUPLICATE KEY UPDATE ssn = new.s", + MYSQL, P) + assert unbound(a) == [] + + def test_row_alias_column_naming_another_insert_column_is_unbound(self): + # new.ssn is the incoming *name*: alias columns rename by position. + a = analyze("INSERT INTO users (name, ssn) VALUES (%s, %s) AS new(ssn, name) " + "ON DUPLICATE KEY UPDATE ssn = new.ssn", MYSQL, P) + assert unbound(a) == ["users.ssn"] + + # ---- copies from another table ---- + + @pytest.mark.parametrize("dialect, sql", [ + (MYSQL, "UPDATE users u JOIN orders o ON o.uid = u.id SET u.ssn = o.ssn"), + (PG, "UPDATE users SET ssn = o.ssn FROM other o WHERE o.id = users.id"), + ]) + def test_copy_of_another_tables_column_of_the_same_name_is_unbound(self, dialect, sql): + assert unbound(analyze(sql, dialect)) == ["users.ssn"] + + # ---- SQLAlchemy's multi-row ORM insert on PostgreSQL ---- + + def test_insert_select_from_values_list(self): + sql = ("INSERT INTO users (name, ssn) SELECT p0::VARCHAR, p1::BYTEA FROM " + "(VALUES (%(name__0)s::VARCHAR, %(ssn__0)s, 0), (%(name__1)s::VARCHAR, %(ssn__1)s, 1)) " + "AS imp_sen(p0, p1, sen_counter) ORDER BY sen_counter RETURNING users.id, users.id AS id__1") + a = analyze(sql, PG, N) + assert a.complete + assert [(u.placeholder.key, str(u.column)) for u in a.assignments] == [ + ("name__0", "users.name"), ("ssn__0", "users.ssn"), ("name__1", "users.name"), ("ssn__1", "users.ssn")] + assert a.assignments[1].casts == ("VARBINARY",) + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (ssn) SELECT v.p0 FROM (VALUES (%s)) AS v(p0) WHERE v.p0 IS NOT NULL", + "INSERT INTO users (ssn) SELECT upper(p0) FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (ssn) SELECT p0 FROM (VALUES (%s)) AS v(p0) JOIN x ON true", + "INSERT INTO users (ssn) SELECT q FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (name, ssn) SELECT %s, %s", + ]) + def test_other_insert_selects_are_values_from_query(self, sql): + assert analyze(sql, PG, P).gap is AnalysisGap.VALUES_FROM_QUERY + + # ---- statements that run a stored statement ---- + + def test_execute_may_write(self): + a = analyze("EXECUTE ins_user(%s, %s)", PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + + def test_prepare_body_is_read(self): + a = analyze("PREPARE ins (text, text) AS INSERT INTO users (name, ssn) VALUES ($1, '123-45-6789')", PG) + assert a.kind is StatementKind.INSERT and a.writes + assert a.gap is AnalysisGap.PREPARED_PARAMETERS + # The literal is reported as an unbound write; $1 is bound by a later + # EXECUTE. + assert unbound(a) == ["users.ssn"] + + def test_prepare_of_a_read(self): + a = analyze('PREPARE "q" AS SELECT ssn FROM users WHERE id = $1', PG) + assert a.kind is StatementKind.SELECT and not a.writes and a.complete + + # ---- DELETE ... USING ---- + + def test_delete_using_aliases_are_in_scope(self): + a = analyze("DELETE FROM users USING accounts a WHERE a.uid = users.id AND a.secret = %s RETURNING a.secret", + PG, P) + assert compared(a) == [(0, "accounts.secret")] + assert a.result_columns == (ColumnRef("secret", "accounts"),) + + # ---- ALL / SOME ---- + + @pytest.mark.parametrize("sql", ["SELECT * FROM t WHERE c <> ALL(%s)", "SELECT * FROM t WHERE c = SOME(%s)", + "SELECT * FROM t WHERE c = ANY(%s::text[])"]) + def test_all_some_and_any_are_array_comparisons(self, sql): + a = analyze(sql, PG, P) + assert [(u.ordinal, str(u.column), u.array) for u in a.comparisons] == [(0, "t.c", True)] + + # ---- MySQL qualified INSERT column lists ---- + + @pytest.mark.parametrize("sql, expected", [ + ("INSERT INTO users (users.name, users.ssn) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn")]), + ("INSERT INTO mydb.users (mydb.users.ssn) VALUES (%s)", [(0, "users.ssn")]), + ("INSERT INTO `users` (`users`.`ssn`) VALUES (%s)", [(0, "users.ssn")]), + ]) + def test_mysql_qualified_insert_columns(self, sql, expected): + a = analyze(sql, MYSQL, P) + assert a.complete and assigned(a) == expected + + # ---- names that are not plain identifiers ---- + + def test_subscripted_column_is_not_a_column_name(self): + a = analyze("MERGE INTO t USING s ON 1=1 WHEN NOT MATCHED THEN INSERT (ssn[1]) VALUES (%s)", PG, P) + assert a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + assert assigned(a) == [] + + # ---- keyword fallback ---- + + @pytest.mark.parametrize("sql", [ + "SET search_path TO app; WITH w AS (INSERT INTO users (ssn) VALUES (%s) RETURNING id) SELECT * FROM w", + "SET search_path TO app; COPY users (ssn) FROM STDIN", + ]) + def test_unparsed_statement_before_a_write_is_not_complete(self, sql): + a = analyze(sql, PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT + + # ---- parse-trust guards ---- + + def test_placeholder_missing_from_the_parse_is_a_mismatch(self, monkeypatch): + real = sqlglot.parse + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", + lambda _sql, read: real("INSERT INTO users (name, ssn) VALUES (:_kms_p0, 'x')", read=read)) + a = sql_analyzer._analysis("INSERT INTO users (name, ssn) VALUES (%s, %s)", PG, ParamStyle.POSITIONAL) + assert a.gap is AnalysisGap.PLACEHOLDER_MISMATCH and a.assignments == () + + def test_command_fallback_is_unparseable(self, monkeypatch): + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", lambda _sql, read: [exp.Command(this="INSERT")]) + a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES ('x')", PG, ParamStyle.NONE) + assert a.writes and a.gap is AnalysisGap.UNPARSEABLE + + def test_unterminated_is_unparseable_even_if_the_parser_accepts_it(self, monkeypatch): + real = sqlglot.parse + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", + lambda _sql, read: real("INSERT INTO users (ssn) VALUES (:_kms_p0)", read=read)) + a = sql_analyzer._analysis("INSERT INTO users (ssn) VALUES (%s) /* a /* b */", PG, ParamStyle.POSITIONAL) + assert a.writes and a.gap is AnalysisGap.UNPARSEABLE and a.assignments == () + + # ---- row lengths ---- + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (a) VALUES (%s, %s)", + "MERGE INTO users u USING src s ON u.id = s.id WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (%s)", + "MERGE INTO users u USING src s ON u.id = s.id WHEN NOT MATCHED THEN INSERT (id) VALUES (%s, %s)", + ]) + def test_row_length_mismatch_both_ways(self, sql): + assert analyze(sql, PG, P).gap is AnalysisGap.ROW_LENGTH_MISMATCH + + def test_several_selects_have_no_result_columns(self): + assert analyze("SELECT ssn FROM users; SELECT name FROM accounts", PG).result_columns is None + + # ---- performance ---- + + def test_long_boolean_chain_is_linear(self): + sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 3000) + a = analyze(sql, PG, P) + assert len(a.comparisons) == 6000 and a.comparisons[-1].column == ColumnRef("ssn", "users") + + +class TestReviewRegressionsRound2: + """Regression tests: annotations across tables, SQLAlchemy's multi-row + insert, regex cost, caching and the logging filter.""" + + # ---- annotations ---- + + @pytest.mark.parametrize("sql, expected", [ + ("UPDATE users u SET name = %s WHERE id IN (SELECT uid FROM accounts a WHERE a.x = /*@encrypt:u.ssn*/ %s)", + {0: "users.name", 1: "users.ssn"}), + ("SELECT * FROM users u WHERE EXISTS " + "(SELECT 1 FROM accounts a WHERE a.uid = u.id AND a.x = /*@encrypt:u.ssn*/ %s)", + {0: "users.ssn"}), + ]) + def test_annotation_qualifier_resolves_through_outer_queries(self, sql, expected): + assert {k: str(v) for k, v in analyze(sql, PG, P).parameter_columns().items()} == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "UPDATE users SET ssn = /*@encrypt:ssn*/ %s FROM accounts a WHERE a.id = users.id", + ColumnRef("ssn", "users")), + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id SET u.SSN = /*@encrypt:ssn*/ %s", + ColumnRef("ssn", "users")), + # A column other than the one assigned: the single written table. + (PG, "UPDATE users SET note = /*@encrypt:ssn*/ %s FROM accounts a WHERE a.id = users.id", + ColumnRef("ssn", "users")), + # Several written tables and another column: the table can't be told. + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id SET u.note = /*@encrypt:ssn*/ %s, a.x = 1", + ColumnRef("ssn")), + ]) + def test_bare_annotation_with_several_tables(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns() == {0: expected} + + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "INSERT INTO orders (user_id, payment_info) SELECT id, /*@encrypt:payment_info*/ %s FROM temp", + ColumnRef("payment_info", "orders")), + (MYSQL, "INSERT INTO orders (payment_info) SELECT /*@encrypt:payment_info*/ %s FROM DUAL", + ColumnRef("payment_info", "orders")), + (PG, "INSERT INTO users (name, ssn) SELECT name, /*@encrypt:ssn*/ %s FROM accounts", ColumnRef("ssn", "users")), + (PG, "UPDATE users SET ssn = (SELECT /*@encrypt:ssn*/ %s FROM accounts)", ColumnRef("ssn", "users")), + ]) + def test_bare_annotation_in_a_query_feeding_a_write_names_the_written_table(self, dialect, sql, expected): + # The value goes to the write's target, even though the subquery reads another table. + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + # ---- SQLAlchemy's multi-row insert ---- + + def test_insert_select_from_values_maps_select_items_by_name(self): + a = analyze("INSERT INTO users (name, ssn) SELECT p1, p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", PG, P) + assert a.complete + assert assigned(a) == [(0, "users.ssn"), (1, "users.name")] + + @pytest.mark.parametrize("sql", [ + "INSERT INTO users (ssn, note) SELECT p0, p0 FROM (VALUES (%s)) AS v(p0)", + "INSERT INTO users (name, ssn) SELECT v.p0, p0::text FROM (VALUES (%s, %s)) AS v(p0, p1)", + ]) + def test_insert_select_from_values_using_a_column_twice_is_not_read(self, sql): + # One value would fill two columns, and could be encrypted for only one. + a = analyze(sql, PG, P) + assert a.gap is AnalysisGap.VALUES_FROM_QUERY and a.assignments == () + + @pytest.mark.parametrize("sql, gap", [ + ("INSERT INTO users (name, ssn) SELECT p0 FROM (VALUES (%s, %s)) AS v(p0, p1)", AnalysisGap.VALUES_FROM_QUERY), + ("INSERT INTO users (name, ssn) SELECT p0, p1 FROM (VALUES (%s, %s), (%s)) AS v(p0, p1)", + AnalysisGap.ROW_LENGTH_MISMATCH), + ("INSERT INTO users (ssn) SELECT p0 FROM (VALUES (%s)) AS v(p0) FETCH FIRST 1 ROWS ONLY", + AnalysisGap.VALUES_FROM_QUERY), + ]) + def test_insert_select_from_values_widths_and_extras(self, sql, gap): + assert analyze(sql, PG, P).gap is gap + + # ---- regex cost on indented SQL ---- + + @pytest.mark.timeout(10) + @pytest.mark.parametrize("dialect, sql", [ + (MYSQL, "\n" + " " * 60 + "\n" + " " * 60 + "UPDATE users SET ssn = %s WHERE id = %s AND (name = 'x'"), + (MYSQL, " " * 60 + "SELECT a FROM t WHERE b = %s INTO OUTFILE '/tmp/x'"), + (MYSQL, " " * 60 + "INSERT INTO users (users.ssn) VALUE (%s"), + (PG, "\n" + " " * 60 + "PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ($1)"), + (PG, "/* a */" * 60 + " PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ($1)"), + ]) + def test_leading_whitespace_and_comments_do_not_backtrack(self, dialect, sql): + assert analyze(sql, dialect, P).gap is not None + + def test_indented_prepare_and_qualified_insert_are_still_read(self): + a = analyze("\n PREPARE p (int) /* c */ AS INSERT INTO users (ssn) VALUES ('x')", PG) + assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] + a = analyze("\n INSERT INTO users (users.ssn) VALUES (%s)", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + # ---- MySQL qualified INSERT columns with dotted back-quoted names ---- + + @pytest.mark.parametrize("sql, expected", [ + ("INSERT INTO users (users.name, `x.ssn`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.x.ssn")]), + ("INSERT INTO users (users.name, `ssn.v2`) VALUES (%s, %s)", [(0, "users.name"), (1, "users.ssn.v2")]), + ("INSERT INTO users (`users`.`ssn`, name) VALUES (%s, %s)", [(0, "users.ssn"), (1, "users.name")]), + ]) + def test_back_quoted_name_with_a_dot_is_one_name(self, sql, expected): + a = analyze(sql, MYSQL, P) + assert a.complete and assigned(a) == expected + + def test_qualifier_retry_only_for_inserts(self, monkeypatch): + calls = [] + real = sql_analyzer._without_insert_column_qualifiers + monkeypatch.setattr(sql_analyzer, "_without_insert_column_qualifiers", + lambda text: calls.append(text) or real(text)) + analyze("UPDATE users SET ssn = %s WHERE (", MYSQL, P) + assert calls == [] + + # ---- keyword fallback ---- + + @pytest.mark.parametrize("dialect, sql", [ + (PG, "SET search_path TO app; PREPARE p AS INSERT INTO users (ssn) VALUES ('123-45-6789')"), + (PG, "EXPLAIN ANALYZE EXECUTE p(%s)"), + (MYSQL, "SELECT 1 /*!LOAD DATA INFILE 'x' INTO TABLE users */"), + ]) + def test_more_statements_that_may_write(self, dialect, sql): + a = analyze(sql, dialect, P) + assert a.writes and a.gap is not None + + # ---- names that are not plain identifiers ---- + + def test_subscripted_update_target_is_unsupported(self): + a = analyze("UPDATE users SET ssn[1] = %s", PG, P) + assert a.writes and a.gap is AnalysisGap.UNSUPPORTED_STATEMENT and a.assignments == () + + # ---- TABLE is not parsed (sqlglot reads it as an alias) ---- + + def test_table_statement_is_not_parsed(self): + a = analyze("TABLE users", PG) + assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () + + # ---- scopes ---- + + def test_nearest_query_memo_does_not_cross_queries(self): + a = analyze("SELECT * FROM users u WHERE EXISTS " + "(SELECT 1 FROM accounts WHERE u.name = %s GROUP BY secret HAVING secret = %s)", PG, P) + assert compared(a) == [(0, "users.name"), (1, "accounts.secret")] + + @pytest.mark.timeout(10) + def test_long_boolean_chain_is_time_bounded(self): + sql = "SELECT ssn FROM users WHERE " + " OR ".join(["(id = %s AND ssn = %s)"] * 12000) + assert len(analyze(sql, PG, P).comparisons) == 24000 + + # ---- caching ---- + + def test_long_sql_with_few_placeholders_is_not_cached(self): + sql = "UPDATE users SET ssn = %s WHERE note = '" + "x" * sql_analyzer.CACHEABLE_SQL_LENGTH + "'" + assert sql.count("%") <= sql_analyzer.CACHEABLE_PERCENT_SIGNS + assert analyze(sql, PG, P) is not analyze(sql, PG, P) + + def test_recursion_error_wrapped_by_the_tokenizer_is_not_cached(self, monkeypatch): + real = sqlglot.parse + calls = [] + + def flaky(sql, read): + calls.append(sql) + if len(calls) == 1: + try: + raise RecursionError("too deep") + except RecursionError as e: + raise sqlglot.errors.TokenError("wrapped") from e + return real(sql, read=read) + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", flaky) + sql = "SELECT a FROM users WHERE ssn = %s" + first = analyze(sql, PG, P) + assert first.gap is AnalysisGap.UNPARSEABLE and first.detail == "RecursionError" + assert analyze(sql, PG, P).gap is None + + # ---- the logging filter is per thread ---- + + def test_quiet_filter_does_not_silence_other_threads(self, caplog): + entered, release = threading.Event(), threading.Event() + + def parse_elsewhere(): + with sql_analyzer._QUIET.active(): + entered.set() + release.wait(5) + + thread = threading.Thread(target=parse_elsewhere) + thread.start() + try: + assert entered.wait(5) + with caplog.at_level(logging.WARNING, logger="sqlglot"): + logging.getLogger("sqlglot").warning("application record") + assert [r.getMessage() for r in caplog.records] == ["application record"] + finally: + release.set() + thread.join() + + +class TestReviewRegressionsRound3: + """Regression tests: regexes that fail after a long gap, and which table a + bare annotation gets.""" + + # ---- regexes that fail after a long run of whitespace or comments ---- + + _BAD_PREPARE = "PREPARE p (int AS INSERT INTO users (ssn) VALUES ($1)" # unbalanced header + _PARTITION = "INSERT INTO users PARTITION (p0) (users.ssn) VALUES (%s)" # valid MySQL neither read can parse + + @pytest.mark.timeout(10) + @pytest.mark.parametrize("dialect, sql, gap", [ + (PG, " " * 60 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "/* a */ " * 60 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- " + "-" * 60 + "\n" + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- " * 60 + "\n" + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "-- header line\r\n" * 40 + _BAD_PREPARE, AnalysisGap.UNSUPPORTED_STATEMENT), + (PG, "PREPARE p" + "-- c\r\n" * 40 + "INSERT INTO users (ssn) VALUES ($1)", AnalysisGap.UNSUPPORTED_STATEMENT), + (MYSQL, " " * 60 + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "/* a */ " * 60 + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- " + "-" * 60 + "\n" + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- " + " -- ".join("abcdefghijklmnopqrstuvwxyz") + "\n" + _PARTITION, AnalysisGap.UNPARSEABLE), + (MYSQL, "-- c \n" * 40 + "INSERT INTO users SET ssn = %s, note = 'a' 'b' garbage(", AnalysisGap.UNPARSEABLE), + ], ids=["pg-spaces", "pg-comments", "pg-dash-banner", "pg-dashes", "pg-crlf", "pg-crlf-header", "my-spaces", + "my-comments", "my-dash-banner", "my-dashed-prose", "my-trailing-space"]) + def test_a_regex_that_fails_after_a_long_gap_fails_fast(self, dialect, sql, gap): + assert analyze(sql, dialect, P).gap is gap + + def test_line_comments_in_a_prepare_header(self): + a = analyze("-- c\r\n PREPARE -- x\r\n p (int) -- y \r\n AS INSERT INTO users (ssn) VALUES ('x')", PG) + assert a.gap is AnalysisGap.PREPARED_PARAMETERS and unbound(a) == ["users.ssn"] + + # ---- bare annotations: written vs compared values ---- + + @pytest.mark.parametrize("dialect, sql, ordinal, expected", [ + # A filter value gets the table it is compared in, even in a statement that writes. + (PG, "UPDATE users SET note = %s WHERE id IN " + "(SELECT user_id FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s)", 1, ColumnRef("pan", "cards")), + (PG, "INSERT INTO audit (note) SELECT note FROM users WHERE coalesce(ssn, '') = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "users")), + (PG, "WITH c AS (SELECT user_id FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s) " + "UPDATE users SET flag = true WHERE id IN (SELECT user_id FROM c)", 0, ColumnRef("pan", "cards")), + # Another statement's write doesn't count. + (MYSQL, "UPDATE a SET x = %s; SELECT * FROM cards WHERE lower(pan) = /*@encrypt:pan*/ %s", + 1, ColumnRef("pan", "cards")), + (MYSQL, "SELECT * FROM users u WHERE u.tax = /*@encrypt:ssn*/ %s; UPDATE audit SET n = n + 1", + 0, ColumnRef("ssn", "users")), + (PG, "INSERT INTO logs (msg) VALUES (%s); SELECT id FROM users WHERE ssn || '' = /*@encrypt:ssn*/ %s", + 1, ColumnRef("ssn", "users")), + # Values that flow into the write: the written table. + (PG, "INSERT INTO users (ssn) SELECT /*@encrypt:ssn*/ %s FROM temp", 0, ColumnRef("ssn", "users")), + (PG, "UPDATE users SET note = (SELECT /*@encrypt:ssn*/ %s FROM temp LIMIT 1)", 0, ColumnRef("ssn", "users")), + # Values bound in a source of the write may feed it or only be compared + # with another table's column: the table can't be told. + (PG, "MERGE INTO users t USING (SELECT /*@encrypt:ssn*/ %s AS v) s ON t.id = 1 " + "WHEN NOT MATCHED THEN INSERT (id, ssn) VALUES (1, s.v)", 0, ColumnRef("ssn")), + (PG, "WITH s AS (SELECT /*@encrypt:ssn*/ %s AS v) INSERT INTO users (ssn) SELECT v FROM s", + 0, ColumnRef("ssn")), + # Several written tables: the table can't be told. + (MYSQL, "UPDATE users u JOIN accounts a ON a.uid = u.id " + "SET u.note = (SELECT /*@encrypt:ssn*/ %s FROM temp), a.x = 1", 0, ColumnRef("ssn")), + ]) + def test_bare_annotation_by_where_the_value_goes(self, dialect, sql, ordinal, expected): + assert analyze(sql, dialect, P).parameter_columns()[ordinal] == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + # A value compared or tested inside a written expression is not written. + (PG, "INSERT INTO audit (note) SELECT CASE WHEN lower(ssn) = /*@encrypt:ssn*/ %s THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) = /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (note) SELECT IF(lower(ssn) = /*@encrypt:ssn*/ %s, 'm', 'n') FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (note) SELECT CASE lower(ssn) WHEN /*@encrypt:ssn*/ %s THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + (PG, "UPDATE users SET flag = (SELECT lower(pan) = /*@encrypt:pan*/ %s FROM cards LIMIT 1)", + ColumnRef("pan", "cards")), + (PG, "UPDATE users SET note = CASE WHEN lower(a.tax) = /*@encrypt:tax*/ %s THEN 'x' END " + "FROM accounts a WHERE a.uid = users.id", ColumnRef("tax")), + # The THEN value is written. + (PG, "UPDATE users SET note = CASE WHEN flag THEN /*@encrypt:ssn*/ %s END", ColumnRef("ssn", "users")), + # A parameter CTE or derived table compared with another table's column. + (PG, "WITH params AS (SELECT /*@encrypt:ssn*/ %s::text AS ssn) UPDATE orders o SET status = 'flagged' " + "FROM customers c, params p WHERE o.customer_id = c.id AND c.ssn = p.ssn", ColumnRef("ssn")), + (PG, "WITH params AS (SELECT /*@encrypt:ssn*/ %s AS ssn) INSERT INTO audit (customer_id) " + "SELECT c.id FROM customers c JOIN params p ON c.ssn = p.ssn", ColumnRef("ssn")), + (MYSQL, "INSERT INTO audit (customer_id) WITH params AS (SELECT /*@encrypt:ssn*/ %s AS ssn) " + "SELECT c.id FROM customers c JOIN params p ON c.ssn = p.ssn", ColumnRef("ssn")), + # A value fed to the write through a source: bare as well. + (PG, "INSERT INTO t (a) SELECT j.v FROM src JOIN (SELECT /*@encrypt:ssn*/ %s AS v) j ON true", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT s.v FROM (SELECT /*@encrypt:ssn*/ %s AS v) s", ColumnRef("ssn")), + ], ids=["case-when", "boolean-item", "mysql-if", "simple-case", "set-subquery-item", "set-case-two-sources", + "case-then", "param-cte-update", "param-cte-insert", "mysql-param-cte", "join-source", "from-source"]) + def test_bare_annotation_on_a_compared_or_source_value(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + @pytest.mark.parametrize("dialect, sql, expected", [ + # THEN, ELSE and IF() results in an INSERT ... SELECT reading another table are written. + (PG, "INSERT INTO audit (note) SELECT CASE WHEN flag THEN /*@encrypt:ssn*/ %s END FROM users", + ColumnRef("ssn", "audit")), + (PG, "INSERT INTO audit (note) SELECT CASE WHEN flag THEN 'a' ELSE /*@encrypt:ssn*/ %s END FROM users", + ColumnRef("ssn", "audit")), + (MYSQL, "INSERT INTO audit (note) SELECT IF(flag, /*@encrypt:ssn*/ %s, 'n') FROM users", + ColumnRef("ssn", "audit")), + # Tests other than the plain comparisons. + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) IN (/*@encrypt:ssn*/ %s) FROM users", ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT lower(ssn) BETWEEN /*@encrypt:ssn*/ %s AND 'z' FROM users", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT ssn ~ /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (flag) SELECT doc @> /*@encrypt:ssn*/ %s::jsonb FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (flag) SELECT ssn REGEXP /*@encrypt:ssn*/ %s FROM users", ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (flag) SELECT MATCH (ssn) AGAINST (/*@encrypt:ssn*/ %s) FROM users", + ColumnRef("ssn", "users")), + # The operand of a simple CASE. + (PG, "INSERT INTO audit (note) SELECT CASE /*@encrypt:ssn*/ %s WHEN lower(ssn) THEN 'm' END FROM users", + ColumnRef("ssn", "users")), + # A window's PARTITION BY is not written. + (PG, "INSERT INTO audit (n) SELECT row_number() OVER (PARTITION BY /*@encrypt:ssn*/ %s) FROM users", + ColumnRef("ssn", "users")), + # Sources that read a table: bare, not that table. + (PG, "INSERT INTO t (a) SELECT j.v FROM src JOIN (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) j ON true", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT s.v FROM (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) s", ColumnRef("ssn")), + (PG, "WITH s AS (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) INSERT INTO users (note) SELECT v FROM s", + ColumnRef("ssn")), + (PG, "MERGE INTO users t USING (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) s ON t.id = 1 " + "WHEN NOT MATCHED THEN INSERT (id, note) VALUES (1, s.v)", ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT l.v FROM src CROSS JOIN LATERAL (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) l", + ColumnRef("ssn")), + (PG, "INSERT INTO t (a) SELECT l.v FROM src, LATERAL (SELECT /*@encrypt:ssn*/ %s AS v FROM cards) l", + ColumnRef("ssn")), + # A SET value in an UPDATE that also reads another table: the assignment is not a test. + (PG, "UPDATE users SET note = /*@encrypt:ssn*/ %s FROM cards c WHERE c.uid = users.id", + ColumnRef("ssn", "users")), + ], ids=["then", "else", "mysql-if-true", "in", "between", "regex", "jsonb-contains", "mysql-regexp", + "mysql-match", "simple-case-operand", "partition-by", "join-source-reads", "from-source-reads", + "cte-reads", "merge-using-reads", "cross-join-lateral-reads", "comma-lateral-reads", "set-with-from"]) + def test_bare_annotation_written_tested_or_from_a_source(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + # A value tested by any of these operators resolves to the table it is tested against on + # every supported sqlglot, though the operators are Predicates only from 30.16. + @pytest.mark.parametrize("op", ["~*", "!~*", "<@", "&&", "?", "?|", "?&", "-|-", "&<", "&>"]) + def test_bare_annotation_tested_by_an_operator(self, op): + sql = f"UPDATE audit SET flag = (SELECT ssn {op} /*@encrypt:ssn*/ %s FROM users LIMIT 1)" + assert analyze(sql, PG, P).parameter_columns()[0] == ColumnRef("ssn", "users") + + def test_bare_annotation_tested_by_overlaps(self): + sql = "UPDATE audit SET flag = (SELECT (d1, ssn) OVERLAPS (d2, /*@encrypt:ssn*/ %s) FROM users LIMIT 1)" + assert analyze(sql, PG, P).parameter_columns()[0] == ColumnRef("ssn", "users") + + # A condition with no test operator around the value (a function sqlglot + # does not model as one): only the slot keeps the value out of the write. + @pytest.mark.parametrize("dialect, sql, expected", [ + (PG, "INSERT INTO audit (uid) SELECT id FROM users WHERE starts_with(ssn, /*@encrypt:ssn*/ %s)", + ColumnRef("ssn", "users")), + (MYSQL, "INSERT INTO audit (uid) SELECT id FROM users WHERE LOCATE(/*@encrypt:ssn*/ %s, ssn)", + ColumnRef("ssn", "users")), + (PG, "INSERT INTO audit (n) SELECT count(*) FROM users GROUP BY note " + "HAVING bool_or(starts_with(ssn, /*@encrypt:ssn*/ %s))", ColumnRef("ssn", "users")), + (PG, "UPDATE users SET flag = true FROM cards c " + "WHERE c.uid = users.id AND starts_with(c.pan, /*@encrypt:pan*/ %s)", ColumnRef("pan")), + (PG, "MERGE INTO users t USING cards c ON t.id = c.uid AND starts_with(c.pan, /*@encrypt:pan*/ %s) " + "WHEN MATCHED THEN UPDATE SET flag = true", ColumnRef("pan")), + (PG, "MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED AND starts_with(c.pan, /*@encrypt:pan*/ %s) THEN UPDATE SET flag = true", ColumnRef("pan")), + ], ids=["where", "mysql-where", "having", "update-from-where", "merge-on", "merge-when-condition"]) + def test_bare_annotation_in_a_condition_slot(self, dialect, sql, expected): + assert analyze(sql, dialect, P).parameter_columns()[0] == expected + + @pytest.mark.parametrize("sql, ordinal, expected", [ + ("INSERT INTO audit (n) SELECT count(*) FROM users GROUP BY note HAVING max(lower(ssn)) = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "users")), + ("MERGE INTO users t USING cards c ON t.id = c.uid AND lower(c.pan) = /*@encrypt:pan*/ %s " + "WHEN MATCHED THEN UPDATE SET flag = true", 0, ColumnRef("pan")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED AND lower(c.pan) = /*@encrypt:pan*/ %s THEN UPDATE SET flag = true", 0, ColumnRef("pan")), + ("UPDATE users SET flag = true FROM cards c WHERE c.uid = users.id AND lower(c.pan) = /*@encrypt:pan*/ %s", + 0, ColumnRef("pan")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN NOT MATCHED THEN INSERT (id, note) VALUES (c.uid, /*@encrypt:ssn*/ %s)", 0, ColumnRef("ssn", "users")), + ("MERGE INTO users t USING cards c ON t.id = c.uid " + "WHEN MATCHED THEN UPDATE SET note = /*@encrypt:ssn*/ %s", 0, ColumnRef("ssn", "users")), + ("INSERT INTO logs (msg) VALUES (%s); UPDATE users SET note = /*@encrypt:ssn*/ %s", 1, ColumnRef("ssn", "users")), + ("INSERT INTO t (a) VALUES (1) ON CONFLICT (a) DO UPDATE SET note = /*@encrypt:ssn*/ %s", + 0, ColumnRef("ssn", "t")), + ], ids=["having", "merge-on", "merge-when-condition", "update-from-where", "merge-when-insert", "merge-when-update", + "two-writes", "on-conflict-set"]) + def test_bare_annotation_slots(self, sql, ordinal, expected): + assert analyze(sql, PG, P).parameter_columns()[ordinal] == expected + + # ---- one-dialect gaps ---- + + def test_replace_with_qualified_columns_is_read(self): + a = analyze("REPLACE INTO users (users.ssn) VALUES (%s)", MYSQL, P) + assert a.complete and assigned(a) == [(0, "users.ssn")] + + @BOTH + def test_table_statement_is_not_parsed_on_either_dialect(self, dialect): + a = analyze("TABLE users", dialect) + assert a.kind is StatementKind.SELECT and not a.writes and a.tables == () + + # ---- a cyclic exception chain ends ---- + + @pytest.mark.timeout(10) + def test_cyclic_exception_chain_does_not_hang(self, monkeypatch): + def cyclic(sql, read): + error = sqlglot.errors.ParseError("x") + error.__cause__ = error + raise error + + monkeypatch.setattr(sql_analyzer.sqlglot, "parse", cyclic) + a = sql_analyzer._analysis("SELECT 1", PG, ParamStyle.NONE) + assert a.gap is AnalysisGap.UNPARSEABLE and a.detail == "ParseError" diff --git a/tests/unit/test_sql_tokenizer.py b/tests/unit/test_sql_tokenizer.py new file mode 100644 index 000000000..032217c2c --- /dev/null +++ b/tests/unit/test_sql_tokenizer.py @@ -0,0 +1,415 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import re +from types import MappingProxyType + +import pytest + +from aws_advanced_python_wrapper.encryption.sql_dialect import MYSQL, PG +from aws_advanced_python_wrapper.encryption.sql_tokenizer import ( + ColumnRef, ParamStyle, normalized_ordinal, tokenize) + +POS, NAMED, NONE = ParamStyle.POSITIONAL, ParamStyle.NAMED, ParamStyle.NONE + + +def keys(tokens): + return [p.key for p in tokens.placeholders] + + +def hidden(tokens): + return [p.hidden for p in tokens.placeholders] + + +class TestParamStyle: + @pytest.mark.parametrize("params, expected", [ + (None, NONE), ((), POS), ([], POS), ((1,), POS), ([1], POS), + ({}, NAMED), ({"a": 1}, NAMED), (MappingProxyType({"a": 1}), NAMED), + ]) + def test_psycopg(self, params, expected): + # psycopg splits the query whenever params is not None, even if empty. + assert ParamStyle.of(params, PG) is expected + + @pytest.mark.parametrize("params, expected", [ + (None, NONE), ((), NONE), ([], NONE), ({}, NONE), ((1,), POS), ([1], POS), ({"a": 1}, NAMED), + # Connector/Python only accepts a dict, list or tuple. + (MappingProxyType({"a": 1}), NONE), ("abc", NONE), + ]) + def test_mysql_connector(self, params, expected): + # Connector/Python substitutes only for a non-empty dict, list or tuple. + assert ParamStyle.of(params, MYSQL) is expected + + +class TestPsycopgPlaceholders: + def test_positional_in_order(self): + t = tokenize("INSERT INTO t (a, b) VALUES (%s, %s)", PG, POS) + assert keys(t) == [0, 1] + assert [p.ordinal for p in t.placeholders] == [0, 1] + + def test_binary_and_text_formats_are_placeholders(self): + assert keys(tokenize("VALUES (%s, %b, %t)", PG, POS)) == [0, 1, 2] + + def test_named_may_repeat(self): + t = tokenize("UPDATE t SET a = %(v)s, b = %(v)s WHERE id = %(id)b", PG, NAMED) + assert keys(t) == ["v", "v", "id"] + assert [p.ordinal for p in t.placeholders] == [0, 1, 2] + + def test_double_percent_is_a_percent_sign(self): + t = tokenize("SELECT 7 %% 2, a FROM t WHERE b LIKE 'x%%' AND c = %s", PG, POS) + assert keys(t) == [0] + assert "7 % 2" in t.normalized and "'x%'" in t.normalized + + def test_placeholders_inside_literals_and_comments_are_still_bound(self): + # psycopg does not skip quotes or comments, so neither may we: the + # second %s is the second parameter even though it's in a string. + sql = "SELECT %s, '%s', \"%s\", $$%s$$, $tag$%s$tag$, E'\\'%s', /* %s */ -- %s\n %s" + t = tokenize(sql, PG, POS) + assert keys(t) == list(range(9)) + assert hidden(t) == [False, True, True, True, True, True, True, True, False] + assert t.has_hidden_placeholders + + def test_nested_block_comments(self): + t = tokenize("/* a /* b */ %s */ SELECT %s", PG, POS) + assert hidden(t) == [True, False] + + @pytest.mark.timeout(10) + def test_deeply_nested_comments_stay_linear(self): + depth = 100_000 + t = tokenize("SELECT /*" + " /*" * depth + " */" * (depth + 1) + " %s", PG, POS) + assert hidden(t) == [False] + + def test_dollar_number_is_not_a_dollar_quote(self): + t = tokenize("SELECT $1, %s", PG, POS) + assert hidden(t) == [False] + + def test_identifier_with_dollar_is_not_a_dollar_quote(self): + t = tokenize("SELECT a$b$, %s", PG, POS) + assert hidden(t) == [False] + + def test_standard_strings_do_not_escape_backslash(self): + # standard_conforming_strings=on: 'a\' is a whole literal. + t = tokenize("SELECT 'a\\', %s", PG, POS) + assert hidden(t) == [False] + + def test_escape_strings_do(self): + t = tokenize("SELECT E'a\\', %s'", PG, POS) + assert hidden(t) == [True] + + def test_doubled_quotes(self): + t = tokenize("SELECT 'it''s', \"a\"\"b\", %s", PG, POS) + assert hidden(t) == [False] + + @pytest.mark.parametrize("sql, rejected", [ + ("SELECT 1 % 2", True), ("SELECT '100%'", True), ("SELECT %d", True), ("SELECT %()s", True), + # A lone % at the very end is not matched by psycopg's pattern either. + ("SELECT %", False), + ]) + def test_driver_rejects_other_percent_sequences(self, sql, rejected): + assert (tokenize(sql, PG, POS).driver_error is not None) is rejected + + @pytest.mark.parametrize("sql, style", [ + ("SELECT '%(card 4111-1111-1111-1111)x', %s", POS), + ("SELECT '4111-1111-1111-1111 %d'", POS), + ("VALUES (%s, %(4111-1111)s)", NAMED), + ]) + def test_driver_error_never_quotes_the_sql(self, sql, style): + error = tokenize(sql, PG, style).driver_error + assert error is not None and "4111" not in error + + def test_percent_before_newline_is_left_alone(self): + # psycopg's pattern does not match a newline after %. + assert tokenize("SELECT 1 %\n2", PG, POS).driver_error is None + + @pytest.mark.parametrize("style", [POS, NAMED]) + def test_mixed_styles_are_a_driver_error(self, style): + assert tokenize("VALUES (%s, %(a)s)", PG, style).driver_error is not None + + @pytest.mark.parametrize("sql, style", [("VALUES (%s)", NAMED), ("VALUES (%(a)s)", POS)]) + def test_style_mismatch_is_a_driver_error(self, sql, style): + assert tokenize(sql, PG, style).driver_error is not None + + def test_no_params_means_no_placeholders(self): + t = tokenize("SELECT '%s', %s, 1 %% 2", PG, NONE) + assert t.placeholders == () + assert t.driver_error is None + assert t.normalized == "SELECT '%s', %s, 1 %% 2" + + def test_spans(self): + sql = "SELECT %(name)s" + p = tokenize(sql, PG, NAMED).placeholders[0] + assert sql[p.start:p.end] == "%(name)s" + + +class TestMySqlPlaceholders: + def test_positional(self): + assert keys(tokenize("INSERT INTO t (a, b) VALUES (%s, %s)", MYSQL, POS)) == [0, 1] + + def test_double_percent_is_not_an_escape(self): + # Connector/Python replaces every "%s" substring, including in "%%s". + t = tokenize("SELECT 5 %% 2, %%s", MYSQL, POS) + assert keys(t) == [0] + assert t.driver_error is None + + def test_any_other_percent_sequence_is_left_alone(self): + t = tokenize("SELECT a FROM t WHERE b LIKE 'x%' AND c = %d AND d = %s", MYSQL, POS) + assert keys(t) == [0] + assert t.driver_error is None + + def test_named_only_with_a_dict(self): + assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, NAMED)) == ["a"] + assert keys(tokenize("VALUES (%(a)s, %s)", MYSQL, POS)) == [0] + + def test_named_percent_conversion_is_a_percent_sign(self): + t = tokenize("SELECT %(a)s, 5 %(x)% 2", MYSQL, NAMED) + assert keys(t) == ["a"] + assert "5 % 2" in t.normalized + + def test_named_other_conversion_is_a_driver_error(self): + error = tokenize("SELECT '%(123-45-6789)d'", MYSQL, NAMED).driver_error + assert error is not None and "123-45" not in error + + def test_no_params_means_no_placeholders(self): + assert tokenize("SELECT %s", MYSQL, NONE).placeholders == () + + def test_placeholders_inside_literals_and_comments_are_still_bound(self): + sql = "SELECT %s, '%s', \"%s\", `%s`, /* %s */, # %s\n -- %s\n %s" + t = tokenize(sql, MYSQL, POS) + assert hidden(t) == [False, True, True, True, True, True, True, False] + + def test_backslash_escapes_in_strings(self): + t = tokenize("SELECT 'a\\'b', \"c\\\"d\", %s", MYSQL, POS) + assert hidden(t) == [False] + + def test_double_dash_needs_whitespace_to_start_a_comment(self): + t = tokenize("SELECT 1--%s", MYSQL, POS) + assert hidden(t) == [False] + assert hidden(tokenize("SELECT 1-- %s", MYSQL, POS)) == [True] + + def test_block_comments_do_not_nest(self): + t = tokenize("/* a /* b */ %s */", MYSQL, POS) + assert hidden(t) == [False] + + @pytest.mark.parametrize("sql, executable", [ + ("SELECT /*!40001 SQL_NO_CACHE */ 1", True), + ("SELECT /*! 1 */", True), + ("SELECT /*M!100000 1 */", True), + ("SELECT /*+ hint */ 1", False), + ("SELECT '/*! x */'", False), + ]) + def test_executable_comments(self, sql, executable): + assert tokenize(sql, MYSQL, NONE).executable_comment is executable + + def test_executable_comment_is_only_a_mysql_notion(self): + assert not tokenize("SELECT /*! 1 */", PG, NONE).executable_comment + + def test_executable_comment_keywords(self): + assert "INSERT" in tokenize("SELECT 1 /*! ; INSERT INTO t VALUES (1) */", MYSQL, NONE).keywords + + @pytest.mark.parametrize("sql, introducers", [ + ("VALUES (_binary %s, _utf8mb4'x', %s)", ["_binary", None]), + ("VALUES (_BINARY %s)", ["_binary"]), + ("VALUES (_x %s, a_binary %s)", [None, None]), + ("VALUES ('_binary' %s)", [None]), + ("VALUES (_binary '%s')", [None]), + ]) + def test_charset_introducers(self, sql, introducers): + t = tokenize(sql, MYSQL, POS) + assert [p.introducer for p in t.placeholders] == introducers + if introducers[0]: + assert "_binary" not in t.normalized.lower() + + def test_introducer_inside_a_comment_is_ignored(self): + t = tokenize("VALUES (-- _binary\n%s)", MYSQL, POS) + assert [p.introducer for p in t.placeholders] == [None] + assert "_binary" in t.normalized + + +class TestLexing: + @pytest.mark.parametrize("dialect, sql", [ + (PG, "SELECT 'abc"), (PG, "SELECT \"abc"), (PG, "SELECT $$abc"), (PG, "SELECT /* /* */"), + (PG, "SELECT 'it''"), (MYSQL, "SELECT 'abc\\'"), (MYSQL, "SELECT `a"), (MYSQL, "SELECT /* a"), + ]) + def test_unterminated(self, dialect, sql): + assert tokenize(sql, dialect, POS).unterminated + + def test_leading_words_per_statement(self): + t = tokenize("/* hint */ insert INTO t VALUES (1); -- c\n (SELECT 1); ; UPDATE t SET a = 1;", PG, NONE) + assert t.leading_words == ("INSERT", "SELECT", "UPDATE") + + def test_semicolon_in_literal_does_not_split(self): + assert tokenize("SELECT ';' ; SELECT 2", PG, NONE).leading_words == ("SELECT", "SELECT") + assert tokenize("SELECT ';'", MYSQL, NONE).leading_words == ("SELECT",) + + def test_keywords_ignore_literals_comments_and_placeholder_names(self): + t = tokenize("SELECT 'INSERT' /* UPDATE */ FROM t WHERE a = %(merge)s", PG, NAMED) + assert t.keywords == {"FROM"} + + def test_type_error_for_non_str(self): + with pytest.raises(TypeError): + tokenize(b"SELECT 1", PG, NONE) # type: ignore[arg-type] + + +class TestNormalized: + def test_placeholders_carry_their_ordinal(self): + t = tokenize("VALUES (%s, %s)", PG, POS) + names = re.findall(r":(\w+)", t.normalized) + assert [normalized_ordinal(n) for n in names] == [0, 1] + + def test_cast_after_placeholder_stays_readable(self): + assert ":_kms_p0 ::bytea" in tokenize("VALUES (%s::bytea)", PG, POS).normalized + + @pytest.mark.parametrize("name, expected", [ + ("_kms_p0", 0), ("_kms_p12", 12), ("_kms_p", None), ("_kms_px", None), ("other", None), (None, None), + ("_kms_pŁ£", None), # a non-ASCII digit + ]) + def test_normalized_ordinal(self, name, expected): + assert normalized_ordinal(name) == expected + + @pytest.mark.parametrize("sql, expected", [ + ("REPLACE INTO t (a) VALUES (%s)", "INSERT INTO t (a) VALUES"), + ("REPLACE LOW_PRIORITY INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("INSERT HIGH_PRIORITY IGNORE INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("INSERT DELAYED INTO t (a) VALUES (%s)", "INSERT INTO t"), + ("UPDATE LOW_PRIORITY IGNORE t SET a = %s", "UPDATE t SET"), + ("DELETE LOW_PRIORITY QUICK IGNORE FROM t WHERE a = %s", "DELETE FROM t"), + ("/* x */ replace t SET a = %s", "/* x */ INSERT t SET"), + ]) + def test_mysql_statement_modifiers_and_replace(self, sql, expected): + assert expected in " ".join(tokenize(sql, MYSQL, POS).normalized.split()) + + def test_replace_function_is_left_alone(self): + t = tokenize("SELECT REPLACE(a, 'x', 'y') FROM t; UPDATE t SET a = REPLACE(a, 'x', %s)", MYSQL, POS) + assert t.normalized.count("REPLACE(") == 2 + + def test_modifier_words_elsewhere_are_left_alone(self): + # QUICK is not reserved and can name a table. + t = tokenize("UPDATE quick SET a = %s", MYSQL, POS) + assert "UPDATE quick" in t.normalized + + def test_postgresql_keeps_modifier_words(self): + assert "UPDATE ignore" in tokenize("UPDATE ignore SET a = %s", PG, POS).normalized + + +class TestAnnotations: + def test_annotation_before_a_placeholder(self): + t = tokenize("INSERT INTO t (a, b) VALUES (%s, /*@encrypt:users.ssn*/ %s)", PG, POS) + assert [p.annotation for p in t.placeholders] == [None, ColumnRef("ssn", "users")] + assert t.stray_annotations == () + + def test_named_placeholder(self): + t = tokenize("UPDATE t SET b = /*@encrypt:ssn*/%(ssn)s", PG, NAMED) + assert t.placeholders[0].annotation == ColumnRef("ssn") + + def test_schema_is_dropped(self): + t = tokenize("VALUES (/*@encrypt:app.users.ssn*/ %s)", PG, POS) + assert t.placeholders[0].annotation == ColumnRef("ssn", "users") + + @pytest.mark.parametrize("ref, expected", [ + # References the shared [\w.]+ grammar allows: empty and extra parts. + (".ssn", ColumnRef("ssn")), + ("t..ssn", ColumnRef("ssn", "t")), + ("a.b.t.ssn", ColumnRef("ssn", "t")), + ("9t.1a", ColumnRef("1a", "9t")), + ]) + def test_empty_and_extra_parts(self, ref, expected): + t = tokenize(f"VALUES (/*@encrypt:{ref}*/ %s)", PG, POS) + assert t.placeholders[0].annotation == expected + + def test_doubled_quote_in_a_quoted_part(self): + t = tokenize('VALUES (/*@encrypt:"a""b".ssn*/ %s)', PG, POS) + assert t.placeholders[0].annotation == ColumnRef("ssn", 'a"b') + + def test_postgresql_folds_unquoted_parts_and_keeps_quoted_ones(self): + t = tokenize('VALUES (/*@encrypt:Users."SSN"*/ %s)', PG, POS) + assert t.placeholders[0].annotation == ColumnRef("SSN", "users") + + def test_mysql_backtick_parts(self): + t = tokenize("VALUES (/*@encrypt:`My Table`.SSN*/ %s)", MYSQL, POS) + assert t.placeholders[0].annotation == ColumnRef("SSN", "My Table") + + @pytest.mark.parametrize("sql", [ + "VALUES (%s /*@encrypt:users.ssn*/)", # after, not before + "VALUES (/*@encrypt:users.ssn*/ 'x', %s)", # not followed by a placeholder + "VALUES (/*@encrypt:users.*/ %s)", # no column + "VALUES (/*@encrypt:users ssn*/ %s)", + "VALUES (/*@encrypt:users.ssn*/ '%s')", # a literal, not a placeholder, follows + ]) + def test_stray_annotations(self, sql): + t = tokenize(sql, PG, POS) + assert all(p.annotation is None for p in t.placeholders) + assert len(t.stray_annotations) == 1 + + def test_annotation_before_a_hidden_placeholder_is_stray(self): + # psycopg reads %("x")s as one placeholder that starts outside a + # quoted identifier and ends inside it. + t = tokenize('VALUES (/*@encrypt:t.a*/ %("x")s)', PG, NAMED) + assert hidden(t) == [True] + assert t.placeholders[0].annotation is None and len(t.stray_annotations) == 1 + + def test_space_after_comment_opener_is_not_an_annotation(self): + t = tokenize("VALUES (/* @encrypt:users.ssn*/ %s)", PG, POS) + assert t.placeholders[0].annotation is None + assert t.stray_annotations == () + + def test_annotation_inside_a_literal_is_text(self): + t = tokenize("VALUES ('/*@encrypt:users.ssn*/', %s)", PG, POS) + assert t.placeholders[0].annotation is None + + +# ---- the drivers themselves as the oracle ---- +# +# These call the drivers' own placeholder scanning, so a driver upgrade that +# changes what it binds fails here rather than silently shifting which value +# the plugin encrypts. + +_ORACLE_SQL = [ + "INSERT INTO t (a, b) VALUES (%s, %s)", + "SELECT %s, '%s', \"%s\" -- %s\n, %s", + "SELECT 7 %% 2, %s, '%%s', /* %s */ %s", + "UPDATE t SET a = %s WHERE b LIKE 'x%%' AND c IN (%s, %s)", + "SELECT $$ %s $$, E'\\'%s', %s", + "SELECT %%s, %s%s", +] + +_NAMED_ORACLE_SQL = [ + "INSERT INTO t (a, b) VALUES (%(a)s, %(b)s)", + "UPDATE t SET a = %(v)s, b = %(v)s WHERE c = '%(w)s' -- %(x)s", + "SELECT %(a)s, 5 %% 2, %(b)s", +] + + +@pytest.mark.parametrize("sql", _ORACLE_SQL + _NAMED_ORACLE_SQL) +def test_matches_psycopg(sql): + queries = pytest.importorskip("psycopg._queries") + named = "%(" in sql + parts = queries._split_query(sql.encode()) + expected = [part.item for part in parts[:-1]] + t = tokenize(sql, PG, NAMED if named else POS) + assert keys(t) == expected + assert t.driver_error is None # psycopg accepted it + + +@pytest.mark.parametrize("sql", _ORACLE_SQL) +def test_matches_mysql_connector_positional(sql): + cursor = pytest.importorskip("mysql.connector.cursor") + expected = list(range(len(cursor.RE_PY_PARAM.findall(sql.encode())))) + assert keys(tokenize(sql, MYSQL, POS)) == expected + + +@pytest.mark.parametrize("sql", _NAMED_ORACLE_SQL) +def test_matches_mysql_connector_named(sql): + cursor = pytest.importorskip("mysql.connector.cursor") + expected = [m.group("mapping_key").decode() for m in cursor.RE_PY_MAPPING_PARAM.finditer(sql.encode()) + if m.group("conversion_type") == b"s"] + assert keys(tokenize(sql, MYSQL, NAMED)) == expected