Skip to content

Commit

Permalink
Fix parsing of IPv6 addresses in the connection URI (MagicStack#845)
Browse files Browse the repository at this point in the history
Plain IPv6 addresses specified in square brackets in the connection URI
are now parsed correctly.

Fixes: MagicStack#838.
  • Loading branch information
elprans authored Nov 16, 2021
1 parent 03a3d18 commit f900b73
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 4 deletions.
20 changes: 17 additions & 3 deletions asyncpg/connect_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,25 @@ def _parse_hostlist(hostlist, port, *, unquote=False):
port = _validate_port_spec(hostspecs, port)

for i, hostspec in enumerate(hostspecs):
if not hostspec.startswith('/'):
addr, _, hostspec_port = hostspec.partition(':')
else:
if hostspec[0] == '/':
# Unix socket
addr = hostspec
hostspec_port = ''
elif hostspec[0] == '[':
# IPv6 address
m = re.match(r'(?:\[([^\]]+)\])(?::([0-9]+))?', hostspec)
if m:
addr = m.group(1)
hostspec_port = m.group(2)
else:
raise ValueError(
'invalid IPv6 address in the connection URI: {!r}'.format(
hostspec
)
)
else:
# IPv4 address
addr, _, hostspec_port = hostspec.partition(':')

if unquote:
addr = urllib.parse.unquote(addr)
Expand Down
8 changes: 7 additions & 1 deletion asyncpg/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1813,7 +1813,13 @@ async def connect(dsn=None, *,
.. note::
The URI must be *valid*, which means that all components must
be properly quoted with :py:func:`urllib.parse.quote`.
be properly quoted with :py:func:`urllib.parse.quote`, and
any literal IPv6 addresses must be enclosed in square brackets.
For example:
.. code-block:: text
postgres:https://dbuser@[fe80::1ff:fe23:4567:890a%25eth0]/dbname
:param host:
Database host address as one of the following:
Expand Down
28 changes: 28 additions & 0 deletions tests/test_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,34 @@ class TestConnectParams(tb.TestCase):
})
},

{
'name': 'dsn_ipv6_multi_host',
'dsn': 'postgresql:https://user@[2001:db8::1234%25eth0],[::1]/db',
'result': ([('2001:db8::1234%eth0', 5432), ('::1', 5432)], {
'database': 'db',
'user': 'user',
})
},

{
'name': 'dsn_ipv6_multi_host_port',
'dsn': 'postgresql:https://user@[2001:db8::1234]:1111,[::1]:2222/db',
'result': ([('2001:db8::1234', 1111), ('::1', 2222)], {
'database': 'db',
'user': 'user',
})
},

{
'name': 'dsn_ipv6_multi_host_query_part',
'dsn': 'postgresql:https:///db?user=user&host=[2001:db8::1234],[::1]',
'result': ([('2001:db8::1234', 5432), ('::1', 5432)], {
'database': 'db',
'user': 'user',
})
},


{
'name': 'dsn_combines_env_multi_host',
'env': {
Expand Down

0 comments on commit f900b73

Please sign in to comment.