From c989a8485f093b6bd6fb9a37a993423c95ac763a Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:10:51 +0100 Subject: [PATCH 1/4] fix: keep the API key out of error messages and tracebacks (1.3.2) Connection errors, timeouts and request-encoding errors from the sync client carried the request URL, including the apiKey query parameter, in the SDK error and in the chained requests/urllib3 exceptions. Mask the key and key-like query parameters or headers in every error the SDK raises, in its chained exceptions and in WebSocket refusals. --- CHANGELOG.md | 5 + CITATION.cff | 4 +- README.md | 2 +- odds_api/__init__.py | 2 +- odds_api/_redact.py | 221 +++++++++++++++++++++++++++++++++ odds_api/async_client.py | 6 +- odds_api/client.py | 6 +- odds_api/ws.py | 19 ++- pyproject.toml | 2 +- tests/test_redaction.py | 257 +++++++++++++++++++++++++++++++++++++++ 10 files changed, 503 insertions(+), 21 deletions(-) create mode 100644 odds_api/_redact.py create mode 100644 tests/test_redaction.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f983e9..2aa3cdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 1.3.2 (2026-11-26) + +### Security +- Errors no longer contain the API key. The key is sent as the `apiKey` query parameter, and in 1.3.1 and earlier a connection error, timeout or invalid request body from `OddsAPIClient` carried the full request URL in its message and in the chained `requests`/`urllib3` exception, so the key showed up in `str(error)` and in printed tracebacks. The key, and any key-like query parameter or header, is now masked as `***` in the SDK error, in every chained exception (`__cause__`, `__context__`, `args`, `request.url`, `response.url`, aiohttp `request_info`), in error bodies that echo the URL, and in `OddsStream` WebSocket errors. If you have shared a traceback from an older version, regenerate the key in your dashboard settings at https://odds-api.io/dashboard/settings. + ## 1.3.1 (2026-11-20) ### Docs diff --git a/CITATION.cff b/CITATION.cff index 009497f..24c2e1e 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -2,8 +2,8 @@ cff-version: 1.2.0 message: "If you use this software, please cite it using the metadata from this file." type: software title: "odds-api-io: Official Python SDK for Odds-API.io" -version: 1.3.1 -date-released: "2026-11-20" +version: 1.3.2 +date-released: "2026-11-26" authors: - name: "Outlier AS" email: "hello@odds-api.io" diff --git a/README.md b/README.md index 63e2c8a..ccae9e0 100644 --- a/README.md +++ b/README.md @@ -324,5 +324,5 @@ MIT. See [LICENSE](LICENSE). If you use this package in research or a publication, please cite it. Citation metadata is in [CITATION.cff](CITATION.cff) (GitHub renders a "Cite this repository" button from it) and Zenodo metadata is in `.zenodo.json`. ``` -Outlier AS. odds-api-io: Official Python SDK for Odds-API.io (version 1.3.1). https://github.com/odds-api-io/odds-api-python +Outlier AS. odds-api-io: Official Python SDK for Odds-API.io (version 1.3.2). https://github.com/odds-api-io/odds-api-python ``` diff --git a/odds_api/__init__.py b/odds_api/__init__.py index 70b40a4..354de18 100644 --- a/odds_api/__init__.py +++ b/odds_api/__init__.py @@ -3,7 +3,7 @@ Official Python client for the Odds-API.io sports betting odds API. """ -__version__ = "1.3.1" +__version__ = "1.3.2" from .client import OddsAPIClient from .async_client import AsyncOddsAPIClient diff --git a/odds_api/_redact.py b/odds_api/_redact.py new file mode 100644 index 0000000..fcb708f --- /dev/null +++ b/odds_api/_redact.py @@ -0,0 +1,221 @@ +"""Keep the API key out of error messages, chained exceptions and tracebacks. + +The key travels as the ``apiKey`` query parameter, and HTTP libraries put the +request URL into their exception messages. Every exception the SDK raises, and +every exception chained to it, is scrubbed before it leaves the SDK. +""" + +import dataclasses +import re +from typing import Any, Iterable, Optional, Set +from urllib.parse import quote, quote_plus + +REDACTED = "***" + +_SECRET_PARAM = re.compile( + r"(?i)(?()\[\],;]+" +) +_SECRET_HEADER = re.compile( + r"(?i)((?:x-)?api[_-]?key|authorization)(['\"]?\s*:\s*['\"]?)" + r"(?:bearer\s+|basic\s+)?[^'\"\s,}&]+" +) +_URL_ATTRS = ("url", "real_url", "uri", "path", "filename", "filename2") +_NESTED_ATTRS = ("request", "response", "reason", "original_error", "os_error") +_MAX_DEPTH = 12 + + +def _variants(secrets: Iterable[Optional[str]]) -> Set[str]: + found = set() + for secret in secrets: + if not secret: + continue + found.update({secret, quote(secret, safe=""), quote_plus(secret)}) + return found + + +def redact(text: str, secrets: Iterable[Optional[str]] = ()) -> str: + """Mask ``secrets`` and any key-like query parameter or header in ``text``.""" + for secret in sorted(_variants(secrets), key=len, reverse=True): + text = text.replace(secret, REDACTED) + text = _SECRET_PARAM.sub(lambda m: f"{m.group(1)}{m.group(2)}{REDACTED}", text) + return _SECRET_HEADER.sub(lambda m: f"{m.group(1)}{m.group(2)}{REDACTED}", text) + + +def _leaks(text: str, secrets: Iterable[Optional[str]]) -> bool: + return redact(text, secrets) != text + + +def redact_value(value: Any, secrets: Iterable[Optional[str]]) -> Any: + """Return ``value`` with secrets masked in every string inside it.""" + if isinstance(value, str): + return redact(value, secrets) + if isinstance(value, bytes): + text = value.decode("utf-8", errors="replace") + return redact(text, secrets).encode() if _leaks(text, secrets) else value + if isinstance(value, dict): + return {k: redact_value(v, secrets) for k, v in value.items()} + if isinstance(value, list): + return [redact_value(v, secrets) for v in value] + if isinstance(value, tuple) and not hasattr(value, "_fields"): + return tuple(redact_value(v, secrets) for v in value) + return value + + +def _rebuild_url(value: Any, secrets: Iterable[Optional[str]]) -> Any: + text = str(value) + if not _leaks(text, secrets): + return value + clean = redact(text, secrets) + try: + return type(value)(clean) + except Exception: + return clean + + +def _scrub_object( + obj: Any, secrets: Iterable[Optional[str]], seen: Set[int], depth: int +) -> None: + if obj is None or id(obj) in seen or depth > _MAX_DEPTH: + return + if isinstance(obj, (str, bytes, int, float, bool)): + return + if isinstance(obj, BaseException): + scrub_exception(obj, secrets, seen, depth) + return + seen.add(id(obj)) + _scrub_attrs(obj, secrets, seen, depth) + + +def _set_clean(obj: Any, name: str, secrets: Iterable[Optional[str]]) -> None: + try: + value = getattr(obj, name, None) + except Exception: + return + if value is None or isinstance(value, (int, float, bool, BaseException)): + return + if isinstance(value, (str, bytes, dict, list, tuple)): + clean = redact_value(value, secrets) + else: + clean = _rebuild_url(value, secrets) + if clean is value: + return + try: + setattr(obj, name, clean) + except Exception: + try: + object.__setattr__(obj, name, clean) + except Exception: + pass + + +def _scrub_request_info(obj: Any, secrets: Iterable[Optional[str]]) -> None: + info = getattr(obj, "request_info", None) + clean = _clean_record(info, secrets) if info is not None else None + if clean is not None: + try: + obj.request_info = clean + except Exception: + pass + + +def _clean_record(obj: Any, secrets: Iterable[Optional[str]]) -> Any: + """A copy of a namedtuple or dataclass with its leaking fields masked, else None.""" + if dataclasses.is_dataclass(obj) and not isinstance(obj, type): + names = [f.name for f in dataclasses.fields(obj)] + elif hasattr(obj, "_fields") and hasattr(obj, "_replace"): + names = list(obj._fields) + else: + return None + changes = {} + for name in names: + value = getattr(obj, name, None) + if value is None or not _leaks(repr(value), secrets): + continue + if isinstance(value, (str, bytes, dict, list, tuple)): + changes[name] = redact_value(value, secrets) + else: + changes[name] = _rebuild_url(value, secrets) + if not changes: + return obj + try: + if hasattr(obj, "_replace"): + return obj._replace(**changes) + return dataclasses.replace(obj, **changes) + except Exception: + return None + + +def _scrubbed( + obj: Any, secrets: Iterable[Optional[str]], seen: Set[int], depth: int +) -> Any: + _scrub_object(obj, secrets, seen, depth + 1) + return obj if not _leaks(repr(obj), secrets) else redact(str(obj), secrets) + + +def scrub_exception( + error: BaseException, + secrets: Iterable[Optional[str]], + seen: Optional[Set[int]] = None, + depth: int = 0, +) -> BaseException: + """Mask secrets in ``error`` and everything chained to it, in place.""" + secrets = tuple(secrets) + seen = set() if seen is None else seen + if id(error) in seen or depth > _MAX_DEPTH: + return error + seen.add(id(error)) + + clean_args = [] + for arg in error.args: + if isinstance(arg, BaseException): + scrub_exception(arg, secrets, seen, depth + 1) + clean_args.append(arg) + elif isinstance(arg, (str, bytes, dict, list)) or ( + isinstance(arg, tuple) and not hasattr(arg, "_fields") + ): + clean_args.append(redact_value(arg, secrets)) + elif arg is not None and _leaks(repr(arg), secrets): + clean_args.append( + _clean_record(arg, secrets) or _scrubbed(arg, secrets, seen, depth) + ) + else: + clean_args.append(arg) + try: + error.args = tuple(clean_args) + except Exception: + pass + + for name in ("msg", "message", "strerror", "reason", "body", "headers"): + _set_clean(error, name, secrets) + _scrub_attrs(error, secrets, seen, depth) + + notes = getattr(error, "__notes__", None) + if isinstance(notes, list): + clean_notes = [redact(n, secrets) if isinstance(n, str) else n for n in notes] + setattr(error, "__notes__", clean_notes) + + for linked in (error.__cause__, error.__context__): + if linked is not None: + scrub_exception(linked, secrets, seen, depth + 1) + return error + + +def _scrub_attrs( + obj: Any, secrets: Iterable[Optional[str]], seen: Set[int], depth: int +) -> None: + for name in _URL_ATTRS: + _set_clean(obj, name, secrets) + for name in _NESTED_ATTRS: + try: + value = getattr(obj, name, None) + except Exception: + continue + _scrub_object(value, secrets, seen, depth + 1) + _scrub_request_info(obj, secrets) + history = getattr(obj, "history", None) + if isinstance(history, (list, tuple)): + for item in history: + _scrub_object(item, secrets, seen, depth + 1) diff --git a/odds_api/async_client.py b/odds_api/async_client.py index 713b849..84034dd 100644 --- a/odds_api/async_client.py +++ b/odds_api/async_client.py @@ -18,6 +18,7 @@ parse_rate_limit, to_csv, ) +from ._redact import redact, scrub_exception from .constants import ( BASE_API_URL, DEFAULT_TIMEOUT, @@ -133,9 +134,10 @@ async def _request( if 200 <= response.status < 300: return content if raw else decode_body(content) error = build_error(response.status, content, headers) + scrub_exception(error, (self.api_key,)) except (aiohttp.ClientError, asyncio.TimeoutError) as e: - cause = e - error = OddsAPIError(f"Request failed: {e!r}") + cause = scrub_exception(e, (self.api_key,)) + error = OddsAPIError(redact(f"Request failed: {e!r}", (self.api_key,))) delay = next_retry_delay( attempt, error, self.max_retries, self.max_retry_wait diff --git a/odds_api/client.py b/odds_api/client.py index 5b8a68c..cf0c0df 100644 --- a/odds_api/client.py +++ b/odds_api/client.py @@ -18,6 +18,7 @@ parse_rate_limit, to_csv, ) +from ._redact import redact, scrub_exception from .constants import ( BASE_API_URL, DEFAULT_TIMEOUT, @@ -129,8 +130,8 @@ def _request( method, url, params=query, json=body, timeout=self.timeout ) except requests.RequestException as e: - cause = e - error = OddsAPIError(f"Request failed: {e}") + cause = scrub_exception(e, (self.api_key,)) + error = OddsAPIError(redact(f"Request failed: {e}", (self.api_key,))) else: headers: Mapping[str, str] = response.headers self.last_response_headers = dict(headers) @@ -138,6 +139,7 @@ def _request( if response.ok: return response.content if raw else decode_body(response.content) error = build_error(response.status_code, response.content, headers) + scrub_exception(error, (self.api_key,)) delay = next_retry_delay( attempt, error, self.max_retries, self.max_retry_wait diff --git a/odds_api/ws.py b/odds_api/ws.py index b739f68..80aa25f 100644 --- a/odds_api/ws.py +++ b/odds_api/ws.py @@ -30,6 +30,7 @@ ) from e from ._base import to_csv +from ._redact import redact, scrub_exception from .constants import WEBSOCKET_URL from .exceptions import ( ForbiddenError, @@ -153,25 +154,19 @@ async def __aiter__(self) -> AsyncIterator[Dict[str, Any]]: except OSError: code = None except Exception as e: + scrub_exception(e, (self.api_key,)) status = _handshake_status(e) if status is None: raise + refused = redact(f"WebSocket refused: {e}", (self.api_key,)) if status == 400: - raise ValidationError( - f"WebSocket refused: {e}", status_code=status - ) from e + raise ValidationError(refused, status_code=status) from e if status == 401: - raise InvalidAPIKeyError( - f"WebSocket refused: {e}", status_code=status - ) from e + raise InvalidAPIKeyError(refused, status_code=status) from e if status == 403: - raise ForbiddenError( - f"WebSocket refused: {e}", status_code=status - ) from e + raise ForbiddenError(refused, status_code=status) from e if status < 500 and status != 429: - raise OddsAPIError( - f"WebSocket refused: {e}", status_code=status - ) from e + raise OddsAPIError(refused, status_code=status) from e finally: self._ws = None diff --git a/pyproject.toml b/pyproject.toml index 9359e6a..39d7873 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "odds-api-io" -version = "1.3.1" +version = "1.3.2" description = "Official Python SDK for Odds-API.io, the sports betting odds API: live and pre-match odds from 500+ bookmakers across 34 sports, player props, golf outrights, closing lines, settlement, arbitrage, value bets and WebSocket" readme = "README.md" requires-python = ">=3.8" diff --git a/tests/test_redaction.py b/tests/test_redaction.py new file mode 100644 index 0000000..5f6a90d --- /dev/null +++ b/tests/test_redaction.py @@ -0,0 +1,257 @@ +"""The API key must never appear in an error, its chain or its traceback.""" + +import asyncio +import socket +import traceback + +import aiohttp +import pytest +import requests +import responses +import websockets +from aiohttp import web +from urllib3.exceptions import ConnectTimeoutError, MaxRetryError, ReadTimeoutError + +from odds_api import ( + AsyncOddsAPIClient, + InvalidAPIKeyError, + OddsAPIClient, + OddsAPIError, + ServerError, +) +from odds_api._redact import redact, scrub_exception +from odds_api.ws import OddsStream + +KEY = "sk-live-7f3a9c1e5b2d4f60a8e1" +BASE = "https://api.odds-api.io/v3" +URL_WITH_KEY = f"{BASE}/sports?apiKey={KEY}" + + +def _closed_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def _chain(error): + seen, todo = [], [error] + while todo: + current = todo.pop() + if current is None or any(current is s for s in seen): + continue + seen.append(current) + todo += [current.__cause__, current.__context__] + todo += [a for a in current.args if isinstance(a, BaseException)] + todo += ( + [getattr(current, "reason", None)] + if isinstance(getattr(current, "reason", None), BaseException) + else [] + ) + return seen + + +def assert_no_key(error): + text = "".join(traceback.format_exception(type(error), error, error.__traceback__)) + assert KEY not in text + for link in _chain(error): + assert KEY not in str(link) + assert KEY not in repr(link) + assert KEY not in repr(link.args) + for name in ("url", "body", "headers", "message"): + assert KEY not in str(getattr(link, name, "")) + for name in ("request", "response"): + obj = getattr(link, name, None) + assert KEY not in str(getattr(obj, "url", "")) + assert "apiKey=***" in text or "apiKey" not in text + + +def test_redact_masks_key_and_key_like_params(): + text = f"GET /x?apiKey={KEY}&token=abc&api_key=def X-API-Key: ghi Authorization: Bearer jkl" + clean = redact(text, (KEY,)) + for secret in (KEY, "abc", "def", "ghi", "jkl"): + assert secret not in clean + assert "apiKey=***" in clean + + +def test_redact_masks_url_encoded_key(): + key = "a+b/c=d" + clean = redact("q=a%2Bb%2Fc%3Dd and a+b/c=d", (key,)) + assert "a%2Bb%2Fc%3Dd" not in clean and "a+b/c=d" not in clean + + +def test_redact_leaves_ordinary_words_alone(): + assert redact("monkey=1&sport=football", (KEY,)) == "monkey=1&sport=football" + + +def test_sync_connection_error_hides_key(): + client = OddsAPIClient( + KEY, base_url=f"http://127.0.0.1:{_closed_port()}/v3", timeout=2 + ) + with pytest.raises(OddsAPIError) as info: + client.get_sports() + assert "Request failed" in str(info.value) + assert isinstance(info.value.__cause__, requests.ConnectionError) + assert_no_key(info.value) + + +@pytest.mark.parametrize( + "error", + [ + lambda req: requests.exceptions.ConnectTimeout( + MaxRetryError( + None, f"/v3/sports?apiKey={KEY}", ConnectTimeoutError(None, "timed out") + ), + request=req, + ), + lambda req: requests.exceptions.ReadTimeout( + ReadTimeoutError(None, f"/v3/sports?apiKey={KEY}", "Read timed out."), + request=req, + ), + lambda req: requests.exceptions.ConnectionError( + MaxRetryError(None, f"/v3/sports?apiKey={KEY}", OSError("refused")), + request=req, + ), + ], + ids=["connect-timeout", "read-timeout", "connection-error"], +) +@responses.activate +def test_sync_timeouts_and_connection_errors_hide_key(error): + prepared = requests.Request("GET", URL_WITH_KEY).prepare() + responses.add(responses.GET, f"{BASE}/sports", body=error(prepared)) + with OddsAPIClient(KEY) as client, pytest.raises(OddsAPIError) as info: + client.get_sports() + assert_no_key(info.value) + + +@responses.activate +def test_sync_http_error_echoing_url_hides_key(): + responses.add( + responses.GET, + f"{BASE}/sports", + json={"error": f"Invalid API key for {URL_WITH_KEY}", "apiKey": KEY}, + status=401, + ) + with OddsAPIClient(KEY) as client, pytest.raises(InvalidAPIKeyError) as info: + client.get_sports() + assert_no_key(info.value) + assert info.value.status_code == 401 + + +@responses.activate +def test_sync_html_proxy_error_hides_key(): + responses.add( + responses.GET, + f"{BASE}/sports", + body=f"502 Bad Gateway for {URL_WITH_KEY}", + status=502, + content_type="text/html", + ) + with OddsAPIClient(KEY) as client, pytest.raises(ServerError) as info: + client.get_sports() + assert_no_key(info.value) + + +def test_sync_json_encoding_error_hides_key(): + with OddsAPIClient(KEY) as client, pytest.raises(OddsAPIError) as info: + client._post("sgp/quote", {"stake": float("nan")}) + assert isinstance(info.value.__cause__, requests.exceptions.InvalidJSONError) + assert_no_key(info.value) + + +async def test_async_connection_error_hides_key(): + async with AsyncOddsAPIClient( + KEY, base_url=f"http://127.0.0.1:{_closed_port()}/v3", timeout=2 + ) as client: + with pytest.raises(OddsAPIError) as info: + await client.get_sports() + assert_no_key(info.value) + + +@pytest.fixture +async def slow_server(): + async def handler(request): + await asyncio.sleep(2) + return web.json_response({"error": f"slow {request.url}"}, status=500) + + app = web.Application() + app.router.add_route("*", "/{tail:.*}", handler) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + yield f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}/v3" + await runner.cleanup() + + +async def test_async_timeout_hides_key(slow_server): + async with AsyncOddsAPIClient(KEY, base_url=slow_server, timeout=0.2) as client: + with pytest.raises(OddsAPIError) as info: + await client.get_sports() + assert_no_key(info.value) + + +@pytest.fixture +async def echo_server(): + async def handler(request): + if request.path.endswith("/html"): + return web.Response(text=f"bad gateway {request.url}", status=502) + return web.json_response({"error": f"bad key in {request.url}"}, status=401) + + app = web.Application() + app.router.add_route("*", "/{tail:.*}", handler) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + yield f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}/v3" + await runner.cleanup() + + +async def test_async_http_and_non_json_errors_hide_key(echo_server): + async with AsyncOddsAPIClient(KEY, base_url=echo_server) as client: + with pytest.raises(InvalidAPIKeyError) as info: + await client.get_sports() + assert_no_key(info.value) + with pytest.raises(ServerError) as info: + await client._get("html") + assert_no_key(info.value) + + +async def test_async_client_response_error_request_info_is_scrubbed(): + from yarl import URL + + info = aiohttp.RequestInfo(URL(URL_WITH_KEY), "GET", {}, URL(URL_WITH_KEY)) + error = aiohttp.ClientResponseError(info, (), status=500, message="boom") + try: + raise error + except aiohttp.ClientResponseError as e: + scrub_exception(e, (KEY,)) + assert_no_key(e) + assert KEY not in str(e.request_info.real_url) + + +async def test_ws_invalid_url_hides_key(): + stream = OddsStream(KEY, markets="ML", url="not a websocket url") + with pytest.raises(Exception) as info: + async for _ in stream: + pass + assert_no_key(info.value) + + +async def test_ws_handshake_refusal_hides_key(): + def reject(connection, request): + if isinstance(connection, str): + return 401, [], f"Invalid API key {connection}\n".encode() + return connection.respond(401, f"Invalid API key {request.path}\n") + + async with websockets.serve( + lambda *a: None, "127.0.0.1", 0, process_request=reject + ) as server: + port = next(iter(server.sockets)).getsockname()[1] + stream = OddsStream( + KEY, markets="ML", url=f"ws://127.0.0.1:{port}/v3/ws", max_reconnects=1 + ) + with pytest.raises(InvalidAPIKeyError) as info: + async for _ in stream: + pass + assert_no_key(info.value) From 4b436643346cc00b0cbd5409c687c8d6f4d8b8d7 Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:20:09 +0100 Subject: [PATCH 2/4] fix: mask every attribute of chained exceptions, stand in when masking in place fails Scrub all instance attributes and slots of exceptions and the objects they hold (response bodies, headers, header values), not a fixed list, and replace an exception that still shows the key, such as one whose message reads a read-only property, with a masked stand-in. Raise WebSocket failures outside the except block so the unmasked original is never attached as __context__. --- CHANGELOG.md | 2 +- odds_api/_redact.py | 336 ++++++++++++++++++++-------------------- odds_api/ws.py | 42 +++-- tests/test_redaction.py | 124 ++++++++++++--- 4 files changed, 302 insertions(+), 202 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2aa3cdc..cc1dfe5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## 1.3.2 (2026-11-26) ### Security -- Errors no longer contain the API key. The key is sent as the `apiKey` query parameter, and in 1.3.1 and earlier a connection error, timeout or invalid request body from `OddsAPIClient` carried the full request URL in its message and in the chained `requests`/`urllib3` exception, so the key showed up in `str(error)` and in printed tracebacks. The key, and any key-like query parameter or header, is now masked as `***` in the SDK error, in every chained exception (`__cause__`, `__context__`, `args`, `request.url`, `response.url`, aiohttp `request_info`), in error bodies that echo the URL, and in `OddsStream` WebSocket errors. If you have shared a traceback from an older version, regenerate the key in your dashboard settings at https://odds-api.io/dashboard/settings. +- Errors no longer contain the API key. The key is sent as the `apiKey` query parameter, and in 1.3.1 and earlier a connection error, timeout or invalid request body from `OddsAPIClient` carried the full request URL in its message and in the chained `requests`/`urllib3` exception, so the key showed up in `str(error)` and in printed tracebacks. The key, and any key-like query parameter or header, is now masked as `***` in the SDK error, in every chained exception (`__cause__`, `__context__`, `args`, `request.url`, `response.url`, aiohttp `request_info`), in error bodies that echo the URL, and in `OddsStream` WebSocket errors. A chained exception that cannot be masked in place (one whose message comes from a read-only property) is replaced by a masked stand-in with the same text. If you have shared a traceback from an older version, regenerate the key in your dashboard settings at https://odds-api.io/dashboard/settings. ## 1.3.1 (2026-11-20) diff --git a/odds_api/_redact.py b/odds_api/_redact.py index fcb708f..30ede19 100644 --- a/odds_api/_redact.py +++ b/odds_api/_redact.py @@ -1,13 +1,16 @@ """Keep the API key out of error messages, chained exceptions and tracebacks. The key travels as the ``apiKey`` query parameter, and HTTP libraries put the -request URL into their exception messages. Every exception the SDK raises, and -every exception chained to it, is scrubbed before it leaves the SDK. +request URL into their exception messages and attributes. Every exception the +SDK raises, and every exception chained to it, is scrubbed before it leaves the +SDK. An exception that still shows the key afterwards (for example one whose +``__str__`` reads a read-only property) is replaced by a masked stand-in. """ import dataclasses import re -from typing import Any, Iterable, Optional, Set +import traceback +from typing import Any, Iterable, List, Optional, Set, Tuple from urllib.parse import quote, quote_plus REDACTED = "***" @@ -22,200 +25,205 @@ r"(?i)((?:x-)?api[_-]?key|authorization)(['\"]?\s*:\s*['\"]?)" r"(?:bearer\s+|basic\s+)?[^'\"\s,}&]+" ) -_URL_ATTRS = ("url", "real_url", "uri", "path", "filename", "filename2") -_NESTED_ATTRS = ("request", "response", "reason", "original_error", "os_error") -_MAX_DEPTH = 12 +_MAX_DEPTH = 10 +Secrets = Tuple[str, ...] -def _variants(secrets: Iterable[Optional[str]]) -> Set[str]: + +class RedactedError(Exception): + """Stands in for an underlying exception that could not be masked in place.""" + + +def _variants(secrets: Iterable[Optional[str]]) -> List[str]: found = set() for secret in secrets: - if not secret: - continue - found.update({secret, quote(secret, safe=""), quote_plus(secret)}) - return found + if secret: + found.update({secret, quote(secret, safe=""), quote_plus(secret)}) + return sorted(found, key=len, reverse=True) def redact(text: str, secrets: Iterable[Optional[str]] = ()) -> str: """Mask ``secrets`` and any key-like query parameter or header in ``text``.""" - for secret in sorted(_variants(secrets), key=len, reverse=True): + for secret in _variants(secrets): text = text.replace(secret, REDACTED) text = _SECRET_PARAM.sub(lambda m: f"{m.group(1)}{m.group(2)}{REDACTED}", text) return _SECRET_HEADER.sub(lambda m: f"{m.group(1)}{m.group(2)}{REDACTED}", text) -def _leaks(text: str, secrets: Iterable[Optional[str]]) -> bool: +def _leaks(text: str, secrets: Secrets) -> bool: return redact(text, secrets) != text -def redact_value(value: Any, secrets: Iterable[Optional[str]]) -> Any: - """Return ``value`` with secrets masked in every string inside it.""" - if isinstance(value, str): - return redact(value, secrets) - if isinstance(value, bytes): - text = value.decode("utf-8", errors="replace") - return redact(text, secrets).encode() if _leaks(text, secrets) else value - if isinstance(value, dict): - return {k: redact_value(v, secrets) for k, v in value.items()} - if isinstance(value, list): - return [redact_value(v, secrets) for v in value] - if isinstance(value, tuple) and not hasattr(value, "_fields"): - return tuple(redact_value(v, secrets) for v in value) - return value - - -def _rebuild_url(value: Any, secrets: Iterable[Optional[str]]) -> Any: - text = str(value) - if not _leaks(text, secrets): - return value - clean = redact(text, secrets) +def _shows_secret(value: Any, secrets: Secrets) -> bool: try: - return type(value)(clean) + return _leaks(str(value), secrets) or _leaks(repr(value), secrets) except Exception: - return clean - + return True -def _scrub_object( - obj: Any, secrets: Iterable[Optional[str]], seen: Set[int], depth: int -) -> None: - if obj is None or id(obj) in seen or depth > _MAX_DEPTH: - return - if isinstance(obj, (str, bytes, int, float, bool)): - return - if isinstance(obj, BaseException): - scrub_exception(obj, secrets, seen, depth) - return - seen.add(id(obj)) - _scrub_attrs(obj, secrets, seen, depth) - -def _set_clean(obj: Any, name: str, secrets: Iterable[Optional[str]]) -> None: - try: - value = getattr(obj, name, None) - except Exception: - return - if value is None or isinstance(value, (int, float, bool, BaseException)): - return - if isinstance(value, (str, bytes, dict, list, tuple)): - clean = redact_value(value, secrets) - else: - clean = _rebuild_url(value, secrets) - if clean is value: - return +def _set(obj: Any, name: str, value: Any) -> bool: try: - setattr(obj, name, clean) + setattr(obj, name, value) + return True except Exception: try: - object.__setattr__(obj, name, clean) + object.__setattr__(obj, name, value) + return True except Exception: - pass - + return False + + +def _attr_names(obj: Any) -> List[str]: + names = list(getattr(obj, "__dict__", None) or {}) + for cls in type(obj).__mro__: + slots = cls.__dict__.get("__slots__", ()) + names += [slots] if isinstance(slots, str) else list(slots) + return [n for n in dict.fromkeys(names) if n not in ("__dict__", "__weakref__")] + + +class _Scrubber: + def __init__(self, secrets: Iterable[Optional[str]]): + self.secrets: Secrets = tuple(s for s in secrets if s) + self.seen: Set[int] = set() + + def value(self, value: Any, depth: int) -> Any: + """``value`` with secrets masked; mutable objects are cleaned in place.""" + if value is None or isinstance(value, (bool, int, float)): + return value + if isinstance(value, str): + return redact(value, self.secrets) + if isinstance(value, (bytes, bytearray)): + text = bytes(value).decode("utf-8", errors="replace") + if not _leaks(text, self.secrets): + return value + return redact(text, self.secrets).encode() + if depth > _MAX_DEPTH: + return REDACTED if _shows_secret(value, self.secrets) else value + if isinstance(value, BaseException): + return self.exception(value, depth + 1) + if isinstance(value, dict): + return { + self.value(k, depth + 1): self.value(v, depth + 1) + for k, v in value.items() + } + if isinstance(value, list): + return [self.value(v, depth + 1) for v in value] + if isinstance(value, tuple) and not hasattr(value, "_fields"): + return tuple(self.value(v, depth + 1) for v in value) + if id(value) in self.seen: + return value + if not _shows_secret(value, self.secrets) and not self._holds_secret(value): + return value + record = self._record(value, depth) + if record is not None: + return record + rebuilt = self._rebuild(value) + if rebuilt is not None: + return rebuilt + self.object(value, depth + 1) + if _shows_secret(value, self.secrets): + return redact(str(value), self.secrets) + return value -def _scrub_request_info(obj: Any, secrets: Iterable[Optional[str]]) -> None: - info = getattr(obj, "request_info", None) - clean = _clean_record(info, secrets) if info is not None else None - if clean is not None: + def _holds_secret(self, obj: Any) -> bool: try: - obj.request_info = clean + return any( + _shows_secret(getattr(obj, name, None), self.secrets) + for name in _attr_names(obj) + ) except Exception: - pass + return True + def _rebuild(self, value: Any) -> Any: + """A URL-like value (yarl.URL, a str subclass) rebuilt from its masked text.""" + if not isinstance(value, str) and type(value).__name__ != "URL": + return None + try: + rebuilt = type(value)(redact(str(value), self.secrets)) + except Exception: + return None + return None if _shows_secret(rebuilt, self.secrets) else rebuilt -def _clean_record(obj: Any, secrets: Iterable[Optional[str]]) -> Any: - """A copy of a namedtuple or dataclass with its leaking fields masked, else None.""" - if dataclasses.is_dataclass(obj) and not isinstance(obj, type): - names = [f.name for f in dataclasses.fields(obj)] - elif hasattr(obj, "_fields") and hasattr(obj, "_replace"): - names = list(obj._fields) - else: - return None - changes = {} - for name in names: - value = getattr(obj, name, None) - if value is None or not _leaks(repr(value), secrets): - continue - if isinstance(value, (str, bytes, dict, list, tuple)): - changes[name] = redact_value(value, secrets) - else: - changes[name] = _rebuild_url(value, secrets) - if not changes: - return obj - try: - if hasattr(obj, "_replace"): - return obj._replace(**changes) - return dataclasses.replace(obj, **changes) - except Exception: - return None + def _record(self, value: Any, depth: int) -> Any: + """A copy of a namedtuple or dataclass with its fields masked.""" + try: + if hasattr(value, "_fields") and hasattr(value, "_replace"): + fields = list(value._fields) + changes = {f: self.value(getattr(value, f), depth + 1) for f in fields} + clean = value._replace(**changes) + elif dataclasses.is_dataclass(value) and not isinstance(value, type): + fields = [f.name for f in dataclasses.fields(value) if f.init] + changes = {f: self.value(getattr(value, f), depth + 1) for f in fields} + clean = dataclasses.replace(value, **changes) + else: + return None + except Exception: + return None + return None if _shows_secret(clean, self.secrets) else clean + + def object(self, obj: Any, depth: int) -> None: + if id(obj) in self.seen: + return + self.seen.add(id(obj)) + for name in _attr_names(obj): + try: + current = getattr(obj, name) + except Exception: + continue + clean = self.value(current, depth) + if clean is not current: + _set(obj, name, clean) + + def exception(self, error: BaseException, depth: int = 0) -> BaseException: + """``error`` masked in place, or a masked stand-in when that is not enough.""" + if id(error) in self.seen: + return error + self.seen.add(id(error)) + try: + error.args = tuple(self.value(a, depth + 1) for a in error.args) + except Exception: + pass + for name in _attr_names(error): + try: + current = getattr(error, name) + except Exception: + continue + clean = self.value(current, depth + 1) + if clean is not current: + _set(error, name, clean) + if error.__cause__ is not None: + error.__cause__ = self.exception(error.__cause__, depth + 1) + if error.__context__ is not None: + error.__context__ = self.exception(error.__context__, depth + 1) + if self._exception_leaks(error): + return self._stand_in(error) + return error + def _exception_leaks(self, error: BaseException) -> bool: + try: + text = "".join(traceback.format_exception_only(type(error), error)) + except Exception: + return True + return _leaks(text, self.secrets) or _shows_secret(error, self.secrets) -def _scrubbed( - obj: Any, secrets: Iterable[Optional[str]], seen: Set[int], depth: int -) -> Any: - _scrub_object(obj, secrets, seen, depth + 1) - return obj if not _leaks(repr(obj), secrets) else redact(str(obj), secrets) + def _stand_in(self, error: BaseException) -> BaseException: + try: + text = str(error) + except Exception: + text = "" + name = f"{type(error).__module__}.{type(error).__qualname__}" + stand_in = RedactedError(redact(f"{name}: {text}", self.secrets)) + stand_in.__cause__ = error.__cause__ + stand_in.__suppress_context__ = True + return stand_in def scrub_exception( - error: BaseException, - secrets: Iterable[Optional[str]], - seen: Optional[Set[int]] = None, - depth: int = 0, + error: BaseException, secrets: Iterable[Optional[str]] ) -> BaseException: - """Mask secrets in ``error`` and everything chained to it, in place.""" - secrets = tuple(secrets) - seen = set() if seen is None else seen - if id(error) in seen or depth > _MAX_DEPTH: - return error - seen.add(id(error)) - - clean_args = [] - for arg in error.args: - if isinstance(arg, BaseException): - scrub_exception(arg, secrets, seen, depth + 1) - clean_args.append(arg) - elif isinstance(arg, (str, bytes, dict, list)) or ( - isinstance(arg, tuple) and not hasattr(arg, "_fields") - ): - clean_args.append(redact_value(arg, secrets)) - elif arg is not None and _leaks(repr(arg), secrets): - clean_args.append( - _clean_record(arg, secrets) or _scrubbed(arg, secrets, seen, depth) - ) - else: - clean_args.append(arg) - try: - error.args = tuple(clean_args) - except Exception: - pass - - for name in ("msg", "message", "strerror", "reason", "body", "headers"): - _set_clean(error, name, secrets) - _scrub_attrs(error, secrets, seen, depth) - - notes = getattr(error, "__notes__", None) - if isinstance(notes, list): - clean_notes = [redact(n, secrets) if isinstance(n, str) else n for n in notes] - setattr(error, "__notes__", clean_notes) + """Mask secrets in ``error`` and its whole chain. - for linked in (error.__cause__, error.__context__): - if linked is not None: - scrub_exception(linked, secrets, seen, depth + 1) - return error - - -def _scrub_attrs( - obj: Any, secrets: Iterable[Optional[str]], seen: Set[int], depth: int -) -> None: - for name in _URL_ATTRS: - _set_clean(obj, name, secrets) - for name in _NESTED_ATTRS: - try: - value = getattr(obj, name, None) - except Exception: - continue - _scrub_object(value, secrets, seen, depth + 1) - _scrub_request_info(obj, secrets) - history = getattr(obj, "history", None) - if isinstance(history, (list, tuple)): - for item in history: - _scrub_object(item, secrets, seen, depth + 1) + Returns ``error`` itself, or a :class:`RedactedError` stand-in when the + exception would still show a secret. + """ + return _Scrubber(secrets).exception(error) diff --git a/odds_api/ws.py b/odds_api/ws.py index 80aa25f..d752cda 100644 --- a/odds_api/ws.py +++ b/odds_api/ws.py @@ -137,6 +137,7 @@ async def __aiter__(self) -> AsyncIterator[Dict[str, Any]]: while not self._closed: code: Optional[int] = None reason = "" + failure: Optional[BaseException] = None try: async with websockets.connect(self.connect_url(), max_size=None) as ws: self._ws = ws @@ -154,22 +155,13 @@ async def __aiter__(self) -> AsyncIterator[Dict[str, Any]]: except OSError: code = None except Exception as e: - scrub_exception(e, (self.api_key,)) - status = _handshake_status(e) - if status is None: - raise - refused = redact(f"WebSocket refused: {e}", (self.api_key,)) - if status == 400: - raise ValidationError(refused, status_code=status) from e - if status == 401: - raise InvalidAPIKeyError(refused, status_code=status) from e - if status == 403: - raise ForbiddenError(refused, status_code=status) from e - if status < 500 and status != 429: - raise OddsAPIError(refused, status_code=status) from e + failure = self._failure(e) finally: self._ws = None + if failure is not None: + raise failure + if self._closed: return if code == CLOSE_REPLACED and "newer connection" in reason: @@ -186,6 +178,30 @@ async def __aiter__(self) -> AsyncIterator[Dict[str, Any]]: attempt += 1 await asyncio.sleep(delay) + def _failure(self, error: Exception) -> Optional[BaseException]: + """The masked exception to raise for ``error``, or None to reconnect.""" + status = _handshake_status(error) + cause = scrub_exception(error, (self.api_key,)) + if status is None: + if cause is error: + return error + wrapped = OddsAPIError(str(cause)) + wrapped.__cause__ = cause + return wrapped + refused = redact(f"WebSocket refused: {cause}", (self.api_key,)) + if status == 400: + failure: OddsAPIError = ValidationError(refused, status_code=status) + elif status == 401: + failure = InvalidAPIKeyError(refused, status_code=status) + elif status == 403: + failure = ForbiddenError(refused, status_code=status) + elif status < 500 and status != 429: + failure = OddsAPIError(refused, status_code=status) + else: + return None + failure.__cause__ = cause + return failure + def _handshake_status(error: Exception) -> Optional[int]: response = getattr(error, "response", None) diff --git a/tests/test_redaction.py b/tests/test_redaction.py index 5f6a90d..76cc780 100644 --- a/tests/test_redaction.py +++ b/tests/test_redaction.py @@ -33,35 +33,51 @@ def _closed_port(): return s.getsockname()[1] -def _chain(error): - seen, todo = [], [error] - while todo: - current = todo.pop() - if current is None or any(current is s for s in seen): - continue - seen.append(current) - todo += [current.__cause__, current.__context__] - todo += [a for a in current.args if isinstance(a, BaseException)] - todo += ( - [getattr(current, "reason", None)] - if isinstance(getattr(current, "reason", None), BaseException) - else [] - ) - return seen +def _find_key(value, path, seen, depth=0): + """Paths under ``value`` (attributes, items, the exception chain) that show the key.""" + if value is None or isinstance(value, (bool, int, float)) or id(value) in seen: + return [] + if depth > 8: + return [] + seen.add(id(value)) + found = [] + try: + if KEY in str(value) or KEY in repr(value): + found.append(path) + except Exception: + found.append(path + " (str/repr raised)") + if isinstance(value, (str, bytes)): + return found + if isinstance(value, dict): + children = list(value.items()) + elif isinstance(value, (list, tuple, set)): + children = list(enumerate(value)) + else: + children = [] + names = list(getattr(value, "__dict__", None) or {}) + for cls in type(value).__mro__: + slots = cls.__dict__.get("__slots__", ()) + names += [slots] if isinstance(slots, str) else list(slots) + for name in dict.fromkeys(names): + try: + children.append((name, getattr(value, name))) + except Exception: + pass + if isinstance(value, BaseException): + children += [ + ("args", value.args), + ("__cause__", value.__cause__), + ("__context__", value.__context__), + ] + for name, child in children: + found += _find_key(child, f"{path}.{name}", seen, depth + 1) + return found def assert_no_key(error): text = "".join(traceback.format_exception(type(error), error, error.__traceback__)) assert KEY not in text - for link in _chain(error): - assert KEY not in str(link) - assert KEY not in repr(link) - assert KEY not in repr(link.args) - for name in ("url", "body", "headers", "message"): - assert KEY not in str(getattr(link, name, "")) - for name in ("request", "response"): - obj = getattr(link, name, None) - assert KEY not in str(getattr(obj, "url", "")) + assert _find_key(error, "error", set()) == [] assert "apiKey=***" in text or "apiKey" not in text @@ -255,3 +271,63 @@ def reject(connection, request): async for _ in stream: pass assert_no_key(info.value) + + +def _raised(error): + try: + raise error + except BaseException as e: + return e + + +def test_read_only_url_property_is_replaced_by_a_masked_stand_in(): + from yarl import URL + + error = _raised(aiohttp.InvalidURL(URL(URL_WITH_KEY), "bad redirect")) + clean = scrub_exception(error, (KEY,)) + assert "apiKey=***" in str(clean) + assert_no_key(clean) + + +@pytest.mark.parametrize( + "error", + [ + lambda: websockets.exceptions.InvalidHeader("Location", URL_WITH_KEY), + lambda: websockets.exceptions.InvalidHeaderValue("Location", URL_WITH_KEY), + lambda: websockets.exceptions.InvalidURI(URL_WITH_KEY, "bad"), + ], + ids=["invalid-header", "invalid-header-value", "invalid-uri"], +) +def test_websockets_exceptions_with_the_key_are_masked(error): + clean = scrub_exception(_raised(error()), (KEY,)) + assert_no_key(clean) + + +def test_nested_transport_objects_are_masked(): + class Response: + def __init__(self): + self.body = f"echo {URL_WITH_KEY}".encode() + self.headers = {"Location": URL_WITH_KEY} + + def __repr__(self): + return f"Response(body={self.body!r}, headers={self.headers!r})" + + inner = _raised(OSError(f"refused {URL_WITH_KEY}")) + error = RuntimeError("handshake failed") + error.response = Response() + error.__cause__ = inner + clean = scrub_exception(_raised(error), (KEY,)) + assert clean is error + assert_no_key(clean) + + +async def test_ws_malformed_header_hides_key(monkeypatch): + def connect(url, **kwargs): + raise websockets.exceptions.InvalidHeaderValue("Location", url) + + monkeypatch.setattr("odds_api.ws.websockets.connect", connect) + stream = OddsStream(KEY, markets="ML", max_reconnects=0) + with pytest.raises(websockets.exceptions.InvalidHeaderValue) as info: + async for _ in stream: + pass + assert_no_key(info.value) From 1c9e0301d0bdb57fa7f5880659a061b1d16779da Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:25:10 +0100 Subject: [PATCH 3/4] fix: reuse stand-ins for shared exceptions, mask credential fields in mappings --- odds_api/_redact.py | 23 ++++++++++++++++------- tests/test_redaction.py | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/odds_api/_redact.py b/odds_api/_redact.py index 30ede19..02a4fae 100644 --- a/odds_api/_redact.py +++ b/odds_api/_redact.py @@ -10,7 +10,7 @@ import dataclasses import re import traceback -from typing import Any, Iterable, List, Optional, Set, Tuple +from typing import Any, Dict, Iterable, List, Optional, Set, Tuple from urllib.parse import quote, quote_plus REDACTED = "***" @@ -25,6 +25,10 @@ r"(?i)((?:x-)?api[_-]?key|authorization)(['\"]?\s*:\s*['\"]?)" r"(?:bearer\s+|basic\s+)?[^'\"\s,}&]+" ) +_SECRET_FIELD = re.compile( + r"(?i)^(?:x-)?(?:api[_-]?key|access[_-]?token|auth[_-]?token|token|secret" + r"|password|authorization|proxy-authorization)$" +) _MAX_DEPTH = 10 Secrets = Tuple[str, ...] @@ -85,6 +89,7 @@ class _Scrubber: def __init__(self, secrets: Iterable[Optional[str]]): self.secrets: Secrets = tuple(s for s in secrets if s) self.seen: Set[int] = set() + self.done: Dict[int, BaseException] = {} def value(self, value: Any, depth: int) -> Any: """``value`` with secrets masked; mutable objects are cleaned in place.""" @@ -103,7 +108,11 @@ def value(self, value: Any, depth: int) -> Any: return self.exception(value, depth + 1) if isinstance(value, dict): return { - self.value(k, depth + 1): self.value(v, depth + 1) + self.value(k, depth + 1): ( + REDACTED + if isinstance(k, str) and _SECRET_FIELD.match(k) and v + else self.value(v, depth + 1) + ) for k, v in value.items() } if isinstance(value, list): @@ -176,9 +185,9 @@ def object(self, obj: Any, depth: int) -> None: def exception(self, error: BaseException, depth: int = 0) -> BaseException: """``error`` masked in place, or a masked stand-in when that is not enough.""" - if id(error) in self.seen: - return error - self.seen.add(id(error)) + if id(error) in self.done: + return self.done[id(error)] + self.done[id(error)] = error try: error.args = tuple(self.value(a, depth + 1) for a in error.args) except Exception: @@ -196,8 +205,8 @@ def exception(self, error: BaseException, depth: int = 0) -> BaseException: if error.__context__ is not None: error.__context__ = self.exception(error.__context__, depth + 1) if self._exception_leaks(error): - return self._stand_in(error) - return error + self.done[id(error)] = self._stand_in(error) + return self.done[id(error)] def _exception_leaks(self, error: BaseException) -> bool: try: diff --git a/tests/test_redaction.py b/tests/test_redaction.py index 76cc780..d1e9698 100644 --- a/tests/test_redaction.py +++ b/tests/test_redaction.py @@ -331,3 +331,26 @@ def connect(url, **kwargs): async for _ in stream: pass assert_no_key(info.value) + + +def test_an_exception_reached_twice_gets_the_same_stand_in(): + from yarl import URL + + shared = _raised(aiohttp.InvalidURL(URL(URL_WITH_KEY), "bad redirect")) + outer = RuntimeError("outer") + outer.reason = shared + outer.__cause__ = shared + clean = scrub_exception(_raised(outer), (KEY,)) + assert clean.reason is clean.__cause__ + assert_no_key(clean) + + +def test_credential_fields_in_mappings_are_masked(): + error = OddsAPIError( + "boom", + body={"apiKey": "other-key", "detail": "x"}, + headers={"Authorization": "Bearer other-token", "Content-Type": "json"}, + ) + clean = scrub_exception(error, (KEY,)) + assert clean.body == {"apiKey": "***", "detail": "x"} + assert clean.headers == {"Authorization": "***", "Content-Type": "json"} From 2f12707f321d73935b4c40bf178a4366ac1db63b Mon Sep 17 00:00:00 2001 From: odds-api-io Date: Thu, 26 Nov 2026 09:29:27 +0100 Subject: [PATCH 4/4] fix: mask detached copies of transport objects, never the live ones Objects held by an exception, such as a connection pool with proxy headers or a prepared request, may still be used by the session. Replace the exception's reference with a masked shallow copy instead of modifying the original. --- odds_api/_redact.py | 35 ++++++++++++++++++++++------------- tests/test_redaction.py | 26 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/odds_api/_redact.py b/odds_api/_redact.py index 02a4fae..f6495f7 100644 --- a/odds_api/_redact.py +++ b/odds_api/_redact.py @@ -7,10 +7,11 @@ ``__str__`` reads a read-only property) is replaced by a masked stand-in. """ +import copy import dataclasses import re import traceback -from typing import Any, Dict, Iterable, List, Optional, Set, Tuple +from typing import Any, Dict, Iterable, List, Optional, Tuple from urllib.parse import quote, quote_plus REDACTED = "***" @@ -88,7 +89,7 @@ def _attr_names(obj: Any) -> List[str]: class _Scrubber: def __init__(self, secrets: Iterable[Optional[str]]): self.secrets: Secrets = tuple(s for s in secrets if s) - self.seen: Set[int] = set() + self.copies: Dict[int, Any] = {} self.done: Dict[int, BaseException] = {} def value(self, value: Any, depth: int) -> Any: @@ -119,8 +120,8 @@ def value(self, value: Any, depth: int) -> Any: return [self.value(v, depth + 1) for v in value] if isinstance(value, tuple) and not hasattr(value, "_fields"): return tuple(self.value(v, depth + 1) for v in value) - if id(value) in self.seen: - return value + if id(value) in self.copies: + return self.copies[id(value)] if not _shows_secret(value, self.secrets) and not self._holds_secret(value): return value record = self._record(value, depth) @@ -129,10 +130,7 @@ def value(self, value: Any, depth: int) -> Any: rebuilt = self._rebuild(value) if rebuilt is not None: return rebuilt - self.object(value, depth + 1) - if _shows_secret(value, self.secrets): - return redact(str(value), self.secrets) - return value + return self._detached(value, depth + 1) def _holds_secret(self, obj: Any) -> bool: try: @@ -170,10 +168,18 @@ def _record(self, value: Any, depth: int) -> Any: return None return None if _shows_secret(clean, self.secrets) else clean - def object(self, obj: Any, depth: int) -> None: - if id(obj) in self.seen: - return - self.seen.add(id(obj)) + def _detached(self, obj: Any, depth: int) -> Any: + """A masked shallow copy of ``obj``; the original, which may be live transport + state such as a connection pool, is never modified.""" + try: + clone = copy.copy(obj) + except Exception: + clone = None + if clone is None or clone is obj: + masked = redact(str(obj), self.secrets) + self.copies[id(obj)] = masked + return masked + self.copies[id(obj)] = clone for name in _attr_names(obj): try: current = getattr(obj, name) @@ -181,7 +187,10 @@ def object(self, obj: Any, depth: int) -> None: continue clean = self.value(current, depth) if clean is not current: - _set(obj, name, clean) + _set(clone, name, clean) + if _shows_secret(clone, self.secrets): + self.copies[id(obj)] = redact(str(obj), self.secrets) + return self.copies[id(obj)] def exception(self, error: BaseException, depth: int = 0) -> BaseException: """``error`` masked in place, or a masked stand-in when that is not enough.""" diff --git a/tests/test_redaction.py b/tests/test_redaction.py index d1e9698..b645e42 100644 --- a/tests/test_redaction.py +++ b/tests/test_redaction.py @@ -354,3 +354,29 @@ def test_credential_fields_in_mappings_are_masked(): clean = scrub_exception(error, (KEY,)) assert clean.body == {"apiKey": "***", "detail": "x"} assert clean.headers == {"Authorization": "***", "Content-Type": "json"} + + +def test_live_transport_objects_are_not_modified(): + class Pool: + def __init__(self): + self.proxy_headers = {"Proxy-Authorization": "Basic cHJveHk6c2VjcmV0"} + self.url = URL_WITH_KEY + + pool = Pool() + headers = pool.proxy_headers + error = RuntimeError("connection failed") + error.pool = pool + clean = scrub_exception(_raised(error), (KEY,)) + assert_no_key(clean) + assert pool.proxy_headers is headers + assert headers == {"Proxy-Authorization": "Basic cHJveHk6c2VjcmV0"} + assert pool.url == URL_WITH_KEY + assert clean.pool is not pool + + +def test_requests_prepared_request_is_not_modified(): + prepared = requests.Request("GET", URL_WITH_KEY).prepare() + error = requests.ConnectionError("refused", request=prepared) + clean = scrub_exception(_raised(error), (KEY,)) + assert_no_key(clean) + assert prepared.url == URL_WITH_KEY