diff --git a/README.md b/README.md index 328d137..77f90fd 100644 --- a/README.md +++ b/README.md @@ -480,6 +480,11 @@ final class Document extends Model implements HasValidators } ``` +On a nested route, such as `folders/{folder}/documents/{document}`, the last bound parameter that +implements `HasValidators` is used. A URI names its parents first, so that is the resource the +request is about: the document's ETag is sent, and `If-Match` is checked against the document and +never the folder. + `HasModelValidators` gives a strong ETag from the model's class, key and `updated_at`, and `Last-Modified` from `updated_at`. Section 8.8.1 says a strong tag must change whenever the representation does, and that holds only while every change touches `updated_at` and two writes @@ -627,6 +632,13 @@ keys last. Put your `ttl` in your API documentation. - **A replay is the stored response** with its original status, headers and body, minus `Date` and cookies. With Negotiation on, it gets its own request ID and `traceparent`, because a retry is a new request. No header marks it as a replay: the draft defines none. +- **Stored responses are encrypted.** A response can hold a secret, such as an API key shown once + when it is created, and a retry has to get it back. Each one is encrypted with AES-256-GCM under + a key derived (HKDF, RFC 5869) from the application key and the client's `Idempotency-Key`, and + kept under a hash of that key. Reading the cache, or even the cache and `APP_KEY` together, + does not reveal it: that takes the `Idempotency-Key`, which only the client has. Keep a rotated + application key in `APP_PREVIOUS_KEYS` until the TTL has passed, or stored responses are + forgotten and retries run again. - **The cache store has to support atomic locks**, which is how a concurrent retry is told apart from a completed one. Redis, Memcached, database, file, DynamoDB and array do. APC, session and storage stores do not, and nor does the null store in practice, since it keeps nothing. The @@ -1231,6 +1243,10 @@ type. is for `multipart/form-data`: PHP parses it into fields and files and leaves `php://input` empty. - Types match on type and subtype, case-insensitively. `consumes:application/json` accepts `application/json; charset=utf-8`, and does not accept `application/merge-patch+json`; list it. +- **The last declaration wins.** A route that declares `consumes` overrides one from its group, and + a controller's overrides the route's. Put `consumes:application/json` on a whole API group, and + a PATCH route can declare `consumes:application/merge-patch+json` without lifting the group's + first. A declaration removed with `withoutMiddleware()` does not count. ### Trace context diff --git a/resources/boost/skills/api-toolbox-development/references/api-lifecycle.md b/resources/boost/skills/api-toolbox-development/references/api-lifecycle.md index dfd17f7..31368ec 100644 --- a/resources/boost/skills/api-toolbox-development/references/api-lifecycle.md +++ b/resources/boost/skills/api-toolbox-development/references/api-lifecycle.md @@ -59,6 +59,7 @@ Route::patch('leads/{lead}', UpdateLead::class)->middleware('consumes:applicatio - `produces` returns 406 when `Accept` rules out every listed type. A missing `Accept` accepts anything. - `consumes` returns 415 when the request has content of another type, or content with no `Content-Type`. A request with no content always passes. - `consumes:application/json` does not accept `application/merge-patch+json`. List each type a route takes. +- The last `consumes` declaration wins: a route's overrides its group's, and a controller's overrides the route's. A PATCH route in a group that consumes `application/json` declares `consumes:application/merge-patch+json` itself; do not lift the group's declaration with `withoutMiddleware()`. ## Request IDs and tracing diff --git a/resources/boost/skills/api-toolbox-development/references/caching-and-pagination.md b/resources/boost/skills/api-toolbox-development/references/caching-and-pagination.md index 3be83b0..2fcdae1 100644 --- a/resources/boost/skills/api-toolbox-development/references/caching-and-pagination.md +++ b/resources/boost/skills/api-toolbox-development/references/caching-and-pagination.md @@ -27,7 +27,7 @@ protected function entityTagVersion(): ?string } ``` -The model is found through route model binding, so the route parameter must be bound to it. +The model is found through route model binding, so the route parameter must be bound to it. On a nested route such as `folders/{folder}/documents/{document}`, the last bound parameter that implements `HasValidators` is used, which is the document. Every parameter before it is treated as a parent. ### 2. Add the middleware diff --git a/src/ConditionalRequests/RouteValidators.php b/src/ConditionalRequests/RouteValidators.php index 1291640..58c9eb4 100644 --- a/src/ConditionalRequests/RouteValidators.php +++ b/src/ConditionalRequests/RouteValidators.php @@ -9,9 +9,11 @@ use JustSteveKing\Toolbox\ConditionalRequests\Contracts\HasValidators; /** - * Finds the route-bound object that supplies a request's validators: the first route parameter - * implementing HasValidators. Parameters are bound by SubstituteBindings, so the conditional - * middleware is registered to run after it. + * Finds the route-bound object that supplies a request's validators: the last route parameter + * implementing HasValidators. On a nested route such as documents/{document}/comments/{comment} + * the URI names its parents first, so the last bound parameter is the resource the request is + * about. Parameters are bound by SubstituteBindings, so the conditional middleware is registered + * to run after it. */ final class RouteValidators { @@ -23,12 +25,14 @@ public static function for(Request $request): ?HasValidators return null; } + $resource = null; + foreach ($route->parameters() as $parameter) { if ($parameter instanceof HasValidators) { - return $parameter; + $resource = $parameter; } } - return null; + return $resource; } } diff --git a/src/Idempotency/Http/Middleware/EnsureIdempotency.php b/src/Idempotency/Http/Middleware/EnsureIdempotency.php index fe9739d..6286c09 100644 --- a/src/Idempotency/Http/Middleware/EnsureIdempotency.php +++ b/src/Idempotency/Http/Middleware/EnsureIdempotency.php @@ -53,14 +53,14 @@ public function handle(Request $request, Closure $next, string ...$options): Res $key = IdempotencyKey::parse($field) ?? throw InvalidIdempotencyKey::malformed($this->documentation); - $storageKey = $this->storageKey($request, $key); + $scope = $this->scope($request); $fingerprint = $this->fingerprint($request); - if (($stored = $this->store->get($storageKey)) !== null) { + if (($stored = $this->store->get($scope, $key)) !== null) { return $this->replay($stored, $fingerprint); } - $lock = $this->store->lock($storageKey); + $lock = $this->store->lock($scope, $key); if (! $lock->get()) { throw IdempotencyKeyConflict::inFlight($this->retryAfter); @@ -68,7 +68,7 @@ public function handle(Request $request, Closure $next, string ...$options): Res try { // The original may have finished between the first look and taking the lock. - if (($stored = $this->store->get($storageKey)) !== null) { + if (($stored = $this->store->get($scope, $key)) !== null) { return $this->replay($stored, $fingerprint); } @@ -77,7 +77,7 @@ public function handle(Request $request, Closure $next, string ...$options): Res $captured = $this->shouldStore($response) ? StoredResponse::capture($fingerprint, $response) : null; if ($captured !== null) { - $this->store->put($storageKey, $captured); + $this->store->put($scope, $key, $captured); } return $response; @@ -104,12 +104,11 @@ private function replay(StoredResponse $stored, string $fingerprint): Response * or the client address when there is none, so two clients that pick the same key do not * collide. */ - private function storageKey(Request $request, IdempotencyKey $key): string + private function scope(Request $request): string { $identifier = $request->user()?->getAuthIdentifier(); - $scope = is_scalar($identifier) ? 'user:'.$identifier : 'ip:'.$request->ip(); - return hash('sha256', $scope."\n".$key->value); + return is_scalar($identifier) ? 'user:'.$identifier : 'ip:'.$request->ip(); } /** diff --git a/src/Idempotency/IdempotencyServiceProvider.php b/src/Idempotency/IdempotencyServiceProvider.php index b85da1d..2d5f59e 100644 --- a/src/Idempotency/IdempotencyServiceProvider.php +++ b/src/Idempotency/IdempotencyServiceProvider.php @@ -8,6 +8,7 @@ use Illuminate\Contracts\Cache\Factory; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Http\Kernel as KernelContract; +use Illuminate\Encryption\Encrypter; use Illuminate\Foundation\Http\Kernel; use Illuminate\Routing\Router; use Illuminate\Support\ServiceProvider; @@ -30,6 +31,7 @@ public function register(): void $app->make(Factory::class)->store(is_string($store) ? $store : null), self::integer($options['ttl'] ?? null, self::DEFAULT_TTL), self::integer($options['lock'] ?? null, 60), + array_values(array_filter($app->make(Encrypter::class)->getAllKeys(), is_string(...))), ); }); diff --git a/src/Idempotency/IdempotencyStore.php b/src/Idempotency/IdempotencyStore.php index 1677144..a60c1f7 100644 --- a/src/Idempotency/IdempotencyStore.php +++ b/src/Idempotency/IdempotencyStore.php @@ -8,10 +8,19 @@ use Illuminate\Contracts\Cache\Lock; use Illuminate\Contracts\Cache\LockProvider; use Illuminate\Contracts\Cache\Repository; +use Illuminate\Contracts\Encryption\DecryptException; +use Illuminate\Encryption\Encrypter; +use JsonException; use LogicException; /** * Completed responses and in-flight locks, in any Laravel cache store that supports locks. + * + * A stored response can hold a secret, such as an API key shown once when it is created, and a + * replay has to return it. So each response is encrypted with a key derived from the application + * key and the client's own Idempotency-Key, and stored under a hash of that key. The cache alone + * cannot be read, and nor can the cache with the application key: decrypting an entry takes the + * Idempotency-Key that created it, which only the client has. */ final readonly class IdempotencyStore { @@ -22,12 +31,18 @@ /** * @param int $ttl Seconds a completed response is kept, and so how long a key stays valid. * @param int $lockSeconds Longest a request is treated as in flight, should it never finish. + * @param list $keys The application's encryption keys, current first, then any previous ones. */ public function __construct( private Repository $cache, private int $ttl, private int $lockSeconds, + private array $keys, ) { + if ($keys === []) { + throw new LogicException('Idempotency needs the application key to encrypt stored responses.'); + } + $store = $cache->getStore(); // Without an atomic lock there is no way to tell a retry from a concurrent duplicate, @@ -50,21 +65,71 @@ public function __construct( /** * Reads shared state another request can change at any moment. * + * An entry that cannot be decrypted is treated as missing. That happens when the application + * key changes and the old one is not kept in APP_PREVIOUS_KEYS. + * * @phpstan-impure */ - public function get(string $key): ?StoredResponse + public function get(string $scope, IdempotencyKey $key): ?StoredResponse { - return StoredResponse::fromArray($this->cache->get(self::PREFIX.$key)); + $entry = $this->cache->get(self::PREFIX.self::id($scope, $key)); + + // Versions before 0.4 stored the response unencrypted. Reading those until they expire + // keeps a retry that straddles an upgrade from running twice. + if (is_array($entry)) { + return StoredResponse::fromArray($entry); + } + + if (! is_string($entry)) { + return null; + } + + foreach ($this->keys as $applicationKey) { + try { + $json = self::encrypter($applicationKey, $scope, $key)->decryptString($entry); + + return StoredResponse::fromArray(json_decode($json, true, flags: JSON_THROW_ON_ERROR)); + } catch (DecryptException|JsonException) { + continue; + } + } + + return null; } - public function put(string $key, StoredResponse $response): void + public function put(string $scope, IdempotencyKey $key, StoredResponse $response): void { - $this->cache->put(self::PREFIX.$key, $response->toArray(), $this->ttl); + $json = json_encode($response->toArray(), JSON_THROW_ON_ERROR); + + $this->cache->put( + self::PREFIX.self::id($scope, $key), + self::encrypter($this->keys[0], $scope, $key)->encryptString($json), + $this->ttl, + ); } - public function lock(string $key): Lock + public function lock(string $scope, IdempotencyKey $key): Lock { - return $this->locks->lock(self::PREFIX.'lock:'.$key, $this->lockSeconds); + return $this->locks->lock(self::PREFIX.'lock:'.self::id($scope, $key), $this->lockSeconds); + } + + /** + * Where an entry is kept: a hash, so the cache never holds the Idempotency-Key itself. + */ + private static function id(string $scope, IdempotencyKey $key): string + { + return hash('sha256', $scope."\n".$key->value); + } + + /** + * HKDF (RFC 5869) from the application key, with the scope and Idempotency-Key as the + * context, so every entry has its own key and none can be derived without the client's. + */ + private static function encrypter(string $applicationKey, string $scope, IdempotencyKey $key): Encrypter + { + $derived = hash_hkdf('sha256', $applicationKey, 32, 'api-toolbox idempotency v1|'.$scope."\n".$key->value); + + return new Encrypter($derived, 'aes-256-gcm'); } public function ttl(): int diff --git a/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php b/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php index 1916e81..7ccf376 100644 --- a/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php +++ b/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php @@ -6,6 +6,7 @@ use Closure; use Illuminate\Http\Request; +use Illuminate\Routing\Route; use InvalidArgumentException; use JustSteveKing\Toolbox\Negotiation\Exceptions\UnsupportedMediaType; use JustSteveKing\Toolbox\Negotiation\MediaType; @@ -17,6 +18,11 @@ * * ->middleware('consumes:application/json,application/merge-patch+json') * + * A route that declares its own consumes overrides one from its group: only the last declaration + * the route lists applies, and group middleware is listed before the route's own. So an API can + * put consumes:application/json on its whole group and let a PATCH route consume + * application/merge-patch+json instead, without lifting the group's declaration first. + * * Only requests with content are checked. Content without a Content-Type is refused too: RFC 9110 * section 8.3 lets a recipient assume application/octet-stream or sniff, and neither is a type * the route said it consumes. @@ -25,7 +31,7 @@ { public function handle(Request $request, Closure $next, string ...$consumes): Response { - if (self::hasContent($request)) { + if (self::hasContent($request) && self::applies($request, $consumes)) { $supported = array_map( static fn (string $type): MediaType => MediaType::parse($type) ?? throw new InvalidArgumentException("[{$type}] is not a media type."), $consumes, @@ -55,6 +61,39 @@ public function handle(Request $request, Closure $next, string ...$consumes): Re return $response; } + /** + * Whether this declaration is the route's last. A route gathers its group's middleware before + * its own and its controller's, so the last is the most specific. One the route excluded with + * withoutMiddleware() never runs, so it is not counted. + * + * @param array $consumes + */ + private static function applies(Request $request, array $consumes): bool + { + $route = $request->route(); + + if (! $route instanceof Route) { + return true; + } + + $excluded = $route->excludedMiddleware(); + $last = null; + + foreach ($route->gatherMiddleware() as $middleware) { + if (! is_string($middleware) || in_array($middleware, $excluded, true)) { + continue; + } + + [$name, $parameters] = array_pad(explode(':', $middleware, 2), 2, ''); + + if ($name === 'consumes' || $name === self::class) { + $last = $parameters; + } + } + + return $last === null || explode(',', $last) === array_values($consumes); + } + /** * The raw body is not enough on its own: PHP parses multipart/form-data into fields and files * and leaves php://input empty, so a multipart upload has content only in the parameter bags. diff --git a/tests/Feature/ConditionalRequestsTest.php b/tests/Feature/ConditionalRequestsTest.php index 413c4a6..3a862c2 100644 --- a/tests/Feature/ConditionalRequestsTest.php +++ b/tests/Feature/ConditionalRequestsTest.php @@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Schema; use JustSteveKing\Toolbox\Tests\Fixtures\Models\Document; +use JustSteveKing\Toolbox\Tests\Fixtures\Models\Folder; beforeEach(function (): void { Schema::create('documents', function (Blueprint $table): void { @@ -16,6 +17,15 @@ $table->timestamps(); }); + Schema::create('folders', function (Blueprint $table): void { + $table->id(); + $table->string('name'); + $table->timestamps(); + }); + + $this->folder = Folder::query()->create(['name' => 'Contracts']); + $this->folder->forceFill(['updated_at' => '2026-10-01 09:00:00'])->saveQuietly(); + $this->document = Document::query()->create(['title' => 'Draft']); $this->document->forceFill(['updated_at' => '2026-10-15 09:00:00'])->saveQuietly(); @@ -26,6 +36,12 @@ return ['title' => $document->title]; }); + Route::get('api/folders/{folder}/documents/{document}', fn (Folder $folder, Document $document) => ['title' => $document->title]); + Route::patch('api/folders/{folder}/documents/{document}', function (Request $request, Folder $folder, Document $document) { + $document->update(['title' => $request->string('title')->toString()]); + + return ['title' => $document->title]; + }); Route::put('api/drafts/{slug}', fn (string $slug) => response(['slug' => $slug], 201)); Route::get('api/content', fn () => ['hello' => 'world']); }); @@ -172,3 +188,23 @@ function currentTag(): string ->assertCacheControl(['public', 'max-age' => 60, 'stale-while-revalidate' => 30, 'stale-if-error' => 86400, 'immutable']); }); }); + +describe('nested routes', function (): void { + it('takes validators from the resource the URI names, not its parent', function (): void { + $this->get('api/folders/1/documents/1') + ->assertOk() + ->assertETag(currentTag(), weak: false) + ->assertHeader('Last-Modified', 'Thu, 15 Oct 2026 09:00:00 GMT'); + }); + + it('checks If-Match against the nested resource', function (): void { + $this->patch('api/folders/1/documents/1', ['title' => 'Final'], ['If-Match' => currentTag()])->assertOk(); + }); + + it('refuses an If-Match that only matches the parent', function (): void { + $this->patch('api/folders/1/documents/1', ['title' => 'Final'], ['If-Match' => $this->folder->entityTag()->toString()]) + ->assertPreconditionFailed(); + + expect(Document::query()->firstOrFail()->title)->toBe('Draft'); + }); +}); diff --git a/tests/Feature/IdempotencyTest.php b/tests/Feature/IdempotencyTest.php index cf0f7fe..f2e5ed9 100644 --- a/tests/Feature/IdempotencyTest.php +++ b/tests/Feature/IdempotencyTest.php @@ -5,6 +5,7 @@ use Illuminate\Auth\GenericUser; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; +use JustSteveKing\Toolbox\Idempotency\IdempotencyKey; use JustSteveKing\Toolbox\Idempotency\IdempotencyStore; beforeEach(function (): void { @@ -90,9 +91,8 @@ function charge(PHPUnit\Framework\TestCase $test, string $key, int $amount = 50) }); it('answers a retry while the original is in flight with 409, Retry-After and the apiguide.dev type', function (): void { - // Hold the lock the original request would hold. The storage key is the user or client - // address, then the key, hashed, as the middleware builds it. - $lock = app(IdempotencyStore::class)->lock(hash('sha256', "ip:127.0.0.1\nabc")); + // Hold the lock the original request would hold, scoped to the client address. + $lock = app(IdempotencyStore::class)->lock('ip:127.0.0.1', IdempotencyKey::parse('"abc"')); $lock->get(); charge($this, '"abc"') diff --git a/tests/Feature/NegotiationTest.php b/tests/Feature/NegotiationTest.php index f2a44a3..fb2a90d 100644 --- a/tests/Feature/NegotiationTest.php +++ b/tests/Feature/NegotiationTest.php @@ -88,6 +88,39 @@ ->assertJsonPath('detail', 'The request has content but no Content-Type. Supported content types: application/json.'); }); + it('lets a route declaration override its group', function (): void { + Route::middleware('consumes:application/json')->group(function (): void { + Route::post('api/documents', fn () => ['ok' => true]); + Route::patch('api/documents/1', fn () => ['ok' => true])->middleware('consumes:application/merge-patch+json'); + }); + + $patch = fn (string $type) => $this->call('PATCH', 'api/documents/1', [], [], [], ['CONTENT_TYPE' => $type, 'HTTP_ACCEPT' => 'application/json'], '{"a":1}'); + + $patch('application/merge-patch+json')->assertOk(); + $patch('application/json')->assertStatus(415)->assertHeader('Accept', 'application/merge-patch+json'); + + $this->call('POST', 'api/documents', [], [], [], ['CONTENT_TYPE' => 'application/merge-patch+json', 'HTTP_ACCEPT' => 'application/json'], '{"a":1}') + ->assertStatus(415); + }); + + it('lets a controller declaration override the route', function (): void { + Route::patch('api/documents/2', ConsumesMergePatchController::class)->middleware('consumes:application/json'); + + $this->call('PATCH', 'api/documents/2', [], [], [], ['CONTENT_TYPE' => 'application/merge-patch+json', 'HTTP_ACCEPT' => 'application/json'], '{"a":1}') + ->assertOk(); + }); + + it('applies the group declaration when the route excludes its own', function (): void { + Route::middleware('consumes:application/json')->group(function (): void { + Route::patch('api/documents/3', fn () => ['ok' => true]) + ->middleware('consumes:application/merge-patch+json') + ->withoutMiddleware('consumes:application/merge-patch+json'); + }); + + $this->call('PATCH', 'api/documents/3', [], [], [], ['CONTENT_TYPE' => 'application/merge-patch+json', 'HTTP_ACCEPT' => 'application/json'], '{"a":1}') + ->assertStatus(415); + }); + it('adds Accept-Patch to a refused PATCH (RFC 5789 section 2.2)', function (): void { $this->call('PATCH', 'api/leads/1', [], [], [], ['CONTENT_TYPE' => 'application/json', 'HTTP_ACCEPT' => 'application/json'], '{"a":1}') ->assertStatus(415) @@ -189,3 +222,16 @@ Http::assertSent(fn (ClientRequest $request) => $request->header('traceparent') === ['00-11111111111111111111111111111111-2222222222222222-01']); }); }); + +final class ConsumesMergePatchController implements Illuminate\Routing\Controllers\HasMiddleware +{ + public static function middleware(): array + { + return ['consumes:application/merge-patch+json']; + } + + public function __invoke(): array + { + return ['ok' => true]; + } +} diff --git a/tests/Fixtures/Models/Folder.php b/tests/Fixtures/Models/Folder.php new file mode 100644 index 0000000..f193b0b --- /dev/null +++ b/tests/Fixtures/Models/Folder.php @@ -0,0 +1,20 @@ +lock(hash('sha256', "ip:127.0.0.1\nabc")); + $lock = app(IdempotencyStore::class)->lock('ip:127.0.0.1', IdempotencyKey::parse('"abc"')); $lock->get(); $this->postJson('v1/strict', [], ['Idempotency-Key' => '"abc"'])->assertStatus(409)->assertHeader('Retry-After', '5'); diff --git a/tests/TestCase.php b/tests/TestCase.php index f1bec65..952bf40 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -49,6 +49,8 @@ protected function resolveApplicationConfiguration($app): void { parent::resolveApplicationConfiguration($app); + // Every Laravel application has one, and idempotency encrypts what it stores with it. + $app['config']->set('app.key', 'base64:'.base64_encode(str_repeat('k', 32))); $app['config']->set(Features::CONFIG_KEY.'.features', $this->features()); } } diff --git a/tests/Unit/IdempotencyStoreTest.php b/tests/Unit/IdempotencyStoreTest.php index a275691..3ab5bda 100644 --- a/tests/Unit/IdempotencyStoreTest.php +++ b/tests/Unit/IdempotencyStoreTest.php @@ -2,9 +2,12 @@ declare(strict_types=1); +use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; use Illuminate\Contracts\Cache\Store; +use JustSteveKing\Toolbox\Idempotency\IdempotencyKey; use JustSteveKing\Toolbox\Idempotency\IdempotencyStore; +use JustSteveKing\Toolbox\Idempotency\StoredResponse; it('refuses a cache store that cannot lock, rather than fail open', function (): void { $store = new class implements Store @@ -65,9 +68,79 @@ public function getPrefix(): string } }; - new IdempotencyStore(new Repository($store), 60, 60); + new IdempotencyStore(new Repository($store), 60, 60, ['key']); })->throws(LogicException::class, 'needs a cache store that supports atomic locks'); it('refuses the null store, which would recognise no retry', function (): void { - new IdempotencyStore(new Repository(new Illuminate\Cache\NullStore), 60, 60); + new IdempotencyStore(new Repository(new Illuminate\Cache\NullStore), 60, 60, ['key']); })->throws(LogicException::class, 'cannot use the null cache store'); + +function storedResponse(): StoredResponse +{ + return new StoredResponse('fingerprint', 201, ['Content-Type' => ['application/json']], '{"token":"secret-value"}'); +} + +function idempotencyKey(string $value): IdempotencyKey +{ + return IdempotencyKey::parse('"'.$value.'"') ?? throw new LogicException('Invalid key.'); +} + +it('refuses to run without an application key', function (): void { + new IdempotencyStore(new Repository(new ArrayStore), 60, 60, []); +})->throws(LogicException::class, 'Idempotency needs the application key to encrypt stored responses.'); + +it('reads back what it stored', function (): void { + $store = new IdempotencyStore(new Repository(new ArrayStore), 60, 60, ['app-key']); + + $store->put('user:1', idempotencyKey('abc'), storedResponse()); + + expect($store->get('user:1', idempotencyKey('abc')))->toEqual(storedResponse()); +}); + +it('keeps neither the response nor the key readable in the cache', function (): void { + $cache = new Repository(new ArrayStore); + $store = new IdempotencyStore($cache, 60, 60, ['app-key']); + + $store->put('user:1', idempotencyKey('abc'), storedResponse()); + + $entry = $cache->get('api-toolbox:idempotency:'.hash('sha256', "user:1\nabc")); + + expect($entry)->toBeString() + ->not->toContain('secret-value') + ->not->toContain('abc'); +}); + +it('cannot read an entry without the Idempotency-Key that wrote it, even with the application key', function (): void { + $cache = new Repository(new ArrayStore); + $store = new IdempotencyStore($cache, 60, 60, ['app-key']); + + $store->put('user:1', idempotencyKey('abc'), storedResponse()); + + // Copy the entry to where another key's response would live. + $cache->put( + 'api-toolbox:idempotency:'.hash('sha256', "user:1\nxyz"), + $cache->get('api-toolbox:idempotency:'.hash('sha256', "user:1\nabc")), + 60, + ); + + expect($store->get('user:1', idempotencyKey('xyz')))->toBeNull(); +}); + +it('reads entries written under a previous application key', function (): void { + $cache = new Repository(new ArrayStore); + + (new IdempotencyStore($cache, 60, 60, ['old-key']))->put('user:1', idempotencyKey('abc'), storedResponse()); + + expect((new IdempotencyStore($cache, 60, 60, ['new-key', 'old-key']))->get('user:1', idempotencyKey('abc'))) + ->toEqual(storedResponse()) + ->and((new IdempotencyStore($cache, 60, 60, ['new-key']))->get('user:1', idempotencyKey('abc'))) + ->toBeNull(); +}); + +it('reads an unencrypted entry left by an earlier version', function (): void { + $cache = new Repository(new ArrayStore); + $cache->put('api-toolbox:idempotency:'.hash('sha256', "user:1\nabc"), storedResponse()->toArray(), 60); + + expect((new IdempotencyStore($cache, 60, 60, ['app-key']))->get('user:1', idempotencyKey('abc'))) + ->toEqual(storedResponse()); +});