From 3bfe4939e8a50a6ed456e76f378b8f5e497303e4 Mon Sep 17 00:00:00 2001 From: Lari Taskula Date: Tue, 24 Feb 2026 13:47:15 +0200 Subject: [PATCH] Bug 38365: (follow-up) Only get the nonce in templates if CSP is enabled, add tests To test: 1. prove t/db_dependent/Koha/Template/Plugin/Koha.t --- t/db_dependent/Koha/Template/Plugin/Koha.t | 23 ++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/t/db_dependent/Koha/Template/Plugin/Koha.t b/t/db_dependent/Koha/Template/Plugin/Koha.t index 67c0d986dd0..09bebfa6a5e 100755 --- a/t/db_dependent/Koha/Template/Plugin/Koha.t +++ b/t/db_dependent/Koha/Template/Plugin/Koha.t @@ -29,6 +29,8 @@ use Koha::Cache::Memory::Lite; use Koha::Database; use Koha::Template::Plugin::Koha; +use t::lib::Mocks; + my $schema = Koha::Database->new->schema; my $session_id = 42; @@ -81,7 +83,7 @@ subtest 'GenerateCSRF - New CSRF token generated every time we need one' => sub }; subtest 'CSPNonce' => sub { - plan tests => 1; + plan tests => 3; $schema->storage->txn_begin; @@ -90,12 +92,25 @@ subtest 'CSPNonce' => sub { my $plugin = Koha::Template::Plugin::Koha->new($context); - my $csp = Koha::ContentSecurityPolicy->new; - my $nonce = $csp->get_nonce; + C4::Context->interface('opac'); + t::lib::Mocks::mock_config( + 'content_security_policy', + { 'opac' => { csp_mode => 'enabled', csp_header_value => 'test' } } + ); - my $token = $plugin->CSPNonce; + my $csp = Koha::ContentSecurityPolicy->new; + $csp->set_nonce(); + my $nonce = $csp->get_nonce; is( $plugin->CSPNonce, $nonce, 'the correct nonce was provided' ); + like( $nonce, qr/^\w{22}$/, 'nonce is a random string of 22 characters' ); + + t::lib::Mocks::mock_config( + 'content_security_policy', + { 'opac' => { csp_mode => 'disabled', csp_header_value => 'test' } } + ); + + is( $plugin->CSPNonce, undef, 'no nonce was provided because CSP is dsabled' ); $schema->storage->txn_rollback; -- 2.34.1