Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions api/core/network.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,109 @@
import errno
import http.client
import ipaddress
import socket
import ssl
from collections.abc import Iterator

import requests

# RFC 6598 carrier-grade NAT; not caught by ipaddress.is_private.
_SHARED_ADDRESS_SPACE = ipaddress.ip_network("100.64.0.0/10")

# OpenSSL 3+ certificate verification results, from `include/openssl/x509_vfy.h`.
# Python exposes the numeric `verify_code`, but not the constant names.
_CERT_VERIFY_ERROR_NAMES = {
2: "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT",
3: "X509_V_ERR_UNABLE_TO_GET_CRL",
4: "X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE",
5: "X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE",
6: "X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
7: "X509_V_ERR_CERT_SIGNATURE_FAILURE",
8: "X509_V_ERR_CRL_SIGNATURE_FAILURE",
9: "X509_V_ERR_CERT_NOT_YET_VALID",
10: "X509_V_ERR_CERT_HAS_EXPIRED",
11: "X509_V_ERR_CRL_NOT_YET_VALID",
12: "X509_V_ERR_CRL_HAS_EXPIRED",
13: "X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD",
14: "X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD",
15: "X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD",
16: "X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD",
18: "X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT",
19: "X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN",
20: "X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
21: "X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE",
22: "X509_V_ERR_CERT_CHAIN_TOO_LONG",
23: "X509_V_ERR_CERT_REVOKED",
24: "X509_V_ERR_NO_ISSUER_PUBLIC_KEY",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This labels verify_code == 24 incorrectly on Python builds linked to OpenSSL 1.1.1, where code 24 is X509_V_ERR_INVALID_CA. Select the name based on ssl.OPENSSL_VERSION_INFO so invalid-CA failures are not misreported.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At api/core/network.py, line 37:

<comment>This labels `verify_code == 24` incorrectly on Python builds linked to OpenSSL 1.1.1, where code 24 is `X509_V_ERR_INVALID_CA`. Select the name based on `ssl.OPENSSL_VERSION_INFO` so invalid-CA failures are not misreported.</comment>

<file context>
@@ -10,63 +10,74 @@
+    21: "X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE",
+    22: "X509_V_ERR_CERT_CHAIN_TOO_LONG",
+    23: "X509_V_ERR_CERT_REVOKED",
+    24: "X509_V_ERR_NO_ISSUER_PUBLIC_KEY",
+    25: "X509_V_ERR_PATH_LENGTH_EXCEEDED",
+    26: "X509_V_ERR_INVALID_PURPOSE",
</file context>
Suggested change
24: "X509_V_ERR_NO_ISSUER_PUBLIC_KEY",
24: "X509_V_ERR_NO_ISSUER_PUBLIC_KEY" if ssl.OPENSSL_VERSION_INFO >= (3, 0, 0) else "X509_V_ERR_INVALID_CA",

25: "X509_V_ERR_PATH_LENGTH_EXCEEDED",
26: "X509_V_ERR_INVALID_PURPOSE",
27: "X509_V_ERR_CERT_UNTRUSTED",
28: "X509_V_ERR_CERT_REJECTED",
62: "X509_V_ERR_HOSTNAME_MISMATCH",
64: "X509_V_ERR_IP_ADDRESS_MISMATCH",
66: "X509_V_ERR_EE_KEY_TOO_SMALL",
67: "X509_V_ERR_CA_KEY_TOO_SMALL",
68: "X509_V_ERR_CA_MD_TOO_WEAK",
79: "X509_V_ERR_INVALID_CA",
}

# getaddrinfo() returns EAI_* codes, which don't overlap with errno.
_GETADDRINFO_ERROR_NAMES = {
getattr(socket, name): name for name in dir(socket) if name.startswith("EAI_")
}


def get_request_error_code(error: requests.RequestException) -> str | None:
"""Return the POSIX error name, or the OpenSSL certificate verification
error name, for a request that failed without an HTTP response."""
if isinstance(error, requests.exceptions.Timeout):
return "ETIMEDOUT"
for exc in _iter_exception_chain(error):
if code := _get_exception_error_code(exc):
return code
return None


def _get_exception_error_code(exc: BaseException) -> str | None:
# SSL errors subclass OSError, with an OpenSSL-specific errno.
if isinstance(exc, ssl.SSLCertVerificationError):
return _CERT_VERIFY_ERROR_NAMES.get(exc.verify_code, "EPROTO")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: An unmapped certificate verification code is reported as EPROTO, which tells the user this is a protocol error rather than a trust failure. Return None for unmapped verify codes so the code is omitted, as the commit message describes.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At api/core/network.py, line 70:

<comment>An unmapped certificate verification code is reported as `EPROTO`, which tells the user this is a protocol error rather than a trust failure. Return `None` for unmapped verify codes so the code is omitted, as the commit message describes.</comment>

<file context>
@@ -10,63 +10,74 @@
     # SSL errors subclass OSError, with an OpenSSL-specific errno.
     if isinstance(exc, ssl.SSLCertVerificationError):
-        return _CERT_VERIFY_ERROR_CODES.get(exc.verify_code, "EPROTO")
+        return _CERT_VERIFY_ERROR_NAMES.get(exc.verify_code, "EPROTO")
     if isinstance(exc, ssl.SSLError):
         return "EPROTO"
</file context>
Suggested change
return _CERT_VERIFY_ERROR_NAMES.get(exc.verify_code, "EPROTO")
return _CERT_VERIFY_ERROR_NAMES.get(exc.verify_code)

if isinstance(exc, ssl.SSLError):
return "EPROTO"
if isinstance(exc, socket.gaierror) and exc.errno is not None:
return _GETADDRINFO_ERROR_NAMES.get(exc.errno)
if isinstance(exc, OSError) and exc.errno is not None:
if name := errno.errorcode.get(exc.errno):
return name
# A socket timeout, e.g. connecting to a proxy, without an errno.
if isinstance(exc, TimeoutError):
return "ETIMEDOUT"
# e.g. `RemoteDisconnected`: the peer closed without responding.
if isinstance(exc, ConnectionResetError):
return "ECONNRESET"
# The peer responded with something other than HTTP.
if isinstance(exc, http.client.HTTPException):
return "EPROTO"
return None


def _iter_exception_chain(error: BaseException) -> Iterator[BaseException]:
# requests and urllib3 wrap the underlying error in `reason` and
# `original_error` as well as in the standard `__cause__`/`__context__`.
seen: set[int] = set()
pending: list[BaseException] = [error]
while pending:
exc = pending.pop(0)
if id(exc) in seen:
continue
seen.add(id(exc))
yield exc
for attr in ("reason", "original_error", "__cause__", "__context__"):
linked = getattr(exc, attr, None)
if isinstance(linked, BaseException):
pending.append(linked)
pending.extend(arg for arg in exc.args if isinstance(arg, BaseException))


def is_internal_address(
hostname: str,
Expand Down
225 changes: 225 additions & 0 deletions api/tests/unit/core/test_network.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import errno
import http.client
import socket
import ssl
from typing import TypeVar

import pytest
import requests
from urllib3 import HTTPSConnectionPool
from urllib3.connection import HTTPSConnection
from urllib3.exceptions import (
ConnectTimeoutError,
MaxRetryError,
NameResolutionError,
NewConnectionError,
ProtocolError,
)
from urllib3.exceptions import ProxyError as Urllib3ProxyError
from urllib3.exceptions import SSLError as Urllib3SSLError

from core.network import get_request_error_code

_E = TypeVar("_E", bound=BaseException)

# Constructing these doesn't open a connection.
_POOL = HTTPSConnectionPool("example.com")
_CONN = HTTPSConnection("example.com")


def _caused_by(error: _E, cause: BaseException) -> _E:
error.__cause__ = cause
return error


def _max_retries(reason: Exception) -> MaxRetryError:
# How requests' HTTPAdapter receives connection failures from urllib3.
return MaxRetryError(_POOL, "/", reason=reason)


def _cert_verify_error(verify_code: int) -> ssl.SSLCertVerificationError:
error = ssl.SSLCertVerificationError(1, "certificate verify failed")
error.verify_code = verify_code
return error


@pytest.mark.parametrize(
"error, expected_code",
[
(
requests.exceptions.ConnectionError(
_max_retries(
_caused_by(
NewConnectionError(_CONN, "Failed to establish a connection"),
ConnectionRefusedError(errno.ECONNREFUSED, "refused"),
)
)
),
"ECONNREFUSED",
),
(
requests.exceptions.ConnectionError(
_max_retries(
_caused_by(
NewConnectionError(_CONN, "Failed to establish a connection"),
OSError(errno.EHOSTUNREACH, "no route to host"),
)
)
),
"EHOSTUNREACH",
),
(
requests.exceptions.ConnectionError(
_max_retries(
_caused_by(
NameResolutionError(
"example.com",
_CONN,
socket.gaierror(socket.EAI_NONAME, "Name not known"),
),
socket.gaierror(socket.EAI_NONAME, "Name not known"),
)
)
),
"EAI_NONAME",
),
(
requests.exceptions.ConnectionError(
_max_retries(
_caused_by(
NameResolutionError(
"example.com",
_CONN,
socket.gaierror(socket.EAI_AGAIN, "Temporary failure"),
),
socket.gaierror(socket.EAI_AGAIN, "Temporary failure"),
)
)
),
"EAI_AGAIN",
),
(
requests.exceptions.ConnectionError(
_max_retries(
_caused_by(
NameResolutionError(
"example.com",
_CONN,
socket.gaierror(socket.EAI_FAIL, "Non-recoverable"),
),
socket.gaierror(socket.EAI_FAIL, "Non-recoverable"),
)
)
),
"EAI_FAIL",
),
(
requests.exceptions.ConnectionError(
ProtocolError(
"Connection aborted.",
ConnectionResetError(errno.ECONNRESET, "reset by peer"),
)
),
"ECONNRESET",
),
(
requests.exceptions.ConnectionError(
ProtocolError(
"Connection aborted.",
http.client.RemoteDisconnected("closed without response"),
)
),
"ECONNRESET",
),
(
requests.exceptions.ConnectionError(
ProtocolError("Connection aborted.", http.client.BadStatusLine("SSH"))
),
"EPROTO",
),
(
requests.exceptions.SSLError(
_max_retries(Urllib3SSLError(_cert_verify_error(20)))
),
"X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
),
(
requests.exceptions.SSLError(
_max_retries(Urllib3SSLError(_cert_verify_error(10)))
),
"X509_V_ERR_CERT_HAS_EXPIRED",
),
(
requests.exceptions.SSLError(
_max_retries(Urllib3SSLError(_cert_verify_error(62)))
),
"X509_V_ERR_HOSTNAME_MISMATCH",
),
(
requests.exceptions.SSLError(
_max_retries(Urllib3SSLError(_cert_verify_error(24)))
),
"X509_V_ERR_NO_ISSUER_PUBLIC_KEY",
),
(
requests.exceptions.SSLError(
_max_retries(Urllib3SSLError(_cert_verify_error(79)))
),
"X509_V_ERR_INVALID_CA",
),
(
requests.exceptions.SSLError(
_max_retries(Urllib3SSLError(_cert_verify_error(-1)))
),
"EPROTO",
),
(
requests.exceptions.SSLError(
_max_retries(
Urllib3SSLError(ssl.SSLError(1, "[SSL] wrong version number"))
)
),
"EPROTO",
),
(
requests.exceptions.ProxyError(
_max_retries(
Urllib3ProxyError(
"Unable to connect to proxy",
_caused_by(
NewConnectionError(_CONN, "Failed to establish"),
ConnectionRefusedError(errno.ECONNREFUSED, "refused"),
),
)
)
),
"ECONNREFUSED",
),
(
requests.exceptions.ProxyError(
_max_retries(
Urllib3ProxyError(
"Unable to connect to proxy",
_caused_by(
ConnectTimeoutError(_CONN, "Connection timed out"),
TimeoutError("timed out"),
),
)
)
),
"ETIMEDOUT",
),
(requests.exceptions.ConnectTimeout("timed out"), "ETIMEDOUT"),
(requests.exceptions.ReadTimeout("timed out"), "ETIMEDOUT"),
(requests.exceptions.RequestException("unexpected"), None),
],
)
def test_get_request_error_code__request_failed__returns_expected_code(
error: requests.RequestException,
expected_code: str | None,
) -> None:
# Given / When
code = get_request_error_code(error)

# Then
assert code == expected_code
38 changes: 38 additions & 0 deletions api/tests/unit/webhooks/test_unit_webhooks.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import errno
import hashlib
import hmac
import json
Expand Down Expand Up @@ -608,6 +609,43 @@ def test_send_test_webhook__request_exception__returns_error_response(
}


def test_send_test_webhook__connection_refused__returns_error_code_without_details(
mocker: MockerFixture,
admin_client: APIClient,
organisation: Organisation,
) -> None:
# Given
mocker.patch(
"core.network.socket.getaddrinfo",
return_value=[(socket.AF_INET, None, None, None, ("93.184.216.34", 0))],
)
refused = ConnectionRefusedError(
errno.ECONNREFUSED, "Connection refused by 10.1.2.3:7000"
)
error = ConnectionError("HTTPSConnectionPool(host='example.com', port=7000)")
error.__cause__ = refused
mocker.patch("webhooks.webhooks.requests.post", side_effect=error)

url = reverse("api-v1:webhooks:webhooks-test")
data = {
"webhook_url": "https://example.com:7000/hook",
"scope": {"type": "organisation", "id": organisation.id},
}

# When
response = admin_client.post(
url, data=json.dumps(data), content_type="application/json"
)

# Then
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json() == {
"detail": "Could not connect to webhook URL",
"body": "Please check the URL, and ensure it is valid and accessible from the server.",
"code": "ECONNREFUSED",
}


def test_send_test_webhook__empty_webhook_url__returns_bad_request(
admin_client: APIClient,
organisation: Organisation,
Expand Down
Loading
Loading