8000 [AssetMapper] Add audit command by Jean-Beru · Pull Request #51650 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[AssetMapper] Add audit command #51650

8000
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 1 commit into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Symfony\Component\AssetMapper\AssetMapperInterface;
use Symfony\Component\AssetMapper\AssetMapperRepository;
use Symfony\Component\AssetMapper\Command\AssetMapperCompileCommand;
use Symfony\Component\AssetMapper\Command\ImportMapAuditCommand;
use Symfony\Component\AssetMapper\Command\DebugAssetMapperCommand;
use Symfony\Component\AssetMapper\Command\ImportMapInstallCommand;
use Symfony\Component\AssetMapper\Command\ImportMapRemoveCommand;
Expand All @@ -27,6 +28,7 @@
use Symfony\Component\AssetMapper\Compiler\SourceMappingUrlsCompiler;
use Symfony\Component\AssetMapper\Factory\CachedMappedAssetFactory;
use Symfony\Component\AssetMapper\Factory\MappedAssetFactory;
use Symfony\Component\AssetMapper\ImportMap\ImportMapAuditor;
use Symfony\Component\AssetMapper\ImportMap\ImportMapConfigReader;
use Symfony\Component\AssetMapper\ImportMap\ImportMapManager;
use Symfony\Component\AssetMapper\ImportMap\ImportMapRenderer;
Expand Down Expand Up @@ -193,6 +195,13 @@
abstract_arg('script HTML attributes'),
])

->set('asset_mapper.importmap.auditor', ImportMapAuditor::class)
->args([
service('asset_mapper.importmap.config_reader'),
service('asset_mapper.importmap.resolver'),
service('http_client'),
])

->set('asset_mapper.importmap.command.require', ImportMapRequireCommand::class)
->args([
service('asset_mapper.importmap.manager'),
Expand All @@ -212,5 +221,9 @@
->set('asset_mapper.importmap.command.install', ImportMapInstallCommand::class)
->args([service('asset_mapper.importmap.manager')])
->tag('console.command')

->set('asset_mapper.importmap.command.audit', ImportMapAuditCommand::class)
->args([service('asset_mapper.importmap.auditor')])
->tag('console.command')
;
};
187 changes: 187 additions & 0 deletions src/Symfony/Component/AssetMapper/Command/ImportMapAuditCommand.php
8000
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 <fabien@symfony.com>
*
* 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 src/Symfony/Component/AssetMapper/ImportMap/ImportMapAuditor.php
F438
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 <fabien@symfony.com>
*
* 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 [];
}

/** @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;
}
}

return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)));
}
Expand All @@ -57,6 +57,7 @@ public function getEntries(): ImportMapEntries
isDownloaded: isset($data['downloaded_to']),
type: $type,
isEntrypoint: $isEntry,
version: $data['version'] ?? null,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

version needs to be written also if it's not null in writeEntries().

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure. it's done.

));
}

Expand All @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public function __construct(
public readonly bool $isDownloaded = false,
public readonly ImportMapType $type = ImportMapType::JS,
public readonly bool $isEntrypoint = false,
public readonly ?string $version = null,
) {
}

Expand Down
Loading
0