shlink/module/Rest/test/Middleware/AuthenticationMiddlewareTest.php

156 lines
6.2 KiB
PHP
Raw Normal View History

<?php
2019-10-05 10:26:10 -05:00
2017-10-12 03:13:20 -05:00
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Rest\Middleware;
use Fig\Http\Message\RequestMethodInterface;
2020-01-01 14:11:53 -06:00
use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequest;
use Laminas\Diactoros\ServerRequestFactory;
2020-01-01 14:11:53 -06:00
use Mezzio\Router\Route;
use Mezzio\Router\RouteResult;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\MockObject\MockObject;
2017-03-24 14:34:18 -05:00
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
2018-03-26 12:02:41 -05:00
use Psr\Http\Server\RequestHandlerInterface;
2019-12-31 08:38:37 -06:00
use Shlinkio\Shlink\Rest\Action\HealthAction;
2020-11-08 04:28:27 -06:00
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Exception\MissingAuthenticationException;
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Shlinkio\Shlink\Rest\Middleware\AuthenticationMiddleware;
2020-11-08 04:28:27 -06:00
use Shlinkio\Shlink\Rest\Service\ApiKeyCheckResult;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
2020-01-01 14:11:53 -06:00
use function Laminas\Stratigility\middleware;
class AuthenticationMiddlewareTest extends TestCase
{
private AuthenticationMiddleware $middleware;
2022-10-24 12:59:03 -05:00
private MockObject & ApiKeyServiceInterface $apiKeyService;
private MockObject & RequestHandlerInterface $handler;
2018-03-21 05:13:03 -05:00
protected function setUp(): void
{
$this->apiKeyService = $this->createMock(ApiKeyServiceInterface::class);
2021-01-21 12:26:19 -06:00
$this->middleware = new AuthenticationMiddleware(
$this->apiKeyService,
2021-01-21 12:26:19 -06:00
[HealthAction::class],
['with_query_api_key'],
);
$this->handler = $this->createMock(RequestHandlerInterface::class);
}
#[Test, DataProvider('provideRequestsWithoutAuth')]
public function someSituationsFallbackToNextMiddleware(ServerRequestInterface $request): void
{
$this->handler->expects($this->once())->method('handle')->with($request)->willReturn(new Response());
$this->apiKeyService->expects($this->never())->method('check');
$this->middleware->process($request, $this->handler);
}
2023-02-09 02:32:38 -06:00
public static function provideRequestsWithoutAuth(): iterable
{
2023-02-09 02:32:38 -06:00
$dummyMiddleware = self::getDummyMiddleware();
yield 'no route result' => [new ServerRequest()];
yield 'failure route result' => [(new ServerRequest())->withAttribute(
2019-02-17 13:28:34 -06:00
RouteResult::class,
2020-01-01 13:48:31 -06:00
RouteResult::fromRouteFailure([RequestMethodInterface::METHOD_GET]),
2019-02-17 13:28:34 -06:00
)];
yield 'route without API key required' => [(new ServerRequest())->withAttribute(
2019-02-17 13:28:34 -06:00
RouteResult::class,
RouteResult::fromRoute(
2020-01-01 13:48:31 -06:00
new Route('foo', $dummyMiddleware, Route::HTTP_METHOD_ANY, HealthAction::class),
),
2019-02-17 13:28:34 -06:00
)];
yield 'OPTIONS method' => [(new ServerRequest())->withAttribute(
2019-02-17 13:28:34 -06:00
RouteResult::class,
2020-01-01 13:48:31 -06:00
RouteResult::fromRoute(new Route('bar', $dummyMiddleware), []),
2019-02-17 13:28:34 -06:00
)->withMethod(RequestMethodInterface::METHOD_OPTIONS)];
}
#[Test, DataProvider('provideRequestsWithoutApiKey')]
2021-01-21 12:26:19 -06:00
public function throwsExceptionWhenNoApiKeyIsProvided(
ServerRequestInterface $request,
string $expectedMessage,
2021-01-21 12:26:19 -06:00
): void {
$this->apiKeyService->expects($this->never())->method('check');
$this->handler->expects($this->never())->method('handle');
$this->expectException(MissingAuthenticationException::class);
2021-01-21 12:26:19 -06:00
$this->expectExceptionMessage($expectedMessage);
$this->middleware->process($request, $this->handler);
}
2023-02-09 02:32:38 -06:00
public static function provideRequestsWithoutApiKey(): iterable
{
2021-01-21 12:26:19 -06:00
$baseRequest = fn (string $routeName) => ServerRequestFactory::fromGlobals()->withAttribute(
RouteResult::class,
2023-02-09 02:32:38 -06:00
RouteResult::fromRoute(new Route($routeName, self::getDummyMiddleware())), // @phpstan-ignore-line
);
2021-01-21 12:26:19 -06:00
$apiKeyMessage = 'Expected one of the following authentication headers, ["X-Api-Key"], but none were provided';
$queryMessage = 'Expected authentication to be provided in "apiKey" query param';
yield 'no api key in header' => [$baseRequest('bar'), $apiKeyMessage];
yield 'empty api key in header' => [$baseRequest('bar')->withHeader('X-Api-Key', ''), $apiKeyMessage];
yield 'no api key in query' => [$baseRequest('with_query_api_key'), $queryMessage];
yield 'empty api key in query' => [
$baseRequest('with_query_api_key')->withQueryParams(['apiKey' => '']),
$queryMessage,
];
}
#[Test]
public function throwsExceptionWhenProvidedApiKeyIsInvalid(): void
{
$apiKey = 'abc123';
$request = ServerRequestFactory::fromGlobals()
->withAttribute(
RouteResult::class,
2023-02-09 02:32:38 -06:00
RouteResult::fromRoute(new Route('bar', self::getDummyMiddleware()), []),
)
->withHeader('X-Api-Key', $apiKey);
$this->apiKeyService->expects($this->once())->method('check')->with($apiKey)->willReturn(
new ApiKeyCheckResult(),
);
$this->handler->expects($this->never())->method('handle');
$this->expectException(VerifyAuthenticationException::class);
$this->expectExceptionMessage('Provided API key does not exist or is invalid');
$this->middleware->process($request, $this->handler);
}
#[Test]
public function validApiKeyFallsBackToNextMiddleware(): void
{
$apiKey = ApiKey::create();
2020-11-08 04:28:27 -06:00
$key = $apiKey->toString();
$request = ServerRequestFactory::fromGlobals()
->withAttribute(
RouteResult::class,
2023-02-09 02:32:38 -06:00
RouteResult::fromRoute(new Route('bar', self::getDummyMiddleware()), []),
)
2020-11-08 04:28:27 -06:00
->withHeader('X-Api-Key', $key);
$this->handler->expects($this->once())->method('handle')->with(
$request->withAttribute(ApiKey::class, $apiKey),
)->willReturn(new Response());
$this->apiKeyService->expects($this->once())->method('check')->with($key)->willReturn(
new ApiKeyCheckResult($apiKey),
);
$this->middleware->process($request, $this->handler);
}
2023-02-09 02:32:38 -06:00
private static function getDummyMiddleware(): MiddlewareInterface
{
return middleware(fn () => new Response\EmptyResponse());
}
}