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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
|
<?php
namespace MediaWiki\Rest;
use HttpStatus;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\MainConfigNames;
use MediaWiki\MainConfigSchema;
use MediaWiki\Permissions\Authority;
use MediaWiki\Rest\BasicAccess\BasicAuthorizerInterface;
use MediaWiki\Rest\Module\ExtraRoutesModule;
use MediaWiki\Rest\Module\Module;
use MediaWiki\Rest\Module\SpecBasedModule;
use MediaWiki\Rest\PathTemplateMatcher\ModuleConfigurationException;
use MediaWiki\Rest\Reporter\ErrorReporter;
use MediaWiki\Rest\Validator\Validator;
use MediaWiki\Session\Session;
use Throwable;
use Wikimedia\Message\MessageValue;
use Wikimedia\ObjectCache\BagOStuff;
use Wikimedia\ObjectFactory\ObjectFactory;
use Wikimedia\Stats\StatsFactory;
/**
* The REST router is responsible for gathering module configuration, matching
* an input path against the defined modules, and constructing
* and executing the relevant module for a request.
*/
class Router {
private const PREFIX_PATTERN = '!^/([-_.\w]+(?:/v\d+)?)(/.*)$!';
/** @var string[] */
private $routeFiles;
/** @var array[] */
private $extraRoutes;
/** @var null|array[] */
private $moduleMap = null;
/** @var Module[] */
private $modules = [];
/** @var int[]|null */
private $moduleFileTimestamps = null;
/** @var string */
private $baseUrl;
/** @var string */
private $privateBaseUrl;
/** @var string */
private $rootPath;
/** @var string */
private $scriptPath;
/** @var string|null */
private $configHash = null;
/** @var CorsUtils|null */
private $cors;
private BagOStuff $cacheBag;
private ResponseFactory $responseFactory;
private BasicAuthorizerInterface $basicAuth;
private Authority $authority;
private ObjectFactory $objectFactory;
private Validator $restValidator;
private ErrorReporter $errorReporter;
private HookContainer $hookContainer;
private Session $session;
/** @var ?StatsFactory */
private $stats = null;
/**
* @internal
*/
public const CONSTRUCTOR_OPTIONS = [
MainConfigNames::CanonicalServer,
MainConfigNames::InternalServer,
MainConfigNames::RestPath,
MainConfigNames::ScriptPath,
];
/**
* @param string[] $routeFiles
* @param array[] $extraRoutes
* @param ServiceOptions $options
* @param BagOStuff $cacheBag A cache in which to store the matcher trees
* @param ResponseFactory $responseFactory
* @param BasicAuthorizerInterface $basicAuth
* @param Authority $authority
* @param ObjectFactory $objectFactory
* @param Validator $restValidator
* @param ErrorReporter $errorReporter
* @param HookContainer $hookContainer
* @param Session $session
* @internal
*/
public function __construct(
array $routeFiles,
array $extraRoutes,
ServiceOptions $options,
BagOStuff $cacheBag,
ResponseFactory $responseFactory,
BasicAuthorizerInterface $basicAuth,
Authority $authority,
ObjectFactory $objectFactory,
Validator $restValidator,
ErrorReporter $errorReporter,
HookContainer $hookContainer,
Session $session
) {
$options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
$this->routeFiles = $routeFiles;
$this->extraRoutes = $extraRoutes;
$this->baseUrl = $options->get( MainConfigNames::CanonicalServer );
$this->privateBaseUrl = $options->get( MainConfigNames::InternalServer );
$this->rootPath = $options->get( MainConfigNames::RestPath );
$this->scriptPath = $options->get( MainConfigNames::ScriptPath );
$this->cacheBag = $cacheBag;
$this->responseFactory = $responseFactory;
$this->basicAuth = $basicAuth;
$this->authority = $authority;
$this->objectFactory = $objectFactory;
$this->restValidator = $restValidator;
$this->errorReporter = $errorReporter;
$this->hookContainer = $hookContainer;
$this->session = $session;
}
/**
* Remove the REST path prefix. Return the part of the path with the
* prefix removed, or false if the prefix did not match.
* Both the $this->rootPath and the default REST path are accepted,
* so on a site that uses /api as the RestPath, requests to /w/rest.php
* still work. This is equivalent to supporting both /wiki and /w/index.php
* for page views.
*
* @param string $path
* @return false|string
*/
private function getRelativePath( $path ) {
$allowed = [
$this->rootPath,
MainConfigSchema::getDefaultRestPath( $this->scriptPath )
];
foreach ( $allowed as $prefix ) {
if ( str_starts_with( $path, $prefix ) ) {
return substr( $path, strlen( $prefix ) );
}
}
return false;
}
/**
* @param string $fullPath
*
* @return string[] [ string $module, string $path ]
*/
private function splitPath( string $fullPath ): array {
$pathWithModule = $this->getRelativePath( $fullPath );
if ( $pathWithModule === false ) {
throw new LocalizedHttpException(
( new MessageValue( 'rest-prefix-mismatch' ) )
->plaintextParams( $fullPath, $this->rootPath ),
404
);
}
if ( preg_match( self::PREFIX_PATTERN, $pathWithModule, $matches ) ) {
[ , $module, $pathUnderModule ] = $matches;
} else {
// No prefix found in the given path, assume prefix-less module.
$module = '';
$pathUnderModule = $pathWithModule;
}
if ( $module !== '' && !$this->getModuleInfo( $module ) ) {
// Prefix doesn't match any module, try the prefix-less module...
// TODO: At some point in the future, we'll want to warn and redirect...
$module = '';
$pathUnderModule = $pathWithModule;
}
return [ $module, $pathUnderModule ];
}
/**
* Get the cache data, or false if it is missing or invalid
*
* @return ?array
*/
private function fetchCachedModuleMap(): ?array {
$moduleMapCacheKey = $this->getModuleMapCacheKey();
$cacheData = $this->cacheBag->get( $moduleMapCacheKey );
if ( $cacheData && $cacheData[Module::CACHE_CONFIG_HASH_KEY] === $this->getModuleMapHash() ) {
unset( $cacheData[Module::CACHE_CONFIG_HASH_KEY] );
return $cacheData;
} else {
return null;
}
}
private function fetchCachedModuleData( string $module ): ?array {
$moduleDataCacheKey = $this->getModuleDataCacheKey( $module );
$cacheData = $this->cacheBag->get( $moduleDataCacheKey );
return $cacheData ?: null;
}
private function cacheModuleMap( array $map ) {
$map[Module::CACHE_CONFIG_HASH_KEY] = $this->getModuleMapHash();
$moduleMapCacheKey = $this->getModuleMapCacheKey();
$this->cacheBag->set( $moduleMapCacheKey, $map );
}
private function cacheModuleData( string $module, array $map ) {
$moduleDataCacheKey = $this->getModuleDataCacheKey( $module );
$this->cacheBag->set( $moduleDataCacheKey, $map );
}
private function getModuleDataCacheKey( string $module ): string {
if ( $module === '' ) {
// Proper key for the prefix-less module.
$module = '-';
}
return $this->cacheBag->makeKey( __CLASS__, 'module', $module );
}
private function getModuleMapCacheKey(): string {
return $this->cacheBag->makeKey( __CLASS__, 'map', '1' );
}
/**
* Get a config version hash for cache invalidation
*/
private function getModuleMapHash(): string {
if ( $this->configHash === null ) {
$this->configHash = md5( json_encode( [
$this->extraRoutes,
$this->getModuleFileTimestamps()
] ) );
}
return $this->configHash;
}
private function buildModuleMap(): array {
$modules = [];
$noPrefixFiles = [];
$id = ''; // should not be used, make Phan happy
foreach ( $this->routeFiles as $file ) {
// NOTE: we end up loading the file here (for the meta-data) as well
// as in the Module object (for the routes). But since we have
// caching on both levels, that shouldn't matter.
$spec = Module::loadJsonFile( $file );
if ( isset( $spec['mwapi'] ) || isset( $spec['moduleId'] ) || isset( $spec['routes'] ) ) {
// OpenAPI 3, with some extras like the "module" field
if ( !isset( $spec['moduleId'] ) ) {
throw new ModuleConfigurationException(
"Missing 'moduleId' field in $file"
);
}
$id = $spec['moduleId'];
$moduleInfo = [
'class' => SpecBasedModule::class,
'pathPrefix' => $id,
'specFile' => $file
];
} else {
// Old-style route file containing a flat list of routes.
$noPrefixFiles[] = $file;
$moduleInfo = null;
}
if ( $moduleInfo ) {
if ( isset( $modules[$id] ) ) {
$otherFiles = implode( ' and ', $modules[$id]['routeFiles'] );
throw new ModuleConfigurationException(
"Duplicate module $id in $file, also used in $otherFiles"
);
}
$modules[$id] = $moduleInfo;
}
}
// The prefix-less module will be used when no prefix is matched.
// It provides a mechanism to integrate extra routes and route files
// registered by extensions.
if ( $noPrefixFiles || $this->extraRoutes ) {
$modules[''] = [
'class' => ExtraRoutesModule::class,
'pathPrefix' => '',
'routeFiles' => $noPrefixFiles,
'extraRoutes' => $this->extraRoutes,
];
}
return $modules;
}
/**
* Get an array of last modification times of the defined route files.
*
* @return int[] Last modification times
*/
private function getModuleFileTimestamps() {
if ( $this->moduleFileTimestamps === null ) {
$this->moduleFileTimestamps = [];
foreach ( $this->routeFiles as $fileName ) {
$this->moduleFileTimestamps[$fileName] = filemtime( $fileName );
}
}
return $this->moduleFileTimestamps;
}
private function getModuleMap(): array {
if ( !$this->moduleMap ) {
$map = $this->fetchCachedModuleMap();
if ( !$map ) {
$map = $this->buildModuleMap();
$this->cacheModuleMap( $map );
}
$this->moduleMap = $map;
}
return $this->moduleMap;
}
private function getModuleInfo( $module ): ?array {
$map = $this->getModuleMap();
return $map[$module] ?? null;
}
/**
* @return string[]
*/
public function getModuleIds(): array {
return array_keys( $this->getModuleMap() );
}
public function getModuleForPath( string $fullPath ): ?Module {
[ $moduleName, ] = $this->splitPath( $fullPath );
return $this->getModule( $moduleName );
}
public function getModule( string $name ): ?Module {
if ( isset( $this->modules[$name] ) ) {
return $this->modules[$name];
}
$info = $this->getModuleInfo( $name );
if ( !$info ) {
return null;
}
$module = $this->instantiateModule( $info, $name );
$cacheData = $this->fetchCachedModuleData( $name );
if ( $cacheData !== null ) {
$cacheOk = $module->initFromCacheData( $cacheData );
} else {
$cacheOk = false;
}
if ( !$cacheOk ) {
$cacheData = $module->getCacheData();
$this->cacheModuleData( $name, $cacheData );
}
if ( $this->cors ) {
$module->setCors( $this->cors );
}
if ( $this->stats ) {
$module->setStats( $this->stats );
}
$this->modules[$name] = $module;
return $module;
}
/**
* @since 1.42
*/
public function getRoutePath(
string $routeWithModulePrefix,
array $pathParams = [],
array $queryParams = []
): string {
$routeWithModulePrefix = $this->substPathParams( $routeWithModulePrefix, $pathParams );
$path = $this->rootPath . $routeWithModulePrefix;
return wfAppendQuery( $path, $queryParams );
}
public function getRouteUrl(
string $routeWithModulePrefix,
array $pathParams = [],
array $queryParams = []
): string {
return $this->baseUrl . $this->getRoutePath( $routeWithModulePrefix, $pathParams, $queryParams );
}
public function getPrivateRouteUrl(
string $routeWithModulePrefix,
array $pathParams = [],
array $queryParams = []
): string {
return $this->privateBaseUrl . $this->getRoutePath( $routeWithModulePrefix, $pathParams, $queryParams );
}
/**
* @param string $route
* @param array $pathParams
*
* @return string
*/
protected function substPathParams( string $route, array $pathParams ): string {
foreach ( $pathParams as $param => $value ) {
// NOTE: we use rawurlencode here, since execute() uses rawurldecode().
// Spaces in path params must be encoded to %20 (not +).
// Slashes must be encoded as %2F.
$route = str_replace( '{' . $param . '}', rawurlencode( (string)$value ), $route );
}
return $route;
}
public function execute( RequestInterface $request ): ResponseInterface {
try {
$fullPath = $request->getUri()->getPath();
$response = $this->doExecute( $fullPath, $request );
} catch ( HttpException $e ) {
$extraData = [];
if ( $this->isRestbaseCompatEnabled( $request )
&& $e instanceof LocalizedHttpException
) {
$extraData = $this->getRestbaseCompatErrorData( $request, $e );
}
$response = $this->responseFactory->createFromException( $e, $extraData );
} catch ( Throwable $e ) {
$this->errorReporter->reportError( $e, null, $request );
$response = $this->responseFactory->createFromException( $e );
}
// TODO: Only send the vary header for handlers that opt into
// restbase compat!
$this->varyOnRestbaseCompat( $response );
return $response;
}
private function doExecute( string $fullPath, RequestInterface $request ): ResponseInterface {
[ $modulePrefix, $path ] = $this->splitPath( $fullPath );
// If there is no path at all, redirect to "/".
// That's the minimal path that can be routed.
if ( $modulePrefix === '' && $path === '' ) {
$target = $this->getRoutePath( '/' );
return $this->responseFactory->createRedirect( $target, 308 );
}
$module = $this->getModule( $modulePrefix );
if ( !$module ) {
throw new LocalizedHttpException(
MessageValue::new( 'rest-unknown-module' )->plaintextParams( $modulePrefix ),
404,
[ 'prefix' => $modulePrefix ]
);
}
return $module->execute( $path, $request );
}
/**
* Prepare the handler by injecting relevant service objects and state
* into $handler.
*
* @internal
*/
public function prepareHandler( Handler $handler ) {
// Injecting services in the Router class means we don't have to inject
// them into each Module.
$handler->initServices(
$this->authority,
$this->responseFactory,
$this->hookContainer
);
$handler->initSession( $this->session );
}
/**
* @param CorsUtils $cors
* @return self
*/
public function setCors( CorsUtils $cors ): self {
$this->cors = $cors;
return $this;
}
/**
* @internal
*
* @param StatsFactory $stats
*
* @return self
*/
public function setStats( StatsFactory $stats ): self {
$this->stats = $stats;
return $this;
}
/**
* @param array $info
* @param string $name
*/
private function instantiateModule( array $info, string $name ): Module {
if ( $info['class'] === SpecBasedModule::class ) {
$module = new SpecBasedModule(
$info['specFile'],
$this,
$info['pathPrefix'] ?? $name,
$this->responseFactory,
$this->basicAuth,
$this->objectFactory,
$this->restValidator,
$this->errorReporter
);
} else {
$module = new ExtraRoutesModule(
$info['routeFiles'] ?? [],
$info['extraRoutes'] ?? [],
$this,
$this->responseFactory,
$this->basicAuth,
$this->objectFactory,
$this->restValidator,
$this->errorReporter
);
}
return $module;
}
/**
* @internal
*
* @return bool
*/
public function isRestbaseCompatEnabled( RequestInterface $request ): bool {
// See T374136
return $request->getHeaderLine( 'x-restbase-compat' ) === 'true';
}
private function varyOnRestbaseCompat( ResponseInterface $response ) {
// See T374136
$response->addHeader( 'Vary', 'x-restbase-compat' );
}
/**
* @internal
*
* @return array
*/
public function getRestbaseCompatErrorData( RequestInterface $request, LocalizedHttpException $e ): array {
$msg = $e->getMessageValue();
// Match error fields emitted by the RESTBase endpoints.
// EntryPoint::getTextFormatters() ensures 'en' is always available.
return [
'type' => "MediaWikiError/" .
str_replace( ' ', '_', HttpStatus::getMessage( $e->getCode() ) ),
'title' => $msg->getKey(),
'method' => strtolower( $request->getMethod() ),
'detail' => $this->responseFactory->getFormattedMessage( $msg, 'en' ),
'uri' => (string)$request->getUri()
];
}
}
|