Skip to content

Commit

Permalink
fix: [API] Cleanup compression marks added by Apache from Etag
Browse files Browse the repository at this point in the history
  • Loading branch information
JakubOnderka committed Mar 23, 2024
1 parent 317fd05 commit 0763b82
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions app/Controller/Component/RestResponseComponent.php
Expand Up @@ -671,9 +671,10 @@ private function prepareResponse($response, $code, $format = false, $raw = false
}

if ($response instanceof TmpFileTool) {
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$requestEtag = $this->requestEtag();
if ($requestEtag !== null) {
$etag = '"' . $response->hash('sha1') . '"';
if ($_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
if ($requestEtag === $etag) {
return new CakeResponse(['status' => 304]);
}
$headers['ETag'] = $etag;
Expand All @@ -689,9 +690,10 @@ private function prepareResponse($response, $code, $format = false, $raw = false
}
} else {
// Check if resource was changed when `If-None-Match` header is send and return 304 Not Modified
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$requestEtag = $this->requestEtag();
if ($requestEtag !== null) {
$etag = '"' . sha1($response) . '"';
if ($_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
if ($requestEtag === $etag) {
return new CakeResponse(['status' => 304]);
}
// Generate etag just when HTTP_IF_NONE_MATCH is set
Expand Down Expand Up @@ -724,6 +726,25 @@ private function prepareResponse($response, $code, $format = false, $raw = false
return $cakeResponse;
}

/**
* Return etag from If-None-Match HTTP request header without compression marks added by Apache
* @return string|null
*/
private function requestEtag()
{
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
// Remove compression marks that adds Apache for compressed content
$requestEtag = $_SERVER['HTTP_IF_NONE_MATCH'];
$etagWithoutQuotes = trim($requestEtag, '"');
$dashPos = strrpos($etagWithoutQuotes, '-');
if ($dashPos && in_array(substr($etagWithoutQuotes, $dashPos + 1), ['br', 'gzip'], true)) {
return '"' . substr($etagWithoutQuotes, 0, $dashPos) . '"';
}
return $requestEtag;
}
return null;
}

/**
* @param string $response
* @return string Signature as base64 encoded string
Expand Down

0 comments on commit 0763b82

Please sign in to comment.