Skip to content

Commit 2d97947

Browse files
Fix password error reporting during SSL fallback (MagicStack#1331)
When performing `sslmode=allow/prefer` fallback retain a possible `InvalidPasswordError` from the first attempt. If the fallback also fails with a less-specific authorization error, report the original password failure. Fixes MagicStack#1306. Co-authored-by: Elvis Pranskevichus <[email protected]>
1 parent 6695db7 commit 2d97947

2 files changed

Lines changed: 68 additions & 5 deletions

File tree

‎asyncpg/connect_utils.py‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1052,11 +1052,25 @@ async def _connect_addr(
10521052
# first attempt
10531053
try:
10541054
return await __connect_addr(params, True, *args)
1055-
except _RetryConnectSignal:
1056-
pass
1055+
except _RetryConnectSignal as retry_exc:
1056+
first_error = retry_exc.__cause__
1057+
assert first_error is not None
10571058

10581059
# second attempt
1059-
return await __connect_addr(params_retry, False, *args)
1060+
try:
1061+
return await __connect_addr(params_retry, False, *args)
1062+
except (
1063+
exceptions.InvalidAuthorizationSpecificationError,
1064+
exceptions.ConnectionDoesNotExistError,
1065+
) as second_error:
1066+
# If the preferred attempt produced a useful authentication error,
1067+
# do not hide it behind a generic rejection from the fallback mode.
1068+
if (
1069+
isinstance(first_error, exceptions.InvalidPasswordError)
1070+
and not isinstance(second_error, exceptions.InvalidPasswordError)
1071+
):
1072+
raise first_error from None
1073+
raise
10601074

10611075

10621076
class _RetryConnectSignal(Exception):
@@ -1103,7 +1117,7 @@ async def __connect_addr(
11031117
except (
11041118
exceptions.InvalidAuthorizationSpecificationError,
11051119
exceptions.ConnectionDoesNotExistError, # seen on Windows
1106-
):
1120+
) as exc:
11071121
tr.close()
11081122

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

11221136
else:
11231137
# but will NOT retry if:

‎tests/test_connect.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1940,6 +1940,55 @@ async def verify_fails(sslmode, *, host='localhost', exn_type):
19401940
await verify_fails('verify-full',
19411941
exn_type=ssl.SSLError)
19421942

1943+
async def test_sslmode_preserves_password_error(self):
1944+
await self.con.execute(
1945+
"ALTER ROLE ssl_user PASSWORD 'correct_password'")
1946+
1947+
cases = (
1948+
('prefer', 'hostssl', 'hostnossl', False),
1949+
('allow', 'hostnossl', 'hostssl', True),
1950+
)
1951+
for sslmode, first_type, fallback_type, fallback_is_ssl in cases:
1952+
with self.subTest(sslmode=sslmode):
1953+
self.cluster.reset_hba()
1954+
for address in ('127.0.0.0/24', '::1/128'):
1955+
self.cluster.add_hba_entry(
1956+
type=first_type,
1957+
address=ipaddress.ip_network(address),
1958+
database='postgres', user='ssl_user',
1959+
auth_method='password')
1960+
self.cluster.reload()
1961+
1962+
connect_args = dict(
1963+
host='localhost',
1964+
database='postgres',
1965+
user='ssl_user',
1966+
password='wrong_password',
1967+
ssl=sslmode,
1968+
)
1969+
1970+
with self.assertRaisesRegex(
1971+
asyncpg.InvalidPasswordError,
1972+
'password authentication failed',
1973+
):
1974+
await self.connect(**connect_args)
1975+
1976+
# A password failure in the preferred mode must not prevent
1977+
# a valid, differently-authenticated fallback connection.
1978+
for address in ('127.0.0.0/24', '::1/128'):
1979+
self.cluster.add_hba_entry(
1980+
type=fallback_type,
1981+
address=ipaddress.ip_network(address),
1982+
database='postgres', user='ssl_user',
1983+
auth_method='trust')
1984+
self.cluster.reload()
1985+
1986+
con = await self.connect(**connect_args)
1987+
try:
1988+
self.assertEqual(con._protocol.is_ssl, fallback_is_ssl)
1989+
finally:
1990+
await con.close()
1991+
19431992
async def test_ssl_connection_default_context(self):
19441993
# XXX: uvloop artifact
19451994
old_handler = self.loop.get_exception_handler()

0 commit comments

Comments
 (0)