Merge "Use PHPUnit 4/6 compat in VersionCheckerTest"
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiMainTest.php
1 <?php
2
3 use Wikimedia\TestingAccessWrapper;
4
5 /**
6 * @group API
7 * @group Database
8 * @group medium
9 *
10 * @covers ApiMain
11 */
12 class ApiMainTest extends ApiTestCase {
13
14 /**
15 * Test that the API will accept a FauxRequest and execute.
16 */
17 public function testApi() {
18 $api = new ApiMain(
19 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
20 );
21 $api->execute();
22 $data = $api->getResult()->getResultData();
23 $this->assertInternalType( 'array', $data );
24 $this->assertArrayHasKey( 'query', $data );
25 }
26
27 public function testApiNoParam() {
28 $api = new ApiMain();
29 $api->execute();
30 $data = $api->getResult()->getResultData();
31 $this->assertInternalType( 'array', $data );
32 }
33
34 /**
35 * ApiMain behaves differently if passed a FauxRequest (mInternalMode set
36 * to true) or a proper WebRequest (mInternalMode false). For most tests
37 * we can just set mInternalMode to false using TestingAccessWrapper, but
38 * this doesn't work for the constructor. This method returns an ApiMain
39 * that's been set up in non-internal mode.
40 *
41 * Note that calling execute() will print to the console. Wrap it in
42 * ob_start()/ob_end_clean() to prevent this.
43 *
44 * @param array $requestData Query parameters for the WebRequest
45 * @param array $headers Headers for the WebRequest
46 */
47 private function getNonInternalApiMain( array $requestData, array $headers = [] ) {
48 $req = $this->getMockBuilder( WebRequest::class )
49 ->setMethods( [ 'response', 'getRawIP' ] )
50 ->getMock();
51 $response = new FauxResponse();
52 $req->method( 'response' )->willReturn( $response );
53 $req->method( 'getRawIP' )->willReturn( '127.0.0.1' );
54
55 $wrapper = TestingAccessWrapper::newFromObject( $req );
56 $wrapper->data = $requestData;
57 if ( $headers ) {
58 $wrapper->headers = $headers;
59 }
60
61 return new ApiMain( $req );
62 }
63
64 public function testUselang() {
65 global $wgLang;
66
67 $api = $this->getNonInternalApiMain( [
68 'action' => 'query',
69 'meta' => 'siteinfo',
70 'uselang' => 'fr',
71 ] );
72
73 ob_start();
74 $api->execute();
75 ob_end_clean();
76
77 $this->assertSame( 'fr', $wgLang->getCode() );
78 }
79
80 public function testNonWhitelistedCorsWithCookies() {
81 $logFile = $this->getNewTempFile();
82
83 $this->mergeMwGlobalArrayValue( '_COOKIE', [ 'forceHTTPS' => '1' ] );
84 $logger = new TestLogger( true );
85 $this->setLogger( 'cors', $logger );
86
87 $api = $this->getNonInternalApiMain( [
88 'action' => 'query',
89 'meta' => 'siteinfo',
90 // For some reason multiple origins (which are not allowed in the
91 // WHATWG Fetch spec that supersedes the RFC) are always considered to
92 // be problematic.
93 ], [ 'ORIGIN' => 'https://www.example.com https://www.com.example' ] );
94
95 $this->assertSame(
96 [ [ Psr\Log\LogLevel::WARNING, 'Non-whitelisted CORS request with session cookies' ] ],
97 $logger->getBuffer()
98 );
99 }
100
101 public function testSuppressedLogin() {
102 global $wgUser;
103 $origUser = $wgUser;
104
105 $api = $this->getNonInternalApiMain( [
106 'action' => 'query',
107 'meta' => 'siteinfo',
108 'origin' => '*',
109 ] );
110
111 ob_start();
112 $api->execute();
113 ob_end_clean();
114
115 $this->assertNotSame( $origUser, $wgUser );
116 $this->assertSame( 'true', $api->getContext()->getRequest()->response()
117 ->getHeader( 'MediaWiki-Login-Suppressed' ) );
118 }
119
120 public function testSetContinuationManager() {
121 $api = new ApiMain();
122 $manager = $this->createMock( ApiContinuationManager::class );
123 $api->setContinuationManager( $manager );
124 $this->assertTrue( true, 'No exception' );
125 return [ $api, $manager ];
126 }
127
128 /**
129 * @depends testSetContinuationManager
130 */
131 public function testSetContinuationManagerTwice( $args ) {
132 $this->setExpectedException( UnexpectedValueException::class,
133 'ApiMain::setContinuationManager: tried to set manager from ' .
134 'when a manager is already set from ' );
135
136 list( $api, $manager ) = $args;
137 $api->setContinuationManager( $manager );
138 }
139
140 public function testSetCacheModeUnrecognized() {
141 $api = new ApiMain();
142 $api->setCacheMode( 'unrecognized' );
143 $this->assertSame(
144 'private',
145 TestingAccessWrapper::newFromObject( $api )->mCacheMode,
146 'Unrecognized params must be silently ignored'
147 );
148 }
149
150 public function testSetCacheModePrivateWiki() {
151 $this->setGroupPermissions( '*', 'read', false );
152
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 $user->mRights = $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 if all classes in the main module manager exists
439 */
440 public function testClassNamesInModuleManager() {
441 $api = new ApiMain(
442 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
443 );
444 $modules = $api->getModuleManager()->getNamesWithClasses();
445
446 foreach ( $modules as $name => $class ) {
447 $this->assertTrue(
448 class_exists( $class ),
449 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
450 );
451 }
452 }
453
454 /**
455 * Test HTTP precondition headers
456 *
457 * @dataProvider provideCheckConditionalRequestHeaders
458 * @param array $headers HTTP headers
459 * @param array $conditions Return data for ApiBase::getConditionalRequestData
460 * @param int $status Expected response status
461 * @param array $options Array of options:
462 * post => true Request is a POST
463 * cdn => true CDN is enabled ($wgUseSquid)
464 */
465 public function testCheckConditionalRequestHeaders(
466 $headers, $conditions, $status, $options = []
467 ) {
468 $request = new FauxRequest(
469 [ 'action' => 'query', 'meta' => 'siteinfo' ],
470 !empty( $options['post'] )
471 );
472 $request->setHeaders( $headers );
473 $request->response()->statusHeader( 200 ); // Why doesn't it default?
474
475 $context = $this->apiContext->newTestContext( $request, null );
476 $api = new ApiMain( $context );
477 $priv = TestingAccessWrapper::newFromObject( $api );
478 $priv->mInternalMode = false;
479
480 if ( !empty( $options['cdn'] ) ) {
481 $this->setMwGlobals( 'wgUseSquid', true );
482 }
483
484 // Can't do this in TestSetup.php because Setup.php will override it
485 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
486
487 $module = $this->getMockBuilder( ApiBase::class )
488 ->setConstructorArgs( [ $api, 'mock' ] )
489 ->setMethods( [ 'getConditionalRequestData' ] )
490 ->getMockForAbstractClass();
491 $module->expects( $this->any() )
492 ->method( 'getConditionalRequestData' )
493 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
494 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
495 } ) );
496
497 $ret = $priv->checkConditionalRequestHeaders( $module );
498
499 $this->assertSame( $status, $request->response()->getStatusCode() );
500 $this->assertSame( $status === 200, $ret );
501 }
502
503 public static function provideCheckConditionalRequestHeaders() {
504 global $wgSquidMaxage;
505 $now = time();
506
507 return [
508 // Non-existing from module is ignored
509 'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
510 'If-Modified-Since' =>
511 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
512
513 // No headers
514 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
515
516 // Basic If-None-Match
517 'If-None-Match with matching etag' =>
518 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
519 'If-None-Match with non-matching etag' =>
520 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
521 'Strong If-None-Match with weak matching etag' =>
522 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
523 'Weak If-None-Match with strong matching etag' =>
524 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
525 'Weak If-None-Match with weak matching etag' =>
526 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
527
528 // Pointless for GET, but supported
529 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
530
531 // Basic If-Modified-Since
532 'If-Modified-Since, modified one second earlier' =>
533 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
534 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
535 'If-Modified-Since, modified now' =>
536 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
537 [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
538 'If-Modified-Since, modified one second later' =>
539 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
540 [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
541
542 // If-Modified-Since ignored when If-None-Match is given too
543 'Non-matching If-None-Match and matching If-Modified-Since' =>
544 [ [ 'If-None-Match' => '""',
545 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
546 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
547 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
548 [
549 [
550 'If-None-Match' => '""',
551 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now )
552 ],
553 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ],
554 304
555 ],
556
557 // Ignored for POST
558 'Matching If-None-Match with POST' =>
559 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
560 [ 'post' => true ] ],
561 'Matching If-Modified-Since with POST' =>
562 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
563 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200,
564 [ 'post' => true ] ],
565
566 // Other date formats allowed by the RFC
567 'If-Modified-Since with alternate date format 1' =>
568 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
569 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
570 'If-Modified-Since with alternate date format 2' =>
571 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
572 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
573
574 // Old browser extension to HTTP/1.0
575 'If-Modified-Since with length' =>
576 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
577 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
578
579 // Invalid date formats should be ignored
580 'If-Modified-Since with invalid date format' =>
581 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
582 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
583 'If-Modified-Since with entirely unparseable date' =>
584 [ [ 'If-Modified-Since' => 'a potato' ],
585 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
586
587 // Anything before $wgSquidMaxage seconds ago should be considered
588 // expired.
589 'If-Modified-Since with CDN post-expiry' =>
590 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgSquidMaxage * 2 ) ],
591 [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgSquidMaxage * 3 ) ],
592 200, [ 'cdn' => true ] ],
593 'If-Modified-Since with CDN pre-expiry' =>
594 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgSquidMaxage / 2 ) ],
595 [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgSquidMaxage * 3 ) ],
596 304, [ 'cdn' => true ] ],
597 ];
598 }
599
600 /**
601 * Test conditional headers output
602 * @dataProvider provideConditionalRequestHeadersOutput
603 * @param array $conditions Return data for ApiBase::getConditionalRequestData
604 * @param array $headers Expected output headers
605 * @param bool $isError $isError flag
606 * @param bool $post Request is a POST
607 */
608 public function testConditionalRequestHeadersOutput(
609 $conditions, $headers, $isError = false, $post = false
610 ) {
611 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
612 $response = $request->response();
613
614 $api = new ApiMain( $request );
615 $priv = TestingAccessWrapper::newFromObject( $api );
616 $priv->mInternalMode = false;
617
618 $module = $this->getMockBuilder( ApiBase::class )
619 ->setConstructorArgs( [ $api, 'mock' ] )
620 ->setMethods( [ 'getConditionalRequestData' ] )
621 ->getMockForAbstractClass();
622 $module->expects( $this->any() )
623 ->method( 'getConditionalRequestData' )
624 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
625 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
626 } ) );
627 $priv->mModule = $module;
628
629 $priv->sendCacheHeaders( $isError );
630
631 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
632 $this->assertEquals(
633 isset( $headers[$header] ) ? $headers[$header] : null,
634 $response->getHeader( $header ),
635 $header
636 );
637 }
638 }
639
640 public static function provideConditionalRequestHeadersOutput() {
641 return [
642 [
643 [],
644 []
645 ],
646 [
647 [ 'etag' => '"foo"' ],
648 [ 'ETag' => '"foo"' ]
649 ],
650 [
651 [ 'last-modified' => '20150818000102' ],
652 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
653 ],
654 [
655 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
656 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
657 ],
658 [
659 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
660 [],
661 true,
662 ],
663 [
664 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
665 [],
666 false,
667 true,
668 ],
669 ];
670 }
671
672 public function testCheckExecutePermissionsReadProhibited() {
673 $this->setExpectedException( ApiUsageException::class,
674 'You need read permission to use this module.' );
675
676 $this->setGroupPermissions( '*', 'read', false );
677
678 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
679 $main->execute();
680 }
681
682 public function testCheckExecutePermissionWriteDisabled() {
683 $this->setExpectedException( ApiUsageException::class,
684 'Editing of this wiki through the API is disabled. Make sure the ' .
685 '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
686 '"LocalSettings.php" file.' );
687 $main = new ApiMain( new FauxRequest( [
688 'action' => 'edit',
689 'title' => 'Some page',
690 'text' => 'Some text',
691 'token' => '+\\',
692 ] ) );
693 $main->execute();
694 }
695
696 public function testCheckExecutePermissionWriteApiProhibited() {
697 $this->setExpectedException( ApiUsageException::class,
698 "You're not allowed to edit this wiki through the API." );
699 $this->setGroupPermissions( '*', 'writeapi', false );
700
701 $main = new ApiMain( new FauxRequest( [
702 'action' => 'edit',
703 'title' => 'Some page',
704 'text' => 'Some text',
705 'token' => '+\\',
706 ] ), /* enableWrite = */ true );
707 $main->execute();
708 }
709
710 public function testCheckExecutePermissionPromiseNonWrite() {
711 $this->setExpectedException( ApiUsageException::class,
712 'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
713 'to write-mode API modules.' );
714
715 $req = new FauxRequest( [
716 'action' => 'edit',
717 'title' => 'Some page',
718 'text' => 'Some text',
719 'token' => '+\\',
720 ] );
721 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
722 $main = new ApiMain( $req, /* enableWrite = */ true );
723 $main->execute();
724 }
725
726 public function testCheckExecutePermissionHookAbort() {
727 $this->setExpectedException( ApiUsageException::class, 'Main Page' );
728
729 $this->setTemporaryHook( 'ApiCheckCanExecute', function ( $unused1, $unused2, &$message ) {
730 $message = 'mainpage';
731 return false;
732 } );
733
734 $main = new ApiMain( new FauxRequest( [
735 'action' => 'edit',
736 'title' => 'Some page',
737 'text' => 'Some text',
738 'token' => '+\\',
739 ] ), /* enableWrite = */ true );
740 $main->execute();
741 }
742
743 public function testGetValUnsupportedArray() {
744 $main = new ApiMain( new FauxRequest( [
745 'action' => 'query',
746 'meta' => 'siteinfo',
747 'siprop' => [ 'general', 'namespaces' ],
748 ] ) );
749 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
750 $main->execute();
751 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
752 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
753 }
754
755 public function testReportUnusedParams() {
756 $main = new ApiMain( new FauxRequest( [
757 'action' => 'query',
758 'meta' => 'siteinfo',
759 'unusedparam' => 'unusedval',
760 'anotherunusedparam' => 'anotherval',
761 ] ) );
762 $main->execute();
763 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
764 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
765 }
766
767 public function testLacksSameOriginSecurity() {
768 // Basic test
769 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
770 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
771
772 // JSONp
773 $main = new ApiMain(
774 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
775 );
776 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
777
778 // Header
779 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
780 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
781 $main = new ApiMain( $request );
782 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
783
784 // Hook
785 $this->mergeMwGlobalArrayValue( 'wgHooks', [
786 'RequestHasSameOriginSecurity' => [ function () {
787 return false;
788 } ]
789 ] );
790 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
791 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
792 }
793
794 /**
795 * Test proper creation of the ApiErrorFormatter
796 *
797 * @dataProvider provideApiErrorFormatterCreation
798 * @param array $request Request parameters
799 * @param array $expect Expected data
800 * - uselang: ApiMain language
801 * - class: ApiErrorFormatter class
802 * - lang: ApiErrorFormatter language
803 * - format: ApiErrorFormatter format
804 * - usedb: ApiErrorFormatter use-database flag
805 */
806 public function testApiErrorFormatterCreation( array $request, array $expect ) {
807 $context = new RequestContext();
808 $context->setRequest( new FauxRequest( $request ) );
809 $context->setLanguage( 'ru' );
810
811 $main = new ApiMain( $context );
812 $formatter = $main->getErrorFormatter();
813 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
814
815 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
816 $this->assertInstanceOf( $expect['class'], $formatter );
817 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
818 $this->assertSame( $expect['format'], $wrappedFormatter->format );
819 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
820 }
821
822 public static function provideApiErrorFormatterCreation() {
823 return [
824 'Default (BC)' => [ [], [
825 'uselang' => 'ru',
826 'class' => ApiErrorFormatter_BackCompat::class,
827 'lang' => 'en',
828 'format' => 'none',
829 'usedb' => false,
830 ] ],
831 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
832 'uselang' => 'ru',
833 'class' => ApiErrorFormatter_BackCompat::class,
834 'lang' => 'en',
835 'format' => 'none',
836 'usedb' => false,
837 ] ],
838 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
839 'uselang' => 'ru',
840 'class' => ApiErrorFormatter_BackCompat::class,
841 'lang' => 'en',
842 'format' => 'none',
843 'usedb' => false,
844 ] ],
845 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
846 'uselang' => 'ru',
847 'class' => ApiErrorFormatter::class,
848 'lang' => 'ru',
849 'format' => 'wikitext',
850 'usedb' => false,
851 ] ],
852 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
853 'uselang' => 'fr',
854 'class' => ApiErrorFormatter::class,
855 'lang' => 'fr',
856 'format' => 'plaintext',
857 'usedb' => false,
858 ] ],
859 'Explicitly follows uselang' => [
860 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
861 [
862 'uselang' => 'fr',
863 'class' => ApiErrorFormatter::class,
864 'lang' => 'fr',
865 'format' => 'plaintext',
866 'usedb' => false,
867 ]
868 ],
869 'uselang=content' => [
870 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
871 [
872 'uselang' => 'en',
873 'class' => ApiErrorFormatter::class,
874 'lang' => 'en',
875 'format' => 'plaintext',
876 'usedb' => false,
877 ]
878 ],
879 'errorlang=content' => [
880 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
881 [
882 'uselang' => 'ru',
883 'class' => ApiErrorFormatter::class,
884 'lang' => 'en',
885 'format' => 'plaintext',
886 'usedb' => false,
887 ]
888 ],
889 'Explicit parameters' => [
890 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
891 [
892 'uselang' => 'ru',
893 'class' => ApiErrorFormatter::class,
894 'lang' => 'de',
895 'format' => 'html',
896 'usedb' => true,
897 ]
898 ],
899 'Explicit parameters override uselang' => [
900 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
901 [
902 'uselang' => 'fr',
903 'class' => ApiErrorFormatter::class,
904 'lang' => 'de',
905 'format' => 'raw',
906 'usedb' => false,
907 ]
908 ],
909 'Bogus language doesn\'t explode' => [
910 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
911 [
912 'uselang' => 'en',
913 'class' => ApiErrorFormatter::class,
914 'lang' => 'en',
915 'format' => 'none',
916 'usedb' => false,
917 ]
918 ],
919 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
920 'uselang' => 'ru',
921 'class' => ApiErrorFormatter_BackCompat::class,
922 'lang' => 'en',
923 'format' => 'none',
924 'usedb' => false,
925 ] ],
926 ];
927 }
928
929 /**
930 * @dataProvider provideExceptionErrors
931 * @param Exception $exception
932 * @param array $expectReturn
933 * @param array $expectResult
934 */
935 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
936 $context = new RequestContext();
937 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
938 $context->setLanguage( 'en' );
939 $context->setConfig( new MultiConfig( [
940 new HashConfig( [
941 'ShowHostnames' => true, 'ShowSQLErrors' => false,
942 'ShowExceptionDetails' => true, 'ShowDBErrorBacktrace' => true,
943 ] ),
944 $context->getConfig()
945 ] ) );
946
947 $main = new ApiMain( $context );
948 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
949 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
950
951 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
952 $this->assertSame( $expectReturn, $ret );
953
954 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
955 // so let's try ->assertEquals().
956 $this->assertEquals(
957 $expectResult,
958 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
959 );
960 }
961
962 // Not static so $this can be used
963 public function provideExceptionErrors() {
964 $reqId = WebRequest::getRequestId();
965 $doclink = wfExpandUrl( wfScript( 'api' ) );
966
967 $ex = new InvalidArgumentException( 'Random exception' );
968 $trace = wfMessage( 'api-exception-trace',
969 get_class( $ex ),
970 $ex->getFile(),
971 $ex->getLine(),
972 MWExceptionHandler::getRedactedTraceAsString( $ex )
973 )->inLanguage( 'en' )->useDatabase( false )->text();
974
975 $dbex = new DBQueryError(
976 $this->createMock( \Wikimedia\Rdbms\IDatabase::class ),
977 'error', 1234, 'SELECT 1', __METHOD__ );
978 $dbtrace = wfMessage( 'api-exception-trace',
979 get_class( $dbex ),
980 $dbex->getFile(),
981 $dbex->getLine(),
982 MWExceptionHandler::getRedactedTraceAsString( $dbex )
983 )->inLanguage( 'en' )->useDatabase( false )->text();
984
985 Wikimedia\suppressWarnings();
986 $usageEx = new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] );
987 Wikimedia\restoreWarnings();
988
989 $apiEx1 = new ApiUsageException( null,
990 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
991 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
992 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
993 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
994 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
995
996 return [
997 [
998 $ex,
999 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1000 [
1001 'warnings' => [
1002 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1003 ],
1004 'errors' => [
1005 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1006 [
1007 'code' => 'internal_api_error_InvalidArgumentException',
1008 'text' => "[$reqId] Exception caught: Random exception",
1009 ]
1010 ],
1011 'trace' => $trace,
1012 'servedby' => wfHostname(),
1013 ]
1014 ],
1015 [
1016 $dbex,
1017 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1018 [
1019 'warnings' => [
1020 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1021 ],
1022 'errors' => [
1023 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1024 [
1025 'code' => 'internal_api_error_DBQueryError',
1026 'text' => "[$reqId] Database query error.",
1027 ]
1028 ],
1029 'trace' => $dbtrace,
1030 'servedby' => wfHostname(),
1031 ]
1032 ],
1033 [
1034 $usageEx,
1035 [ 'existing-error', 'ue' ],
1036 [
1037 'warnings' => [
1038 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1039 ],
1040 'errors' => [
1041 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1042 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
1043 ],
1044 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1045 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1046 "for notice of API deprecations and breaking changes.",
1047 'servedby' => wfHostname(),
1048 ]
1049 ],
1050 [
1051 $apiEx1,
1052 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1053 [
1054 'warnings' => [
1055 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1056 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1057 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1058 ],
1059 'errors' => [
1060 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1061 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1062 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1063 ],
1064 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1065 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
1066 "for notice of API deprecations and breaking changes.",
1067 'servedby' => wfHostname(),
1068 ]
1069 ],
1070 ];
1071 }
1072 }