From 11130830669dea6b82316a30fc4ea10b01f88719 Mon Sep 17 00:00:00 2001 From: Steve McDougall Date: Tue, 20 Oct 2026 20:27:11 +0100 Subject: [PATCH 1/4] Take a route's validators from its last bound resource, so nested routes use the child RouteValidators returned the first route parameter implementing HasValidators. On folders/{folder}/documents/{document} that is the folder, so a GET sent the folder's ETag and a PATCH checked If-Match against the folder, letting a stale write to the document through. A URI names parents first, so the last bound validator is the resource the request is about. --- README.md | 5 +++ .../references/caching-and-pagination.md | 2 +- src/ConditionalRequests/RouteValidators.php | 14 +++++--- tests/Feature/ConditionalRequestsTest.php | 36 +++++++++++++++++++ tests/Fixtures/Models/Folder.php | 20 +++++++++++ 5 files changed, 71 insertions(+), 6 deletions(-) create mode 100644 tests/Fixtures/Models/Folder.php diff --git a/README.md b/README.md index 328d137..24e9309 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 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/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/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 @@ + Date: Tue, 20 Oct 2026 20:27:58 +0100 Subject: [PATCH 2/4] Let a route's own consumes declaration override its group's With consumes:application/json on an API group, a PATCH route that took application/merge-patch+json had to lift the group's declaration with withoutMiddleware() first, or the group answered 415 before the route's own middleware ran. Only the last declaration a route lists now applies: group, then route, then controller. --- README.md | 4 ++ .../references/api-lifecycle.md | 1 + .../Middleware/EnsureSupportedMediaType.php | 41 ++++++++++++++++- tests/Feature/NegotiationTest.php | 46 +++++++++++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 24e9309..144f3ef 100644 --- a/README.md +++ b/README.md @@ -1236,6 +1236,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/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php b/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php index 1916e81..08523ff 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) === $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/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]; + } +} From 9e64623ce048338ee16aab3645ef84c6be80edfa Mon Sep 17 00:00:00 2001 From: Steve McDougall Date: Tue, 20 Oct 2026 20:29:43 +0100 Subject: [PATCH 3/4] Encrypt stored idempotent responses with a key only the client can supply A replay must return the original response, and some responses carry a secret shown once, such as a new API key. They sat in the cache as plain arrays for the whole TTL. Each is now encrypted with AES-256-GCM under a key derived by HKDF from the application key and the client's Idempotency-Key, and stored under a hash of that key, so neither the cache nor the cache plus APP_KEY can read it. Previous application keys still decrypt, and unencrypted entries from earlier versions are read until they expire. --- README.md | 7 ++ .../Http/Middleware/EnsureIdempotency.php | 15 ++-- .../IdempotencyServiceProvider.php | 2 + src/Idempotency/IdempotencyStore.php | 77 +++++++++++++++++-- tests/Feature/IdempotencyTest.php | 6 +- tests/Options/IdempotencyOptionsTest.php | 3 +- tests/TestCase.php | 2 + tests/Unit/IdempotencyStoreTest.php | 77 ++++++++++++++++++- 8 files changed, 169 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 144f3ef..77f90fd 100644 --- a/README.md +++ b/README.md @@ -632,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 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..aa39ba8 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($app->make(Encrypter::class)->getAllKeys()), ); }); 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/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/Options/IdempotencyOptionsTest.php b/tests/Options/IdempotencyOptionsTest.php index 09874db..90017df 100644 --- a/tests/Options/IdempotencyOptionsTest.php +++ b/tests/Options/IdempotencyOptionsTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Illuminate\Support\Facades\Route; +use JustSteveKing\Toolbox\Idempotency\IdempotencyKey; use JustSteveKing\Toolbox\Idempotency\IdempotencyStore; beforeEach(function (): void { @@ -23,7 +24,7 @@ }); it('sends the configured Retry-After while a request is in flight', function (): void { - $lock = app(IdempotencyStore::class)->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()); +}); From 0c9ecfd1025b4ffa50be37a7c1002d3c36e64626 Mon Sep 17 00:00:00 2001 From: Steve McDougall Date: Tue, 20 Oct 2026 20:48:00 +0100 Subject: [PATCH 4/4] Narrow the application keys and consumes parameters for PHPStan --- src/Idempotency/IdempotencyServiceProvider.php | 2 +- src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Idempotency/IdempotencyServiceProvider.php b/src/Idempotency/IdempotencyServiceProvider.php index aa39ba8..2d5f59e 100644 --- a/src/Idempotency/IdempotencyServiceProvider.php +++ b/src/Idempotency/IdempotencyServiceProvider.php @@ -31,7 +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($app->make(Encrypter::class)->getAllKeys()), + array_values(array_filter($app->make(Encrypter::class)->getAllKeys(), is_string(...))), ); }); diff --git a/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php b/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php index 08523ff..7ccf376 100644 --- a/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php +++ b/src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php @@ -66,7 +66,7 @@ public function handle(Request $request, Closure $next, string ...$consumes): Re * 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 + * @param array $consumes */ private static function applies(Request $request, array $consumes): bool { @@ -91,7 +91,7 @@ private static function applies(Request $request, array $consumes): bool } } - return $last === null || explode(',', $last) === $consumes; + return $last === null || explode(',', $last) === array_values($consumes); } /**