Merge "build: Karma proxy should convert Host header"
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiMainTest.php
1 <?php
2
3 /**
4 * @group API
5 * @group medium
6 *
7 * @covers ApiMain
8 */
9 class ApiMainTest extends ApiTestCase {
10
11 /**
12 * Test that the API will accept a FauxRequest and execute.
13 */
14 public function testApi() {
15 $api = new ApiMain(
16 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
17 );
18 $api->execute();
19 $data = $api->getResult()->getResultData();
20 $this->assertInternalType( 'array', $data );
21 $this->assertArrayHasKey( 'query', $data );
22 }
23
24 public static function provideAssert() {
25 return [
26 [ false, [], 'user', 'assertuserfailed' ],
27 [ true, [], 'user', false ],
28 [ true, [], 'bot', 'assertbotfailed' ],
29 [ true, [ 'bot' ], 'user', false ],
30 [ true, [ 'bot' ], 'bot', false ],
31 ];
32 }
33
34 /**
35 * Tests the assert={user|bot} functionality
36 *
37 * @covers ApiMain::checkAsserts
38 * @dataProvider provideAssert
39 * @param bool $registered
40 * @param array $rights
41 * @param string $assert
42 * @param string|bool $error False if no error expected
43 */
44 public function testAssert( $registered, $rights, $assert, $error ) {
45 $user = new User();
46 if ( $registered ) {
47 $user->setId( 1 );
48 }
49 $user->mRights = $rights;
50 try {
51 $this->doApiRequest( [
52 'action' => 'query',
53 'assert' => $assert,
54 ], null, null, $user );
55 $this->assertFalse( $error ); // That no error was expected
56 } catch ( ApiUsageException $e ) {
57 $this->assertTrue( self::apiExceptionHasCode( $e, $error ) );
58 }
59 }
60
61 /**
62 * Tests the assertuser= functionality
63 *
64 * @covers ApiMain::checkAsserts
65 */
66 public function testAssertUser() {
67 $user = $this->getTestUser()->getUser();
68 $this->doApiRequest( [
69 'action' => 'query',
70 'assertuser' => $user->getName(),
71 ], null, null, $user );
72
73 try {
74 $this->doApiRequest( [
75 'action' => 'query',
76 'assertuser' => $user->getName() . 'X',
77 ], null, null, $user );
78 $this->fail( 'Expected exception not thrown' );
79 } catch ( ApiUsageException $e ) {
80 $this->assertTrue( self::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
81 }
82 }
83
84 /**
85 * Test if all classes in the main module manager exists
86 */
87 public function testClassNamesInModuleManager() {
88 $api = new ApiMain(
89 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
90 );
91 $modules = $api->getModuleManager()->getNamesWithClasses();
92
93 foreach ( $modules as $name => $class ) {
94 $this->assertTrue(
95 class_exists( $class ),
96 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
97 );
98 }
99 }
100
101 /**
102 * Test HTTP precondition headers
103 *
104 * @covers ApiMain::checkConditionalRequestHeaders
105 * @dataProvider provideCheckConditionalRequestHeaders
106 * @param array $headers HTTP headers
107 * @param array $conditions Return data for ApiBase::getConditionalRequestData
108 * @param int $status Expected response status
109 * @param bool $post Request is a POST
110 */
111 public function testCheckConditionalRequestHeaders(
112 $headers, $conditions, $status, $post = false
113 ) {
114 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
115 $request->setHeaders( $headers );
116 $request->response()->statusHeader( 200 ); // Why doesn't it default?
117
118 $context = $this->apiContext->newTestContext( $request, null );
119 $api = new ApiMain( $context );
120 $priv = TestingAccessWrapper::newFromObject( $api );
121 $priv->mInternalMode = false;
122
123 $module = $this->getMockBuilder( 'ApiBase' )
124 ->setConstructorArgs( [ $api, 'mock' ] )
125 ->setMethods( [ 'getConditionalRequestData' ] )
126 ->getMockForAbstractClass();
127 $module->expects( $this->any() )
128 ->method( 'getConditionalRequestData' )
129 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
130 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
131 } ) );
132
133 $ret = $priv->checkConditionalRequestHeaders( $module );
134
135 $this->assertSame( $status, $request->response()->getStatusCode() );
136 $this->assertSame( $status === 200, $ret );
137 }
138
139 public static function provideCheckConditionalRequestHeaders() {
140 $now = time();
141
142 return [
143 // Non-existing from module is ignored
144 [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
145 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
146
147 // No headers
148 [
149 [],
150 [
151 'etag' => '""',
152 'last-modified' => '20150815000000',
153 ],
154 200
155 ],
156
157 // Basic If-None-Match
158 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
159 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
160 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
161 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
162 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
163
164 // Pointless, but supported
165 [ [ 'If-None-Match' => '*' ], [], 304 ],
166
167 // Basic If-Modified-Since
168 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
169 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
170 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
171 [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
172 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
173 [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
174
175 // If-Modified-Since ignored when If-None-Match is given too
176 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
177 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
178 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
179 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
180
181 // Ignored for POST
182 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
183 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
184 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200, true ],
185
186 // Other date formats allowed by the RFC
187 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
188 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
189 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
190 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
191
192 // Old browser extension to HTTP/1.0
193 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
194 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
195
196 // Invalid date formats should be ignored
197 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
198 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
199 ];
200 }
201
202 /**
203 * Test conditional headers output
204 * @dataProvider provideConditionalRequestHeadersOutput
205 * @param array $conditions Return data for ApiBase::getConditionalRequestData
206 * @param array $headers Expected output headers
207 * @param bool $isError $isError flag
208 * @param bool $post Request is a POST
209 */
210 public function testConditionalRequestHeadersOutput(
211 $conditions, $headers, $isError = false, $post = false
212 ) {
213 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
214 $response = $request->response();
215
216 $api = new ApiMain( $request );
217 $priv = TestingAccessWrapper::newFromObject( $api );
218 $priv->mInternalMode = false;
219
220 $module = $this->getMockBuilder( 'ApiBase' )
221 ->setConstructorArgs( [ $api, 'mock' ] )
222 ->setMethods( [ 'getConditionalRequestData' ] )
223 ->getMockForAbstractClass();
224 $module->expects( $this->any() )
225 ->method( 'getConditionalRequestData' )
226 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
227 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
228 } ) );
229 $priv->mModule = $module;
230
231 $priv->sendCacheHeaders( $isError );
232
233 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
234 $this->assertEquals(
235 isset( $headers[$header] ) ? $headers[$header] : null,
236 $response->getHeader( $header ),
237 $header
238 );
239 }
240 }
241
242 public static function provideConditionalRequestHeadersOutput() {
243 return [
244 [
245 [],
246 []
247 ],
248 [
249 [ 'etag' => '"foo"' ],
250 [ 'ETag' => '"foo"' ]
251 ],
252 [
253 [ 'last-modified' => '20150818000102' ],
254 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
255 ],
256 [
257 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
258 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
259 ],
260 [
261 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
262 [],
263 true,
264 ],
265 [
266 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
267 [],
268 false,
269 true,
270 ],
271 ];
272 }
273
274 /**
275 * @covers ApiMain::lacksSameOriginSecurity
276 */
277 public function testLacksSameOriginSecurity() {
278 // Basic test
279 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
280 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
281
282 // JSONp
283 $main = new ApiMain(
284 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
285 );
286 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
287
288 // Header
289 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
290 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
291 $main = new ApiMain( $request );
292 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
293
294 // Hook
295 $this->mergeMwGlobalArrayValue( 'wgHooks', [
296 'RequestHasSameOriginSecurity' => [ function () {
297 return false;
298 } ]
299 ] );
300 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
301 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
302 }
303
304 /**
305 * Test proper creation of the ApiErrorFormatter
306 * @covers ApiMain::__construct
307 * @dataProvider provideApiErrorFormatterCreation
308 * @param array $request Request parameters
309 * @param array $expect Expected data
310 * - uselang: ApiMain language
311 * - class: ApiErrorFormatter class
312 * - lang: ApiErrorFormatter language
313 * - format: ApiErrorFormatter format
314 * - usedb: ApiErrorFormatter use-database flag
315 */
316 public function testApiErrorFormatterCreation( array $request, array $expect ) {
317 $context = new RequestContext();
318 $context->setRequest( new FauxRequest( $request ) );
319 $context->setLanguage( 'ru' );
320
321 $main = new ApiMain( $context );
322 $formatter = $main->getErrorFormatter();
323 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
324
325 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
326 $this->assertInstanceOf( $expect['class'], $formatter );
327 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
328 $this->assertSame( $expect['format'], $wrappedFormatter->format );
329 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
330 }
331
332 public static function provideApiErrorFormatterCreation() {
333 global $wgContLang;
334
335 return [
336 'Default (BC)' => [ [], [
337 'uselang' => 'ru',
338 'class' => ApiErrorFormatter_BackCompat::class,
339 'lang' => 'en',
340 'format' => 'none',
341 'usedb' => false,
342 ] ],
343 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
344 'uselang' => 'ru',
345 'class' => ApiErrorFormatter_BackCompat::class,
346 'lang' => 'en',
347 'format' => 'none',
348 'usedb' => false,
349 ] ],
350 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
351 'uselang' => 'ru',
352 'class' => ApiErrorFormatter_BackCompat::class,
353 'lang' => 'en',
354 'format' => 'none',
355 'usedb' => false,
356 ] ],
357 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
358 'uselang' => 'ru',
359 'class' => ApiErrorFormatter::class,
360 'lang' => 'ru',
361 'format' => 'wikitext',
362 'usedb' => false,
363 ] ],
364 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
365 'uselang' => 'fr',
366 'class' => ApiErrorFormatter::class,
367 'lang' => 'fr',
368 'format' => 'plaintext',
369 'usedb' => false,
370 ] ],
371 'Explicitly follows uselang' => [
372 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
373 [
374 'uselang' => 'fr',
375 'class' => ApiErrorFormatter::class,
376 'lang' => 'fr',
377 'format' => 'plaintext',
378 'usedb' => false,
379 ]
380 ],
381 'uselang=content' => [
382 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
383 [
384 'uselang' => $wgContLang->getCode(),
385 'class' => ApiErrorFormatter::class,
386 'lang' => $wgContLang->getCode(),
387 'format' => 'plaintext',
388 'usedb' => false,
389 ]
390 ],
391 'errorlang=content' => [
392 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
393 [
394 'uselang' => 'ru',
395 'class' => ApiErrorFormatter::class,
396 'lang' => $wgContLang->getCode(),
397 'format' => 'plaintext',
398 'usedb' => false,
399 ]
400 ],
401 'Explicit parameters' => [
402 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
403 [
404 'uselang' => 'ru',
405 'class' => ApiErrorFormatter::class,
406 'lang' => 'de',
407 'format' => 'html',
408 'usedb' => true,
409 ]
410 ],
411 'Explicit parameters override uselang' => [
412 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
413 [
414 'uselang' => 'fr',
415 'class' => ApiErrorFormatter::class,
416 'lang' => 'de',
417 'format' => 'raw',
418 'usedb' => false,
419 ]
420 ],
421 'Bogus language doesn\'t explode' => [
422 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
423 [
424 'uselang' => 'en',
425 'class' => ApiErrorFormatter::class,
426 'lang' => 'en',
427 'format' => 'none',
428 'usedb' => false,
429 ]
430 ],
431 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
432 'uselang' => 'ru',
433 'class' => ApiErrorFormatter_BackCompat::class,
434 'lang' => 'en',
435 'format' => 'none',
436 'usedb' => false,
437 ] ],
438 ];
439 }
440
441 /**
442 * @covers ApiMain::errorMessagesFromException
443 * @covers ApiMain::substituteResultWithError
444 * @dataProvider provideExceptionErrors
445 * @param Exception $exception
446 * @param array $expectReturn
447 * @param array $expectResult
448 */
449 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
450 $context = new RequestContext();
451 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
452 $context->setLanguage( 'en' );
453 $context->setConfig( new MultiConfig( [
454 new HashConfig( [ 'ShowHostnames' => true, 'ShowSQLErrors' => false ] ),
455 $context->getConfig()
456 ] ) );
457
458 $main = new ApiMain( $context );
459 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
460 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
461
462 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
463 $this->assertSame( $expectReturn, $ret );
464
465 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
466 // so let's try ->assertEquals().
467 $this->assertEquals(
468 $expectResult,
469 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
470 );
471 }
472
473 // Not static so $this->getMock() can be used
474 public function provideExceptionErrors() {
475 $reqId = WebRequest::getRequestId();
476 $doclink = wfExpandUrl( wfScript( 'api' ) );
477
478 $ex = new InvalidArgumentException( 'Random exception' );
479 $trace = wfMessage( 'api-exception-trace',
480 get_class( $ex ),
481 $ex->getFile(),
482 $ex->getLine(),
483 MWExceptionHandler::getRedactedTraceAsString( $ex )
484 )->inLanguage( 'en' )->useDatabase( false )->text();
485
486 $dbex = new DBQueryError( $this->getMock( 'IDatabase' ), 'error', 1234, 'SELECT 1', __METHOD__ );
487 $dbtrace = wfMessage( 'api-exception-trace',
488 get_class( $dbex ),
489 $dbex->getFile(),
490 $dbex->getLine(),
491 MWExceptionHandler::getRedactedTraceAsString( $dbex )
492 )->inLanguage( 'en' )->useDatabase( false )->text();
493
494 $apiEx1 = new ApiUsageException( null,
495 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
496 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
497 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
498 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
499 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
500
501 return [
502 [
503 $ex,
504 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
505 [
506 'warnings' => [
507 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
508 ],
509 'errors' => [
510 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
511 [
512 'code' => 'internal_api_error_InvalidArgumentException',
513 'text' => "[$reqId] Exception caught: Random exception",
514 ]
515 ],
516 'trace' => $trace,
517 'servedby' => wfHostname(),
518 ]
519 ],
520 [
521 $dbex,
522 [ 'existing-error', 'internal_api_error_DBQueryError' ],
523 [
524 'warnings' => [
525 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
526 ],
527 'errors' => [
528 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
529 [
530 'code' => 'internal_api_error_DBQueryError',
531 'text' => "[$reqId] Database query error.",
532 ]
533 ],
534 'trace' => $dbtrace,
535 'servedby' => wfHostname(),
536 ]
537 ],
538 [
539 new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] ),
540 [ 'existing-error', 'ue' ],
541 [
542 'warnings' => [
543 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
544 ],
545 'errors' => [
546 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
547 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
548 ],
549 'docref' => "See $doclink for API usage.",
550 'servedby' => wfHostname(),
551 ]
552 ],
553 [
554 $apiEx1,
555 [ 'existing-error', 'sv-error1', 'sv-error2' ],
556 [
557 'warnings' => [
558 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
559 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
560 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
561 ],
562 'errors' => [
563 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
564 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
565 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
566 ],
567 'docref' => "See $doclink for API usage.",
568 'servedby' => wfHostname(),
569 ]
570 ],
571 ];
572 }
573 }