From 378bd5684f6b030fe425bc14b572de4f072f4416 Mon Sep 17 00:00:00 2001 From: Jesper Noordsij <45041769+jnoordsij@users.noreply.github.com> Date: Mon, 11 Nov 2024 21:17:14 +0100 Subject: [PATCH] Prevent overwriting Link headers in AddLinkHeadersForPreloadedAssets middleware (#53463) --- .../AddLinkHeadersForPreloadedAssets.php | 2 +- tests/Http/Middleware/VitePreloadingTest.php | 29 ++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php b/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php index 36ffb7b3e480..4ef1eb7ea466 100644 --- a/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php +++ b/src/Illuminate/Http/Middleware/AddLinkHeadersForPreloadedAssets.php @@ -21,7 +21,7 @@ public function handle($request, $next) if ($response instanceof Response && Vite::preloadedAssets() !== []) { $response->header('Link', Collection::make(Vite::preloadedAssets()) ->map(fn ($attributes, $url) => "<{$url}>; ".implode('; ', $attributes)) - ->join(', ')); + ->join(', '), false); } }); } diff --git a/tests/Http/Middleware/VitePreloadingTest.php b/tests/Http/Middleware/VitePreloadingTest.php index 63b64b99519e..4fb11f8b0b37 100644 --- a/tests/Http/Middleware/VitePreloadingTest.php +++ b/tests/Http/Middleware/VitePreloadingTest.php @@ -54,8 +54,8 @@ public function testItAddsPreloadLinkHeader() }); $this->assertSame( + '; rel="modulepreload"; foo="bar"', $response->headers->get('Link'), - '; rel="modulepreload"; foo="bar"' ); } @@ -79,4 +79,31 @@ public function testItDoesNotAttachHeadersToNonIlluminateResponses() $this->assertNull($response->headers->get('Link')); } + + public function testItDoesNotOverwriteOtherLinkHeaders() + { + $app = new Container; + $app->instance(Vite::class, new class extends Vite + { + protected $preloadedAssets = [ + 'https://laravel.com/app.js' => [ + 'rel="modulepreload"', + 'foo="bar"', + ], + ]; + }); + Facade::setFacadeApplication($app); + + $response = (new AddLinkHeadersForPreloadedAssets)->handle(new Request, function () { + return new Response('Hello Laravel', headers: ['Link' => '; rel="preload"; as="image"']); + }); + + $this->assertSame( + [ + '; rel="preload"; as="image"', + '; rel="modulepreload"; foo="bar"', + ], + $response->headers->all('Link'), + ); + } }