Repository navigation
Conversation
|
CI doesn't run on this PR while its base is #1317's branch, so here are the local results for
|
d07bef8 to
58f1918
Compare
58f1918 to
f5c843f
Compare
f5c843f to
43ab309
Compare
karenc-bq
left a comment
There was a problem hiding this comment.
Also let some extra comments on #1300 (review)
c733b21 to
0376a8b
Compare
| 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) |
There was a problem hiding this comment.
Dropping socket timeout provided by the application from the connection properties here seems suspicious. Could you please clarify this change?
There was a problem hiding this comment.
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
UnsupportedOperationErrorand 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 withsocket_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.
0376a8b to
3f8e64b
Compare
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.
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, and its base is #1317's branch, so it merges after #1317. The diff also moves the engine-specific SQL that #1300 and #1317 kept in
encryption/sql_dialect.pyinto the driver dialects and runs it undersocket_timeout. That changes code that #1300 and #1330 put ondev, as well as #1317's analyzer and tokenizer. The review of the first commit is addressed in 7072b10. The integration tests in #1349 sit on this PR; their helper imports the deleted module and rewritesencrypt.intrigger_pg.sql, so #1349 needs the matching helper change before it merges.executeandexecutemany, 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 newPluginCallContext.holdsconfirms 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_binarybefore each placeholder it encrypts, except on a prepared cursor, so the server takes the payload as binary data and raises no warning 1300.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 itskey_storagerow, so values written before a key rotation still decrypt. Inside psycopg'swith 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 raiseMetadataError. On psycopg, a row factory other thantuple_row,dict_rowornamedtuple_rowraisesMetadataErrorbefore the application gets a row of an encrypted result.auto_sort_wrapper_plugin_orderon, it runs afteraurora_connection_trackerand 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 theMetadataErrors 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'sAwsWrapperErrorunlesspreserve_driver_exception_typeis on.MetadataError, without reading a key row or calling KMS.encryption/sql_dialect.pyheld, and that file is deleted:DriverDialectgainsengine_name,equals_operator,fold_identifier,metadata_key,upsert_clause,insert_returning_id,fetch_rowsandrun_statement, with overrides inPgDriverDialectandMySQLDriverDialect. The plugin's three driver-specific checks live there too,analyzable_sql(the text ofbytesSQL and psycopgsql.Composableobjects),binary_placeholder_prefix(MySQL's_binary) andunsupported_row_factory(psycopg), so the KMS code imports no driver and tests no driver class or module name.sql_analyzer.analyzeand the tokenizer take the dialect class, andKeyManagerandMetadataManagertake the driver dialect, whichKeyManagementUtilitybuilds itself. The SQL they send is unchanged, the pinned PostgreSQLOPERATOR(pg_catalog.=)included.cursor.executeandfetchalldirectly, sosocket_timeoutdidn't bound them, and in the first commit a hung metadata orkey_storagestatement held up the application's statement. They now go throughDriverDialect.execute, so the application connection'ssocket_timeoutbounds them: a metadata load orkey_storagelookup that runs longer raisesMetadataErrororKeyManagementError, 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;PluginConnectionSourcenow leaves a connection the timeout marked abandoned open, and the worker closes it when it finishes.KeyManagementUtilitybuilds its dialect with no properties, so its statements still have no time limit.Refused and passed through
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). A missing or unusable key row raisesInvalidKeyMetadataError, and a master key that isn't inencryption_allowed_master_key_arnsraisesUnauthorizedMasterKeyErrorbefore KMS is called.MetadataError, a statement with a placeholder inside a quoted literal, quoted identifier or comment when the analysis finds a table with encrypted columns in it, since the driver binds that placeholder too. The same goes for a%(name)sbound for an encrypted column and also used where the value must stay plain, because one parameter can't carry both the payload and the plaintext.<>,<,BETWEEN,NOT IN,NOT LIKE,NOTor an outer join'sON) raisesMetadataError, also inside a write the plugin would otherwise pass through.EncryptionFailedErrorbefore 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. Everyexecuteandexecutemanythrough the wrapper's cursor has its own context.key_storagerow raisesIntegrityCheckErrorunlessencryption_return_unverified_data=True, and a column whoseencryption_metadatarow names an unsupported algorithm raisesInvalidAlgorithmError. Every error class derives fromEncryptionPluginErrorinaws_advanced_python_wrapper.errors.INSERTwithout a column list,INSERT ... SELECT) runs unchanged.bytesSQL is analyzed when the connection's client encoding reads every ASCII byte as itself and the text encodes back to the same bytes (on MySQL, only when it is all ASCII), and a psycopgsql.Composableis analyzed as its text and sent as the object; any other SQL object runs unchanged. 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.EncryptionConfigErrorat the firstexecuteor non-emptyexecutemany, before any analysis.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 importscryptographyandsqlglotonly when it is created.Behaviour changes
aws_advanced_python_wrapper.plugin_servicenow also loads 11 modules ofaws_advanced_python_wrapper.encryption(the plugin and the key layer), but still neithercryptographynorsqlglot.Changes to the code of #1300, #1317 and #1330
This code is on
devor in #1317, so the old behaviour was never released.KeyManagementUtility(engine=...)accepts only"postgresql"or"mysql", in any case. The aliasespg,postgres,psycopg,mysql-connectorandmysql-connector-pythonthat feat: kms encryption crypto core and key/metadata layer #1300 accepted now raiseEncryptionConfigError, and so does anenginewhose driver isn't installed.engine,KeyManagementUtilitynow asks the driver dialects whether they handle the connection, where feat: kms encryption crypto core and key/metadata layer #1300 looked at the connection class's module. A mysql-connectorPooledMySQLConnectionwas taken as MySQL and now needsengine="mysql", as the guide says.encryption/sql_dialect.pyis deleted. It was internal (not exported and not documented), so no public import path goes away.PluginCallContext.holds(args, kwargs)is new, andPluginService.mddocuments it.How to enable it
Install the extra, which adds
cryptographyandsqlglot, and the target driver:pip install "aws-advanced-python-wrapper[encryption]"An administrator creates the two metadata tables (
encryption_metadataandkey_storage) once, sets up each column withKeyManagementUtility(a master key, the column's data key and its metadata rows) and adds a database-side trigger to every encrypted column. Then addkms_encryptionto the connection'spluginsand list the master keys the plugin may use:The guide gives the
encryption_*parameters, the metadata tables' DDL and the per-column triggers. The trigger SQL ships with the package asaws_advanced_python_wrapper/encryption/sql/trigger_pg.sqlandtrigger_mysql.sql; both readSCHEMA_NAME.encryption_metadataandSCHEMA_NAME.key_storage, and the administrator replacesSCHEMA_NAMEwith the metadata schema before running them. With SQLAlchemy, pass the plugin list asconnect_args={"plugins": "..."}or?wrapper_plugins=...; with Django (MySQL only), put it and theencryption_*parameters in the database'sOPTIONS.What this PR contains
38 files, +6913/-362, with no dependency change; the
encryptionextra comes from #1300 (cryptography) and #1317 (sqlglot).aws_advanced_python_wrapper/encryption/kms_encryption_plugin.py, its registration inPluginManager, its message texts, the audit parameter's help text, its unit tests and an import-guard case that a connection asking for the plugin without the extra fails with the install hint.PluginCallContext.holds, the driver-dialect members of item 5 and the key layer's switch to them and toDriverDialect.execute(item 6), with their unit tests.docs/using-the-python-wrapper/using-plugins/UsingTheKmsEncryptionPlugin.md: setup and key rotation withKeyManagementUtility, the parameters, what the plugin encrypts, refuses, passes through and doesn't see, the errors applications catch, hardening, notes for SQLAlchemy, Django and MySQL (including wherelog_bin_trust_function_creatorsis set on a self-managed server and on Aurora MySQL), the metadata tables' DDL and installing the trigger SQL and each column's triggers. The plugin also gets rows inUsingThePythonWrapper.mdandPluginChainCompatibility.md, an entry indocs/README.md, a sentence onholdsinPluginService.mdand a CHANGELOG entry under## [Unreleased].tests/integration/test_kms_encryption_live.py, a live test module run by hand before a PR. No CI workflow runs it, andpytest ./tests/unitdoesn't collect it. test: add kms encryption plugin integration tests #1349 replaces it with container tests and deletes it.aws_advanced_python_wrapper/encryption/sql/trigger_pg.sql(version 2) andtrigger_mysql.sql(version 1), which the wheel includes and the live module installs, and a unit test file that checks each file's version stamp, its 65-byte minimum againstEncryptionService.MIN_ENCRYPTED_LENGTH, the metadata schema it reads and that the PostgreSQL file reads it throughSCHEMA_NAME.Limitations
cursor.copy(),cursor.stream()andcursor.results(), the result sets afternextset()on anexecute,callproc(), SQLPREPAREandEXECUTE,LOAD DATA, stored routines, reads through a view, connections taken fromtarget_connectionand the driver's cursor thatcursor.target_cursorreturns. The guide lists them all under "What the plugin does not see".forloop over a cursor decrypts its rows for the statement that was current when the loop started. Finish the loop before running another statement on the same cursor.encryption_metadata_cache_enabledoff, 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.encryption_audit_logging_enabledis accepted, but no audit records are written; when it isTrue, each connection logs one warning saying so.utf8mb4or a single-byte client character set, set with thecharsetconnection argument rather thanSET NAMES.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 before the closed-connection, hidden-placeholder and shared-parameter checks were added). Each new connection's first encrypted statement also waits for one KMS
Decrypton 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 pay only #1330's cost, plus at most 0.09 µs per call from this PR. These figures predate the review changes and weren't measured again; withsocket_timeoutset, each metadata and key statement now also runs throughDriverDialect.execute's time limit (from readingdriver_dialect.py; not measured).Tests
pytest ./tests/unit -Werrorpasses 4529 tests on Python 3.10 and 3.12, and flake8, isort and mypy are clean on both.KeyManagementUtility, 3 for the import guard, 2 forPluginConnectionSourceand 2 forPluginCallContext.holds). With branch coverage, the plugin module andconnection_source.pyreach 100%, and every line and branch the change adds tokey_management_utility.pyand the three driver dialects is covered. The 11 tests added for behaviour that 7072b10 changes each failed before that change, and with the head's tests run at the base the fivetest_unknown_enginealias cases fail too.SCHEMA_NAMEtoken, pass against LocalStack's KMS (77 on PostgreSQL and 145 on MySQL plus 1 xfail) and against AWS KMS in us-east-2 (3 on PostgreSQL and 4 on MySQL).Decryptevents with no value in any event, the allow-list refused a real key ARN that isn't on it and no DEBUG record held"Plaintext".executemany, every fetch shape and loop, SQLAlchemy and Django on MySQL round-tripped, and the plugin's own connections used the application's TLS settings and logged in as the same user underiamandaws_secrets_manager. A cluster failover with the guide's Aurora chain raised oneFailoverSuccessError, after which writes and reads continued and every earlier value read back; withread_write_splittingorsrw, reads on the reader decrypted, and the statement logs held none of the text and big-integer values written.socket_timeoutwith the metadata cache off, so only unit tests prove thesocket_timeoutlimit; the live module after the review changes; RDS for PostgreSQL and RDS for MySQL, Aurora MySQL with binary logging on, KMS throttling, server errors and automatic key rotation. GitHub CI didn't run on 7072b10.There is a CHANGELOG entry, 22 new message keys and the new guide.
By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.