Merge "libs/Message: Improve documentation"
[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', get_class( $mock ),
246 function () use ( $mock ) {
247 return $mock;
248 }
249 );
250 $api->execute();
251 }
252
253 public function testSetupModuleNeedsTokenNeedntBePosted() {
254 $this->setExpectedException( MWException::class,
255 "Module 'testmodule' must require POST to use tokens." );
256
257 $mock = $this->createMock( ApiBase::class );
258 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
259 $mock->method( 'needsToken' )->willReturn( 'csrf' );
260 $mock->method( 'mustBePosted' )->willReturn( false );
261
262 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
263 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
264 function () use ( $mock ) {
265 return $mock;
266 }
267 );
268 $api->execute();
269 }
270
271 public function testCheckMaxLagFailed() {
272 // It's hard to mock the LoadBalancer properly, so instead we'll mock
273 // checkMaxLag (which is tested directly in other tests below).
274 $req = new FauxRequest( [
275 'action' => 'query',
276 'meta' => 'siteinfo',
277 ] );
278
279 $mock = $this->getMockBuilder( ApiMain::class )
280 ->setConstructorArgs( [ $req ] )
281 ->setMethods( [ 'checkMaxLag' ] )
282 ->getMock();
283 $mock->method( 'checkMaxLag' )->willReturn( false );
284
285 $mock->execute();
286
287 $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
288 }
289
290 public function testCheckConditionalRequestHeadersFailed() {
291 // The detailed checking of all cases of checkConditionalRequestHeaders
292 // is below in testCheckConditionalRequestHeaders(), which calls the
293 // method directly. Here we just check that it will stop execution if
294 // it does fail.
295 $now = time();
296
297 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
298
299 $mock = $this->createMock( ApiBase::class );
300 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
301 $mock->method( 'getConditionalRequestData' )
302 ->willReturn( wfTimestamp( TS_MW, $now - 3600 ) );
303 $mock->expects( $this->exactly( 0 ) )->method( 'execute' );
304
305 $req = new FauxRequest( [
306 'action' => 'testmodule',
307 ] );
308 $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822, $now - 3600 ) );
309 $req->setRequestURL( "http://localhost" );
310
311 $api = new ApiMain( $req );
312 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
313 function () use ( $mock ) {
314 return $mock;
315 }
316 );
317
318 $wrapper = TestingAccessWrapper::newFromObject( $api );
319 $wrapper->mInternalMode = false;
320
321 ob_start();
322 $api->execute();
323 ob_end_clean();
324 }
325
326 private function doTestCheckMaxLag( $lag ) {
327 $mockLB = $this->getMockBuilder( LoadBalancer::class )
328 ->disableOriginalConstructor()
329 ->setMethods( [ 'getMaxLag', '__destruct' ] )
330 ->getMock();
331 $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
332 $this->setService( 'DBLoadBalancer', $mockLB );
333
334 $req = new FauxRequest();
335
336 $api = new ApiMain( $req );
337 $wrapper = TestingAccessWrapper::newFromObject( $api );
338
339 $mockModule = $this->createMock( ApiBase::class );
340 $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
341
342 try {
343 $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
344 } finally {
345 if ( $lag > 3 ) {
346 $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
347 $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
348 }
349 }
350 }
351
352 public function testCheckMaxLagOkay() {
353 $this->doTestCheckMaxLag( 3 );
354
355 // No exception, we're happy
356 $this->assertTrue( true );
357 }
358
359 public function testCheckMaxLagExceeded() {
360 $this->setExpectedException( ApiUsageException::class,
361 'Waiting for a database server: 4 seconds lagged.' );
362
363 $this->setMwGlobals( 'wgShowHostnames', false );
364
365 $this->doTestCheckMaxLag( 4 );
366 }
367
368 public function testCheckMaxLagExceededWithHostNames() {
369 $this->setExpectedException( ApiUsageException::class,
370 'Waiting for somehost: 4 seconds lagged.' );
371
372 $this->setMwGlobals( 'wgShowHostnames', true );
373
374 $this->doTestCheckMaxLag( 4 );
375 }
376
377 public static function provideAssert() {
378 return [
379 [ false, [], 'user', 'assertuserfailed' ],
380 [ true, [], 'user', false ],
381 [ true, [], 'bot', 'assertbotfailed' ],
382 [ true, [ 'bot' ], 'user', false ],
383 [ true, [ 'bot' ], 'bot', false ],
384 ];
385 }
386
387 /**
388 * Tests the assert={user|bot} functionality
389 *
390 * @dataProvider provideAssert
391 * @param bool $registered
392 * @param array $rights
393 * @param string $assert
394 * @param string|bool $error False if no error expected
395 */
396 public function testAssert( $registered, $rights, $assert, $error ) {
397 if ( $registered ) {
398 $user = $this->getMutableTestUser()->getUser();
399 $user->load(); // load before setting mRights
400 } else {
401 $user = new User();
402 }
403 $this->overrideUserPermissions( $user, $rights );
404 try {
405 $this->doApiRequest( [
406 'action' => 'query',
407 'assert' => $assert,
408 ], null, null, $user );
409 $this->assertFalse( $error ); // That no error was expected
410 } catch ( ApiUsageException $e ) {
411 $this->assertTrue( self::apiExceptionHasCode( $e, $error ),
412 "Error '{$e->getMessage()}' matched expected '$error'" );
413 }
414 }
415
416 /**
417 * Tests the assertuser= functionality
418 */
419 public function testAssertUser() {
420 $user = $this->getTestUser()->getUser();
421 $this->doApiRequest( [
422 'action' => 'query',
423 'assertuser' => $user->getName(),
424 ], null, null, $user );
425
426 try {
427 $this->doApiRequest( [
428 'action' => 'query',
429 'assertuser' => $user->getName() . 'X',
430 ], null, null, $user );
431 $this->fail( 'Expected exception not thrown' );
432 } catch ( ApiUsageException $e ) {
433 $this->assertTrue( self::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
434 }
435 }
436
437 /**
438 * Test that 'assert' is processed before module errors
439 */
440 public function testAssertBeforeModule() {
441 // Sanity check that the query without assert throws too-many-titles
442 try {
443 $this->doApiRequest( [
444 'action' => 'query',
445 'titles' => implode( '|', range( 1, ApiBase::LIMIT_SML1 + 1 ) ),
446 ], null, null, new User );
447 $this->fail( 'Expected exception not thrown' );
448 } catch ( ApiUsageException $e ) {
449 $this->assertTrue( self::apiExceptionHasCode( $e, 'too-many-titles' ), 'sanity check' );
450 }
451
452 // Now test that the assert happens first
453 try {
454 $this->doApiRequest( [
455 'action' => 'query',
456 'titles' => implode( '|', range( 1, ApiBase::LIMIT_SML1 + 1 ) ),
457 'assert' => 'user',
458 ], null, null, new User );
459 $this->fail( 'Expected exception not thrown' );
460 } catch ( ApiUsageException $e ) {
461 $this->assertTrue( self::apiExceptionHasCode( $e, 'assertuserfailed' ),
462 "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
463 }
464 }
465
466 /**
467 * Test if all classes in the main module manager exists
468 */
469 public function testClassNamesInModuleManager() {
470 $api = new ApiMain(
471 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
472 );
473 $modules = $api->getModuleManager()->getNamesWithClasses();
474
475 foreach ( $modules as $name => $class ) {
476 $this->assertTrue(
477 class_exists( $class ),
478 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
479 );
480 }
481 }
482
483 /**
484 * Test HTTP precondition headers
485 *
486 * @dataProvider provideCheckConditionalRequestHeaders
487 * @param array $headers HTTP headers
488 * @param array $conditions Return data for ApiBase::getConditionalRequestData
489 * @param int $status Expected response status
490 * @param array $options Array of options:
491 * post => true Request is a POST
492 * cdn => true CDN is enabled ($wgUseCdn)
493 */
494 public function testCheckConditionalRequestHeaders(
495 $headers, $conditions, $status, $options = []
496 ) {
497 $request = new FauxRequest(
498 [ 'action' => 'query', 'meta' => 'siteinfo' ],
499 !empty( $options['post'] )
500 );
501 $request->setHeaders( $headers );
502 $request->response()->statusHeader( 200 ); // Why doesn't it default?
503
504 $context = $this->apiContext->newTestContext( $request, null );
505 $api = new ApiMain( $context );
506 $priv = TestingAccessWrapper::newFromObject( $api );
507 $priv->mInternalMode = false;
508
509 if ( !empty( $options['cdn'] ) ) {
510 $this->setMwGlobals( 'wgUseCdn', true );
511 }
512
513 // Can't do this in TestSetup.php because Setup.php will override it
514 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
515
516 $module = $this->getMockBuilder( ApiBase::class )
517 ->setConstructorArgs( [ $api, 'mock' ] )
518 ->setMethods( [ 'getConditionalRequestData' ] )
519 ->getMockForAbstractClass();
520 $module->expects( $this->any() )
521 ->method( 'getConditionalRequestData' )
522 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
523 return $conditions[$condition] ?? null;
524 } ) );
525
526 $ret = $priv->checkConditionalRequestHeaders( $module );
527
528 $this->assertSame( $status, $request->response()->getStatusCode() );
529 $this->assertSame( $status === 200, $ret );
530 }
531
532 public static function provideCheckConditionalRequestHeaders() {
533 global $wgCdnMaxAge;
534 $now = time();
535
536 return [
537 // Non-existing from module is ignored
538 'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
539 'If-Modified-Since' =>
540 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
541
542 // No headers
543 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
544
545 // Basic If-None-Match
546 'If-None-Match with matching etag' =>
547 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
548 'If-None-Match with non-matching etag' =>
549 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
550 'Strong If-None-Match with weak matching etag' =>
551 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
552 'Weak If-None-Match with strong matching etag' =>
553 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
554 'Weak If-None-Match with weak matching etag' =>
555 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
556
557 // Pointless for GET, but supported
558 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
559
560 // Basic If-Modified-Since
561 'If-Modified-Since, modified one second earlier' =>
562 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
563 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
564 'If-Modified-Since, modified now' =>
565 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
566 [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
567 'If-Modified-Since, modified one second later' =>
568 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
569 [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
570
571 // If-Modified-Since ignored when If-None-Match is given too
572 'Non-matching If-None-Match and matching If-Modified-Since' =>
573 [ [ 'If-None-Match' => '""',
574 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
575 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
576 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
577 [
578 [
579 'If-None-Match' => '""',
580 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now )
581 ],
582 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ],
583 304
584 ],
585
586 // Ignored for POST
587 'Matching If-None-Match with POST' =>
588 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
589 [ 'post' => true ] ],
590 'Matching If-Modified-Since with POST' =>
591 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
592 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200,
593 [ 'post' => true ] ],
594
595 // Other date formats allowed by the RFC
596 'If-Modified-Since with alternate date format 1' =>
597 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
598 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
599 'If-Modified-Since with alternate date format 2' =>
600 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
601 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
602
603 // Old browser extension to HTTP/1.0
604 'If-Modified-Since with length' =>
605 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
606 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
607
608 // Invalid date formats should be ignored
609 'If-Modified-Since with invalid date format' =>
610 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
611 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
612 'If-Modified-Since with entirely unparseable date' =>
613 [ [ 'If-Modified-Since' => 'a potato' ],
614 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
615
616 // Anything before $wgCdnMaxAge seconds ago should be considered
617 // expired.
618 'If-Modified-Since with CDN post-expiry' =>
619 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgCdnMaxAge * 2 ) ],
620 [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgCdnMaxAge * 3 ) ],
621 200, [ 'cdn' => true ] ],
622 'If-Modified-Since with CDN pre-expiry' =>
623 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgCdnMaxAge / 2 ) ],
624 [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgCdnMaxAge * 3 ) ],
625 304, [ 'cdn' => true ] ],
626 ];
627 }
628
629 /**
630 * Test conditional headers output
631 * @dataProvider provideConditionalRequestHeadersOutput
632 * @param array $conditions Return data for ApiBase::getConditionalRequestData
633 * @param array $headers Expected output headers
634 * @param bool $isError $isError flag
635 * @param bool $post Request is a POST
636 */
637 public function testConditionalRequestHeadersOutput(
638 $conditions, $headers, $isError = false, $post = false
639 ) {
640 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
641 $response = $request->response();
642
643 $api = new ApiMain( $request );
644 $priv = TestingAccessWrapper::newFromObject( $api );
645 $priv->mInternalMode = false;
646
647 $module = $this->getMockBuilder( ApiBase::class )
648 ->setConstructorArgs( [ $api, 'mock' ] )
649 ->setMethods( [ 'getConditionalRequestData' ] )
650 ->getMockForAbstractClass();
651 $module->expects( $this->any() )
652 ->method( 'getConditionalRequestData' )
653 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
654 return $conditions[$condition] ?? null;
655 } ) );
656 $priv->mModule = $module;
657
658 $priv->sendCacheHeaders( $isError );
659
660 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
661 $this->assertEquals(
662 $headers[$header] ?? null,
663 $response->getHeader( $header ),
664 $header
665 );
666 }
667 }
668
669 public static function provideConditionalRequestHeadersOutput() {
670 return [
671 [
672 [],
673 []
674 ],
675 [
676 [ 'etag' => '"foo"' ],
677 [ 'ETag' => '"foo"' ]
678 ],
679 [
680 [ 'last-modified' => '20150818000102' ],
681 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
682 ],
683 [
684 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
685 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
686 ],
687 [
688 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
689 [],
690 true,
691 ],
692 [
693 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
694 [],
695 false,
696 true,
697 ],
698 ];
699 }
700
701 public function testCheckExecutePermissionsReadProhibited() {
702 $this->setExpectedException( ApiUsageException::class,
703 'You need read permission to use this module.' );
704
705 $this->setGroupPermissions( '*', 'read', false );
706
707 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
708 $main->execute();
709 }
710
711 public function testCheckExecutePermissionWriteDisabled() {
712 $this->setExpectedException( ApiUsageException::class,
713 'Editing of this wiki through the API is disabled. Make sure the ' .
714 '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
715 '"LocalSettings.php" file.' );
716 $main = new ApiMain( new FauxRequest( [
717 'action' => 'edit',
718 'title' => 'Some page',
719 'text' => 'Some text',
720 'token' => '+\\',
721 ] ) );
722 $main->execute();
723 }
724
725 public function testCheckExecutePermissionWriteApiProhibited() {
726 $this->setExpectedException( ApiUsageException::class,
727 "You're not allowed to edit this wiki through the API." );
728 $this->setGroupPermissions( '*', 'writeapi', false );
729
730 $main = new ApiMain( new FauxRequest( [
731 'action' => 'edit',
732 'title' => 'Some page',
733 'text' => 'Some text',
734 'token' => '+\\',
735 ] ), /* enableWrite = */ true );
736 $main->execute();
737 }
738
739 public function testCheckExecutePermissionPromiseNonWrite() {
740 $this->setExpectedException( ApiUsageException::class,
741 'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
742 'to write-mode API modules.' );
743
744 $req = new FauxRequest( [
745 'action' => 'edit',
746 'title' => 'Some page',
747 'text' => 'Some text',
748 'token' => '+\\',
749 ] );
750 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
751 $main = new ApiMain( $req, /* enableWrite = */ true );
752 $main->execute();
753 }
754
755 public function testCheckExecutePermissionHookAbort() {
756 $this->setExpectedException( ApiUsageException::class, 'Main Page' );
757
758 $this->setTemporaryHook( 'ApiCheckCanExecute', function ( $unused1, $unused2, &$message ) {
759 $message = 'mainpage';
760 return false;
761 } );
762
763 $main = new ApiMain( new FauxRequest( [
764 'action' => 'edit',
765 'title' => 'Some page',
766 'text' => 'Some text',
767 'token' => '+\\',
768 ] ), /* enableWrite = */ true );
769 $main->execute();
770 }
771
772 public function testGetValUnsupportedArray() {
773 $main = new ApiMain( new FauxRequest( [
774 'action' => 'query',
775 'meta' => 'siteinfo',
776 'siprop' => [ 'general', 'namespaces' ],
777 ] ) );
778 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
779 $main->execute();
780 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
781 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
782 }
783
784 public function testReportUnusedParams() {
785 $main = new ApiMain( new FauxRequest( [
786 'action' => 'query',
787 'meta' => 'siteinfo',
788 'unusedparam' => 'unusedval',
789 'anotherunusedparam' => 'anotherval',
790 ] ) );
791 $main->execute();
792 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
793 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
794 }
795
796 public function testLacksSameOriginSecurity() {
797 // Basic test
798 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
799 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
800
801 // JSONp
802 $main = new ApiMain(
803 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
804 );
805 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
806
807 // Header
808 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
809 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
810 $main = new ApiMain( $request );
811 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
812
813 // Hook
814 $this->mergeMwGlobalArrayValue( 'wgHooks', [
815 'RequestHasSameOriginSecurity' => [ function () {
816 return false;
817 } ]
818 ] );
819 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
820 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
821 }
822
823 /**
824 * Test proper creation of the ApiErrorFormatter
825 *
826 * @dataProvider provideApiErrorFormatterCreation
827 * @param array $request Request parameters
828 * @param array $expect Expected data
829 * - uselang: ApiMain language
830 * - class: ApiErrorFormatter class
831 * - lang: ApiErrorFormatter language
832 * - format: ApiErrorFormatter format
833 * - usedb: ApiErrorFormatter use-database flag
834 */
835 public function testApiErrorFormatterCreation( array $request, array $expect ) {
836 $context = new RequestContext();
837 $context->setRequest( new FauxRequest( $request ) );
838 $context->setLanguage( 'ru' );
839
840 $main = new ApiMain( $context );
841 $formatter = $main->getErrorFormatter();
842 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
843
844 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
845 $this->assertInstanceOf( $expect['class'], $formatter );
846 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
847 $this->assertSame( $expect['format'], $wrappedFormatter->format );
848 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
849 }
850
851 public static function provideApiErrorFormatterCreation() {
852 return [
853 'Default (BC)' => [ [], [
854 'uselang' => 'ru',
855 'class' => ApiErrorFormatter_BackCompat::class,
856 'lang' => 'en',
857 'format' => 'none',
858 'usedb' => false,
859 ] ],
860 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
861 'uselang' => 'ru',
862 'class' => ApiErrorFormatter_BackCompat::class,
863 'lang' => 'en',
864 'format' => 'none',
865 'usedb' => false,
866 ] ],
867 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
868 'uselang' => 'ru',
869 'class' => ApiErrorFormatter_BackCompat::class,
870 'lang' => 'en',
871 'format' => 'none',
872 'usedb' => false,
873 ] ],
874 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
875 'uselang' => 'ru',
876 'class' => ApiErrorFormatter::class,
877 'lang' => 'ru',
878 'format' => 'wikitext',
879 'usedb' => false,
880 ] ],
881 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
882 'uselang' => 'fr',
883 'class' => ApiErrorFormatter::class,
884 'lang' => 'fr',
885 'format' => 'plaintext',
886 'usedb' => false,
887 ] ],
888 'Explicitly follows uselang' => [
889 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
890 [
891 'uselang' => 'fr',
892 'class' => ApiErrorFormatter::class,
893 'lang' => 'fr',
894 'format' => 'plaintext',
895 'usedb' => false,
896 ]
897 ],
898 'uselang=content' => [
899 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
900 [
901 'uselang' => 'en',
902 'class' => ApiErrorFormatter::class,
903 'lang' => 'en',
904 'format' => 'plaintext',
905 'usedb' => false,
906 ]
907 ],
908 'errorlang=content' => [
909 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
910 [
911 'uselang' => 'ru',
912 'class' => ApiErrorFormatter::class,
913 'lang' => 'en',
914 'format' => 'plaintext',
915 'usedb' => false,
916 ]
917 ],
918 'Explicit parameters' => [
919 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
920 [
921 'uselang' => 'ru',
922 'class' => ApiErrorFormatter::class,
923 'lang' => 'de',
924 'format' => 'html',
925 'usedb' => true,
926 ]
927 ],
928 'Explicit parameters override uselang' => [
929 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
930 [
931 'uselang' => 'fr',
932 'class' => ApiErrorFormatter::class,
933 'lang' => 'de',
934 'format' => 'raw',
935 'usedb' => false,
936 ]
937 ],
938 'Bogus language doesn\'t explode' => [
939 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
940 [
941 'uselang' => 'en',
942 'class' => ApiErrorFormatter::class,
943 'lang' => 'en',
944 'format' => 'none',
945 'usedb' => false,
946 ]
947 ],
948 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
949 'uselang' => 'ru',
950 'class' => ApiErrorFormatter_BackCompat::class,
951 'lang' => 'en',
952 'format' => 'none',
953 'usedb' => false,
954 ] ],
955 ];
956 }
957
958 /**
959 * @dataProvider provideExceptionErrors
960 * @param Exception $exception
961 * @param array $expectReturn
962 * @param array $expectResult
963 */
964 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
965 $context = new RequestContext();
966 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
967 $context->setLanguage( 'en' );
968 $context->setConfig( new MultiConfig( [
969 new HashConfig( [
970 'ShowHostnames' => true, 'ShowExceptionDetails' => true,
971 ] ),
972 $context->getConfig()
973 ] ) );
974
975 $main = new ApiMain( $context );
976 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
977 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
978
979 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
980 $this->assertSame( $expectReturn, $ret );
981
982 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
983 // so let's try ->assertEquals().
984 $this->assertEquals(
985 $expectResult,
986 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
987 );
988 }
989
990 // Not static so $this can be used
991 public function provideExceptionErrors() {
992 $reqId = WebRequest::getRequestId();
993 $doclink = wfExpandUrl( wfScript( 'api' ) );
994
995 $ex = new InvalidArgumentException( 'Random exception' );
996 $trace = wfMessage( 'api-exception-trace',
997 get_class( $ex ),
998 $ex->getFile(),
999 $ex->getLine(),
1000 MWExceptionHandler::getRedactedTraceAsString( $ex )
1001 )->inLanguage( 'en' )->useDatabase( false )->text();
1002
1003 $dbex = new DBQueryError(
1004 $this->createMock( \Wikimedia\Rdbms\IDatabase::class ),
1005 'error', 1234, 'SELECT 1', __METHOD__ );
1006 $dbtrace = wfMessage( 'api-exception-trace',
1007 get_class( $dbex ),
1008 $dbex->getFile(),
1009 $dbex->getLine(),
1010 MWExceptionHandler::getRedactedTraceAsString( $dbex )
1011 )->inLanguage( 'en' )->useDatabase( false )->text();
1012
1013 // The specific exception doesn't matter, as long as it's namespaced.
1014 $nsex = new MediaWiki\ShellDisabledError();
1015 $nstrace = wfMessage( 'api-exception-trace',
1016 get_class( $nsex ),
1017 $nsex->getFile(),
1018 $nsex->getLine(),
1019 MWExceptionHandler::getRedactedTraceAsString( $nsex )
1020 )->inLanguage( 'en' )->useDatabase( false )->text();
1021
1022 $apiEx1 = new ApiUsageException( null,
1023 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1024 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
1025 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1026 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1027 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1028
1029 $badMsg = $this->getMockBuilder( ApiRawMessage::class )
1030 ->setConstructorArgs( [ 'An error', 'ignored' ] )
1031 ->setMethods( [ 'getApiCode' ] )
1032 ->getMock();
1033 $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1034 $apiEx2 = new ApiUsageException( null, StatusValue::newFatal( $badMsg ) );
1035
1036 return [
1037 [
1038 $ex,
1039 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1040 [
1041 'warnings' => [
1042 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1043 ],
1044 'errors' => [
1045 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1046 [
1047 'code' => 'internal_api_error_InvalidArgumentException',
1048 'text' => "[$reqId] Exception caught: Random exception",
1049 'data' => [
1050 'errorclass' => InvalidArgumentException::class,
1051 ],
1052 ]
1053 ],
1054 'trace' => $trace,
1055 'servedby' => wfHostname(),
1056 ]
1057 ],
1058 [
1059 $dbex,
1060 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1061 [
1062 'warnings' => [
1063 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1064 ],
1065 'errors' => [
1066 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1067 [
1068 'code' => 'internal_api_error_DBQueryError',
1069 'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1070 "This may indicate a bug in the software.",
1071 'data' => [
1072 'errorclass' => DBQueryError::class,
1073 ],
1074 ]
1075 ],
1076 'trace' => $dbtrace,
1077 'servedby' => wfHostname(),
1078 ]
1079 ],
1080 [
1081 $nsex,
1082 [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1083 [
1084 'warnings' => [
1085 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1086 ],
1087 'errors' => [
1088 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1089 [
1090 'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1091 'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1092 'data' => [
1093 'errorclass' => MediaWiki\ShellDisabledError::class,
1094 ],
1095 ]
1096 ],
1097 'trace' => $nstrace,
1098 'servedby' => wfHostname(),
1099 ]
1100 ],
1101 [
1102 $apiEx1,
1103 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1104 [
1105 'warnings' => [
1106 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1107 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1108 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1109 ],
1110 'errors' => [
1111 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1112 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1113 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1114 ],
1115 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1116 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1117 "for notice of API deprecations and breaking changes.",
1118 'servedby' => wfHostname(),
1119 ]
1120 ],
1121 [
1122 $apiEx2,
1123 [ 'existing-error', '<invalid-code>' ],
1124 [
1125 'warnings' => [
1126 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1127 ],
1128 'errors' => [
1129 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1130 [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1131 ],
1132 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1133 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1134 "for notice of API deprecations and breaking changes.",
1135 'servedby' => wfHostname(),
1136 ]
1137 ]
1138 ];
1139 }
1140
1141 public function testPrinterParameterValidationError() {
1142 $api = $this->getNonInternalApiMain( [
1143 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1144 ] );
1145
1146 ob_start();
1147 $api->execute();
1148 $txt = ob_get_clean();
1149
1150 // Test that the actual output is valid JSON, not just the format of the ApiResult.
1151 $data = FormatJson::decode( $txt, true );
1152 $this->assertInternalType( 'array', $data );
1153 $this->assertArrayHasKey( 'error', $data );
1154 $this->assertArrayHasKey( 'code', $data['error'] );
1155 $this->assertSame( 'unknown_formatversion', $data['error']['code'] );
1156 }
1157 }