ldc-arcadia-api/tests/Unit/Infra/Adapters/Services/CachedNonceValidatorTest.php

70 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Unit\Infra\Adapters\Services;
use Application\Security\Models\ValueObjects\ClientIdentifier;
use Application\Security\Models\ValueObjects\Request\Nonce;
use Infra\Adapters\Services\CachedNonceValidator;
use Mockery;
use Psr\Log\NullLogger;
use Psr\SimpleCache\CacheInterface;
use Ramsey\Uuid\Uuid;
covers(CachedNonceValidator::class);
describe('CachedNonceValidator Unit Tests', function (): void {
it('validates and consumes a new nonce', function (): void {
// GIVEN
$cacheStore = Mockery::mock(CacheInterface::class);
$logger = new NullLogger();
$validator = new CachedNonceValidator($logger, $cacheStore);
$clientIdentifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32));
$nonce = new Nonce(Uuid::uuid7());
$expectedKey = 'nonce:' . $clientIdentifier->value . ':' . $nonce->value->toString();
$cacheStore->expects('has')
->once()
->with($expectedKey)
->andReturn(false);
$cacheStore->expects('set')
->once()
->with($expectedKey, 'used', 300)
->andReturn(true);
// WHEN
$isValid = $validator->validateAndConsume($nonce, $clientIdentifier);
// THEN
expect($isValid)->toBeTrue();
});
it('rejects an already consumed nonce', function (): void {
// GIVEN
$cacheStore = Mockery::mock(CacheInterface::class);
$logger = new NullLogger();
$validator = new CachedNonceValidator($logger, $cacheStore);
$clientIdentifier = new ClientIdentifier('arcadia_id_' . str_repeat('a', 32));
$nonce = new Nonce(Uuid::uuid7());
$expectedKey = 'nonce:' . $clientIdentifier->value . ':' . $nonce->value->toString();
$cacheStore->expects('has')
->once()
->with($expectedKey)
->andReturn(true);
$cacheStore->shouldNotReceive('set');
// WHEN
$isValid = $validator->validateAndConsume($nonce, $clientIdentifier);
// THEN
expect($isValid)->toBeFalse();
});
});