Skip to content
Draft
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
- `{% expires in … %}` and `{% expires on … %}` now set just `Cache-Control: public, max-age=…`, without the `Expires` and `Pragma: cache` headers. ([#20753](https://github.com/craftcms/cms/pull/20753))
- `ResponseHeaders::noCache()` no longer overrides cache headers set after it, such as by a later `{% expires %}` tag. Headers queued with `ResponseHeaders` are applied in the order they were set, so the last one wins. Directives set with `ResponseHeaders::cacheControl()` combine with earlier ones instead, so they don’t override an earlier `noCache()`. ([#20753](https://github.com/craftcms/cms/pull/20753))
- Responses that contain the session’s CSRF token in their body or headers, such as pages that output `csrfInput()` or `csrf_token()`, now have no-cache headers, replacing any cache headers set by `{% expires %}` or other means. Streamed responses aren’t checked, though on routes with lazy sessions they always get no-cache headers. Pages can use `csrfInput({async: true})` or the `asyncCsrfInputs` config setting to stay cacheable. `csrfInput()` no longer sets no-cache headers itself, so pages on routes without session middleware, where its token is empty, can be cached. ([#20753](https://github.com/craftcms/cms/pull/20753))
- No-cache headers that Craft sends, such as for control panel, action, and token requests and saved sessions, now also remove `CDN-Cache-Control`, `Cloudflare-CDN-Cache-Control`, and `Surrogate-Control` headers, which CDNs read in place of `Cache-Control`. ([#20769](https://github.com/craftcms/cms/pull/20769))
- Deprecated `{% expires %}` and `@craftExpires` without a duration. `{% do ResponseHeaders.noCache() %}` should be used instead. ([#20753](https://github.com/craftcms/cms/pull/20753))
- Added `CraftCms\Cms\Http\ResponseHeaders::cacheControl()`, which sets the response’s cache directives with Symfony’s `Response` method names, such as `{% do ResponseHeaders.cacheControl.setPublic().setSharedMaxAge(86400) %}` in Twig. ([#20753](https://github.com/craftcms/cms/pull/20753))
- Added `CraftCms\Cms\Http\Events\LazySessionSaved`, which reports the session keys or CSRF token that caused a session to be saved for a request without one. The reason is also logged at the debug level. ([#20753](https://github.com/craftcms/cms/pull/20753))
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Middleware/HandleTokenRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public function handle(Request $request, Closure $next): mixed
private function preventCaching(mixed $response): mixed
{
if ($response instanceof Response) {
$response->headers->add(ResponseHeaders::NO_CACHE_HEADERS);
ResponseHeaders::setNoCacheHeaders($response);
}

return $response;
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Middleware/SetHeaders.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function handle(Request $request, Closure $next): mixed
Context::getHidden(ResolveSite::HAD_SITE_TOKEN_KEY) === true ||
$this->containsCsrfToken($request, $response)
) {
$response->headers->add(ResponseHeaders::NO_CACHE_HEADERS);
ResponseHeaders::setNoCacheHeaders($response);
}

$this->setPoweredByHeader($response);
Expand Down
2 changes: 1 addition & 1 deletion src/Http/Middleware/StartLazySession.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ public function handle(Request $request, Closure $next): mixed
private function preventCaching(mixed $response): mixed
{
if ($response instanceof Response) {
$response->headers->add(ResponseHeaders::NO_CACHE_HEADERS);
ResponseHeaders::setNoCacheHeaders($response);
}

return $response;
Expand Down
26 changes: 25 additions & 1 deletion src/Http/ResponseHeaders.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,30 @@ class ResponseHeaders
'Expires' => '0',
];

/**
* Cache headers aimed at shared caches only, which CDNs read in place of `Cache-Control`.
*
* @see https://www.rfc-editor.org/rfc/rfc9213
*/
private const array TARGETED_CACHE_HEADERS = [
'CDN-Cache-Control',
'Cloudflare-CDN-Cache-Control',
'Surrogate-Control',
];

/**
* Keeps browsers and shared caches from storing the response, replacing its cache headers, including ones
* aimed at CDNs, such as `CDN-Cache-Control`.
*/
public static function setNoCacheHeaders(Response $response): void
{
$response->headers->add(self::NO_CACHE_HEADERS);

foreach (self::TARGETED_CACHE_HEADERS as $name) {
$response->headers->remove($name);
}
}

/** @var list<Closure(Response): mixed> */
private array $queue = [];

Expand All @@ -53,7 +77,7 @@ public function cacheControl(): CacheControl
*/
public function noCache(): void
{
$this->queue[] = fn (Response $response) => $response->headers->add(self::NO_CACHE_HEADERS);
$this->queue[] = self::setNoCacheHeaders(...);
}

/**
Expand Down
8 changes: 7 additions & 1 deletion src/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,14 @@ private function registerMacros(): void
SessionStore::mixin(new SessionMixin);

Response::macro('setNoCacheHeaders', function (bool $replace = true) {
if ($replace) {
ResponseHeaders::setNoCacheHeaders($this);

return $this;
}

foreach (ResponseHeaders::NO_CACHE_HEADERS as $name => $value) {
$this->header($name, $value, $replace);
$this->header($name, $value, false);
}

return $this;
Expand Down
13 changes: 13 additions & 0 deletions tests/Feature/Http/Middleware/SetHeadersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,19 @@
expect($response->headers->has('Cache-Control'))->toBeTrue();
});

it('removes CDN cache headers when setting no-cache headers', function () {
$this->responseHeaders->add('CDN-Cache-Control', 'max-age=3600');
$this->responseHeaders->add('Cloudflare-CDN-Cache-Control', 'max-age=3600');
$this->responseHeaders->add('Surrogate-Control', 'max-age=3600');

$response = $this->middleware->handle(Request::create('/'.Cms::config()->actionTrigger.'/test'), fn () => new Response);

expect($response->headers->get('Cache-Control'))->toBe('must-revalidate, no-cache, no-store, private')
->and($response->headers->has('CDN-Cache-Control'))->toBeFalse()
->and($response->headers->has('Cloudflare-CDN-Cache-Control'))->toBeFalse()
->and($response->headers->has('Surrogate-Control'))->toBeFalse();
});

it('sets X-Robots-Tag header when disallowRobots is true', function () {
$this->generalConfig->disallowRobots();

Expand Down
Loading