Skip to content

Commit ed65ad9

Browse files
fix: libpq's TLS parameters in the DSN reach asyncpg (#80)
A postgresql:// DSN with ?sslmode=require crashed the CLI with "connect() got an unexpected keyword argument 'sslmode'". The CLI rewrites such a DSN to asyncpg, and SQLAlchemy passes the URL's parameters to asyncpg.connect() as keywords; asyncpg understands sslmode, sslrootcert and the rest of libpq's TLS parameters only inside a DSN it parses itself. They now leave the URL and travel as connect_args={"dsn": "postgresql://?sslmode=..."}, so asyncpg reads them the way libpq does while host, user and database still come from the URL. Parameters are split as written, never re-encoded, and a DSN that names its own driver is left alone. An e2e test plans over TLS with sslmode=require against a server that speaks it; on the 1.6.0 image it fails with the TypeError. Closes #73
1 parent 1353ed8 commit ed65ad9

8 files changed

Lines changed: 165 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## 1.6.2 — a DSN with sslmode
9+
10+
A `postgresql://` DSN carrying `?sslmode=require` crashed the CLI before it connected:
11+
`TypeError: connect() got an unexpected keyword argument 'sslmode'`
12+
([#73](https://github.com/bedrock-python/pg-partsmith/issues/73)). The CLI drives such a
13+
DSN with asyncpg, and SQLAlchemy hands the URL's parameters to `asyncpg.connect()` as
14+
keywords; asyncpg reads `sslmode`, `sslrootcert` and the rest of libpq's TLS parameters
15+
only from a DSN it parses itself. They now travel to it as one, so a DSN copied from psql
16+
or a managed PostgreSQL console works as written, `sslrootcert` included. Everything else
17+
in the DSN stays exactly as it was.
818
## [1.6.1](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.6.0...pg-partsmith-v1.6.1) (2026-09-29)
919

1020

‎docs/guide/cli.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,18 @@ arrive as files under `/run/secrets`.
6969
A DSN naming no driver (`postgresql://…`) is driven with asyncpg, which the `cli` extra
7070
installs. One that names its own (`postgresql+psycopg://…`) is left exactly as written.
7171

72+
libpq's TLS parameters work in a DSN naming no driver the way psql reads them:
73+
`sslmode`, `sslrootcert`, `sslcert`, `sslkey`, `sslcrl`, `sslpassword`, `sslnegotiation`
74+
and the protocol-version bounds are handed to asyncpg to parse itself, so a DSN copied from
75+
a managed PostgreSQL console works unchanged:
76+
77+
```bash
78+
export PG_PARTSMITH_DSN='postgresql://app:secret@db.example.com/app?sslmode=verify-full&sslrootcert=/etc/ssl/ca.pem'
79+
```
80+
81+
In a DSN that names `postgresql+asyncpg://` itself, TLS is SQLAlchemy's `?ssl=require`
82+
spelling, as it always was.
83+
7284
## Exit codes
7385

7486
A CronJob and a CI step read the exit code and nothing else, so the codes are worth

‎pg_partsmith/cli/loader.py‎

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
"DSN_FILE_ENV_VAR",
2727
"ConfigError",
2828
"async_url",
29+
"asyncpg_connect_args",
2930
"load_document",
3031
"load_plans",
3132
"load_python_hooks",
@@ -130,19 +131,74 @@ def _dsn_from_file() -> str | None:
130131
raise ConfigError(msg) from exc
131132

132133

134+
# libpq's TLS parameters. asyncpg reads every one of them the way libpq does,
135+
# but only from a DSN it parses itself: SQLAlchemy hands the parameters of its
136+
# URL to asyncpg.connect() as keywords, and asyncpg has no keyword by these
137+
# names -- a DSN copied from psql with ?sslmode=require failed with a TypeError.
138+
_LIBPQ_TLS_PARAMETERS = frozenset(
139+
{
140+
"sslmode",
141+
"sslcert",
142+
"sslkey",
143+
"sslrootcert",
144+
"sslcrl",
145+
"sslpassword",
146+
"sslnegotiation",
147+
"ssl_min_protocol_version",
148+
"ssl_max_protocol_version",
149+
}
150+
)
151+
152+
133153
def async_url(dsn: str) -> str:
134154
"""The DSN with an async driver named, since that is what the CLI drives.
135155
136156
``postgresql://…`` means psycopg2 to SQLAlchemy, which cannot be driven
137157
asynchronously; a DSN that already names its driver is left exactly as it
138158
is, so ``postgresql+psycopg://`` keeps working for whoever installed it.
159+
libpq's TLS parameters leave the URL on the way, for
160+
:func:`asyncpg_connect_args` to hand to asyncpg.
139161
"""
140-
scheme, separator, rest = dsn.partition("://")
141-
if not separator or "+" in scheme:
162+
rewritten = _asyncpg_rewrite(dsn)
163+
if rewritten is None:
142164
return dsn
143-
if scheme in {"postgresql", "postgres"}:
144-
return f"postgresql+asyncpg://{rest}"
145-
return dsn
165+
rest, _ = rewritten
166+
return f"postgresql+asyncpg://{rest}"
167+
168+
169+
def asyncpg_connect_args(dsn: str) -> dict[str, Any]:
170+
"""The ``connect_args`` that carry a DSN's libpq TLS parameters to asyncpg.
171+
172+
They travel as a DSN of their own, ``postgresql://?sslmode=…``, which
173+
asyncpg parses the way libpq would -- ``sslrootcert`` and the rest
174+
included -- while host, user and database still come from the URL.
175+
Empty when the DSN names its own driver or carries no TLS parameters.
176+
"""
177+
rewritten = _asyncpg_rewrite(dsn)
178+
if rewritten is None or not rewritten[1]:
179+
return {}
180+
return {"dsn": "postgresql://?" + "&".join(rewritten[1])}
181+
182+
183+
def _asyncpg_rewrite(dsn: str) -> tuple[str, list[str]] | None:
184+
"""Split a DSN the CLI will hand to asyncpg: the rest, and its TLS query parameters.
185+
186+
None for a DSN that is not rewritten -- one naming its driver, or not a
187+
``postgresql://`` URL at all. Parameters are split as written, never
188+
decoded and encoded again, so everything that stays reads exactly as it did.
189+
"""
190+
scheme, separator, rest = dsn.partition("://")
191+
if not separator or "+" in scheme or scheme not in {"postgresql", "postgres"}:
192+
return None
193+
base, question, query = rest.partition("?")
194+
if not question:
195+
return rest, []
196+
kept: list[str] = []
197+
tls: list[str] = []
198+
for parameter in query.split("&"):
199+
name = parameter.partition("=")[0]
200+
(tls if name in _LIBPQ_TLS_PARAMETERS else kept).append(parameter)
201+
return (f"{base}?{'&'.join(kept)}" if kept else base), tls
146202

147203

148204
def select_configs(document: PartitionsDocument, tables: tuple[str, ...]) -> tuple[TablePartitionConfig, ...]:

‎pg_partsmith/cli/main.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
DSN_FILE_ENV_VAR,
5151
ConfigError,
5252
async_url,
53+
asyncpg_connect_args,
5354
load_document,
5455
load_plans,
5556
load_python_hooks,
@@ -555,9 +556,9 @@ async def _run(invocation: _Invocation) -> CommandResult:
555556
document = load_document(invocation.config)
556557
_check_python_hooks(document, invocation.config)
557558
configs = select_configs(document, invocation.tables)
558-
url = async_url(resolve_dsn(document, override=invocation.dsn))
559+
dsn = resolve_dsn(document, override=invocation.dsn)
559560

560-
engine = create_async_engine(url)
561+
engine = create_async_engine(async_url(dsn), connect_args=asyncpg_connect_args(dsn))
561562
try:
562563
try:
563564
hooks = _hooks(

‎tests/e2e/conftest.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,16 @@
1818
from testcontainers.core.network import Network
1919
from testcontainers.postgres import PostgresContainer
2020

21-
from tests.e2e.support import DB_ALIAS, DB_NAME, DB_PASSWORD, DB_USER, Image
21+
from tests.e2e.support import (
22+
DB_ALIAS,
23+
DB_NAME,
24+
DB_PASSWORD,
25+
DB_USER,
26+
TLS_DB_ALIAS,
27+
TLS_POSTGRES_COMMAND,
28+
TLS_POSTGRES_IMAGE,
29+
Image,
30+
)
2231

2332
if TYPE_CHECKING:
2433
from collections.abc import Iterator
@@ -73,6 +82,19 @@ def postgres(network: Network, postgres_image: str) -> Iterator[PostgresContaine
7382
yield running
7483

7584

85+
@pytest.fixture(scope="session")
86+
def tls_postgres(network: Network) -> Iterator[PostgresContainer]:
87+
"""A database that speaks TLS: what a managed PostgreSQL looks like to ``sslmode=require``."""
88+
container = (
89+
PostgresContainer(TLS_POSTGRES_IMAGE, username=DB_USER, password=DB_PASSWORD, dbname=DB_NAME)
90+
.with_command(TLS_POSTGRES_COMMAND)
91+
.with_network(network)
92+
.with_network_aliases(TLS_DB_ALIAS)
93+
)
94+
with container as running:
95+
yield running
96+
97+
7698
@pytest.fixture(scope="session")
7799
def image(docker_client: docker.DockerClient, image_name: str, network: Network) -> Image:
78100
return Image(docker_client, image_name, network.name)

‎tests/e2e/support.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@
2828
INTERNAL_DSN = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_ALIAS}:5432/{DB_NAME}"
2929
DOCUMENT_PATH = "/etc/partitions.json"
3030

31+
# A server that speaks TLS. The Debian image ships a snakeoil certificate its
32+
# postgres user can read, so TLS is a command line away and needs no key of ours.
33+
TLS_DB_ALIAS = "tls-db"
34+
TLS_DSN = f"postgresql://{DB_USER}:{DB_PASSWORD}@{TLS_DB_ALIAS}:5432/{DB_NAME}"
35+
TLS_POSTGRES_IMAGE = "postgres:17"
36+
TLS_POSTGRES_COMMAND = (
37+
"postgres -c ssl=on -c ssl_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem "
38+
"-c ssl_key_file=/etc/ssl/private/ssl-cert-snakeoil.key"
39+
)
40+
3141
# A hook that holds the run -- and the table's lock -- for as long as a test
3242
# needs it held. The image has no `sleep`; it has the interpreter.
3343
SLEEPING_HOOK = ["/opt/venv/bin/python", "-c", "import time; time.sleep(120)"]

‎tests/e2e/test_run.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
DOCUMENT_PATH,
1616
INTERNAL_DSN,
1717
SLEEPING_HOOK,
18+
TLS_DSN,
1819
expired_partition,
1920
finish,
2021
holds_advisory_lock,
@@ -175,6 +176,21 @@ def test__a_password_the_server_rejects__is_exit_5_and_not_a_traceback(image: Im
175176
assert "Traceback" not in outcome.stderr
176177

177178

179+
def test__a_dsn_asking_for_tls__plans_over_tls(image: Image, tls_postgres: PostgresContainer, tmp_path: Path) -> None:
180+
# A DSN the way psql and managed providers write it, against an image that
181+
# ships asyncpg alone. `require` refuses a connection that is not encrypted,
182+
# so a plan at all is a plan made over TLS.
183+
table = partitioned_table(tls_postgres)
184+
document = write_document(tmp_path / "partitions.json", table=table)
185+
186+
outcome = image.run(
187+
"plan", "-c", DOCUMENT_PATH, env={"PG_PARTSMITH_DSN": f"{TLS_DSN}?sslmode=require"}, mounts=_mounted(document)
188+
)
189+
190+
assert outcome.code == 0, outcome.stderr
191+
assert f"CREATE public.{table}__" in outcome.stdout
192+
193+
178194
# ── Hooks, stops and overlapping runs ─────────────────────────────────────────
179195

180196

‎tests/unit/test_cli.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
DSN_FILE_ENV_VAR,
2828
ConfigError,
2929
async_url,
30+
asyncpg_connect_args,
3031
load_document,
3132
load_plans,
3233
load_python_hooks,
@@ -222,6 +223,33 @@ def test__async_url__a_dsn_naming_its_driver__is_left_exactly_as_it_is() -> None
222223
assert async_url("not a url") == "not a url"
223224

224225

226+
def test__async_url__libpq_tls_parameters__leave_the_url_and_the_rest_stays_as_written() -> None:
227+
# Arrange
228+
dsn = "postgresql://app@db/app?application_name=x&sslmode=verify-full&sslrootcert=/ca.pem&options=-c%20a%3Db"
229+
230+
# Act / Assert
231+
assert async_url(dsn) == "postgresql+asyncpg://app@db/app?application_name=x&options=-c%20a%3Db"
232+
assert async_url("postgresql://app@db/app?sslmode=require") == "postgresql+asyncpg://app@db/app"
233+
234+
235+
def test__asyncpg_connect_args__carries_the_tls_parameters_in_a_dsn_asyncpg_parses() -> None:
236+
# Arrange
237+
dsn = "postgresql://app:s3cr%40t@db:5432/app?sslmode=verify-full&connect_timeout=5&sslrootcert=/ca.pem"
238+
239+
# Act / Assert
240+
assert asyncpg_connect_args(dsn) == {"dsn": "postgresql://?sslmode=verify-full&sslrootcert=/ca.pem"}
241+
242+
243+
def test__asyncpg_connect_args__nothing_to_carry__is_empty() -> None:
244+
# Act / Assert -- no TLS parameters, and a DSN that names its own driver keeps its own
245+
assert asyncpg_connect_args("postgresql://app@db/app?application_name=x") == {}
246+
assert asyncpg_connect_args("postgresql+asyncpg://app@db/app?ssl=require") == {}
247+
assert (
248+
async_url("postgresql+asyncpg://app@db/app?sslmode=require")
249+
== "postgresql+asyncpg://app@db/app?sslmode=require"
250+
)
251+
252+
225253
# ── Narrowing to tables ─────────────────────────────────────────────────────────
226254

227255

@@ -774,8 +802,8 @@ def _stoppable(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, signum: int) ->
774802
config = _write(tmp_path, "partitions.json", json.dumps(payload))
775803
engines: list[_Recording] = []
776804

777-
def recording(url: str) -> _Recording:
778-
engine = _Recording(cli.create_async_engine.__wrapped__(url)) # type: ignore[attr-defined]
805+
def recording(url: str, **kwargs: Any) -> _Recording:
806+
engine = _Recording(cli.create_async_engine.__wrapped__(url, **kwargs)) # type: ignore[attr-defined]
779807
engines.append(engine)
780808
return engine
781809

0 commit comments

Comments
 (0)