Skip to content

Commit 835d939

Browse files
authored
Add line with localhost to pgpass when unix sockets are detected (patroni#3139)
There are two cases when libpq may search for "localhost": 1. When host in the connection string is not specified and it is using default socket directory path. 2. When specified host matches default socket directory path. Since we don't know the value of default socket directory path and effectively can't detect the case 2, the best strategy to mitigate the problem would be to add "localhost" if we detected a "host" be a unix socket directory (it starts with '/' character). Close patroni#3134
1 parent 8cdb0c2 commit 835d939

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

patroni/postgresql/config.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -911,10 +911,12 @@ def escape(value: Any) -> str:
911911
return re.sub(r'([:\\])', r'\\\1', str(value))
912912

913913
# 'host' could be several comma-separated hostnames, in this case we need to write on pgpass line per host
914-
hosts = map(escape, filter(None, map(str.strip,
915-
(record.get('host', '') or '*').split(',')))) # pyright: ignore [reportUnknownArgumentType]
914+
hosts = [escape(host) for host in filter(None, map(str.strip,
915+
(record.get('host', '') or '*').split(',')))] # pyright: ignore [reportUnknownArgumentType]
916+
if any(host.startswith('/') for host in hosts) and 'localhost' not in hosts:
917+
hosts.append('localhost')
916918
record = {n: escape(record.get(n) or '*') for n in ('port', 'user', 'password')}
917-
return '\n'.join('{host}:{port}:*:{user}:{password}'.format(**record, host=host) for host in hosts)
919+
return ''.join('{host}:{port}:*:{user}:{password}\n'.format(**record, host=host) for host in hosts)
918920

919921
def write_pgpass(self, record: Dict[str, Any]) -> Dict[str, str]:
920922
"""Maybe creates :attr:`_passfile` based on connection parameters.

tests/test_postgresql.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,10 @@ def test_write_pgpass(self):
262262
self.p.config.write_pgpass({'host': 'localhost', 'port': '5432', 'user': 'foo'})
263263
self.p.config.write_pgpass({'host': 'localhost', 'port': '5432', 'user': 'foo', 'password': 'bar'})
264264

265+
def test__pgpass_content(self):
266+
pgpass = self.p.config._pgpass_content({'host': '/tmp', 'port': '5432', 'user': 'foo', 'password': 'bar'})
267+
self.assertEqual(pgpass, "/tmp:5432:*:foo:bar\nlocalhost:5432:*:foo:bar\n")
268+
265269
def test_checkpoint(self):
266270
with patch.object(MockCursor, 'fetchone', Mock(return_value=(True, ))):
267271
self.assertEqual(self.p.checkpoint({'user': 'postgres'}), 'is_in_recovery=true')

0 commit comments

Comments
 (0)