Skip to content

Commit

Permalink
Support urllib3 1.26.x and 2.x
Browse files Browse the repository at this point in the history
This changes the assert_fingerprint hack to more directly tell urllib3
that we'll assert the fingerprint ourselves to add support for pinning
root certificates, not only the leaves.
  • Loading branch information
sethmlarson authored and pquentin committed Sep 27, 2023
1 parent e32531a commit f68f2ae
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
26 changes: 22 additions & 4 deletions elastic_transport/_node/_urllib3_chain_certs.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,17 @@
__all__ = ["HTTPSConnectionPool"]


class HTTPSConnection(urllib3.connection.HTTPSConnection):
def connect(self) -> None:
super().connect()
# Hack to prevent a warning within HTTPSConnectionPool._validate_conn()
if self._elastic_assert_fingerprint:
self.is_verified = True


class HTTPSConnectionPool(urllib3.HTTPSConnectionPool):
ConnectionCls = HTTPSConnection

"""HTTPSConnectionPool implementation which supports ``assert_fingerprint``
on certificates within the chain instead of only the leaf cert using private
APIs in CPython 3.10+
Expand All @@ -60,13 +70,21 @@ def __init__(
f", should be one of '{valid_lengths}'"
)

if assert_fingerprint:
# Falsey but not None. This is a hack to skip fingerprinting by urllib3
# but still set 'is_verified=True' within HTTPSConnectionPool._validate_conn()
kwargs["assert_fingerprint"] = ""
if self._elastic_assert_fingerprint:
# Skip fingerprinting by urllib3 as we'll do it ourselves
kwargs["assert_fingerprint"] = None

super().__init__(*args, **kwargs)

def _new_conn(self) -> HTTPSConnection:
"""
Return a fresh :class:`urllib3.connection.HTTPSConnection`.
"""
conn = super()._new_conn()
# Tell our custom connection if we'll assert fingerprint ourselves
conn._elastic_assert_fingerprint = self._elastic_assert_fingerprint
return conn

def _validate_conn(self, conn: urllib3.connection.HTTPSConnection) -> None:
"""
Called right before a request is made, after the socket is created.
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
package_data={"elastic_transport": ["py.typed"]},
packages=packages,
install_requires=[
"urllib3>=1.26.2, <2",
"urllib3>=1.26.2, <3",
"certifi",
"dataclasses; python_version<'3.7'",
],
Expand Down

0 comments on commit f68f2ae

Please sign in to comment.