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