3 use Wikimedia\Rdbms\DBQueryError
;
4 use Wikimedia\TestingAccessWrapper
;
13 class ApiMainTest
extends ApiTestCase
{
16 * Test that the API will accept a FauxRequest and execute.
18 public function testApi() {
20 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
23 $data = $api->getResult()->getResultData();
24 $this->assertInternalType( 'array', $data );
25 $this->assertArrayHasKey( 'query', $data );
28 public function testApiNoParam() {
31 $data = $api->getResult()->getResultData();
32 $this->assertInternalType( 'array', $data );
36 * ApiMain behaves differently if passed a FauxRequest (mInternalMode set
37 * to true) or a proper WebRequest (mInternalMode false). For most tests
38 * we can just set mInternalMode to false using TestingAccessWrapper, but
39 * this doesn't work for the constructor. This method returns an ApiMain
40 * that's been set up in non-internal mode.
42 * Note that calling execute() will print to the console. Wrap it in
43 * ob_start()/ob_end_clean() to prevent this.
45 * @param array $requestData Query parameters for the WebRequest
46 * @param array $headers Headers for the WebRequest
48 private function getNonInternalApiMain( array $requestData, array $headers = [] ) {
49 $req = $this->getMockBuilder( WebRequest
::class )
50 ->setMethods( [ 'response', 'getRawIP' ] )
52 $response = new FauxResponse();
53 $req->method( 'response' )->willReturn( $response );
54 $req->method( 'getRawIP' )->willReturn( '127.0.0.1' );
56 $wrapper = TestingAccessWrapper
::newFromObject( $req );
57 $wrapper->data
= $requestData;
59 $wrapper->headers
= $headers;
62 return new ApiMain( $req );
65 public function testUselang() {
68 $api = $this->getNonInternalApiMain( [
78 $this->assertSame( 'fr', $wgLang->getCode() );
81 public function testNonWhitelistedCorsWithCookies() {
82 $logFile = $this->getNewTempFile();
84 $this->mergeMwGlobalArrayValue( '_COOKIE', [ 'forceHTTPS' => '1' ] );
85 $logger = new TestLogger( true );
86 $this->setLogger( 'cors', $logger );
88 $api = $this->getNonInternalApiMain( [
91 // For some reason multiple origins (which are not allowed in the
92 // WHATWG Fetch spec that supersedes the RFC) are always considered to
94 ], [ 'ORIGIN' => 'https://www.example.com https://www.com.example' ] );
97 [ [ Psr\Log\LogLevel
::WARNING
, 'Non-whitelisted CORS request with session cookies' ] ],
102 public function testSuppressedLogin() {
106 $api = $this->getNonInternalApiMain( [
108 'meta' => 'siteinfo',
116 $this->assertNotSame( $origUser, $wgUser );
117 $this->assertSame( 'true', $api->getContext()->getRequest()->response()
118 ->getHeader( 'MediaWiki-Login-Suppressed' ) );
121 public function testSetContinuationManager() {
122 $api = new ApiMain();
123 $manager = $this->createMock( ApiContinuationManager
::class );
124 $api->setContinuationManager( $manager );
125 $this->assertTrue( true, 'No exception' );
126 return [ $api, $manager ];
130 * @depends testSetContinuationManager
132 public function testSetContinuationManagerTwice( $args ) {
133 $this->setExpectedException( UnexpectedValueException
::class,
134 'ApiMain::setContinuationManager: tried to set manager from ' .
135 'when a manager is already set from ' );
137 list( $api, $manager ) = $args;
138 $api->setContinuationManager( $manager );
141 public function testSetCacheModeUnrecognized() {
142 $api = new ApiMain();
143 $api->setCacheMode( 'unrecognized' );
144 $this->overrideMwServices();
147 TestingAccessWrapper
::newFromObject( $api )->mCacheMode
,
148 'Unrecognized params must be silently ignored'
152 public function testSetCacheModePrivateWiki() {
153 $this->setGroupPermissions( '*', 'read', false );
154 $this->overrideMwServices();
155 $wrappedApi = TestingAccessWrapper
::newFromObject( new ApiMain() );
156 $wrappedApi->setCacheMode( 'public' );
157 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
158 $wrappedApi->setCacheMode( 'anon-public-user-private' );
159 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
162 public function testAddRequestedFieldsRequestId() {
163 $req = new FauxRequest( [
165 'meta' => 'siteinfo',
166 'requestid' => '123456',
168 $api = new ApiMain( $req );
170 $this->assertSame( '123456', $api->getResult()->getResultData()['requestid'] );
173 public function testAddRequestedFieldsCurTimestamp() {
174 $req = new FauxRequest( [
176 'meta' => 'siteinfo',
177 'curtimestamp' => '',
179 $api = new ApiMain( $req );
181 $timestamp = $api->getResult()->getResultData()['curtimestamp'];
182 $this->assertLessThanOrEqual( 1, abs( strtotime( $timestamp ) - time() ) );
185 public function testAddRequestedFieldsResponseLangInfo() {
186 $req = new FauxRequest( [
188 'meta' => 'siteinfo',
189 // errorlang is ignored if errorformat is not specified
190 'errorformat' => 'plaintext',
193 'responselanginfo' => '',
195 $api = new ApiMain( $req );
197 $data = $api->getResult()->getResultData();
198 $this->assertSame( 'fr', $data['uselang'] );
199 $this->assertSame( 'ja', $data['errorlang'] );
202 public function testSetupModuleUnknown() {
203 $this->setExpectedException( ApiUsageException
::class,
204 'Unrecognized value for parameter "action": unknownaction.' );
206 $req = new FauxRequest( [ 'action' => 'unknownaction' ] );
207 $api = new ApiMain( $req );
211 public function testSetupModuleNoTokenProvided() {
212 $this->setExpectedException( ApiUsageException
::class,
213 'The "token" parameter must be set.' );
215 $req = new FauxRequest( [
217 'title' => 'New page',
218 'text' => 'Some text',
220 $api = new ApiMain( $req );
224 public function testSetupModuleInvalidTokenProvided() {
225 $this->setExpectedException( ApiUsageException
::class, 'Invalid CSRF token.' );
227 $req = new FauxRequest( [
229 'title' => 'New page',
230 'text' => 'Some text',
231 'token' => "This isn't a real token!",
233 $api = new ApiMain( $req );
237 public function testSetupModuleNeedsTokenTrue() {
238 $this->setExpectedException( MWException
::class,
239 "Module 'testmodule' must be updated for the new token handling. " .
240 "See documentation for ApiBase::needsToken for details." );
242 $mock = $this->createMock( ApiBase
::class );
243 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
244 $mock->method( 'needsToken' )->willReturn( true );
246 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
247 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
248 function () use ( $mock ) {
255 public function testSetupModuleNeedsTokenNeedntBePosted() {
256 $this->setExpectedException( MWException
::class,
257 "Module 'testmodule' must require POST to use tokens." );
259 $mock = $this->createMock( ApiBase
::class );
260 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
261 $mock->method( 'needsToken' )->willReturn( 'csrf' );
262 $mock->method( 'mustBePosted' )->willReturn( false );
264 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
265 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
266 function () use ( $mock ) {
273 public function testCheckMaxLagFailed() {
274 // It's hard to mock the LoadBalancer properly, so instead we'll mock
275 // checkMaxLag (which is tested directly in other tests below).
276 $req = new FauxRequest( [
278 'meta' => 'siteinfo',
281 $mock = $this->getMockBuilder( ApiMain
::class )
282 ->setConstructorArgs( [ $req ] )
283 ->setMethods( [ 'checkMaxLag' ] )
285 $mock->method( 'checkMaxLag' )->willReturn( false );
289 $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
292 public function testCheckConditionalRequestHeadersFailed() {
293 // The detailed checking of all cases of checkConditionalRequestHeaders
294 // is below in testCheckConditionalRequestHeaders(), which calls the
295 // method directly. Here we just check that it will stop execution if
299 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
301 $mock = $this->createMock( ApiBase
::class );
302 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
303 $mock->method( 'getConditionalRequestData' )
304 ->willReturn( wfTimestamp( TS_MW
, $now - 3600 ) );
305 $mock->expects( $this->exactly( 0 ) )->method( 'execute' );
307 $req = new FauxRequest( [
308 'action' => 'testmodule',
310 $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822
, $now - 3600 ) );
311 $req->setRequestURL( "http://localhost" );
313 $api = new ApiMain( $req );
314 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
315 function () use ( $mock ) {
320 $wrapper = TestingAccessWrapper
::newFromObject( $api );
321 $wrapper->mInternalMode
= false;
328 private function doTestCheckMaxLag( $lag ) {
329 $mockLB = $this->getMockBuilder( LoadBalancer
::class )
330 ->disableOriginalConstructor()
331 ->setMethods( [ 'getMaxLag', '__destruct' ] )
333 $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
334 $this->setService( 'DBLoadBalancer', $mockLB );
336 $req = new FauxRequest();
338 $api = new ApiMain( $req );
339 $wrapper = TestingAccessWrapper
::newFromObject( $api );
341 $mockModule = $this->createMock( ApiBase
::class );
342 $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
345 $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
348 $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
349 $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
354 public function testCheckMaxLagOkay() {
355 $this->doTestCheckMaxLag( 3 );
357 // No exception, we're happy
358 $this->assertTrue( true );
361 public function testCheckMaxLagExceeded() {
362 $this->setExpectedException( ApiUsageException
::class,
363 'Waiting for a database server: 4 seconds lagged.' );
365 $this->setMwGlobals( 'wgShowHostnames', false );
367 $this->doTestCheckMaxLag( 4 );
370 public function testCheckMaxLagExceededWithHostNames() {
371 $this->setExpectedException( ApiUsageException
::class,
372 'Waiting for somehost: 4 seconds lagged.' );
374 $this->setMwGlobals( 'wgShowHostnames', true );
376 $this->doTestCheckMaxLag( 4 );
379 public static function provideAssert() {
381 [ false, [], 'user', 'assertuserfailed' ],
382 [ true, [], 'user', false ],
383 [ true, [], 'bot', 'assertbotfailed' ],
384 [ true, [ 'bot' ], 'user', false ],
385 [ true, [ 'bot' ], 'bot', false ],
390 * Tests the assert={user|bot} functionality
392 * @dataProvider provideAssert
393 * @param bool $registered
394 * @param array $rights
395 * @param string $assert
396 * @param string|bool $error False if no error expected
398 public function testAssert( $registered, $rights, $assert, $error ) {
400 $user = $this->getMutableTestUser()->getUser();
401 $user->load(); // load before setting mRights
405 $this->overrideUserPermissions( $user, $rights );
407 $this->doApiRequest( [
410 ], null, null, $user );
411 $this->assertFalse( $error ); // That no error was expected
412 } catch ( ApiUsageException
$e ) {
413 $this->assertTrue( self
::apiExceptionHasCode( $e, $error ),
414 "Error '{$e->getMessage()}' matched expected '$error'" );
416 $this->overrideMwServices();
420 * Tests the assertuser= functionality
422 public function testAssertUser() {
423 $user = $this->getTestUser()->getUser();
424 $this->doApiRequest( [
426 'assertuser' => $user->getName(),
427 ], null, null, $user );
430 $this->doApiRequest( [
432 'assertuser' => $user->getName() . 'X',
433 ], null, null, $user );
434 $this->fail( 'Expected exception not thrown' );
435 } catch ( ApiUsageException
$e ) {
436 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
441 * Test that 'assert' is processed before module errors
443 public function testAssertBeforeModule() {
444 // Sanity check that the query without assert throws too-many-titles
446 $this->doApiRequest( [
448 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
449 ], null, null, new User
);
450 $this->fail( 'Expected exception not thrown' );
451 } catch ( ApiUsageException
$e ) {
452 $this->assertTrue( self
::apiExceptionHasCode( $e, 'too-many-titles' ), 'sanity check' );
455 // Now test that the assert happens first
457 $this->doApiRequest( [
459 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
461 ], null, null, new User
);
462 $this->fail( 'Expected exception not thrown' );
463 } catch ( ApiUsageException
$e ) {
464 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertuserfailed' ),
465 "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
470 * Test if all classes in the main module manager exists
472 public function testClassNamesInModuleManager() {
474 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
476 $modules = $api->getModuleManager()->getNamesWithClasses();
478 foreach ( $modules as $name => $class ) {
480 class_exists( $class ),
481 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
487 * Test HTTP precondition headers
489 * @dataProvider provideCheckConditionalRequestHeaders
490 * @param array $headers HTTP headers
491 * @param array $conditions Return data for ApiBase::getConditionalRequestData
492 * @param int $status Expected response status
493 * @param array $options Array of options:
494 * post => true Request is a POST
495 * cdn => true CDN is enabled ($wgUseCdn)
497 public function testCheckConditionalRequestHeaders(
498 $headers, $conditions, $status, $options = []
500 $request = new FauxRequest(
501 [ 'action' => 'query', 'meta' => 'siteinfo' ],
502 !empty( $options['post'] )
504 $request->setHeaders( $headers );
505 $request->response()->statusHeader( 200 ); // Why doesn't it default?
507 $context = $this->apiContext
->newTestContext( $request, null );
508 $api = new ApiMain( $context );
509 $priv = TestingAccessWrapper
::newFromObject( $api );
510 $priv->mInternalMode
= false;
512 if ( !empty( $options['cdn'] ) ) {
513 $this->setMwGlobals( 'wgUseCdn', true );
516 // Can't do this in TestSetup.php because Setup.php will override it
517 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
519 $module = $this->getMockBuilder( ApiBase
::class )
520 ->setConstructorArgs( [ $api, 'mock' ] )
521 ->setMethods( [ 'getConditionalRequestData' ] )
522 ->getMockForAbstractClass();
523 $module->expects( $this->any() )
524 ->method( 'getConditionalRequestData' )
525 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
526 return $conditions[$condition] ??
null;
529 $ret = $priv->checkConditionalRequestHeaders( $module );
531 $this->assertSame( $status, $request->response()->getStatusCode() );
532 $this->assertSame( $status === 200, $ret );
535 public static function provideCheckConditionalRequestHeaders() {
540 // Non-existing from module is ignored
541 'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
542 'If-Modified-Since' =>
543 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
546 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
548 // Basic If-None-Match
549 'If-None-Match with matching etag' =>
550 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
551 'If-None-Match with non-matching etag' =>
552 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
553 'Strong If-None-Match with weak matching etag' =>
554 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
555 'Weak If-None-Match with strong matching etag' =>
556 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
557 'Weak If-None-Match with weak matching etag' =>
558 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
560 // Pointless for GET, but supported
561 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
563 // Basic If-Modified-Since
564 'If-Modified-Since, modified one second earlier' =>
565 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
566 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
567 'If-Modified-Since, modified now' =>
568 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
569 [ 'last-modified' => wfTimestamp( TS_MW
, $now ) ], 304 ],
570 'If-Modified-Since, modified one second later' =>
571 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
572 [ 'last-modified' => wfTimestamp( TS_MW
, $now +
1 ) ], 200 ],
574 // If-Modified-Since ignored when If-None-Match is given too
575 'Non-matching If-None-Match and matching If-Modified-Since' =>
576 [ [ 'If-None-Match' => '""',
577 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
578 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
579 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
582 'If-None-Match' => '""',
583 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now )
585 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ],
590 'Matching If-None-Match with POST' =>
591 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
592 [ 'post' => true ] ],
593 'Matching If-Modified-Since with POST' =>
594 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
595 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200,
596 [ 'post' => true ] ],
598 // Other date formats allowed by the RFC
599 'If-Modified-Since with alternate date format 1' =>
600 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
601 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
602 'If-Modified-Since with alternate date format 2' =>
603 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
604 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
606 // Old browser extension to HTTP/1.0
607 'If-Modified-Since with length' =>
608 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) . '; length=123' ],
609 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
611 // Invalid date formats should be ignored
612 'If-Modified-Since with invalid date format' =>
613 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
614 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
615 'If-Modified-Since with entirely unparseable date' =>
616 [ [ 'If-Modified-Since' => 'a potato' ],
617 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
619 // Anything before $wgCdnMaxAge seconds ago should be considered
621 'If-Modified-Since with CDN post-expiry' =>
622 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge * 2 ) ],
623 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
624 200, [ 'cdn' => true ] ],
625 'If-Modified-Since with CDN pre-expiry' =>
626 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge / 2 ) ],
627 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
628 304, [ 'cdn' => true ] ],
633 * Test conditional headers output
634 * @dataProvider provideConditionalRequestHeadersOutput
635 * @param array $conditions Return data for ApiBase::getConditionalRequestData
636 * @param array $headers Expected output headers
637 * @param bool $isError $isError flag
638 * @param bool $post Request is a POST
640 public function testConditionalRequestHeadersOutput(
641 $conditions, $headers, $isError = false, $post = false
643 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
644 $response = $request->response();
646 $api = new ApiMain( $request );
647 $priv = TestingAccessWrapper
::newFromObject( $api );
648 $priv->mInternalMode
= false;
650 $module = $this->getMockBuilder( ApiBase
::class )
651 ->setConstructorArgs( [ $api, 'mock' ] )
652 ->setMethods( [ 'getConditionalRequestData' ] )
653 ->getMockForAbstractClass();
654 $module->expects( $this->any() )
655 ->method( 'getConditionalRequestData' )
656 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
657 return $conditions[$condition] ??
null;
659 $priv->mModule
= $module;
661 $priv->sendCacheHeaders( $isError );
663 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
665 $headers[$header] ??
null,
666 $response->getHeader( $header ),
672 public static function provideConditionalRequestHeadersOutput() {
679 [ 'etag' => '"foo"' ],
680 [ 'ETag' => '"foo"' ]
683 [ 'last-modified' => '20150818000102' ],
684 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
687 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
688 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
691 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
696 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
704 public function testCheckExecutePermissionsReadProhibited() {
705 $this->setExpectedException( ApiUsageException
::class,
706 'You need read permission to use this module.' );
708 $this->setGroupPermissions( '*', 'read', false );
709 $this->overrideMwServices();
711 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
715 public function testCheckExecutePermissionWriteDisabled() {
716 $this->setExpectedException( ApiUsageException
::class,
717 'Editing of this wiki through the API is disabled. Make sure the ' .
718 '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
719 '"LocalSettings.php" file.' );
720 $main = new ApiMain( new FauxRequest( [
722 'title' => 'Some page',
723 'text' => 'Some text',
729 public function testCheckExecutePermissionWriteApiProhibited() {
730 $this->setExpectedException( ApiUsageException
::class,
731 "You're not allowed to edit this wiki through the API." );
732 $this->setGroupPermissions( '*', 'writeapi', false );
733 $this->overrideMwServices();
735 $main = new ApiMain( new FauxRequest( [
737 'title' => 'Some page',
738 'text' => 'Some text',
740 ] ), /* enableWrite = */ true );
744 public function testCheckExecutePermissionPromiseNonWrite() {
745 $this->setExpectedException( ApiUsageException
::class,
746 'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
747 'to write-mode API modules.' );
749 $req = new FauxRequest( [
751 'title' => 'Some page',
752 'text' => 'Some text',
755 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
756 $main = new ApiMain( $req, /* enableWrite = */ true );
760 public function testCheckExecutePermissionHookAbort() {
761 $this->setExpectedException( ApiUsageException
::class, 'Main Page' );
763 $this->setTemporaryHook( 'ApiCheckCanExecute', function ( $unused1, $unused2, &$message ) {
764 $message = 'mainpage';
768 $main = new ApiMain( new FauxRequest( [
770 'title' => 'Some page',
771 'text' => 'Some text',
773 ] ), /* enableWrite = */ true );
777 public function testGetValUnsupportedArray() {
778 $main = new ApiMain( new FauxRequest( [
780 'meta' => 'siteinfo',
781 'siprop' => [ 'general', 'namespaces' ],
783 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
785 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
786 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
789 public function testReportUnusedParams() {
790 $main = new ApiMain( new FauxRequest( [
792 'meta' => 'siteinfo',
793 'unusedparam' => 'unusedval',
794 'anotherunusedparam' => 'anotherval',
797 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
798 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
801 public function testLacksSameOriginSecurity() {
803 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
804 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
808 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
810 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
813 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
814 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
815 $main = new ApiMain( $request );
816 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
819 $this->mergeMwGlobalArrayValue( 'wgHooks', [
820 'RequestHasSameOriginSecurity' => [ function () {
824 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
825 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
829 * Test proper creation of the ApiErrorFormatter
831 * @dataProvider provideApiErrorFormatterCreation
832 * @param array $request Request parameters
833 * @param array $expect Expected data
834 * - uselang: ApiMain language
835 * - class: ApiErrorFormatter class
836 * - lang: ApiErrorFormatter language
837 * - format: ApiErrorFormatter format
838 * - usedb: ApiErrorFormatter use-database flag
840 public function testApiErrorFormatterCreation( array $request, array $expect ) {
841 $context = new RequestContext();
842 $context->setRequest( new FauxRequest( $request ) );
843 $context->setLanguage( 'ru' );
845 $main = new ApiMain( $context );
846 $formatter = $main->getErrorFormatter();
847 $wrappedFormatter = TestingAccessWrapper
::newFromObject( $formatter );
849 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
850 $this->assertInstanceOf( $expect['class'], $formatter );
851 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
852 $this->assertSame( $expect['format'], $wrappedFormatter->format
);
853 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB
);
856 public static function provideApiErrorFormatterCreation() {
858 'Default (BC)' => [ [], [
860 'class' => ApiErrorFormatter_BackCompat
::class,
865 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
867 'class' => ApiErrorFormatter_BackCompat
::class,
872 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
874 'class' => ApiErrorFormatter_BackCompat
::class,
879 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
881 'class' => ApiErrorFormatter
::class,
883 'format' => 'wikitext',
886 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
888 'class' => ApiErrorFormatter
::class,
890 'format' => 'plaintext',
893 'Explicitly follows uselang' => [
894 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
897 'class' => ApiErrorFormatter
::class,
899 'format' => 'plaintext',
903 'uselang=content' => [
904 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
907 'class' => ApiErrorFormatter
::class,
909 'format' => 'plaintext',
913 'errorlang=content' => [
914 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
917 'class' => ApiErrorFormatter
::class,
919 'format' => 'plaintext',
923 'Explicit parameters' => [
924 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
927 'class' => ApiErrorFormatter
::class,
933 'Explicit parameters override uselang' => [
934 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
937 'class' => ApiErrorFormatter
::class,
943 'Bogus language doesn\'t explode' => [
944 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
947 'class' => ApiErrorFormatter
::class,
953 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
955 'class' => ApiErrorFormatter_BackCompat
::class,
964 * @dataProvider provideExceptionErrors
965 * @param Exception $exception
966 * @param array $expectReturn
967 * @param array $expectResult
969 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
970 $context = new RequestContext();
971 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
972 $context->setLanguage( 'en' );
973 $context->setConfig( new MultiConfig( [
975 'ShowHostnames' => true, 'ShowExceptionDetails' => true,
977 $context->getConfig()
980 $main = new ApiMain( $context );
981 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
982 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
984 $ret = TestingAccessWrapper
::newFromObject( $main )->substituteResultWithError( $error );
985 $this->assertSame( $expectReturn, $ret );
987 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
988 // so let's try ->assertEquals().
991 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
995 // Not static so $this can be used
996 public function provideExceptionErrors() {
997 $reqId = WebRequest
::getRequestId();
998 $doclink = wfExpandUrl( wfScript( 'api' ) );
1000 $ex = new InvalidArgumentException( 'Random exception' );
1001 $trace = wfMessage( 'api-exception-trace',
1005 MWExceptionHandler
::getRedactedTraceAsString( $ex )
1006 )->inLanguage( 'en' )->useDatabase( false )->text();
1008 $dbex = new DBQueryError(
1009 $this->createMock( \Wikimedia\Rdbms\IDatabase
::class ),
1010 'error', 1234, 'SELECT 1', __METHOD__
);
1011 $dbtrace = wfMessage( 'api-exception-trace',
1015 MWExceptionHandler
::getRedactedTraceAsString( $dbex )
1016 )->inLanguage( 'en' )->useDatabase( false )->text();
1018 // The specific exception doesn't matter, as long as it's namespaced.
1019 $nsex = new MediaWiki\
ShellDisabledError();
1020 $nstrace = wfMessage( 'api-exception-trace',
1024 MWExceptionHandler
::getRedactedTraceAsString( $nsex )
1025 )->inLanguage( 'en' )->useDatabase( false )->text();
1027 $apiEx1 = new ApiUsageException( null,
1028 StatusValue
::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1029 TestingAccessWrapper
::newFromObject( $apiEx1 )->modulePath
= 'foo+bar';
1030 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1031 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1032 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1034 $badMsg = $this->getMockBuilder( ApiRawMessage
::class )
1035 ->setConstructorArgs( [ 'An error', 'ignored' ] )
1036 ->setMethods( [ 'getApiCode' ] )
1038 $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1039 $apiEx2 = new ApiUsageException( null, StatusValue
::newFatal( $badMsg ) );
1044 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1047 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1050 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1052 'code' => 'internal_api_error_InvalidArgumentException',
1053 'text' => "[$reqId] Exception caught: Random exception",
1055 'errorclass' => InvalidArgumentException
::class,
1060 'servedby' => wfHostname(),
1065 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1068 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1071 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1073 'code' => 'internal_api_error_DBQueryError',
1074 'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1075 "This may indicate a bug in the software.",
1077 'errorclass' => DBQueryError
::class,
1081 'trace' => $dbtrace,
1082 'servedby' => wfHostname(),
1087 [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1090 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1093 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1095 'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1096 'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1098 'errorclass' => MediaWiki\ShellDisabledError
::class,
1102 'trace' => $nstrace,
1103 'servedby' => wfHostname(),
1108 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1111 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1112 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1113 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1116 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1117 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1118 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1120 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1121 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
1122 "for notice of API deprecations and breaking changes.",
1123 'servedby' => wfHostname(),
1128 [ 'existing-error', '<invalid-code>' ],
1131 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1134 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1135 [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1137 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1138 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
1139 "for notice of API deprecations and breaking changes.",
1140 'servedby' => wfHostname(),
1146 public function testPrinterParameterValidationError() {
1147 $api = $this->getNonInternalApiMain( [
1148 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1153 $txt = ob_get_clean();
1155 // Test that the actual output is valid JSON, not just the format of the ApiResult.
1156 $data = FormatJson
::decode( $txt, true );
1157 $this->assertInternalType( 'array', $data );
1158 $this->assertArrayHasKey( 'error', $data );
1159 $this->assertArrayHasKey( 'code', $data['error'] );
1160 $this->assertSame( 'unknown_formatversion', $data['error']['code'] );