Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk-python): trim the API key, keep accepting httpx timeouts
Yudhi Armyndharis887b15799a33
diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.pyindex 6a15f4dd3..73f051fa8 100644--- a/sdk/python/openwa/_http.py+++ b/sdk/python/openwa/_http.py@@ -65,15 +65,33 @@ def build_url(base_url: str, path: str, query: Mapping[str, Any] | None = None)return str(httpx.URL(url).copy_merge_params(params))-def resolve_timeout(timeout: float | None) -> float | None:+def resolve_timeout(+ timeout: float | httpx.Timeout | tuple[float | None, float | None, float | None, float | None] | None,+) -> float | httpx.Timeout | None:"""The timeout httpx is given: seconds per network operation, or ``None`` for none.``None``, ``0`` and ``math.inf`` mean no timeout, as ``0`` does in the JavaScript and PHP clients;- httpx would otherwise take ``0`` literally and fail every connect. Anything that is not a+ httpx would otherwise take ``0`` literally and fail every connect. An :class:`httpx.Timeout`, or a+ ``(connect, read, write, pool)`` tuple, goes to httpx as given: they were accepted before this+ validator existed, and are the way to set the operations apart. Anything else that is not anon-negative number raises at construction rather than at the first request."""if timeout is None:return None+ if isinstance(timeout, httpx.Timeout):+ return timeout+ if isinstance(timeout, tuple):+ parts = [part for part in timeout]+ if len(parts) != 4 or any(+ part is not None+ and (isinstance(part, bool) or not isinstance(part, (int, float)) or math.isnan(part) or part < 0)+ for part in parts+ ):+ raise ValueError(+ "OpenWAClient: a timeout tuple is (connect, read, write, pool), each a non-negative number "+ f"of seconds or None (got {timeout!r})"+ )+ return httpx.Timeout(timeout)if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or math.isnan(timeout) or timeout < 0:raise ValueError(f"OpenWAClient: timeout must be a non-negative number of seconds, or None for none (got {timeout!r})"@@ -92,7 +110,7 @@ class HttpExecutor:self,base_url: str,api_key: str,- timeout: float | None = 30.0,+ timeout: float | httpx.Timeout | tuple[float | None, float | None, float | None, float | None] | None = 30.0,default_headers: Mapping[str, str] | None = None,transport: httpx.BaseTransport | None = None,) -> None:@@ -116,7 +134,13 @@ class HttpExecutor:if transport is not None:client_kwargs["transport"] = transportself._client = httpx.Client(**client_kwargs)- self._timeout = timeout+ # The seconds a timeout error reports: the one number given, or for an httpx.Timeout the longest+ # of its operations that has a limit.+ if isinstance(timeout, httpx.Timeout):+ limits = [part for part in (timeout.connect, timeout.read, timeout.write, timeout.pool) if part is not None]+ self._timeout: float | None = max(limits) if limits else None+ else:+ self._timeout = timeoutdef close(self) -> None:self._client.close()diff --git a/sdk/python/openwa/client.py b/sdk/python/openwa/client.pyindex d91b669a4..037647a02 100644--- a/sdk/python/openwa/client.py+++ b/sdk/python/openwa/client.py@@ -87,14 +87,22 @@ class OpenWAClient:*,# Seconds per network operation (connect, read, write, pool), not for the whole call: a response# that keeps trickling bytes is not cut off. 0 or None means no timeout.- timeout: float | None = 30.0,+ timeout: float | httpx.Timeout | tuple[float | None, float | None, float | None, float | None] | None = 30.0,default_headers: Mapping[str, str] | None = None,transport: httpx.BaseTransport | None = None,) -> None:if not base_url:raise ValueError("OpenWAClient: base_url is required")+ # A key read from a secret file usually ends in a newline, which the HTTP layer refuses with an error+ # that quotes the whole key. Trim it, and refuse anything that is still not a plain token.+ api_key = api_key.strip() if isinstance(api_key, str) else api_keyif not api_key:raise ValueError("OpenWAClient: api_key is required")+ if not isinstance(api_key, str) or not all("!" <= char <= "~" for char in api_key):+ raise ValueError(+ "OpenWAClient: api_key contains illegal characters (whitespace, control or non-ASCII); "+ "check for a stray newline"+ )_warn_if_insecure_http(base_url)self._http = HttpExecutor(base_url=base_url,diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 54ec28e0c..86a658de9 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -263,6 +263,27 @@ class TestClientCore:assert "Bad Gateway" in str(caught.value)assert "None" not in str(caught.value)+ def test_an_httpx_timeout_or_a_tuple_is_taken_as_given(self):+ # The published 0.5.1 handed `timeout` straight to httpx, which takes both.+ per_operation = httpx.Timeout(10.0, connect=2.0)+ client = OpenWAClient(base_url="https://x", api_key="k", timeout=per_operation)+ assert client._http._client.timeout == per_operation+ client = OpenWAClient(base_url="https://x", api_key="k", timeout=(1.0, 2.0, 3.0, 4.0))+ assert client._http._client.timeout == httpx.Timeout(connect=1.0, read=2.0, write=3.0, pool=4.0)+ for bad in [(1.0, 2.0), (1.0, 2.0, 3.0, -1.0), (1.0, "2", 3.0, 4.0)]:+ with pytest.raises(ValueError, match="timeout tuple"):+ OpenWAClient(base_url="https://x", api_key="k", timeout=bad) # type: ignore[arg-type]++ def test_the_api_key_loses_a_trailing_newline_and_an_illegal_one_is_refused_without_being_quoted(self):+ client = OpenWAClient(base_url="https://x", api_key="owa_k1_secret\n")+ assert client._http._client.headers["X-API-Key"] == "owa_k1_secret"+ for bad in ["owa_k1 secret", "owa_k1_se\x00cret", "owa_k1_sécret"]:+ with pytest.raises(ValueError, match="api_key") as raised:+ OpenWAClient(base_url="https://x", api_key=bad)+ assert bad not in str(raised.value)+ with pytest.raises(ValueError, match="required"):+ OpenWAClient(base_url="https://x", api_key=" \n")+def test_timeout_zero_none_and_inf_mean_none_and_a_bad_value_raises(self):for none in (0, None, float("inf")):client = OpenWAClient(base_url="https://x", api_key="k", timeout=none)