Skip to content

fix: do not retry on wrong password (28P01) with sslmode=allow/prefer - #1331

Merged
elprans merged 2 commits into
MagicStack:masterfrom
Mauricio0129:fix/sslmode-prefer-wrong-password
Sep 19, 2026
Merged

elprans merged 2 commits into
MagicStack:masterfrom
Mauricio0129:fix/sslmode-prefer-wrong-password

Conversation

@Mauricio0129

Copy link
Copy Markdown
Contributor

Fixes #1306

Problem

When connecting with sslmode=prefer (the default) or sslmode=allow to a
PostgreSQL server and providing wrong credentials, asyncpg surfaces a misleading
no pg_hba.conf entry ... no encryption error instead of a clear authentication
failure.

Root Cause

The retry logic in __connect_addr catches InvalidAuthorizationSpecificationError
(SQLSTATE 28000) and triggers an SSL retry for both sslmode=prefer and
sslmode=allow. However, wrong password failures raise InvalidPasswordError
(SQLSTATE 28P01), a subclass of InvalidAuthorizationSpecificationError. The retry
then connects with a different SSL state, which the server rejects with the misleading
pg_hba.conf error — hiding the real cause from the user.

Fix

Check if the caught exception is specifically InvalidPasswordError (28P01) before
deciding to retry. Wrong password errors are not SSL-related and retrying with
different SSL settings cannot fix them. Only pg_hba.conf rejections (28000) warrant
a retry.

Comment thread asyncpg/connect_utils.py Outdated
# Do not retry on wrong password (28P01) — the issue is credentials,
# not SSL negotiation. Only pg_hba.conf rejections (28000) warrant a retry.
if isinstance(exc, exceptions.InvalidPasswordError):
raise

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Early re-raise would break valid sslmode=allow/prefer fallback. PostgreSQL can use different authentication methods for hostssl and hostnossl. libpq performs that retry for every startup ErrorResponse, including 28P01. I pushed an improved fix that remembers the original password error and reraises it after all fallbacks have been exhausted.

@elprans
elprans enabled auto-merge (squash) September 19, 2026 06:14
@elprans
elprans merged commit 2d97947 into MagicStack:master Sep 19, 2026
89 of 94 checks passed
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.

sslmode=prefere surface misleading "no encryption" error when using a wrong password

2 participants