Skip to content

FOUR-20933: Implement ETag Caching for Screens Data #7771

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 2, 2024
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
3 changes: 2 additions & 1 deletion ProcessMaker/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class Kernel extends HttpKernel
\Illuminate\Routing\Middleware\SubstituteBindings::class,
Middleware\GenerateMenus::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
\ProcessMaker\Http\Middleware\IgnoreMapFiles::class,
Middleware\IgnoreMapFiles::class,
],
'api' => [
// API Middleware is defined with routeMiddleware below.
Expand Down Expand Up @@ -83,6 +83,7 @@ class Kernel extends HttpKernel
'session_kill' => Middleware\SessionControlKill::class,
'no-cache' => Middleware\NoCache::class,
'admin' => Middleware\IsAdmin::class,
'etag' => Middleware\Etag\HandleEtag::class,
];

/**
Expand Down
59 changes: 59 additions & 0 deletions ProcessMaker/Http/Middleware/Etag/HandleEtag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace ProcessMaker\Http\Middleware\Etag;

use Closure;
use Illuminate\Http\Request;
use ProcessMaker\Http\Resources\Caching\EtagManager;
use Symfony\Component\HttpFoundation\Response;

class HandleEtag
{
public string $middleware = 'etag';

/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next, ?string $scope = null): Response
{
// Save original method and support HEAD requests.
$originalMethod = $request->getMethod();
if ($request->isMethod('HEAD')) {
$request->setMethod('GET');
}

// Handle response.
$response = $next($request);

// Determine if the ETag should include user-specific data.
$includeUser = $scope === 'user';

// Generate ETag for the response.
$etag = EtagManager::getEtag($request, $response, $includeUser);
if ($etag) {
// Set the ETag header.
$response->setEtag($etag);

// Get and strip weak ETags from request headers.
$noneMatch = array_map([$this, 'stripWeakTags'], $request->getETags());

// Compare ETags and set response as not modified if applicable.
if (in_array($etag, $noneMatch)) {
$response->setNotModified();
}
}

// Restore original method and return the response.
$request->setMethod($originalMethod);

return $response;
}

/**
* Remove the weak indicator (W/) from an ETag.
*/
private function stripWeakTags(string $etag): string
{
return str_replace('W/', '', $etag);
}
}
48 changes: 48 additions & 0 deletions ProcessMaker/Http/Resources/Caching/EtagManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace ProcessMaker\Http\Resources\Caching;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class EtagManager
{
/**
* The callback used to generate the ETag.
*/
protected static ?Closure $etagGenerateCallback = null;

/**
* Set a callback that should be used when generating the ETag.
*/
public static function etagGenerateUsing(?Closure $callback): void
{
static::$etagGenerateCallback = $callback;
}

/**
* Get ETag value for this request and response.
*/
public static function getEtag(Request $request, Response $response, bool $includeUser = false): string
{
$etag = static::$etagGenerateCallback
? call_user_func(static::$etagGenerateCallback, $request, $response, $includeUser)
: static::defaultGetEtag($response, $includeUser);

return (string) Str::of($etag)->start('"')->finish('"');
}

/**
* Generate an ETag, optionally including user-specific data.
*/
private static function defaultGetEtag(Response $response, bool $includeUser = false): string
{
if ($includeUser) {
return md5(auth()->id() . $response->getContent());
}

return md5($response->getContent());
}
}
1 change: 1 addition & 0 deletions routes/v1_1/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

// Route to show the screen of a task
Route::get('/{taskId}/screen', [TaskController::class, 'showScreen'])
->middleware('etag')
->name('show.screen');

// Route to show the interstitial screen of a task
Expand Down
51 changes: 51 additions & 0 deletions tests/Feature/Etag/EtagManagerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace ProcessMaker\Tests\Feature\Etag;

use Illuminate\Http\Request;
use ProcessMaker\Http\Resources\Caching\EtagManager;
use Symfony\Component\HttpFoundation\Response;
use Tests\TestCase;

class EtagManagerTest extends TestCase
{
private string $response = 'OK';

public function tearDown(): void
{
EtagManager::etagGenerateUsing(null);
}

public function testGetDefaultEtag()
{
$request = Request::create('/', 'GET');
$response = response($this->response, 200);

$this->assertEquals('"e0aa021e21dddbd6d8cecec71e9cf564"', EtagManager::getEtag($request, $response));
}

public function testGetEtagWithCallbackMd5()
{
$request = Request::create('/', 'GET');
$response = response($this->response, 200);

EtagManager::etagGenerateUsing(function (Request $request, Response $response) {
return md5($response->getContent());
});

$this->assertEquals('"e0aa021e21dddbd6d8cecec71e9cf564"', EtagManager::getEtag($request, $response));
}

public function testGetEtagWithCallbackSha256()
{
$request = Request::create('/', 'GET');
$response = response($this->response, 200);

EtagManager::etagGenerateUsing(function (Request $request, Response $response) {
return hash('sha256', $response->getContent());
});

$expectedHash = hash('sha256', $this->response);
$this->assertEquals("\"$expectedHash\"", EtagManager::getEtag($request, $response));
}
}
87 changes: 87 additions & 0 deletions tests/Feature/Etag/HandleEtagTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

namespace ProcessMaker\Tests\Feature\Etag;

use Illuminate\Support\Facades\Route;
use ProcessMaker\Http\Middleware\Etag\HandleEtag;
use ProcessMaker\Http\Resources\Caching\EtagManager;
use ProcessMaker\Models\User;
use Tests\TestCase;

class HandleEtagTest extends TestCase
{
private string $response = 'OK';

private const TEST_ROUTE = '/_test/handle-etag';

public function setUp(): void
{
parent::setUp();

// Define a route that uses the HandleEtag middleware.
Route::middleware(HandleEtag::class)->any(self::TEST_ROUTE, function () {
return response($this->response, 200);
});
}

public function testMiddlewareSetsEtagHeader()
{
$response = $this->get(self::TEST_ROUTE);
$response->assertHeader('ETag');
}

public function testEtagHeaderHasCorrectValue()
{
$expectedEtag = '"' . md5($this->response) . '"';
$response = $this->get(self::TEST_ROUTE);
$response->assertHeader('ETag', $expectedEtag);
}

public function testRequestReturns200WhenIfNoneMatchDoesNotMatch()
{
$noneMatch = '"' . md5($this->response . 'NoneMatch') . '"';
$response = $this
->withHeaders(['If-None-Match' => $noneMatch])
->get(self::TEST_ROUTE);

$response->assertStatus(200);
$response->assertHeader('ETag');
}

public function testRequestReturns304WhenIfNoneMatchMatches()
{
$matchingEtag = '"' . md5($this->response) . '"';
$response = $this
->withHeaders(['If-None-Match' => $matchingEtag])
->get(self::TEST_ROUTE);

$response->assertStatus(304);
$response->assertHeader('ETag', $matchingEtag);
}

public function testRequestIgnoresWeakEtagsInIfNoneMatch()
{
$weakEtag = 'W/"' . md5($this->response) . '"';
$response = $this
->withHeaders(['If-None-Match' => $weakEtag])
->get(self::TEST_ROUTE);

$response->assertStatus(304);
$response->assertHeader('ETag', '"' . md5($this->response) . '"');
}

public function testDefaultGetEtagGeneratesCorrectEtagWithUser()
{
$user = User::factory()->create();
$this->actingAs($user);

Route::middleware('etag:user')->any(self::TEST_ROUTE, function () {
return response($this->response, 200);
});

$response = $this->get(self::TEST_ROUTE);

$expectedEtag = '"' . md5($user->id . $this->response) . '"';
$response->assertHeader('ETag', $expectedEtag);
}
}
Loading