Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk-php): trim the API key and refuse one that is not a token
Yudhi Armyndharisc91e53ce3810
diff --git a/sdk/php/src/Client.php b/sdk/php/src/Client.phpindex 7f9e0542a..d630e2035 100644--- a/sdk/php/src/Client.php+++ b/sdk/php/src/Client.php@@ -91,9 +91,18 @@ class Clientif (empty($config['baseUrl'])) {throw new OpenWAException('OpenWA Client: baseUrl is required');}- if (empty($config['apiKey'])) {+ // 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.+ $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) {+ throw new OpenWAException(+ 'OpenWA Client: apiKey contains illegal characters (whitespace, control or non-ASCII); '+ . 'check for a stray newline'+ );+ }if (empty($config['allowInsecureHttp'])) {self::warnIfInsecureHttp($config['baseUrl']);@@ -101,7 +110,7 @@ class Client$this->http = new HttpExecutor($config['baseUrl'],- $config['apiKey'],+ $apiKey,$config['timeout'] ?? 30.0,$config['httpClient'] ?? null,$config['defaultHeaders'] ?? [],diff --git a/sdk/php/tests/ClientTest.php b/sdk/php/tests/ClientTest.phpindex 1e2dcc7cf..f3785e6cf 100644--- a/sdk/php/tests/ClientTest.php+++ b/sdk/php/tests/ClientTest.php@@ -14,6 +14,26 @@ use PHPUnit\Framework\TestCase;class ClientTest extends TestCase{+ public function testTheApiKeyLosesATrailingNewlineAndAnIllegalOneIsRefusedWithoutBeingQuoted(): void+ {+ $backend = (new MockBackend())->on(200, []);+ $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) {+ try {+ (new MockBackend())->makeClient('http://localhost:2785', $bad);+ $this->fail('Expected an exception for an illegal key');+ } catch (\OpenWA\Exceptions\OpenWAException $e) {+ $this->assertStringContainsString('apiKey', $e->getMessage());+ $this->assertStringNotContainsString($bad, $e->getMessage());+ }+ }+ $this->expectException(\OpenWA\Exceptions\OpenWAException::class);+ $this->expectExceptionMessage('apiKey is required');+ (new MockBackend())->makeClient('http://localhost:2785', " \n");+ }+public function testRequiresBaseUrlAndApiKey(): void{$this->expectException(\OpenWA\Exceptions\OpenWAException::class);