Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
14 changes: 9 additions & 5 deletions src/ConditionalRequests/RouteValidators.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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;
}
}
15 changes: 7 additions & 8 deletions src/Idempotency/Http/Middleware/EnsureIdempotency.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,22 @@ 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);
}

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);
}

Expand All @@ -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;
Expand All @@ -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();
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/Idempotency/IdempotencyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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(...))),
);
});

Expand Down
77 changes: 71 additions & 6 deletions src/Idempotency/IdempotencyStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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<string> $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,
Expand All @@ -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
Expand Down
41 changes: 40 additions & 1 deletion src/Negotiation/Http/Middleware/EnsureSupportedMediaType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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<array-key, string> $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.
Expand Down
36 changes: 36 additions & 0 deletions tests/Feature/ConditionalRequestsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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();

Expand All @@ -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']);
});
Expand Down Expand Up @@ -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');
});
});
Loading
Loading