Merge "Avoid Database::tableName in WikiExporter"
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiMainTest.php
1 <?php
2
3 use Wikimedia\Rdbms\DBQueryError;
4 use Wikimedia\TestingAccessWrapper;
5
6 /**
7 * @group API
8 * @group Database
9 * @group medium
10 *
11 * @covers ApiMain
12 */
13 class ApiMainTest extends ApiTestCase {
14
15 /**
16 * Test that the API will accept a FauxRequest and execute.
17 */
18 public function testApi() {
19 $api = new ApiMain(
20 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
21 );
22 $api->execute();
23 $data = $api->getResult()->getResultData();
24 $this->assertInternalType( 'array', $data );
25 $this->assertArrayHasKey( 'query', $data );
26 }
27
28 public function testApiNoParam() {
29 $api = new ApiMain();
30 $api->execute();
31 $data = $api->getResult()->getResultData();
32 $this->assertInternalType( 'array', $data );
33 }
34
35 /**
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.
41 *
42 * Note that calling execute() will print to the console. Wrap it in
43 * ob_start()/ob_end_clean() to prevent this.
44 *
45 * @param array $requestData Query parameters for the WebRequest
46 * @param array $headers Headers for the WebRequest
47 */
48 private function getNonInternalApiMain( array $requestData, array $headers = [] ) {
49 $req = $this->getMockBuilder( WebRequest::class )
50 ->setMethods( [ 'response', 'getRawIP' ] )
51 ->getMock();
52 $response = new FauxResponse();
53 $req->method( 'response' )->willReturn( $response );
54 $req->method( 'getRawIP' )->willReturn( '127.0.0.1' );
55
56 $wrapper = TestingAccessWrapper::newFromObject( $req );
57 $wrapper->data = $requestData;
58 if ( $headers ) {
59 $wrapper->headers = $headers;
60 }
61
62 return new ApiMain( $req );
63 }
64
65 public function testUselang() {
66 global $wgLang;
67
68 $api = $this->getNonInternalApiMain( [
69 'action' => 'query',
70 'meta' => 'siteinfo',
71 'uselang' => 'fr',
72 ] );
73
74 ob_start();
75 $api->execute();
76 ob_end_clean();
77
78 $this->assertSame( 'fr', $wgLang->getCode() );
79 }
80
81 public function testNonWhitelistedCorsWithCookies() {
82 $logFile = $this->getNewTempFile();
83
84 $this->mergeMwGlobalArrayValue( '_COOKIE', [ 'forceHTTPS' => '1' ] );
85 $logger = new TestLogger( true );
86 $this->setLogger( 'cors', $logger );
87
88 $api = $this->getNonInternalApiMain( [
89 'action' => 'query',
90 'meta' => 'siteinfo',
91 // For some reason multiple origins (which are not allowed in the
92 // WHATWG Fetch spec that supersedes the RFC) are always considered to
93 // be problematic.
94 ], [ 'ORIGIN' => 'https://www.example.com https://www.com.example' ] );
95
96 $this->assertSame(
97 [ [ Psr\Log\LogLevel::WARNING, 'Non-whitelisted CORS request with session cookies' ] ],
98 $logger->getBuffer()
99 );
100 }
101
102 public function testSuppressedLogin() {
103 global $wgUser;
104 $origUser = $wgUser;
105
106 $api = $this->getNonInternalApiMain( [
107 'action' => 'query',
108 'meta' => 'siteinfo',
109 'origin' => '*',
110 ] );
111
112 ob_start();
113 $api->execute();
114 ob_end_clean();
115
116 $this->assertNotSame( $origUser, $wgUser );
117 $this->assertSame( 'true', $api->getContext()->getRequest()->response()
118 ->getHeader( 'MediaWiki-Login-Suppressed' ) );
119 }
120
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 ];
127 }
128
129 /**
130 * @depends testSetContinuationManager
131 */
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 ' );
136
137 list( $api, $manager ) = $args;
138 $api->setContinuationManager( $manager );
139 }
140
141 public function testSetCacheModeUnrecognized() {
142 $api = new ApiMain();
143 $api->setCacheMode( 'unrecognized' );
144 $this->assertSame(
145 'private',
146 TestingAccessWrapper::newFromObject( $api )->mCacheMode,
147 'Unrecognized params must be silently ignored'
148 );
149 }
150
151 public function testSetCacheModePrivateWiki() {
152 $this->setGroupPermissions( '*', 'read', false );
153 $wrappedApi = TestingAccessWrapper::newFromObject( new ApiMain() );
154 $wrappedApi->setCacheMode( 'public' );
155 $this->assertSame( 'private', $wrappedApi->mCacheMode );
156 $wrappedApi->setCacheMode( 'anon-public-user-private' );
157 $this->assertSame( 'private', $wrappedApi->mCacheMode );
158 }
159
160 public function testAddRequestedFieldsRequestId() {
161 $req = new FauxRequest( [
162 'action' => 'query',
163 'meta' => 'siteinfo',
164 'requestid' => '123456',
165 ] );
166 $api = new ApiMain( $req );
167 $api->execute();
168 $this->assertSame( '123456', $api->getResult()->getResultData()['requestid'] );
169 }
170
171 public function testAddRequestedFieldsCurTimestamp() {
172 $req = new FauxRequest( [
173 'action' => 'query',
174 'meta' => 'siteinfo',
175 'curtimestamp' => '',
176 ] );
177 $api = new ApiMain( $req );
178 $api->execute();
179 $timestamp = $api->getResult()->getResultData()['curtimestamp'];
180 $this->assertLessThanOrEqual( 1, abs( strtotime( $timestamp ) - time() ) );
181 }
182
183 public function testAddRequestedFieldsResponseLangInfo() {
184 $req = new FauxRequest( [
185 'action' => 'query',
186 'meta' => 'siteinfo',
187 // errorlang is ignored if errorformat is not specified
188 'errorformat' => 'plaintext',
189 'uselang' => 'FR',
190 'errorlang' => 'ja',
191 'responselanginfo' => '',
192 ] );
193 $api = new ApiMain( $req );
194 $api->execute();
195 $data = $api->getResult()->getResultData();
196 $this->assertSame( 'fr', $data['uselang'] );
197 $this->assertSame( 'ja', $data['errorlang'] );
198 }
199
200 public function testSetupModuleUnknown() {
201 $this->setExpectedException( ApiUsageException::class,
202 'Unrecognized value for parameter "action": unknownaction.' );
203
204 $req = new FauxRequest( [ 'action' => 'unknownaction' ] );
205 $api = new ApiMain( $req );
206 $api->execute();
207 }
208
209 public function testSetupModuleNoTokenProvided() {
210 $this->setExpectedException( ApiUsageException::class,
211 'The "token" parameter must be set.' );
212
213 $req = new FauxRequest( [
214 'action' => 'edit',
215 'title' => 'New page',
216 'text' => 'Some text',
217 ] );
218 $api = new ApiMain( $req );
219 $api->execute();
220 }
221
222 public function testSetupModuleInvalidTokenProvided() {
223 $this->setExpectedException( ApiUsageException::class, 'Invalid CSRF token.' );
224
225 $req = new FauxRequest( [
226 'action' => 'edit',
227 'title' => 'New page',
228 'text' => 'Some text',
229 'token' => "This isn't a real token!",
230 ] );
231 $api = new ApiMain( $req );
232 $api->execute();
233 }
234
235 public function testSetupModuleNeedsTokenTrue() {
236 $this->setExpectedException( MWException::class,
237 "Module 'testmodule' must be updated for the new token handling. " .
238 "See documentation for ApiBase::needsToken for details." );
239
240 $mock = $this->createMock( ApiBase::class );
241 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
242 $mock->method( 'needsToken' )->willReturn( true );
243
244 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
245 $api->getModuleManager()->addModule( 'testmodule', 'action', [
246 'class' => get_class( $mock ),
247 'factory' => function () use ( $mock ) {
248 return $mock;
249 }
250 ] );
251 $api->execute();
252 }
253
254 public function testSetupModuleNeedsTokenNeedntBePosted() {
255 $this->setExpectedException( MWException::class,
256 "Module 'testmodule' must require POST to use tokens." );
257
258 $mock = $this->createMock( ApiBase::class );
259 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
260 $mock->method( 'needsToken' )->willReturn( 'csrf' );
261 $mock->method( 'mustBePosted' )->willReturn( false );
262
263 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
264 $api->getModuleManager()->addModule( 'testmodule', 'action', [
265 'class' => get_class( $mock ),
266 'factory' => function () use ( $mock ) {
267 return $mock;
268 }
269 ] );
270 $api->execute();
271 }
272
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( [
277 'action' => 'query',
278 'meta' => 'siteinfo',
279 ] );
280
281 $mock = $this->getMockBuilder( ApiMain::class )
282 ->setConstructorArgs( [ $req ] )
283 ->setMethods( [ 'checkMaxLag' ] )
284 ->getMock();
285 $mock->method( 'checkMaxLag' )->willReturn( false );
286
287 $mock->execute();
288
289 $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
290 }
291
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
296 // it does fail.
297 $now = time();
298
299 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
300
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' );
306
307 $req = new FauxRequest( [
308 'action' => 'testmodule',
309 ] );
310 $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822, $now - 3600 ) );
311 $req->setRequestURL( "http://localhost" );
312
313 $api = new ApiMain( $req );
314 $api->getModuleManager()->addModule( 'testmodule', 'action', [
315 'class' => get_class( $mock ),
316 'factory' => function () use ( $mock ) {
317 return $mock;
318 }
319 ] );
320
321 $wrapper = TestingAccessWrapper::newFromObject( $api );
322 $wrapper->mInternalMode = false;
323
324 ob_start();
325 $api->execute();
326 ob_end_clean();
327 }
328
329 private function doTestCheckMaxLag( $lag ) {
330 $mockLB = $this->getMockBuilder( LoadBalancer::class )
331 ->disableOriginalConstructor()
332 ->setMethods( [ 'getMaxLag', '__destruct' ] )
333 ->getMock();
334 $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
335 $this->setService( 'DBLoadBalancer', $mockLB );
336
337 $req = new FauxRequest();
338
339 $api = new ApiMain( $req );
340 $wrapper = TestingAccessWrapper::newFromObject( $api );
341
342 $mockModule = $this->createMock( ApiBase::class );
343 $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
344
345 try {
346 $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
347 } finally {
348 if ( $lag > 3 ) {
349 $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
350 $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
351 }
352 }
353 }
354
355 public function testCheckMaxLagOkay() {
356 $this->doTestCheckMaxLag( 3 );
357
358 // No exception, we're happy
359 $this->assertTrue( true );
360 }
361
362 public function testCheckMaxLagExceeded() {
363 $this->setExpectedException( ApiUsageException::class,
364 'Waiting for a database server: 4 seconds lagged.' );
365
366 $this->setMwGlobals( 'wgShowHostnames', false );
367
368 $this->doTestCheckMaxLag( 4 );
369 }
370
371 public function testCheckMaxLagExceededWithHostNames() {
372 $this->setExpectedException( ApiUsageException::class,
373 'Waiting for somehost: 4 seconds lagged.' );
374
375 $this->setMwGlobals( 'wgShowHostnames', true );
376
377 $this->doTestCheckMaxLag( 4 );
378 }
379
380 public static function provideAssert() {
381 return [
382 [ false, [], 'user', 'assertuserfailed' ],
383 [ true, [], 'user', false ],
384 [ true, [], 'bot', 'assertbotfailed' ],
385 [ true, [ 'bot' ], 'user', false ],
386 [ true, [ 'bot' ], 'bot', false ],
387 ];
388 }
389
390 /**
391 * Tests the assert={user|bot} functionality
392 *
393 * @dataProvider provideAssert
394 * @param bool $registered
395 * @param array $rights
396 * @param string $assert
397 * @param string|bool $error False if no error expected
398 */
399 public function testAssert( $registered, $rights, $assert, $error ) {
400 if ( $registered ) {
401 $user = $this->getMutableTestUser()->getUser();
402 $user->load(); // load before setting mRights
403 } else {
404 $user = new User();
405 }
406 $this->overrideUserPermissions( $user, $rights );
407 try {
408 $this->doApiRequest( [
409 'action' => 'query',
410 'assert' => $assert,
411 ], null, null, $user );
412 $this->assertFalse( $error ); // That no error was expected
413 } catch ( ApiUsageException $e ) {
414 $this->assertTrue( self::apiExceptionHasCode( $e, $error ),
415 "Error '{$e->getMessage()}' matched expected '$error'" );
416 }
417 }
418
419 /**
420 * Tests the assertuser= functionality
421 */
422 public function testAssertUser() {
423 $user = $this->getTestUser()->getUser();
424 $this->doApiRequest( [
425 'action' => 'query',
426 'assertuser' => $user->getName(),
427 ], null, null, $user );
428
429 try {
430 $this->doApiRequest( [
431 'action' => 'query',
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' ) );
437 }
438 }
439
440 /**
441 * Test that 'assert' is processed before module errors
442 */
443 public function testAssertBeforeModule() {
444 // Sanity check that the query without assert throws too-many-titles
445 try {
446 $this->doApiRequest( [
447 'action' => 'query',
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' );
453 }
454
455 // Now test that the assert happens first
456 try {
457 $this->doApiRequest( [
458 'action' => 'query',
459 'titles' => implode( '|', range( 1, ApiBase::LIMIT_SML1 + 1 ) ),
460 'assert' => 'user',
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'" );
466 }
467 }
468
469 /**
470 * Test if all classes in the main module manager exists
471 */
472 public function testClassNamesInModuleManager() {
473 $api = new ApiMain(
474 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
475 );
476 $modules = $api->getModuleManager()->getNamesWithClasses();
477
478 foreach ( $modules as $name => $class ) {
479 $this->assertTrue(
480 class_exists( $class ),
481 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
482 );
483 }
484 }
485
486 /**
487 * Test HTTP precondition headers
488 *
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)
496 */
497 public function testCheckConditionalRequestHeaders(
498 $headers, $conditions, $status, $options = []
499 ) {
500 $request = new FauxRequest(
501 [ 'action' => 'query', 'meta' => 'siteinfo' ],
502 !empty( $options['post'] )
503 );
504 $request->setHeaders( $headers );
505 $request->response()->statusHeader( 200 ); // Why doesn't it default?
506
507 $context = $this->apiContext->newTestContext( $request, null );
508 $api = new ApiMain( $context );
509 $priv = TestingAccessWrapper::newFromObject( $api );
510 $priv->mInternalMode = false;
511
512 if ( !empty( $options['cdn'] ) ) {
513 $this->setMwGlobals( 'wgUseCdn', true );
514 }
515
516 // Can't do this in TestSetup.php because Setup.php will override it
517 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
518
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;
527 } ) );
528
529 $ret = $priv->checkConditionalRequestHeaders( $module );
530
531 $this->assertSame( $status, $request->response()->getStatusCode() );
532 $this->assertSame( $status === 200, $ret );
533 }
534
535 public static function provideCheckConditionalRequestHeaders() {
536 global $wgCdnMaxAge;
537 $now = time();
538
539 return [
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 ],
544
545 // No headers
546 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
547
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 ],
559
560 // Pointless for GET, but supported
561 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
562
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 ],
573
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' =>
580 [
581 [
582 'If-None-Match' => '""',
583 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now )
584 ],
585 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ],
586 304
587 ],
588
589 // Ignored for POST
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 ] ],
597
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 ],
605
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 ],
610
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 ],
618
619 // Anything before $wgCdnMaxAge seconds ago should be considered
620 // expired.
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 ] ],
629 ];
630 }
631
632 /**
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
639 */
640 public function testConditionalRequestHeadersOutput(
641 $conditions, $headers, $isError = false, $post = false
642 ) {
643 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
644 $response = $request->response();
645
646 $api = new ApiMain( $request );
647 $priv = TestingAccessWrapper::newFromObject( $api );
648 $priv->mInternalMode = false;
649
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;
658 } ) );
659 $priv->mModule = $module;
660
661 $priv->sendCacheHeaders( $isError );
662
663 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
664 $this->assertEquals(
665 $headers[$header] ?? null,
666 $response->getHeader( $header ),
667 $header
668 );
669 }
670 }
671
672 public static function provideConditionalRequestHeadersOutput() {
673 return [
674 [
675 [],
676 []
677 ],
678 [
679 [ 'etag' => '"foo"' ],
680 [ 'ETag' => '"foo"' ]
681 ],
682 [
683 [ 'last-modified' => '20150818000102' ],
684 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
685 ],
686 [
687 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
688 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
689 ],
690 [
691 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
692 [],
693 true,
694 ],
695 [
696 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
697 [],
698 false,
699 true,
700 ],
701 ];
702 }
703
704 public function testCheckExecutePermissionsReadProhibited() {
705 $this->setExpectedException( ApiUsageException::class,
706 'You need read permission to use this module.' );
707
708 $this->setGroupPermissions( '*', 'read', false );
709
710 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
711 $main->execute();
712 }
713
714 public function testCheckExecutePermissionWriteDisabled() {
715 $this->setExpectedException( ApiUsageException::class,
716 'Editing of this wiki through the API is disabled. Make sure the ' .
717 '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
718 '"LocalSettings.php" file.' );
719 $main = new ApiMain( new FauxRequest( [
720 'action' => 'edit',
721 'title' => 'Some page',
722 'text' => 'Some text',
723 'token' => '+\\',
724 ] ) );
725 $main->execute();
726 }
727
728 public function testCheckExecutePermissionWriteApiProhibited() {
729 $this->setExpectedException( ApiUsageException::class,
730 "You're not allowed to edit this wiki through the API." );
731 $this->setGroupPermissions( '*', 'writeapi', false );
732
733 $main = new ApiMain( new FauxRequest( [
734 'action' => 'edit',
735 'title' => 'Some page',
736 'text' => 'Some text',
737 'token' => '+\\',
738 ] ), /* enableWrite = */ true );
739 $main->execute();
740 }
741
742 public function testCheckExecutePermissionPromiseNonWrite() {
743 $this->setExpectedException( ApiUsageException::class,
744 'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
745 'to write-mode API modules.' );
746
747 $req = new FauxRequest( [
748 'action' => 'edit',
749 'title' => 'Some page',
750 'text' => 'Some text',
751 'token' => '+\\',
752 ] );
753 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
754 $main = new ApiMain( $req, /* enableWrite = */ true );
755 $main->execute();
756 }
757
758 public function testCheckExecutePermissionHookAbort() {
759 $this->setExpectedException( ApiUsageException::class, 'Main Page' );
760
761 $this->setTemporaryHook( 'ApiCheckCanExecute', function ( $unused1, $unused2, &$message ) {
762 $message = 'mainpage';
763 return false;
764 } );
765
766 $main = new ApiMain( new FauxRequest( [
767 'action' => 'edit',
768 'title' => 'Some page',
769 'text' => 'Some text',
770 'token' => '+\\',
771 ] ), /* enableWrite = */ true );
772 $main->execute();
773 }
774
775 public function testGetValUnsupportedArray() {
776 $main = new ApiMain( new FauxRequest( [
777 'action' => 'query',
778 'meta' => 'siteinfo',
779 'siprop' => [ 'general', 'namespaces' ],
780 ] ) );
781 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
782 $main->execute();
783 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
784 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
785 }
786
787 public function testReportUnusedParams() {
788 $main = new ApiMain( new FauxRequest( [
789 'action' => 'query',
790 'meta' => 'siteinfo',
791 'unusedparam' => 'unusedval',
792 'anotherunusedparam' => 'anotherval',
793 ] ) );
794 $main->execute();
795 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
796 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
797 }
798
799 public function testLacksSameOriginSecurity() {
800 // Basic test
801 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
802 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
803
804 // JSONp
805 $main = new ApiMain(
806 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
807 );
808 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
809
810 // Header
811 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
812 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
813 $main = new ApiMain( $request );
814 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
815
816 // Hook
817 $this->mergeMwGlobalArrayValue( 'wgHooks', [
818 'RequestHasSameOriginSecurity' => [ function () {
819 return false;
820 } ]
821 ] );
822 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
823 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
824 }
825
826 /**
827 * Test proper creation of the ApiErrorFormatter
828 *
829 * @dataProvider provideApiErrorFormatterCreation
830 * @param array $request Request parameters
831 * @param array $expect Expected data
832 * - uselang: ApiMain language
833 * - class: ApiErrorFormatter class
834 * - lang: ApiErrorFormatter language
835 * - format: ApiErrorFormatter format
836 * - usedb: ApiErrorFormatter use-database flag
837 */
838 public function testApiErrorFormatterCreation( array $request, array $expect ) {
839 $context = new RequestContext();
840 $context->setRequest( new FauxRequest( $request ) );
841 $context->setLanguage( 'ru' );
842
843 $main = new ApiMain( $context );
844 $formatter = $main->getErrorFormatter();
845 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
846
847 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
848 $this->assertInstanceOf( $expect['class'], $formatter );
849 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
850 $this->assertSame( $expect['format'], $wrappedFormatter->format );
851 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
852 }
853
854 public static function provideApiErrorFormatterCreation() {
855 return [
856 'Default (BC)' => [ [], [
857 'uselang' => 'ru',
858 'class' => ApiErrorFormatter_BackCompat::class,
859 'lang' => 'en',
860 'format' => 'none',
861 'usedb' => false,
862 ] ],
863 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
864 'uselang' => 'ru',
865 'class' => ApiErrorFormatter_BackCompat::class,
866 'lang' => 'en',
867 'format' => 'none',
868 'usedb' => false,
869 ] ],
870 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
871 'uselang' => 'ru',
872 'class' => ApiErrorFormatter_BackCompat::class,
873 'lang' => 'en',
874 'format' => 'none',
875 'usedb' => false,
876 ] ],
877 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
878 'uselang' => 'ru',
879 'class' => ApiErrorFormatter::class,
880 'lang' => 'ru',
881 'format' => 'wikitext',
882 'usedb' => false,
883 ] ],
884 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
885 'uselang' => 'fr',
886 'class' => ApiErrorFormatter::class,
887 'lang' => 'fr',
888 'format' => 'plaintext',
889 'usedb' => false,
890 ] ],
891 'Explicitly follows uselang' => [
892 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
893 [
894 'uselang' => 'fr',
895 'class' => ApiErrorFormatter::class,
896 'lang' => 'fr',
897 'format' => 'plaintext',
898 'usedb' => false,
899 ]
900 ],
901 'uselang=content' => [
902 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
903 [
904 'uselang' => 'en',
905 'class' => ApiErrorFormatter::class,
906 'lang' => 'en',
907 'format' => 'plaintext',
908 'usedb' => false,
909 ]
910 ],
911 'errorlang=content' => [
912 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
913 [
914 'uselang' => 'ru',
915 'class' => ApiErrorFormatter::class,
916 'lang' => 'en',
917 'format' => 'plaintext',
918 'usedb' => false,
919 ]
920 ],
921 'Explicit parameters' => [
922 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
923 [
924 'uselang' => 'ru',
925 'class' => ApiErrorFormatter::class,
926 'lang' => 'de',
927 'format' => 'html',
928 'usedb' => true,
929 ]
930 ],
931 'Explicit parameters override uselang' => [
932 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
933 [
934 'uselang' => 'fr',
935 'class' => ApiErrorFormatter::class,
936 'lang' => 'de',
937 'format' => 'raw',
938 'usedb' => false,
939 ]
940 ],
941 'Bogus language doesn\'t explode' => [
942 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
943 [
944 'uselang' => 'en',
945 'class' => ApiErrorFormatter::class,
946 'lang' => 'en',
947 'format' => 'none',
948 'usedb' => false,
949 ]
950 ],
951 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
952 'uselang' => 'ru',
953 'class' => ApiErrorFormatter_BackCompat::class,
954 'lang' => 'en',
955 'format' => 'none',
956 'usedb' => false,
957 ] ],
958 ];
959 }
960
961 /**
962 * @dataProvider provideExceptionErrors
963 * @param Exception $exception
964 * @param array $expectReturn
965 * @param array $expectResult
966 */
967 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
968 $context = new RequestContext();
969 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
970 $context->setLanguage( 'en' );
971 $context->setConfig( new MultiConfig( [
972 new HashConfig( [
973 'ShowHostnames' => true, 'ShowExceptionDetails' => true,
974 ] ),
975 $context->getConfig()
976 ] ) );
977
978 $main = new ApiMain( $context );
979 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
980 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
981
982 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
983 $this->assertSame( $expectReturn, $ret );
984
985 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
986 // so let's try ->assertEquals().
987 $this->assertEquals(
988 $expectResult,
989 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
990 );
991 }
992
993 // Not static so $this can be used
994 public function provideExceptionErrors() {
995 $reqId = WebRequest::getRequestId();
996 $doclink = wfExpandUrl( wfScript( 'api' ) );
997
998 $ex = new InvalidArgumentException( 'Random exception' );
999 $trace = wfMessage( 'api-exception-trace',
1000 get_class( $ex ),
1001 $ex->getFile(),
1002 $ex->getLine(),
1003 MWExceptionHandler::getRedactedTraceAsString( $ex )
1004 )->inLanguage( 'en' )->useDatabase( false )->text();
1005
1006 $dbex = new DBQueryError(
1007 $this->createMock( \Wikimedia\Rdbms\IDatabase::class ),
1008 'error', 1234, 'SELECT 1', __METHOD__ );
1009 $dbtrace = wfMessage( 'api-exception-trace',
1010 get_class( $dbex ),
1011 $dbex->getFile(),
1012 $dbex->getLine(),
1013 MWExceptionHandler::getRedactedTraceAsString( $dbex )
1014 )->inLanguage( 'en' )->useDatabase( false )->text();
1015
1016 // The specific exception doesn't matter, as long as it's namespaced.
1017 $nsex = new MediaWiki\ShellDisabledError();
1018 $nstrace = wfMessage( 'api-exception-trace',
1019 get_class( $nsex ),
1020 $nsex->getFile(),
1021 $nsex->getLine(),
1022 MWExceptionHandler::getRedactedTraceAsString( $nsex )
1023 )->inLanguage( 'en' )->useDatabase( false )->text();
1024
1025 $apiEx1 = new ApiUsageException( null,
1026 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1027 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
1028 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1029 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1030 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1031
1032 $badMsg = $this->getMockBuilder( ApiRawMessage::class )
1033 ->setConstructorArgs( [ 'An error', 'ignored' ] )
1034 ->setMethods( [ 'getApiCode' ] )
1035 ->getMock();
1036 $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1037 $apiEx2 = new ApiUsageException( null, StatusValue::newFatal( $badMsg ) );
1038
1039 return [
1040 [
1041 $ex,
1042 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1043 [
1044 'warnings' => [
1045 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1046 ],
1047 'errors' => [
1048 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1049 [
1050 'code' => 'internal_api_error_InvalidArgumentException',
1051 'text' => "[$reqId] Exception caught: Random exception",
1052 'data' => [
1053 'errorclass' => InvalidArgumentException::class,
1054 ],
1055 ]
1056 ],
1057 'trace' => $trace,
1058 'servedby' => wfHostname(),
1059 ]
1060 ],
1061 [
1062 $dbex,
1063 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1064 [
1065 'warnings' => [
1066 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1067 ],
1068 'errors' => [
1069 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1070 [
1071 'code' => 'internal_api_error_DBQueryError',
1072 'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1073 "This may indicate a bug in the software.",
1074 'data' => [
1075 'errorclass' => DBQueryError::class,
1076 ],
1077 ]
1078 ],
1079 'trace' => $dbtrace,
1080 'servedby' => wfHostname(),
1081 ]
1082 ],
1083 [
1084 $nsex,
1085 [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1086 [
1087 'warnings' => [
1088 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1089 ],
1090 'errors' => [
1091 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1092 [
1093 'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1094 'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1095 'data' => [
1096 'errorclass' => MediaWiki\ShellDisabledError::class,
1097 ],
1098 ]
1099 ],
1100 'trace' => $nstrace,
1101 'servedby' => wfHostname(),
1102 ]
1103 ],
1104 [
1105 $apiEx1,
1106 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1107 [
1108 'warnings' => [
1109 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1110 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1111 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1112 ],
1113 'errors' => [
1114 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1115 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1116 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1117 ],
1118 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1119 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1120 "for notice of API deprecations and breaking changes.",
1121 'servedby' => wfHostname(),
1122 ]
1123 ],
1124 [
1125 $apiEx2,
1126 [ 'existing-error', '<invalid-code>' ],
1127 [
1128 'warnings' => [
1129 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1130 ],
1131 'errors' => [
1132 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1133 [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1134 ],
1135 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1136 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1137 "for notice of API deprecations and breaking changes.",
1138 'servedby' => wfHostname(),
1139 ]
1140 ]
1141 ];
1142 }
1143
1144 public function testPrinterParameterValidationError() {
1145 $api = $this->getNonInternalApiMain( [
1146 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1147 ] );
1148
1149 ob_start();
1150 $api->execute();
1151 $txt = ob_get_clean();
1152
1153 // Test that the actual output is valid JSON, not just the format of the ApiResult.
1154 $data = FormatJson::decode( $txt, true );
1155 $this->assertInternalType( 'array', $data );
1156 $this->assertArrayHasKey( 'error', $data );
1157 $this->assertArrayHasKey( 'code', $data['error'] );
1158 $this->assertSame( 'unknown_formatversion', $data['error']['code'] );
1159 }
1160 }