Skip to content

Commit 91c39c7

Browse files
authored
fix: handle invalid http responses (#508)
1 parent 71278f2 commit 91c39c7

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/CachedKeySet.php

+10
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,16 @@ private function keyIdExists(string $keyId): bool
178178
}
179179
$request = $this->httpFactory->createRequest('GET', $this->jwksUri);
180180
$jwksResponse = $this->httpClient->sendRequest($request);
181+
if ($jwksResponse->getStatusCode() !== 200) {
182+
throw new UnexpectedValueException(
183+
sprintf('HTTP Error: %d %s for URI "%s"',
184+
$jwksResponse->getStatusCode(),
185+
$jwksResponse->getReasonPhrase(),
186+
$this->jwksUri,
187+
),
188+
$jwksResponse->getStatusCode()
189+
);
190+
}
181191
$this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody());
182192

183193
if (!isset($this->keySet[$keyId])) {

tests/CachedKeySetTest.php

+34
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,37 @@ public function testOutOfBoundsThrowsException()
8888
$cachedKeySet['bar'];
8989
}
9090

91+
public function testInvalidHttpResponseThrowsException()
92+
{
93+
$this->expectException(\UnexpectedValueException::class);
94+
$this->expectExceptionMessage('HTTP Error: 404 URL not found');
95+
$this->expectExceptionCode(404);
96+
97+
$body = $this->prophesize('Psr\Http\Message\StreamInterface');
98+
99+
$response = $this->prophesize('Psr\Http\Message\ResponseInterface');
100+
$response->getStatusCode()
101+
->shouldBeCalled()
102+
->willReturn(404);
103+
$response->getReasonPhrase()
104+
->shouldBeCalledTimes(1)
105+
->willReturn('URL not found');
106+
107+
$http = $this->prophesize(ClientInterface::class);
108+
$http->sendRequest(Argument::any())
109+
->shouldBeCalledTimes(1)
110+
->willReturn($response->reveal());
111+
112+
$cachedKeySet = new CachedKeySet(
113+
$this->testJwksUri,
114+
$http->reveal(),
115+
$this->getMockHttpFactory(),
116+
$this->getMockEmptyCache()
117+
);
118+
119+
isset($cachedKeySet[0]);
120+
}
121+
91122
public function testWithExistingKeyId()
92123
{
93124
$cachedKeySet = new CachedKeySet(
@@ -382,6 +413,9 @@ private function getMockHttpClient($testJwks, int $timesCalled = 1)
382413
$response->getBody()
383414
->shouldBeCalledTimes($timesCalled)
384415
->willReturn($body->reveal());
416+
$response->getStatusCode()
417+
->shouldBeCalledTimes($timesCalled)
418+
->willReturn(200);
385419

386420
$http = $this->prophesize(ClientInterface::class);
387421
$http->sendRequest(Argument::any())

0 commit comments

Comments
 (0)