Skip to content

Commit 0832782

Browse files
authored
Merge pull request #142 from abhinavrastogi2627/fix/http-client-verify
fix: honor TLS verification settings in HTTP clients
2 parents 207fb0b + 7c7d3f6 commit 0832782

10 files changed

Lines changed: 139 additions & 13 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ dev = [
5454
"respx>=0.22.0",
5555
"requests",
5656
"unasync>=0.6.0",
57+
"certifi>=2025.11.12",
5758
]
5859

5960
[tool.uv]

‎src/typesense/async_/api_call.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,12 @@
5151
ServiceUnavailable,
5252
TypesenseClientError,
5353
)
54-
from typesense.http_backend import ASYNC_CLIENT_TYPES, AsyncClientType, backend_errors
54+
from typesense.http_backend import (
55+
ASYNC_CLIENT_TYPES,
56+
AsyncClientType,
57+
backend_errors,
58+
verify_option,
59+
)
5560
from typesense.node_manager import NodeManager
5661
from typesense.request_handler import RequestHandler
5762

@@ -163,8 +168,8 @@ def __init__(
163168
config (Configuration): The configuration object for the Typesense client.
164169
http_client (httpx.AsyncClient | httpx2.AsyncClient, optional): A client
165170
to send requests with instead of the default httpx client. The
166-
connection pool settings in ``config`` are not applied to it, and it
167-
is not closed by ``aclose``.
171+
connection pool and ``verify`` settings in ``config`` are not
172+
applied to it, and it is not closed by ``aclose``.
168173
169174
Raises:
170175
TypeError: If ``http_client`` is not an httpx or httpx2 async client.
@@ -192,6 +197,7 @@ def __init__(
192197
max_connections=config.max_connections,
193198
max_keepalive_connections=config.max_keepalive_connections,
194199
),
200+
verify=verify_option(config.verify),
195201
)
196202

197203
async def __aenter__(self) -> "AsyncApiCall":

‎src/typesense/async_/client.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ def __init__(
102102
http_client (httpx.AsyncClient | httpx2.AsyncClient, optional):
103103
A client to send requests with instead of the default httpx client,
104104
e.g. an ``httpx2.AsyncClient`` (``pip install typesense[httpx2]``).
105-
The connection pool settings in ``config_dict`` are not applied to
106-
it, and the Typesense client does not close it.
105+
The connection pool and ``verify`` settings in ``config_dict`` are
106+
not applied to it, and the Typesense client does not close it.
107107
108108
Example:
109109
>>> config = {

‎src/typesense/configuration.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
- ConfigError: Custom exception for configuration-related errors.
1515
"""
1616

17+
import ssl
1718
import sys
1819
import time
1920

@@ -67,7 +68,9 @@ class ConfigDict(typing.TypedDict):
6768
healthcheck_interval_seconds (int): The interval in seconds between
6869
health checks.
6970
70-
verify (bool): Whether to verify the SSL certificate.
71+
verify (bool | str | ssl.SSLContext): Whether to verify the SSL
72+
certificate. Pass a CA bundle path or an ``ssl.SSLContext`` to verify
73+
against custom certificates. Defaults to ``True``.
7174
7275
timeout_seconds (int, deprecated): The connection timeout in seconds.
7376
@@ -108,7 +111,7 @@ class ConfigDict(typing.TypedDict):
108111
retry_interval_seconds: typing.NotRequired[float]
109112
interval_seconds: typing.NotRequired[int] # deprecated alias
110113
healthcheck_interval_seconds: typing.NotRequired[int]
111-
verify: typing.NotRequired[typing.Union[bool, str]]
114+
verify: typing.NotRequired[typing.Union[bool, str, ssl.SSLContext]]
112115
timeout_seconds: typing.NotRequired[int] # deprecated
113116
master_node: typing.NotRequired[typing.Union[str, NodeConfigDict]] # deprecated
114117
additional_headers: typing.NotRequired[typing.Dict[str, str]]
@@ -208,7 +211,7 @@ class Configuration:
208211
num_retries (int): The number of retries to attempt before failing.
209212
retry_interval_seconds (float): The interval in seconds between retries.
210213
healthcheck_interval_seconds (int): The interval in seconds between health checks.
211-
verify (bool): Whether to verify the SSL certificate.
214+
verify (bool | str | ssl.SSLContext): Whether to verify the SSL certificate.
212215
pool_timeout_seconds (float): How long to wait for a free pooled connection.
213216
max_connections (int): The maximum number of connections in the pool.
214217
max_keepalive_connections (int): The maximum number of idle pooled connections.

‎src/typesense/http_backend.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"""
1414

1515
import importlib
16+
import ssl
1617
import sys
1718
from types import ModuleType
1819

@@ -61,6 +62,26 @@ def backend_errors(name: str) -> typing.Tuple[typing.Type[Exception], ...]:
6162
return tuple(getattr(backend, name) for backend in _BACKENDS)
6263

6364

65+
def verify_option(
66+
verify: typing.Union[bool, str, ssl.SSLContext],
67+
) -> typing.Union[bool, ssl.SSLContext]:
68+
"""
69+
Return the ``verify`` value to build an httpx client with.
70+
71+
httpx deprecates CA bundle paths as ``verify`` values, so a path is loaded
72+
into an SSL context here instead.
73+
74+
Args:
75+
verify (bool | str | ssl.SSLContext): The configured ``verify`` setting.
76+
77+
Returns:
78+
bool | ssl.SSLContext: ``verify`` with a CA bundle path loaded.
79+
"""
80+
if isinstance(verify, str):
81+
return ssl.create_default_context(cafile=verify)
82+
return verify
83+
84+
6485
# Declared precisely for type checkers so ``isinstance`` narrows to the client
6586
# unions above; at runtime they only contain the backends that are installed.
6687
if typing.TYPE_CHECKING:

‎src/typesense/sync/api_call.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,12 @@
5151
ServiceUnavailable,
5252
TypesenseClientError,
5353
)
54-
from typesense.http_backend import CLIENT_TYPES, SyncClientType, backend_errors
54+
from typesense.http_backend import (
55+
CLIENT_TYPES,
56+
SyncClientType,
57+
backend_errors,
58+
verify_option,
59+
)
5560
from typesense.node_manager import NodeManager
5661
from typesense.request_handler import RequestHandler
5762

@@ -163,8 +168,8 @@ def __init__(
163168
config (Configuration): The configuration object for the Typesense client.
164169
http_client (httpx.Client | httpx2.Client, optional): A client
165170
to send requests with instead of the default httpx client. The
166-
connection pool settings in ``config`` are not applied to it, and it
167-
is not closed by ``close``.
171+
connection pool and ``verify`` settings in ``config`` are not
172+
applied to it, and it is not closed by ``close``.
168173
169174
Raises:
170175
TypeError: If ``http_client`` is not an httpx or httpx2 async client.
@@ -192,6 +197,7 @@ def __init__(
192197
max_connections=config.max_connections,
193198
max_keepalive_connections=config.max_keepalive_connections,
194199
),
200+
verify=verify_option(config.verify),
195201
)
196202

197203
def __enter__(self) -> "ApiCall":

‎src/typesense/sync/client.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ def __init__(
102102
http_client (httpx.Client | httpx2.Client, optional):
103103
A client to send requests with instead of the default httpx client,
104104
e.g. an ``httpx2.Client`` (``pip install typesense[httpx2]``).
105-
The connection pool settings in ``config_dict`` are not applied to
106-
it, and the Typesense client does not close it.
105+
The connection pool and ``verify`` settings in ``config_dict`` are
106+
not applied to it, and the Typesense client does not close it.
107107
108108
Example:
109109
>>> config = {

‎tests/api_call_ssl_test.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
"""Regression tests for TLS configuration in both HTTP clients."""
2+
3+
import ssl
4+
from pathlib import Path
5+
6+
import certifi
7+
import pytest
8+
from pytest_mock import MockerFixture
9+
10+
from typesense.async_.api_call import AsyncApiCall
11+
from typesense.configuration import Configuration
12+
from typesense.sync.api_call import ApiCall
13+
14+
15+
@pytest.fixture(params=[ApiCall, AsyncApiCall])
16+
def api_call_class(request):
17+
"""Exercise both the async source and the generated sync client."""
18+
return request.param
19+
20+
21+
def pool_ssl_context(api_call) -> ssl.SSLContext:
22+
"""Return the SSL context of the client's connection pool.
23+
24+
This reads private httpx 0.28 attributes and may need updating on upgrades.
25+
"""
26+
return api_call._client._transport._pool._ssl_context
27+
28+
29+
async def close_api_call(api_call):
30+
if isinstance(api_call, AsyncApiCall):
31+
await api_call.aclose()
32+
else:
33+
api_call.close()
34+
35+
36+
@pytest.mark.parametrize("verify", [True, False])
37+
async def test_verification_mode(fake_config, api_call_class, verify):
38+
"""The effective TLS context must honor explicit verification settings."""
39+
fake_config.verify = verify
40+
api_call = api_call_class(fake_config)
41+
try:
42+
ssl_context = pool_ssl_context(api_call)
43+
assert ssl_context.verify_mode == (
44+
ssl.CERT_REQUIRED if verify else ssl.CERT_NONE
45+
)
46+
assert ssl_context.check_hostname is verify
47+
finally:
48+
await close_api_call(api_call)
49+
50+
51+
async def test_ssl_context(fake_config, api_call_class):
52+
"""A configured SSL context must be used as is."""
53+
context = ssl.create_default_context()
54+
fake_config.verify = context
55+
api_call = api_call_class(fake_config)
56+
try:
57+
assert pool_ssl_context(api_call) is context
58+
finally:
59+
await close_api_call(api_call)
60+
61+
62+
async def test_custom_ca_bundle(
63+
fake_config: Configuration,
64+
api_call_class,
65+
tmp_path: Path,
66+
mocker: MockerFixture,
67+
):
68+
"""A configured CA bundle must reach the real SSL context builder."""
69+
ca_bundle = tmp_path / "custom-ca.pem"
70+
ca_bundle.write_bytes(Path(certifi.where()).read_bytes())
71+
fake_config.verify = str(ca_bundle)
72+
create_context = mocker.spy(ssl, "create_default_context")
73+
74+
api_call = api_call_class(fake_config)
75+
try:
76+
create_context.assert_any_call(cafile=str(ca_bundle))
77+
finally:
78+
await close_api_call(api_call)
79+
80+
81+
async def test_missing_ca_bundle(fake_config, api_call_class, tmp_path):
82+
"""An invalid CA path must fail instead of silently using default trust roots."""
83+
fake_config.verify = str(tmp_path / "missing-ca.pem")
84+
with pytest.raises(FileNotFoundError):
85+
api_call_class(fake_config)

‎tests/api_call_test.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -865,6 +865,7 @@ def test_client_uses_connection_pool_settings(
865865
client_mock.assert_called_once_with(
866866
timeout=httpx.Timeout(3.0, pool=1.5),
867867
limits=httpx.Limits(max_connections=200, max_keepalive_connections=50),
868+
verify=True,
868869
)
869870

870871

@@ -884,6 +885,7 @@ def test_async_client_uses_connection_pool_settings(
884885
client_mock.assert_called_once_with(
885886
timeout=httpx.Timeout(3.0, pool=1.5),
886887
limits=httpx.Limits(max_connections=200, max_keepalive_connections=50),
888+
verify=True,
887889
)
888890

889891

‎uv.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)