71 lines
2.2 KiB
PHP
71 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Tests\Security\AccessToken;
|
|
|
|
use App\Security\AccessToken\ApiKeyTokenHandler;
|
|
use PHPUnit\Framework\Attributes\DataProvider;
|
|
use PHPUnit\Framework\TestCase;
|
|
use Psr\Log\NullLogger;
|
|
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
|
|
|
|
/**
|
|
* Each key resolves to its own caller, and an unconfigured key must not open the door for an
|
|
* empty one: hash_equals('', '') is true.
|
|
*/
|
|
class ApiKeyTokenHandlerTest extends TestCase
|
|
{
|
|
public function testEachKeyResolvesToItsOwnCaller(): void
|
|
{
|
|
$handler = $this->handler(['api' => 'forms-key', 'n8n' => 'n8n-key']);
|
|
|
|
$this->assertSame('api', $handler->getUserBadgeFrom('forms-key')->getUserIdentifier());
|
|
$this->assertSame('n8n', $handler->getUserBadgeFrom('n8n-key')->getUserIdentifier());
|
|
}
|
|
|
|
public function testAWrongKeyIsRejected(): void
|
|
{
|
|
$this->expectException(BadCredentialsException::class);
|
|
|
|
$this->handler(['api' => 'forms-key', 'n8n' => 'n8n-key'])->getUserBadgeFrom('other-key');
|
|
}
|
|
|
|
/**
|
|
* The extractor never hands over an empty key, but the handler must not rely on that.
|
|
*/
|
|
public function testAnUnconfiguredKeyDoesNotAcceptAnEmptyOne(): void
|
|
{
|
|
$this->expectException(BadCredentialsException::class);
|
|
|
|
$this->handler(['api' => 'forms-key', 'n8n' => ''])->getUserBadgeFrom('');
|
|
}
|
|
|
|
public function testAnUnconfiguredKeyLeavesTheOtherWorking(): void
|
|
{
|
|
$this->assertSame('api', $this->handler(['api' => 'forms-key', 'n8n' => ''])->getUserBadgeFrom('forms-key')->getUserIdentifier());
|
|
}
|
|
|
|
#[DataProvider('anyKey')]
|
|
public function testNoConfiguredKeyRejectsEverything(string $key): void
|
|
{
|
|
$this->expectException(BadCredentialsException::class);
|
|
|
|
$this->handler(['api' => '', 'n8n' => ''])->getUserBadgeFrom($key);
|
|
}
|
|
|
|
public static function anyKey(): iterable
|
|
{
|
|
yield 'empty' => [''];
|
|
yield 'some' => ['forms-key'];
|
|
}
|
|
|
|
/**
|
|
* @param array<string, string> $keys
|
|
*/
|
|
private function handler(array $keys): ApiKeyTokenHandler
|
|
{
|
|
return new ApiKeyTokenHandler($keys, new NullLogger());
|
|
}
|
|
}
|