Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk): validate default headers, accept an inner space in a key

Yudhi Armyndharis173ed20c6df9
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java b/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java
index 6cb183204..db5ecbc2d 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java
@@ -30,7 +30,7 @@ public final class ClientConfig {
}
if (hasIllegalChar(key)) {
throw new IllegalArgumentException(
- "OpenWAClient: apiKey contains illegal characters (whitespace, control or non-ASCII) — check for a stray newline");
+ "OpenWAClient: apiKey contains illegal characters (control or non-ASCII) — check for a stray newline");
}
if (b.timeout != null && (b.timeout.isZero() || b.timeout.isNegative())) {
throw new IllegalArgumentException("OpenWAClient: timeout must be positive");
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
index 5c1be9503..b791ad3d8 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
@@ -49,7 +49,7 @@ import java.util.Map;
* // Sessions are addressed by the UUID that create() returns, not by name.
* SessionResponse session = client.sessions.create(CreateSessionRequest.builder().name("my-session").build());
* client.sessions.start(session.id());
- * // Link the account before sending: scan sessions.getQrCode or use sessions.requestPairingCode,
+ * // Link the account before sending: scan sessions.getQrCode (or use sessions.requestPairingCode for a number with no linked session),
* // then wait for status READY. An unlinked session answers the send with 409.
* client.messages.sendText(session.id(),
* SendTextRequest.builder().chatId("[email protected]").text("Hello!").build());
@@ -255,10 +255,12 @@ public final class OpenWAClient {
} catch (IllegalArgumentException e) {
// e.g. a JDK-restricted header name in defaultHeaders, or a URI-illegal char — keep it
// inside the OpenWAError contract instead of leaking a raw JDK exception to the caller.
- // The JDK words a refused header as: invalid header value: "<the value>". Never repeat that.
+ // The JDK words a refused header VALUE as: invalid header value: "<the value>". Never repeat that.
+ // A refused header NAME is worded with the name only (restricted header name: "Host"), which is
+ // what tells the caller what to change, so it stays.
String why = reason(e);
- if (why.toLowerCase(java.util.Locale.ROOT).contains("header")) {
- why = "a header was refused by the HTTP stack (check defaultHeaders for control or non-ASCII characters)";
+ if (why.toLowerCase(java.util.Locale.ROOT).contains("header value")) {
+ why = "a header value was refused by the HTTP stack (check defaultHeaders for control or non-ASCII characters)";
}
throw new OpenWAError("Invalid request — " + method + " " + path + ": " + why);
}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/ConfigTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/ConfigTest.java
index 14133fa6d..d016b8935 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/ConfigTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/ConfigTest.java
@@ -93,6 +93,33 @@ class ConfigTest {
assertTrue(e.getMessage().contains("Invalid request"));
}
+ @Test
+ void aRefusedHeaderValueIsNotRepeatedButARefusedHeaderNameIsNamed() {
+ HttpTransport badValue = req -> {
+ throw new IllegalArgumentException("invalid header value: \"s3cret-token\"");
+ };
+ OpenWAError value = assertThrows(OpenWAError.class,
+ () -> new OpenWAClient(base().transport(badValue).build())
+ .request(HttpMethod.GET, "/x", null, null, SuccessResult.class));
+ assertFalse(value.getMessage().contains("s3cret-token"));
+ assertTrue(value.getMessage().contains("header value"));
+
+ HttpTransport restricted = req -> {
+ throw new IllegalArgumentException("restricted header name: \"Host\"");
+ };
+ OpenWAError name = assertThrows(OpenWAError.class,
+ () -> new OpenWAClient(base().transport(restricted).build())
+ .request(HttpMethod.GET, "/x", null, null, SuccessResult.class));
+ assertTrue(name.getMessage().contains("restricted header name: \"Host\""));
+ }
+
+ @Test
+ void anApiKeyWithAnInnerSpaceIsAcceptedAsTheGatewayAndOtherClientsTakeIt() {
+ MockTransport tx = new MockTransport().respond(200, "{\"valid\":true}");
+ new OpenWAClient(ClientConfig.builder().baseUrl("http://h").apiKey("correct horse battery staple\n").transport(tx).build()).auth();
+ assertEquals("correct horse battery staple", tx.lastRequest().headers().get("X-API-Key"));
+ }
+
@Test
void rejectsApiKeyWithNonAsciiCharacterWithoutEchoingIt() {
// A zero-width space is a common copy artifact; the JDK would quote the whole key when it
diff --git a/sdk/php/src/Client.php b/sdk/php/src/Client.php
index d630e2035..d1ce454d5 100644
--- a/sdk/php/src/Client.php
+++ b/sdk/php/src/Client.php
@@ -42,7 +42,7 @@ use OpenWA\Resources\WebhooksResource;
* // Sessions are addressed by the UUID that create() returns, not by name.
* $session = $client->sessions->create(['name' => 'my-session']);
* $client->sessions->start($session['id']);
- * // Link the account before sending: scan sessions->getQrCode or use sessions->requestPairingCode,
+ * // Link the account before sending: scan sessions->getQrCode (or use sessions->requestPairingCode for a number with no linked session),
* // then wait for status 'ready'. An unlinked session answers the send with 409.
* $result = $client->messages->sendText($session['id'], [
* 'chatId' => '[email protected]',
@@ -86,21 +86,21 @@ class Client
*
* @throws OpenWAException If baseUrl or apiKey is missing.
*/
- public function __construct(array $config)
+ public function __construct(#[\SensitiveParameter] array $config)
{
if (empty($config['baseUrl'])) {
throw new OpenWAException('OpenWA Client: baseUrl 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.
+ // that quotes the whole key. Trim it, and refuse a control or non-ASCII character left inside: the
+ // gateway takes any printable ASCII, a space included, and the other clients send it as it is.
$apiKey = is_string($config['apiKey'] ?? null) ? trim($config['apiKey']) : ($config['apiKey'] ?? '');
if (empty($apiKey)) {
throw new OpenWAException('OpenWA Client: apiKey is required');
}
- if (!is_string($apiKey) || preg_match('/\A[\x21-\x7e]+\z/', $apiKey) !== 1) {
+ if (!is_string($apiKey) || preg_match('/\A[\x20-\x7e]+\z/', $apiKey) !== 1) {
throw new OpenWAException(
- 'OpenWA Client: apiKey contains illegal characters (whitespace, control or non-ASCII); '
- . 'check for a stray newline'
+ 'OpenWA Client: apiKey contains a control or non-ASCII character; check for a stray newline'
);
}
diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.php
index 7041ac971..046065e31 100644
--- a/sdk/php/src/Http/HttpExecutor.php
+++ b/sdk/php/src/Http/HttpExecutor.php
@@ -7,6 +7,7 @@ namespace OpenWA\Http;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use OpenWA\Exceptions\OpenWAApiException;
+use OpenWA\Exceptions\OpenWAException;
use OpenWA\Exceptions\OpenWATimeoutException;
use Psr\Http\Message\ResponseInterface;
@@ -21,18 +22,19 @@ use Psr\Http\Message\ResponseInterface;
class HttpExecutor
{
/**
- * The API keys of the executors, outside their property tables: print_r, var_dump, var_export, a
- * (array) cast and a framework's dumper all read properties, and the key is bearer-equivalent.
+ * The API keys and default header values of the executors, outside their property tables: print_r,
+ * var_dump, var_export, an (array) cast and a framework's dumper all read properties, and both are
+ * bearer-equivalent (a header often carries the credential of a proxy in front of the gateway).
*
- * @var \WeakMap<HttpExecutor,string>|null
+ * @var \WeakMap<HttpExecutor,array{apiKey:string,headers:array<string,string>}>|null
*/
- private static ?\WeakMap $keys = null;
+ private static ?\WeakMap $secrets = null;
private ClientInterface $http;
private float $timeout;
private string $baseUrl;
- /** @var array<string,string> */
- private array $defaultHeaders;
+ /** @var list<string> Only the names: see $secrets for the values. */
+ private array $headerNames;
/**
* @param array<string,string> $defaultHeaders Applied UNDER the auth/JSON headers
@@ -40,16 +42,17 @@ class HttpExecutor
*/
public function __construct(
string $baseUrl,
- string $apiKey,
+ #[\SensitiveParameter] string $apiKey,
float $timeout = 30.0,
?ClientInterface $httpClient = null,
- array $defaultHeaders = []
+ #[\SensitiveParameter] array $defaultHeaders = []
) {
+ self::checkDefaultHeaders($defaultHeaders);
$this->timeout = $timeout;
- self::$keys ??= new \WeakMap();
- self::$keys[$this] = $apiKey;
+ self::$secrets ??= new \WeakMap();
+ self::$secrets[$this] = ['apiKey' => $apiKey, 'headers' => $defaultHeaders];
$this->baseUrl = rtrim($baseUrl, '/');
- $this->defaultHeaders = $defaultHeaders;
+ $this->headerNames = array_map('strval', array_keys($defaultHeaders));
// Auth/JSON headers are applied per-request (in request()). Request URLs
// are built absolute (baseUrl . path) so a base path prefix (e.g. /v1
// behind a reverse proxy) is preserved; base_uri is intentionally unset,
@@ -59,9 +62,36 @@ class HttpExecutor
]);
}
+ /**
+ * Refuse a default header the HTTP stack would refuse, naming the header and never its value: the
+ * stack's own message quotes the value, which would put a proxy credential in the application's log.
+ *
+ * @param array<mixed> $headers
+ *
+ * @throws OpenWAException
+ */
+ private static function checkDefaultHeaders(array $headers): void
+ {
+ foreach ($headers as $name => $value) {
+ if (!is_string($name) || preg_match('/\A[!#$%&\'*+\-.^_`|~0-9A-Za-z]+\z/', $name) !== 1) {
+ throw new OpenWAException(
+ 'OpenWA Client: defaultHeaders has a header name that is not a valid HTTP token'
+ );
+ }
+ if (!is_string($value) || preg_match('/\A[\t\x20-\x7e]*\z/', $value) !== 1) {
+ throw new OpenWAException(sprintf(
+ 'OpenWA Client: defaultHeaders value for "%s" must be text without control or non-ASCII '
+ . 'characters; check for a stray newline',
+ $name
+ ));
+ }
+ }
+ }
+
/**
* What print_r and var_dump show of the executor, and so of every client and resource that holds it.
- * The key is not among the properties at all (see $keys), so no dump, export or cast can reach it.
+ * The key and the header values are not among the properties at all (see $secrets), so no dump,
+ * export or cast can reach them.
*
* @return array<string,mixed>
*/
@@ -71,7 +101,7 @@ class HttpExecutor
'baseUrl' => $this->baseUrl,
'timeout' => $this->timeout,
'apiKey' => '[redacted]',
- 'defaultHeaders' => array_keys($this->defaultHeaders),
+ 'defaultHeaders' => $this->headerNames,
];
}
@@ -170,6 +200,7 @@ class HttpExecutor
// Auth/JSON headers are applied per-request so they are correct whether
// a default or injected client is used (and never leak Guzzle exceptions:
// http_errors disabled so we translate status into typed SDK exceptions).
+ $secrets = (self::$secrets ?? new \WeakMap())[$this] ?? ['apiKey' => '', 'headers' => []];
$options = [
'http_errors' => false,
// Per-request options override injected Guzzle client defaults, so the SDK's configured
@@ -181,12 +212,12 @@ class HttpExecutor
// Caller default headers first; auth/JSON win so they can't be clobbered. Header names are
// case-insensitive and PSR-7 keeps every value, so a caller's copy in another case is dropped.
'headers' => array_merge(array_filter(
- $this->defaultHeaders,
+ $secrets['headers'],
fn ($name) => !in_array(strtolower((string) $name), ['x-api-key', 'content-type', 'accept'], true)
&& ($idempotencyKey === null || strtolower((string) $name) !== 'idempotency-key'),
ARRAY_FILTER_USE_KEY
), [
- 'X-API-Key' => (self::$keys ?? new \WeakMap())[$this] ?? '',
+ 'X-API-Key' => $secrets['apiKey'],
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]),
diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.php
index f3785e6cf..08b90c7a9 100644
--- a/sdk/php/tests/ClientTest.php
+++ b/sdk/php/tests/ClientTest.php
@@ -20,7 +20,7 @@ class ClientTest extends TestCase
$backend->makeClient('http://localhost:2785', "owa_k1_secret\n")->request('GET', '/api/anything');
$this->assertSame('owa_k1_secret', $backend->lastCall()['headers']['x-api-key'] ?? null);
- foreach (['owa_k1 secret', "owa_k1_se\0cret", "owa_k1_s\u{e9}cret"] as $bad) {
+ foreach (["owa_k1_se\tcret", "owa_k1_se\0cret", "owa_k1_s\u{e9}cret", "owa_k1_se\ncret"] as $bad) {
try {
(new MockBackend())->makeClient('http://localhost:2785', $bad);
$this->fail('Expected an exception for an illegal key');
@@ -34,6 +34,43 @@ class ClientTest extends TestCase
(new MockBackend())->makeClient('http://localhost:2785', " \n");
}
+ public function testAKeyWithAnInnerSpaceIsAcceptedAsTheGatewayAndOtherClientsTakeIt(): void
+ {
+ $backend = (new MockBackend())->on(200, []);
+ $key = 'correct horse battery staple correct horse';
+ $backend->makeClient('http://localhost:2785', $key . "\n")->request('GET', '/api/anything');
+ $this->assertSame($key, $backend->lastCall()['headers']['x-api-key'] ?? null);
+ }
+
+ public function testADefaultHeaderTheStackWouldRefuseIsRefusedWithoutQuotingItsValue(): void
+ {
+ $cases = [['CF-Access-Client-Secret', "s3cret-token\n"], ['X-Trace', "caf\u{e9}"], ['X-Trace', "a\0b"]];
+ foreach ($cases as [$name, $value]) {
+ try {
+ new \OpenWA\Client(['baseUrl' => 'http://localhost:2785', 'apiKey' => 'k', 'defaultHeaders' => [$name => $value]]);
+ $this->fail('Expected an exception for an illegal header value');
+ } catch (\OpenWA\Exceptions\OpenWAException $e) {
+ $this->assertStringContainsString($name, $e->getMessage());
+ $this->assertStringNotContainsString(trim($value), $e->getMessage());
+ }
+ }
+ try {
+ new \OpenWA\Client(['baseUrl' => 'http://localhost:2785', 'apiKey' => 'k', 'defaultHeaders' => ['X Bad' => 'v']]);
+ $this->fail('Expected an exception for an illegal header name');
+ } catch (\OpenWA\Exceptions\OpenWAException $e) {
+ $this->assertStringContainsString('header name', $e->getMessage());
+ }
+ // A tab and plain printable ASCII are fine.
+ $backend = (new MockBackend())->on(200, []);
+ (new \OpenWA\Client([
+ 'baseUrl' => 'http://localhost:2785',
+ 'apiKey' => 'k',
+ 'httpClient' => $backend->httpClient(),
+ 'defaultHeaders' => ['X-Trace' => "a\tb c"],
+ ]))->request('GET', '/api/anything');
+ $this->assertSame("a\tb c", $backend->lastCall()['headers']['x-trace'] ?? null);
+ }
+
public function testRequiresBaseUrlAndApiKey(): void
{
$this->expectException(\OpenWA\Exceptions\OpenWAException::class);
diff --git a/sdk/php/tests/HttpExecutorTest.php b/sdk/php/tests/HttpExecutorTest.php
index 9a8c14025..fa790956f 100644
--- a/sdk/php/tests/HttpExecutorTest.php
+++ b/sdk/php/tests/HttpExecutorTest.php
@@ -51,6 +51,43 @@ class HttpExecutorTest extends TestCase
$this->assertSame($key, $backend->lastCall()['headers']['x-api-key'] ?? null);
}
+ /**
+ * A default header often carries the credential of a proxy in front of the gateway: it is held out of
+ * the property table with the key, and only its name shows.
+ */
+ public function testDefaultHeaderValuesDoNotAppearWhenTheClientIsDumpedEither(): void
+ {
+ $secret = 'PROXYSECRET';
+ $backend = (new MockBackend())->on(200, []);
+ $client = new \OpenWA\Client([
+ 'baseUrl' => 'http://localhost:2785',
+ 'apiKey' => 'owa_k1_test',
+ 'httpClient' => $backend->httpClient(),
+ 'defaultHeaders' => ['CF-Access-Client-Secret' => $secret],
+ ]);
+ $executor = (new \ReflectionObject($client))->getProperty('http')->getValue($client);
+
+ $this->assertStringNotContainsString($secret, print_r($client, true));
+ $this->assertStringContainsString('CF-Access-Client-Secret', print_r($client, true));
+ $this->assertStringNotContainsString($secret, var_export($client, true));
+ $this->assertStringNotContainsString($secret, var_export($executor, true));
+ $this->assertStringNotContainsString($secret, print_r((array) $executor, true));
+ // and the value is still what goes out on the wire
+ $client->request('GET', '/api/anything');
+ $this->assertSame($secret, $backend->lastCall()['headers']['cf-access-client-secret'] ?? null);
+ }
+
+ /** A copy would have no key and no headers, since both belong to the object they were given to. */
+ public function testAnExecutorCannotBeCloned(): void
+ {
+ $client = (new MockBackend())->makeClient();
+ $executor = (new \ReflectionObject($client))->getProperty('http')->getValue($client);
+
+ $this->expectException(\Error::class);
+ $copy = clone $executor;
+ $this->assertNotSame($executor, $copy);
+ }
+
public function testQueryParamsExtendAQueryAlreadyInThePath(): void
{
$backend = (new MockBackend())->on(200, [])->on(200, []);
diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.py
index 73f051fa8..225ba23c2 100644
--- a/sdk/python/openwa/_http.py
+++ b/sdk/python/openwa/_http.py
@@ -71,10 +71,11 @@ def resolve_timeout(
"""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. 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 a
- non-negative number raises at construction rather than at the first request.
+ httpx would otherwise take ``0`` literally and fail every connect. A ``(connect, read, write, pool)``
+ tuple is the way to set the operations apart, and each of its elements means the same: ``0`` and
+ ``math.inf`` leave that operation without a limit. An :class:`httpx.Timeout` goes to httpx as given,
+ since it was accepted before this validator existed. Anything else that is not a non-negative number
+ raises at construction rather than at the first request.
"""
if timeout is None:
return None
@@ -91,7 +92,10 @@ def resolve_timeout(
"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)
+ connect, read, write, pool = (
+ None if part is None or part == 0 or math.isinf(part) else float(part) for part in parts
+ )
+ return httpx.Timeout(connect=connect, read=read, write=write, pool=pool)
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})"
@@ -99,6 +103,25 @@ def resolve_timeout(
return None if timeout == 0 or math.isinf(timeout) else float(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.
+ """
+ for name, value in (default_headers or {}).items():
+ 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):
+ raise ValueError(
+ f"OpenWAClient: default_headers value for {name!r} must be text without control or non-ASCII "
+ "characters; check for a stray newline"
+ )
+
+
class HttpExecutor:
"""Owns the :class:`httpx.Client` and performs JSON requests.
@@ -115,6 +138,7 @@ 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
diff --git a/sdk/python/openwa/client.py b/sdk/python/openwa/client.py
index 037647a02..1f5164d6e 100644
--- a/sdk/python/openwa/client.py
+++ b/sdk/python/openwa/client.py
@@ -14,7 +14,7 @@ transport) and exposes domain resources as properties::
# Sessions are addressed by the UUID that create() returns, not by name.
session = client.sessions.create({"name": "my-session"})
client.sessions.start(session["id"])
- # Link the account before sending: scan sessions.get_qr_code or use sessions.request_pairing_code,
+ # Link the account before sending: scan sessions.get_qr_code (or use sessions.request_pairing_code for a number with no linked session),
# then wait for status "ready". An unlinked session answers the send with 409.
client.messages.send_text(session["id"], {
"chatId": "[email protected]",
@@ -94,14 +94,14 @@ class OpenWAClient:
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.
+ # that quotes the whole key. Trim it, and refuse a control or non-ASCII character left inside: the
+ # gateway takes any printable ASCII, a space included, and the other clients send it as it is.
api_key = api_key.strip() if isinstance(api_key, str) else api_key
if 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):
+ 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"
+ "OpenWAClient: api_key contains a control or non-ASCII character; check for a stray newline"
)
_warn_if_insecure_http(base_url)
self._http = HttpExecutor(
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 86a658de9..b9fb21730 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import math
import time
from typing import get_args, get_type_hints
@@ -273,17 +274,40 @@ class TestClientCore:
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]
+ # 0 and infinity mean no limit for that operation, as they do for the scalar: left as they are,
+ # httpx fails the first connect or read, or raises OverflowError, instead of the call.
+ client = OpenWAClient(base_url="https://x", api_key="k", timeout=(5, 0, 5, math.inf))
+ assert client._http._client.timeout == httpx.Timeout(connect=5.0, read=None, write=5.0, pool=None)
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"]:
+ for bad in ["owa_k1_se\tcret", "owa_k1_se\x00cret", "owa_k1_sécret", "owa_k1_se\ncret"]:
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_a_key_with_an_inner_space_is_accepted_as_the_gateway_and_other_clients_take_it(self):
+ client = OpenWAClient(base_url="https://x", api_key="correct horse battery staple correct horse\n")
+ assert client._http._client.headers["X-API-Key"] == "correct horse battery staple correct horse"
+
+ def test_a_default_header_the_stack_would_refuse_is_refused_without_quoting_its_value(self):
+ for name, value in [
+ ("CF-Access-Client-Secret", "s3cret-token\n"),
+ ("X-Trace", "caf\u00e9"),
+ ("X-Trace", "a\x00b"),
+ ]:
+ with pytest.raises(ValueError, match=name) as raised:
+ OpenWAClient(base_url="https://x", api_key="k", default_headers={name: value})
+ assert value.strip() not in str(raised.value)
+ with pytest.raises(ValueError, match="header name"):
+ OpenWAClient(base_url="https://x", api_key="k", default_headers={"X Bad": "v"})
+ # A tab and plain printable ASCII are fine.
+ 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_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)