Skip to content

Commit 5ee042f

Browse files
JuanLeeekarenc-bq
andauthored
feat: kms encryption plugin (#1331)
Co-authored-by: Karen [C] Chen <64801825+karenc-bq@users.noreply.github.com>
1 parent aaed53d commit 5ee042f

58 files changed

Lines changed: 11648 additions & 1400 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
88
### :magic_wand: Added
99
* 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))
1010
* 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))
11+
* 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))
1112

1213
### :bug: Fixed
1314
* 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))

‎aws_advanced_python_wrapper/driver_dialect_manager.py‎

Lines changed: 38 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515
from __future__ import annotations
1616

17-
from typing import TYPE_CHECKING, Callable, Dict, Optional, Protocol, Union
17+
from typing import (TYPE_CHECKING, Any, Callable, Dict, Optional, Protocol,
18+
Union)
1819

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

78-
result: Optional[str]
7979
dialect_code: Optional[str] = WrapperProperties.DRIVER_DIALECT.get(props)
8080
if dialect_code:
81-
result = DriverDialectManager.known_dialects_by_code.get(dialect_code)
82-
if result is None:
83-
raise AwsWrapperError(Messages.get_formatted(
84-
"DriverDialectManager.UnknownDialectCode",
85-
dialect_code))
86-
self._log_dialect(dialect_code, result)
87-
dialect = Utils.initialize_class(result, props)
88-
if dialect is None:
89-
raise AwsWrapperError(Messages.get_formatted(
90-
"DriverDialectManager.InitializationError",
91-
dialect_code))
92-
return dialect
81+
return self._get_dialect_by_code(dialect_code, props)
9382

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

92+
def get_dialect_for_connection(self, conn: Any, props: Properties) -> Optional[DriverDialect]:
93+
"""
94+
Returns the driver dialect for a connection that the wrapper didn't open.
95+
It doesn't use a custom dialect, because that dialect keeps its own properties and ``props`` can't bound its statements.
96+
97+
:param conn: the driver connection, or an object that holds one.
98+
:param props: the properties; their ``wrapper_driver_dialect`` code always wins over detection.
99+
:return: the dialect of the ``wrapper_driver_dialect`` code, else the first known dialect that finds
100+
a connection in ``conn``, or None.
101+
"""
102+
dialect_code: Optional[str] = WrapperProperties.DRIVER_DIALECT.get(props)
103+
if dialect_code:
104+
return self._get_dialect_by_code(dialect_code, props)
105+
106+
for key, value in DriverDialectManager.known_dialects_by_code.items():
107+
dialect = Utils.initialize_class(value, props)
108+
if dialect is not None and dialect.get_connection_from_obj(conn) is not None:
109+
self._log_dialect(key, value)
110+
return dialect
111+
return None
112+
113+
def _get_dialect_by_code(self, dialect_code: str, props: Properties) -> DriverDialect:
114+
result = DriverDialectManager.known_dialects_by_code.get(dialect_code)
115+
if result is None:
116+
raise AwsWrapperError(Messages.get_formatted(
117+
"DriverDialectManager.UnknownDialectCode",
118+
dialect_code))
119+
self._log_dialect(dialect_code, result)
120+
dialect = Utils.initialize_class(result, props)
121+
if dialect is None:
122+
raise AwsWrapperError(Messages.get_formatted(
123+
"DriverDialectManager.InitializationError",
124+
dialect_code))
125+
return dialect
126+
103127
@staticmethod
104128
def _log_dialect(dialect_code: str, driver_dialect: Union[DriverDialect, str]):
105129
logger.debug(

‎aws_advanced_python_wrapper/encryption/buffers.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@
2020

2121
from __future__ import annotations
2222

23-
from typing import Any, Union
23+
from typing import Union
2424

2525
BytesLike = Union[bytes, bytearray, memoryview]
2626

2727

28-
def wipe(buffer: Any) -> None:
28+
def wipe(buffer: bytearray) -> None:
2929
"""Overwrite a mutable ``bytearray`` with zeros, in place. Best effort:
3030
immutable ``bytes`` cannot be zeroed, so hold key material in
3131
``bytearray`` where wiping matters. CPython may still leave copies

‎aws_advanced_python_wrapper/encryption/config.py‎

Lines changed: 70 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,14 @@
1515
from __future__ import annotations
1616

1717
import math
18-
import os
1918
import re
20-
from dataclasses import dataclass, field
21-
from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Type,
22-
TypeVar)
19+
from dataclasses import dataclass
20+
from typing import (TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Set,
21+
Type, TypeVar)
2322

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

38+
# The region of a KMS key or alias ARN. An alias name (alias/...) or a bare key id names no region.
39+
_KMS_ARN_REGION = re.compile(r"arn:[^:]+:kms:([^:]+):")
40+
41+
logger = Logger(__name__)
42+
43+
# The configuration is built for every connection, so each region mismatch is warned about once.
44+
_warned_region_mismatches: ConcurrentSet[str] = ConcurrentSet()
45+
46+
# The longest name the key management utility puts in its re-encryption SQL; MySQL's limit for most identifiers.
47+
_MAX_IDENTIFIER_LENGTH = 64
48+
3749
T = TypeVar("T", int, float)
3850

3951

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

4860

61+
def is_valid_identifier(name: Any) -> bool:
62+
return isinstance(name, str) and len(name) <= _MAX_IDENTIFIER_LENGTH and bool(_SCHEMA_NAME_PATTERN.fullmatch(name))
63+
64+
4965
def _normalize_arns(value: Any) -> FrozenSet[str]:
5066
"""Accept ``None``, a comma-separated string, or an iterable of strings."""
5167
if value is None:
@@ -60,23 +76,26 @@ class EncryptionConfig:
6076
properties. Build it with :meth:`from_props`; the constructor validates."""
6177

6278
kms_region: str
63-
allowed_master_key_arns: FrozenSet[str] = field(default_factory=frozenset)
64-
kms_endpoint: Optional[str] = None
65-
metadata_schema: str = "encrypt"
66-
metadata_cache_enabled: bool = True
67-
metadata_cache_expiration_sec: float = 3600.0
68-
metadata_cache_refresh_interval_sec: float = 300.0
69-
data_key_cache_enabled: bool = True
70-
data_key_cache_max_size: int = 1000
71-
data_key_cache_expiration_sec: float = 300.0
72-
key_management_max_retries: int = 3
73-
key_management_retry_backoff_base_sec: float = 0.1
74-
audit_logging_enabled: bool = False
75-
return_unverified_data: bool = False
79+
allowed_master_key_arns: FrozenSet[str]
80+
kms_endpoint: Optional[str]
81+
metadata_schema: str
82+
metadata_cache_enabled: bool
83+
metadata_cache_expiration_sec: float
84+
metadata_cache_refresh_interval_sec: float
85+
data_key_cache_enabled: bool
86+
data_key_cache_max_size: int
87+
data_key_cache_expiration_sec: float
88+
key_management_max_retries: int
89+
key_management_retry_backoff_base_sec: float
90+
audit_logging_enabled: bool
91+
return_unverified_data: bool
92+
fail_on_unmapped_parameter: bool = True
7693

7794
def __post_init__(self) -> None:
7895
if not self.kms_region or not self.kms_region.strip():
79-
raise EncryptionConfigError(Messages.get("EncryptionConfig.MissingRegion"))
96+
raise EncryptionConfigError(Messages.get_formatted(
97+
"EncryptionConfig.MissingRegion", WrapperProperties.ENCRYPTION_KMS_REGION.name,
98+
WrapperProperties.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name))
8099
# Normalize here too, so a directly constructed config gets the same
81100
# exact-match semantics as one built from properties.
82101
object.__setattr__(self, "allowed_master_key_arns", _normalize_arns(self.allowed_master_key_arns))
@@ -110,16 +129,13 @@ def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = Tr
110129
:raises EncryptionConfigError: if a value is missing or out of range.
111130
"""
112131
wp = WrapperProperties
113-
# A blank value at one level falls through to the next.
114-
region = (_stripped(wp.ENCRYPTION_KMS_REGION.get(props))
115-
or _stripped(os.environ.get("AWS_REGION"))
116-
or _stripped(os.environ.get("AWS_DEFAULT_REGION")))
132+
# Read directly: the value may be a list, which WrapperProperty.get
133+
# (typed Optional[str]) does not model.
134+
allowed_master_key_arns = _normalize_arns(props.get(wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name))
117135
config = cls(
118-
kms_region=region,
136+
kms_region=_kms_region(_stripped(wp.ENCRYPTION_KMS_REGION.get(props)), allowed_master_key_arns),
119137
kms_endpoint=wp.ENCRYPTION_KMS_ENDPOINT.get(props),
120-
# Read directly: the value may be a list, which WrapperProperty.get
121-
# (typed Optional[str]) does not model.
122-
allowed_master_key_arns=_normalize_arns(props.get(wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name)),
138+
allowed_master_key_arns=allowed_master_key_arns,
123139
metadata_schema=wp.ENCRYPTION_METADATA_SCHEMA.get(props) or "",
124140
metadata_cache_enabled=wp.ENCRYPTION_METADATA_CACHE_ENABLED.get_bool(props),
125141
metadata_cache_expiration_sec=_number(wp.ENCRYPTION_METADATA_CACHE_EXPIRATION_SEC, props, float),
@@ -132,6 +148,7 @@ def from_props(cls, props: Properties, *, require_allowed_master_keys: bool = Tr
132148
wp.ENCRYPTION_KEY_MANAGEMENT_RETRY_BACKOFF_BASE_SEC, props, float),
133149
audit_logging_enabled=wp.ENCRYPTION_AUDIT_LOGGING_ENABLED.get_bool(props),
134150
return_unverified_data=wp.ENCRYPTION_RETURN_UNVERIFIED_DATA.get_bool(props),
151+
fail_on_unmapped_parameter=wp.ENCRYPTION_FAIL_ON_UNMAPPED_PARAMETER.get_bool(props),
135152
)
136153

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

164181

182+
def _kms_region(region: str, allowed_master_key_arns: FrozenSet[str]) -> str:
183+
"""``region`` when it is set, else the one region of the KMS key and alias ARNs in the allow-list."""
184+
arn_regions: Set[str] = set()
185+
for arn in allowed_master_key_arns:
186+
match = _KMS_ARN_REGION.match(arn)
187+
if match is not None:
188+
arn_regions.add(match[1])
189+
wp = WrapperProperties
190+
if region:
191+
others = ", ".join(sorted(arn_regions - {region}))
192+
# Reported, not refused: an unused leftover, or a multi-region key's replica listed for a deployment in
193+
# another region, doesn't stop this one from working.
194+
if others and f"{region} {others}" not in _warned_region_mismatches:
195+
_warned_region_mismatches.add(f"{region} {others}")
196+
logger.warning("EncryptionConfig.RegionMismatch", wp.ENCRYPTION_KMS_REGION.name, region,
197+
wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name, others, region)
198+
return region
199+
if len(arn_regions) > 1:
200+
raise EncryptionConfigError(Messages.get_formatted(
201+
"EncryptionConfig.AmbiguousRegion", wp.ENCRYPTION_ALLOWED_MASTER_KEY_ARNS.name, wp.ENCRYPTION_KMS_REGION.name))
202+
return next(iter(arn_regions), "")
203+
204+
165205
def _stripped(value: Optional[str]) -> str:
166206
return (value or "").strip()
167207

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

0 commit comments

Comments
 (0)