Skip to content
Open
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
24 changes: 19 additions & 5 deletions asyncpg/connect_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1052,11 +1052,25 @@ async def _connect_addr(
# first attempt
try:
return await __connect_addr(params, True, *args)
except _RetryConnectSignal:
pass
except _RetryConnectSignal as retry_exc:
first_error = retry_exc.__cause__
assert first_error is not None

# second attempt
return await __connect_addr(params_retry, False, *args)
try:
return await __connect_addr(params_retry, False, *args)
except (
exceptions.InvalidAuthorizationSpecificationError,
exceptions.ConnectionDoesNotExistError,
) as second_error:
# If the preferred attempt produced a useful authentication error,
# do not hide it behind a generic rejection from the fallback mode.
if (
isinstance(first_error, exceptions.InvalidPasswordError)
and not isinstance(second_error, exceptions.InvalidPasswordError)
):
raise first_error from None
raise


class _RetryConnectSignal(Exception):
Expand Down Expand Up @@ -1103,7 +1117,7 @@ async def __connect_addr(
except (
exceptions.InvalidAuthorizationSpecificationError,
exceptions.ConnectionDoesNotExistError, # seen on Windows
):
) as exc:
tr.close()

# retry=True here is a redundant check because we don't want to
Expand All @@ -1117,7 +1131,7 @@ async def __connect_addr(
# 2. First attempt with sslmode=prefer, ssl=ctx failed while the
# server claimed to support SSL (returning "S" for SSLRequest)
# (likely because pg_hba.conf rejected the connection)
raise _RetryConnectSignal()
raise _RetryConnectSignal() from exc

else:
# but will NOT retry if:
Expand Down
49 changes: 49 additions & 0 deletions tests/test_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1940,6 +1940,55 @@ async def verify_fails(sslmode, *, host='localhost', exn_type):
await verify_fails('verify-full',
exn_type=ssl.SSLError)

async def test_sslmode_preserves_password_error(self):
await self.con.execute(
"ALTER ROLE ssl_user PASSWORD 'correct_password'")

cases = (
('prefer', 'hostssl', 'hostnossl', False),
('allow', 'hostnossl', 'hostssl', True),
)
for sslmode, first_type, fallback_type, fallback_is_ssl in cases:
with self.subTest(sslmode=sslmode):
self.cluster.reset_hba()
for address in ('127.0.0.0/24', '::1/128'):
self.cluster.add_hba_entry(
type=first_type,
address=ipaddress.ip_network(address),
database='postgres', user='ssl_user',
auth_method='password')
self.cluster.reload()

connect_args = dict(
host='localhost',
database='postgres',
user='ssl_user',
password='wrong_password',
ssl=sslmode,
)

with self.assertRaisesRegex(
asyncpg.InvalidPasswordError,
'password authentication failed',
):
await self.connect(**connect_args)

# A password failure in the preferred mode must not prevent
# a valid, differently-authenticated fallback connection.
for address in ('127.0.0.0/24', '::1/128'):
self.cluster.add_hba_entry(
type=fallback_type,
address=ipaddress.ip_network(address),
database='postgres', user='ssl_user',
auth_method='trust')
self.cluster.reload()

con = await self.connect(**connect_args)
try:
self.assertEqual(con._protocol.is_ssl, fallback_is_ssl)
finally:
await con.close()

async def test_ssl_connection_default_context(self):
# XXX: uvloop artifact
old_handler = self.loop.get_exception_handler()
Expand Down
Loading