diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f983e9..cc1dfe5 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. 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) ### 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..f6495f7 --- /dev/null +++ b/odds_api/_redact.py @@ -0,0 +1,247 @@ +"""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 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 copy +import dataclasses +import re +import traceback +from typing import Any, Dict, Iterable, List, Optional, Tuple +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,}&]+" +) +_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, ...] + + +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 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 _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: Secrets) -> bool: + return redact(text, secrets) != text + + +def _shows_secret(value: Any, secrets: Secrets) -> bool: + try: + return _leaks(str(value), secrets) or _leaks(repr(value), secrets) + except Exception: + return True + + +def _set(obj: Any, name: str, value: Any) -> bool: + try: + setattr(obj, name, value) + return True + except Exception: + try: + object.__setattr__(obj, name, value) + return True + except Exception: + 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.copies: Dict[int, Any] = {} + self.done: Dict[int, BaseException] = {} + + 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): ( + 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): + 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.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) + if record is not None: + return record + rebuilt = self._rebuild(value) + if rebuilt is not None: + return rebuilt + return self._detached(value, depth + 1) + + def _holds_secret(self, obj: Any) -> bool: + try: + return any( + _shows_secret(getattr(obj, name, None), self.secrets) + for name in _attr_names(obj) + ) + except Exception: + 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 _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 _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) + except Exception: + continue + clean = self.value(current, depth) + if clean is not current: + _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.""" + 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: + 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): + self.done[id(error)] = self._stand_in(error) + return self.done[id(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 _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]] +) -> BaseException: + """Mask secrets in ``error`` and its whole chain. + + 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/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..d752cda 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, @@ -136,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 @@ -153,28 +155,13 @@ async def __aiter__(self) -> AsyncIterator[Dict[str, Any]]: except OSError: code = None except Exception as e: - status = _handshake_status(e) - if status is None: - raise - if status == 400: - raise ValidationError( - f"WebSocket refused: {e}", status_code=status - ) from e - if status == 401: - raise InvalidAPIKeyError( - f"WebSocket refused: {e}", status_code=status - ) from e - if status == 403: - raise ForbiddenError( - f"WebSocket refused: {e}", status_code=status - ) from e - if status < 500 and status != 429: - raise OddsAPIError( - f"WebSocket refused: {e}", 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: @@ -191,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/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..b645e42 --- /dev/null +++ b/tests/test_redaction.py @@ -0,0 +1,382 @@ +"""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 _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 + assert _find_key(error, "error", set()) == [] + 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) + + +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) + + +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"} + + +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