From 6261c94fc98e2e48f8a6145a733d39b116c58739 Mon Sep 17 00:00:00 2001 From: El RIDO Date: Tue, 9 Jul 2024 22:20:08 +0200 Subject: [PATCH] break unit tests if mismatch between JS files and SRI configuration array is detected --- tst/Bootstrap.php | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/tst/Bootstrap.php b/tst/Bootstrap.php index 59fb4060..bee35847 100644 --- a/tst/Bootstrap.php +++ b/tst/Bootstrap.php @@ -1,5 +1,7 @@ read())) { - if (substr($file, -3) === '.js') { - self::$hashes[$file] = base64_encode( - hash('sha512', file_get_contents( - PATH . 'js' . DIRECTORY_SEPARATOR . $file - ), true) - ); + foreach (new GlobIterator(PATH . 'js' . DIRECTORY_SEPARATOR . '*.js') as $file) { + if ($file->getBasename() == 'common.js') { + continue; // ignore JS unit test bootstrap } + self::$hashes[$file->getBasename()] = base64_encode( + hash('sha512', file_get_contents($file->getPathname()), true) + ); } + $counter = 0; $file = PATH . 'lib' . DIRECTORY_SEPARATOR . 'Configuration.php'; $content = preg_replace_callback( '#\'js/([a-z0-9.-]+.js)(\' +)=\> \'[^\']*\',#', - function ($matches) { + function ($matches) use (&$counter) { if (array_key_exists($matches[1], Helper::$hashes)) { + $counter++; return '\'js/' . $matches[1] . $matches[2] . '=> \'sha512-' . Helper::$hashes[$matches[1]] . '\','; } else { - return $matches[0]; + throw new Exception('SRI hash for file js/' . $matches[1] . ' not found, please add the missing file or remove it from lib/Configuration.php.'); } }, file_get_contents($file) ); file_put_contents($file, $content); + if ($counter != count(self::$hashes)) { + throw new Exception('Mismatch between ' . count(self::$hashes) . ' found js files and ' . $counter . ' SRI hashes in lib/Configuration.php, please update lib/Configuration.php to match the list of js files.'); + } } }