Skip to content

Commit b00ff6a

Browse files
committed
fix: mark invalid json response as authentication error
1 parent 713d833 commit b00ff6a

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/HttpClient/AuthenticatedClient.php

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,24 @@ private function fetchAccessToken(): string
4343
throw new AuthenticationFailedException($this->shop->getShopId(), $response);
4444
}
4545

46-
/** @var array{access_token: string, expires_in: int} $token */
47-
$token = json_decode($response->getBody()->getContents(), true);
46+
$body = $response->getBody()->getContents();
47+
48+
try {
49+
$token = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
50+
} catch (\JsonException) {
51+
throw new AuthenticationFailedException($this->shop->getShopId(), $response);
52+
}
53+
54+
if (!is_array($token) || !isset($token['access_token'], $token['expires_in'])) {
55+
throw new AuthenticationFailedException(
56+
$this->shop->getShopId(),
57+
$response,
58+
);
59+
}
4860

4961
$this->cache->set($cacheKey, $token['access_token'], $token['expires_in'] - self::TOKEN_EXPIRE_DIFF);
5062

51-
return $token['access_token'];
63+
return (string) $token['access_token'];
5264
}
5365

5466
/**

tests/HttpClient/AuthenticatedClientTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,4 +172,28 @@ public function getAuthenticatedClient(MockClient $mockClient, CacheInterface $c
172172
$cache
173173
);
174174
}
175+
176+
public function testInvalidJsonTokenResponseThrowsException(): void
177+
{
178+
$mockClient = new MockClient([
179+
new Response(200, [], 'not-a-json'),
180+
]);
181+
182+
$client = $this->getAuthenticatedClient($mockClient);
183+
184+
static::expectException(AuthenticationFailedException::class);
185+
$client->sendRequest(new Request('GET', 'https://example.com'));
186+
}
187+
188+
public function testMissingTokenFieldsThrowsException(): void
189+
{
190+
$mockClient = new MockClient([
191+
new Response(200, [], '{"foo":"bar"}'),
192+
]);
193+
194+
$client = $this->getAuthenticatedClient($mockClient);
195+
static::expectException(AuthenticationFailedException::class);
196+
197+
$client->sendRequest(new Request('GET', 'https://example.com'));
198+
}
175199
}

0 commit comments

Comments
 (0)