Repository navigation
Use hashlib.pbkdf2_hmac for SCRAM salted password - #1359
Merged
Merged
Conversation
_generate_salted_password becomes cpdef so tests can reach the compiled method; internal call sites keep the C fast path.
elprans
approved these changes
Sep 24, 2026
Merged
MaciejZet
pushed a commit
to MaciejZet/asyncpg
that referenced
this pull request
Oct 8, 2026
## Improvements * Support Python 3.15 (MagicStack#1367, MagicStack#1378) (by @elprans in 1b11846 and 58c0c59) * Support PostgreSQL 19 (MagicStack#1379) (by @elprans in 8d2a5ae) * Make pool `min_size` a maintained connection floor and add `init_size` to control the number of connections opened at startup (MagicStack#1323). Idle connections at or below `min_size` are retained, and closed connections are replaced in the background. `init_size` defaults to `min_size`. To preserve the previous behavior, where the pool could drain to zero, replace `min_size=N` with `init_size=N, min_size=0`. (by @shatilov-diman in 67a1cbc) * Use `hashlib.pbkdf2_hmac()` for faster SCRAM password derivation (MagicStack#1359) (by @twelfthlabor in 00319a9) * Use the statement cache for `copy_records_to_table()` introspection (MagicStack#1360) (by @matemax in dd05865) ## Fixes * Clean up connections rejected by `target_session_attrs` immediately so an unresponsive rejected host cannot delay the selected connection, and cleanup tasks cannot outlive the event loop. Rejected connections are aborted without waiting for a graceful disconnect; servers may log "unexpected EOF on client connection" if the Terminate message is not delivered before the transport closes. * Fix a connection pool deadlock when releasing a connection after a protocol abort (MagicStack#1324) (by @pchaseh in 4a83cc2) * Honor `Connection.close(timeout=...)` while waiting for a pending cancellation (MagicStack#1361) (by @gyanu2507 in c06bcb4) * Prevent stuck cancellation from blocking connection teardown or pool release by bounding cancellation with the command or release timeout (MagicStack#1370) (by @elprans in 4cf0220) * Preserve the server error when the connection closes mid-operation (MagicStack#1369) (by @RitiGrover in 6c8f1a7) * Fix COPY cleanup when a records generator raises, preserving the original exception and avoiding protocol desynchronization and stalled rollback (MagicStack#1358) (by @CodingCossack in fdc6bc8) * Reparse unnamed statements before cursor binding when the statement cache is disabled (MagicStack#1364) (by @elprans in 302ba49) * Allow cursors in transactions started outside `Connection.transaction()`, such as with an explicit `BEGIN` (MagicStack#1350) (by @aryansk in 25aaaf5) * Remove the query logger when the `query_logger()` block raises (MagicStack#1373) (by @kratos0718 in 6a7fbd3) * Fix a segfault in `Record.get()` with an invalid number of positional arguments (MagicStack#1333) (by @apoorvdarshan in 40a3832) * Align SSL startup retries with libpq and improve SSL rejection diagnostics (MagicStack#1366). Retry alternative transports only before authentication succeeds. Direct TLS now requires `sslmode=require`, `verify-ca`, or `verify-full`, or an explicit `SSLContext`. (by @elprans in 78752c9) * Preserve password errors during SSL fallback when the fallback fails with a less specific authorization error (MagicStack#1331) (by @Mauricio0129 in 2d97947) * Handle cleartext password authentication when no password is supplied without raising an `AttributeError` (MagicStack#1351) (by @aryansk in 6be5915) * Set the `postgresql` ALPN protocol on SSL contexts created by asyncpg so direct TLS connections work with PostgreSQL 17 and later (MagicStack#1372). User-provided contexts must set this protocol for direct TLS connections. (by @DurandA in b21325d) * Link explicitly against `libm` on non-Windows platforms to fix undefined math symbol errors when loading the extensions (MagicStack#1305) (by @veeceey in db8ecc2) * Fix builds on FreeBSD 15 by linking against `libstdthreads` (MagicStack#1368) (by @elprans in 87bcaf9) ## Other * Replace `pkg_resources` with `packaging` in `setup.py` (MagicStack#1362) (by @elprans in 6695db7) * Build Linux and macOS ARM64 wheels on native runners and add Windows ARM64 wheel builds (MagicStack#1308) (by @ddelange in 1e8cc1c) * Add manual and PR-label-triggered dry runs to the release workflow (MagicStack#1374) (by @elprans in 1bd643e) * Clarify how `execute()` uses prepared statements and how to confirm an `INSERT` in the documentation (MagicStack#1336) (by @pctablet505 in cdf816c) * Fix typos in comments and docstrings (MagicStack#1332) (by @maxtaran2010 in bc3e246)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
SCRAMAuthentication._generate_salted_password()reimplements the RFC 5802Hi() function as a Python-level PBKDF2 loop: one
hmac.new()and aPython-level XOR over
zip()for each iteration. PostgreSQL's defaultiteration count is 4096, so that loop runs 4095 times before every
password-authenticated connection can finish its handshake.
hashlib.pbkdf2_hmac("sha256", ...)computes exactly the same value in C.Hi() is PBKDF2-HMAC-SHA256 with a single output block, so
dkLenequals thedigest size (32 bytes) and the result is byte-identical to the loop.
The old code's first HMAC used
self.DIGEST, and every iteration after thathardcoded
hashlib.sha256. SinceSCRAM-SHA-256is the only mechanism thisclass handles, naming the algorithm explicitly removes no real digest
agility.
_bytes_xorstays, because_generate_client_proofstill uses it.Fixes #1357.
Verification
The old loop and
hashlib.pbkdf2_hmacwere compared in a standalone batteryof 324 cases that reproduces the loop verbatim: published
PBKDF2-HMAC-SHA256 test vectors, iteration counts 1, 2, 3, 4096 and 10000,
empty, short, long and unicode passwords and salts, and 310 random
combinations. Every result is 32 bytes and byte-for-byte equal.
A build of the patch was then connected with a password to a local
PostgreSQL 16 server with
password_encryption = scram-sha-256andscram-sha-256inpg_hba.conf. Handshakes succeeded with storediteration counts 2, 4096 and 10000, a wrong password still failed with
InvalidPasswordError, and the server log recordedmethod=scram-sha-256.Instrumenting
hashlib.pbkdf2_hmacshowed the compiled extension calling itwith
('sha256', ..., 4096)during a live handshake, while the same check onthe pre-fix build recorded no calls. The compiled path was exercised
end-to-end but was not separately timed.
A standalone microbenchmark of the old loop against the stdlib primitive at
4096 iterations, best of 7 runs, measured 12.9 ms against 0.85 ms in one run
(15.3x) and 18.8 ms against 1.08 ms in another (17.5x) on this machine (Apple
silicon, CPython 3.11).
Tests
tests/test_scram.pyis new and runs without a server: RFC 7914 and RFC 7677vectors, byte-equality against the old Hi() loop (including a unicode
password), and a spy asserting the compiled path calls
hashlib.pbkdf2_hmac("sha256", password, salt, iterations). All 4 pass on the fix. The pbkdf2-call test fails against the pre-fix code(no call is recorded), so it pins the change. The server-free subset
(
test_scram,test_record,test__sourcecode) is 31 tests OK, 2 skipped.To make the compiled method reachable from a test without a server,
_generate_salted_passwordchanges fromcdeftocpdefinscram.pyx/scram.pxd; internal call sites keep the C fast path. If youwould rather keep the method fully private, say so and I will move the test
behind a fake-server harness or drop it; the performance fix does not depend
on the visibility change.
tests.test_connectpasses on both the pre-fix and post-fix build (51 tests,2 environment skips), including
test_auth_password_scram_sha_256against amanaged cluster.
tests.test__sourcecodeandtests.test_testpass. Thefull suite needs a PostgreSQL instance, so only the connect and auth subset
was run locally. CI runs the suite against PostgreSQL 9.5 through 18, and
test_auth_password_scram_sha_256connects with a password on 10 and above,so a wrong digest, dkLen or iteration handling fails in CI.
One edge case changes behavior. PostgreSQL never sends an iteration count of
zero and RFC 5802 does not allow it, but if a nonconforming server did, the
old loop quietly computed a one-iteration value while
pbkdf2_hmacraisesValueErrorand the connection fails. Validatingi >= 1inparse_server_first_messagewould move that error into the auth layer; leftas a follow-up here.