Skip to content

Commit

Permalink
Raise http.client.connect audit events in HTTPConnection (#2859)
Browse files Browse the repository at this point in the history
  • Loading branch information
CCLDArjun committed Jul 18, 2023
1 parent c056eb3 commit 0a375d1
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/2757.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed ``urllib3.connection.HTTPConnection`` to raise the ``http.client.connect`` audit event to have the same behavior as the standard library HTTP client
7 changes: 7 additions & 0 deletions src/urllib3/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
import re
import socket
import sys
import typing
import warnings
from http.client import HTTPConnection as _HTTPConnection
Expand Down Expand Up @@ -76,6 +77,8 @@ class BaseSSLError(BaseException): # type: ignore[no-redef]

_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")

_HAS_SYS_AUDIT = hasattr(sys, "audit")


class HTTPConnection(_HTTPConnection):
"""
Expand Down Expand Up @@ -216,6 +219,10 @@ def _new_conn(self) -> socket.socket:
self, f"Failed to establish a new connection: {e}"
) from e

# Audit hooks are only available in Python 3.8+
if _HAS_SYS_AUDIT:
sys.audit("http.client.connect", self, self.host, self.port)

return sock

def set_tunnel(
Expand Down
15 changes: 15 additions & 0 deletions test/with_dummyserver/test_connection.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from __future__ import annotations

import sys
import typing
from http.client import ResponseNotReady
from unittest import mock

import pytest

Expand Down Expand Up @@ -33,6 +35,19 @@ def test_returns_urllib3_HTTPResponse(pool: HTTPConnectionPool) -> None:
assert isinstance(response, HTTPResponse)


@pytest.mark.skipif(not hasattr(sys, "audit"), reason="requires python 3.8+")
@mock.patch("urllib3.connection.sys.audit")
def test_audit_event(audit_mock: mock.Mock, pool: HTTPConnectionPool) -> None:
conn = pool._get_conn()
conn.request("GET", "/")
audit_mock.assert_any_call("http.client.connect", conn, conn.host, conn.port)
# Ensure the event is raised only once.
connect_events = [
call for call in audit_mock.mock_calls if call.args[0] == "http.client.connect"
]
assert len(connect_events) == 1


def test_does_not_release_conn(pool: HTTPConnectionPool) -> None:
conn = pool._get_conn()

Expand Down

0 comments on commit 0a375d1

Please sign in to comment.