forked from FriendsOfPHP/security-advisories
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.php
297 lines (234 loc) · 10.9 KB
/
validator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
<?php
// validates that all security advisories are valid
if (!is_file($autoloader = __DIR__.'/vendor/autoload.php')) {
echo "Dependencies are not installed, please run 'composer install' first!\n";
exit(1);
}
require $autoloader;
use Composer\Config;
use Composer\IO\NullIO;
use Composer\Repository\ComposerRepository;
use Composer\Repository\RepositoryInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Helper\TableCell;
use Symfony\Component\Console\Helper\TableSeparator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Parser;
final class Validate extends Command
{
private $parser;
private $composerRepositories = array();
private $composerConfig;
public function __construct()
{
parent::__construct('validate');
$this->parser = new Parser();
$this->composerConfig = new Config(false);
$this->composerConfig->merge(array('config' => array('cache-dir' => sys_get_temp_dir().'/php-security-advisories')));
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$advisoryFilter = function (SplFileInfo $file) {
if ($file->isFile() && __DIR__ === $file->getPath()) {
return false; // We want to skip root files
}
if ($file->isDir()) {
if (__DIR__.DIRECTORY_SEPARATOR.'vendor' === $file->getPathname()) {
return false; // We want to skip the vendor dir
}
$dirName = $file->getFilename();
if ('.' === $dirName[0]) {
return false; // Exclude hidden folders (.git and IDE folders at the root)
}
}
return true; // any other file gets checks and any other folder gets iterated
};
$isAcceptableVersionConstraint = function ($versionString) {
return (bool) preg_match('/^(\\<|\\>)(=){0,1}(([1-9]\d*)|0)(\.(([1-9]\d*)|0))*(-(alpha|beta|rc)[1-9]\d*){0,1}$/', $versionString);
};
$messages = array();
/* @var $dir \SplFileInfo[] */
$dir = new \RecursiveIteratorIterator(new RecursiveCallbackFilterIterator(new \RecursiveDirectoryIterator(__DIR__), $advisoryFilter));
$progress = new ProgressBar($io, count(iterator_to_array($dir)));
$progress->start();
foreach ($dir as $file) {
if (!$file->isFile()) {
$progress->advance();
continue;
}
$path = str_replace(__DIR__.DIRECTORY_SEPARATOR, '', $file->getPathname());
if ('yaml' !== $file->getExtension()) {
$messages[$path][] = 'The file extension should be ".yaml".';
continue;
}
try {
$data = $this->parser->parse(file_get_contents($file));
// validate first level keys
if ($keys = array_diff(array_keys($data), array('reference', 'branches', 'title', 'link', 'cve', 'composer-repository'))) {
foreach ($keys as $key) {
$messages[$path][] = sprintf('Key "%s" is not supported.', $key);
}
}
// required keys
foreach (array('reference', 'title', 'link', 'branches') as $key) {
if (!isset($data[$key])) {
$messages[$path][] = sprintf('Key "%s" is required.', $key);
}
}
if (isset($data['reference'])) {
if (0 !== strpos($data['reference'], 'composer://')) {
$messages[$path][] = 'Reference must start with "composer://"';
} else {
$composerPackage = substr($data['reference'], 11);
if (str_replace(DIRECTORY_SEPARATOR, '/', dirname($path)) !== $composerPackage) {
$messages[$path][] = 'Reference composer package must match the folder name';
}
if (!isset($data['composer-repository'])) {
$data['composer-repository'] = 'https://packagist.org';
}
if (!empty($data['composer-repository'])) {
$composerRepository = $this->getComposerRepository($data['composer-repository']);
$found = false;
foreach ($composerRepository->search($composerPackage, RepositoryInterface::SEARCH_NAME) as $package) {
if ($package['name'] === $composerPackage) {
$found = true;
break;
}
}
if (!$found) {
$messages[$path][] = sprintf('Invalid composer package (not found in repository %s)', $data['composer-repository']);
}
}
}
}
if (!isset($data['branches'])) {
$progress->advance();
continue; // Don't validate branches when not set to avoid notices
}
if (!is_array($data['branches'])) {
$messages[$path][] = '"branches" must be an array.';
$progress->advance();
continue; // Don't validate branches when not set to avoid notices
}
$upperBoundWithoutLowerBound = null;
foreach ($data['branches'] as $name => $branch) {
if (!preg_match('/^([\d\.\-]+(\.x)?(\-dev)?|master)$/', $name)) {
$messages[$path][] = sprintf('Invalid branch name "%s".', $name);
}
if ($keys = array_diff(array_keys($branch), array('time', 'versions'))) {
foreach ($keys as $key) {
$messages[$path][] = sprintf('Key "%s" is not supported for branch "%s".', $key, $name);
}
}
if (!array_key_exists('time', $branch)) {
$messages[$path][] = sprintf('Key "time" is required for branch "%s".', $name);
}
if (!isset($branch['versions'])) {
$messages[$path][] = sprintf('Key "versions" is required for branch "%s".', $name);
} elseif (!is_array($branch['versions'])) {
$messages[$path][] = sprintf('"versions" must be an array for branch "%s".', $name);
} else {
$upperBound = null;
$hasMin = false;
foreach ($branch['versions'] as $version) {
if (!$isAcceptableVersionConstraint($version)) {
$messages[$path][] = sprintf('Version constraint "%s" is not in an acceptable format.', $version);
}
if ('<' === substr($version, 0, 1)) {
$upperBound = $version;
continue;
}
if ('>' === substr($version, 0, 1)) {
$hasMin = true;
}
}
if (null === $upperBound) {
$messages[$path][] = sprintf('"versions" must have an upper bound for branch "%s".', $name);
}
if (!$hasMin && null === $upperBoundWithoutLowerBound) {
$upperBoundWithoutLowerBound = $upperBound;
}
// Branches can omit the lower bound only if their upper bound is the same than for other branches without lower bound.
if (!$hasMin && $upperBoundWithoutLowerBound !== $upperBound) {
$messages[$path][] = sprintf('"versions" must have a lower bound for branch "%s" to avoid overlapping lower branches.', $name);
}
}
}
} catch (ParseException $e) {
$messages[$path][] = sprintf('YAML is not valid (%s).', $e->getMessage());
}
$progress->advance();
}
$progress->finish();
$io->newLine();
if ($messages) {
$io->error(sprintf('Found %s issue%s in %s file%s.',
$issues = array_sum(array_map('count', $messages)),
1 === $issues ? '' : 's', $files = count($messages),
1 === $files ? '' : 's'
));
$table = new Table($io);
$table->setHeaders(array('File', 'Issues'));
$files = array_keys($messages);
$lastFile = array_pop($files);
foreach ($messages as $file => $issues) {
$table->addRow(array(
new TableCell($file, array('rowspan' => count($issues))),
array_shift($issues)
));
foreach ($issues as $issue) {
$table->addRow(array($issue));
}
if ($file !== $lastFile) {
$table->addRow(new TableSeparator());
}
}
$table->render();
} else {
$io->success('No issues found.');
}
return count($messages);
}
private function getComposerRepository($uri)
{
if (!isset($this->composerRepositories[$uri])) {
$repository = new ComposerRepository(
array(
'url' => $uri,
),
new NullIO(),
$this->composerConfig
);
$this->composerRepositories[$uri] = $repository;
}
return $this->composerRepositories[$uri];
}
}
final class Validator extends Application
{
protected function getCommandName(InputInterface $input)
{
return 'validate';
}
protected function getDefaultCommands()
{
$defaultCommands = parent::getDefaultCommands();
$defaultCommands[] = new Validate();
return $defaultCommands;
}
public function getDefinition()
{
$inputDefinition = parent::getDefinition();
$inputDefinition->setArguments();
return $inputDefinition;
}
}
$application = new Validator();
$application->run();