Skip to content

Fix parsing of IPv6 addresses in the connection URI #845

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 16, 2021
Merged
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
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 @@ -1796,7 +1796,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://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://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://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:///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