#!/usr/bin/env php
<?php declare(strict_types=1);/* Adobe Commerce Monthly Security Release Versioning Tool — single-file build. Auto-generated by scripts/build.php. Requires PHP 8.1+. */namespace Magento\PatchStatus\Model;final class PatchStatus{public function __construct(public readonly string $baseVersion,public readonly array $appliedPatches,public readonly array $missingPatches,public readonly array $installedComponents,public readonly array $vulnerabilityStatus,public readonly array $warnings=[],public readonly string $registrySource='none',public readonly array $unknownPatches=[],){}public static function fromArray(array $data):self{return new self(baseVersion:$data['base_version']??'unknown',appliedPatches:$data['applied_patches']??[],missingPatches:$data['missing_patches']??[],vulnerabilityStatus:$data['vulnerability_status']??[],installedComponents:$data['installed_components']??[],warnings:$data['warnings']??[],registrySource:$data['registry_source']??'none',unknownPatches:$data['unknown_patches']??[],);}public function toArray():array{return['base_version'=>$this->baseVersion,'installed_components'=>$this->installedComponents,'applied_patches'=>$this->appliedPatches,'missing_patches'=>$this->missingPatches,'unknown_patches'=>$this->unknownPatches,'vulnerability_status'=>$this->vulnerabilityStatus,'registry_source'=>$this->registrySource,'warnings'=>$this->warnings,];}}namespace Magento\PatchStatus\Util;class UrlValidator{public static function isValid(string $url):bool{if(filter_var($url,FILTER_VALIDATE_URL)===false){return false;}$scheme=parse_url($url,PHP_URL_SCHEME);return is_string($scheme)&&strtolower($scheme)==='https';}}namespace Magento\PatchStatus\Credential;class ComposerCredentialResolver{public function resolve(string $magentoRoot,string $host):?array{$creds=$this->readComposerAuthEnv($host);if($creds!==null){return $creds;}$paths=array_merge([rtrim($magentoRoot,'/').'/auth.json'],$this->globalAuthJsonPaths(),);foreach($paths as $path){$creds=$this->readCredentials($path,$host);if($creds!==null){return $creds;}}$creds=$this->promptCredentials($host);if($creds!==null){$this->offerToSaveCredentials($magentoRoot,$creds,$host);return $creds;}return null;}protected function globalAuthJsonPaths():array{$composerHome=getenv('COMPOSER_HOME');if($composerHome!==false&&$composerHome!==''){return[rtrim($composerHome,'/').'/auth.json'];}$home=getenv('HOME');if($home!==false&&$home!==''){return[rtrim($home,'/').'/.composer/auth.json'];}return[];}protected function promptCredentials(string $host):?array{$isTty=function_exists('stream_isatty')?stream_isatty(STDIN):(function_exists('posix_isatty')?posix_isatty(STDIN):false);if(!$isTty){return null;}fwrite(STDERR,"\n{$host} credentials required.\n");fwrite(STDERR,'Username (Composer public key): ');$username=trim((string)fgets(STDIN));fwrite(STDERR,'Password (Composer private key): ');$canHideInput=function_exists('shell_exec');if($canHideInput){shell_exec('stty -echo');}try{$password=trim((string)fgets(STDIN));}finally{if($canHideInput){shell_exec('stty echo');}}fwrite(STDERR,"\n");if($username===''||$password===''){return null;}return['username'=>$username,'password'=>$password];}protected function offerToSaveCredentials(string $magentoRoot,array $credentials,string $host):void{$isTty=function_exists('stream_isatty')?stream_isatty(STDIN):(function_exists('posix_isatty')?posix_isatty(STDIN):false);if(!$isTty){return;}$authJsonPath=rtrim($magentoRoot,'/').'/auth.json';$action=file_exists($authJsonPath)?'Update':'Create';fwrite(STDERR,"{$action} {$authJsonPath} with these credentials? [Y/n]: ");$rawResponse=fgets(STDIN);if($rawResponse===false){return;}$response=strtolower(trim($rawResponse));if($response!=='n'&&$response!=='no'){$this->saveCredentialsToAuthJson($authJsonPath,$credentials,$host);}}protected function saveCredentialsToAuthJson(string $path,array $credentials,string $host):void{$data=[];if(file_exists($path)){$existing=@file_get_contents($path);if($existing!==false){$decoded=json_decode($existing,true);if(is_array($decoded)){$data=$decoded;}}}if(!is_array($data['http-basic']??null)){$data['http-basic']=[];}$data['http-basic'][$host]=['username'=>$credentials['username'],'password'=>$credentials['password'],];$encoded=json_encode($data,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);if($encoded===false){return;}$prevUmask=umask(0177);$written=false;try{$written=@file_put_contents($path,$encoded."\n",LOCK_EX)!==false;}finally{umask($prevUmask);}if($written){@chmod($path,0600);}}private function readComposerAuthEnv(string $host):?array{$raw=getenv('COMPOSER_AUTH');if($raw===false||$raw===''){return null;}$data=json_decode($raw,true);if(!is_array($data)){return null;}return $this->extractCredentials($data,$host);}private function readCredentials(string $path,string $host):?array{if(!file_exists($path)){return null;}$content=@file_get_contents($path);if($content===false){return null;}$data=json_decode($content,true);if(!is_array($data)){return null;}return $this->extractCredentials($data,$host);}private function extractCredentials(array $data,string $host):?array{if(!is_array($data['http-basic']??null)){return null;}$username=$data['http-basic'][$host]['username']??null;$password=$data['http-basic'][$host]['password']??null;if(!is_string($username)||$username===''||!is_string($password)||$password===''){return null;}return['username'=>$username,'password'=>$password];}}namespace Magento\PatchStatus\Fetcher;class PatchFetcher{public const DIFF_BASE_URL='https://repo.magento.com/patch';private const CACHE_DIR='var/patch_metadata/.patch_diffs';private const TIMEOUT=3;protected int $lastHttpStatus=0;public function __construct(private readonly string $magentoRoot,private readonly string $patchBaseUrl,private readonly?array $credentials=null,private readonly bool $noCache=false,){}public function hasCredentials():bool{return($this->credentials['username']??'')!==''&&($this->credentials['password']??'')!=='';}public function fetch(string $patchId,string $patchFile,string $expectedSha256,bool $authRequired=false,array&$warnings=[],):?string{if(!$this->isSafePatchFileName($patchFile)){return null;}$cachePath=rtrim($this->magentoRoot,'/').'/'.self::CACHE_DIR.'/'.$patchFile;if(!$this->noCache&&file_exists($cachePath)){$content=@file_get_contents($cachePath);if($content!==false&&$this->verifySha256($content,$expectedSha256)){return $content;}@unlink($cachePath);}if($authRequired&&!$this->hasCredentials()){$warnings[]="Patch {$patchId} requires authentication. Set credentials via COMPOSER_AUTH or auth.json.";return null;}$base=rtrim($this->patchBaseUrl,'/');$url=$authRequired?"{$base}/auth/{$patchFile}":"{$base}/{$patchFile}";$creds=$authRequired?$this->credentials:null;$content=$this->fetchRemote($url,$creds);if($content===false){$status=$this->lastHttpStatus;if($status>=400){$suffix=$authRequired?" Check credentials (COMPOSER_AUTH / auth.json).":"";$warnings[]="Could not fetch patch {$patchId} (HTTP {$status}).{$suffix}";}elseif($authRequired){$warnings[]="Could not fetch or verify patch {$patchId}. Check network connectivity and credentials (COMPOSER_AUTH / auth.json).";}else{$warnings[]="Could not fetch patch file for {$patchId}.";}return null;}if(!$this->verifySha256($content,$expectedSha256)){$warnings[]="SHA-256 verification failed for patch {$patchId}; discarding download.";return null;}$this->writeCache($cachePath,$content);return $content;}protected function fetchRemote(string $url,?array $credentials=null):string|false{$headers=[];if(($credentials['username']??'')!==''&&($credentials['password']??'')!==''){$encoded=base64_encode($credentials['username'].':'.$credentials['password']);$headers[]='Authorization: Basic '.$encoded;}$context=stream_context_create(['http'=>['timeout'=>self::TIMEOUT,'ignore_errors'=>true,'user_agent'=>'Adobe-Commerce-PatchStatus/'.\Magento\PatchStatus\PatchStatusCommand::VERSION,'header'=>implode("\r\n",$headers),],'ssl'=>['verify_peer'=>true,'verify_peer_name'=>true,],]);$this->lastHttpStatus=0;$content=@file_get_contents($url,context:$context);if($content!==false){$status=$this->parseResponseStatus($http_response_header??[]);$this->lastHttpStatus=$status;if($status>=400){return false;}}return $content;}private function parseResponseStatus(array $responseHeaders):int{$status=0;foreach($responseHeaders as $header){if(preg_match('#^HTTP/\S+ (\d{3})#',$header,$m)){$status=(int)$m[1];}}return $status;}private function verifySha256(string $content,string $expectedSha256):bool{return hash('sha256',$content)===strtolower($expectedSha256);}private function writeCache(string $path,string $content):void{$dir=dirname($path);if(!is_dir($dir)){@mkdir($dir,0775,true);}@file_put_contents($path,$content,LOCK_EX);}private function isSafePatchFileName(string $name):bool{return(bool)preg_match('/\A[A-Za-z0-9][A-Za-z0-9_\-]*\.(?:patch|diff)\z/',$name)&&basename($name)===$name;}}namespace Magento\PatchStatus\Detector;final class ComposerDetector{private const BASE_PACKAGES=['magento/product-enterprise-edition','magento/product-community-edition','magento/magento2-base',];public function __construct(private readonly string $magentoRoot){}public function detect():array{$lockFile=rtrim($this->magentoRoot,'/').'/composer.lock';$empty=['base_version'=>null,'release_line'=>null,'installed_packages'=>[],'method'=>'none','warnings'=>[]];if(!file_exists($lockFile)){return $empty;}$raw=file_get_contents($lockFile);if($raw===false){return array_merge($empty,['warnings'=>['composer.lock exists but could not be read']]);}$lock=json_decode($raw,true);if(!is_array($lock)){return array_merge($empty,['warnings'=>['composer.lock could not be parsed as JSON']]);}$packages=array_merge($lock['packages']??[],$lock['packages-dev']??[]);$installedPackages=[];foreach($packages as $pkg){$installedPackages[$pkg['name']??'']=$pkg['version']??'';}$baseVersion=null;foreach(self::BASE_PACKAGES as $pkg){if(isset($installedPackages[$pkg])){$baseVersion=ltrim($installedPackages[$pkg],'v');break;}}$warnings=[];$method='composer';if($baseVersion===null){$warnings[]='No recognized Commerce base package found in composer.lock';$method='none';}$releaseLine=$baseVersion!==null?$this->extractReleaseLine($baseVersion):null;return['base_version'=>$baseVersion,'release_line'=>$releaseLine,'installed_packages'=>$installedPackages,'method'=>$method,'warnings'=>$warnings,];}private function extractReleaseLine(string $version):string{if(preg_match('/^(\d+\.\d+\.\d+)/',$version,$m)){return $m[1];}return $version;}}namespace Magento\PatchStatus\Detector;use Magento\PatchStatus\Fetcher\PatchFetcher;class DryRunDetector{public function __construct(private readonly string $magentoRoot,private readonly array $registry,private readonly PatchFetcher $fetcher,){}public static function isPatchBinaryAvailable():bool{exec('patch --version',$output,$code);return $code===0;}public function detect(array $applicablePatchIds):array{$statuses=[];$warnings=[];$unknownLogs=[];$root=rtrim($this->magentoRoot,'/');if(!$this->isTempDirWritable()){throw new \RuntimeException("Temp directory ".sys_get_temp_dir()." is not writable — check permissions. Aborting.");}foreach($applicablePatchIds as $patchId){$entry=$this->registry['patches'][$patchId]??null;if($entry===null){continue;}$patchFile=$entry['file_name']??null;$patchSha256=$entry['sha256']??null;if($patchFile===null||$patchSha256===null){$statuses[$patchId]='unknown';$warnings[]="No file_name or sha256 for {$patchId}";continue;}$authRequired=!empty($entry['entitlements']??[]);$rawContent=$this->fetcher->fetch($patchId,$patchFile,$patchSha256,$authRequired,$warnings);if($rawContent===null){$statuses[$patchId]='unknown';continue;}$diffContent=$rawContent;$descendants=$this->getDescendants($patchId,$applicablePatchIds);$prerequisites=$this->getPrerequisites($patchId,$applicablePatchIds,$warnings);[$overlappingDescDiffs,$overlappingPrereqDiffs,$missingDepIds]=$this->resolveDependencyDiffs($diffContent,$descendants,$prerequisites);if(!empty($missingDepIds)){$warnings[]='descendant diffs unavailable for '.implode(', ',$missingDepIds)."; dry-run for {$patchId} may be inaccurate";}$affectedFiles=$this->collectAffectedFiles($diffContent,$overlappingDescDiffs,$overlappingPrereqDiffs);$tmpDiff=sys_get_temp_dir().'/patch_status_'.$this->sanitizeForFilename($patchId).'_'.uniqid().'.diff';file_put_contents($tmpDiff,$diffContent);$tmpDirToClean=null;$descendantSanitizationFailed=false;try{$workDir=$root;if(!empty($overlappingDescDiffs)){$tmpDirToClean=$this->createTempWorkDir($root,$patchId,$affectedFiles);$revertWarn=$this->revertDescendantsIn($tmpDirToClean,$patchId,$overlappingDescDiffs);if($revertWarn!==null){$warnings[]=$revertWarn;$this->rmdirRecursive($tmpDirToClean);$tmpDirToClean=null;$descendantSanitizationFailed=true;}else{$workDir=$tmpDirToClean;}}$fwd=$this->runPatch($tmpDiff,$workDir,reverse:false,dryRun:true);$rev=$this->runPatch($tmpDiff,$workDir,reverse:true,dryRun:true);$status=$this->classify($fwd['exit'],$rev['exit']);if($status==='unknown'&&!empty($overlappingPrereqDiffs)&&!$descendantSanitizationFailed){if($tmpDirToClean===null){$tmpDirToClean=$this->createTempWorkDir($root,$patchId,$affectedFiles);$workDir=$tmpDirToClean;}$applyWarn=$this->forwardApplyPrereqsIn($tmpDirToClean,$patchId,$overlappingPrereqDiffs);if($applyWarn!==null){$warnings[]=$applyWarn;}else{$fwd=$this->runPatch($tmpDiff,$workDir,reverse:false,dryRun:true);$rev=$this->runPatch($tmpDiff,$workDir,reverse:true,dryRun:true);$status=$this->classify($fwd['exit'],$rev['exit']);}}$statuses[$patchId]=$status;if($status==='unknown'){$unknownLogs[$patchId]="FWD:\n{$fwd['output']}\nREV:\n{$rev['output']}";}}finally{@unlink($tmpDiff);if($tmpDirToClean!==null){$this->rmdirRecursive($tmpDirToClean);}}}return['statuses'=>$statuses,'method'=>'dry_run','warnings'=>$warnings,'unknown_logs'=>$unknownLogs,];}private function getDescendants(string $patchId,array $applicablePatchIds):array{$applicableSet=array_flip($applicablePatchIds);$descendants=[];$queue=[$patchId];$visited=[$patchId=>true];while(!empty($queue)){$current=array_shift($queue);foreach($this->registry['patches']??[]as $id=>$entry){if(!isset($applicableSet[$id])||isset($visited[$id])){continue;}if(in_array($current,$entry['requires']??[],true)){$descendants[]=$id;$visited[$id]=true;$queue[]=$id;}}}return $descendants;}private function getPrerequisites(string $patchId,array $applicablePatchIds,array&$warnings):array{$applicableSet=array_flip($applicablePatchIds);$result=[];$visited=[$patchId=>true];$this->collectTransitivePrereqs($patchId,$applicableSet,$visited,$result,$warnings);return $result;}private function collectTransitivePrereqs(string $patchId,array $applicableSet,array&$visited,array&$result,array&$warnings):void{$requires=$this->registry['patches'][$patchId]['requires']??[];foreach($requires as $preId){if(isset($visited[$preId])){continue;}$visited[$preId]=true;if(!isset($this->registry['patches'][$preId])){$warnings[]="Registry entry '{$patchId}' requires unknown patch '{$preId}'; skipping.";continue;}if(!isset($applicableSet[$preId])){continue;}$this->collectTransitivePrereqs($preId,$applicableSet,$visited,$result,$warnings);$result[]=$preId;}}private function resolveDependencyDiffs(string $diffContent,array $descendants,array $prerequisites):array{$pFiles=array_flip($this->parseDiffFiles($diffContent));$missingDepIds=[];$overlappingDescDiffs=[];foreach(array_reverse($descendants)as $depId){$diff=$this->fetchDependencyDiff($depId);if($diff===null){$missingDepIds[]=$depId;continue;}if($this->diffOverlapsFiles($diff,$pFiles)){$overlappingDescDiffs[$depId]=$diff;}}$overlappingPrereqDiffs=[];foreach($prerequisites as $preId){$diff=$this->fetchDependencyDiff($preId);if($diff===null){continue;}if($this->diffOverlapsFiles($diff,$pFiles)){$overlappingPrereqDiffs[$preId]=$diff;}}return[$overlappingDescDiffs,$overlappingPrereqDiffs,$missingDepIds];}private function fetchDependencyDiff(string $patchId):?string{$entry=$this->registry['patches'][$patchId]??null;if($entry===null){return null;}$authRequired=!empty($entry['entitlements']??[]);$raw=$this->fetcher->fetch($patchId,$entry['file_name']??'',$entry['sha256']??'',$authRequired);if($raw===null){return null;}return $raw;}private function diffOverlapsFiles(string $diff,array $fileSet):bool{foreach($this->parseDiffFiles($diff)as $f){if(isset($fileSet[$f])){return true;}}return false;}private function collectAffectedFiles(string $diffContent,array $overlappingDescDiffs,array $overlappingPrereqDiffs):array{$files=$this->parseDiffFiles($diffContent);foreach($overlappingDescDiffs as $d){$files=array_merge($files,$this->parseDiffFiles($d));}foreach($overlappingPrereqDiffs as $d){$files=array_merge($files,$this->parseDiffFiles($d));}return array_values(array_unique($files));}private function createTempWorkDir(string $root,string $patchId,array $affectedFiles):string{$tmpDir=sys_get_temp_dir().'/patch_status_wd_'.$this->sanitizeForFilename($patchId).'_'.uniqid();if(!mkdir($tmpDir,0700,true)){throw new \RuntimeException("Could not create temp workdir {$tmpDir}");}try{foreach($affectedFiles as $relPath){$src=$root.'/'.$relPath;if(!file_exists($src)){continue;}$dst=$tmpDir.'/'.$relPath;$dstDir=dirname($dst);if(!is_dir($dstDir)&&!mkdir($dstDir,0700,true)){throw new \RuntimeException("Could not create directory {$dstDir} in temp workdir");}if(!copy($src,$dst)){throw new \RuntimeException("Could not copy {$relPath} into temp workdir");}}}catch(\RuntimeException $e){$this->rmdirRecursive($tmpDir);throw $e;}return $tmpDir;}private function revertDescendantsIn(string $workDir,string $patchId,array $overlappingDescDiffs):?string{foreach($overlappingDescDiffs as $depId=>$depDiff){$tmpDepDiff=sys_get_temp_dir().'/patch_status_dep_'.$this->sanitizeForFilename($depId).'_'.uniqid().'.diff';file_put_contents($tmpDepDiff,$depDiff);$check=$this->runPatch($tmpDepDiff,$workDir,reverse:true,dryRun:true);if($check['exit']!==0){@unlink($tmpDepDiff);continue;}$result=$this->runPatch($tmpDepDiff,$workDir,reverse:true,dryRun:false);@unlink($tmpDepDiff);if($result['exit']!==0){return"Failed to reverse-apply {$depId} when preparing dry-run for {$patchId}; result may be inaccurate";}}return null;}private function forwardApplyPrereqsIn(string $workDir,string $patchId,array $overlappingPrereqDiffs):?string{foreach($overlappingPrereqDiffs as $preId=>$preDiff){$tmpPreDiff=sys_get_temp_dir().'/patch_status_pre_'.$this->sanitizeForFilename($preId).'_'.uniqid().'.diff';file_put_contents($tmpPreDiff,$preDiff);$checkRev=$this->runPatch($tmpPreDiff,$workDir,reverse:true,dryRun:true);if($checkRev['exit']===0){@unlink($tmpPreDiff);continue;}$result=$this->runPatch($tmpPreDiff,$workDir,reverse:false,dryRun:false);@unlink($tmpPreDiff);if($result['exit']!==0){return"Failed to forward-apply prerequisite {$preId} when preparing dry-run for {$patchId}; result may be inaccurate";}}return null;}protected function runPatch(string $diffFile,string $workDir,bool $reverse,bool $dryRun):array{$args=['patch','-p1','--fuzz=0','--batch','--forward'];if($reverse){$args[]='-R';}if($dryRun){$args[]='--dry-run';}$args[]='-d';$args[]=$workDir;$args[]='-i';$args[]=$diffFile;$cmd=implode(' ',array_map('escapeshellarg',$args)).' 2>&1';$descriptors=[0=>['pipe','r'],1=>['pipe','w']];$process=proc_open($cmd,$descriptors,$pipes);if(!is_resource($process)){return['exit'=>-1,'output'=>''];}fclose($pipes[0]);$output=(string)stream_get_contents($pipes[1]);fclose($pipes[1]);$exit=proc_close($process);return['exit'=>$exit,'output'=>trim($output)];}private function classify(int $fwdExit,int $revExit):string{return match(true){$fwdExit!==0&&$revExit===0=>'applied',$fwdExit===0&&$revExit!==0=>'not_applied',default=>'unknown',};}private function parseDiffFiles(string $diffContent):array{$files=[];foreach(explode("\n",$diffContent)as $line){if(preg_match('#^(?:---|\+\+\+) [ab]/(.+)$#',$line,$m)){$path=trim($m[1]);if($path!=='/dev/null'){$files[$path]=true;}}}return array_keys($files);}private function rmdirRecursive(string $path):void{if(!is_dir($path)){return;}$entries=scandir($path);if($entries===false){return;}foreach($entries as $item){if($item==='.'||$item==='..'){continue;}$full=$path.'/'.$item;is_dir($full)?$this->rmdirRecursive($full):unlink($full);}rmdir($path);}protected function isTempDirWritable():bool{return is_writable(sys_get_temp_dir());}private function sanitizeForFilename(string $id):string{$sanitized=preg_replace('/[^A-Za-z0-9_.\-]/','_',$id);if($sanitized!==null){return $sanitized;}return'patch_'.sha1($id);}}namespace Magento\PatchStatus\Registry;use Magento\PatchStatus\Util\UrlValidator;class RegistryLoader{public const REMOTE_URL='https://repo.magento.com/patch/patch-registry.json';private const CACHE_FILE='var/patch_metadata/.patch_registry_cache.json';private const CACHE_TTL=3600;private const TIMEOUT=3;public function __construct(private readonly string $magentoRoot,private readonly bool $forceRefresh=false,){}public function load():array{$cachePath=rtrim($this->magentoRoot,'/').'/'.self::CACHE_FILE;$warnings=[];$cached=$this->forceRefresh?null:$this->readCache($cachePath);if($cached!==null&&$this->cacheAge($cachePath)<self::CACHE_TTL){return['registry'=>$cached,'source'=>'cache','warnings'=>[]];}$remote=$this->fetchRemote($warnings);if($remote!==null){$this->writeCache($cachePath,$remote);return['registry'=>$remote,'source'=>'remote','warnings'=>[]];}if($this->forceRefresh){$warnings[]='Could not fetch remote registry and --no-cache was set; aborting.';return['registry'=>[],'source'=>'none','warnings'=>$warnings];}if($cached!==null){$ageHours=(int)round($this->cacheAge($cachePath)/3600);$warnings[]=sprintf('Could not load remote registry. Using cached registry (%d hour%s old). CVE coverage may be incomplete.',$ageHours,$ageHours===1?'':'s',);return['registry'=>$cached,'source'=>'stale_cache','warnings'=>$warnings];}$warnings[]='Patch registry could not be loaded.';return['registry'=>[],'source'=>'none','warnings'=>$warnings];}protected function fetchRemote(array&$warnings):?array{$context=stream_context_create(['http'=>['timeout'=>self::TIMEOUT,'ignore_errors'=>true,'user_agent'=>'Adobe-Commerce-PatchStatus/'.\Magento\PatchStatus\PatchStatusCommand::VERSION,],'ssl'=>['verify_peer'=>true,'verify_peer_name'=>true,],]);$override=getenv('PATCH_REGISTRY_URL');if($override!==false&&trim($override)!==''){$override=trim($override);if(!UrlValidator::isValid($override)){throw new \InvalidArgumentException('Environment variable PATCH_REGISTRY_URL contains an invalid URL (must be https).');}$url=$override;}else{$url=self::REMOTE_URL;}$raw=@file_get_contents($url,context:$context);if($raw===false){return null;}$status=$this->parseHttpStatus($http_response_header??[]);if($status>=400){$warnings[]=sprintf('Remote registry fetch failed (HTTP %d). Check PATCH_REGISTRY_URL (if set) and network connectivity.',$status,);return null;}$data=json_decode($raw,true);if(!is_array($data)){$warnings[]='Remote registry response was not valid JSON; ignoring.';return null;}return $data;}private function parseHttpStatus(array $responseHeaders):int{$status=0;foreach($responseHeaders as $header){if(preg_match('#^HTTP/\S+ (\d{3})#',$header,$m)){$status=(int)$m[1];}}return $status;}private function readCache(string $path):?array{if(!file_exists($path)){return null;}$raw=@file_get_contents($path);if($raw===false){return null;}$data=json_decode($raw,true);return is_array($data)?$data:null;}private function writeCache(string $path,array $data):void{$dir=dirname($path);if(!is_dir($dir)){@mkdir($dir,0775,true);}@file_put_contents($path,json_encode($data),LOCK_EX);}private function cacheAge(string $path):int{$mtime=@filemtime($path);return $mtime!==false?(time()-$mtime):PHP_INT_MAX;}}namespace Magento\PatchStatus\Resolver;final class PatchResolver{public function __construct(private readonly array $registry){}public function getApplicableIds(array $componentVersions,array $installedAreas):array{$assumeAll=empty($installedAreas)||empty($componentVersions);return array_keys($this->applicablePatches($componentVersions,$installedAreas,$assumeAll));}public function resolve(array $appliedIds,array $componentVersions,array $installedAreas=[]):array{$warnings=[];$assumeAll=empty($installedAreas)||empty($componentVersions);if($assumeAll){$warnings[]='Installed components could not be detected; all patches treated as applicable. Results may include patches irrelevant to this installation.';}$applicable=$this->applicablePatches($componentVersions,$installedAreas,$assumeAll);if(empty($applicable)){$versionsStr=implode(', ',array_map(fn($a,$v)=>"{$a}={$v}",array_keys($componentVersions),array_values($componentVersions)));$warnings[]="No patches found in registry for installed component versions ({$versionsStr})";return['missing'=>[],'warnings'=>$warnings,];}$appliedSet=array_flip($appliedIds);$missing=[];foreach($applicable as $patchId=>$patch){if(!isset($appliedSet[$patchId])){$missing[]=$patchId;}}return['missing'=>$missing,'warnings'=>$warnings,];}private function applicablePatches(array $componentVersions,array $installedAreas,bool $assumeAll):array{$areaSet=$assumeAll?null:array_flip($installedAreas);$result=[];foreach($this->registry['patches']??[]as $patchId=>$patch){if($assumeAll){$result[$patchId]=$patch;continue;}$area=$patch['area']??'';if($areaSet!==null&&!isset($areaSet[$area])){continue;}$installedVersion=$componentVersions[$area]??null;if($installedVersion===null){continue;}if(!in_array($installedVersion,$patch['applies_to']??[],true)){continue;}$result[$patchId]=$patch;}return $result;}}namespace Magento\PatchStatus\Resolver;final class CveResolver{public function __construct(private readonly array $registry){}public function resolve(array $appliedIds,array $missingIds=[],array $installedAreas=[],array $componentVersions=[],array $unknownIds=[],):array{$appliedSet=array_flip($appliedIds);$unknownSet=array_flip($unknownIds);$areaSet=!empty($installedAreas)?array_flip($installedAreas):null;$byCve=[];foreach($this->registry['patches']??[]as $patchId=>$patch){$patchArea=$patch['area']??'CE';if(!empty($componentVersions)){$areaIsInstalled=$areaSet===null||isset($areaSet[$patchArea]);if($areaIsInstalled){$installedVersion=$componentVersions[$patchArea]??null;if($installedVersion===null||!in_array($installedVersion,$patch['applies_to']??[],true)){continue;}}}if(isset($appliedSet[$patchId])){$patchStatus='PROTECTED';}elseif($areaSet!==null&&!isset($areaSet[$patchArea])){$patchStatus='NOT_APPLICABLE';}elseif(isset($unknownSet[$patchId])){$patchStatus='UNKNOWN';}else{$patchStatus='VULNERABLE';}foreach($patch['cves']??[]as $cve){$byCve[$cve][$patchStatus]=true;}}$status=[];foreach($byCve as $cve=>$statuses){$status[$cve]=['status'=>match(true){isset($statuses['VULNERABLE'])=>'VULNERABLE',isset($statuses['UNKNOWN'])=>'UNKNOWN',isset($statuses['PROTECTED'])=>'PROTECTED',default=>'NOT_APPLICABLE',},];}ksort($status);return $status;}}namespace Magento\PatchStatus\Formatter;use Magento\PatchStatus\Model\PatchStatus;final class JsonFormatter{public function format(PatchStatus $status):string{return json_encode($status->toArray(),JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES)."\n";}}namespace Magento\PatchStatus\Formatter;use Magento\PatchStatus\Model\PatchStatus;final class CsvFormatter{private const HEADERS=['base_version','installed_components','applied_patches','missing_patches','unknown_patches','cve','cve_status',];public function format(PatchStatus $status):string{$buf=fopen('php://temp','r+');fputcsv($buf,self::HEADERS,separator:',',enclosure:'"',escape:'\\');$common=[$status->baseVersion,implode(';',array_map(static fn($area,$ver)=>"{$area}:{$ver}",array_keys($status->installedComponents),$status->installedComponents,)),implode(';',$status->appliedPatches),implode(';',$status->missingPatches),implode(';',$status->unknownPatches),];if(empty($status->vulnerabilityStatus)){fputcsv($buf,array_merge($common,['','']),separator:',',enclosure:'"',escape:'\\');}else{foreach($status->vulnerabilityStatus as $cve=>$info){fputcsv($buf,array_merge($common,[$cve,$info['status'],]),separator:',',enclosure:'"',escape:'\\');}}rewind($buf);$content=stream_get_contents($buf);fclose($buf);return $content;}}namespace Magento\PatchStatus;use Magento\PatchStatus\Credential\ComposerCredentialResolver;use Magento\PatchStatus\Detector\ComposerDetector;use Magento\PatchStatus\Detector\DryRunDetector;use Magento\PatchStatus\Fetcher\PatchFetcher;use Magento\PatchStatus\Formatter\CsvFormatter;use Magento\PatchStatus\Formatter\JsonFormatter;use Magento\PatchStatus\Model\PatchStatus;use Magento\PatchStatus\Registry\RegistryLoader;use Magento\PatchStatus\Resolver\CveResolver;use Magento\PatchStatus\Resolver\PatchResolver;use Magento\PatchStatus\Util\UrlValidator;class PatchStatusCommand{public const VERSION='1.0.0';private const LOG_FILE='var/log/patch_status.log';private string $root='.';private string $format='json';private bool $noCache=false;public function run(array $argv):int{try{return $this->doRun($argv);}catch(\InvalidArgumentException $e){$this->error($e->getMessage());return 1;}}private function doRun(array $argv):int{$this->parseArgs($argv);$loaded=$this->makeRegistryLoader($this->root,forceRefresh:$this->noCache)->load();$warnings=$loaded['warnings'];$registry=$loaded['registry'];if(empty($registry)){foreach($warnings as $warning){$this->error($warning);}if(empty($warnings)){$this->error('Cannot load patch registry');}return 1;}$comp=(new ComposerDetector($this->root))->detect();$warnings=array_merge($warnings,$comp['warnings']);$baseVersion=$comp['base_version']??'unknown';$areaDefinitions=$registry['_areas']??[];$installedAreas=[];$componentVersions=[];foreach($areaDefinitions as $area=>$def){if(($def['detection']??'')==='base_version'){if($baseVersion!=='unknown'){$installedAreas[]=$area;$componentVersions[$area]=$baseVersion;}}elseif(isset($def['composer_package'])){$pkg=$def['composer_package'];if(isset($comp['installed_packages'][$pkg])){$installedAreas[]=$area;$componentVersions[$area]=ltrim($comp['installed_packages'][$pkg],'v');}}}if($baseVersion==='unknown'){$status=new PatchStatus(baseVersion:'unknown',appliedPatches:[],missingPatches:[],installedComponents:[],vulnerabilityStatus:[],warnings:array_values(array_unique($warnings)),registrySource:$loaded['source'],);echo match($this->format){'csv'=>(new CsvFormatter())->format($status),default=>(new JsonFormatter())->format($status),};return 1;}if(!$this->isPatchBinaryAvailable()){$this->error('patch(1) binary not found. Install the patch utility and try again.');return 1;}$patchResolver=new PatchResolver($registry);$applicableIds=$patchResolver->getApplicableIds($componentVersions,$installedAreas);if(empty($applicableIds)){$versionsStr=implode(', ',array_map(fn($a,$v)=>"{$a}={$v}",array_keys($componentVersions),array_values($componentVersions),));$warnings[]="No patches found in registry for installed component versions ({$versionsStr})";}try{$detected=$this->runDryRunDetection($applicableIds,$registry);}catch(\RuntimeException $e){$this->error($e->getMessage());return 1;}$warnings=array_merge($warnings,$detected['warnings']);$unknownLogs=$detected['unknown_logs'];$appliedPatches=[];$missingPatches=[];$unknownPatches=[];foreach($detected['statuses']as $patchId=>$patchStatus){match($patchStatus){'applied'=>$appliedPatches[]=$patchId,'not_applied'=>$missingPatches[]=$patchId,'unknown'=>$unknownPatches[]=$patchId,default=>null,};}$cveResolver=new CveResolver($registry);$vulnStatus=$cveResolver->resolve($appliedPatches,$missingPatches,$installedAreas,$componentVersions,$unknownPatches,);$status=new PatchStatus(baseVersion:$baseVersion,appliedPatches:array_values($appliedPatches),missingPatches:array_values($missingPatches),installedComponents:$componentVersions,vulnerabilityStatus:$vulnStatus,warnings:array_values(array_unique($warnings)),registrySource:$loaded['source'],unknownPatches:array_values($unknownPatches),);$output=match($this->format){'csv'=>(new CsvFormatter())->format($status),default=>(new JsonFormatter())->format($status),};echo $output;$this->writeLog($status,$unknownLogs);return 0;}protected function makeRegistryLoader(string $magentoRoot,bool $forceRefresh):RegistryLoader{return new RegistryLoader(magentoRoot:$magentoRoot,forceRefresh:$forceRefresh);}protected function isPatchBinaryAvailable():bool{return DryRunDetector::isPatchBinaryAvailable();}protected function runDryRunDetection(array $applicableIds,array $registry):array{$override=getenv('PATCH_DIFF_BASE_URL');if($override!==false&&trim($override)!==''){$override=trim($override);if(!UrlValidator::isValid($override)){throw new \InvalidArgumentException('Environment variable PATCH_DIFF_BASE_URL contains an invalid URL (must be https).');}$baseUrl=$override;}else{$baseUrl=PatchFetcher::DIFF_BASE_URL;}$needsAuth=false;foreach($applicableIds as $id){if(!empty($registry['patches'][$id]['entitlements']??[])){$needsAuth=true;break;}}$credentials=null;if($needsAuth){$host=(string)(parse_url($baseUrl,PHP_URL_HOST)??'');$credentials=(new ComposerCredentialResolver())->resolve($this->root,$host);}$fetcher=new PatchFetcher($this->root,$baseUrl,$credentials,noCache:$this->noCache);$detector=new DryRunDetector($this->root,$registry,$fetcher);return $detector->detect($applicableIds);}private function parseArgs(array $argv):void{foreach(array_slice($argv,1)as $arg){if(preg_match('/^--root=(.+)$/',$arg,$m)){$this->root=rtrim($m[1],'/');}elseif(preg_match('/^--format=(json|csv)$/',$arg,$m)){$this->format=$m[1];}elseif($arg==='--no-cache'){$this->noCache=true;}elseif(in_array($arg,['--version','-V'],true)){echo'patch-status '.self::VERSION."\n";exit(0);}elseif(in_array($arg,['--help','-h'],true)){$this->printUsage();exit(0);}}}private function printUsage():void{$version=self::VERSION;echo"Adobe Commerce Monthly Security Release Versioning Tool v{$version}\n\n"."Usage:\n"."  vendor/bin/patch-status [OPTIONS]\n\n"."Options:\n"."  --root=PATH           Path to Commerce installation root (default: current directory)\n"."  --format=FORMAT       Output format: json (default) or csv\n"."  --no-cache            Bypass all local caches (registry and patch diffs); force fresh fetches from remote; exits with an error if the remote registry is unreachable\n"."  --version             Show version\n"."  --help                Show this help message\n\n"."Note: Output format is not final and may change in future releases.\n\n";}private function writeLog(PatchStatus $status,array $unknownLogs):void{$logPath=rtrim($this->root,'/').'/'.self::LOG_FILE;$logDir=dirname($logPath);if(!is_dir($logDir)&&!@mkdir($logDir,0775,true)){return;}$line=sprintf("[%s] base=%s applied=[%s] missing=[%s] unknown=[%s]\n",date('c'),$status->baseVersion,implode(',',$status->appliedPatches),implode(',',$status->missingPatches),implode(',',$status->unknownPatches),);@file_put_contents($logPath,$line,FILE_APPEND|LOCK_EX);foreach($unknownLogs as $patchId=>$logOutput){$block=sprintf("[%s] UNKNOWN %s:\n%s\n",date('c'),$patchId,$logOutput);@file_put_contents($logPath,$block,FILE_APPEND|LOCK_EX);}}private function error(string $msg):void{fwrite(STDERR,"patch-status: {$msg}\n");}}
$command=new PatchStatusCommand();exit($command->run($argv));
