Repository navigation
feat(webhooks): Return an error code when a webhook test can't connect #9019
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
khvn26
wants to merge
3
commits into
main
Choose a base branch
from
fix/webhook-test-error-reason
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+387
−10
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||||||
| 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") | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: An unmapped certificate verification code is reported as Prompt for AI agents
Suggested change
|
||||||
| 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, | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 == 24incorrectly on Python builds linked to OpenSSL 1.1.1, where code 24 isX509_V_ERR_INVALID_CA. Select the name based onssl.OPENSSL_VERSION_INFOso invalid-CA failures are not misreported.Prompt for AI agents