Skip to content
Merged
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
96 changes: 70 additions & 26 deletions aws_advanced_python_wrapper/encryption/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@
from __future__ import annotations

import math
import os
import re
from dataclasses import dataclass, field
from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Type,
TypeVar)
from dataclasses import dataclass
from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Set,
Type, TypeVar)

from aws_advanced_python_wrapper.errors import EncryptionConfigError
from aws_advanced_python_wrapper.utils.concurrent import ConcurrentSet
from aws_advanced_python_wrapper.utils.log import Logger
from aws_advanced_python_wrapper.utils.messages import Messages
from aws_advanced_python_wrapper.utils.properties import (WrapperProperties,
WrapperProperty)
Expand All @@ -34,6 +35,17 @@
# which rules out quoting, whitespace, comments, and statement separators.
_SCHEMA_NAME_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")

# The region of a KMS key or alias ARN. An alias name (alias/...) or a bare key id names no region.
_KMS_ARN_REGION = re.compile(r"arn:[^:]+:kms:([^:]+):")

logger = Logger(__name__)

# The configuration is built for every connection, so each region mismatch is warned about once.
_warned_region_mismatches: ConcurrentSet[str] = ConcurrentSet()

# The longest name the key management utility puts in its re-encryption SQL; MySQL's limit for most identifiers.
_MAX_IDENTIFIER_LENGTH = 64

T = TypeVar("T", int, float)


Expand All @@ -46,6 +58,10 @@ def validate_schema_name(name: Any) -> str:
return name


def is_valid_identifier(name: Any) -> bool:
return isinstance(name, str) and len(name) <= _MAX_IDENTIFIER_LENGTH and bool(_SCHEMA_NAME_PATTERN.fullmatch(name))


def _normalize_arns(value: Any) -> FrozenSet[str]:
"""Accept ``None``, a comma-separated string, or an iterable of strings."""
if value is None:
Expand All @@ -60,23 +76,26 @@ class EncryptionConfig:
properties. Build it with :meth:`from_props`; the constructor validates."""

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

def __post_init__(self) -> None:
if not self.kms_region or not self.kms_region.strip():
raise EncryptionConfigError(Messages.get("EncryptionConfig.MissingRegion"))
raise EncryptionConfigError(Messages.get_formatted(
"EncryptionConfig.MissingRegion", WrapperProperties.ENCRYPTION_KMS_REGION.name,
WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name))
# Normalize here too, so a directly constructed config gets the same
# exact-match semantics as one built from properties.
object.__setattr__(self, "allowed_master_key_arns", _normalize_arns(self.allowed_master_key_arns))
Expand Down Expand Up @@ -110,16 +129,13 @@ def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = Tr
:raises EncryptionConfigError: if a value is missing or out of range.
"""
wp = WrapperProperties
# A blank value at one level falls through to the next.
region = (_stripped(wp.ENCRYPTION_KMS_REGION.get(props))
or _stripped(os.environ.get("AWS_REGION"))
or _stripped(os.environ.get("AWS_DEFAULT_REGION")))
# Read directly: the value may be a list, which WrapperProperty.get
# (typed Optional[str]) does not model.
allowed_master_key_arns = _normalize_arns(props.get(wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name))
config = cls(
kms_region=region,
kms_region=_kms_region(_stripped(wp.ENCRYPTION_KMS_REGION.get(props)), allowed_master_key_arns),
kms_endpoint=wp.ENCRYPTION_KMS_ENDPOINT.get(props),
# Read directly: the value may be a list, which WrapperProperty.get
# (typed Optional[str]) does not model.
allowed_master_key_arns=_normalize_arns(props.get(wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)),
allowed_master_key_arns=allowed_master_key_arns,
metadata_schema=wp.ENCRYPTION_METADATA_SCHEMA.get(props) or "",
metadata_cache_enabled=wp.ENCRYPTION_METADATA_CACHE_ENABLED.get_bool(props),
metadata_cache_expiration_sec=_number(wp.ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC, props, float),
Expand All @@ -132,6 +148,7 @@ def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = Tr
wp.ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC, props, float),
audit_logging_enabled=wp.ENCRYPTION_AUDIT_LOGGING_ENABLED.get_bool(props),
return_unverified_data=wp.ENCRYPTION_RETURN_UNVERIFIED_DATA.get_bool(props),
fail_on_unmapped_parameter=wp.ENCRYPTION_FAIL_ON_UNMAPPED_PARAMETER.get_bool(props),
)

if require_allowed_master_keys and not config.restricts_master_keys:
Expand Down Expand Up @@ -162,6 +179,29 @@ def _require(condition: bool, prop: WrapperProperty, requirement: str) -> None:
raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.OutOfRange", prop.name, requirement))


def _kms_region(region: str, allowed_master_key_arns: FrozenSet[str]) -> str:
"""``region`` when it is set, else the one region of the KMS key and alias ARNs in the allow-list."""
arn_regions: Set[str] = set()
for arn in allowed_master_key_arns:
match = _KMS_ARN_REGION.match(arn)
if match is not None:
arn_regions.add(match[1])
wp = WrapperProperties
if region:
others = ", ".join(sorted(arn_regions - {region}))
# Reported, not refused: an unused leftover, or a multi-region key's replica listed for a deployment in
# another region, doesn't stop this one from working.
if others and f"{region} {others}" not in _warned_region_mismatches:
_warned_region_mismatches.add(f"{region} {others}")
logger.warning("EncryptionConfig.RegionMismatch", wp.ENCRYPTION_KMS_REGION.name, region,
wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name, others, region)
return region
if len(arn_regions) > 1:
raise EncryptionConfigError(Messages.get_formatted(
"EncryptionConfig.AmbiguousRegion", wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name, wp.ENCRYPTION_KMS_REGION.name))
return next(iter(arn_regions), "")


def _stripped(value: Optional[str]) -> str:
return (value or "").strip()

Expand All @@ -173,6 +213,10 @@ def _finite(value: float) -> bool:
def _number(prop: WrapperProperty, props: Properties, kind: Type[T]) -> T:
"""Read a numeric property, naming it if the value is not a number.
Property values are configuration, not secrets, so chaining is fine."""
value = props.get(prop.name)
# int() drops the fraction, so 1.5 would become 1 without an error.
if kind is int and isinstance(value, float) and not value.is_integer():
raise EncryptionConfigError(Messages.get_formatted("EncryptionConfig.InvalidValue", prop.name, value))
try:
return prop.get_type(props, kind)
except (TypeError, ValueError) as e:
Expand Down
Loading