From f614da8d51071bec153669a9411a520fa3c308af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Bu=CC=88nemann?= Date: Thu, 15 Oct 2026 19:16:04 +0200 Subject: [PATCH 1/3] refactor(htaccess): read the cache header configuration through CacheHeaderService Move reading config.sendCacheHeaders from the request's frontend TypoScript into a CacheHeaderService, which also returns config.sendCacheHeadersForSharedCaches. No change in behaviour; the following commits use the service to send the same cache headers as TYPO3 from both the .htaccess and the fallback middleware delivery. --- Classes/Generator/HtaccessGenerator.php | 9 ++-- Classes/Service/CacheHeaderService.php | 32 +++++++++++++ Tests/Unit/Service/CacheHeaderServiceTest.php | 48 +++++++++++++++++++ 3 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 Classes/Service/CacheHeaderService.php create mode 100644 Tests/Unit/Service/CacheHeaderServiceTest.php diff --git a/Classes/Generator/HtaccessGenerator.php b/Classes/Generator/HtaccessGenerator.php index 87ae4813a82..508518c39d5 100644 --- a/Classes/Generator/HtaccessGenerator.php +++ b/Classes/Generator/HtaccessGenerator.php @@ -4,11 +4,12 @@ namespace SFC\Staticfilecache\Generator; +use Psr\Http\Message\ServerRequestInterface; use SFC\Staticfilecache\Event\GeneratorCreate; use SFC\Staticfilecache\Event\GeneratorRemove; +use SFC\Staticfilecache\Service\CacheHeaderService; use SFC\Staticfilecache\Service\ConfigurationService; use SFC\Staticfilecache\Service\DateTimeService; -use TYPO3\CMS\Core\TypoScript\FrontendTypoScript; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Core\Utility\PathUtility; @@ -32,8 +33,8 @@ public function generate(GeneratorCreate $generatorCreateEvent): void $contentType = $matches[0]; } - $frontendTypoScript = ($GLOBALS['TYPO3_REQUEST'] ?? null)?->getAttribute('frontend.typoscript'); - $sendCacheControlHeader = $frontendTypoScript instanceof FrontendTypoScript && (bool) ($frontendTypoScript->getConfigArray()['sendCacheHeaders'] ?? false); + $request = ($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface ? $GLOBALS['TYPO3_REQUEST'] : null; + $typoScriptConfiguration = GeneralUtility::makeInstance(CacheHeaderService::class)->getTypoScriptConfiguration($request); $variables = [ 'contentType' => $contentType, @@ -41,7 +42,7 @@ public function generate(GeneratorCreate $generatorCreateEvent): void 'lifetime' => $lifetime, 'TIME' => '{TIME}', 'expires' => (new DateTimeService())->getCurrentTime() + $lifetime, - 'sendCacheControlHeader' => $sendCacheControlHeader, + 'sendCacheControlHeader' => $typoScriptConfiguration['sendCacheHeaders'], 'sendCacheControlHeaderRedirectAfterCacheTimeout' => $configuration->isBool('sendCacheControlHeaderRedirectAfterCacheTimeout'), 'headers' => $this->cleanupHeaderValues($headers), ]; diff --git a/Classes/Service/CacheHeaderService.php b/Classes/Service/CacheHeaderService.php new file mode 100644 index 00000000000..c93f5829ee7 --- /dev/null +++ b/Classes/Service/CacheHeaderService.php @@ -0,0 +1,32 @@ +getAttribute('frontend.typoscript'); + $configArray = $frontendTypoScript instanceof FrontendTypoScript ? $frontendTypoScript->getConfigArray() : []; + + return [ + 'sendCacheHeaders' => (bool) ($configArray['sendCacheHeaders'] ?? false), + 'sendCacheHeadersForSharedCaches' => (string) ($configArray['sendCacheHeadersForSharedCaches'] ?? ''), + ]; + } +} diff --git a/Tests/Unit/Service/CacheHeaderServiceTest.php b/Tests/Unit/Service/CacheHeaderServiceTest.php new file mode 100644 index 00000000000..e463298c0a7 --- /dev/null +++ b/Tests/Unit/Service/CacheHeaderServiceTest.php @@ -0,0 +1,48 @@ + false, 'sendCacheHeadersForSharedCaches' => ''], + (new CacheHeaderService())->getTypoScriptConfiguration(null) + ); + } + + public function testTypoScriptConfigurationWithoutFrontendTypoScript(): void + { + self::assertSame( + ['sendCacheHeaders' => false, 'sendCacheHeadersForSharedCaches' => ''], + (new CacheHeaderService())->getTypoScriptConfiguration(new ServerRequest('https://example.com/')) + ); + } + + public function testTypoScriptConfigurationFromFrontendTypoScript(): void + { + $frontendTypoScript = new FrontendTypoScript(new RootNode(), [], [], []); + $frontendTypoScript->setConfigArray(['sendCacheHeaders' => '1', 'sendCacheHeadersForSharedCaches' => 'force']); + $request = (new ServerRequest('https://example.com/'))->withAttribute('frontend.typoscript', $frontendTypoScript); + + self::assertSame( + ['sendCacheHeaders' => true, 'sendCacheHeadersForSharedCaches' => 'force'], + (new CacheHeaderService())->getTypoScriptConfiguration($request) + ); + } +} From 5b87fb73457a2ae89e8b7a59aec579a93b49207e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Bu=CC=88nemann?= Date: Thu, 15 Oct 2026 19:16:25 +0200 Subject: [PATCH 2/3] feat(htaccess): send s-maxage for shared caches like TYPO3 With config.sendCacheHeadersForSharedCaches TYPO3 answers max-age=0, s-maxage=, so browsers revalidate while shared caches such as a CDN keep the page. Entries delivered from Apache via the .htaccess template only ever got mod_expires' max-age, and nothing at all when config.sendCacheHeaders was off. HtaccessGenerator now evaluates config.sendCacheHeadersForSharedCaches the way TYPO3 does - always for "force", for "auto" when the request comes through a trusted reverse proxy - and the template rewrites mod_expires' max-age into max-age=0, s-maxage= for those entries. Like in TYPO3 this does not require config.sendCacheHeaders. Apache cannot evaluate the reverse proxy check itself, so for "auto" the request that generates the entry decides. --- Classes/Generator/HtaccessGenerator.php | 8 +++- Classes/Service/CacheHeaderService.php | 22 +++++++++ Resources/Private/Templates/Htaccess.html | 13 +++++- .../Unit/Generator/HtaccessGeneratorTest.php | 36 +++++++++++++++ Tests/Unit/Service/CacheHeaderServiceTest.php | 46 +++++++++++++++++++ 5 files changed, 123 insertions(+), 2 deletions(-) diff --git a/Classes/Generator/HtaccessGenerator.php b/Classes/Generator/HtaccessGenerator.php index 508518c39d5..40a9cefb8a0 100644 --- a/Classes/Generator/HtaccessGenerator.php +++ b/Classes/Generator/HtaccessGenerator.php @@ -33,8 +33,13 @@ public function generate(GeneratorCreate $generatorCreateEvent): void $contentType = $matches[0]; } + $cacheHeaderService = GeneralUtility::makeInstance(CacheHeaderService::class); $request = ($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface ? $GLOBALS['TYPO3_REQUEST'] : null; - $typoScriptConfiguration = GeneralUtility::makeInstance(CacheHeaderService::class)->getTypoScriptConfiguration($request); + $typoScriptConfiguration = $cacheHeaderService->getTypoScriptConfiguration($request); + // Apache cannot tell whether a later request comes through a trusted + // reverse proxy, so for "auto" the request generating the entry decides. + $sendCacheControlHeaderForSharedCaches = null !== $request + && $cacheHeaderService->isForSharedCaches($typoScriptConfiguration['sendCacheHeadersForSharedCaches'], $request); $variables = [ 'contentType' => $contentType, @@ -43,6 +48,7 @@ public function generate(GeneratorCreate $generatorCreateEvent): void 'TIME' => '{TIME}', 'expires' => (new DateTimeService())->getCurrentTime() + $lifetime, 'sendCacheControlHeader' => $typoScriptConfiguration['sendCacheHeaders'], + 'sendCacheControlHeaderForSharedCaches' => $sendCacheControlHeaderForSharedCaches, 'sendCacheControlHeaderRedirectAfterCacheTimeout' => $configuration->isBool('sendCacheControlHeaderRedirectAfterCacheTimeout'), 'headers' => $this->cleanupHeaderValues($headers), ]; diff --git a/Classes/Service/CacheHeaderService.php b/Classes/Service/CacheHeaderService.php index c93f5829ee7..54c0246ed4b 100644 --- a/Classes/Service/CacheHeaderService.php +++ b/Classes/Service/CacheHeaderService.php @@ -5,6 +5,7 @@ namespace SFC\Staticfilecache\Service; use Psr\Http\Message\ServerRequestInterface; +use TYPO3\CMS\Core\Http\NormalizedParams; use TYPO3\CMS\Core\TypoScript\FrontendTypoScript; /** @@ -29,4 +30,25 @@ public function getTypoScriptConfiguration(?ServerRequestInterface $request): ar 'sendCacheHeadersForSharedCaches' => (string) ($configArray['sendCacheHeadersForSharedCaches'] ?? ''), ]; } + + /** + * Whether TYPO3 sends the shared-cache variant (max-age=0, s-maxage=): + * always for "force", for "auto" when the request comes through a trusted + * reverse proxy. Like in TYPO3, this takes precedence over sendCacheHeaders. + */ + public function isForSharedCaches(string $sendCacheHeadersForSharedCaches, ServerRequestInterface $request): bool + { + if ('force' === $sendCacheHeadersForSharedCaches) { + return true; + } + if ('auto' !== $sendCacheHeadersForSharedCaches) { + return false; + } + $normalizedParams = $request->getAttribute('normalizedParams'); + if (!$normalizedParams instanceof NormalizedParams) { + $normalizedParams = NormalizedParams::createFromRequest($request); + } + + return $normalizedParams->isBehindReverseProxy(); + } } diff --git a/Resources/Private/Templates/Htaccess.html b/Resources/Private/Templates/Htaccess.html index c3151b99104..479ca6c54e6 100755 --- a/Resources/Private/Templates/Htaccess.html +++ b/Resources/Private/Templates/Htaccess.html @@ -2,12 +2,23 @@ {namespace sfc=SFC\Staticfilecache\ViewHelpers} ForceType {contentType} - + ExpiresActive on ExpiresByType {contentType} {mode}{lifetime} + + + + Header edit Cache-Control "^max-age=(\d+)$" "max-age=0, s-maxage=$1" + + diff --git a/Tests/Unit/Generator/HtaccessGeneratorTest.php b/Tests/Unit/Generator/HtaccessGeneratorTest.php index 0add94c5d43..c0b3be58925 100644 --- a/Tests/Unit/Generator/HtaccessGeneratorTest.php +++ b/Tests/Unit/Generator/HtaccessGeneratorTest.php @@ -6,6 +6,7 @@ use SFC\Staticfilecache\Generator\HtaccessGenerator; use SFC\Staticfilecache\Service\DateTimeService; +use TYPO3\CMS\Core\Http\NormalizedParams; use TYPO3\CMS\Core\Http\ServerRequest; use TYPO3\CMS\Core\TypoScript\AST\Node\RootNode; use TYPO3\CMS\Core\TypoScript\FrontendTypoScript; @@ -48,6 +49,7 @@ public function testGenerateAssignVariablesBasedOnLifetime(): void 'TIME' => '{TIME}', 'expires' => (new DateTimeService())->getCurrentTime() + 300, 'sendCacheControlHeader' => false, + 'sendCacheControlHeaderForSharedCaches' => false, 'sendCacheControlHeaderRedirectAfterCacheTimeout' => true, 'headers' => [ 'X-Custom' => 'value with \"quotes\"', @@ -117,6 +119,40 @@ public function testGenerateReadSendCacheHeadersFromFrontendTypoScript(array $co self::assertSame($expected, $this->assignedVariables['sendCacheControlHeader']); } + /** + * @return array + */ + public static function sendCacheHeadersForSharedCachesDataProvider(): array + { + return [ + 'force' => ['force', false, true], + 'auto behind a trusted reverse proxy' => ['auto', true, true], + 'auto without a trusted reverse proxy' => ['auto', false, false], + 'not set' => ['', true, false], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('sendCacheHeadersForSharedCachesDataProvider')] + public function testGenerateReadSendCacheHeadersForSharedCachesFromFrontendTypoScript(string $sendCacheHeadersForSharedCaches, bool $behindReverseProxy, bool $expected): void + { + $this->setExtensionConfiguration(); + $frontendTypoScript = new FrontendTypoScript(new RootNode(), [], [], []); + $frontendTypoScript->setConfigArray(['sendCacheHeadersForSharedCaches' => $sendCacheHeadersForSharedCaches]); + $normalizedParams = NormalizedParams::createFromServerParams( + ['REMOTE_ADDR' => '10.0.0.1', 'HTTP_HOST' => 'example.com'], + ['reverseProxyIP' => $behindReverseProxy ? '10.0.0.1' : ''] + ); + $GLOBALS['TYPO3_REQUEST'] = (new ServerRequest('https://example.com/')) + ->withAttribute('frontend.typoscript', $frontendTypoScript) + ->withAttribute('normalizedParams', $normalizedParams); + + $generator = new HtaccessGenerator($this->getEventDispatcher(), $this->getViewFactory()); + $generator->generate($this->getCreateEvent($this->createTemporaryDirectory() . 'index.html')); + + self::assertSame($expected, $this->assignedVariables['sendCacheControlHeaderForSharedCaches']); + self::assertFalse($this->assignedVariables['sendCacheControlHeader']); + } + public function testCleanupHeaderValuesRespectMaxHeaderSize(): void { $this->setExtensionConfiguration(['maxHeaderSize' => '10', 'headerSizeBuffer' => '2']); diff --git a/Tests/Unit/Service/CacheHeaderServiceTest.php b/Tests/Unit/Service/CacheHeaderServiceTest.php index e463298c0a7..645b46c0a80 100644 --- a/Tests/Unit/Service/CacheHeaderServiceTest.php +++ b/Tests/Unit/Service/CacheHeaderServiceTest.php @@ -6,6 +6,7 @@ use SFC\Staticfilecache\Service\CacheHeaderService; use SFC\Staticfilecache\Tests\Unit\AbstractTest; +use TYPO3\CMS\Core\Http\NormalizedParams; use TYPO3\CMS\Core\Http\ServerRequest; use TYPO3\CMS\Core\TypoScript\AST\Node\RootNode; use TYPO3\CMS\Core\TypoScript\FrontendTypoScript; @@ -45,4 +46,49 @@ public function testTypoScriptConfigurationFromFrontendTypoScript(): void (new CacheHeaderService())->getTypoScriptConfiguration($request) ); } + + /** + * @return array + */ + public static function forSharedCachesDataProvider(): array + { + return [ + 'force' => ['force', false, true], + 'auto behind a trusted reverse proxy' => ['auto', true, true], + 'auto without a trusted reverse proxy' => ['auto', false, false], + 'not set' => ['', true, false], + 'unknown value' => ['always', true, false], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('forSharedCachesDataProvider')] + public function testIsForSharedCaches(string $sendCacheHeadersForSharedCaches, bool $behindReverseProxy, bool $expected): void + { + $request = $this->getRequest($behindReverseProxy); + + self::assertSame($expected, (new CacheHeaderService())->isForSharedCaches($sendCacheHeadersForSharedCaches, $request)); + } + + public function testIsForSharedCachesCreatesNormalizedParamsWhenMissing(): void + { + $previous = $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'] ?? null; + $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'] = '10.0.0.1'; + $request = new ServerRequest('https://example.com/', 'GET', null, [], ['REMOTE_ADDR' => '10.0.0.1']); + + try { + self::assertTrue((new CacheHeaderService())->isForSharedCaches('auto', $request)); + } finally { + $GLOBALS['TYPO3_CONF_VARS']['SYS']['reverseProxyIP'] = $previous; + } + } + + protected function getRequest(bool $behindReverseProxy): ServerRequest + { + $normalizedParams = NormalizedParams::createFromServerParams( + ['REMOTE_ADDR' => '10.0.0.1', 'HTTP_HOST' => 'example.com'], + ['reverseProxyIP' => $behindReverseProxy ? '10.0.0.1' : ''] + ); + + return (new ServerRequest('https://example.com/'))->withAttribute('normalizedParams', $normalizedParams); + } } From f40ab9b4a45143e70981c61f7f2df55b429ef3c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Bu=CC=88nemann?= Date: Thu, 15 Oct 2026 19:16:40 +0200 Subject: [PATCH 3/3] feat(fallback): send the remaining lifetime as cache headers like TYPO3 The fallback middleware sent no cache headers of its own, only those validFallbackHeaders let into the entry's config.json. Storing TYPO3's Cache-Control there freezes it at generation time: every delivery then restarts the full lifetime, so a shared cache can keep a copy long after the entry expired. Not storing it leaves the response without any cache header, which shared caches answer with their own default TTL. The config generator now stores config.sendCacheHeaders and config.sendCacheHeadersForSharedCaches with the entry, and the fallback computes the headers on every delivery, as TYPO3 does when it serves from its page cache: Expires at the end of the entry's lifetime and Cache-Control max-age=, or max-age=0, s-maxage= for shared caches - always for "force", for "auto" when this request comes through a trusted reverse proxy. They take precedence over a stored Cache-Control or Expires. Entries written before this change send no cache headers until they are regenerated, as before. --- Classes/Generator/ConfigGenerator.php | 6 +++ Classes/Middleware/FallbackMiddleware.php | 15 ++++++ Classes/Service/CacheHeaderService.php | 19 +++++++ Tests/Unit/Generator/ConfigGeneratorTest.php | 33 ++++++++++++ .../Middleware/FallbackMiddlewareTest.php | 52 +++++++++++++++++++ Tests/Unit/Service/CacheHeaderServiceTest.php | 36 +++++++++++++ 6 files changed, 161 insertions(+) diff --git a/Classes/Generator/ConfigGenerator.php b/Classes/Generator/ConfigGenerator.php index 306d47d55ff..75fc1ddf55d 100644 --- a/Classes/Generator/ConfigGenerator.php +++ b/Classes/Generator/ConfigGenerator.php @@ -4,9 +4,11 @@ namespace SFC\Staticfilecache\Generator; +use Psr\Http\Message\ServerRequestInterface; use SFC\Staticfilecache\Event\GeneratorConfigManipulationEvent; use SFC\Staticfilecache\Event\GeneratorCreate; use SFC\Staticfilecache\Event\GeneratorRemove; +use SFC\Staticfilecache\Service\CacheHeaderService; use SFC\Staticfilecache\Service\ConfigurationService; use SFC\Staticfilecache\Service\DateTimeService; use TYPO3\CMS\Core\Utility\GeneralUtility; @@ -16,6 +18,7 @@ class ConfigGenerator extends AbstractGenerator public function generate(GeneratorCreate $generatorCreateEvent): void { $time = (new DateTimeService())->getCurrentTime(); + $request = ($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface ? $GLOBALS['TYPO3_REQUEST'] : null; $config = [ 'generated' => date('r', $time), 'generatedTimestamp' => $time, @@ -23,6 +26,9 @@ public function generate(GeneratorCreate $generatorCreateEvent): void 'invalidAtTimestamp' => $time + $generatorCreateEvent->getLifetime(), 'headers' => GeneralUtility::makeInstance(ConfigurationService::class) ->getValidHeaders($generatorCreateEvent->getResponse()->getHeaders(), 'validFallbackHeaders'), + // Evaluated by the fallback middleware on every delivery, so it can + // send the remaining lifetime and decide "auto" per request. + ...GeneralUtility::makeInstance(CacheHeaderService::class)->getTypoScriptConfiguration($request), ]; /** @var GeneratorConfigManipulationEvent $configManipulationEvent */ $configManipulationEvent = $this->eventDispatcher->dispatch(new GeneratorConfigManipulationEvent($config)); diff --git a/Classes/Middleware/FallbackMiddleware.php b/Classes/Middleware/FallbackMiddleware.php index 10273bf8266..4ae71417036 100644 --- a/Classes/Middleware/FallbackMiddleware.php +++ b/Classes/Middleware/FallbackMiddleware.php @@ -12,6 +12,7 @@ use SFC\Staticfilecache\Cache\IdentifierBuilder; use SFC\Staticfilecache\Event\CacheRuleFallbackEvent; use SFC\Staticfilecache\Exception; +use SFC\Staticfilecache\Service\CacheHeaderService; use SFC\Staticfilecache\Service\CacheService; use SFC\Staticfilecache\Service\ConfigurationService; use SFC\Staticfilecache\Service\CookieService; @@ -96,6 +97,20 @@ protected function getHeaders(ServerRequestInterface $request, string &$possible $headers[$header] = $value; } + // Stored headers are frozen when the entry is written; the cache headers + // count down the remaining lifetime, like TYPO3's from its page cache. + if (isset($config['invalidAtTimestamp'])) { + $cacheHeaderService = GeneralUtility::makeInstance(CacheHeaderService::class); + $cacheHeaders = $cacheHeaderService->getHeaders( + (bool) ($config['sendCacheHeaders'] ?? false), + $cacheHeaderService->isForSharedCaches((string) ($config['sendCacheHeadersForSharedCaches'] ?? ''), $request), + (int) $config['invalidAtTimestamp'], + ); + foreach ($cacheHeaders as $header => $value) { + $headers[$header] = $value; + } + } + $debug = $this->configurationService->isBool('debugHeaders'); if ($debug) { $headers['X-SFC-State'] = 'StaticFileCache - via Fallback Middleware'; diff --git a/Classes/Service/CacheHeaderService.php b/Classes/Service/CacheHeaderService.php index 54c0246ed4b..109d04cadf2 100644 --- a/Classes/Service/CacheHeaderService.php +++ b/Classes/Service/CacheHeaderService.php @@ -51,4 +51,23 @@ public function isForSharedCaches(string $sendCacheHeadersForSharedCaches, Serve return $normalizedParams->isBehindReverseProxy(); } + + /** + * Expires and Cache-Control for an entry valid until $expires, counting down + * the remaining lifetime as TYPO3 does when it serves from its page cache. + * + * @return array + */ + public function getHeaders(bool $sendCacheHeaders, bool $forSharedCaches, int $expires): array + { + if (!$forSharedCaches && !$sendCacheHeaders) { + return []; + } + $lifetime = max(0, $expires - (new DateTimeService())->getCurrentTime()); + + return [ + 'Expires' => gmdate('D, d M Y H:i:s T', $expires), + 'Cache-Control' => $forSharedCaches ? 'max-age=0, s-maxage=' . $lifetime : 'max-age=' . $lifetime, + ]; + } } diff --git a/Tests/Unit/Generator/ConfigGeneratorTest.php b/Tests/Unit/Generator/ConfigGeneratorTest.php index 29abd670c0d..839a7916fa5 100644 --- a/Tests/Unit/Generator/ConfigGeneratorTest.php +++ b/Tests/Unit/Generator/ConfigGeneratorTest.php @@ -8,6 +8,9 @@ use SFC\Staticfilecache\Event\GeneratorConfigManipulationEvent; use SFC\Staticfilecache\Generator\ConfigGenerator; use SFC\Staticfilecache\Service\DateTimeService; +use TYPO3\CMS\Core\Http\ServerRequest; +use TYPO3\CMS\Core\TypoScript\AST\Node\RootNode; +use TYPO3\CMS\Core\TypoScript\FrontendTypoScript; /** * ConfigGeneratorTest. @@ -40,6 +43,36 @@ public function testGenerateWriteConfigJson(): void ], $config['headers']); } + public function testGenerateStoreCacheHeaderConfigurationOfThePage(): void + { + $this->setExtensionConfiguration(); + $frontendTypoScript = new FrontendTypoScript(new RootNode(), [], [], []); + $frontendTypoScript->setConfigArray(['sendCacheHeaders' => '1', 'sendCacheHeadersForSharedCaches' => 'auto']); + $GLOBALS['TYPO3_REQUEST'] = (new ServerRequest('https://example.com/'))->withAttribute('frontend.typoscript', $frontendTypoScript); + $fileName = $this->createTemporaryDirectory() . 'index.html'; + + $generator = new ConfigGenerator($this->getEventDispatcher(), $this->getViewFactory()); + $generator->generate($this->getCreateEvent($fileName)); + + $config = json_decode((string) file_get_contents($fileName . '.config.json'), true); + self::assertTrue($config['sendCacheHeaders']); + self::assertSame('auto', $config['sendCacheHeadersForSharedCaches']); + } + + public function testGenerateStoreNoCacheHeaderConfigurationWithoutRequest(): void + { + $this->setExtensionConfiguration(); + unset($GLOBALS['TYPO3_REQUEST']); + $fileName = $this->createTemporaryDirectory() . 'index.html'; + + $generator = new ConfigGenerator($this->getEventDispatcher(), $this->getViewFactory()); + $generator->generate($this->getCreateEvent($fileName)); + + $config = json_decode((string) file_get_contents($fileName . '.config.json'), true); + self::assertFalse($config['sendCacheHeaders']); + self::assertSame('', $config['sendCacheHeadersForSharedCaches']); + } + public function testGenerateUseManipulatedConfig(): void { $this->setExtensionConfiguration(); diff --git a/Tests/Unit/Middleware/FallbackMiddlewareTest.php b/Tests/Unit/Middleware/FallbackMiddlewareTest.php index 1e27b7ffa2c..826febd4bc2 100644 --- a/Tests/Unit/Middleware/FallbackMiddlewareTest.php +++ b/Tests/Unit/Middleware/FallbackMiddlewareTest.php @@ -10,7 +10,9 @@ use SFC\Staticfilecache\Middleware\FallbackMiddleware; use SFC\Staticfilecache\Service\CacheService; use SFC\Staticfilecache\Service\CookieService; +use SFC\Staticfilecache\Service\DateTimeService; use TYPO3\CMS\Core\Http\HtmlResponse; +use TYPO3\CMS\Core\Http\NormalizedParams; use TYPO3\CMS\Core\Http\ServerRequest; /** @@ -90,6 +92,56 @@ public function testDeliverStaticFile(): void self::assertFalse($response->hasHeader('Content-Encoding')); } + public function testNoCacheHeadersWithoutCacheHeaderConfiguration(): void + { + file_put_contents($this->staticFile, 'cached'); + file_put_contents($this->staticFile . '.config.json', json_encode(['invalidAtTimestamp' => time() + 3600])); + + $response = $this->getMiddleware()->process($this->getRequest(), $this->getHandler(new HtmlResponse('typo3'))); + + self::assertFalse($response->hasHeader('Cache-Control')); + self::assertFalse($response->hasHeader('Expires')); + } + + /** + * @return array + */ + public static function cacheHeadersDataProvider(): array + { + return [ + 'sendCacheHeaders' => [true, '', false, 'max-age=%d'], + 'shared caches forced' => [false, 'force', false, 'max-age=0, s-maxage=%d'], + 'shared caches forced with sendCacheHeaders' => [true, 'force', false, 'max-age=0, s-maxage=%d'], + 'shared caches auto behind a trusted reverse proxy' => [true, 'auto', true, 'max-age=0, s-maxage=%d'], + 'shared caches auto without a trusted reverse proxy' => [true, 'auto', false, 'max-age=%d'], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('cacheHeadersDataProvider')] + public function testCacheHeadersCountDownTheRemainingLifetime(bool $sendCacheHeaders, string $sendCacheHeadersForSharedCaches, bool $behindReverseProxy, string $expectedCacheControl): void + { + $invalidAt = time() + 3600; + file_put_contents($this->staticFile, 'cached'); + file_put_contents($this->staticFile . '.config.json', json_encode([ + 'invalidAtTimestamp' => $invalidAt, + // A stored Cache-Control is frozen at generation time and must not win. + 'headers' => ['Cache-Control' => 'max-age=0, s-maxage=86400'], + 'sendCacheHeaders' => $sendCacheHeaders, + 'sendCacheHeadersForSharedCaches' => $sendCacheHeadersForSharedCaches, + ])); + $normalizedParams = NormalizedParams::createFromServerParams( + ['REMOTE_ADDR' => '10.0.0.1', 'HTTP_HOST' => 'example.com'], + ['reverseProxyIP' => $behindReverseProxy ? '10.0.0.1' : ''] + ); + $request = $this->getRequest()->withAttribute('normalizedParams', $normalizedParams); + + $response = $this->getMiddleware()->process($request, $this->getHandler(new HtmlResponse('typo3'))); + + $remaining = $invalidAt - (new DateTimeService())->getCurrentTime(); + self::assertSame(\sprintf($expectedCacheControl, $remaining), $response->getHeaderLine('Cache-Control')); + self::assertSame(gmdate('D, d M Y H:i:s T', $invalidAt), $response->getHeaderLine('Expires')); + } + public function testDebugHeader(): void { $this->setExtensionConfiguration(['useFallbackMiddleware' => '1', 'debugHeaders' => '1']); diff --git a/Tests/Unit/Service/CacheHeaderServiceTest.php b/Tests/Unit/Service/CacheHeaderServiceTest.php index 645b46c0a80..01dec6830a7 100644 --- a/Tests/Unit/Service/CacheHeaderServiceTest.php +++ b/Tests/Unit/Service/CacheHeaderServiceTest.php @@ -5,6 +5,7 @@ namespace SFC\Staticfilecache\Tests\Unit\Service; use SFC\Staticfilecache\Service\CacheHeaderService; +use SFC\Staticfilecache\Service\DateTimeService; use SFC\Staticfilecache\Tests\Unit\AbstractTest; use TYPO3\CMS\Core\Http\NormalizedParams; use TYPO3\CMS\Core\Http\ServerRequest; @@ -82,6 +83,41 @@ public function testIsForSharedCachesCreatesNormalizedParamsWhenMissing(): void } } + public function testNoHeadersWithoutSendCacheHeaders(): void + { + self::assertSame([], (new CacheHeaderService())->getHeaders(false, false, $this->getNow() + 300)); + } + + public function testHeadersForClients(): void + { + $expires = $this->getNow() + 300; + + self::assertSame([ + 'Expires' => gmdate('D, d M Y H:i:s T', $expires), + 'Cache-Control' => 'max-age=300', + ], (new CacheHeaderService())->getHeaders(true, false, $expires)); + } + + public function testHeadersForSharedCachesWithoutSendCacheHeaders(): void + { + $expires = $this->getNow() + 300; + + self::assertSame([ + 'Expires' => gmdate('D, d M Y H:i:s T', $expires), + 'Cache-Control' => 'max-age=0, s-maxage=300', + ], (new CacheHeaderService())->getHeaders(false, true, $expires)); + } + + public function testHeadersOfAnExpiredEntryNeverGoNegative(): void + { + self::assertSame('max-age=0, s-maxage=0', (new CacheHeaderService())->getHeaders(true, true, $this->getNow() - 10)['Cache-Control']); + } + + protected function getNow(): int + { + return (new DateTimeService())->getCurrentTime(); + } + protected function getRequest(bool $behindReverseProxy): ServerRequest { $normalizedParams = NormalizedParams::createFromServerParams(