Skip to content

feat: kms encryption plugin - #1331

Merged
JuanLeee merged 4 commits into
devfrom
feat/kms-stack-4-plugin
Dec 2, 2026
Merged

JuanLeee merged 4 commits into
devfrom
feat/kms-stack-4-plugin

Conversation

@JuanLeee

@JuanLeee JuanLeee commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

This adds the KMS Encryption Plugin (kms_encryption). It encrypts the values an application binds for configured columns before the driver sends them, and decrypts them when they are read back, so the application's SQL doesn't change. Each column has its own data key, and the database holds only a copy of it encrypted by an AWS Key Management Service (KMS) master key, so neither the plaintext nor a usable data key reaches the database. The plugin works with the synchronous wrapper, on PostgreSQL with psycopg and on MySQL with MySQL Connector/Python.

The plugin uses the call context from #1330, the encryption library from #1300 and the SQL analysis from #1317, all on dev, and it changes some of that code, which was never released. It also routes six more cursor methods through the plugins on every synchronous connection, so the KMS plugin can check them. It masks more connection properties in the wrapper's logs on every connection and fixes callproc, which has dropped its positional arguments in every release since 1.0.0. The integration tests in #1349 sit on this PR and should merge with it.

  1. On execute and executemany, the plugin makes a copy of the arguments in which every bound parameter that the SQL analysis maps to an encrypted column, written or compared, is encrypted. It hands that copy to the plugins after it and to the driver through the call context (PluginService.current_call_context), once the new PluginCallContext.holds confirms that the context holds the same argument objects it analyzed. The caller's SQL and parameter objects are never modified, and the default plugin stays in the chain. On MySQL the plugin adds _binary before each placeholder it encrypts, except on a prepared cursor, so the server takes the payload as binary data and raises no warning 1300.
  2. Encrypted result columns are decrypted on fetchone, fetchmany, fetchall, next(cursor), iteration and psycopg's chained reads (feat: plugin call context for cursor execute arguments #1330 routes the last three through the plugins), and each value comes back as the Python type it was written as. Each value's key id selects its key_storage row, so values written before a key rotation still decrypt. The plugin places result columns by the analysis, so a column renamed by a derived table's or a CTE's column list (AS t(x), WITH c(x) AS (...)) or an alias beside * decrypts too, and a name that a USING or NATURAL join could fill from another source raises MetadataError before any row is read.
  3. The plugin's weight is 390, so with auto_sort_wrapper_plugin_order on, it runs after aurora_connection_tracker and the read/write splitting plugins and before the failover plugins. The plugins that run before it receive the caller's values; the plugins after it and the driver receive the encrypted copies. The plugin raises its own errors before a failover plugin sees them, so applications get the plugin's error classes, and the MetadataErrors it reports for unreadable metadata don't start failover. With auto-sort off and the plugin listed after a failover plugin, its errors reach the application wrapped in that plugin's AwsWrapperError unless preserve_driver_exception_type is on.
  4. Each connection that uses the plugin has its own metadata cache, data-key cache and KMS client, with up to two background threads, and closing the connection releases them. The metadata load, each background refresh and the first read of a value written under an earlier key open a short-lived connection with the application connection's properties. Once the connection is closed, a statement, a fetch or a loop that began before the close raises MetadataError, without reading a key row or calling KMS.
  5. The engine-specific SQL of encryption/sql_dialect.py and the per-engine tables of the analyzer and tokenizer now live in PgDriverDialect and MySQLDriverDialect, under members that the new mixin EncryptionDriverDialect (aws_advanced_python_wrapper/encryption_driver_dialect.py) declares, and sql_dialect.py is deleted. The members are the grammar the analysis needs (equals_operator, sqlglot_dialect, sql_token_pattern), fold_identifier, metadata_key, quote_identifier, upsert_clause, insert_returning_id and three new driver checks: analyzable_sql (the text of bytes SQL and psycopg sql.Composable objects), binary_placeholder_prefix (MySQL's _binary) and unsupported_row_factory (psycopg), so the KMS code imports no driver and tests no driver class or module name. DriverDialect itself doesn't change, and the generic helpers fetch_rows, run_statement and describe_failure are functions in encryption/connection_source.py. The SQL the key layer sends is unchanged, the pinned PostgreSQL OPERATOR(pg_catalog.=) included.
  6. The key layer's statements called cursor.execute and fetchall directly, so socket_timeout didn't bound them. They now go through DriverDialect.execute, so the application connection's socket_timeout bounds them: a metadata load or key_storage lookup that runs longer raises MetadataError or KeyManagementError, and a background refresh that runs longer logs a warning. mysql-connector's C extension can't interrupt a statement, so a timed-out statement can leave its worker running on the connection; PluginConnectionSource now leaves a connection the timeout marked abandoned open, and the worker closes it when it finishes. KeyManagementUtility applies the socket_timeout in its props only on the driver's own connection, because the dialect's timer can abort only a raw psycopg or mysql-connector connection.
  7. AwsWrapperCursor had no copy, stream, results or set_result (psycopg) and no fetchsets or stored_results (mysql-connector), so __getattr__ sent them to the driver cursor past every plugin. They are now methods that go through the plugin chain under six new DbApiMethod members, on every synchronous connection, so the KMS plugin can analyze a copy() and refuse the other five. The PostgreSQL and MySQL dialects don't count them as network-bound, so the failover and monitoring plugins and socket_timeout don't apply to them there; under the generic driver dialect, whose network-bound set is *, they do. The plugins wrap only the call, not reads from the object it returns. The async cursor still forwards them through __getattr__.
  8. KeyManagementUtility sets up AES-256-GCM columns only, and rotate_data_key refuses, before any change, a column that holds a value or uses another algorithm, because a rotation left existing values under the old key. The new validate_schema() reads only the catalog and returns one message per missing metadata table, column, primary key, unique key or foreign key.
  9. The new rotate_data_key_and_reencrypt and reencrypt_remaining_rows move a column's values to the new key in primary-key batches (1000 by default, 100000 at most), one commit per batch, with SELECT ... FOR UPDATE and an UPDATE that writes only while the stored value is still the old payload, so an application's write during the run isn't lost. They open each payload and seal its plaintext bytes again with a new IV and the same type marker, and they refuse an AwsWrapperConnection, whose plugin would encrypt the payloads a second time. On PostgreSQL the primary key must have a built-in type, and both methods turn autocommit off and restore it.
  10. The KMS region is encryption_kms_region, else the one region that the key and alias ARNs in encryption_allowed_master_key_arns name. Without the parameter, ARNs in more than one region, or an allow-list that names no region, raise EncryptionConfigError; with it, a region that differs from an ARN's logs one warning. The region no longer comes from AWS_REGION or AWS_DEFAULT_REGION.
  11. A failed KMS call raised KeyManagementError with KMS's text and chained botocore's ClientError, whose text names the account, the caller's role session and the key ARN. The message now gives the operation, the KMS error code and the HTTP status ("KMS DECRYPT_DATA_KEY failed after 1 attempt(s): ClientError, error code AccessDeniedException, HTTP status 400"), and nothing is chained. Key-row reads and metadata loads now give only the driver error's type and SQLSTATE or errno, also unchained. mask_error_text masks ARNs, URL user info and the values of secret-named name=value pairs, replaces control characters with ? and cuts text to 200 characters, and mask_arn masks an alias ARN or alias/ name whole.

Refused and passed through

  1. Before the driver is called, and before any KMS call for the value, the plugin refuses a literal or other non-parameter value written to an encrypted column (MetadataError), a value with no exact stored form such as a UUID, list or dict (EncryptionFailedError) and a value the analysis can't tie to the encrypted column it may belong to (MetadataError). While encryption_fail_on_unmapped_parameter is on (the default), it also refuses a statement with parameters on a table with encrypted columns that the analysis can't fully map (MetadataError).
  2. A missing or unusable key row raises InvalidKeyMetadataError, and a master key that isn't in encryption_allowed_master_key_arns raises UnauthorizedMasterKeyError before KMS is called.
  3. A statement with a placeholder inside a quoted literal, quoted identifier or comment raises MetadataError when the analysis finds a table with encrypted columns in it, since the driver binds that placeholder too, and so does a MySQL /*! */ comment or a CTE named like a table with encrypted columns.
  4. A %(name)s bound for an encrypted column and also used where the value must stay plain raises MetadataError, because one parameter can't carry both the payload and the plaintext.
  5. A comparison of a parameter with an encrypted column that would still select rows when it never matches (for example <>, <, BETWEEN, NOT IN, NOT LIKE, NOT or an outer join's ON) raises MetadataError, also inside a write the plugin would otherwise pass through.
  6. A statement the plugin has to change is also refused, with EncryptionFailedError before the driver is called, when the plugin finds no call context for it or finds one that holds arguments other than the ones it analyzed. Every execute and executemany through the wrapper's cursor has its own context.
  7. A stored value that fails its HMAC check, isn't binary or names an earlier key id with no usable key_storage row raises IntegrityCheckError unless encryption_return_unverified_data=True, and a column whose encryption_metadata row names an unsupported algorithm raises InvalidAlgorithmError. Every error class derives from EncryptionPluginError in aws_advanced_python_wrapper.errors.
  8. Inside psycopg's with conn.pipeline():, a result's column description arrives only with its rows, so the plugin reads the columns then, and rows of an encrypted result that arrive without one raise MetadataError. On psycopg, a row factory other than tuple_row, dict_row or namedtuple_row raises MetadataError before the application gets a row of an encrypted result.
  9. SQL the plugin can't analyze raises MetadataError before anything is sent while encryption_fail_on_unmapped_parameter is on and any column is encrypted: an object other than str or a psycopg sql.Composable, bytes that don't decode and encode back to the same bytes in the client encoding, or non-ASCII bytes on MySQL.
  10. A write the analysis can't fully read runs unchanged when it has no parameters or encryption_fail_on_unmapped_parameter is off, and so does SQL it can't analyze with the parameter off. The plugin logs one warning per connection for each kind of statement it passes through this way, up to 256 kinds, and the database-side trigger must reject any plaintext in them.
  11. A copy() raises MetadataError when its COPY ... FROM names an encrypted column, when the plugin can't parse a COPY that can write such a table and, whenever a column is encrypted, when the plugin can't analyze its SQL. A COPY with parameters on a table with encrypted columns raises while encryption_fail_on_unmapped_parameter is on, and a COPY ... FROM without a column list runs with a warning.
  12. stream(), results(), set_result(), fetchsets() and stored_results() raise MetadataError while the plugin is on, even when no column is encrypted, because their rows never pass through the plugin. callproc() with arguments raises MetadataError while encryption_fail_on_unmapped_parameter is on and any column is encrypted; without arguments it runs without the plugin seeing it.
  13. A loop over a cursor raises MetadataError at its next row once the cursor has run another statement and either statement names a table with an encrypted column, since the rows it would return belong to the new statement.
  14. A driver dialect that doesn't mix in EncryptionDriverDialect, such as the generic one, raises EncryptionConfigError when the plugin is created, at connect.
  15. The plugin's messages name tables, columns, parameter names and Python types, never a value read or written, a key or SQL text, and the errors it raises while running statements carry no chained exception. Each value's data-key and HMAC-key copies are wiped after use (best effort). The plugin builds its KMS client with KeyManager.create_kms_client, so feat: kms encryption crypto core and key/metadata layer #1300's botocore log filters are on from its first connection, and it imports cryptography and sqlglot only when it is created.

Behaviour changes

  1. On every synchronous connection, with or without the plugin, copy, stream, results, set_result, fetchsets and stored_results now go through the plugin chain, so the plugins subscribed to every method (DefaultPlugin, DeveloperPlugin, ExecuteTimePlugin) see them. A method the driver cursor lacks now exists on the wrapper cursor and raises the driver's AttributeError from inside the chain.
  2. PropertiesUtils.mask_properties, which feeds Properties.__repr__, the DEBUG record of the connection properties, both connection providers and the failover handlers' DEBUG records, sync and async, now also masks names containing pwd, secret, token or credential, the name key and encryption_allowed_master_key_arns. Seven more wrapper parameters now show as '***', six of them released, among them secrets_manager_secret_id, secrets_manager_region and iam_token_expiration, which fix: qualify the async topology query, mask all credential properties, and correct plugin docs #1270 left readable on purpose in 3.1.0, so the 3.1.0 CHANGELOG line about the Secrets Manager properties no longer matches the code. _is_secret_property is now public as is_secret_property.
  3. Importing aws_advanced_python_wrapper.plugin_service now also loads 12 modules (the aws_advanced_python_wrapper.encryption package with 10 of its modules, and encryption_driver_dialect), but still neither cryptography nor sqlglot. The import took 0.309 s at the head and 0.308 s at the base (Python 3.12, medians of 7 fresh runs).

Other fixes

  1. AwsWrapperCursor.callproc passed only **kwargs to the driver, so with the base code callproc("sp", (1, 2)) on a mysql-connector MySQLCursor raised TypeError: MySQLCursor.callproc() missing 1 required positional argument: 'procname'. It now passes the positional arguments too, as the async cursor already did. Live since e3e3aedf (feat: add poc, 2023-05-16), so every release from 1.0.0 to 3.1.0 has it.

Changes to the code of #1300, #1317 and #1330

This code is on dev, so the old behaviour was never released. Items 8 to 11 change #1300's KeyManagementUtility, region rule and KMS errors; the plugin still reads and writes an AES-128-GCM column set up before.

  1. KeyManagementUtility(engine=...) is gone; the utility takes props= instead. A wrapper_driver_dialect code in it wins, and otherwise the new DriverDialectManager.get_dialect_for_connection picks the dialect that recognizes the connection, so a mysql-connector PooledMySQLConnection needs props={"wrapper_driver_dialect": "mysql-connector-python"}, as the guide says.
  2. KeyManager now installs the botocore log filters itself, so a KeyManagementUtility given a KMS client built another way, such as boto3.client("kms"), gets them too.
  3. encryption/sql_dialect.py and models.mask_arns_in_text are deleted. Both were internal (not exported and not documented), so no public import path goes away.
  4. PluginCallContext.holds(args, kwargs) is new, and PluginService.md documents it.

How to enable it

Install the extra, which adds cryptography and sqlglot, and the target driver:

pip install "aws-advanced-python-wrapper[encryption]"

An administrator creates the two metadata tables (encryption_metadata and key_storage) once, can check them with KeyManagementUtility.validate_schema(), sets up each column with KeyManagementUtility (a master key, the column's data key and its metadata rows) and adds a database-side trigger to every encrypted column. Then add kms_encryption to the connection's plugins and list the master keys the plugin may use:

import psycopg

from aws_advanced_python_wrapper import AwsWrapperConnection, release_resources

try:
    with AwsWrapperConnection.connect(
            psycopg.Connection.connect,
            "host=db.example.com dbname=mydb user=app password=...",
            plugins="initial_connection,aurora_connection_tracker,failover_v2,host_monitoring_v2,kms_encryption",
            encryption_kms_region="us-east-1",
            encryption_allowed_master_key_arns="arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
            autocommit=True,
    ) as conn, conn.cursor() as cur:
        cur.execute("INSERT INTO users (name, ssn) VALUES (%s, %s)", ("Jane Doe", "000-00-0000"))
        cur.execute("SELECT ssn FROM users WHERE name = %s", ("Jane Doe",))
        print(cur.fetchone())
finally:
    release_resources()

The guide gives the encryption_* parameters, the metadata tables' DDL and the per-column triggers. The trigger SQL ships with the package as aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql and trigger_mysql.sql; both read SCHEMA_NAME.encryption_metadata and SCHEMA_NAME.key_storage, and the administrator replaces SCHEMA_NAME with the metadata schema before running them. With SQLAlchemy, pass the plugin list as connect_args={"plugins": "..."} or ?wrapper_plugins=...; with Django (MySQL only), put it and the encryption_* parameters in the database's OPTIONS.

What this PR contains

58 files, +11648/-1400, with no dependency change; the encryption extra comes from #1300 (cryptography) and #1317 (sqlglot).

  1. The plugin module aws_advanced_python_wrapper/encryption/kms_encryption_plugin.py, its registration in PluginManager, its message texts and the new encryption_fail_on_unmapped_parameter parameter, the mixin module aws_advanced_python_wrapper/encryption_driver_dialect.py and the other changes above, with their unit tests and an import-guard case that a connection asking for the plugin without the extra fails with the install hint.
  2. The guide, docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md: setup, validate_schema(), key rotation and re-encryption with KeyManagementUtility, the parameters, what the plugin encrypts, refuses, passes through and doesn't see, the errors applications catch, the trigger and hardening, with notes for SQLAlchemy, Django and MySQL. The plugin also gets rows in UsingThePythonWrapper.md and PluginChainCompatibility.md, a note in SqlAlchemySupport.md, an entry in docs/README.md, a sentence on holds in PluginService.md and a CHANGELOG entry under ## [Unreleased].
  3. tests/integration/test_kms_encryption_live.py, a live test module run by hand. No CI workflow runs it, and pytest ./tests/unit doesn't collect it. test: add kms encryption plugin integration tests #1349 replaces it with container tests and deletes it.
  4. The trigger SQL, aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql (version 2) and trigger_mysql.sql (version 1), which the live module installs, and a unit test file that checks each file's version stamp, its 65-byte minimum against EncryptionService.MIN_ENCRYPTED_LENGTH, the metadata schema it reads and that it reads it through SCHEMA_NAME.

Limitations

  1. Every encrypted column needs a database-side trigger. The plugin sees only the statements sent on connections that enable it, and it finds encrypted columns by reading the SQL, so some statements reach the database without the plugin seeing them: callproc() without arguments, SQL CALL, DO, PREPARE and EXECUTE, LOAD DATA, stored routines, reads through a view, connections taken from target_connection, the driver's cursor that cursor.target_cursor returns and the driver connection's own methods, such as mysql-connector's cmd_query() and psycopg's conn.pgconn. The guide lists them all under "What the plugin does not see".
  2. Encryption is randomized, so a comparison with an encrypted column never matches, and a unique index or an upsert's conflict target on one never detects a duplicate. A value the plugin doesn't see that is compared with an encrypted column is sent as written, so the database's statement log holds it.
  3. Error reporters that record local variables capture plaintext values from the wrapper's frames.
  4. Leave room for one more connection per application connection under any connection limit (with encryption_metadata_cache_enabled off, one for each thread using that connection at the same time). A plugin connection that a timed-out statement left running stays open until that statement ends.
  5. encryption_audit_logging_enabled is accepted, but no audit records are written; when it is True, each connection logs one warning saying so.
  6. The plugin's KMS calls carry no encryption context, so a key policy or grant can't limit a role to one column's data keys.
  7. When KMS refuses a call, botocore's botocore.parsers DEBUG record of the error response can name the caller's ARN and the master key ARN.
  8. KeyManagementUtility's metadata INSERT, UPDATE and DELETE statements and columns_using_key still put the driver's error text in their messages and chain the driver error.
  9. On MySQL, connections that write encrypted columns should use utf8mb4 or a single-byte client character set, set with the charset connection argument rather than SET NAMES.
  10. On a connection that is neither the driver's own nor an AwsWrapperConnection, such as a mysql-connector PooledMySQLConnection, nothing limits how long KeyManagementUtility's statements run.
  11. The encryption_* booleans are read with get_bool, so the strings "true" and "True" and any nonzero number turn one on, and a mistyped "ture" or the string "1" reads as off.
  12. There is no async support.

Cost

With the plugin enabled, a statement costs 3.5 to 9.2 µs more client CPU without an encrypted value and 29.0 to 35.9 µs more with one, plus 1.2 to 1.8 µs at the start of a loop (local servers and LocalStack, data key cached, measured on an early revision of the first commit and not since). Each new connection's first encrypted statement also waited for one KMS Decrypt on a new KMS client: about 35 ms from EC2 in the KMS region and about 300 ms from a laptop. Connections that don't enable the plugin get no new work on execute and the fetch paths, and the six routed cursor methods now pay for one pass through the plugin chain (from reading the diff; not measured).

Tests

  1. pytest ./tests/unit -Werror passes 4952 tests on Python 3.12 (3955 at the base), and flake8, isort and mypy are clean. GitHub CI on this tree passed 4952 tests on each of Python 3.10, 3.11, 3.12, 3.13 and 3.14, with mypy clean.
  2. The 24 changed unit test files hold 997 more cases than at the base: 689 for the plugin, 65 for the SQL analysis, 63 for KeyManagementUtility, 57 for the driver dialects, the mixin and DriverDialectManager, 28 for models, 22 for EncryptionConfig and 73 elsewhere. With the head's tests run against the base code, 21 assertion failures show the changes outside the plugin: 1 for callproc, 11 for the masking, 4 for the psycopg routing, 4 for quoted type-marker messages and 1 for a data key read at its exact expiry, which now comes back; the other failures come from names, signatures and files the PR adds, and 7 from tests that read the data-key cache's internal store, whose type changed.
  3. Outside this PR, on a tree one guide line from this one, test: add kms encryption plugin integration tests #1349's container tests, with the follow-up changes they need, passed against LocalStack's KMS (104 on PostgreSQL and 203 on MySQL plus 2 xfail, and 103 on PostgreSQL 19) and against AWS KMS in us-east-2 (5 on PostgreSQL and 8 on MySQL, also with a decrypt-only role). test: add kms encryption plugin integration tests #1349's Aurora tests passed on test: add kms encryption plugin integration tests #1349's head acc6b50c, which sits on this PR's head, against Aurora PostgreSQL and Aurora MySQL clusters of two instances each in us-east-2: 5 on PostgreSQL and 7 on MySQL (C extension and pure), for a round trip, failover with read/write splitting, rotation with re-encryption, the plugin's own connections keeping the application's auth and TLS, and psycopg's named cursor.
  4. On earlier revisions of the first commit, and not rerun since: each test that guards a security rule was checked by breaking the code it guards, and of 245 such breaks every one made a test fail, apart from two that don't change behaviour and one control. The live module passed all its tests against PostgreSQL 16, MySQL 8 and LocalStack's KMS. Three black-box suites written from the documentation, not part of this PR, passed against LocalStack and AWS KMS. On Aurora PostgreSQL 17.9 and Aurora MySQL 3.10.3, every supported type and fetch shape, SQLAlchemy and Django on MySQL round-tripped, and a cluster failover with the guide's Aurora chain raised one FailoverSuccessError, after which writes and reads continued and every earlier value read back.
  5. Not tested on this tree: SQLAlchemy and Django on Aurora, the live module (it now collects 293 tests), RDS for PostgreSQL and RDS for MySQL, Aurora MySQL with binary logging on, KMS throttling, server errors and automatic key rotation.

There is a CHANGELOG entry for the plugin, 92 new message keys and the new guide. The CHANGELOG has no entry for the callproc fix, the routed cursor methods or the wider masking.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

@JuanLeee

JuanLeee commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

CI doesn't run on this PR while its base is #1317's branch, so here are the local results for d07bef8 (the same tree as fdf1034, with the commit message reduced to its subject line), from a clean git archive export with poetry install -E encryption on Python 3.12.15:

  • flake8 .: clean
  • isort --check-only .: clean
  • mypy .: no issues in 392 source files
  • pytest ./tests/unit -Werror: 3756 passed, and 3756 on Python 3.10.22 and 3.11.17 too
  • poetry check --lock: passes

@JuanLeee
JuanLeee force-pushed the feat/kms-stack-4-plugin branch 2 times, most recently from d07bef8 to 58f1918 Compare October 29, 2026 12:02
@JuanLeee
JuanLeee force-pushed the feat/kms-stack-4-plugin branch from 58f1918 to f5c843f Compare November 2, 2026 11:01
@JuanLeee
JuanLeee force-pushed the feat/kms-stack-4-plugin branch from f5c843f to 43ab309 Compare November 5, 2026 00:02
@JuanLeee
JuanLeee marked this pull request as ready for review November 5, 2026 21:41

@karenc-bq karenc-bq left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also let some extra comments on #1300 (review)

Base automatically changed from feat/kms-sql-analysis to dev November 18, 2026 00:21
@JuanLeee
JuanLeee force-pushed the feat/kms-stack-4-plugin branch 2 times, most recently from c733b21 to 0376a8b Compare November 18, 2026 17:21
@JuanLeee
JuanLeee added this pull request to stack #1381 November 20, 2026 03:46
Messages.get_formatted("KeyManagementUtility.UnsupportedDriver", type(target).__name__))
if dialect.get_connection_from_obj(connection) is not connection:
# The dialect can abort only the driver's own connection, and a wrapper connection bounds its statements itself.
driver_props.pop(WrapperProperties.SOCKET_TIMEOUT_SEC.name, None)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping socket timeout provided by the application from the connection properties here seems suspicious. Could you please clarify this change?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The utility drops socket_timeout only when it isn't given the driver's own connection, because then its timer can't stop anything. On a wrapper connection, the wrapper already runs its own timer, and that one works.

What socket_timeout in props does

The utility passes props to the driver dialect, and DriverDialect.execute() reads socket_timeout from them (driver_dialect.py:140). If it's set, each statement runs on a worker thread with a timer. When the timer runs out, it calls abort_connection(conn) to stop the statement (utils/decorators.py:142). The PG dialect can only do that for a raw psycopg.Connection, by shutting its socket, and raises UnsupportedOperationError for anything else (pg_driver_dialect.py:116-160). The MySQL dialect works the same way.

Raw psycopg connection

utility
  └─ timer (props socket_timeout)
       └─ psycopg connection        ← on timeout: socket shut ✓

The timer gets the psycopg connection, shuts it, and the call raises QueryTimeoutError. The utility keeps the setting here.

AwsWrapperConnection

The utility runs its statements on the wrapper object, not on the psycopg connection inside it, so they go through the wrapper's plugins (failover and so on) like the application's own statements. That gives two timers:

utility
  └─ outer timer (props socket_timeout)          ← gets the wrapper object: can't shut it ✗
       └─ AwsWrapperConnection
            └─ plugins
                 └─ inner timer (wrapper's socket_timeout)   ← gets the psycopg connection ✓
                      └─ psycopg connection
  • The outer timer is handed the wrapper object, so on timeout it raises UnsupportedOperationError and the statement keeps running.
  • The inner timer is the wrapper's own (default_plugin.py:108). It's there when the wrapper connection was opened with socket_timeout, and it gets the real psycopg connection, so it works.

Dropping socket_timeout from the utility's own copy of props (key_management_utility.py:128) turns off the outer timer and leaves the inner one in charge. The dict the application passes in doesn't change. The same goes for other objects that aren't the driver's own connection, like a PooledMySQLConnection: the timer can't stop them either, and the guide says the utility doesn't limit them.

@JuanLeee
JuanLeee force-pushed the feat/kms-stack-4-plugin branch from 0376a8b to 3f8e64b Compare November 27, 2026 08:46
Pass the dialect to MetadataManager and KeyManager twice in the KMS live
test, as the plugin and KeyManagementUtility do, so mypy passes again.
The abstract-class test now calls EncryptionDriverDialect() with no
arguments and matches "abstract", so it fails if the class stops being
abstract.
- keep kms and driver errors out of exception chains and messages
- replace control characters and mask more secret names in logs
- refuse stream() and the result-set methods the plugin can't see
- refuse sql the plugin can't analyze when columns are encrypted
- place renamed result columns and refuse stale cursor loops
- create aes-256-gcm columns only, take the kms region from the key arns
- refuse rotate_data_key on a column with data and add re-encryption
- add an opt-in schema check
- pass callproc() arguments to the driver, refuse them for encrypted columns
- describe unseen paths, the endpoint and logging in the guide
@JuanLeee
JuanLeee force-pushed the feat/kms-stack-4-plugin branch from 14721da to e420c63 Compare December 2, 2026 11:48
@JuanLeee
JuanLeee merged commit 5ee042f into dev Dec 2, 2026
6 checks passed
@JuanLeee
JuanLeee deleted the feat/kms-stack-4-plugin branch December 2, 2026 17:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants