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
|
<?php
use MediaWiki\Context\RequestContext;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\StaticHookRegistry;
use MediaWiki\Language\Language;
use MediaWiki\MediaWikiServices;
use MediaWiki\Message\Message;
use MediaWiki\ParamValidator\TypeDef\ArrayDef;
use MediaWiki\Permissions\SimpleAuthority;
use MediaWiki\Request\WebRequest;
use MediaWiki\Rest\CorsUtils;
use MediaWiki\Rest\EntryPoint;
use MediaWiki\Rest\Handler;
use MediaWiki\Rest\PathTemplateMatcher\PathMatcher;
use MediaWiki\Rest\RequestData;
use MediaWiki\Rest\ResponseFactory;
use MediaWiki\Rest\Router;
use MediaWiki\Rest\Validator\Validator;
use MediaWiki\Session\Session;
use MediaWiki\Tests\Unit\DummyServicesTrait;
use MediaWiki\Title\Title;
use MediaWiki\User\UserIdentityValue;
use Wikimedia\ObjectCache\EmptyBagOStuff;
use Wikimedia\ParamValidator\ParamValidator;
use Wikimedia\Stats\StatsFactory;
use Wikimedia\TestingAccessWrapper;
/**
* Checks that all REST Handlers, core and extensions, conform to the conventions:
* - parameters in path have correct PARAM_SOURCE
* - path parameters not in path are not required
* - do not have inconsistencies in the parameter definitions
*
* @coversNothing
* @group Database
*/
class RestStructureTest extends MediaWikiIntegrationTestCase {
use DummyServicesTrait;
use JsonSchemaAssertionTrait;
private const SPEC_FILES = [
'https://spec.openapis.org/oas/3.0/schema/2021-09-28#' =>
MW_INSTALL_PATH . '/tests/phpunit/integration/includes/' .
'Rest/Handler/data/OpenApi-3.0.json',
'http://json-schema.org/draft-04/schema#' =>
MW_INSTALL_PATH . '/vendor/justinrainbow/json-schema/dist/' .
'schema/json-schema-draft-04.json',
'https://www.mediawiki.org/schema/mwapi-1.0#' =>
MW_INSTALL_PATH . '/docs/rest/mwapi-1.0.json',
'https://www.mediawiki.org/schema/discovery-1.0#' =>
MW_INSTALL_PATH . '/docs/rest/discovery-1.0.json',
];
/** @var ?Router */
private $router = null;
/**
* Constructs a fake MediaWikiServices instance for use in data providers.
*
* @return MediaWikiServices
*/
private function getFakeServiceContainer(): MediaWikiServices {
$realConfig = MediaWikiServices::getInstance()->getMainConfig();
$objectFactory = $this->getDummyObjectFactory();
$hookContainer = new HookContainer(
new StaticHookRegistry(),
$objectFactory
);
$services = $this->createNoOpMock(
MediaWikiServices::class,
[
'getMainConfig',
'getHookContainer',
'getObjectFactory',
'getLocalServerObjectCache',
'getStatsFactory',
]
);
$services->method( 'getMainConfig' )->willReturn( $realConfig );
$services->method( 'getHookContainer' )->willReturn( $hookContainer );
$services->method( 'getObjectFactory' )->willReturn( $objectFactory );
$services->method( 'getLocalServerObjectCache' )->willReturn( new EmptyBagOStuff() );
$services->method( 'getStatsFactory' )->willReturn( StatsFactory::newNull() );
return $services;
}
private function getRouterForDataProviders(): Router {
static $router = null;
if ( !$router ) {
$language = $this->createNoOpMock( Language::class, [ 'getCode' ] );
$language->method( 'getCode' )->willReturn( 'en' );
$title = Title::makeTitle( NS_SPECIAL, 'Badtitle/dummy title for RestStructureTest' );
$authority = new SimpleAuthority( new UserIdentityValue( 0, 'Testor' ), [] );
$request = $this->createNoOpMock( WebRequest::class, [ 'getSession' ] );
$request->method( 'getSession' )->willReturn( $this->createNoOpMock( Session::class ) );
$context = $this->createNoOpMock(
RequestContext::class,
[ 'getLanguage', 'getTitle', 'getAuthority', 'getRequest' ]
);
$context->method( 'getLanguage' )->willReturn( $language );
$context->method( 'getTitle' )->willReturn( $title );
$context->method( 'getAuthority' )->willReturn( $authority );
$context->method( 'getRequest' )->willReturn( $request );
$responseFactory = $this->createNoOpMock( ResponseFactory::class );
$cors = $this->createNoOpMock( CorsUtils::class );
$services = $this->getFakeServiceContainer();
// NOTE: createRouter() implements the logic for determining the list of route files to load.
$entryPoint = TestingAccessWrapper::newFromClass( EntryPoint::class );
$router = $entryPoint->createRouter(
$services,
$context,
new RequestData(),
$responseFactory,
$cors
);
}
return $router;
}
/**
* Initialize/fetch the Router instance for testing
* @warning Must not be called in data providers!
* @return Router
*/
private function getTestRouter(): Router {
if ( !$this->router ) {
$language = $this->createNoOpMock( Language::class, [ 'getCode' ] );
$language->method( 'getCode' )->willReturn( 'en' );
$title = Title::makeTitle( NS_SPECIAL, 'Badtitle/dummy title for RestStructureTest' );
$authority = new SimpleAuthority( new UserIdentityValue( 0, 'Testor' ), [] );
$request = $this->createNoOpMock( WebRequest::class, [ 'getSession' ] );
$request->method( 'getSession' )->willReturn( $this->createNoOpMock( Session::class ) );
$context = $this->createNoOpMock(
RequestContext::class,
[ 'getLanguage', 'getTitle', 'getAuthority', 'getRequest' ]
);
$context->method( 'getLanguage' )->willReturn( $language );
$context->method( 'getTitle' )->willReturn( $title );
$context->method( 'getAuthority' )->willReturn( $authority );
$context->method( 'getRequest' )->willReturn( $request );
$responseFactory = $this->createNoOpMock( ResponseFactory::class );
$cors = $this->createNoOpMock( CorsUtils::class );
$this->router = EntryPoint::createRouter(
$this->getServiceContainer(), $context, new RequestData(), $responseFactory, $cors
);
}
return $this->router;
}
/**
* @dataProvider provideRoutes
*/
public function testPathParameters( string $moduleName, string $method, string $path ): void {
$router = $this->getTestRouter();
$module = $router->getModule( $moduleName );
$request = new RequestData( [ 'method' => $method ] );
$handler = $module->getHandlerForPath( $path, $request, false );
$params = $handler->getParamSettings();
$dataName = $this->dataName();
// Test that all parameters in the path exist and are declared as such
$matcher = TestingAccessWrapper::newFromObject( new PathMatcher );
$pathParams = [];
foreach ( explode( '/', $path ) as $part ) {
$param = $matcher->getParamName( $part );
if ( $param !== false ) {
$this->assertArrayHasKey( $param, $params, "Path parameter $param exists" );
$this->assertSame( 'path', $params[$param][Handler::PARAM_SOURCE] ?? null,
"$dataName: Path parameter {{$param}} must have PARAM_SOURCE = 'path'" );
$pathParams[$param] = true;
}
}
// Test that any path parameters not in the path aren't marked as required
foreach ( $params as $param => $settings ) {
if ( ( $settings[Handler::PARAM_SOURCE] ?? null ) === 'path' &&
!isset( $pathParams[$param] )
) {
$this->assertFalse( $settings[ParamValidator::PARAM_REQUIRED] ?? false,
"$dataName, parameter $param: PARAM_REQUIRED cannot be true for a path parameter "
. 'not in the path'
);
}
}
// In case there were no path parameters
$this->addToAssertionCount( 1 );
}
/**
* @dataProvider provideRoutes
*/
public function testBodyParameters( string $moduleName, string $method, string $path ): void {
$router = $this->getTestRouter();
$module = $router->getModule( $moduleName );
$request = new RequestData( [ 'method' => $method ] );
$handler = $module->getHandlerForPath( $path, $request, false );
$bodySettings = $handler->getBodyParamSettings();
if ( !$bodySettings ) {
$this->addToAssertionCount( 1 );
return;
}
foreach ( $bodySettings as $settings ) {
$this->assertArrayHasKey( Handler::PARAM_SOURCE, $settings );
$this->assertSame( 'body', $settings[Handler::PARAM_SOURCE] );
if ( isset( $settings[ ArrayDef::PARAM_SCHEMA ] ) ) {
try {
$this->assertValidJsonSchema( $settings[ ArrayDef::PARAM_SCHEMA ] );
} catch ( LogicException $e ) {
$this->fail( "Invalid JSON schema for parameter {$settings['name']}: " . $e->getMessage() );
}
}
}
}
/**
* @dataProvider provideRoutes
*/
public function testBodyParametersNotInParamSettings( string $moduleName, string $method, string $path ): void {
$router = $this->getTestRouter();
$module = $router->getModule( $moduleName );
$request = new RequestData( [ 'method' => $method ] );
$handler = $module->getHandlerForPath( $path, $request, false );
$paramSettings = $handler->getParamSettings();
if ( !$paramSettings ) {
$this->addToAssertionCount( 1 );
return;
}
foreach ( $paramSettings as $settings ) {
$this->assertArrayHasKey( Handler::PARAM_SOURCE, $settings );
$this->assertNotSame( 'body', $settings[Handler::PARAM_SOURCE] );
}
}
public function provideModules(): Iterator {
$router = $this->getRouterForDataProviders();
foreach ( $router->getModuleIds() as $name ) {
yield "Module '$name'" => [ $name ];
}
}
public function provideRoutes(): Iterator {
$router = $this->getRouterForDataProviders();
foreach ( $router->getModuleIds() as $moduleName ) {
$module = $router->getModule( $moduleName );
foreach ( $module->getDefinedPaths() as $path => $methods ) {
foreach ( $methods as $method ) {
// NOTE: we can't use the $module object directly, since it
// may hold references to incorrect service instance.
yield "Handler in module '$moduleName' for $method $path"
=> [ $moduleName, $method, $path ];
}
}
}
}
/**
* @dataProvider provideRoutes
*/
public function testParameters( string $moduleName, string $method, string $path ): void {
$router = $this->getTestRouter();
$module = $router->getModule( $moduleName );
$request = new RequestData( [ 'method' => $method ] );
$handler = $module->getHandlerForPath( $path, $request, false );
$params = $handler->getParamSettings();
foreach ( $params as $param => $settings ) {
$method = $routeSpec['method'] ?? 'GET';
$method = implode( ",", (array)$method );
$this->assertParameter( $param, $settings, "Handler {$method} {$path}, parameter $param" );
}
}
private function assertParameter( string $name, $settings, $msg ) {
$router = TestingAccessWrapper::newFromObject( $this->getTestRouter() );
$dataName = $this->dataName();
$this->assertNotSame( '', $name, "$msg: $dataName: Name cannot be empty" );
$paramValidator = TestingAccessWrapper::newFromObject( $router->restValidator )->paramValidator;
$ret = $paramValidator->checkSettings( $name, $settings, [ 'source' => 'unspecified' ] );
// REST-specific parameters
$ret['allowedKeys'][] = Handler::PARAM_SOURCE;
$ret['allowedKeys'][] = Handler::PARAM_DESCRIPTION;
if ( !in_array( $settings[Handler::PARAM_SOURCE] ?? '', Validator::KNOWN_PARAM_SOURCES, true ) ) {
$ret['issues'][Handler::PARAM_SOURCE] = "PARAM_SOURCE must be one of " . implode( ', ', Validator::KNOWN_PARAM_SOURCES );
}
// Check that "array" type is not used in getParamSettings
if ( isset( $settings[ParamValidator::PARAM_TYPE] ) && $settings[ParamValidator::PARAM_TYPE] === 'array' ) {
$this->fail( "$msg: $dataName: 'array' type is not allowed in getParamSettings" );
}
// Warn about unknown keys. Don't fail, they might be for forward- or back-compat.
if ( is_array( $settings ) ) {
$keys = array_diff(
array_keys( $settings ),
$ret['allowedKeys']
);
if ( $keys ) {
$this->addWarning(
"$msg: $dataName: Unrecognized settings keys were used: " . implode( ', ', $keys )
);
}
}
if ( count( $ret['issues'] ) === 1 ) {
$this->fail( "$msg: $dataName: Validation failed: " . reset( $ret['issues'] ) );
} elseif ( $ret['issues'] ) {
$this->fail( "$msg: $dataName: Validation failed:\n* " . implode( "\n* ", $ret['issues'] ) );
}
// Check message existence
$done = [];
foreach ( $ret['messages'] as $msg ) {
// We don't really care about the parameters, so do it simply
$key = $msg->getKey();
if ( !isset( $done[$key] ) ) {
$done[$key] = true;
$this->assertTrue( Message::newFromKey( $key )->exists(),
"$msg: $dataName: Parameter message $key exists" );
}
}
}
public function testRoutePathAndMethodForDuplicates() {
$router = $this->getTestRouter();
$routes = [];
foreach ( $router->getModuleIds() as $moduleName ) {
$module = $router->getModule( $moduleName );
$paths = $module->getDefinedPaths();
foreach ( $paths as $path => $methods ) {
foreach ( $methods as $method ) {
// NOTE: we can't use the $module object directly, since it
// may hold references to incorrect service instance.
$key = "$moduleName: $method $path";
$this->assertArrayNotHasKey( $key, $routes, "{$key} already exists in routes" );
$routes[$key] = true;
}
}
}
}
public function provideModuleDefinitionFiles() {
$conf = MediaWikiServices::getInstance()->getMainConfig();
$entryPoint = TestingAccessWrapper::newFromClass( EntryPoint::class );
$routeFiles = $entryPoint->getRouteFiles( $conf );
foreach ( $routeFiles as $file ) {
$moduleSpec = self::loadJsonData( $file );
if ( !isset( $moduleSpec->mwapi ) ) {
// old-school flat route file, skip
continue;
}
yield $file => [ $moduleSpec ];
}
}
/**
* @dataProvider provideModuleDefinitionFiles
*/
public function testModuleDefinitionFiles( stdClass $moduleSpec ) {
$schemaFile = MW_INSTALL_PATH . '/docs/rest/mwapi-1.0.json';
$this->assertMatchesJsonSchema( $schemaFile, $moduleSpec, self::SPEC_FILES );
}
/**
* @dataProvider provideModules
*/
public function testGetModuleDescription( string $moduleName ): void {
static $infoSchema = [ '$ref' =>
'https://www.mediawiki.org/schema/discovery-1.0#/definitions/Module'
];
$router = $this->getTestRouter();
$module = $router->getModule( $moduleName );
$info = $module->getModuleDescription();
$this->assertMatchesJsonSchema( $infoSchema, $info, self::SPEC_FILES );
}
/**
* @dataProvider provideModules
*/
public function testGetOpenApiInfo( string $moduleName ): void {
static $infoSchema = [ '$ref' =>
'https://spec.openapis.org/oas/3.0/schema/2021-09-28#/definitions/Info'
];
$router = $this->getTestRouter();
$module = $router->getModule( $moduleName );
$info = $module->getOpenApiInfo();
$this->assertMatchesJsonSchema( $infoSchema, $info, self::SPEC_FILES );
}
}
|