Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
### :magic_wand: Added
* Synchronous plugins can replace the arguments that `Cursor.execute` and `Cursor.executemany` pass to the plugins after them and to the target driver, without modifying the caller's objects, by assigning new `args` and `kwargs` to the plugin service's `current_call_context`. See [The Call Context](./docs/development-guide/PluginService.md#the-call-context). ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330))
* The `failover` and `failover_v2` plugins currently rewraps all errors to an AwsWrapperError even when the errors do not trigger failover. Set the `preserve_driver_exception_type` configuration parameter to `True` to re-raise the target driver errors as-is for the failover plugins. Failover errors are unaffected and are still raised as `FailoverSuccessError`, `FailoverFailedError` or `TransactionResolutionUnknownError`. This is useful for ORMs to properly classify the errors. ([Issue #1275](https://github.com/aws/aws-advanced-python-wrapper/issues/1275))
* KMS Encryption Plugin (`kms_encryption`), which encrypts the values an application binds for columns configured in the database's encryption metadata before the driver sends them, and decrypts them on read, with each column's data key protected by an AWS KMS master key. Install it with `pip install "aws-advanced-python-wrapper[encryption]"`, and add a database-side trigger to every encrypted column with the trigger SQL that ships in `aws_advanced_python_wrapper/encryption/sql`. The plugin works with the synchronous wrapper only. See [KMS Encryption Plugin](./docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md). ([PR #1331](https://github.com/aws/aws-advanced-python-wrapper/pull/1331))

### :bug: Fixed
* With psycopg's synchronous cursor, a fetch chained onto `cursor.execute()` (`cursor.execute(query).fetchone()`) skipped every plugin, the failover and host monitoring plugins included, because `execute()` returned the driver's cursor. It now returns the wrapper's cursor, so `isinstance(cursor.execute(query), psycopg.Cursor)` is now `False`. ([PR #1330](https://github.com/aws/aws-advanced-python-wrapper/pull/1330))
Expand Down
52 changes: 38 additions & 14 deletions aws_advanced_python_wrapper/driver_dialect_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Callable, Dict, Optional, Protocol, Union
from typing import (TYPE_CHECKING, Any, Callable, Dict, Optional, Protocol,
Union)

if TYPE_CHECKING:
from aws_advanced_python_wrapper.connection_provider import ConnectionProvider
Expand Down Expand Up @@ -75,21 +76,9 @@ def get_dialect(self, conn_func: Callable, props: Properties) -> DriverDialect:
else:
logger.warning("DriverDialectManager.CustomDialectNotSupported")

result: Optional[str]
dialect_code: Optional[str] = WrapperProperties.DRIVER_DIALECT.get(props)
if dialect_code:
result = DriverDialectManager.known_dialects_by_code.get(dialect_code)
if result is None:
raise AwsWrapperError(Messages.get_formatted(
"DriverDialectManager.UnknownDialectCode",
dialect_code))
self._log_dialect(dialect_code, result)
dialect = Utils.initialize_class(result, props)
if dialect is None:
raise AwsWrapperError(Messages.get_formatted(
"DriverDialectManager.InitializationError",
dialect_code))
return dialect
return self._get_dialect_by_code(dialect_code, props)

for key, value in DriverDialectManager.known_dialects_by_code.items():
dialect = Utils.initialize_class(value, props)
Expand All @@ -100,6 +89,41 @@ def get_dialect(self, conn_func: Callable, props: Properties) -> DriverDialect:
self._log_dialect(DriverDialectCodes.GENERIC, "generic")
return DriverDialect(props)

def get_dialect_for_connection(self, conn: Any, props: Properties) -> Optional[DriverDialect]:
"""
Returns the driver dialect for a connection that the wrapper didn't open.
It doesn't use a custom dialect, because that dialect keeps its own properties and ``props`` can't bound its statements.
:param conn: the driver connection, or an object that holds one.
:param props: the properties; their ``wrapper_driver_dialect`` code always wins over detection.
:return: the dialect of the ``wrapper_driver_dialect`` code, else the first known dialect that finds
a connection in ``conn``, or None.
"""
dialect_code: Optional[str] = WrapperProperties.DRIVER_DIALECT.get(props)
if dialect_code:
return self._get_dialect_by_code(dialect_code, props)

for key, value in DriverDialectManager.known_dialects_by_code.items():
dialect = Utils.initialize_class(value, props)
if dialect is not None and dialect.get_connection_from_obj(conn) is not None:
self._log_dialect(key, value)
return dialect
return None

def _get_dialect_by_code(self, dialect_code: str, props: Properties) -> DriverDialect:
result = DriverDialectManager.known_dialects_by_code.get(dialect_code)
if result is None:
raise AwsWrapperError(Messages.get_formatted(
"DriverDialectManager.UnknownDialectCode",
dialect_code))
self._log_dialect(dialect_code, result)
dialect = Utils.initialize_class(result, props)
if dialect is None:
raise AwsWrapperError(Messages.get_formatted(
"DriverDialectManager.InitializationError",
dialect_code))
return dialect

@staticmethod
def _log_dialect(dialect_code: str, driver_dialect: Union[DriverDialect, str]):
logger.debug(
Expand Down
4 changes: 2 additions & 2 deletions aws_advanced_python_wrapper/encryption/buffers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@

from __future__ import annotations

from typing import Any, Union
from typing import Union

BytesLike = Union[bytes, bytearray, memoryview]


def wipe(buffer: Any) -> None:
def wipe(buffer: bytearray) -> None:
"""Overwrite a mutable ``bytearray`` with zeros, in place. Best effort:
immutable ``bytes`` cannot be zeroed, so hold key material in
``bytearray`` where wiping matters. CPython may still leave copies
Expand Down
34 changes: 20 additions & 14 deletions aws_advanced_python_wrapper/encryption/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import math
import os
import re
from dataclasses import dataclass, field
from dataclasses import dataclass
from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Type,
TypeVar)

Expand Down Expand Up @@ -60,19 +60,20 @@ class EncryptionConfig:
properties. Build it with :meth:`from_props`; the constructor validates."""

kms_region: str
allowed_master_key_arns: FrozenSet[str] = field(default_factory=frozenset)
kms_endpoint: Optional[str] = None
metadata_schema: str = "encrypt"
metadata_cache_enabled: bool = True
metadata_cache_expiration_sec: float = 3600.0
metadata_cache_refresh_interval_sec: float = 300.0
data_key_cache_enabled: bool = True
data_key_cache_max_size: int = 1000
data_key_cache_expiration_sec: float = 300.0
key_management_max_retries: int = 3
key_management_retry_backoff_base_sec: float = 0.1
audit_logging_enabled: bool = False
return_unverified_data: bool = False
allowed_master_key_arns: FrozenSet[str]
kms_endpoint: Optional[str]
metadata_schema: str
metadata_cache_enabled: bool
metadata_cache_expiration_sec: float
metadata_cache_refresh_interval_sec: float
data_key_cache_enabled: bool
data_key_cache_max_size: int
data_key_cache_expiration_sec: float
key_management_max_retries: int
key_management_retry_backoff_base_sec: float
audit_logging_enabled: bool
return_unverified_data: bool
fail_on_unmapped_parameter: bool = True

def __post_init__(self) -> None:
if not self.kms_region or not self.kms_region.strip():
Expand Down Expand Up @@ -132,6 +133,7 @@ def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = Tr
wp.ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC, props, float),
audit_logging_enabled=wp.ENCRYPTION_AUDIT_LOGGING_ENABLED.get_bool(props),
return_unverified_data=wp.ENCRYPTION_RETURN_UNVERIFIED_DATA.get_bool(props),
fail_on_unmapped_parameter=wp.ENCRYPTION_FAIL_ON_UNMAPPED_PARAMETER.get_bool(props),
)

if require_allowed_master_keys and not config.restricts_master_keys:
Expand Down Expand Up @@ -173,6 +175,10 @@ def _finite(value: float) -> bool:
def _number(prop: WrapperProperty, props: Properties, kind: Type[T]) -> T:
"""Read a numeric property, naming it if the value is not a number.
Property values are configuration, not secrets, so chaining is fine."""
value = props.get(prop.name)
# int() drops the fraction, so 1.5 would become 1 without an error.
if kind is int and isinstance(value, float) and not value.is_integer():
raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.InvalidValue", prop.name, value))
try:
return prop.get_type(props, kind)
except (TypeError, ValueError) as e:
Expand Down
74 changes: 66 additions & 8 deletions aws_advanced_python_wrapper/encryption/connection_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,24 @@
# See the License for the specific language governing permissions and
# limitations under the License.

"""Where the key and metadata layer gets a connection to run its SQL on."""
"""How the key and metadata layer gets a connection and runs its SQL through the driver dialect."""

from __future__ import annotations

from contextlib import contextmanager
from contextlib import closing, contextmanager
from threading import local
from typing import (TYPE_CHECKING, Any, ContextManager, Iterator, Optional,
Protocol)
from typing import (TYPE_CHECKING, Any, ContextManager, Dict, Iterator, List,
Mapping, Optional, Protocol, Sequence, cast)

from aws_advanced_python_wrapper.pep249_methods import DbApiMethod
from aws_advanced_python_wrapper.utils.decorators import \
is_connection_abandoned
from aws_advanced_python_wrapper.utils.properties import Properties
from aws_advanced_python_wrapper.utils.retry_util import RetryUtil

if TYPE_CHECKING:
from aws_advanced_python_wrapper.driver_dialect import DriverDialect
from aws_advanced_python_wrapper.pep249 import Connection
from aws_advanced_python_wrapper.plugin import Plugin
from aws_advanced_python_wrapper.plugin_service import PluginService

Expand Down Expand Up @@ -72,8 +77,9 @@ def statement(self) -> Iterator[None]:

The connection opens at the first lookup inside the scope and closes when
the outermost scope ends, also when a lookup fails, so a statement uses at
most one short-lived connection. A scope that looks nothing up opens
nothing.
most one short-lived connection. A connection that a timed-out statement
still runs on stays open, and that statement's worker frees it when it
finishes. A scope that looks nothing up opens nothing.
"""
depth = getattr(self._scope, "depth", 0)
self._scope.depth = depth + 1
Expand All @@ -85,7 +91,9 @@ def statement(self) -> Iterator[None]:
self._scope.depth = depth
if depth == 0:
conn, self._scope.conn = self._scope.conn, None
if conn is not None:
# A statement that timed out can leave its worker on the connection; closing it then would crash the
# process, so the worker frees it when it finishes.
if conn is not None and not is_connection_abandoned(conn):
RetryUtil.close_connection(self._plugin_service, conn)

@contextmanager
Expand All @@ -99,7 +107,10 @@ def connection(self) -> Iterator[Any]:
try:
yield conn
finally:
RetryUtil.close_connection(self._plugin_service, conn)
# A statement that timed out can leave its worker on the connection; closing it then would crash the
# process, so the worker frees it when it finishes.
if not is_connection_abandoned(conn):
RetryUtil.close_connection(self._plugin_service, conn)

def _open(self) -> Any:
service = self._plugin_service
Expand All @@ -111,3 +122,50 @@ def _open(self) -> Any:
RetryUtil.close_connection(service, conn)
raise
return conn


def fetch_rows(dialect: DriverDialect, conn: Connection, sql: str, params: Sequence[Any] = ()) -> List[Dict[str, Any]]:
"""
Runs a query and returns its rows as dicts keyed by the lower-cased column name.
MySQL reports ``information_schema`` names in upper case on some versions, so callers never depend on the case
of a result key.
Rows can come back as tuples or, on a connection opened with a dict-like row factory (for example psycopg's
``row_factory=dict_row``), as mappings; both are handled.
Each cursor call runs through the dialect's :meth:`DriverDialect.execute`, so the ``socket_timeout`` of the
dialect's properties applies, and a timeout raises ``QueryTimeoutError``.

:param dialect: the driver dialect whose ``execute`` runs each cursor call.
:param conn: the connection to run the query on.
:param sql: the query.
:param params: the query's parameters.
:return: the rows, each a dict keyed by the lower-cased column name.
"""
with closing(conn.cursor()) as cursor:
dialect.execute(DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(sql, params), sql, conn=conn)
if cursor.description is None:
return []
names = [_lower(d[0]) for d in cursor.description]
rows = cast("List[Any]", dialect.execute(DbApiMethod.CURSOR_FETCHALL.method_name, lambda: cursor.fetchall(), conn=conn))
return [{_lower(k): v for k, v in row.items()} if isinstance(row, Mapping) else dict(zip(names, row))
for row in rows]


def _lower(name: Any) -> Any:
return name.lower() if isinstance(name, str) else name


def run_statement(dialect: DriverDialect, conn: Connection, sql: str, params: Sequence[Any] = ()) -> int:
"""
Runs a statement and returns the number of rows it affected.
The cursor call runs through the dialect's :meth:`DriverDialect.execute`, so the ``socket_timeout`` of the
dialect's properties applies, and a timeout raises ``QueryTimeoutError``.

:param dialect: the driver dialect whose ``execute`` runs each cursor call.
:param conn: the connection to run the statement on.
:param sql: the statement.
:param params: the statement's parameters.
:return: the number of rows the statement affected, 0 when the driver doesn't report it.
"""
with closing(conn.cursor()) as cursor:
dialect.execute(DbApiMethod.CURSOR_EXECUTE.method_name, lambda: cursor.execute(sql, params), sql, conn=conn)
return max(cursor.rowcount, 0)
Loading