Skip to content

Commit e8d6823

Browse files
test: add CSP nonce handling tests and refactor BrowserLogger attributes handling
Co-authored-by: Joost de Bruijn <[email protected]> Signed-off-by: Pushpak Chhajed <[email protected]>
1 parent 360779a commit e8d6823

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

src/Services/BrowserLogger.php

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Illuminate\Support\Facades\Route;
88
use Illuminate\Support\Facades\Vite;
9+
use Illuminate\View\ComponentAttributeBag;
910

1011
class BrowserLogger
1112
{
@@ -15,18 +16,16 @@ public static function getScript(): string
1516
? route('boost.browser-logs')
1617
: '/_boost/browser-logs';
1718

18-
$attributes = ['id' => 'browser-logger-active'];
19+
$attributes = new ComponentAttributeBag([
20+
'id' => 'browser-logger-active',
21+
]);
1922

2023
if ($nonce = Vite::cspNonce()) {
21-
$attributes['nonce'] = $nonce;
24+
$attributes = $attributes->merge(['nonce' => $nonce]);
2225
}
2326

24-
$scriptAttributes = collect($attributes)
25-
->map(fn ($value, $key) => sprintf('%s="%s"', $key, $value))
26-
->implode(' ');
27-
2827
return <<<HTML
29-
<script {$scriptAttributes}>
28+
<script {$attributes->toHtml()}>
3029
(function() {
3130
const ENDPOINT = '{$endpoint}';
3231
const logQueue = [];

tests/Feature/Middleware/InjectBoostTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Illuminate\Http\Request;
66
use Illuminate\Http\Response;
77
use Illuminate\Support\Facades\Route;
8+
use Illuminate\Support\Facades\Vite;
89
use Laravel\Boost\Middleware\InjectBoost;
910
use Symfony\Component\HttpFoundation\BinaryFileResponse;
1011
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -89,3 +90,30 @@ function createMiddlewareResponse($response): SymfonyResponse
8990
'with head and body tags' => '<html><head><title>Test</title></head><body></body></html>',
9091
'without head/body tags' => '<html>Test</html>',
9192
]);
93+
94+
it('handles CSP nonce attribute correctly', function ($nonce, $assertions) {
95+
if ($nonce) {
96+
Vite::useCspNonce($nonce);
97+
}
98+
99+
Route::get('injection-test', fn () => view('test::injection-test'))
100+
->middleware(InjectBoost::class);
101+
102+
$response = $this->get('injection-test')->assertViewIs('test::injection-test');
103+
104+
$assertions($response);
105+
})->with([
106+
'with CSP nonce configured' => [
107+
'test-nonce',
108+
fn ($response) => $response
109+
->assertSee('nonce="test-nonce"', false)
110+
->assertSee('id="browser-logger-active"', false),
111+
],
112+
'without CSP nonce configured' => [
113+
null,
114+
fn ($response) => $response
115+
->assertSee('<script id="browser-logger-active">', false)
116+
->assertDontSee('nonce=', false)
117+
->assertDontSee('test-nonce', false),
118+
],
119+
]);

0 commit comments

Comments
 (0)