Completed
Pull Request — master (#339)
by Alejandro
09:39 queued 07:20
created

AuthenticationTest::provideInvalidApiKeys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace ShlinkioApiTest\Shlink\Rest\Middleware;
5
6
use GuzzleHttp\Exception\ClientException;
7
use Shlinkio\Shlink\Rest\Authentication\Plugin\ApiKeyHeaderPlugin;
8
use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPlugin;
9
use Shlinkio\Shlink\Rest\Util\RestUtils;
10
use ShlinkioTest\Shlink\Common\ApiTest\ApiTestCase;
11
use function implode;
12
use function Shlinkio\Shlink\Common\json_decode;
13
use function sprintf;
14
15
class AuthenticationTest extends ApiTestCase
16
{
17
    /**
18
     * @test
19
     */
20
    public function authorizationErrorIsReturnedIfNoApiKeyIsSent()
21
    {
22
        try {
23
            $this->callApi(self::METHOD_GET, '/short-codes');
24
        } catch (ClientException $e) {
25
            ['error' => $error, 'message' => $message] = $this->getJsonResponsePayload($e->getResponse());
26
27
            $this->assertEquals(self::STATUS_UNAUTHORIZED, $e->getCode());
28
            $this->assertEquals(RestUtils::INVALID_AUTHORIZATION_ERROR, $error);
29
            $this->assertEquals(
30
                sprintf(
31
                    'Expected one of the following authentication headers, but none were provided, ["%s"]',
32
                    implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS)
33
                ),
34
                $message
35
            );
36
        }
37
    }
38
39
    /**
40
     * @test
41
     * @dataProvider provideInvalidApiKeys
42
     */
43
    public function apiKeyErrorIsReturnedWhenProvidedApiKeyIsInvalid(string $apiKey)
44
    {
45
        try {
46
            $this->callApi(self::METHOD_GET, '/short-codes', [
47
                'headers' => [
48
                    ApiKeyHeaderPlugin::HEADER_NAME => $apiKey,
49
                ],
50
            ]);
51
        } catch (ClientException $e) {
52
            ['error' => $error, 'message' => $message] = json_decode((string) $e->getResponse()->getBody());
53
54
            $this->assertEquals(self::STATUS_UNAUTHORIZED, $e->getCode());
55
            $this->assertEquals(RestUtils::INVALID_API_KEY_ERROR, $error);
56
            $this->assertEquals('Provided API key does not exist or is invalid.', $message);
57
        }
58
    }
59
60
    public function provideInvalidApiKeys(): array
61
    {
62
        return [
63
            'key which does not exist' => ['invalid'],
64
            'key which is expired' => ['expired_api_key'],
65
            'key which is disabled' => ['disabled_api_key'],
66
        ];
67
    }
68
}
69