Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk-python): trim a default header and take the shapes httpx takes
Yudhi Armyndharis1fe1650d15eb
diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.pyindex 225ba23c2..d1f733da2 100644--- a/sdk/python/openwa/_http.py+++ b/sdk/python/openwa/_http.py@@ -106,13 +106,36 @@ def resolve_timeout(_HEADER_NAME_CHARS = frozenset("!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")-def check_default_headers(default_headers: Mapping[str, str] | None) -> None:- """Refuse a default header the HTTP layer would refuse, naming the header and never its value.-- A credential for a proxy in front of the gateway is usually read from a file and keeps its newline;- the stack's own error quotes the value, which would put the credential in the application's log.+def clean_default_headers(default_headers: Any) -> httpx.Headers:+ """The default headers as httpx will hold them, or a ``ValueError`` naming the header and never its value.++ Whatever httpx takes (a mapping, a list of ``(name, value)`` pairs, text or bytes) is read the same way.+ A value is trimmed of the spaces and tabs the HTTP stack would refuse at its ends, as the JDK and PSR-7+ do, and refused when a control or non-ASCII character is left. A credential for a proxy in front of the+ gateway is usually read from a file and keeps its newline; the stack's own error quotes the value, which+ would put the credential in the application's log."""- for name, value in (default_headers or {}).items():+ if default_headers is None:+ return httpx.Headers()+ if isinstance(default_headers, Mapping):+ pairs: list[Any] = list(default_headers.items())+ else:+ try:+ pairs = list(default_headers)+ except TypeError:+ raise ValueError(+ "OpenWAClient: default_headers must be a mapping of header names to text, or (name, value) pairs"+ ) from None+ cleaned: list[tuple[str, str]] = []+ for pair in pairs:+ try:+ name, value = pair+ except (TypeError, ValueError):+ raise ValueError("OpenWAClient: default_headers entries must be (name, value) pairs") from None+ if isinstance(name, bytes):+ name = name.decode("latin-1")+ if isinstance(value, bytes):+ value = value.decode("latin-1")if not isinstance(name, str) or not name or not all(char in _HEADER_NAME_CHARS for char in name):raise ValueError("OpenWAClient: default_headers has a header name that is not a valid HTTP token")if not isinstance(value, str) or any(char != "\t" and not " " <= char <= "~" for char in value):@@ -120,6 +143,8 @@ def check_default_headers(default_headers: Mapping[str, str] | None) -> None:f"OpenWAClient: default_headers value for {name!r} must be text without control or non-ASCII ""characters; check for a stray newline")+ cleaned.append((name, value.strip(" \t")))+ return httpx.Headers(cleaned)class HttpExecutor:@@ -138,12 +163,11 @@ class HttpExecutor:transport: httpx.BaseTransport | None = None,) -> None:timeout = resolve_timeout(timeout)- check_default_headers(default_headers)# Caller-supplied default headers are applied FIRST so the auth/JSON# headers below always win and can never be clobbered (mirrors the JS SDK).# httpx.Headers matches names case-insensitively, so a lowercase copy is# replaced instead of being sent alongside ours.- headers = httpx.Headers(default_headers)+ headers = clean_default_headers(default_headers)headers["Content-Type"] = "application/json"headers["X-API-Key"] = api_keyclient_kwargs: dict[str, Any] = {diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex b9fb21730..ffc977d78 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -308,6 +308,28 @@ class TestClientCore:client = OpenWAClient(base_url="https://x", api_key="k", default_headers={"X-Trace": "a\tb c"})assert client._http._client.headers["X-Trace"] == "a\tb c"+ def test_a_default_header_value_is_trimmed_of_the_spaces_the_stack_would_refuse_at_its_ends(self):+ client = OpenWAClient(+ base_url="https://x", api_key="k", default_headers={"X-Proxy-Cred": " token \t", "X-Other": "\tv"}+ )+ assert client._http._client.headers["X-Proxy-Cred"] == "token"+ assert client._http._client.headers["X-Other"] == "v"++ def test_default_headers_take_every_shape_httpx_takes_and_refuse_the_rest_by_name(self):+ pairs = OpenWAClient(+ base_url="https://x", api_key="k", default_headers=[("X-Trace", "abc"), ("X-Two", "2")] # type: ignore[arg-type]+ )+ assert pairs._http._client.headers["X-Trace"] == "abc"+ assert pairs._http._client.headers["X-Two"] == "2"+ raw = OpenWAClient(base_url="https://x", api_key="k", default_headers={b"X-Trace": b"abc"}) # type: ignore[dict-item]+ assert raw._http._client.headers["X-Trace"] == "abc"+ with pytest.raises(ValueError, match="X-Trace") as raised:+ OpenWAClient(base_url="https://x", api_key="k", default_headers={"X-Trace": b"s3cret\n"}) # type: ignore[dict-item]+ assert "s3cret" not in str(raised.value)+ for bad in (42, ["X-Trace"], [("X-Trace", "a", "b")]):+ with pytest.raises(ValueError, match="default_headers"):+ OpenWAClient(base_url="https://x", api_key="k", default_headers=bad) # type: ignore[arg-type]+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)