From 35e57bce788b204c139d34761e5b6aae271d705b Mon Sep 17 00:00:00 2001 From: Duncan McClean Date: Fri, 18 Oct 2024 18:43:09 +0100 Subject: [PATCH] [5.x] Prevent protected pages being cached (#10929) Co-authored-by: Jason Varga --- src/Http/Responses/DataResponse.php | 10 +++++++--- src/StaticCaching/Middleware/Cache.php | 8 ++++++-- tests/FrontendTest.php | 19 +++++++++++++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/Http/Responses/DataResponse.php b/src/Http/Responses/DataResponse.php index ccc921e66c..baca6e7896 100644 --- a/src/Http/Responses/DataResponse.php +++ b/src/Http/Responses/DataResponse.php @@ -91,9 +91,13 @@ protected function getRedirect() protected function protect() { - app(Protection::class) - ->setData($this->data) - ->protect(); + $protection = app(Protection::class)->setData($this->data); + + $protection->protect(); + + if ($protection->scheme()) { + $this->headers['X-Statamic-Protected'] = true; + } return $this; } diff --git a/src/StaticCaching/Middleware/Cache.php b/src/StaticCaching/Middleware/Cache.php index 77ed71fe5d..80f86e5ce1 100644 --- a/src/StaticCaching/Middleware/Cache.php +++ b/src/StaticCaching/Middleware/Cache.php @@ -179,8 +179,12 @@ private function shouldBeCached($request, $response) return false; } - // Draft and private pages should not be cached. - if ($response->headers->has('X-Statamic-Draft') || $response->headers->has('X-Statamic-Private')) { + // Draft, private and protected pages should not be cached. + if ( + $response->headers->has('X-Statamic-Draft') + || $response->headers->has('X-Statamic-Private') + || $response->headers->has('X-Statamic-Protected') + ) { return false; } diff --git a/tests/FrontendTest.php b/tests/FrontendTest.php index 68a5295d87..418fa02a94 100644 --- a/tests/FrontendTest.php +++ b/tests/FrontendTest.php @@ -354,6 +354,25 @@ public function past_private_entries_dont_get_statically_cached() $this->markTestIncomplete(); } + #[Test] + public function header_is_added_to_protected_responses() + { + $page = $this->createPage('about'); + + $this + ->get('/about') + ->assertOk() + ->assertHeaderMissing('X-Statamic-Protected'); + + $page->set('protect', 'logged_in')->save(); + + $this + ->actingAs(User::make()) + ->get('/about') + ->assertOk() + ->assertHeader('X-Statamic-Protected', true); + } + #[Test] public function key_variables_key_added() {