Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): reject empty and dot path segments
Yudhi Armyndharisdc79064071b7
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex 83045601a..e20e40a55 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -404,6 +404,7 @@ try {- **Redirects are never followed.** The transport uses `redirect: 'manual'`, so a `3xx` surfaces to the caller as an error (via `OpenWAApiError`) rather than being followed — this guarantees the `X-API-Key` header is never re-sent to a redirect target (potentially a different origin).- **Auth and JSON headers take precedence.** Request headers are merged in the order `defaultHeaders` → per-call headers → `Content-Type: application/json` → `X-API-Key`. Both `Content-Type` and `X-API-Key` are applied last, so neither can be overridden by a caller-supplied header.- **Path segments are percent-encoded.** Ids (session, chat, message, etc.) are encoded so a value cannot break out of its path position, while keeping the WhatsApp-safe characters `@`, `:`, and `+` readable (e.g. `[email protected]`).+- **Empty and dot segments are refused.** An empty, `.` or `..` segment rejects with a `TypeError` and nothing is sent, because `fetch` would otherwise resolve it to the parent resource.- **Base-URL path prefix is preserved.** A `baseUrl` such as `https://gateway.example.com/v1` keeps its `/v1` prefix on every request; only a trailing slash is trimmed.- **No automatic retries.** A failed request rejects immediately — the SDK does not retry, even on `429`. Wrap calls in your own backoff if you need retries.- **Injectable transport.** Supply a custom `fetch` to wrap outbound calls with retry, logging, or observability middleware, or to run on a runtime without a global `fetch`. This is also the recommended way to unit-test without monkey-patching globals.@@ -772,6 +773,7 @@ except OpenWAApiError as e:- **Redirects are never followed.** `follow_redirects` is forced off so the `X-API-Key` header is never re-sent to a redirect target. An unfollowed `3xx` therefore surfaces as an `OpenWAApiError` rather than a success.- **Auth/JSON headers always win.** `default_headers` are applied first; the SDK then sets `Content-Type: application/json` and `X-API-Key`, so caller headers can never clobber them.- **Path segments are percent-encoded.** Each path value (session/chat/message id, etc.) is encoded so a `/`, `#`, or `?` can't break out of its position; already-safe id characters `@`, `:`, `+` are left readable. Boolean query params are serialized lowercase (`true`/`false`); `None` query values are dropped.+- **Empty and dot segments are refused.** An empty, `.` or `..` id raises `ValueError` before anything is sent, because httpx would otherwise resolve it to the parent resource.- **Base-URL path prefix is preserved.** A trailing `/` is stripped from `base_url`, but any path prefix (e.g. when running behind a reverse proxy) is kept on every request.- **No automatic retries.** Each call issues exactly one request; retry/backoff is the caller's responsibility. Wrap or inject a custom `transport` for retry or observability middleware.- **Testable transport injection.** Pass `transport=httpx.MockTransport(handler)` to intercept requests in tests — no global monkey-patching.@@ -1119,6 +1121,7 @@ try {- **Redirects are never followed.** Guzzle is configured with `allow_redirects => false`, so a `3xx` surfaces as an `OpenWAApiException` rather than being followed — the `X-API-Key` header is never re-sent to a redirect target.- **Auth/JSON headers take precedence.** `defaultHeaders` are merged in first, then `X-API-Key`, `Content-Type: application/json`, and `Accept: application/json` are applied on top, so they can't be clobbered.- **Path segments are percent-encoded.** Ids (session/chat/message/group ids) pass through `encodeSegment()`, which `rawurlencode`s the value but keeps the WhatsApp-id-safe characters `@`, `:`, and `+` readable — so a value containing `/`, `#`, or `?` cannot break out of its path position.+- **Empty and dot segments are refused.** An empty, `.` or `..` id throws `InvalidArgumentException` before anything is sent, because the HTTP stack would otherwise resolve it to the parent resource.- **Base-URL path prefix is preserved.** The base URL has its trailing `/` trimmed and requests are issued against an absolute `baseUrl . $path`; Guzzle's `base_uri` is intentionally unset, so a prefix like `/v1` behind a reverse proxy is retained.- **Null query values are dropped.** Absent optional query parameters (`null`) are filtered out before the request, so they are never sent.- **No automatic retries.** A failed request throws immediately; wrap calls in your own backoff if you need retries (notably for `429`). The injectable `httpClient` is the extension point for retry/observability middleware.diff --git a/sdk/javascript/src/http.ts b/sdk/javascript/src/http.tsindex ea7a3fe94..1cf6d0d82 100644--- a/sdk/javascript/src/http.ts+++ b/sdk/javascript/src/http.ts@@ -139,6 +139,20 @@ async function send<T>(options: RequestOptions,consume: (res: Response) => Promise<T>,): Promise<T> {+ // fetch resolves `.` and `..` segments before sending, so such a segment would reach the parent+ // resource instead of the intended one. Mirror the URL parser: it drops tab and newline, trims+ // trailing C0 controls and spaces, reads `\` as `/`, and treats %2e as a dot. An empty segment is+ // refused too: it means a required id was blank.+ const pathOnly = options.path+ .split(/[?#]/, 1)[0]+ .replace(/[\t\n\r]/g, '')+ .replace(/[\x00-\x20]+$/, '');+ for (const segment of pathOnly.split(/[/\\]/).slice(1)) {+ const dots = segment.replace(/%2e/gi, '.');+ if (dots === '' || dots === '.' || dots === '..') {+ throw new TypeError(`OpenWA: empty or dot path segment in ${JSON.stringify(options.path)}`);+ }+ }const url = buildUrl(config.baseUrl, options.path, options.query);const timeoutMs = toTimeoutMs(options.timeoutMs ?? config.timeoutMs);diff --git a/sdk/javascript/test/client.test.ts b/sdk/javascript/test/client.test.tsindex 74621b2da..f6c20bbd0 100644--- a/sdk/javascript/test/client.test.ts+++ b/sdk/javascript/test/client.test.ts@@ -84,6 +84,27 @@ describe('OpenWAClient', () => {expect(t2.lastCall!.url).toContain('weird%2Fid%23x'); // path-breaking chars encoded});+ it('refuses an empty or dot id instead of letting fetch collapse the path to the parent resource', async () => {+ const t = new MockTransport().passthrough({ status: 204 });+ const c = client(t);+ await expect(c.webhooks.delete('s1', '..')).rejects.toThrow(TypeError);+ await expect(c.contacts.delete('s1', '.')).rejects.toThrow(TypeError);+ await expect(c.templates.delete('s1', '')).rejects.toThrow(TypeError);+ await expect(c.request({ method: 'DELETE', path: '/api/sessions/s1/labels/%2E%2e' })).rejects.toThrow(TypeError);+ // The URL parser also reads `\` as `/`, drops tab and newline, and trims trailing controls and spaces.+ for (const tail of ['labels\\..', 'labels/\t..', 'labels/.\n.', 'labels/.. ']) {+ const path = `/api/sessions/s1/${tail}`;+ await expect(c.request({ method: 'DELETE', path })).rejects.toThrow(TypeError);+ }+ expect(t.calls).toHaveLength(0);++ // Dots inside an id, and a dot-only query value, are not path segments and still go out.+ await c.webhooks.delete('s1', '[email protected]');+ expect(t.lastCall!.url).toBe('http://localhost:2785/api/sessions/s1/webhooks/[email protected]');+ await c.request({ method: 'GET', path: '/api/sessions/s1/labels/a.b?x=/..' });+ expect(t.calls).toHaveLength(2);+ });+it('serializes query params and skips null/undefined', async () => {const t = new MockTransport().on('GET', /\/messages/, { body: [] });await client(t).messages.list('s1', { chatId: '[email protected]', from: undefined, limit: 10 });diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.phpindex feb1e054a..bbdde33bb 100644--- a/sdk/php/src/Http/HttpExecutor.php+++ b/sdk/php/src/Http/HttpExecutor.php@@ -55,9 +55,18 @@ class HttpExecutor* Percent-encode a single path segment (e.g. a chat/message id) so a value* containing /, # or ? can't break out of its path position. WhatsApp-id* characters that are already path-safe (@, :, +) are kept readable.+ *+ * An empty, "." or ".." segment is refused: the HTTP stack resolves dot+ * segments before sending, so such an id would reach the parent resource+ * instead of the intended one.+ *+ * @throws \InvalidArgumentException For an empty, "." or ".." segment.*/public function encodeSegment(string $segment): string{+ if ($segment === '' || $segment === '.' || $segment === '..') {+ throw new \InvalidArgumentException(sprintf('OpenWA: empty or dot path segment "%s"', $segment));+ }return str_replace(['%40', '%3A', '%2B'], ['@', ':', '+'], rawurlencode($segment));}diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.phpindex 6b4437685..d82be2a45 100644--- a/sdk/php/tests/ClientTest.php+++ b/sdk/php/tests/ClientTest.php@@ -120,6 +120,31 @@ class ClientTest extends TestCase$this->assertStringContainsString('/labels/[email protected]', $backend2->lastCall()['path']); // @ preserved}+ public function testEmptyOrDotIdsAreRefusedBeforeSending(): void+ {+ // The HTTP stack resolves dot segments, so such an id would otherwise reach the parent resource.+ $backend = new MockBackend();+ $client = $backend->makeClient();+ $attempts = [+ fn () => $client->webhooks->delete('s1', '..'),+ fn () => $client->contacts->delete('s1', '.'),+ fn () => $client->templates->delete('s1', ''),+ ];+ foreach ($attempts as $attempt) {+ try {+ $attempt();+ $this->fail('expected InvalidArgumentException');+ } catch (\InvalidArgumentException $e) {+ $this->assertStringContainsString('dot path segment', $e->getMessage());+ }+ }+ $this->assertSame([], $backend->calls());++ $backend->on(204);+ $client->webhooks->delete('s1', '[email protected]');+ $this->assertSame('/api/sessions/s1/webhooks/[email protected]', $backend->lastCall()['path']);+ }+public function testRawRequestEscapeHatch(): void{$backend = (new MockBackend())->on(200, ['ok' => true]);diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.pyindex 9d88aa313..8a2dffb85 100644--- a/sdk/python/openwa/_http.py+++ b/sdk/python/openwa/_http.py@@ -23,8 +23,15 @@ def quote_segment(segment: Any) -> str:"""Percent-encode a single path segment so a value containing ``/``, ``#`` or``?`` can't break out of its path position. WhatsApp-id characters that arealready path-safe (``@``, ``:``, ``+``) are kept readable.++ Raises :class:`ValueError` for an empty, ``.`` or ``..`` segment: httpx+ resolves dot segments before sending, so such an id would reach the+ parent resource instead of the intended one."""- return quote(str(segment), safe="@:+")+ text = str(segment)+ if text in ("", ".", ".."):+ raise ValueError(f"OpenWA: empty or dot path segment {text!r}")+ return quote(text, safe="@:+")def build_url(base_url: str, path: str, query: Mapping[str, Any] | None = None) -> str:diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex 9da72956c..dfb011aba 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -75,6 +75,22 @@ class TestClientCore:make_client(backend2).messages.history("s", "[email protected]")assert "/messages/[email protected]/history" in backend2.last_call.url # @ preserved+ def test_empty_or_dot_ids_are_refused_before_sending(self):+ # httpx resolves dot segments, so such an id would otherwise reach the+ # parent resource.+ backend = MockBackend()+ client = make_client(backend)+ with pytest.raises(ValueError):+ client.webhooks.delete("s1", "..")+ with pytest.raises(ValueError):+ client.contacts.delete("s1", ".")+ with pytest.raises(ValueError):+ client.templates.delete("s1", "")+ assert backend.calls == []+ backend.on("DELETE", "/webhooks/", status=204)+ client.webhooks.delete("s1", "[email protected]")+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s1/webhooks/[email protected]"+def test_raw_request_escape_hatch(self):backend = MockBackend().on("GET", "/api/anything", body={"ok": True})result = make_client(backend).request("GET", "/api/anything", query={"a": 1})