Debian Codegraph @

includes/ResourceLoader/ForeignResourceManager.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\ResourceLoader;
22
23 use Composer\Spdx\SpdxLicenses;
24 use LogicException;
25 use MediaWiki\MainConfigNames;
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\Message\Message;
28 use PharData;
29 use RecursiveDirectoryIterator;
30 use RecursiveIteratorIterator;
31 use SplFileInfo;
32 use Symfony\Component\Yaml\Yaml;
33 use Wikimedia\UUID\GlobalIdGenerator;
34
35 /**
36 * Manage foreign resources registered with ResourceLoader.
37 *
38 * @since 1.32
39 * @ingroup ResourceLoader
40 * @see https://www.mediawiki.org/wiki/Foreign_resources
41 */
42 class ForeignResourceManager {
43 /** @var string */
44 private $defaultAlgo = 'sha384';
45
46 /** @var bool */
47 private $hasErrors = false;
48
49 /** @var string */
50 private $registryFile;
51
52 /** @var string */
53 private $libDir;
54
55 /** @var string */
56 private $tmpParentDir;
57
58 /** @var string */
59 private $cacheDir;
60
61 /**
62 * @var callable|Closure
63 * @phan-var callable(string):void
64 */
65 private $infoPrinter;
66
67 /**
68 * @var callable|Closure
69 * @phan-var callable(string):void
70 */
71 private $errorPrinter;
72 /**
73 * @var callable|Closure
74 * @phan-var callable(string):void
75 */
76 private $verbosePrinter;
77
78 /** @var string */
79 private $action;
80
81 /** @var array[] */
82 private $registry;
83
84 private GlobalIdGenerator $globalIdGenerator;
85
86 /**
87 * @param string $registryFile Path to YAML file
88 * @param string $libDir Path to a modules directory
89 * @param callable|null $infoPrinter Callback for printing info about the run.
90 * @param callable|null $errorPrinter Callback for printing errors from the run.
91 * @param callable|null $verbosePrinter Callback for printing extra verbose
92 * progress information from the run.
93 */
94 public function __construct(
95 $registryFile,
96 $libDir,
97 ?callable $infoPrinter = null,
98 ?callable $errorPrinter = null,
99 ?callable $verbosePrinter = null
100 ) {
101 $this->globalIdGenerator = MediaWikiServices::getInstance()->getGlobalIdGenerator();
102 $this->registryFile = $registryFile;
103 $this->libDir = $libDir;
104 $this->infoPrinter = $infoPrinter ?? static function ( $_ ) {
105 };
106 $this->errorPrinter = $errorPrinter ?? $this->infoPrinter;
107 $this->verbosePrinter = $verbosePrinter ?? static function ( $_ ) {
108 };
109
110 // Support XDG_CACHE_HOME to speed up CI by avoiding repeated downloads.
111 $cacheHome = getenv( 'XDG_CACHE_HOME' );
112 if ( $cacheHome !== false ) {
113 $this->cacheDir = realpath( $cacheHome ) . '/mw-foreign';
114 } else {
115 $conf = MediaWikiServices::getInstance()->getMainConfig();
116 $cacheConf = $conf->get( MainConfigNames::CacheDirectory );
117 if ( $cacheConf !== false ) {
118 $this->cacheDir = "$cacheConf/ForeignResourceManager";
119 } else {
120 $this->cacheDir = "{$this->libDir}/.foreign/cache";
121 }
122 }
123 }
124
125 /**
126 * @param string $action
127 * @param string $module
128 * @return bool
129 * @throws LogicException
130 */
131 public function run( $action, $module ) {
132 $actions = [ 'update', 'verify', 'make-sri', 'make-cdx' ];
133 if ( !in_array( $action, $actions ) ) {
134 $this->error( "Invalid action.\n\nMust be one of " . implode( ', ', $actions ) . '.' );
135 return false;
136 }
137 $this->action = $action;
138 $this->setupTempDir( $action );
139
140 $this->registry = Yaml::parseFile( $this->registryFile );
141 if ( $module === 'all' ) {
142 $modules = $this->registry;
143 } elseif ( isset( $this->registry[$module] ) ) {
144 $modules = [ $module => $this->registry[$module] ];
145 } else {
146 $this->error( "Unknown module name.\n\nMust be one of:\n" .
147 wordwrap( implode( ', ', array_keys( $this->registry ) ), 80 ) .
148 '.'
149 );
150 return false;
151 }
152
153 if ( $this->action === 'make-cdx' ) {
154 $cdxFile = $this->getCdxFileLocation();
155 $cdxJson = json_encode(
156 $this->generateCdxForModules( $modules ),
157 JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
158 );
159 file_put_contents( $cdxFile, $cdxJson );
160 $this->output( "Created CycloneDX file at $cdxFile\n" );
161 return true;
162 }
163
164 foreach ( $modules as $moduleName => $info ) {
165 $this->verbose( "\n### {$moduleName}\n\n" );
166
167 if ( $this->action === 'update' ) {
168 $this->output( "... updating '{$moduleName}'\n" );
169 } elseif ( $this->action === 'verify' ) {
170 $this->output( "... verifying '{$moduleName}'\n" );
171 } else {
172 $this->output( "... checking '{$moduleName}'\n" );
173 }
174
175 // Do checks on yaml content (such as license existence, validity and type keys)
176 // before doing any potentially destructive actions (potentially deleting directories,
177 // depending on action.
178
179 if ( !isset( $info['type'] ) ) {
180 throw new LogicException( "Module '$moduleName' must have a 'type' key." );
181 }
182
183 $this->validateLicense( $moduleName, $info );
184
185 if ( $info['type'] === 'doc-only' ) {
186 $this->output( "... {$moduleName} is documentation-only, skipping integrity checks.\n" );
187 continue;
188 }
189
190 $destDir = "{$this->libDir}/$moduleName";
191
192 if ( $this->action === 'update' ) {
193 $this->verbose( "... emptying directory for $moduleName\n" );
194 wfRecursiveRemoveDir( $destDir );
195 }
196
197 $this->verbose( "... preparing {$this->tmpParentDir}\n" );
198 wfRecursiveRemoveDir( $this->tmpParentDir );
199 if ( !wfMkdirParents( $this->tmpParentDir ) ) {
200 throw new LogicException( "Unable to create {$this->tmpParentDir}" );
201 }
202
203 switch ( $info['type'] ) {
204 case 'tar':
205 case 'zip':
206 $this->handleTypeTar( $moduleName, $destDir, $info, $info['type'] );
207 break;
208 case 'file':
209 $this->handleTypeFile( $moduleName, $destDir, $info );
210 break;
211 case 'multi-file':
212 $this->handleTypeMultiFile( $moduleName, $destDir, $info );
213 break;
214 default:
215 throw new LogicException( "Unknown type '{$info['type']}' for '$moduleName'" );
216 }
217 }
218
219 $this->cleanUp();
220 if ( $this->hasErrors ) {
221 // The "verify" action should check all modules and files and fail after, not during.
222 // We don't throw on the first issue so that developers enjoy access to all actionable
223 // information at once (given we can't have cascading errors).
224 // The "verify" action prints errors along the way and simply exits here.
225 return false;
226 }
227
228 return true;
229 }
230
231 /**
232 * Returns a JSON string describing the foreign resources in a CycloneDX format.
233 */
234 public function generateCdx(): string {
235 $this->registry = Yaml::parseFile( $this->registryFile );
236 return json_encode(
237 $this->generateCdxForModules( $this->registry ),
238 JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
239 );
240 }
241
242 /**
243 * Get the path to the CycloneDX file that describes the foreign resources.
244 */
245 public function getCdxFileLocation(): string {
246 return "$this->libDir/foreign-resources.cdx.json";
247 }
248
249 /**
250 * Choose the temp parent directory
251 *
252 * @param string $action
253 */
254 private function setupTempDir( $action ) {
255 if ( $action === 'verify' ) {
256 $this->tmpParentDir = wfTempDir() . '/ForeignResourceManager';
257 } else {
258 // Use a temporary directory under the destination directory instead
259 // of wfTempDir() because PHP's rename() does not work across file
260 // systems, and the user's /tmp and $IP may be on different filesystems.
261 $this->tmpParentDir = "{$this->libDir}/.foreign/tmp";
262 }
263 }
264
265 /**
266 * @param string $src
267 * @param string $integrity
268 * @param string $moduleName
269 * @return string
270 */
271 private function cacheKey( $src, $integrity, $moduleName ) {
272 $key = $moduleName
273 . '_' . hash( 'fnv132', $integrity )
274 . '_' . hash( 'fnv132', $src )
275 // Append readable filename to aid cache inspection and debugging
276 . '_' . basename( $src );
277 $key = preg_replace( '/[.\/+?=_-]+/', '_', $key );
278 return rtrim( $key, '_' );
279 }
280
281 /**
282 * @param string $key
283 * @return string|false
284 */
285 private function cacheGet( $key ) {
286 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
287 return @file_get_contents( "{$this->cacheDir}/$key.data" );
288 }
289
290 /**
291 * @param string $key
292 * @param mixed $data
293 */
294 private function cacheSet( $key, $data ) {
295 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
296 @mkdir( $this->cacheDir, 0777, true );
297 file_put_contents( "{$this->cacheDir}/$key.data", $data, LOCK_EX );
298 }
299
300 /**
301 * @param string $src
302 * @param string|null $integrity
303 * @param string $moduleName
304 * @return string
305 */
306 private function fetch( string $src, $integrity, string $moduleName ) {
307 if ( $integrity !== null ) {
308 $key = $this->cacheKey( $src, $integrity, $moduleName );
309 $data = $this->cacheGet( $key );
310 if ( $data ) {
311 return $data;
312 }
313 }
314
315 $services = MediaWikiServices::getInstance();
316 $req = $services->getHttpRequestFactory()
317 ->create( $src, [ 'method' => 'GET', 'followRedirects' => false ], __METHOD__ );
318 $reqStatusValue = $req->execute();
319 if ( !$reqStatusValue->isOK() ) {
320 $message = "Failed to download resource at {$src}";
321 $reqError = $reqStatusValue->getMessages( 'error' )[0] ?? null;
322 if ( $reqError !== null ) {
323 $message .= ': ' . Message::newFromSpecifier( $reqError )->inLanguage( 'en' )->plain();
324 }
325 throw new ForeignResourceNetworkException( $message );
326 }
327 if ( $req->getStatus() !== 200 ) {
328 throw new ForeignResourceNetworkException( "Unexpected HTTP {$req->getStatus()} response from {$src}" );
329 }
330 $data = $req->getContent();
331 $algo = $integrity === null ? $this->defaultAlgo : explode( '-', $integrity )[0];
332 $actualIntegrity = $algo . '-' . base64_encode( hash( $algo, $data, true ) );
333 if ( $integrity === $actualIntegrity ) {
334 $this->verbose( "... passed integrity check for {$src}\n" );
335 $key = $this->cacheKey( $src, $actualIntegrity, $moduleName );
336 $this->cacheSet( $key, $data );
337 } elseif ( $this->action === 'make-sri' ) {
338 $this->output( "Integrity for {$src}\n\tintegrity: {$actualIntegrity}\n" );
339 } else {
340 $expectedIntegrity = $integrity ?? 'null';
341 throw new ForeignResourceNetworkException( "Integrity check failed for {$src}\n" .
342 "\tExpected: {$expectedIntegrity}\n" .
343 "\tActual: {$actualIntegrity}"
344 );
345 }
346 return $data;
347 }
348
349 /**
350 * @param string $moduleName
351 * @param string $destDir
352 * @param array $info
353 */
354 private function handleTypeFile( $moduleName, $destDir, array $info ) {
355 if ( !isset( $info['src'] ) ) {
356 throw new LogicException( "Module '$moduleName' must have a 'src' key." );
357 }
358 $data = $this->fetch( $info['src'], $info['integrity'] ?? null, $moduleName );
359 $dest = $info['dest'] ?? basename( $info['src'] );
360 $path = "$destDir/$dest";
361 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
362 $this->error( "File for '$moduleName' is different.\n" );
363 }
364 if ( $this->action === 'update' ) {
365 wfMkdirParents( $destDir );
366 file_put_contents( "$destDir/$dest", $data );
367 }
368 }
369
370 /**
371 * @param string $moduleName
372 * @param string $destDir
373 * @param array $info
374 */
375 private function handleTypeMultiFile( $moduleName, $destDir, array $info ) {
376 if ( !isset( $info['files'] ) ) {
377 throw new LogicException( "Module '$moduleName' must have a 'files' key." );
378 }
379 foreach ( $info['files'] as $dest => $file ) {
380 if ( !isset( $file['src'] ) ) {
381 throw new LogicException( "Module '$moduleName' file '$dest' must have a 'src' key." );
382 }
383 $data = $this->fetch( $file['src'], $file['integrity'] ?? null, $moduleName );
384 $path = "$destDir/$dest";
385 if ( $this->action === 'verify' && sha1_file( $path ) !== sha1( $data ) ) {
386 $this->error( "File '$dest' for '$moduleName' is different.\n" );
387 } elseif ( $this->action === 'update' ) {
388 wfMkdirParents( $destDir );
389 file_put_contents( "$destDir/$dest", $data );
390 }
391 }
392 }
393
394 /**
395 * @param string $moduleName
396 * @param string $destDir
397 * @param array $info
398 * @param string $fileType
399 */
400 private function handleTypeTar( $moduleName, $destDir, array $info, string $fileType ) {
401 $info += [ 'src' => null, 'integrity' => null, 'dest' => null ];
402 if ( $info['src'] === null ) {
403 throw new LogicException( "Module '$moduleName' must have a 'src' key." );
404 }
405 // Download the resource to a temporary file and open it
406 $data = $this->fetch( $info['src'], $info['integrity'], $moduleName );
407 $tmpFile = "{$this->tmpParentDir}/$moduleName." . $fileType;
408 $this->verbose( "... writing '$moduleName' src to $tmpFile\n" );
409 file_put_contents( $tmpFile, $data );
410 $p = new PharData( $tmpFile );
411 $tmpDir = "{$this->tmpParentDir}/$moduleName";
412 $p->extractTo( $tmpDir );
413 unset( $data, $p );
414
415 if ( $info['dest'] === null ) {
416 // Default: Replace the entire directory
417 $toCopy = [ $tmpDir => $destDir ];
418 } else {
419 // Expand and normalise the 'dest' entries
420 $toCopy = [];
421 foreach ( $info['dest'] as $fromSubPath => $toSubPath ) {
422 // Use glob() to expand wildcards and check existence
423 $fromPaths = glob( "{$tmpDir}/{$fromSubPath}", GLOB_BRACE );
424 if ( !$fromPaths ) {
425 throw new LogicException( "Path '$fromSubPath' of '$moduleName' not found." );
426 }
427 foreach ( $fromPaths as $fromPath ) {
428 $toCopy[$fromPath] = $toSubPath === null
429 ? "$destDir/" . basename( $fromPath )
430 : "$destDir/$toSubPath/" . basename( $fromPath );
431 }
432 }
433 }
434 foreach ( $toCopy as $from => $to ) {
435 if ( $this->action === 'verify' ) {
436 $this->verbose( "... verifying $to\n" );
437 if ( is_dir( $from ) ) {
438 $rii = new RecursiveIteratorIterator( new RecursiveDirectoryIterator(
439 $from,
440 RecursiveDirectoryIterator::SKIP_DOTS
441 ) );
442 /** @var SplFileInfo $file */
443 foreach ( $rii as $file ) {
444 $remote = $file->getPathname();
445 $local = strtr( $remote, [ $from => $to ] );
446 if ( sha1_file( $remote ) !== sha1_file( $local ) ) {
447 $this->error( "File '$local' is different.\n" );
448 }
449 }
450 } elseif ( sha1_file( $from ) !== sha1_file( $to ) ) {
451 $this->error( "File '$to' is different.\n" );
452 }
453 } elseif ( $this->action === 'update' ) {
454 $this->verbose( "... moving $from to $to\n" );
455 wfMkdirParents( dirname( $to ) );
456 if ( !rename( $from, $to ) ) {
457 throw new LogicException( "Could not move $from to $to." );
458 }
459 }
460 }
461 }
462
463 /**
464 * @param string $text
465 */
466 private function verbose( $text ) {
467 ( $this->verbosePrinter )( $text );
468 }
469
470 /**
471 * @param string $text
472 */
473 private function output( $text ) {
474 ( $this->infoPrinter )( $text );
475 }
476
477 /**
478 * @param string $text
479 */
480 private function error( $text ) {
481 $this->hasErrors = true;
482 ( $this->errorPrinter )( $text );
483 }
484
485 private function cleanUp() {
486 wfRecursiveRemoveDir( $this->tmpParentDir );
487
488 // Prune the cache of files we don't recognise.
489 $knownKeys = [];
490 foreach ( $this->registry as $module => $info ) {
491 if ( $info['type'] === 'file' || $info['type'] === 'tar' ) {
492 $knownKeys[] = $this->cacheKey( $info['src'], $info['integrity'], $module );
493 } elseif ( $info['type'] === 'multi-file' ) {
494 foreach ( $info['files'] as $file ) {
495 $knownKeys[] = $this->cacheKey( $file['src'], $file['integrity'], $module );
496 }
497 }
498 }
499 foreach ( glob( "{$this->cacheDir}/*" ) as $cacheFile ) {
500 if ( !in_array( basename( $cacheFile, '.data' ), $knownKeys ) ) {
501 unlink( $cacheFile );
502 }
503 }
504 }
505
506 /**
507 * @param string $moduleName
508 * @param array $info
509 */
510 private function validateLicense( $moduleName, $info ) {
511 if ( !isset( $info['license'] ) || !is_string( $info['license'] ) ) {
512 throw new LogicException(
513 "Module '$moduleName' needs a valid SPDX license; no license is currently present"
514 );
515 }
516 $licenses = new SpdxLicenses();
517 if ( !$licenses->validate( $info['license'] ) ) {
518 $this->error(
519 "Module '$moduleName' has an invalid SPDX license identifier '{$info['license']}', "
520 . "see <https://spdx.org/licenses/>.\n"
521 );
522 }
523 }
524
525 private function generateCdxForModules( array $modules ): array {
526 $cdx = [
527 '$schema' => 'http://cyclonedx.org/schema/bom-1.6.schema.json',
528 'bomFormat' => 'CycloneDX',
529 'specVersion' => '1.6',
530 'serialNumber' => 'urn:uuid:' . $this->globalIdGenerator->newUUIDv4(),
531 'version' => 1,
532 'components' => [],
533 ];
534 foreach ( $modules as $moduleName => $module ) {
535 $moduleCdx = [
536 'type' => 'library',
537 'name' => $moduleName,
538 'version' => $module['version'],
539 ];
540 if ( preg_match( '/ (AND|OR|WITH) /', $module['license'] ) ) {
541 $moduleCdx['licenses'][] = [ 'expression' => $module['license'] ];
542 } else {
543 $moduleCdx['licenses'][] = [ 'license' => [ 'id' => $module['license'] ] ];
544 }
545 if ( $module['purl'] ?? false ) {
546 $moduleCdx['purl'] = $module['purl'];
547 }
548 if ( $module['version'] ?? false ) {
549 $moduleCdx['version'] = $module['version'];
550 }
551 if ( $module['authors'] ?? false ) {
552 $moduleCdx['authors'] = array_map(
553 fn ( $author ) => [ 'name' => $author ],
554 preg_split( '/,( and)? /', $module['authors'] )
555 );
556 }
557 if ( $module['homepage'] ?? false ) {
558 $moduleCdx['externalReferences'] = [ [ 'url' => $module['homepage'], 'type' => 'website' ] ];
559 }
560 $cdx['components'][] = $moduleCdx;
561 }
562 return $cdx;
563 }
564 }
565
566 /** @deprecated class alias since 1.40 */
567 class_alias( ForeignResourceManager::class, 'ForeignResourceManager' );