1
0
Fork 0

Clean up md5/sha1 usages, upgrade algos where possible (#12088)

* Clean up md5/sha1 usages, upgrade algos where possible

* Fully qualify PHP_VERSION_ID constant usages

* Fix 7.2 build
pull/12091/head
Jordi Boggiano 2024-08-21 17:06:42 +02:00 committed by GitHub
parent 556ca06906
commit 8f3fed674b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
33 changed files with 64 additions and 58 deletions

View File

@ -65,6 +65,16 @@ parameters:
count: 1
path: ../src/Composer/Console/Input/InputOption.php
-
message: "#^Casting to string something that's already string\\.$#"
count: 1
path: ../src/Composer/DependencyResolver/GenericRule.php
-
message: "#^Casting to string something that's already string\\.$#"
count: 1
path: ../src/Composer/DependencyResolver/MultiConflictRule.php
-
message: "#^Parameter \\#2 \\$callback of function uksort expects callable\\(string, string\\)\\: int, 'version_compare' given\\.$#"
count: 2
@ -260,6 +270,11 @@ parameters:
count: 2
path: ../tests/Composer/Test/ConfigTest.php
-
message: "#^Casting to string something that's already string\\.$#"
count: 1
path: ../tests/Composer/Test/DependencyResolver/RuleTest.php
-
message: "#^Call to function method_exists\\(\\) with Composer\\\\Console\\\\Application and 'setCatchErrors' will always evaluate to true\\.$#"
count: 1

View File

@ -85,11 +85,6 @@ parameters:
count: 1
path: ../src/Composer/Autoload/AutoloadGenerator.php
-
message: "#^Parameter \\#2 \\$subject of static method Composer\\\\Pcre\\\\Preg\\:\\:isMatch\\(\\) expects string, string\\|false given\\.$#"
count: 1
path: ../src/Composer/Autoload/AutoloadGenerator.php
-
message: "#^Parameter \\#2 \\$to of method Composer\\\\Util\\\\Filesystem\\:\\:findShortestPathCode\\(\\) expects string, string\\|false given\\.$#"
count: 1
@ -1052,7 +1047,7 @@ parameters:
-
message: "#^Only booleans are allowed in \\|\\|, string\\|false given on the left side\\.$#"
count: 2
count: 1
path: ../src/Composer/Console/Application.php
-
@ -4193,11 +4188,6 @@ parameters:
count: 1
path: ../src/Composer/Util/Perforce.php
-
message: "#^Only booleans are allowed in a negated boolean, string\\|false given\\.$#"
count: 1
path: ../src/Composer/Util/Platform.php
-
message: "#^Method Composer\\\\Util\\\\ProcessExecutor\\:\\:doExecute\\(\\) should return int but returns int\\|null\\.$#"
count: 1

View File

@ -417,7 +417,7 @@ EOF;
}
if (null === $suffix) {
$suffix = $locker !== null && $locker->isLocked() ? $locker->getLockData()['content-hash'] : md5(uniqid('', true));
$suffix = $locker !== null && $locker->isLocked() ? $locker->getLockData()['content-hash'] : bin2hex(random_bytes(16));
}
}
@ -1052,7 +1052,7 @@ CLASSMAPAUTHORITATIVE;
}
if ($this->apcu) {
$apcuPrefix = var_export(($this->apcuPrefix !== null ? $this->apcuPrefix : substr(base64_encode(md5(uniqid('', true), true)), 0, -3)), true);
$apcuPrefix = var_export(($this->apcuPrefix !== null ? $this->apcuPrefix : bin2hex(random_bytes(10))), true);
$file .= <<<APCU
\$loader->setApcuPrefix($apcuPrefix);
@ -1312,7 +1312,8 @@ INITIALIZER;
*/
protected function getFileIdentifier(PackageInterface $package, string $path)
{
return md5($package->getName() . ':' . $path);
// TODO composer v3 change this to sha1 or xxh3? Possibly not worth the potential breakage though
return hash('md5', $package->getName() . ':' . $path);
}
/**

View File

@ -144,7 +144,7 @@ class Cache
$this->io->writeError('Writing '.$this->root . $file.' into cache', true, IOInterface::DEBUG);
$tempFileName = $this->root . $file . uniqid('.', true) . '.tmp';
$tempFileName = $this->root . $file . bin2hex(random_bytes(5)) . '.tmp';
try {
return file_put_contents($tempFileName, $contents) !== false && rename($tempFileName, $this->root . $file);
} catch (\ErrorException $e) {
@ -357,7 +357,7 @@ class Cache
if ($this->isEnabled()) {
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file)) {
return sha1_file($this->root . $file);
return hash_file('sha1', $this->root . $file);
}
}

View File

@ -630,7 +630,7 @@ EOT
$errors['ioncube'] = ioncube_loader_version();
}
if (PHP_VERSION_ID < 70205) {
if (\PHP_VERSION_ID < 70205) {
$errors['php'] = PHP_VERSION;
}

View File

@ -328,7 +328,7 @@ TAGSPUBKEY
$verified = 1 === openssl_verify((string) file_get_contents($tempFilename), $signatureSha384, $pubkeyid, $algo);
// PHP 8 automatically frees the key instance and deprecates the function
if (PHP_VERSION_ID < 80000) {
if (\PHP_VERSION_ID < 80000) {
// @phpstan-ignore function.deprecated
openssl_free_key($pubkeyid);
}

View File

@ -321,7 +321,7 @@ class Application extends BaseApplication
function_exists('php_uname') ? php_uname('s') . ' / ' . php_uname('r') : 'Unknown OS'
), true, IOInterface::DEBUG);
if (PHP_VERSION_ID < 70205) {
if (\PHP_VERSION_ID < 70205) {
$io->writeError('<warning>Composer supports PHP 7.2.5 and above, you will most likely encounter problems with your PHP '.PHP_VERSION.'. Upgrading is strongly recommended but you can use Composer 2.2.x LTS as a fallback.</warning>');
}
@ -348,7 +348,7 @@ class Application extends BaseApplication
// Check system temp folder for usability as it can cause weird runtime issues otherwise
Silencer::call(static function () use ($io): void {
$pid = function_exists('getmypid') ? getmypid() . '-' : '';
$tempfile = sys_get_temp_dir() . '/temp-' . $pid . md5(microtime());
$tempfile = sys_get_temp_dir() . '/temp-' . $pid . bin2hex(random_bytes(5));
if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) === __FILE__) && unlink($tempfile) && !file_exists($tempfile))) {
$io->writeError(sprintf('<error>PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini</error>', sys_get_temp_dir()));
}

View File

@ -46,7 +46,7 @@ class GenericRule extends Rule
*/
public function getHash()
{
$data = unpack('ihash', md5(implode(',', $this->literals), true));
$data = unpack('ihash', (string) hash(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', implode(',', $this->literals), true));
return $data['hash'];
}

View File

@ -52,7 +52,7 @@ class MultiConflictRule extends Rule
*/
public function getHash()
{
$data = unpack('ihash', md5('c:'.implode(',', $this->literals), true));
$data = unpack('ihash', (string) hash(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', 'c:'.implode(',', $this->literals), true));
return $data['hash'];
}

View File

@ -68,7 +68,7 @@ abstract class ArchiveDownloader extends FileDownloader
}
do {
$temporaryDir = $vendorDir.'/composer/'.substr(md5(uniqid('', true)), 0, 8);
$temporaryDir = $vendorDir.'/composer/'.bin2hex(random_bytes(4));
} while (is_dir($temporaryDir));
$this->addCleanupPath($package, $temporaryDir);

View File

@ -126,7 +126,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
}
$cacheKeyGenerator = static function (PackageInterface $package, $key): string {
$cacheKey = sha1($key);
$cacheKey = hash('sha1', $key);
return $package->getName().'/'.$cacheKey.'.'.$package->getDistType();
};
@ -441,7 +441,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
$extension = $package->getDistType();
}
return rtrim($this->config->get('vendor-dir') . '/composer/tmp-' . md5($package . spl_object_hash($package)) . '.' . $extension, '.');
return rtrim($this->config->get('vendor-dir') . '/composer/tmp-' . hash('md5', $package . spl_object_hash($package)) . '.' . $extension, '.');
}
/**

View File

@ -299,7 +299,7 @@ class EventDispatcher
// it does not hurt to keep the same stream as the current Application
if ($this->io instanceof ConsoleIO) {
$reflProp = new \ReflectionProperty($this->io, 'output');
if (PHP_VERSION_ID < 80100) {
if (\PHP_VERSION_ID < 80100) {
$reflProp->setAccessible(true);
}
$output = $reflProp->getValue($this->io);

View File

@ -96,7 +96,7 @@ class ArchiveManager
$sourceReference = $package->getSourceReference();
if (null !== $sourceReference) {
$parts['source_reference'] = substr(sha1($sourceReference), 0, 6);
$parts['source_reference'] = substr(hash('sha1', $sourceReference), 0, 6);
}
$parts = array_filter($parts, function (?string $part) {
@ -171,7 +171,7 @@ class ArchiveManager
$sourcePath = realpath('.');
} else {
// Directory used to download the sources
$sourcePath = sys_get_temp_dir().'/composer_archive'.uniqid();
$sourcePath = sys_get_temp_dir().'/composer_archive'.bin2hex(random_bytes(5));
$filesystem->ensureDirectoryExists($sourcePath);
try {
@ -216,7 +216,7 @@ class ArchiveManager
}
// Create the archive
$tempTarget = sys_get_temp_dir().'/composer_archive'.uniqid().'.'.$format;
$tempTarget = sys_get_temp_dir().'/composer_archive'.bin2hex(random_bytes(5)).'.'.$format;
$filesystem->ensureDirectoryExists(dirname($tempTarget));
$archivePath = $usableArchiver->archive(

View File

@ -136,7 +136,7 @@ class Comparer
return false;
}
} elseif (is_file($dir.'/'.$file) && filesize($dir.'/'.$file)) {
$array[$dir][$file] = md5_file($dir.'/'.$file);
$array[$dir][$file] = hash_file(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', $dir.'/'.$file);
}
}
}

View File

@ -66,7 +66,7 @@ class Locker
{
$this->lockFile = $lockFile;
$this->installationManager = $installationManager;
$this->hash = md5($composerFileContents);
$this->hash = hash('md5', $composerFileContents);
$this->contentHash = self::getContentHash($composerFileContents);
$this->loader = new ArrayLoader(null, true);
$this->dumper = new ArrayDumper();
@ -107,7 +107,7 @@ class Locker
ksort($relevantContent);
return md5(JsonFile::encode($relevantContent, 0));
return hash('md5', JsonFile::encode($relevantContent, 0));
}
/**

View File

@ -129,7 +129,7 @@ class ArtifactRepository extends ArrayRepository implements ConfigurableReposito
$package['dist'] = [
'type' => $fileType,
'url' => strtr($file->getPathname(), '\\', '/'),
'shasum' => sha1_file($file->getRealPath()),
'shasum' => hash_file('sha1', $file->getRealPath()),
];
try {

View File

@ -181,7 +181,7 @@ class PathRepository extends ArrayRepository implements ConfigurableRepositoryIn
if ('none' === $reference) {
$package['dist']['reference'] = null;
} elseif ('config' === $reference || 'auto' === $reference) {
$package['dist']['reference'] = sha1($json . serialize($this->options));
$package['dist']['reference'] = hash('sha1', $json . serialize($this->options));
}
// copy symlink/relative options to transport options

View File

@ -89,7 +89,7 @@ class Versions
$versions = $this->getVersionsData();
foreach ($versions[$channel ?: $this->getChannel()] as $version) {
if ($version['min-php'] <= PHP_VERSION_ID) {
if ($version['min-php'] <= \PHP_VERSION_ID) {
return $version;
}
}

View File

@ -28,9 +28,9 @@ class ComposerMirror
public static function processUrl(string $mirrorUrl, string $packageName, string $version, ?string $reference, ?string $type, ?string $prettyVersion = null): string
{
if ($reference) {
$reference = Preg::isMatch('{^([a-f0-9]*|%reference%)$}', $reference) ? $reference : md5($reference);
$reference = Preg::isMatch('{^([a-f0-9]*|%reference%)$}', $reference) ? $reference : hash('md5', $reference);
}
$version = strpos($version, '/') === false ? $version : md5($version);
$version = strpos($version, '/') === false ? $version : hash('md5', $version);
$from = ['%package%', '%version%', '%reference%', '%type%'];
$to = [$packageName, $version, $reference, $type];

View File

@ -99,7 +99,7 @@ class CurlDownloader
$this->multiHandle = $mh = curl_multi_init();
if (function_exists('curl_multi_setopt')) {
curl_multi_setopt($mh, CURLMOPT_PIPELINING, PHP_VERSION_ID >= 70400 ? /* CURLPIPE_MULTIPLEX */ 2 : /*CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX*/ 3);
curl_multi_setopt($mh, CURLMOPT_PIPELINING, \PHP_VERSION_ID >= 70400 ? /* CURLPIPE_MULTIPLEX */ 2 : /*CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX*/ 3);
if (defined('CURLMOPT_MAX_HOST_CONNECTIONS') && !defined('HHVM_VERSION')) {
curl_multi_setopt($mh, CURLMOPT_MAX_HOST_CONNECTIONS, 8);
}
@ -363,7 +363,7 @@ class CurlDownloader
continue;
}
if ($errno === 28 /* CURLE_OPERATION_TIMEDOUT */ && PHP_VERSION_ID >= 70300 && $progress['namelookup_time'] === 0.0 && !$timeoutWarning) {
if ($errno === 28 /* CURLE_OPERATION_TIMEDOUT */ && \PHP_VERSION_ID >= 70300 && $progress['namelookup_time'] === 0.0 && !$timeoutWarning) {
$timeoutWarning = true;
$this->io->writeError('<warning>A connection timeout was encountered. If you intend to run Composer without connecting to the internet, run the command again prefixed with COMPOSER_DISABLE_NETWORK=1 to make Composer run in offline mode.</warning>');
}

View File

@ -533,7 +533,7 @@ class RemoteFilesystem
}
// https://www.php.net/manual/en/reserved.variables.httpresponseheader.php
if (PHP_VERSION_ID >= 80400) {
if (\PHP_VERSION_ID >= 80400) {
$responseHeaders = http_get_last_response_headers();
http_clear_last_response_headers();
} else {

View File

@ -150,7 +150,7 @@ final class TlsHelper
$pemtrim = substr($pubkeypem, strpos($pubkeypem, $start) + strlen($start), (strlen($pubkeypem) - strpos($pubkeypem, $end)) * (-1));
$der = base64_decode($pemtrim);
return sha1($der);
return hash('sha1', $der);
}
/**

View File

@ -26,7 +26,7 @@ class RuleTest extends TestCase
{
$rule = new GenericRule([123], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]);
$hash = unpack('ihash', md5('123', true));
$hash = unpack('ihash', (string) hash(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', '123', true));
self::assertEquals($hash['hash'], $rule->getHash());
}

View File

@ -158,7 +158,7 @@ class FileDownloaderTest extends TestCase
$composer->setConfig($config);
$expectedUrl = 'foobar';
$expectedCacheKey = 'dummy/pkg/'.sha1($expectedUrl).'.';
$expectedCacheKey = 'dummy/pkg/'.hash('sha1', $expectedUrl).'.';
$dispatcher = new EventDispatcher(
$composer,
@ -242,7 +242,7 @@ class FileDownloaderTest extends TestCase
$expectedUrl = 'url';
$customCacheKey = 'xyzzy';
$expectedCacheKey = 'dummy/pkg/'.sha1($customCacheKey).'.';
$expectedCacheKey = 'dummy/pkg/'.hash('sha1', $customCacheKey).'.';
$dispatcher = new EventDispatcher(
$composer,

View File

@ -66,7 +66,7 @@ class GitDownloaderTest extends TestCase
$config = new Config();
}
if (!$config->has('home')) {
$tmpDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'cmptest-'.md5(uniqid('', true));
$tmpDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'cmptest-'.bin2hex(random_bytes(5));
$config->merge(['config' => ['home' => $tmpDir]]);
}

View File

@ -121,7 +121,7 @@ EOL
protected function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\Package')
->setConstructorArgs([md5((string) mt_rand()), '1.0.0.0', '1.0.0'])
->setConstructorArgs([bin2hex(random_bytes(5)), '1.0.0.0', '1.0.0'])
->getMock();
}
}

View File

@ -113,7 +113,7 @@ class MetapackageInstallerTest extends TestCase
private function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\Package')
->setConstructorArgs([md5((string) mt_rand()), '1.0.0.0', '1.0.0'])
->setConstructorArgs([bin2hex(random_bytes(5)), '1.0.0.0', '1.0.0'])
->getMock();
}
}

View File

@ -272,7 +272,7 @@ class SuggestedPackagesReporterTest extends TestCase
private function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\Package')
->setConstructorArgs([md5((string) mt_rand()), '1.0.0.0', '1.0.0'])
->setConstructorArgs([bin2hex(random_bytes(5)), '1.0.0.0', '1.0.0'])
->getMock();
}
}

View File

@ -533,7 +533,7 @@ class InstallerTest extends TestCase
if (!empty($testData['LOCK'])) {
$lock = JsonFile::parseJson($testData['LOCK']);
if (!isset($lock['hash'])) {
$lock['hash'] = md5(JsonFile::encode($composer, 0));
$lock['hash'] = hash('md5', JsonFile::encode($composer, 0));
}
}
if (!empty($testData['INSTALLED'])) {

View File

@ -96,7 +96,7 @@ class LockerTest extends TestCase
$package1 = self::getPackage('pkg1', '1.0.0-beta');
$package2 = self::getPackage('pkg2', '0.1.10');
$contentHash = md5(trim($jsonContent));
$contentHash = hash('md5', trim($jsonContent));
$json
->expects($this->once())
@ -154,7 +154,7 @@ class LockerTest extends TestCase
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['hash' => md5($jsonContent)]));
->will($this->returnValue(['hash' => hash('md5', $jsonContent)]));
self::assertTrue($locker->isFresh());
}
@ -185,7 +185,7 @@ class LockerTest extends TestCase
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['hash' => md5($jsonContent . ' '), 'content-hash' => md5($jsonContent)]));
->will($this->returnValue(['hash' => hash('md5', $jsonContent . ' '), 'content-hash' => hash('md5', $jsonContent)]));
self::assertTrue($locker->isFresh());
}
@ -201,7 +201,7 @@ class LockerTest extends TestCase
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['content-hash' => md5($jsonContent)]));
->will($this->returnValue(['content-hash' => hash('md5', $jsonContent)]));
self::assertTrue($locker->isFresh());
}
@ -213,7 +213,7 @@ class LockerTest extends TestCase
$locker = new Locker(new NullIO, $json, $inst, $this->getJsonContent());
$differentHash = md5($this->getJsonContent(['name' => 'test2']));
$differentHash = hash('md5', $this->getJsonContent(['name' => 'test2']));
$json
->expects($this->once())

View File

@ -156,7 +156,7 @@ class PathRepositoryTest extends TestCase
foreach ($packages as $package) {
self::assertEquals(
$package->getDistReference(),
sha1(file_get_contents($package->getDistUrl() . '/composer.json') . serialize($options))
hash('sha1', file_get_contents($package->getDistUrl() . '/composer.json') . serialize($options))
);
}
}

View File

@ -102,7 +102,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase
$root = sys_get_temp_dir();
do {
$unique = $root . DIRECTORY_SEPARATOR . uniqid('composer-test-' . random_int(1000, 9000));
$unique = $root . DIRECTORY_SEPARATOR . 'composer-test-' . bin2hex(random_bytes(10));
if (!file_exists($unique) && Silencer::call('mkdir', $unique, 0777)) {
return realpath($unique);

View File

@ -36,7 +36,7 @@ class ErrorHandlerTest extends TestCase
*/
public function testErrorHandlerCaptureNotice(): void
{
if (PHP_VERSION_ID >= 80000) {
if (\PHP_VERSION_ID >= 80000) {
self::expectException('\ErrorException');
self::expectExceptionMessage('Undefined array key "baz"');
} else {
@ -54,7 +54,7 @@ class ErrorHandlerTest extends TestCase
*/
public function testErrorHandlerCaptureWarning(): void
{
if (PHP_VERSION_ID >= 80000) {
if (\PHP_VERSION_ID >= 80000) {
self::expectException('TypeError');
self::expectExceptionMessage('array_merge');
} else {