3 namespace MediaWiki\Tests\Api
;
6 use InvalidArgumentException
;
8 use MediaWiki\Api\ApiBase
;
9 use MediaWiki\Api\ApiContinuationManager
;
10 use MediaWiki\Api\ApiErrorFormatter
;
11 use MediaWiki\Api\ApiErrorFormatter_BackCompat
;
12 use MediaWiki\Api\ApiMain
;
13 use MediaWiki\Api\ApiRawMessage
;
14 use MediaWiki\Api\ApiUsageException
;
15 use MediaWiki\Config\Config
;
16 use MediaWiki\Config\HashConfig
;
17 use MediaWiki\Config\MultiConfig
;
18 use MediaWiki\Context\RequestContext
;
19 use MediaWiki\Json\FormatJson
;
20 use MediaWiki\Language\RawMessage
;
21 use MediaWiki\MainConfigNames
;
22 use MediaWiki\Permissions\Authority
;
23 use MediaWiki\Request\FauxRequest
;
24 use MediaWiki\Request\FauxResponse
;
25 use MediaWiki\Request\WebRequest
;
26 use MediaWiki\ShellDisabledError
;
27 use MediaWiki\StubObject\StubGlobalUser
;
28 use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait
;
29 use MediaWiki\User\User
;
30 use MWExceptionHandler
;
32 use UnexpectedValueException
;
33 use Wikimedia\Rdbms\DBQueryError
;
34 use Wikimedia\Rdbms\IDatabase
;
35 use Wikimedia\Rdbms\ILoadBalancer
;
36 use Wikimedia\TestingAccessWrapper
;
37 use Wikimedia\Timestamp\ConvertibleTimestamp
;
44 * @covers \MediaWiki\Api\ApiMain
46 class ApiMainTest
extends ApiTestCase
{
47 use MockAuthorityTrait
;
49 protected function setUp(): void
{
51 $this->setGroupPermissions( [
55 'apihighlimits' => false,
61 * Test that the API will accept a MediaWiki\Request\FauxRequest and execute.
63 public function testApi() {
64 $fauxRequest = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
65 $fauxRequest->setRequestURL( 'https://' );
70 $data = $api->getResult()->getResultData();
71 $this->assertIsArray( $data );
72 $this->assertArrayHasKey( 'query', $data );
75 public function testApiNoParam() {
78 $data = $api->getResult()->getResultData();
79 $this->assertIsArray( $data );
83 * ApiMain behaves differently if passed a MediaWiki\Request\FauxRequest (mInternalMode set
84 * to true) or a proper WebRequest (mInternalMode false). For most tests
85 * we can just set mInternalMode to false using TestingAccessWrapper, but
86 * this doesn't work for the constructor. This method returns an ApiMain
87 * that's been set up in non-internal mode.
89 * Note that calling execute() will print to the console. Wrap it in
90 * ob_start()/ob_end_clean() to prevent this.
92 * @param array $requestData Query parameters for the WebRequest
93 * @param array $headers Headers for the WebRequest
96 private function getNonInternalApiMain( array $requestData, array $headers = [] ) {
97 $req = $this->getMockBuilder( WebRequest
::class )
98 ->onlyMethods( [ 'response', 'getRawIP' ] )
100 $response = new FauxResponse();
101 $req->method( 'response' )->willReturn( $response );
102 $req->method( 'getRawIP' )->willReturn( '127.0.0.1' );
104 $wrapper = TestingAccessWrapper
::newFromObject( $req );
105 $wrapper->data
= $requestData;
107 $wrapper->headers
= $headers;
110 return new ApiMain( $req );
113 public function testUselang() {
116 $api = $this->getNonInternalApiMain( [
118 'meta' => 'siteinfo',
126 $this->assertSame( 'fr', $wgLang->getCode() );
129 public function testSuppressedLogin() {
130 // Testing some logic that changes the global $wgUser
131 // ApiMain will be setting it to a MediaWiki\StubObject\StubGlobalUser object, it should already
132 // be one but in case its a full User object we will wrap the comparisons
133 // in MediaWiki\StubObject\StubGlobalUser::getRealUser() which will return the inner User object
134 // for a MediaWiki\StubObject\StubGlobalUser, or the actual User object if given a user.
136 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgUser
138 $origUser = StubGlobalUser
::getRealUser( $wgUser );
140 $api = $this->getNonInternalApiMain( [
142 'meta' => 'siteinfo',
150 $this->assertNotSame( $origUser, StubGlobalUser
::getRealUser( $wgUser ) );
151 $this->assertSame( 'true', $api->getContext()->getRequest()->response()
152 ->getHeader( 'MediaWiki-Login-Suppressed' ) );
155 public function testSetContinuationManager() {
156 $api = new ApiMain();
157 $manager = $this->createMock( ApiContinuationManager
::class );
158 $api->setContinuationManager( $manager );
159 $this->assertTrue( true, 'No exception' );
162 public function testSetContinuationManagerTwice() {
163 $this->expectException( UnexpectedValueException
::class );
164 $this->expectExceptionMessage(
165 'ApiMain::setContinuationManager: tried to set manager from ' .
166 'when a manager is already set from '
169 $api = new ApiMain();
170 $manager = $this->createMock( ApiContinuationManager
::class );
171 $api->setContinuationManager( $manager );
172 $api->setContinuationManager( $manager );
175 public function testSetCacheModeUnrecognized() {
176 $api = new ApiMain();
177 $api->setCacheMode( 'unrecognized' );
180 TestingAccessWrapper
::newFromObject( $api )->mCacheMode
,
181 'Unrecognized params must be silently ignored'
185 public function testSetCacheModePrivateWiki() {
186 $this->setGroupPermissions( '*', 'read', false );
187 $wrappedApi = TestingAccessWrapper
::newFromObject( new ApiMain() );
188 $wrappedApi->setCacheMode( 'public' );
189 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
190 $wrappedApi->setCacheMode( 'anon-public-user-private' );
191 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
194 public function testAddRequestedFieldsRequestId() {
195 $req = new FauxRequest( [
197 'meta' => 'siteinfo',
198 'requestid' => '123456',
200 $api = new ApiMain( $req );
202 $this->assertSame( '123456', $api->getResult()->getResultData()['requestid'] );
205 public function testAddRequestedFieldsCurTimestamp() {
206 // Fake timestamp for better testability, CI can sometimes take
207 // unreasonably long to run the simple test request here.
208 ConvertibleTimestamp
::setFakeTime( '20190102030405' );
210 $req = new FauxRequest( [
212 'meta' => 'siteinfo',
213 'curtimestamp' => '',
215 $api = new ApiMain( $req );
217 $timestamp = $api->getResult()->getResultData()['curtimestamp'];
218 $this->assertSame( '2019-01-02T03:04:05Z', $timestamp );
221 public function testAddRequestedFieldsResponseLangInfo() {
222 $req = new FauxRequest( [
224 'meta' => 'siteinfo',
225 // errorlang is ignored if errorformat is not specified
226 'errorformat' => 'plaintext',
229 'responselanginfo' => '',
231 $api = new ApiMain( $req );
233 $data = $api->getResult()->getResultData();
234 $this->assertSame( 'fr', $data['uselang'] );
235 $this->assertSame( 'ja', $data['errorlang'] );
238 public function testSetupModuleUnknown() {
239 $this->expectApiErrorCode( 'badvalue' );
241 $req = new FauxRequest( [ 'action' => 'unknownaction' ] );
242 $api = new ApiMain( $req );
246 public function testSetupModuleNoTokenProvided() {
247 $this->expectApiErrorCode( 'missingparam' );
249 $req = new FauxRequest( [
251 'title' => 'New page',
252 'text' => 'Some text',
254 $api = new ApiMain( $req );
258 public function testSetupModuleInvalidTokenProvided() {
259 $this->expectApiErrorCode( 'badtoken' );
261 $req = new FauxRequest( [
263 'title' => 'New page',
264 'text' => 'Some text',
265 'token' => "This isn't a real token!",
267 $api = new ApiMain( $req );
271 public function testSetupModuleNeedsTokenTrue() {
272 $this->expectException( LogicException
::class );
273 $this->expectExceptionMessage(
274 "Module 'testmodule' must be updated for the new token handling. " .
275 "See documentation for ApiBase::needsToken for details."
278 $mock = $this->createMock( ApiBase
::class );
279 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
280 $mock->method( 'needsToken' )->willReturn( true );
282 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
283 $api->getModuleManager()->addModule( 'testmodule', 'action', [
284 'class' => get_class( $mock ),
285 'factory' => static function () use ( $mock ) {
292 public function testSetupModuleNeedsTokenNeedntBePosted() {
293 $this->expectException( LogicException
::class );
294 $this->expectExceptionMessage( "Module 'testmodule' must require POST to use tokens." );
296 $mock = $this->createMock( ApiBase
::class );
297 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
298 $mock->method( 'needsToken' )->willReturn( 'csrf' );
299 $mock->method( 'mustBePosted' )->willReturn( false );
301 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
302 $api->getModuleManager()->addModule( 'testmodule', 'action', [
303 'class' => get_class( $mock ),
304 'factory' => static function () use ( $mock ) {
311 public function testCheckMaxLagFailed() {
312 // It's hard to mock the LoadBalancer properly, so instead we'll mock
313 // checkMaxLag (which is tested directly in other tests below).
314 $req = new FauxRequest( [
316 'meta' => 'siteinfo',
319 $mock = $this->getMockBuilder( ApiMain
::class )
320 ->setConstructorArgs( [ $req ] )
321 ->onlyMethods( [ 'checkMaxLag' ] )
323 $mock->method( 'checkMaxLag' )->willReturn( false );
327 $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
330 public function testCheckConditionalRequestHeadersFailed() {
331 // The detailed checking of all cases of checkConditionalRequestHeaders
332 // is below in testCheckConditionalRequestHeaders(), which calls the
333 // method directly. Here we just check that it will stop execution if
337 $this->overrideConfigValue( MainConfigNames
::CacheEpoch
, '20030516000000' );
339 $mock = $this->createMock( ApiBase
::class );
340 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
341 $mock->method( 'getConditionalRequestData' )
342 ->willReturn( wfTimestamp( TS_MW
, $now - 3600 ) );
343 $mock->expects( $this->never() )->method( 'execute' );
345 $req = new FauxRequest( [
346 'action' => 'testmodule',
348 $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822
, $now - 3600 ) );
349 $req->setRequestURL( "http://localhost" );
351 $api = new ApiMain( $req );
352 $api->getModuleManager()->addModule( 'testmodule', 'action', [
353 'class' => get_class( $mock ),
354 'factory' => static function () use ( $mock ) {
359 $wrapper = TestingAccessWrapper
::newFromObject( $api );
360 $wrapper->mInternalMode
= false;
367 private function doTestCheckMaxLag( $lag ) {
368 $mockLB = $this->createMock( ILoadBalancer
::class );
369 $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
370 $mockLB->method( 'getConnection' )->willReturn( $this->createMock( IDatabase
::class ) );
371 $this->setService( 'DBLoadBalancer', $mockLB );
373 $req = new FauxRequest();
375 $api = new ApiMain( $req );
376 $wrapper = TestingAccessWrapper
::newFromObject( $api );
378 $mockModule = $this->createMock( ApiBase
::class );
379 $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
382 $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
385 $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
386 $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
391 public function testCheckMaxLagOkay() {
392 $this->doTestCheckMaxLag( 3 );
394 // No exception, we're happy
395 $this->assertTrue( true );
398 public function testCheckMaxLagExceeded() {
399 $this->expectApiErrorCode( 'maxlag' );
401 $this->overrideConfigValue( MainConfigNames
::ShowHostnames
, false );
403 $this->doTestCheckMaxLag( 4 );
406 public function testCheckMaxLagExceededWithHostNames() {
407 $this->expectApiErrorCode( 'maxlag' );
409 $this->overrideConfigValue( MainConfigNames
::ShowHostnames
, true );
411 $this->doTestCheckMaxLag( 4 );
414 public function provideAssert() {
416 [ $this->mockAnonNullAuthority(), 'user', 'assertuserfailed' ],
417 [ $this->mockRegisteredNullAuthority(), 'user', false ],
418 [ $this->mockAnonNullAuthority(), 'anon', false ],
419 [ $this->mockRegisteredNullAuthority(), 'anon', 'assertanonfailed' ],
420 [ $this->mockRegisteredNullAuthority(), 'bot', 'assertbotfailed' ],
421 [ $this->mockRegisteredAuthorityWithPermissions( [ 'bot' ] ), 'user', false ],
422 [ $this->mockRegisteredAuthorityWithPermissions( [ 'bot' ] ), 'bot', false ],
427 * Tests the assert={user|bot} functionality
429 * @dataProvider provideAssert
431 public function testAssert( Authority
$performer, $assert, $error ) {
433 $this->doApiRequest( [
436 ], null, null, $performer );
437 $this->assertFalse( $error ); // That no error was expected
438 } catch ( ApiUsageException
$e ) {
439 $this->assertApiErrorCode( $error, $e,
440 "Error '{$e->getMessage()}' matched expected '$error'" );
445 * Tests the assertuser= functionality
447 public function testAssertUser() {
448 $user = $this->getTestUser()->getUser();
449 $this->doApiRequest( [
451 'assertuser' => $user->getName(),
452 ], null, null, $user );
455 $this->doApiRequest( [
457 'assertuser' => $user->getName() . 'X',
458 ], null, null, $user );
459 $this->fail( 'Expected exception not thrown' );
460 } catch ( ApiUsageException
$e ) {
461 $this->assertApiErrorCode( 'assertnameduserfailed', $e );
466 * Test that 'assert' is processed before module errors
468 public function testAssertBeforeModule() {
469 // Check that the query without assert throws too-many-titles
471 $this->doApiRequest( [
473 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
474 ], null, null, new User
);
475 $this->fail( 'Expected exception not thrown' );
476 } catch ( ApiUsageException
$e ) {
477 $this->assertApiErrorCode( 'toomanyvalues', $e );
480 // Now test that the assert happens first
482 $this->doApiRequest( [
484 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
486 ], null, null, new User
);
487 $this->fail( 'Expected exception not thrown' );
488 } catch ( ApiUsageException
$e ) {
489 $this->assertApiErrorCode( 'assertuserfailed', $e,
490 "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
495 * Test if all classes in the main module manager exists
497 public function testClassNamesInModuleManager() {
499 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
501 $modules = $api->getModuleManager()->getNamesWithClasses();
503 foreach ( $modules as $name => $class ) {
505 class_exists( $class ),
506 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
512 * Test HTTP precondition headers
514 * @dataProvider provideCheckConditionalRequestHeaders
515 * @param array $headers HTTP headers
516 * @param array $conditions Return data for ApiBase::getConditionalRequestData
517 * @param int $status Expected response status
518 * @param array $options Array of options:
519 * post => true Request is a POST
520 * cdn => true CDN is enabled ($wgUseCdn)
522 public function testCheckConditionalRequestHeaders(
523 $headers, $conditions, $status, $options = []
525 $request = new FauxRequest(
526 [ 'action' => 'query', 'meta' => 'siteinfo' ],
527 !empty( $options['post'] )
529 $request->setHeaders( $headers );
530 $request->response()->statusHeader( 200 ); // Why doesn't it default?
532 $context = $this->apiContext
->newTestContext( $request, null );
533 $api = new ApiMain( $context );
534 $priv = TestingAccessWrapper
::newFromObject( $api );
535 $priv->mInternalMode
= false;
537 if ( !empty( $options['cdn'] ) ) {
538 $this->overrideConfigValue( MainConfigNames
::UseCdn
, true );
541 // Can't do this in TestSetup.php because Setup.php will override it
542 $this->overrideConfigValue( MainConfigNames
::CacheEpoch
, '20030516000000' );
544 $module = $this->getMockBuilder( ApiBase
::class )
545 ->setConstructorArgs( [ $api, 'mock' ] )
546 ->onlyMethods( [ 'getConditionalRequestData' ] )
547 ->getMockForAbstractClass();
548 $module->method( 'getConditionalRequestData' )
549 ->willReturnCallback( static function ( $condition ) use ( $conditions ) {
550 return $conditions[$condition] ??
null;
553 $ret = $priv->checkConditionalRequestHeaders( $module );
555 $this->assertSame( $status, $request->response()->getStatusCode() );
556 $this->assertSame( $status === 200, $ret );
559 public static function provideCheckConditionalRequestHeaders() {
564 // Non-existing from module is ignored
565 'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
566 'If-Modified-Since' =>
567 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
570 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
572 // Basic If-None-Match
573 'If-None-Match with matching etag' =>
574 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
575 'If-None-Match with non-matching etag' =>
576 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
577 'Strong If-None-Match with weak matching etag' =>
578 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
579 'Weak If-None-Match with strong matching etag' =>
580 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
581 'Weak If-None-Match with weak matching etag' =>
582 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
584 // Pointless for GET, but supported
585 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
587 // Basic If-Modified-Since
588 'If-Modified-Since, modified one second earlier' =>
589 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
590 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
591 'If-Modified-Since, modified now' =>
592 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
593 [ 'last-modified' => wfTimestamp( TS_MW
, $now ) ], 304 ],
594 'If-Modified-Since, modified one second later' =>
595 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
596 [ 'last-modified' => wfTimestamp( TS_MW
, $now +
1 ) ], 200 ],
598 // If-Modified-Since ignored when If-None-Match is given too
599 'Non-matching If-None-Match and matching If-Modified-Since' =>
600 [ [ 'If-None-Match' => '""',
601 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
602 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
603 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
606 'If-None-Match' => '""',
607 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now )
609 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ],
614 'Matching If-None-Match with POST' =>
615 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
616 [ 'post' => true ] ],
617 'Matching If-Modified-Since with POST' =>
618 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
619 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200,
620 [ 'post' => true ] ],
622 // Other date formats allowed by the RFC
623 'If-Modified-Since with alternate date format 1' =>
624 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
625 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
626 'If-Modified-Since with alternate date format 2' =>
627 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
628 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
630 // Old browser extension to HTTP/1.0
631 'If-Modified-Since with length' =>
632 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) . '; length=123' ],
633 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
635 // Invalid date formats should be ignored
636 'If-Modified-Since with invalid date format' =>
637 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
638 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
639 'If-Modified-Since with entirely unparseable date' =>
640 [ [ 'If-Modified-Since' => 'a potato' ],
641 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
643 // Anything before $wgCdnMaxAge seconds ago should be considered
645 'If-Modified-Since with CDN post-expiry' =>
646 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge * 2 ) ],
647 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
648 200, [ 'cdn' => true ] ],
649 'If-Modified-Since with CDN pre-expiry' =>
650 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge / 2 ) ],
651 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
652 304, [ 'cdn' => true ] ],
657 * Test conditional headers output
658 * @dataProvider provideConditionalRequestHeadersOutput
659 * @param array $conditions Return data for ApiBase::getConditionalRequestData
660 * @param array $headers Expected output headers
661 * @param bool $isError $isError flag
662 * @param bool $post Request is a POST
664 public function testConditionalRequestHeadersOutput(
665 $conditions, $headers, $isError = false, $post = false
667 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
668 $response = $request->response();
670 $api = new ApiMain( $request );
671 $priv = TestingAccessWrapper
::newFromObject( $api );
672 $priv->mInternalMode
= false;
674 $module = $this->getMockBuilder( ApiBase
::class )
675 ->setConstructorArgs( [ $api, 'mock' ] )
676 ->onlyMethods( [ 'getConditionalRequestData' ] )
677 ->getMockForAbstractClass();
678 $module->method( 'getConditionalRequestData' )
679 ->willReturnCallback( static function ( $condition ) use ( $conditions ) {
680 return $conditions[$condition] ??
null;
682 $priv->mModule
= $module;
684 $priv->sendCacheHeaders( $isError );
686 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
688 $headers[$header] ??
null,
689 $response->getHeader( $header ),
695 public static function provideConditionalRequestHeadersOutput() {
702 [ 'etag' => '"foo"' ],
703 [ 'ETag' => '"foo"' ]
706 [ 'last-modified' => '20150818000102' ],
707 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
710 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
711 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
714 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
719 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
727 public function testCheckExecutePermissionsReadProhibited() {
728 $this->expectApiErrorCode( 'readapidenied' );
730 $this->setGroupPermissions( '*', 'read', false );
732 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
736 public function testCheckExecutePermissionWriteDisabled() {
737 $this->expectApiErrorCode( 'noapiwrite' );
738 $main = new ApiMain( new FauxRequest( [
740 'title' => 'Some page',
741 'text' => 'Some text',
747 public function testCheckExecutePermissionPromiseNonWrite() {
748 $this->expectApiErrorCode( 'promised-nonwrite-api' );
750 $req = new FauxRequest( [
752 'title' => 'Some page',
753 'text' => 'Some text',
756 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
757 $main = new ApiMain( $req, /* enableWrite = */ true );
761 public function testCheckExecutePermissionHookAbort() {
762 $this->expectApiErrorCode( 'mainpage' );
764 $this->setTemporaryHook( 'ApiCheckCanExecute', static function ( $unused1, $unused2, &$message ) {
765 $message = 'mainpage';
769 $main = new ApiMain( new FauxRequest( [
771 'title' => 'Some page',
772 'text' => 'Some text',
774 ] ), /* enableWrite = */ true );
778 public function testGetValUnsupportedArray() {
779 $main = new ApiMain( new FauxRequest( [
781 'meta' => 'siteinfo',
782 'siprop' => [ 'general', 'namespaces' ],
784 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
786 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
787 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
790 public function testReportUnusedParams() {
791 $main = new ApiMain( new FauxRequest( [
793 'meta' => 'siteinfo',
794 'unusedparam' => 'unusedval',
795 'anotherunusedparam' => 'anotherval',
798 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
799 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
802 public function testLacksSameOriginSecurity() {
804 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
805 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
809 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
811 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
814 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
815 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
816 $main = new ApiMain( $request );
817 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
820 $this->mergeMwGlobalArrayValue( 'wgHooks', [
821 'RequestHasSameOriginSecurity' => [ static function () {
825 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
826 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
830 * Test proper creation of the ApiErrorFormatter
832 * @dataProvider provideApiErrorFormatterCreation
833 * @param array $request Request parameters
834 * @param array $expect Expected data
835 * - uselang: ApiMain language
836 * - class: ApiErrorFormatter class
837 * - lang: ApiErrorFormatter language
838 * - format: ApiErrorFormatter format
839 * - usedb: ApiErrorFormatter use-database flag
841 public function testApiErrorFormatterCreation( array $request, array $expect ) {
842 $context = new RequestContext();
843 $context->setRequest( new FauxRequest( $request ) );
844 $context->setLanguage( 'ru' );
846 $main = new ApiMain( $context );
847 $formatter = $main->getErrorFormatter();
848 $wrappedFormatter = TestingAccessWrapper
::newFromObject( $formatter );
850 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
851 $this->assertInstanceOf( $expect['class'], $formatter );
852 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
853 $this->assertSame( $expect['format'], $wrappedFormatter->format
);
854 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB
);
857 public static function provideApiErrorFormatterCreation() {
859 'Default (BC)' => [ [], [
861 'class' => ApiErrorFormatter_BackCompat
::class,
866 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
868 'class' => ApiErrorFormatter_BackCompat
::class,
873 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
875 'class' => ApiErrorFormatter_BackCompat
::class,
880 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
882 'class' => ApiErrorFormatter
::class,
884 'format' => 'wikitext',
887 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
889 'class' => ApiErrorFormatter
::class,
891 'format' => 'plaintext',
894 'Explicitly follows uselang' => [
895 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
898 'class' => ApiErrorFormatter
::class,
900 'format' => 'plaintext',
904 'uselang=content' => [
905 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
908 'class' => ApiErrorFormatter
::class,
910 'format' => 'plaintext',
914 'errorlang=content' => [
915 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
918 'class' => ApiErrorFormatter
::class,
920 'format' => 'plaintext',
924 'Explicit parameters' => [
925 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
928 'class' => ApiErrorFormatter
::class,
934 'Explicit parameters override uselang' => [
935 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
938 'class' => ApiErrorFormatter
::class,
944 'Bogus language doesn\'t explode' => [
945 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
948 'class' => ApiErrorFormatter
::class,
954 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
956 'class' => ApiErrorFormatter_BackCompat
::class,
965 * @dataProvider provideExceptionErrors
967 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
968 $this->overrideConfigValues( [
969 MainConfigNames
::Server
=> 'https://local.example',
970 MainConfigNames
::ScriptPath
=> '/w',
972 $context = new RequestContext();
973 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
974 $context->setLanguage( 'en' );
975 $context->setConfig( new MultiConfig( [
977 MainConfigNames
::ShowHostnames
=> true, MainConfigNames
::ShowExceptionDetails
=> true,
979 $context->getConfig()
982 $main = new ApiMain( $context );
983 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
984 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
986 $ret = TestingAccessWrapper
::newFromObject( $main )->substituteResultWithError( $error );
987 $this->assertSame( $expectReturn, $ret );
989 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
990 // so let's try ->assertEquals().
993 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
997 // Not static so $this can be used
998 public function provideExceptionErrors() {
999 $reqId = WebRequest
::getRequestId();
1000 $doclink = 'https://local.example/w/api.php';
1002 $ex = new InvalidArgumentException( 'Random exception' );
1003 $trace = wfMessage( 'api-exception-trace',
1007 MWExceptionHandler
::getRedactedTraceAsString( $ex )
1008 )->inLanguage( 'en' )->useDatabase( false )->text();
1010 $dbex = new DBQueryError(
1011 $this->createMock( IDatabase
::class ),
1012 'error', 1234, 'SELECT 1', __METHOD__
);
1013 $dbtrace = wfMessage( 'api-exception-trace',
1017 MWExceptionHandler
::getRedactedTraceAsString( $dbex )
1018 )->inLanguage( 'en' )->useDatabase( false )->text();
1020 // The specific exception doesn't matter, as long as it's namespaced.
1021 $nsex = new ShellDisabledError();
1022 $nstrace = wfMessage( 'api-exception-trace',
1026 MWExceptionHandler
::getRedactedTraceAsString( $nsex )
1027 )->inLanguage( 'en' )->useDatabase( false )->text();
1029 $apiEx1 = new ApiUsageException( null,
1030 StatusValue
::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1031 TestingAccessWrapper
::newFromObject( $apiEx1 )->modulePath
= 'foo+bar';
1032 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1033 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1034 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1036 $badMsg = $this->getMockBuilder( ApiRawMessage
::class )
1037 ->setConstructorArgs( [ 'An error', 'ignored' ] )
1038 ->onlyMethods( [ 'getApiCode' ] )
1040 $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1041 $apiEx2 = new ApiUsageException( null, StatusValue
::newFatal( $badMsg ) );
1046 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1049 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1052 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1054 'code' => 'internal_api_error_InvalidArgumentException',
1055 'text' => "[$reqId] Exception caught: Random exception",
1057 'errorclass' => InvalidArgumentException
::class,
1062 'servedby' => wfHostname(),
1067 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1070 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1073 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1075 'code' => 'internal_api_error_DBQueryError',
1076 'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1077 "This may indicate a bug in the software.",
1079 'errorclass' => DBQueryError
::class,
1083 'trace' => $dbtrace,
1084 'servedby' => wfHostname(),
1089 [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1092 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1095 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1097 'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1098 'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1100 'errorclass' => ShellDisabledError
::class,
1104 'trace' => $nstrace,
1105 'servedby' => wfHostname(),
1110 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1113 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1114 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1115 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1118 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1119 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1120 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1122 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1123 "list at <https://lists.wikimedia.org/postorius/lists/mediawiki-api-announce.lists.wikimedia.org/> " .
1124 "for notice of API deprecations and breaking changes.",
1125 'servedby' => wfHostname(),
1130 [ 'existing-error', '<invalid-code>' ],
1133 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1136 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1137 [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1139 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1140 "list at <https://lists.wikimedia.org/postorius/lists/mediawiki-api-announce.lists.wikimedia.org/> " .
1141 "for notice of API deprecations and breaking changes.",
1142 'servedby' => wfHostname(),
1148 public function testPrinterParameterValidationError() {
1149 $api = $this->getNonInternalApiMain( [
1150 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1155 $txt = ob_get_clean();
1157 // Test that the actual output is valid JSON, not just the format of the ApiResult.
1158 $data = FormatJson
::decode( $txt, true );
1159 $this->assertIsArray( $data );
1160 $this->assertArrayHasKey( 'error', $data );
1161 $this->assertArrayHasKey( 'code', $data['error'] );
1162 $this->assertSame( 'badvalue', $data['error']['code'] );
1165 public function testMatchRequestedHeaders() {
1166 $api = TestingAccessWrapper
::newFromClass( ApiMain
::class );
1167 $allowedHeaders = [ 'Accept', 'Origin', 'User-Agent' ];
1169 $this->assertTrue( $api->matchRequestedHeaders( 'Accept', $allowedHeaders ) );
1170 $this->assertTrue( $api->matchRequestedHeaders( 'Accept,Origin', $allowedHeaders ) );
1171 $this->assertTrue( $api->matchRequestedHeaders( 'accEpt, oRIGIN', $allowedHeaders ) );
1172 $this->assertFalse( $api->matchRequestedHeaders( 'Accept,Foo', $allowedHeaders ) );
1173 $this->assertFalse( $api->matchRequestedHeaders( 'Accept, fOO', $allowedHeaders ) );
1177 * Common test code for tests that cover ApiMain::sendCacheHeaders.
1179 * @param TestingAccessWrapper $api An ApiMain instance, wrapped in a TestingAccessWrapper.
1180 * @param FauxRequest $req
1181 * @param bool $isError
1182 * @param string $cacheMode
1183 * @param string|null $expectedVary
1184 * @param string $expectedCacheControl
1186 private function commonTestCacheHeaders(
1187 TestingAccessWrapper
$api,
1191 ?
string $expectedVary,
1192 string $expectedCacheControl
1194 $api->setCacheMode( $cacheMode );
1195 $this->assertSame( $cacheMode, $api->mCacheMode
, 'Cache mode precondition' );
1196 $api->sendCacheHeaders( $isError );
1198 $this->assertSame( $expectedVary, $req->response()->getHeader( 'Vary' ), 'Vary' );
1199 $this->assertSame( $expectedCacheControl, $req->response()->getHeader( 'Cache-Control' ), 'Cache-Control' );
1203 * @param string $cacheMode
1204 * @param string|null $expectedVary
1205 * @param string $expectedCacheControl
1206 * @param array $requestData
1207 * @param Config|null $config
1208 * @dataProvider provideCacheHeaders
1210 public function testCacheHeaders(
1212 ?
string $expectedVary,
1213 string $expectedCacheControl,
1214 array $requestData = [],
1215 ?Config
$config = null
1217 $req = new FauxRequest( $requestData );
1218 $ctx = new RequestContext();
1219 $ctx->setRequest( $req );
1221 $ctx->setConfig( $config );
1223 /** @var ApiMain|TestingAccessWrapper $api */
1224 $api = TestingAccessWrapper
::newFromObject( new ApiMain( $ctx ) );
1226 $this->commonTestCacheHeaders( $api, $req, false, $cacheMode, $expectedVary, $expectedCacheControl );
1229 public static function provideCacheHeaders(): Generator
{
1230 yield
'Private' => [ 'private', null, 'private, must-revalidate, max-age=0' ];
1233 'Accept-Encoding, Treat-as-Untrusted, Cookie',
1234 'private, must-revalidate, max-age=0',
1235 [ 'uselang' => 'en' ]
1237 yield
'Anon public, user private' => [
1238 'anon-public-user-private',
1239 'Accept-Encoding, Treat-as-Untrusted, Cookie',
1240 'private, must-revalidate, max-age=0'
1244 /** @dataProvider provideCacheHeaders */
1245 public function testCacheHeadersOnIsErrorAsTrue(
1247 ?
string $expectedVary,
1248 string $expectedCacheControl,
1249 array $requestData = []
1251 $req = new FauxRequest( $requestData );
1252 $ctx = new RequestContext();
1253 $ctx->setRequest( $req );
1254 /** @var ApiMain|TestingAccessWrapper $api */
1255 $api = TestingAccessWrapper
::newFromObject( new ApiMain( $ctx ) );
1257 // Create a mock ApiBase object that throws an ApiUsageException from ::isWriteMode. This will be used as the
1258 // mModule property of $api, and will test that ::isWriteMode is either never called or properly wrapped in
1259 // a try block in the method we are testing (T363133).
1260 $module = $this->getMockBuilder( ApiBase
::class )
1261 ->setConstructorArgs( [ $api->object, 'mock' ] )
1262 ->onlyMethods( [ 'isWriteMode' ] )
1263 ->getMockForAbstractClass();
1264 $module->method( 'isWriteMode' )
1265 ->willThrowException( new ApiUsageException( $module, StatusValue
::newFatal( 'test' ) ) );
1266 $api->mModule
= $module;
1268 // This will test that ::isWriteMode will not be called if $isError is true.
1269 $this->commonTestCacheHeaders( $api, $req, true, $cacheMode, $expectedVary, $expectedCacheControl );