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
264 changes: 264 additions & 0 deletions .github/workflows/kms_encryption_integration_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
name: KMS Encryption Integration Tests

# The LocalStack job needs no AWS account and no secrets, so it also runs on pull requests from forks.
# The real-key and Aurora jobs read the key ARN, its region and the roles from repository variables,
# which an administrator sets up once; CI never creates or changes KMS keys.
# On a push to main they run only when the variables they need are set, so main stays green until then;
# a manual run of either fails when KMS_KEY_ARN is missing.

on:
pull_request:
paths:
- 'aws_advanced_python_wrapper/**'
- 'tests/integration/**'
- 'pyproject.toml'
- 'poetry.lock'
- '.github/workflows/kms_encryption_integration_tests.yml'
push:
branches: [ main ]
paths:
- 'aws_advanced_python_wrapper/**'
- 'tests/integration/**'
- 'pyproject.toml'
- 'poetry.lock'
- '.github/workflows/kms_encryption_integration_tests.yml'
workflow_dispatch:
inputs:
lane:
description: 'Which KMS environment to run'
type: choice
options: [ localstack, real-kms, aurora ]
default: localstack

permissions:
contents: read

concurrency:
# Each push has its own group, so a long Aurora job never holds back or cancels a later push's other jobs.
group: ${{ github.workflow }}-${{ github.ref }}-${{ inputs.lane }}-${{ github.event_name == 'push' && github.sha || '' }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
kms-localstack:
name: Run KMS Encryption Tests with LocalStack
if: github.event_name != 'workflow_dispatch' || inputs.lane == 'localstack'
runs-on: ubuntu-latest
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
include:
- { engine: pg, skip: mysql }
- { engine: mysql, skip: pg }

steps:
- name: 'Clone repository'
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6

- name: 'Set up JDK 8'
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5
with:
distribution: 'corretto'
java-version: 8

- name: 'Set up Python 3.12'
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: '3.12'

- name: Install poetry
shell: bash
run: |
pipx install poetry==1.8.2
poetry config virtualenvs.prefer-active-python true

- name: Install dependencies
run: poetry install

- name: 'Run the KMS tests on Docker with LocalStack'
run: |
DB_PASSWORD="$(openssl rand -hex 16)"
echo "::add-mask::${DB_PASSWORD}"
export DB_PASSWORD DB_USERNAME=test_user DB_DATABASE_NAME=test_db
./gradlew --no-parallel --no-daemon test-kms-encryption-docker \
-Dexclude-${{ matrix.skip }}-engine=true -Dexclude-${{ matrix.skip }}-driver=true

# pytest exits 0 when every test is skipped, so count the KMS test cases that ran.
- name: 'Fail when no KMS test ran'
run: |
python3 -c 'import glob,sys,xml.etree.ElementTree as E; c=[t for f in glob.glob("tests/integration/container/reports/*.xml") for t in E.parse(f).iter("testcase") if "kms_encryption" in t.get("classname","") and t.find("skipped") is None]; print("KMS tests run:", len(c)); sys.exit(0 if c else 1)'

- name: 'Archive results'
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: kms-localstack-${{ matrix.engine }}
path: ./tests/integration/container/reports
retention-days: 5

kms-real-key:
name: Run KMS Encryption Tests with a real KMS key
if: >-
(github.event_name == 'push' && github.ref == 'refs/heads/main'
&& vars.KMS_KEY_ARN != '' && vars.KMS_REGION != '' && vars.KMS_DECRYPT_ONLY_ROLE_ARN != '' && vars.KMS_IT_ROLE_ARN != '')
|| inputs.lane == 'real-kms'
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
strategy:
fail-fast: false
matrix:
include:
- { engine: pg, skip: mysql }
- { engine: mysql, skip: pg }

steps:
- name: 'Clone repository'
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6

- name: 'Set up JDK 8'
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5
with:
distribution: 'corretto'
java-version: 8

- name: 'Set up Python 3.12'
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: '3.12'

- name: Install poetry
shell: bash
run: |
pipx install poetry==1.8.2
poetry config virtualenvs.prefer-active-python true

- name: Install dependencies
run: poetry install

- name: 'Configure AWS Credentials'
uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6
with:
role-to-assume: ${{ vars.KMS_IT_ROLE_ARN }}
role-session-name: python_kms_integration_tests
role-duration-seconds: 3600
aws-region: ${{ vars.KMS_REGION }}

- name: 'Run the KMS tests on Docker with a real KMS key'
run: |
test -n "${KMS_KEY_ARN}" || { echo "::error::Set the KMS_KEY_ARN repository variable: CI uses the administrator's key and never makes one."; exit 1; }
DB_PASSWORD="$(openssl rand -hex 16)"
echo "::add-mask::${DB_PASSWORD}"
export DB_PASSWORD DB_USERNAME=test_user DB_DATABASE_NAME=test_db
./gradlew --no-parallel --no-daemon test-kms-encryption-docker-kms \
-Dexclude-${{ matrix.skip }}-engine=true -Dexclude-${{ matrix.skip }}-driver=true
env:
KMS_KEY_ARN: ${{ vars.KMS_KEY_ARN }}
KMS_REGION: ${{ vars.KMS_REGION }}
KMS_DECRYPT_ONLY_ROLE_ARN: ${{ vars.KMS_DECRYPT_ONLY_ROLE_ARN }}

- name: 'Fail when no KMS test ran'
run: |
python3 -c 'import glob,sys,xml.etree.ElementTree as E; c=[t for f in glob.glob("tests/integration/container/reports/*.xml") for t in E.parse(f).iter("testcase") if "kms_encryption" in t.get("classname","") and t.find("skipped") is None]; print("KMS tests run:", len(c)); sys.exit(0 if c else 1)'

- name: 'Archive results'
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: kms-real-key-${{ matrix.engine }}
path: ./tests/integration/container/reports
retention-days: 5

kms-aurora:
name: Run KMS Encryption Tests on Aurora
if: >-
(github.event_name == 'push' && github.ref == 'refs/heads/main' && vars.KMS_KEY_ARN != '' && vars.KMS_REGION != '')
|| inputs.lane == 'aurora'
runs-on: ubuntu-latest
timeout-minutes: 150
permissions:
id-token: write # This is required for requesting the JWT
contents: read # This is required for actions/checkout
strategy:
fail-fast: false
matrix:
include:
- { engine: pg, skip: mysql }
- { engine: mysql, skip: pg }
concurrency:
group: kms-aurora-${{ matrix.engine }}
cancel-in-progress: false
env:
# The harness doesn't delete its cluster when a run is cancelled, so the last step deletes this one by name.
RDS_DB_NAME: kms-it-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.engine }}

steps:
- name: 'Clone repository'
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6

- name: 'Set up JDK 8'
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5
with:
distribution: 'corretto'
java-version: 8

- name: 'Set up Python 3.12'
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: '3.12'

- name: Install poetry
shell: bash
run: |
pipx install poetry==1.8.2
poetry config virtualenvs.prefer-active-python true

- name: Install dependencies
run: poetry install

- name: 'Configure AWS Credentials'
uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/${{ secrets.AWS_DEPLOY_ROLE }}
role-session-name: python_integration_tests
role-duration-seconds: 21600
aws-region: ${{ secrets.AWS_DEFAULT_REGION }}

- name: 'Run the KMS tests on Aurora'
run: |
test -n "${KMS_KEY_ARN}" || { echo "::error::Set the KMS_KEY_ARN repository variable: CI uses the administrator's key and never makes one."; exit 1; }
DB_PASSWORD="$(openssl rand -hex 16)"
echo "::add-mask::${DB_PASSWORD}"
export DB_PASSWORD DB_USERNAME=test_user DB_DATABASE_NAME=test_db
./gradlew --no-parallel --no-daemon test-kms-encryption-aurora \
-Dexclude-${{ matrix.skip }}-engine=true -Dexclude-${{ matrix.skip }}-driver=true
env:
NUM_INSTANCES: 2
RDS_DB_REGION: ${{ secrets.AWS_DEFAULT_REGION }}
KMS_KEY_ARN: ${{ vars.KMS_KEY_ARN }}
KMS_REGION: ${{ vars.KMS_REGION }}

- name: 'Fail when no KMS test ran'
run: |
python3 -c 'import glob,sys,xml.etree.ElementTree as E; c=[t for f in glob.glob("tests/integration/container/reports/*.xml") for t in E.parse(f).iter("testcase") if "kms_encryption" in t.get("classname","") and t.find("skipped") is None]; print("KMS tests run:", len(c)); sys.exit(0 if c else 1)'

- name: 'Archive results'
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: kms-aurora-${{ matrix.engine }}
path: ./tests/integration/container/reports
retention-days: 5

# Deletes the cluster named RDS_DB_NAME and its member instances, never clusters matched by a name prefix.
- name: 'Delete the cluster of this run'
if: always()
run: |
instances="$(aws rds describe-db-clusters --db-cluster-identifier "${RDS_DB_NAME}" \
--query 'DBClusters[0].DBClusterMembers[].DBInstanceIdentifier' --output text 2>/dev/null)" || exit 0
for instance in ${instances}; do
aws rds delete-db-instance --db-instance-identifier "${instance}" --skip-final-snapshot > /dev/null || true
done
aws rds delete-db-cluster --db-cluster-identifier "${RDS_DB_NAME}" --skip-final-snapshot > /dev/null || true
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

### :magic_wand: Added
* The `connection_lifetime` plugin, bounding how long a physical connection is used. Once `connection_lifetime_ms` has elapsed, the next network-bound call either closes the connection or reconnects through the host the application originally supplied, depending on `connection_lifetime_action`. Expiration is deferred while a transaction is open, and reports through `ConnectionLifetimeSuccessError`, `ConnectionLifetimeExpiredError` or `ConnectionLifetimeFailedError` so a connection pool can tell a usable connection from a dead one. With an internal connection pool, the plugin evicts an expired connection so the pool closes it instead of handing it out again. Available in both the synchronous and asynchronous wrapper. See [Connection Lifetime Plugin](./docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md).
* 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))
* `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
Expand Down
4 changes: 3 additions & 1 deletion aws_advanced_python_wrapper/driver_dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
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
13 changes: 13 additions & 0 deletions aws_advanced_python_wrapper/encryption/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
Loading