diff --git a/plugins/misc/URLSummary/components/event_listener/url_detector.py b/plugins/misc/URLSummary/components/event_listener/url_detector.py index ec77954e1..4ce1a0aa7 100644 --- a/plugins/misc/URLSummary/components/event_listener/url_detector.py +++ b/plugins/misc/URLSummary/components/event_listener/url_detector.py @@ -55,6 +55,12 @@ def _redact_url(url: str) -> str: _URL_IN_TEXT = re.compile(r"[A-Za-z][A-Za-z0-9+.\-]*://[^\s'\"<>()\[\],;]+") +# The extraction pattern keeps control characters (a DEL survives the trailing +# punctuation strip). A fetch of such a URL makes ``http.client`` raise +# ``InvalidURL`` with the raw request target, query string included, so these +# URLs never reach the fetch or the log boundary. +_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]") + def _redact_text(text: str) -> str: """Redact credentials/query/fragment from every URL inside ``text``. @@ -110,6 +116,8 @@ class URLDetector(EventListener): unique_urls = [] for url in urls: url = url.rstrip('.,;:!?') + if _CONTROL_CHARS.search(url): + continue if url not in seen: seen.add(url) unique_urls.append(url) @@ -147,12 +155,17 @@ class URLDetector(EventListener): ])) except Exception as e: + # Exception classes only: a message can quote the request + # target, whose query string may hold a credential. logger.warning( - f"Failed to summarize {_redact_url(url)}: {_redact_text(str(e))}" + f"Failed to summarize {_redact_url(url)}: {type(e).__name__}" ) except Exception as e: + # Frames without the exception message: traceback.format_exc() + # ends with the raw exception text, which can quote a request + # target and its query string. logger.error( - "Error in _handle_message: " - f"{_redact_text(str(e))}\n{_redact_text(traceback.format_exc())}" + f"Error in _handle_message ({type(e).__name__}): " + f"{_redact_text(''.join(traceback.format_tb(e.__traceback__)))}" ) diff --git a/plugins/misc/URLSummary/safe_fetch.py b/plugins/misc/URLSummary/safe_fetch.py index 215003940..eb1aafb6c 100644 --- a/plugins/misc/URLSummary/safe_fetch.py +++ b/plugins/misc/URLSummary/safe_fetch.py @@ -162,6 +162,12 @@ def redact_url(url: str) -> str: _URL_IN_TEXT = re.compile(r"[A-Za-z][A-Za-z0-9+.\-]*://[^\s'\"<>()\[\],;]+") +# http.client rejects control characters inside the request target and quotes +# the whole target in ``InvalidURL``. That message would carry a query string +# (and any token in it) into the shared log, so control characters are refused +# before a request is built. +_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]") + def redact_text(text: str) -> str: """Redact credentials/query/fragment from every URL inside ``text``. @@ -462,6 +468,10 @@ def _getaddrinfo(host: str, port: int, deadline: float | None, stop_event: Any) def validate_url(url: str) -> tuple[str, str, int, str]: """Validate scheme/host/port and return ``(scheme, host, port, path)``.""" + if _CONTROL_CHARS.search(url): + raise BlockedTargetError( + f"URL contains control characters: {redact_url(_CONTROL_CHARS.sub('', url))!r}" + ) try: parts = urlsplit(url) except ValueError as exc: @@ -634,8 +644,11 @@ def _request_once( raise FetchAbortedError( "fetch cancelled or deadline exceeded" ) from _scrub_exception(exc) + # Only the exception class: an exception message can quote the request + # target, and a relative target such as ``/page?token=...`` carries a + # credential that no absolute-URL redaction can strip. raise FetchError( - f"request to {redact_url(url)!r} failed: {redact_text(str(exc))}" + f"request to {redact_url(url)!r} failed: {type(exc).__name__}" ) from _scrub_exception(exc) finally: watch.stop() diff --git a/plugins/misc/URLSummary/tests/test_outbound_safety.py b/plugins/misc/URLSummary/tests/test_outbound_safety.py index b471c2d99..2b05fd8a2 100644 --- a/plugins/misc/URLSummary/tests/test_outbound_safety.py +++ b/plugins/misc/URLSummary/tests/test_outbound_safety.py @@ -261,6 +261,33 @@ def test_malformed_urls_are_refused(url: str, monkeypatch): safe_fetch.fetch_document(url) +def test_control_characters_are_refused_before_a_request_target_is_built(monkeypatch): + """``http.client`` quotes the whole target in ``InvalidURL``. + + A control character inside a URL used to reach ``connection.request``, which + raised ``InvalidURL`` containing the relative target — query string + included — and that text was logged. The URL is now refused up front, and + the refusal message carries no query string. + """ + monkeypatch.setattr( + safe_fetch.socket, "create_connection", lambda *a, **k: pytest.fail("no connection expected") + ) + + with pytest.raises(BlockedTargetError) as excinfo: + safe_fetch.fetch_document("http://example.com/page?token=REVIEW_SECRET\x7f") + + message = str(excinfo.value) + assert "REVIEW_SECRET" not in message + assert "control characters" in message + + +@pytest.mark.parametrize("control", ["\x00", "\x1f", "\x7f"]) +def test_validate_url_rejects_control_characters(control): + with pytest.raises(BlockedTargetError) as excinfo: + safe_fetch.validate_url(f"http://example.com/a?token=REVIEW_SECRET{control}b") + assert "REVIEW_SECRET" not in str(excinfo.value) + + def test_redirect_to_private_address_is_refused_and_never_connected(monkeypatch): plugin = URLSummary() attempted: list = []