-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[AssetMapper] Add audit command #51650
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
187 changes: 187 additions & 0 deletions
187
src/Symfony/Component/AssetMapper/Command/ImportMapAuditCommand.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,187 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\AssetMapper\Command; | ||
|
||
use Symfony\Component\AssetMapper\ImportMap\ImportMapAuditor; | ||
use Symfony\Component\AssetMapper\ImportMap\ImportMapPackageAuditVulnerability; | ||
use Symfony\Component\Console\Attribute\AsCommand; | ||
use Symfony\Component\Console\Command\Command; | ||
use Symfony\Component\Console\Input\InputInterface; | ||
use Symfony\Component\Console\Input\InputOption; | ||
use Symfony\Component\Console\Output\OutputInterface; | ||
use Symfony\Component\Console\Style\SymfonyStyle; | ||
|
||
#[AsCommand(name: 'importmap:audit', description: 'Checks for security vulnerability advisories for dependencies.')] | ||
class ImportMapAuditCommand extends Command | ||
{ | ||
private const SEVERITY_COLORS = [ | ||
'critical' => 'red', | ||
'high' => 'red', | ||
'medium' => 'yellow', | ||
'low' => 'default', | ||
'unknown' => 'default', | ||
]; | ||
|
||
private SymfonyStyle $io; | ||
|
||
public function __construct( | ||
private readonly ImportMapAuditor $importMapAuditor, | ||
) { | ||
parent::__construct(); | ||
} | ||
|
||
protected function configure(): void | ||
{ | ||
$this->addOption( | ||
name: 'format', | ||
mode: InputOption::VALUE_REQUIRED, | ||
description: sprintf('The output format ("%s")', implode(', ', $this->getAvailableFormatOptions())), | ||
default: 'txt', | ||
); | ||
} | ||
|
||
protected function initialize(InputInterface $input, OutputInterface $output): void | ||
{ | ||
$this->io = new SymfonyStyle($input, $output); | ||
} | ||
|
||
protected function execute(InputInterface $input, OutputInterface $output): int | ||
{ | ||
$format = $input->getOption('format'); | ||
|
||
$audit = $this->importMapAuditor->audit(); | ||
|
||
return match ($format) { | ||
'txt' => $this->displayTxt($audit), | ||
'json' => $this->displayJson($audit), | ||
default => throw new \InvalidArgumentException(sprintf('Supported formats are "%s".', implode('", "', $this->getAvailableFormatOptions()))), | ||
}; | ||
} | ||
|
||
private function displayTxt(array $audit): int | ||
{ | ||
$rows = []; | ||
|
||
$packagesWithoutVersion = []; | ||
$vulnerabilitiesCount = array_map(fn() => 0, self::SEVERITY_COLORS); | ||
foreach ($audit as $packageAudit) { | ||
if (!$packageAudit->version) { | ||
$packagesWithoutVersion[] = $packageAudit->package; | ||
} | ||
foreach($packageAudit->vulnerabilities as $vulnerability) { | ||
$rows[] = [ | ||
sprintf('<fg=%s>%s</>', self::SEVERITY_COLORS[$vulnerability->severity] ?? 'default', ucfirst($vulnerability->severity)), | ||
$vulnerability->summary, | ||
$packageAudit->package, | ||
$packageAudit->version ?? 'n/a', | ||
$vulnerability->firstPatchedVersion ?? 'n/a', | ||
$vulnerability->url, | ||
]; | ||
++$vulnerabilitiesCount[$vulnerability->severity]; | ||
} | ||
} | ||
$packagesCount = count($audit); | ||
$packagesWithoutVersionCount = count($packagesWithoutVersion); | ||
|
||
if ([] === $rows && 0 === $packagesWithoutVersionCount) { | ||
$this->io->info('No vulnerabilities found.'); | ||
|
||
return self::SUCCESS; | ||
} | ||
|
||
if ([] !== $rows) { | ||
$table = $this->io->createTable(); | ||
$table->setHeaders([ | ||
'Severity', | ||
'Title', | ||
'Package', | ||
'Version', | ||
'Patched in', | ||
'More info', | ||
]); | ||
$table->addRows($rows); | ||
$table->render(); | ||
$this->io->newLine(); | ||
} | ||
|
||
$this->io->text(sprintf('%d package%s found: %d audited / %d skipped', | ||
$packagesCount, | ||
1 === $packagesCount ? '' : 's', | ||
$packagesCount - $packagesWithoutVersionCount, | ||
$packagesWithoutVersionCount, | ||
)); | ||
|
||
if (0 < $packagesWithoutVersionCount) { | ||
$this->io->warning(sprintf('Unable to retrieve versions for package%s: %s', | ||
1 === $packagesWithoutVersionCount ? '' : 's', | ||
implode(', ', $packagesWithoutVersion) | ||
)); | ||
} | ||
|
||
if ([] !== $rows) { | ||
$vulnerabilityCount = 0; | ||
$vulnerabilitySummary = []; | ||
foreach ($vulnerabilitiesCount as $severity => $count) { | ||
if (0 === $count) { | ||
continue; | ||
} | ||
$vulnerabilitySummary[] = sprintf( '%d %s', $count, ucfirst($severity)); | ||
$vulnerabilityCount += $count; | ||
} | ||
$this->io->text(sprintf('%d vulnerabilit%s found: %s', | ||
$vulnerabilityCount, | ||
1 === $vulnerabilityCount ? 'y' : 'ies', | ||
implode(' / ', $vulnerabilitySummary), | ||
)); | ||
} | ||
|
||
return self::FAILURE; | ||
} | ||
|
||
private function displayJson(array $audit): int | ||
{ | ||
$vulnerabilitiesCount = array_map(fn() => 0, self::SEVERITY_COLORS); | ||
|
||
$json = [ | ||
'packages' => [], | ||
'summary' => $vulnerabilitiesCount, | ||
]; | ||
|
||
foreach ($audit as $packageAudit) { | ||
$json['packages'][] = [ | ||
'package' => $packageAudit->package, | ||
'version' => $packageAudit->version, | ||
'vulnerabilities' => array_map(fn (ImportMapPackageAuditVulnerability $v) => [ | ||
'ghsa_id' => $v->ghsaId, | ||
'cve_id' => $v->cveId, | ||
'url' => $v->url, | ||
'summary' => $v->summary, | ||
'severity' => $v->severity, | ||
'vulnerable_version_range' => $v->vulnerableVersionRange, | ||
'first_patched_version' => $v->firstPatchedVersion, | ||
], $packageAudit->vulnerabilities), | ||
]; | ||
foreach ($packageAudit->vulnerabilities as $vulnerability) { | ||
++$json['summary'][$vulnerability->severity]; | ||
} | ||
} | ||
|
||
$this->io->write(json_encode($json)); | ||
|
||
return 0 < array_sum($json['summary']) ? self::FAILURE : self::SUCCESS; | ||
} | ||
|
||
private function getAvailableFormatOptions(): array | ||
{ | ||
return ['txt', 'json']; | ||
} | ||
} |
119 changes: 119 additions & 0 deletions
119
src/Symfony/Component/AssetMapper/ImportMap/ImportMapAuditor.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <[email protected]> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\AssetMapper\ImportMap; | ||
|
||
use Symfony\Component\AssetMapper\Exception\RuntimeException; | ||
use Symfony\Component\AssetMapper\ImportMap\Resolver\PackageResolverInterface; | ||
use Symfony\Component\HttpClient\HttpClient; | ||
use Symfony\Contracts\HttpClient\HttpClientInterface; | ||
|
||
class ImportMapAuditor | ||
{ | ||
private const AUDIT_URL = 'https://api.github.com/advisories'; | ||
|
||
private readonly HttpClientInterface $httpClient; | ||
|
||
public function __construct( | ||
private readonly ImportMapConfigReader $configReader, | ||
private readonly PackageResolverInterface $packageResolver, | ||
HttpClientInterface $httpClient = null, | ||
) { | ||
$this->httpClient = $httpClient ?? HttpClient::create(); | ||
} | ||
|
||
/** | ||
* @return list<ImportMapPackageAudit> | ||
*/ | ||
public function audit(): array | ||
{ | ||
$entries = $this->configReader->getEntries(); | ||
|
||
if ([] === $entries) { | ||
return []; | ||
Jean-Beru marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
/** @var array<string, array<string, ImportMapPackageAudit>> $installed */ | ||
$packageAudits = []; | ||
|
||
/** @var array<string, list<string>> $installed */ | ||
$installed = []; | ||
$affectsQuery = []; | ||
foreach ($entries as $entry) { | ||
if (null === $entry->url) { | ||
continue; | ||
} | ||
$version = $entry->version ?? $this->packageResolver->getPackageVersion($entry->url); | ||
|
||
$installed[$entry->importName] ??= []; | ||
$installed[$entry->importName][] = $version; | ||
|
||
$packageVersion = $entry->importName.($version ? '@'.$version : ''); | ||
$packageAudits[$packageVersion] ??= new ImportMapPackageAudit($entry->importName, $version); | ||
$affectsQuery[] = $packageVersion; | ||
} | ||
|
||
// @see https://docs.github.com/en/rest/security-advisories/global-advisories?apiVersion=2022-11-28#list-global-security-advisories | ||
$response = $this->httpClient->request('GET', self::AUDIT_URL, [ | ||
'query' => ['affects' => implode(',', $affectsQuery)], | ||
]); | ||
|
||
if (200 !== $response->getStatusCode()) { | ||
throw new RuntimeException(sprintf('Error %d auditing packages. Response: %s', $response->getStatusCode(), $response->getContent(false))); | ||
} | ||
|
||
foreach ($response->toArray() as $advisory) { | ||
foreach ($advisory['vulnerabilities'] ?? [] as $vulnerability) { | ||
if ( | ||
null === $vulnerability['package'] | ||
|| 'npm' !== $vulnerability['package']['ecosystem'] | ||
|| !array_key_exists($package = $vulnerability['package']['name'], $installed) | ||
) { | ||
continue; | ||
} | ||
foreach ($installed[$package] as $version) { | ||
if (!$version || !$this->versionMatches($version, $vulnerability['vulnerable_version_range'] ?? '>= *')) { | ||
continue; | ||
} | ||
$packageAudits[$package.($version ? '@'.$version : '')] = $packageAudits[$package.($version ? '@'.$version : '')]->withVulnerability( | ||
new ImportMapPackageAuditVulnerability( | ||
$advisory['ghsa_id'], | ||
$advisory['cve_id'], | ||
$advisory['url'], | ||
$advisory['summary'], | ||
$advisory['severity'], | ||
$vulnerability['vulnerable_version_range'], | ||
$vulnerability['first_patched_version'], | ||
) | ||
); | ||
} | ||
} | ||
} | ||
|
||
return array_values($packageAudits); | ||
} | ||
|
||
private function versionMatches(string $version, string $ranges): bool | ||
{ | ||
foreach (explode(',', $ranges) as $rangeString) { | ||
$range = explode(' ', trim($rangeString)); | ||
if (1 === count($range)) { | ||
$range = ['=', $range[0]]; | ||
} | ||
|
||
if (!version_compare($version, $range[1], $range[0])) { | ||
return false; | ||
} | ||
Jean-Beru marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
return true; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -38,7 +38,7 @@ public function getEntries(): ImportMapEntries | |
|
||
$entries = new ImportMapEntries(); | ||
foreach ($importMapConfig ?? [] as $importName => $data) { | ||
$validKeys = ['path', 'url', 'downloaded_to', 'type', 'entrypoint']; | ||
$validKeys = ['path', 'url', 'downloaded_to', 'type', 'entrypoint', 'version']; | ||
if ($invalidKeys = array_diff(array_keys($data), $validKeys)) { | ||
throw new \InvalidArgumentException(sprintf('The following keys are not valid for the importmap entry "%s": "%s". Valid keys are: "%s".', $importName, implode('", "', $invalidKeys), implode('", "', $validKeys))); | ||
} | ||
|
@@ -57,6 +57,7 @@ public function getEntries(): ImportMapEntries | |
isDownloaded: isset($data['downloaded_to']), | ||
type: $type, | ||
isEntrypoint: $isEntry, | ||
version: $data['version'] ?? null, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. sure. it's done. |
||
)); | ||
} | ||
|
||
|
@@ -83,6 +84,9 @@ public function writeEntries(ImportMapEntries $entries): void | |
if ($entry->isEntrypoint) { | ||
$config['entrypoint'] = true; | ||
} | ||
if ($entry->version) { | ||
$config['version'] = $entry->version; | ||
} | ||
$importMapConfig[$entry->importName] = $config; | ||
} | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.