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
6 changes: 6 additions & 0 deletions Classes/Generator/ConfigGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -16,13 +18,17 @@ 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,
'invalidAt' => date('r', $time + $generatorCreateEvent->getLifetime()),
'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));
Expand Down
15 changes: 11 additions & 4 deletions Classes/Generator/HtaccessGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -32,16 +33,22 @@ 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);
$cacheHeaderService = GeneralUtility::makeInstance(CacheHeaderService::class);
$request = ($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface ? $GLOBALS['TYPO3_REQUEST'] : null;
$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,
'mode' => $accessTimeout ? 'A' : 'M',
'lifetime' => $lifetime,
'TIME' => '{TIME}',
'expires' => (new DateTimeService())->getCurrentTime() + $lifetime,
'sendCacheControlHeader' => $sendCacheControlHeader,
'sendCacheControlHeader' => $typoScriptConfiguration['sendCacheHeaders'],
'sendCacheControlHeaderForSharedCaches' => $sendCacheControlHeaderForSharedCaches,
'sendCacheControlHeaderRedirectAfterCacheTimeout' => $configuration->isBool('sendCacheControlHeaderRedirectAfterCacheTimeout'),
'headers' => $this->cleanupHeaderValues($headers),
];
Expand Down
15 changes: 15 additions & 0 deletions Classes/Middleware/FallbackMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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';
Expand Down
73 changes: 73 additions & 0 deletions Classes/Service/CacheHeaderService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

declare(strict_types=1);

namespace SFC\Staticfilecache\Service;

use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Http\NormalizedParams;
use TYPO3\CMS\Core\TypoScript\FrontendTypoScript;

/**
* Cache headers of statically served entries, decided the way TYPO3 decides
* them for its own responses via config.sendCacheHeaders and
* config.sendCacheHeadersForSharedCaches.
*/
class CacheHeaderService
{
/**
* The cache header configuration of the page the request rendered.
*
* @return array{sendCacheHeaders: bool, sendCacheHeadersForSharedCaches: string}
*/
public function getTypoScriptConfiguration(?ServerRequestInterface $request): array
{
$frontendTypoScript = $request?->getAttribute('frontend.typoscript');
$configArray = $frontendTypoScript instanceof FrontendTypoScript ? $frontendTypoScript->getConfigArray() : [];

return [
'sendCacheHeaders' => (bool) ($configArray['sendCacheHeaders'] ?? false),
'sendCacheHeadersForSharedCaches' => (string) ($configArray['sendCacheHeadersForSharedCaches'] ?? ''),
];
}

/**
* Whether TYPO3 sends the shared-cache variant (max-age=0, s-maxage=<lifetime>):
* 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();
}

/**
* 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<string, string>
*/
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,
];
}
}
13 changes: 12 additions & 1 deletion Resources/Private/Templates/Htaccess.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,23 @@
{namespace sfc=SFC\Staticfilecache\ViewHelpers}
ForceType {contentType}
<sfc:format.stripEmptyVerticalSpaces>
<f:if condition="{sendCacheControlHeader}">
<f:if condition="{sendCacheControlHeader} || {sendCacheControlHeaderForSharedCaches}">
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType {contentType} {mode}{lifetime}
</IfModule>
</f:if>
<f:if condition="{sendCacheControlHeaderForSharedCaches}">
<f:comment><!--
Like TYPO3 with config.sendCacheHeadersForSharedCaches: browsers get
max-age=0, shared caches the lifetime as s-maxage. With mode M
(htaccessTimeout = 0) mod_expires sends the remaining lifetime of the entry,
so a shared cache keeps its copy no longer than the entry exists.
--></f:comment>
<IfModule mod_headers.c>
Header edit Cache-Control "^max-age=(\d+)$" "max-age=0, s-maxage=$1"
</IfModule>
</f:if>

<f:if condition="{sendCacheControlHeaderRedirectAfterCacheTimeout}">
<IfModule mod_rewrite.c>
Expand Down
33 changes: 33 additions & 0 deletions Tests/Unit/Generator/ConfigGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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();
Expand Down
36 changes: 36 additions & 0 deletions Tests/Unit/Generator/HtaccessGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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\"',
Expand Down Expand Up @@ -117,6 +119,40 @@ public function testGenerateReadSendCacheHeadersFromFrontendTypoScript(array $co
self::assertSame($expected, $this->assignedVariables['sendCacheControlHeader']);
}

/**
* @return array<string, array{string, bool, bool}>
*/
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']);
Expand Down
52 changes: 52 additions & 0 deletions Tests/Unit/Middleware/FallbackMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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<string, array{bool, string, bool, string}>
*/
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']);
Expand Down
Loading
Loading