Skip to content

Commit

Permalink
fix: handle invalid http responses (#508)
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer committed Jun 14, 2023
1 parent 71278f2 commit 91c39c7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/CachedKeySet.php
Expand Up @@ -178,6 +178,16 @@ private function keyIdExists(string $keyId): bool
}
$request = $this->httpFactory->createRequest('GET', $this->jwksUri);
$jwksResponse = $this->httpClient->sendRequest($request);
if ($jwksResponse->getStatusCode() !== 200) {
throw new UnexpectedValueException(
sprintf('HTTP Error: %d %s for URI "%s"',
$jwksResponse->getStatusCode(),
$jwksResponse->getReasonPhrase(),
$this->jwksUri,
),
$jwksResponse->getStatusCode()
);
}
$this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody());

if (!isset($this->keySet[$keyId])) {
Expand Down
34 changes: 34 additions & 0 deletions tests/CachedKeySetTest.php
Expand Up @@ -88,6 +88,37 @@ public function testOutOfBoundsThrowsException()
$cachedKeySet['bar'];
}

public function testInvalidHttpResponseThrowsException()
{
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('HTTP Error: 404 URL not found');
$this->expectExceptionCode(404);

$body = $this->prophesize('Psr\Http\Message\StreamInterface');

$response = $this->prophesize('Psr\Http\Message\ResponseInterface');
$response->getStatusCode()
->shouldBeCalled()
->willReturn(404);
$response->getReasonPhrase()
->shouldBeCalledTimes(1)
->willReturn('URL not found');

$http = $this->prophesize(ClientInterface::class);
$http->sendRequest(Argument::any())
->shouldBeCalledTimes(1)
->willReturn($response->reveal());

$cachedKeySet = new CachedKeySet(
$this->testJwksUri,
$http->reveal(),
$this->getMockHttpFactory(),
$this->getMockEmptyCache()
);

isset($cachedKeySet[0]);
}

public function testWithExistingKeyId()
{
$cachedKeySet = new CachedKeySet(
Expand Down Expand Up @@ -382,6 +413,9 @@ private function getMockHttpClient($testJwks, int $timesCalled = 1)
$response->getBody()
->shouldBeCalledTimes($timesCalled)
->willReturn($body->reveal());
$response->getStatusCode()
->shouldBeCalledTimes($timesCalled)
->willReturn(200);

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

0 comments on commit 91c39c7

Please sign in to comment.