break unit tests if mismatch between JS files and SRI configuration array is detected

This commit is contained in:
El RIDO 2024-07-09 22:20:08 +02:00
parent 118c919663
commit 6261c94fc9
No known key found for this signature in database
GPG Key ID: 0F5C940A6BD81F92

View File

@ -1,5 +1,7 @@
<?php declare(strict_types=1); <?php declare(strict_types=1);
use Exception;
use GlobIterator;
use Google\Cloud\Core\Exception\BadRequestException; use Google\Cloud\Core\Exception\BadRequestException;
use Google\Cloud\Core\Exception\NotFoundException; use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\Storage\Bucket; use Google\Cloud\Storage\Bucket;
@ -371,31 +373,34 @@ class Helper
*/ */
public static function updateSubresourceIntegrity() public static function updateSubresourceIntegrity()
{ {
$dir = dir(PATH . 'js'); foreach (new GlobIterator(PATH . 'js' . DIRECTORY_SEPARATOR . '*.js') as $file) {
while (false !== ($file = $dir->read())) { if ($file->getBasename() == 'common.js') {
if (substr($file, -3) === '.js') { continue; // ignore JS unit test bootstrap
self::$hashes[$file] = base64_encode( }
hash('sha512', file_get_contents( self::$hashes[$file->getBasename()] = base64_encode(
PATH . 'js' . DIRECTORY_SEPARATOR . $file hash('sha512', file_get_contents($file->getPathname()), true)
), true)
); );
} }
}
$counter = 0;
$file = PATH . 'lib' . DIRECTORY_SEPARATOR . 'Configuration.php'; $file = PATH . 'lib' . DIRECTORY_SEPARATOR . 'Configuration.php';
$content = preg_replace_callback( $content = preg_replace_callback(
'#\'js/([a-z0-9.-]+.js)(\' +)=\> \'[^\']*\',#', '#\'js/([a-z0-9.-]+.js)(\' +)=\> \'[^\']*\',#',
function ($matches) { function ($matches) use (&$counter) {
if (array_key_exists($matches[1], Helper::$hashes)) { if (array_key_exists($matches[1], Helper::$hashes)) {
$counter++;
return '\'js/' . $matches[1] . $matches[2] . return '\'js/' . $matches[1] . $matches[2] .
'=> \'sha512-' . Helper::$hashes[$matches[1]] . '\','; '=> \'sha512-' . Helper::$hashes[$matches[1]] . '\',';
} else { } 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_get_contents($file)
); );
file_put_contents($file, $content); 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.');
}
} }
} }