Debian Codegraph @

tests/phpunit/unit/includes/Rest/Handler/HandlerTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Handler;
4
5 use GuzzleHttp\Psr7\Uri;
6 use MediaWiki\ParamValidator\TypeDef\ArrayDef;
7 use MediaWiki\Rest\ConditionalHeaderUtil;
8 use MediaWiki\Rest\Handler;
9 use MediaWiki\Rest\HttpException;
10 use MediaWiki\Rest\LocalizedHttpException;
11 use MediaWiki\Rest\Module\Module;
12 use MediaWiki\Rest\RequestData;
13 use MediaWiki\Rest\RequestInterface;
14 use MediaWiki\Rest\Response;
15 use MediaWiki\Rest\ResponseFactory;
16 use MediaWiki\Rest\ResponseInterface;
17 use MediaWiki\Rest\Router;
18 use MediaWiki\Rest\Validator\BodyValidator;
19 use MediaWiki\Session\Session;
20 use MediaWikiUnitTestCase;
21 use PHPUnit\Framework\Assert;
22 use PHPUnit\Framework\MockObject\MockObject;
23 use Wikimedia\Message\MessageValue;
24 use Wikimedia\ParamValidator\ParamValidator;
25 use Wikimedia\TestingAccessWrapper;
26 use Wikimedia\Timestamp\ConvertibleTimestamp;
27
28 /**
29 * @covers \MediaWiki\Rest\Handler
30 */
31 class HandlerTest extends MediaWikiUnitTestCase {
32
33 use HandlerTestTrait;
34
35 /**
36 * @param string[] $methods
37 *
38 * @return Handler&MockObject
39 */
40 private function newHandler( $methods = [] ) {
41 $methods = array_merge( $methods, [ 'execute' ] );
42 /** @var Handler&MockObject $handler */
43 $handler = $this->getMockBuilder( Handler::class )
44 ->onlyMethods( $methods )
45 ->getMock();
46 $handler->method( 'execute' )->willReturn( (object)[] );
47
48 return $handler;
49 }
50
51 private function initHandlerPartially( Handler $handler ) {
52 $formatter = $this->getDummyTextFormatter( true );
53 $responseFactory = new ResponseFactory( [ 'qqx' => $formatter ] );
54
55 $router = $this->newRouter();
56 $module = $this->newModule( [ 'router' => $router ] );
57
58 $authority = $this->mockAnonUltimateAuthority();
59 $hookContainer = $this->createHookContainer();
60
61 $session = $this->getSession( true );
62 $handler->initContext( $module, 'test', [] );
63 $handler->initServices( $authority, $responseFactory, $hookContainer );
64 $handler->initSession( $session );
65
66 return $handler;
67 }
68
69 public function testGetRouter() {
70 $handler = $this->newHandler();
71 $this->initHandler( $handler, new RequestData() );
72
73 $handler = TestingAccessWrapper::newFromObject( $handler );
74 $this->assertInstanceOf( Router::class, $handler->getRouter() );
75 }
76
77 public static function provideGetRouteUrl() {
78 yield 'empty' => [
79 '/test',
80 [],
81 [],
82 '/test'
83 ];
84 yield 'path params' => [
85 '/test/{foo}/{bar}',
86 [ 'foo' => 'Kittens', 'bar' => 'mew' ],
87 [],
88 '/test/Kittens/mew'
89 ];
90 yield 'missing path params' => [
91 '/test/{foo}/{bar}',
92 [ 'bar' => 'mew' ],
93 [],
94 '/test/{foo}/mew'
95 ];
96 yield 'path param encoding' => [
97 '/test/{foo}',
98 [ 'foo' => 'ä/+/&/?/{}/#/%' ],
99 [],
100 '/test/%C3%A4%2F%2B%2F%26%2F%3F%2F%7B%7D%2F%23%2F%25'
101 ];
102 yield 'recursive path params' => [
103 '/test/{foo}/{bar}',
104 [ 'foo' => '{bar}', 'bar' => 'mew' ],
105 [],
106 '/test/%7Bbar%7D/mew'
107 ];
108 yield 'query params' => [
109 '/test',
110 [],
111 [ 'foo' => 'Kittens', 'bar' => 'mew' ],
112 '/test?foo=Kittens&bar=mew'
113 ];
114 yield 'query param encoding' => [
115 '/test',
116 [],
117 [ 'foo' => 'ä/+/&/?/{}/#/%' ],
118 '/test?foo=%C3%A4%2F%2B%2F%26%2F%3F%2F%7B%7D%2F%23%2F%25'
119 ];
120 }
121
122 /**
123 * @dataProvider provideGetRouteUrl
124 *
125 * @param string $path
126 * @param string[] $pathParams
127 * @param string[] $queryParams
128 * @param string $expected
129 */
130 public function testGetRouteUrl( $path, $pathParams, $queryParams, $expected ) {
131 $handler = $this->newHandler();
132 $request = new RequestData();
133 $this->initHandler( $handler, $request, [ 'path' => $path ] );
134 $handler = TestingAccessWrapper::newFromObject( $handler );
135 $url = $handler->getRouteUrl( $pathParams, $queryParams );
136 $this->assertStringEndsWith( $expected, $url );
137 }
138
139 public function testGetPath() {
140 $handler = $this->newHandler();
141 $request = new RequestData();
142 $this->initHandler( $handler, $request, [ 'path' => 'just/some/path' ] );
143 $this->assertSame( 'just/some/path', $handler->getPath() );
144 }
145
146 public function testSupportedPathparams() {
147 $handler = $this->newHandler();
148 $request = new RequestData();
149 $this->initHandler( $handler, $request, [ 'path' => 'some/path/{foo}/{bar}' ] );
150 $this->assertSame( [ 'foo', 'bar' ], $handler->getSupportedPathParams() );
151 }
152
153 public function testGetResponseFactory() {
154 $handler = $this->newHandler();
155 $this->initHandler( $handler, new RequestData() );
156
157 $this->assertInstanceOf( ResponseFactory::class, $handler->getResponseFactory() );
158 }
159
160 public function testGetConditionalHeaderUtil() {
161 $handler = $this->newHandler();
162 $this->initHandler( $handler, new RequestData() );
163
164 $handler = TestingAccessWrapper::newFromObject( $handler );
165 $this->assertInstanceOf( ConditionalHeaderUtil::class, $handler->getConditionalHeaderUtil() );
166 }
167
168 public static function provideCheckPreconditions() {
169 yield 'no status' => [ null ];
170 yield 'a status' => [ 444 ];
171 }
172
173 /**
174 * @dataProvider provideCheckPreconditions
175 */
176 public function testCheckPreconditions( $status ) {
177 $request = new RequestData();
178
179 $util = $this->createNoOpMock( ConditionalHeaderUtil::class, [ 'checkPreconditions' ] );
180 $util->method( 'checkPreconditions' )->with( $request )->willReturn( $status );
181
182 $handler = $this->newHandler( [ 'getConditionalHeaderUtil' ] );
183 $handler->method( 'getConditionalHeaderUtil' )->willReturn( $util );
184
185 $this->initHandler( $handler, $request );
186 $resp = $handler->checkPreconditions();
187
188 $responseStatus = $resp ? $resp->getStatusCode() : null;
189 $this->assertSame( $status, $responseStatus );
190 }
191
192 public function testApplyConditionalResponseHeaders() {
193 $util = $this->createNoOpMock( ConditionalHeaderUtil::class, [ 'applyResponseHeaders' ] );
194 $util->method( 'applyResponseHeaders' )->willReturnCallback(
195 static function ( ResponseInterface $response ) {
196 $response->setHeader( 'Testing', 'foo' );
197 }
198 );
199
200 $handler = $this->newHandler( [ 'getConditionalHeaderUtil' ] );
201 $handler->method( 'getConditionalHeaderUtil' )->willReturn( $util );
202
203 $this->initHandler( $handler, new RequestData() );
204 $response = $handler->getResponseFactory()->create();
205 $handler->applyConditionalResponseHeaders( $response );
206
207 $this->assertSame( 'foo', $response->getHeaderLine( 'Testing' ) );
208 }
209
210 public static function provideValidate() {
211 yield 'empty' => [ [], [], new RequestData(), [], [] ];
212
213 yield 'query parameter' => [
214 [
215 'foo' => [
216 ParamValidator::PARAM_TYPE => 'string',
217 ParamValidator::PARAM_REQUIRED => true,
218 Handler::PARAM_SOURCE => 'query',
219 ]
220 ],
221 [],
222 new RequestData( [ 'queryParams' => [ 'foo' => 'kittens' ] ] ),
223 [ 'foo' => 'kittens' ],
224 []
225 ];
226
227 yield 'body parameter' => [
228 [],
229 [
230 'foo' => [
231 ParamValidator::PARAM_TYPE => 'string',
232 ParamValidator::PARAM_REQUIRED => true,
233 Handler::PARAM_SOURCE => 'body',
234 ]
235 ],
236 new RequestData( [ 'parsedBody' => [ 'foo' => 'kittens' ] ] ),
237 [],
238 [ 'foo' => 'kittens' ]
239 ];
240 }
241
242 /**
243 * @dataProvider provideValidate
244 */
245 public function testValidate( $paramSettings, $bodyParamSettings, $request, $expectedParams, $expectedBody ) {
246 $handler = $this->newHandler( [ 'getParamSettings', 'getBodyParamSettings' ] );
247 $handler->method( 'getParamSettings' )->willReturn( $paramSettings );
248 $handler->method( 'getBodyParamSettings' )->willReturn( $bodyParamSettings );
249
250 $this->initHandler( $handler, $request );
251 $this->validateHandler( $handler );
252
253 $this->assertSame( $expectedParams, $handler->getValidatedParams() );
254 $this->assertSame( $expectedBody, $handler->getValidatedBody() );
255 }
256
257 public function testValidate_post() {
258 $this->expectDeprecationAndContinue( '/The "post" source is deprecated/' );
259
260 $paramSettings = [
261 'foo' => [
262 ParamValidator::PARAM_TYPE => 'string',
263 ParamValidator::PARAM_REQUIRED => true,
264 Handler::PARAM_SOURCE => 'post',
265 ]
266 ];
267
268 $request = new RequestData( [ 'postParams' => [ 'foo' => 'kittens' ] ] );
269
270 $handler = $this->newHandler( [ 'getParamSettings' ] );
271 $handler->method( 'getParamSettings' )->willReturn( $paramSettings );
272
273 $this->initHandler( $handler, $request );
274 $this->validateHandler( $handler );
275
276 $params = $handler->getValidatedParams();
277 $this->assertSame( [ 'foo' => 'kittens' ], $params );
278 }
279
280 public static function provideValidate_invalid() {
281 yield 'missing required' => [
282 [
283 'foo' => [
284 ParamValidator::PARAM_TYPE => 'string',
285 ParamValidator::PARAM_REQUIRED => true,
286 Handler::PARAM_SOURCE => 'query',
287 ]
288 ],
289 [ 'queryParams' => [ 'bar' => 'kittens' ] ],
290 [
291 'error' => 'parameter-validation-failed',
292 'failureCode' => 'missingparam'
293 ]
294 ];
295 }
296
297 /**
298 * @dataProvider provideValidate_invalid
299 */
300 public function testValidate_invalid( $paramSettings, $requestData, $expectedError ) {
301 $request = new RequestData( $requestData );
302
303 $handler = $this->newHandler( [ 'getParamSettings' ] );
304 $handler->method( 'getParamSettings' )->willReturn( $paramSettings );
305
306 try {
307 $this->initHandler( $handler, $request );
308 $this->validateHandler( $handler );
309 $this->fail( 'Expected LocalizedHttpException' );
310 } catch ( LocalizedHttpException $ex ) {
311 $data = $ex->getErrorData();
312
313 foreach ( $expectedError as $field => $value ) {
314 $this->assertSame( $value, $data[$field] ?? null );
315 }
316 }
317 }
318
319 public static function provideValidateBodyParams() {
320 yield 'no body parameter' => [
321 [
322 'pathfoo' => [
323 ParamValidator::PARAM_TYPE => 'string',
324 ParamValidator::PARAM_REQUIRED => false,
325 Handler::PARAM_SOURCE => 'path',
326 ],
327 ],
328 new RequestData( [ 'parsedBody' => [ 'foo' => 'kittens' ] ] ),
329 [] // extra parameter should be ignored if no body param is defined
330 ];
331
332 yield 'parameter' => [
333 [
334 'foo' => [
335 ParamValidator::PARAM_TYPE => 'string',
336 ParamValidator::PARAM_REQUIRED => true,
337 Handler::PARAM_SOURCE => 'body',
338 ]
339 ],
340 new RequestData( [ 'parsedBody' => [ 'foo' => 'kittens' ] ] ),
341 [ 'foo' => 'kittens' ]
342 ];
343
344 yield 'body parameter with type coercion' => [
345 [
346 'foo' => [
347 ParamValidator::PARAM_TYPE => 'integer',
348 ParamValidator::PARAM_REQUIRED => true,
349 Handler::PARAM_SOURCE => 'body',
350 ]
351 ],
352 new RequestData( [
353 'headers' => [
354 // Form data automatically enabled type coercion
355 'Content-Type' => RequestInterface::FORM_URLENCODED_CONTENT_TYPE
356 ],
357 'parsedBody' => [ 'foo' => '1234' ]
358 ] ),
359 [ 'foo' => 1234 ]
360 ];
361
362 yield 'multivalue string in form data' => [
363 [
364 'foo' => [
365 ParamValidator::PARAM_TYPE => 'string',
366 ParamValidator::PARAM_REQUIRED => true,
367 ParamValidator::PARAM_ISMULTI => true,
368 Handler::PARAM_SOURCE => 'body',
369 ]
370 ],
371 new RequestData( [
372 'headers' => [
373 'Content-Type' => RequestInterface::FORM_URLENCODED_CONTENT_TYPE
374 ],
375 'parsedBody' => [ 'foo' => 'x|y|z' ]
376 ] ),
377 [ 'foo' => [ 'x', 'y', 'z' ] ]
378 ];
379
380 yield 'multivalue string in JSON' => [
381 [
382 'foo' => [
383 ParamValidator::PARAM_TYPE => 'string',
384 ParamValidator::PARAM_REQUIRED => true,
385 ParamValidator::PARAM_ISMULTI => true,
386 Handler::PARAM_SOURCE => 'body',
387 ]
388 ],
389 new RequestData( [
390 'headers' => [
391 'Content-Type' => RequestInterface::JSON_CONTENT_TYPE
392 ],
393 'parsedBody' => [ 'foo' => [ 'x', 'y', 'z' ] ]
394 ] ),
395 [ 'foo' => [ 'x', 'y', 'z' ] ]
396 ];
397 }
398
399 /**
400 * @dataProvider provideValidateBodyParams
401 */
402 public function testValidateBodyParams( $paramSettings, $request, $expected ) {
403 $handler = $this->newHandler( [ 'getBodyParamSettings' ] );
404 $handler->method( 'getBodyParamSettings' )->willReturn( $paramSettings );
405
406 $this->initHandler( $handler, $request );
407 $this->validateHandler( $handler );
408
409 $params = $handler->getValidatedBody();
410 $this->assertSame( $expected, $params );
411 }
412
413 public function testGetBodyParamSettings() {
414 $bodyParamSettings = [
415 'bodyfoo' => [
416 ParamValidator::PARAM_TYPE => 'string',
417 Handler::PARAM_SOURCE => 'body',
418 ]
419 ];
420 $handler = $this->newHandler( [ 'getBodyParamSettings' ] );
421 $handler->method( 'getBodyParamSettings' )->willReturn( $bodyParamSettings );
422
423 $bodyParams = $handler->getBodyParamSettings();
424
425 $expected = [
426 'bodyfoo' => $bodyParamSettings['bodyfoo']
427 ];
428
429 $this->assertSame( $expected, $bodyParamSettings );
430 }
431
432 public function testOverrideGetBodyParamSettings() {
433 $paramSettings =
434
435 $handler = new class() extends Handler {
436
437 public function execute() {
438 return [];
439 }
440
441 public function getBodyParamSettings(): array {
442 return [
443 'x' => [
444 ParamValidator::PARAM_TYPE => 'string',
445 Handler::PARAM_SOURCE => 'body',
446 ],
447 'y' => [
448 ParamValidator::PARAM_TYPE => 'string',
449 Handler::PARAM_SOURCE => 'body',
450 ],
451 ];
452 }
453
454 public function getParamSettings(): array {
455 return [
456 'pathfoo' => [
457 ParamValidator::PARAM_TYPE => 'string',
458 ParamValidator::PARAM_DEFAULT => 'foo',
459 Handler::PARAM_SOURCE => 'path',
460 ],
461 'bodyfoo' => [ // should not be used for validation
462 ParamValidator::PARAM_TYPE => 'string',
463 ParamValidator::PARAM_DEFAULT => 'foo',
464 Handler::PARAM_SOURCE => 'body',
465 ],
466 'queryfoo' => [
467 ParamValidator::PARAM_TYPE => 'string',
468 ParamValidator::PARAM_DEFAULT => 'foo',
469 Handler::PARAM_SOURCE => 'query',
470 ],
471 ];
472 }
473 };
474
475 $request = new RequestData( [
476 'parsedBody' => [
477 'x' => 'test 1',
478 'y' => 'test 2',
479 ],
480 ] );
481
482 $this->initHandler( $handler, $request );
483 $this->validateHandler( $handler );
484
485 // The validated body should contain x and y, but not bodyfoo
486 $expectedBody = [
487 'x' => 'test 1',
488 'y' => 'test 2',
489 ];
490 $body = $handler->getValidatedBody();
491 $this->assertSame( $expectedBody, $body );
492
493 // The validated params should contain pathfoo and queryfoo, but not bodyfoo
494 $expectedParams = [
495 'pathfoo' => 'foo',
496 'queryfoo' => 'foo',
497 ];
498 $params = $handler->getValidatedParams();
499 $this->assertSame( $expectedParams, $params );
500 }
501
502 public function provideValidateBodyParams_invalid() {
503 $paramDefintions = [
504 'foo' => [
505 ParamValidator::PARAM_TYPE => 'timestamp',
506 ParamValidator::PARAM_REQUIRED => true,
507 Handler::PARAM_SOURCE => 'body',
508 ]
509 ];
510
511 yield 'missing param' => [
512 $paramDefintions,
513 new RequestData( [ 'parsedBody' => [], ] ),
514 'missingparam'
515 ];
516
517 yield 'extra param' => [
518 $paramDefintions,
519 new RequestData(
520 [
521 'parsedBody' => [
522 'foo' => 23,
523 'xyzzy' => 'lizzards',
524 ],
525 ]
526 ),
527 'extraneous-body-fields'
528 ];
529
530 yield 'bad param' => [
531 $paramDefintions,
532 new RequestData(
533 [
534 'parsedBody' => [
535 'foo' => 'kittens',
536 ],
537 ]
538 ),
539 'badtimestamp'
540 ];
541
542 yield 'body parameter without type coercion' => [
543 [
544 'foo' => [
545 ParamValidator::PARAM_TYPE => 'integer',
546 ParamValidator::PARAM_REQUIRED => true,
547 Handler::PARAM_SOURCE => 'body',
548 ]
549 ],
550 new RequestData( [
551 // JSON doesn't enable type coercion
552 'headers' => [ 'Content-Type' => 'application/json', ],
553 'parsedBody' => [ 'foo' => '1234' ]
554 ] ),
555 'badinteger-type'
556 ];
557
558 yield 'multivalue body parameter as string in JSON' => [
559 [
560 'foo' => [
561 ParamValidator::PARAM_TYPE => 'string',
562 ParamValidator::PARAM_REQUIRED => true,
563 ParamValidator::PARAM_ISMULTI => true,
564 Handler::PARAM_SOURCE => 'body',
565 ]
566 ],
567 new RequestData( [
568 'headers' => [ 'Content-Type' => 'application/json', ],
569 'parsedBody' => [ 'foo' => 'x|y|z' ]
570 ] ),
571 'multivalue-must-be-array'
572 ];
573
574 yield 'multivalue integer as array of strings in JSON' => [
575 [
576 'foo' => [
577 ParamValidator::PARAM_TYPE => 'integer',
578 ParamValidator::PARAM_REQUIRED => true,
579 ParamValidator::PARAM_ISMULTI => true,
580 Handler::PARAM_SOURCE => 'body',
581 ]
582 ],
583 new RequestData( [
584 'headers' => [ 'Content-Type' => 'application/json' ],
585 'parsedBody' => [ 'foo' => [ '1', '2', '3' ] ]
586 ] ),
587 'badinteger-type'
588 ];
589 }
590
591 /**
592 * @dataProvider provideValidateBodyParams_invalid
593 */
594 public function testValidateBodyParams_invalid( $paramSettings, $request, $expectedError ) {
595 $handler = $this->newHandler( [ 'getBodyParamSettings' ] );
596 $handler->method( 'getBodyParamSettings' )->willReturn( $paramSettings );
597
598 try {
599 $this->initHandler( $handler, $request );
600 $this->validateHandler( $handler );
601 $this->fail( 'Expected LocalizedHttpException' );
602 } catch ( LocalizedHttpException $ex ) {
603 $data = $ex->getErrorData();
604 $this->assertSame( 'parameter-validation-failed', $data['error'] ?? null );
605 $this->assertSame( $expectedError, $data['failureCode'] ?? null );
606 }
607 }
608
609 public function testBodyValidator() {
610 $request = new RequestData( [
611 'method' => 'POST',
612 'headers' => [
613 'Content-Type' => 'test/test'
614 ],
615 'bodyContents' => 'test test test'
616 ] );
617
618 $bodyValidator = new class () implements BodyValidator {
619
620 public function validateBody( RequestInterface $request ) {
621 return 'VALIDATED BODY';
622 }
623 };
624
625 $this->expectDeprecationAndContinue( '/overrides getBodyValidator/' );
626 $this->expectDeprecationAndContinue( '/Validator::validateBody/' );
627 $handler = $this->newHandler( [ 'getBodyValidator' ] );
628 $handler->method( 'getBodyValidator' )->willReturn( $bodyValidator );
629
630 $this->initHandler( $handler, $request );
631 $this->validateHandler( $handler );
632
633 $body = $handler->getValidatedBody();
634 $this->assertSame( 'VALIDATED BODY', $body );
635 }
636
637 public function testGetRequest() {
638 $handler = $this->newHandler();
639 $request = new RequestData();
640 $this->initHandler( $handler, $request );
641
642 $this->assertSame( $request, $handler->getRequest() );
643 }
644
645 public function testGetConfig() {
646 $handler = $this->newHandler();
647 $config = [ 'foo' => 'bar' ];
648 $this->initHandler( $handler, new RequestData(), $config );
649
650 $this->assertSame( $config, $handler->getConfig() );
651 }
652
653 public function testGetBodyValidator() {
654 $handler = $this->newHandler();
655 $this->assertInstanceOf(
656 BodyValidator::class,
657 $handler->getBodyValidator( 'unknown/unknown' )
658 );
659 }
660
661 public function testThatGetParamSettingsReturnsNothingPerDefault() {
662 $handler = $this->newHandler();
663 $this->assertSame( [], $handler->getParamSettings() );
664 }
665
666 public function testThatGetLastModifiedReturnsNullPerDefault() {
667 $handler = $this->newHandler();
668
669 $handler = TestingAccessWrapper::newFromObject( $handler );
670 $this->assertNull( $handler->getLastModified() );
671 }
672
673 public function testThatGetETagReturnsNullPerDefault() {
674 $handler = $this->newHandler();
675
676 $handler = TestingAccessWrapper::newFromObject( $handler );
677 $this->assertNull( $handler->getETag() );
678 }
679
680 public function testThatHasRepresentationReturnsNullPerDefault() {
681 $handler = $this->newHandler();
682
683 $handler = TestingAccessWrapper::newFromObject( $handler );
684 $this->assertNull( $handler->hasRepresentation() );
685 }
686
687 public function testThatNeedsReadAccessReturnsTruePerDefault() {
688 $handler = $this->newHandler();
689
690 $handler = TestingAccessWrapper::newFromObject( $handler );
691 $this->assertTrue( $handler->needsReadAccess() );
692 }
693
694 public function testThatNeedsWriteAccessReturnsTruePerDefault() {
695 $handler = $this->newHandler();
696
697 $handler = TestingAccessWrapper::newFromObject( $handler );
698 $this->assertTrue( $handler->needsWriteAccess() );
699 }
700
701 public static function provideBodyValidationFailure() {
702 yield 'extraneous token (bodyContents)' => [
703 [
704 'method' => 'POST',
705 'pathParams' => [ 'title' => 'Foo' ],
706 'headers' => [
707 'Content-Type' => 'application/json',
708 ],
709 'bodyContents' => json_encode( [
710 'title' => 'Foo',
711 'token' => 'TOKEN',
712 'comment' => 'Testing',
713 'source' => 'Lorem Ipsum',
714 'content_model' => 'wikitext'
715 ] ),
716 ],
717 new MessageValue( 'rest-extraneous-csrf-token' )
718 ];
719 yield 'extraneous token (parsedBody)' => [
720 [
721 'method' => 'POST',
722 'pathParams' => [ 'title' => 'Foo' ],
723 'headers' => [
724 'Content-Type' => 'application/json',
725 ],
726 'parsedBody' => [
727 'title' => 'Foo',
728 'token' => 'TOKEN',
729 'comment' => 'Testing',
730 'source' => 'Lorem Ipsum',
731 'content_model' => 'wikitext'
732 ],
733 ],
734 new MessageValue( 'rest-extraneous-csrf-token' )
735 ];
736 }
737
738 /**
739 * @dataProvider provideBodyValidationFailure
740 */
741 public function testBodyValidationFailure( $requestData, $expectedMessage ) {
742 $request = new RequestData( $requestData );
743
744 $handler = $this->newHandler();
745 $this->initHandler( $handler, $request, [], [], null, $this->getSession( true ) );
746
747 // NOTE: initHandler() should be setting the parsed body if needed!
748 $validator = $this->getMockValidator( [], $request->getParsedBody() );
749 $handler->validate( $validator );
750
751 // sanity check
752 $this->assertTrue( $handler->getSession()->getProvider()->safeAgainstCsrf() );
753
754 try {
755 $handler->checkSession();
756 Assert::fail( 'Expected a LocalizedHttpException to be thrown' );
757 } catch ( HttpException $ex ) {
758 $this->assertSame( 400, $ex->getCode(), 'HTTP status' );
759 $this->assertInstanceOf( LocalizedHttpException::class, $ex );
760
761 $this->assertEquals( $expectedMessage, $ex->getMessageValue() );
762 }
763 }
764
765 public function testCsrfUnsafeSessionProviderRejection() {
766 $handler = $this->newHandler( [ 'requireSafeAgainstCsrf' ] );
767 $handler->method( 'requireSafeAgainstCsrf' )->willReturn( true );
768 $this->initHandler( $handler, new RequestData(), [], [], null, $this->getSession( false ) );
769
770 try {
771 $handler->checkSession();
772 Assert::fail( 'Expected a LocalizedHttpException to be thrown' );
773 } catch ( HttpException $ex ) {
774 }
775
776 $this->assertSame( 400, $ex->getCode(), 'HTTP status' );
777 $this->assertInstanceOf( LocalizedHttpException::class, $ex );
778
779 $expectedMessage = new MessageValue( 'rest-requires-safe-against-csrf' );
780 $this->assertEquals( $expectedMessage, $ex->getMessageValue() );
781
782 $this->assertFalse( $handler->getSession()->getProvider()->safeAgainstCsrf() );
783 }
784
785 public function testThatVerifierHeadersAreLoopedThroughForGet() {
786 $handler = $this->newHandler( [ 'getETag', 'getLastModified' ] );
787 $handler->method( 'getETag' )->willReturn( '"TEST"' );
788 $handler->method( 'getLastModified' )->willReturn( '20220101223344' );
789
790 $params = [ 'method' => 'GET' ];
791 $this->initHandler( $handler, new RequestData( $params ) );
792 $handler->checkPreconditions();
793
794 $response = new Response();
795 $handler->applyConditionalResponseHeaders( $response );
796 $this->assertSame( '"TEST"', $response->getHeaderLine( 'ETag' ) );
797
798 $lastModified = ConvertibleTimestamp::convert( TS_MW, $response->getHeaderLine( 'Last-Modified' ) );
799 $this->assertSame( '20220101223344', $lastModified );
800 }
801
802 public function testThatVerifierHeadersAreNotLoopedThroughForPost() {
803 $handler = $this->newHandler( [ 'getETag', 'getLastModified' ] );
804 $handler->method( 'getETag' )->willReturn( '"TEST"' );
805 $handler->method( 'getLastModified' )->willReturn( '20220101223344' );
806
807 $params = [ 'method' => 'POST' ];
808 $this->initHandler( $handler, new RequestData( $params ) );
809 $handler->checkPreconditions();
810
811 $response = new Response();
812 $handler->applyConditionalResponseHeaders( $response );
813 $this->assertSame( '', $response->getHeaderLine( 'ETag' ) );
814 $this->assertSame( '', $response->getHeaderLine( 'Last-Modified' ) );
815 }
816
817 public static function provideCacheControl() {
818 yield 'nothing' => [
819 'GET',
820 [],
821 false, // no persistent session
822 ''
823 ];
824
825 yield 'set-cookie in response' => [
826 'GET',
827 [
828 'Set-Cookie' => 'foo=bar',
829 'Cache-Control' => 'max-age=123'
830 ],
831 false, // no persistent session
832 'private,must-revalidate,s-maxage=0'
833 ];
834
835 yield 'POST with cache control' => [
836 'POST',
837 [
838 'Cache-Control' => 'max-age=123'
839 ],
840 false, // no persistent session
841 'max-age=123'
842 ];
843
844 yield 'POST use default cache control' => [
845 'POST',
846 [],
847 false, // no persistent session
848 'private,no-cache,s-maxage=0'
849 ];
850
851 yield 'persistent session' => [
852 'GET',
853 [ 'Cache-Control' => 'max-age=123' ],
854 true, // persistent session
855 'private,must-revalidate,s-maxage=0'
856 ];
857 }
858
859 /**
860 * @dataProvider provideCacheControl
861 */
862 public function testCacheControl(
863 string $method,
864 array $headers,
865 bool $hasPersistentSession,
866 $expected
867 ) {
868 $response = new Response();
869
870 foreach ( $headers as $name => $value ) {
871 $response->setHeader( $name, $value );
872 }
873
874 $session = $this->createMock( Session::class );
875 $session->method( 'isPersistent' )->willReturn( $hasPersistentSession );
876
877 $handler = $this->newHandler( [ 'getRequest', 'getSession' ] );
878 $handler->method( 'getRequest' )->willReturn( new RequestData( [ 'method' => $method ] ) );
879 $handler->method( 'getSession' )->willReturn( $session );
880
881 $handler->applyCacheControl( $response );
882
883 $this->assertSame( $expected, $response->getHeaderLine( 'Cache-Control' ) );
884 }
885
886 public static function provideParseBodyData() {
887 return [
888 'no body type with non-empty body' => [
889 new RequestData( [
890 'method' => 'POST',
891 'bodyContents' => '{"foo":"bar"}',
892 ] ),
893 new LocalizedHttpException(
894 new MessageValue( 'rest-unsupported-content-type', [ '' ] ),
895 415
896 )
897 ],
898 'no body type with empty body' => [
899 new RequestData( [
900 'headers' => [ 'content-length' => '0' ],
901 'bodyContent' => '',
902 ] ),
903 null
904 ],
905 'json body' => [
906 new RequestData( [
907 'bodyContents' => '{"foo":"bar"}',
908 'headers' => [ 'Content-Type' => 'application/json' ]
909 ] ),
910 [ 'foo' => 'bar' ]
911 ],
912 'json patch body' => [
913 new RequestData( [
914 'bodyContents' => '{"patch":[]}',
915 'headers' => [ 'Content-Type' => 'application/json-patch+json' ]
916 ] ),
917 [ 'patch' => [] ]
918 ],
919 'form data' => [
920 new RequestData( [
921 'postParams' => [ 'foo' => 'bar' ],
922 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ]
923 ] ),
924 [ 'foo' => 'bar' ]
925 ],
926 'multipart form data' => [
927 new RequestData( [
928 'postParams' => [ 'foo' => 'bar' ],
929 'headers' => [ 'Content-Type' => 'multipart/form-data' ]
930 ] ),
931 [ 'foo' => 'bar' ]
932 ],
933 'unknown body type' => [
934 new RequestData( [
935 'headers' => [ 'Content-Type' => 'unknown/type' ]
936 ] ),
937 new LocalizedHttpException(
938 new MessageValue( 'rest-unsupported-content-type', [ '' ] ),
939 415
940 )
941 ],
942 'malformed json body' => [
943 new RequestData( [
944 'bodyContents' => '{"foo":"bar"',
945 'headers' => [ 'Content-Type' => 'application/json' ]
946 ] ),
947 new LocalizedHttpException(
948 new MessageValue( 'rest-json-body-parse-error', [ '' ] ),
949 400
950 )
951 ],
952 'empty json body' => [
953 new RequestData( [
954 'bodyContents' => '',
955 'headers' => [ 'Content-Type' => 'application/json' ]
956 ] ),
957 new LocalizedHttpException(
958 new MessageValue( 'rest-json-body-parse-error', [ '' ] ),
959 400
960 )
961 ],
962 'non-array json body' => [
963 new RequestData( [
964 'bodyContents' => '"foo"',
965 'headers' => [ 'Content-Type' => 'application/json' ]
966 ] ),
967 new LocalizedHttpException(
968 new MessageValue( 'rest-json-body-parse-error', [ '' ] ),
969 400
970 )
971 ],
972 'json body with normalization' => [
973 new RequestData( [
974 'bodyContents' => json_encode( [ 'param' => "L\u{0061}\u{0308}rm" ], JSON_UNESCAPED_UNICODE ),
975 'headers' => [ 'Content-Type' => 'application/json' ]
976 ] ),
977 [ 'param' => "L\u{00E4}rm" ]
978 ],
979 'form data with normalization' => [
980 new RequestData( [
981 'postParams' => [ 'param' => "L\u{0061}\u{0308}rm" ],
982 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ]
983 ] ),
984 [ 'param' => "L\u{00E4}rm" ]
985 ],
986 'multipart form data with normalization' => [
987 new RequestData( [
988 'postParams' => [ 'param' => "L\u{0061}\u{0308}rm" ],
989 'headers' => [ 'Content-Type' => 'multipart/form-data' ]
990 ] ),
991 [ 'param' => "L\u{00E4}rm" ]
992 ]
993 ];
994 }
995
996 /** @dataProvider provideParseBodyData */
997 public function testParseBodyData( $requestData, $expectedResult ) {
998 $handler = $this->newHandler( [ 'getSupportedRequestTypes' ] );
999 $handler->method( 'getSupportedRequestTypes' )->willReturn( [
1000 'application/json',
1001 'application/json-patch+json',
1002 'application/x-www-form-urlencoded',
1003 'multipart/form-data'
1004 ] );
1005
1006 if ( $expectedResult instanceof LocalizedHttpException ) {
1007 $this->expectException( LocalizedHttpException::class );
1008 $this->expectExceptionCode( $expectedResult->getCode() );
1009 $this->expectExceptionMessage( $expectedResult->getMessage() );
1010 $handler->parseBodyData( $requestData );
1011 } else {
1012 $parsedBody = $handler->parseBodyData( $requestData );
1013 $this->assertEquals( $expectedResult, $parsedBody );
1014 }
1015 }
1016
1017 public function testPostRequestFailsWithFormData() {
1018 $handler = $this->newHandler();
1019 $requestData = new RequestData( [
1020 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ],
1021 'postParams' => [ 'test' => 'foo' ]
1022 ] );
1023
1024 $expectedResult = new LocalizedHttpException(
1025 new MessageValue( 'rest-unsupported-content-type', [ '' ] ),
1026 415
1027 );
1028
1029 $this->expectException( LocalizedHttpException::class );
1030 $this->expectExceptionCode( $expectedResult->getCode() );
1031 $this->expectExceptionMessage( $expectedResult->getMessage() );
1032 $handler->parseBodyData( $requestData );
1033 }
1034
1035 public function testGetRequestFailsWithBody() {
1036 $this->markTestSkipped( 'T359509' );
1037 $request = new RequestData( [
1038 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1039 'method' => 'GET',
1040 'bodyContents' => '{"foo":"bar"}',
1041 'headers' => [ "content-type" => 'application/json' ]
1042 ] );
1043 $handler = new EchoHandler();
1044 $this->initHandlerPartially( $handler );
1045
1046 $this->expectExceptionCode( 400 );
1047 $handler->initForExecute( $request );
1048 }
1049
1050 public function testGetRequestIgnoresEmptyBody() {
1051 $request = new RequestData( [
1052 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1053 'method' => 'GET',
1054 'bodyContents' => '',
1055 'headers' => [
1056 "content-length" => 0,
1057 "content-type" => 'text/plain'
1058 ]
1059 ] );
1060 $handler = new EchoHandler();
1061 $this->initHandlerPartially( $handler );
1062 $handler->initForExecute( $request );
1063 $this->addToAssertionCount( 1 );
1064 }
1065
1066 public function testPostRequestFailsWithoutBody() {
1067 $request = new RequestData( [
1068 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1069 'method' => 'POST',
1070 ] );
1071 $handler = new EchoHandler();
1072 $this->initHandlerPartially( $handler );
1073
1074 $this->expectExceptionCode( 411 );
1075 $handler->initForExecute( $request );
1076 }
1077
1078 public function testEmptyBodyWithoutContentTypePasses() {
1079 $request = new RequestData( [
1080 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1081 'method' => 'POST',
1082 'headers' => [ 'content-length' => '0' ],
1083 'bodyContent' => '',
1084 // Should pass even without content-type!
1085 ] );
1086
1087 $handler = new EchoHandler();
1088 $this->initHandlerPartially( $handler );
1089 $handler->initForExecute( $request );
1090 $this->addToAssertionCount( 1 );
1091 }
1092
1093 public function testRequestBodyWithoutContentTypeFails() {
1094 $request = new RequestData( [
1095 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1096 'method' => 'POST',
1097 'bodyContents' => '{"foo":"bar"}', // Request body without content-type
1098 ] );
1099 $handler = new EchoHandler();
1100 $this->initHandlerPartially( $handler );
1101
1102 $this->expectExceptionCode( 415 );
1103 $handler->initForExecute( $request );
1104 }
1105
1106 public function testDeleteRequestWithoutBody() {
1107 // Test DELETE request without body
1108 $request = new RequestData( [
1109 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1110 'method' => 'DELETE',
1111 ] );
1112 $handler = new EchoHandler();
1113 $this->initHandlerPartially( $handler );
1114 $handler->initForExecute( $request );
1115 $this->addToAssertionCount( 1 );
1116 }
1117
1118 public function testDeleteRequestWithBody() {
1119 // Test DELETE request with body
1120 $request = new RequestData( [
1121 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1122 'method' => 'DELETE',
1123 'bodyContents' => '{"bodyParam":"bar"}',
1124 'headers' => [ "content-type" => 'application/json' ]
1125 ] );
1126 $handler = new EchoHandler();
1127 $this->initHandlerPartially( $handler );
1128 $handler->initForExecute( $request );
1129 $this->addToAssertionCount( 1 );
1130 }
1131
1132 public function testUnsupportedContentTypeReturns415() {
1133 $request = new RequestData( [
1134 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1135 'method' => 'POST',
1136 'bodyContents' => '{"foo":"bar"}',
1137 'headers' => [ "content-type" => 'text/plain' ] // Unsupported content type
1138 ] );
1139 $handler = new EchoHandler();
1140 $this->initHandlerPartially( $handler );
1141
1142 $this->expectExceptionCode( 415 );
1143 $handler->initForExecute( $request );
1144 }
1145
1146 public function testHandlerCanAccessParsedBodyForJsonRequest() {
1147 $request = new RequestData( [
1148 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1149 'method' => 'POST',
1150 'bodyContents' => '{"bodyParam":"bar"}',
1151 'headers' => [ "content-type" => 'application/json' ]
1152 ] );
1153 $handler = new EchoHandler();
1154 $this->initHandler( $handler, $request );
1155 $this->validateHandler( $handler );
1156 $data = $handler->execute();
1157
1158 // Check if the response contains a field called 'parsedBody'
1159 $this->assertArrayHasKey( 'parsedBody', $data );
1160
1161 // Check the value of the 'parsedBody' field
1162 $parsedBody = $data['parsedBody'];
1163 $this->assertEquals( [ 'bodyParam' => 'bar' ], $parsedBody );
1164 }
1165
1166 public function testHandlerCanAccessValidatedBodyForJsonRequest() {
1167 $request = new RequestData( [
1168 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
1169 'method' => 'POST',
1170 'bodyContents' => '{"bodyParam":"bar"}',
1171 'headers' => [ "content-type" => 'application/json' ]
1172 ] );
1173 $handler = new EchoHandler();
1174 $this->initHandler( $handler, $request );
1175 $this->validateHandler( $handler );
1176 $data = $handler->execute();
1177
1178 // Check if the response contains a field called 'validatedBody'
1179 $this->assertArrayHasKey( 'validatedBody', $data );
1180
1181 // Check the value of the 'validatedBody' field
1182 $validatedBody = $data['validatedBody'];
1183 $this->assertEquals( [ 'bodyParam' => 'bar' ], $validatedBody );
1184
1185 // Check the value of the 'validatedParams' field.
1186 // It should not contain bodyParam.
1187 $validatedParams = $data['validatedParams'];
1188 $this->assertArrayNotHasKey( 'bodyParam', $validatedParams );
1189 }
1190
1191 public function testHandlerCanAccessValidatedParams() {
1192 $request = new RequestData( [
1193 'uri' => new Uri( '/rest/mock/v1/RouterTest/echo/bar' ),
1194 'pathParams' => [ 'pathParam' => 'bar' ],
1195 'method' => 'POST',
1196 'headers' => [ "content-type" => 'application/json' ],
1197 'bodyContents' => '{}'
1198 ] );
1199 $handler = new EchoHandler();
1200 $this->initHandler( $handler, $request );
1201 $this->validateHandler( $handler );
1202 $data = $handler->execute();
1203
1204 // Check if the response contains a field called 'pathParams'
1205 $this->assertArrayHasKey( 'validatedParams', $data );
1206
1207 // Check the value of the 'pathParams' field
1208 $validatedParams = $data['validatedParams'];
1209 $this->assertEquals( 'bar', $validatedParams[ 'pathParam' ] );
1210 }
1211
1212 /**
1213 * Assert that getSupportedRequestTypes() will detect that "post" parameters
1214 * are declared, so form data is allowed.
1215 */
1216 public function testGetSupportedRequestTypes_post() {
1217 $this->expectDeprecationAndContinue( '/The "post" source is deprecated/' );
1218
1219 $paramSettings = [
1220 'test' => [
1221 Handler::PARAM_SOURCE => 'post',
1222 ]
1223 ];
1224 $handler = $this->newHandler( [ 'getParamSettings' ] );
1225 $handler->method( 'getParamSettings' )->willReturn( $paramSettings );
1226
1227 $supportedTypes = $handler->getSupportedRequestTypes();
1228
1229 $this->assertContains( 'application/x-www-form-urlencoded', $supportedTypes );
1230 $this->assertContains( 'multipart/form-data', $supportedTypes );
1231 $this->assertContains( 'application/json', $supportedTypes );
1232
1233 // Should accept form data
1234 $request = new RequestData( [
1235 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ],
1236 'postParams' => [ 'test' => 'foo' ]
1237 ] );
1238 $handler->parseBodyData( $request );
1239
1240 // The "post" parameter should be processed as "parameter" but not as "body".
1241 $this->initHandler( $handler, $request );
1242 $this->validateHandler( $handler );
1243
1244 $this->assertArrayHasKey( 'test', $handler->getValidatedParams() );
1245 $this->assertArrayNotHasKey( 'test', $handler->getValidatedBody() );
1246 }
1247
1248 /**
1249 * Assert that getSupportedRequestTypes() can be overwritten
1250 * to allow form data.
1251 */
1252 public function testGetSupportedRequestTypes_body() {
1253 $paramSettings = [
1254 'test' => [
1255 Handler::PARAM_SOURCE => 'body',
1256 ]
1257 ];
1258
1259 $supportedTypes = [
1260 'application/x-www-form-urlencoded'
1261 ];
1262
1263 $handler = $this->newHandler( [ 'getBodyParamSettings', 'getSupportedRequestTypes' ] );
1264 $handler->method( 'getBodyParamSettings' )->willReturn( $paramSettings );
1265 $handler->method( 'getSupportedRequestTypes' )->willReturn( $supportedTypes );
1266
1267 // Should accept form data
1268 $request = new RequestData( [
1269 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ],
1270 'postParams' => [ 'test' => 'foo' ]
1271 ] );
1272 $handler->parseBodyData( $request );
1273
1274 // The "body" parameter should be processed as "body", not as "parameter".
1275 $this->initHandler( $handler, $request );
1276 $this->validateHandler( $handler );
1277
1278 $this->assertArrayHasKey( 'test', $handler->getValidatedBody() );
1279 $this->assertArrayNotHasKey( 'test', $handler->getValidatedParams() );
1280 }
1281
1282 private static function assertWellFormedOAS( array $spec, array $required ) {
1283 foreach ( $required as $key ) {
1284 Assert::assertArrayHasKey( $key, $spec );
1285 }
1286 }
1287
1288 private static function makeMap( array $list, string $key ): array {
1289 $map = [];
1290 foreach ( $list as $obj ) {
1291 $val = $obj[$key];
1292 $map[$val] = $obj;
1293 }
1294 return $map;
1295 }
1296
1297 public static function provideGetOpenApiSpec() {
1298 yield 'defaults' => [
1299 '$paramSettings' => [],
1300 '$bodySettings' => [],
1301 '$requestTypes' => [ 'application/json' ],
1302 '$routeConfig' => [ 'path' => '/test' ],
1303 '$method' => 'GET',
1304 '$assertions' =>
1305 static function ( array $spec ) {
1306 self::assertWellFormedOAS( $spec, [ 'responses' ] );
1307 $resp = $spec['responses'];
1308
1309 Assert::assertArrayHasKey( 200, $resp );
1310 Assert::assertArrayHasKey( 400, $resp );
1311 Assert::assertArrayHasKey( 500, $resp );
1312 },
1313 ];
1314
1315 yield 'path parameters' => [
1316 '$paramSettings' => [
1317 'a' => [
1318 Handler::PARAM_SOURCE => 'path',
1319 ParamValidator::PARAM_TYPE => 'integer',
1320 ParamValidator::PARAM_REQUIRED => true,
1321 ],
1322 'b' => [
1323 Handler::PARAM_SOURCE => 'path',
1324 ParamValidator::PARAM_TYPE => [ 'x', 'y', 'z' ],
1325 ParamValidator::PARAM_REQUIRED => false,
1326 ],
1327 'c' => [
1328 Handler::PARAM_SOURCE => 'path',
1329 ParamValidator::PARAM_TYPE => 'string',
1330 ParamValidator::PARAM_REQUIRED => false,
1331 ],
1332 ],
1333 '$bodySettings' => [],
1334 '$requestTypes' => [ 'application/json' ],
1335 '$routeConfig' => [ 'path' => '/test/{a}/{b}' ],
1336 '$method' => 'GET',
1337 '$assertions' =>
1338 static function ( array $spec ) {
1339 self::assertWellFormedOAS( $spec, [ 'parameters' ] );
1340 $params = self::makeMap( $spec['parameters'], 'name' );
1341
1342 // The parameter "c" is optional and not in the declared path.
1343 Assert::assertArrayHasKey( 'a', $params, 'required path param' );
1344 Assert::assertArrayHasKey( 'b', $params, 'used optional path param' );
1345 Assert::assertArrayNotHasKey( 'c', $params, 'unused optional path param' );
1346
1347 Assert::assertSame( 'path', $params['a']['in'] );
1348 Assert::assertSame( 'path', $params['b']['in'] );
1349
1350 // All path params must be required in OAS, even if they
1351 // were declared as optional (T359652) in getParamSettings.
1352 Assert::assertTrue( $params['a']['required'] );
1353 Assert::assertTrue( $params['b']['required'] );
1354
1355 Assert::assertSame( 'integer', $params['a']['schema']['type'] );
1356 Assert::assertSame( 'string', $params['b']['schema']['type'] );
1357 Assert::assertSame( [ 'x', 'y', 'z' ], $params['b']['schema']['enum'] );
1358 },
1359 ];
1360
1361 yield 'query parameters' => [
1362 '$paramSettings' => [
1363 'a' => [
1364 Handler::PARAM_SOURCE => 'query',
1365 ParamValidator::PARAM_TYPE => 'integer',
1366 ParamValidator::PARAM_REQUIRED => true,
1367 ],
1368 'b' => [
1369 Handler::PARAM_SOURCE => 'query',
1370 ParamValidator::PARAM_TYPE => [ 'x', 'y', 'z' ],
1371 ParamValidator::PARAM_REQUIRED => false,
1372 ],
1373 ],
1374 '$bodySettings' => [],
1375 '$requestTypes' => [ 'application/json' ],
1376 '$routeConfig' => [ 'path' => '/test' ],
1377 '$method' => 'GET',
1378 '$assertions' =>
1379 static function ( array $spec ) {
1380 self::assertWellFormedOAS( $spec, [ 'parameters' ] );
1381 $params = self::makeMap( $spec['parameters'], 'name' );
1382
1383 Assert::assertArrayHasKey( 'a', $params );
1384 Assert::assertArrayHasKey( 'b', $params );
1385
1386 Assert::assertSame( 'query', $params['a']['in'] );
1387 Assert::assertSame( 'query', $params['b']['in'] );
1388
1389 Assert::assertTrue( $params['a']['required'] );
1390 Assert::assertFalse( $params['b']['required'] );
1391
1392 Assert::assertSame( 'integer', $params['a']['schema']['type'] );
1393 Assert::assertSame( 'string', $params['b']['schema']['type'] );
1394 Assert::assertSame( [ 'x', 'y', 'z' ], $params['b']['schema']['enum'] );
1395 },
1396 ];
1397
1398 yield 'request body' => [
1399 '$paramSettings' => [],
1400 '$bodySettings' => [
1401 'a' => [
1402 Handler::PARAM_SOURCE => 'body',
1403 ParamValidator::PARAM_TYPE => 'array',
1404 ArrayDef::PARAM_SCHEMA => [
1405 'type' => 'object',
1406 'required' => [ 'x', 'y', 'z' ]
1407 ],
1408 ParamValidator::PARAM_REQUIRED => true,
1409 ],
1410 'b' => [
1411 Handler::PARAM_SOURCE => 'body',
1412 ParamValidator::PARAM_REQUIRED => false,
1413 ],
1414 'p' => [
1415 Handler::PARAM_SOURCE => 'post',
1416 ],
1417 ],
1418 '$requestTypes' => [ 'application/foo+json', 'application/bar+json' ],
1419 '$routeConfig' => [ 'path' => '/test' ],
1420 '$method' => 'PUT',
1421 '$assertions' =>
1422 static function ( array $spec ) {
1423 self::assertWellFormedOAS( $spec, [ 'requestBody' ] );
1424 Assert::assertTrue( $spec['requestBody']['required'] );
1425
1426 Assert::assertArrayHasKey(
1427 'application/foo+json',
1428 $spec['requestBody']['content']
1429 );
1430
1431 Assert::assertSame(
1432 $spec['requestBody']['content']['application/foo+json'],
1433 $spec['requestBody']['content']['application/bar+json']
1434 );
1435
1436 $schema = $spec['requestBody']['content']
1437 ['application/foo+json']['schema'];
1438
1439 Assert::assertSame( 'object', $schema['type'] );
1440
1441 // Do not include "post" params if the request type
1442 // is not application/x-www-form-urlencoded or multipart/form-data.
1443 Assert::assertArrayHasKey( 'a', $schema['properties'] );
1444 Assert::assertArrayHasKey( 'b', $schema['properties'] );
1445 Assert::assertArrayNotHasKey( 'p', $schema['properties'] );
1446
1447 Assert::assertContains( 'a', $schema['required'] );
1448 Assert::assertNotContains( 'b', $schema['required'] );
1449
1450 // Nested schema, from ArrayDef
1451 $aSchema = $schema['properties']['a'];
1452 Assert::assertSame( 'object', $aSchema['type'] );
1453 Assert::assertSame( [ 'x', 'y', 'z' ], $aSchema['required'] );
1454 },
1455 ];
1456
1457 yield 'form data' => [
1458 '$paramSettings' => [],
1459 '$bodySettings' => [
1460 'a' => [
1461 Handler::PARAM_SOURCE => 'body',
1462 ],
1463 'p' => [
1464 Handler::PARAM_SOURCE => 'post',
1465 ],
1466 ],
1467 '$requestTypes' => [ 'application/x-www-form-urlencoded' ],
1468 '$routeConfig' => [ 'path' => '/test' ],
1469 '$method' => 'POST',
1470 '$assertions' =>
1471 static function ( array $spec ) {
1472 self::assertWellFormedOAS( $spec, [ 'requestBody' ] );
1473 Assert::assertTrue( $spec['requestBody']['required'] );
1474
1475 Assert::assertArrayHasKey(
1476 'application/x-www-form-urlencoded',
1477 $spec['requestBody']['content']
1478 );
1479 $schema = $spec['requestBody']['content']
1480 ['application/x-www-form-urlencoded']['schema'];
1481
1482 Assert::assertSame( 'object', $schema['type'] );
1483
1484 // Include both "post" and "body" params, because the
1485 // request type is application/x-www-form-urlencoded.
1486 Assert::assertArrayHasKey( 'a', $schema['properties'] );
1487 Assert::assertArrayHasKey( 'p', $schema['properties'] );
1488 },
1489 ];
1490
1491 yield 'no request body for GET' => [
1492 '$paramSettings' => [],
1493 '$bodySettings' => [
1494 'a' => [
1495 Handler::PARAM_SOURCE => 'body',
1496 ParamValidator::PARAM_TYPE => 'integer',
1497 ParamValidator::PARAM_REQUIRED => true,
1498 ],
1499 ],
1500 '$requestTypes' => [ 'application/json' ],
1501 '$routeConfig' => [ 'path' => '/test' ],
1502 '$method' => 'GET',
1503 '$assertions' =>
1504 static function ( array $spec ) {
1505 self::assertWellFormedOAS( $spec, [] );
1506
1507 // When generating a spec for GET, don't include the request body.
1508 Assert::assertArrayNotHasKey( 'requestBody', $spec );
1509 },
1510 ];
1511
1512 yield 'optional body for DELETE' => [
1513 '$paramSettings' => [],
1514 '$bodySettings' => [
1515 'a' => [
1516 Handler::PARAM_SOURCE => 'body',
1517 ParamValidator::PARAM_TYPE => 'integer',
1518 ParamValidator::PARAM_REQUIRED => false,
1519 ],
1520 ],
1521 '$requestTypes' => [ 'application/json' ],
1522 '$routeConfig' => [ 'path' => '/test' ],
1523 '$method' => 'DELETE',
1524 '$assertions' =>
1525 static function ( array $spec ) {
1526 self::assertWellFormedOAS( $spec, [ 'requestBody' ] );
1527
1528 // When generating a spec for GET, don't include the request body.
1529 // FIXME: check if there are required body params!
1530 Assert::assertFalse( $spec['requestBody']['required'] );
1531 },
1532 ];
1533
1534 yield 'optional path params' => [
1535 '$paramSettings' => [
1536 'p' => [
1537 Handler::PARAM_SOURCE => 'path',
1538 ParamValidator::PARAM_REQUIRED => false,
1539 ],
1540 'r' => [ // not in declared path, will be ignored
1541 Handler::PARAM_SOURCE => 'path',
1542 ParamValidator::PARAM_REQUIRED => false,
1543 ],
1544 ],
1545 '$bodySettings' => [],
1546 '$requestTypes' => [ 'application/json' ],
1547 '$routeConfig' => [ 'path' => '/test/{p}' ],
1548 '$method' => 'GET',
1549 '$assertions' =>
1550 static function ( array $spec ) {
1551 self::assertWellFormedOAS( $spec, [ 'parameters' ] );
1552 $params = self::makeMap( $spec['parameters'], 'name' );
1553
1554 Assert::assertArrayHasKey(
1555 'p',
1556 $params,
1557 'used optional path parameter should be listed'
1558 );
1559 Assert::assertArrayNotHasKey(
1560 'r',
1561 $params,
1562 'unused optional path parameter should not be listed'
1563 );
1564
1565 Assert::assertSame( 'path', $params['p']['in'] );
1566 Assert::assertTrue(
1567 $params['p']['required'],
1568 'used optional path parameter should be marked as required'
1569 );
1570 },
1571 ];
1572
1573 yield 'OAS info' => [
1574 '$paramSettings' => [
1575 'p' => [
1576 Handler::PARAM_SOURCE => 'path',
1577 ],
1578 ],
1579 '$bodySettings' => [],
1580 '$requestTypes' => [ 'application/json' ],
1581 '$routeConfig' => [
1582 'path' => 'test/{p}',
1583 'OAS' => [
1584 'title' => 'just a test',
1585 'parameters' => 'will be ignored',
1586 ]
1587 ],
1588 '$method' => 'GET',
1589 '$assertions' =>
1590 static function ( array $spec ) {
1591 self::assertWellFormedOAS( $spec, [ 'title', 'parameters' ] );
1592 Assert::assertArrayHasKey( 'title', $spec );
1593 Assert::assertSame( 'just a test', $spec['title'] );
1594
1595 $params = self::makeMap( $spec['parameters'], 'name' );
1596 Assert::assertArrayHasKey( 'p', $params );
1597 },
1598 ];
1599 }
1600
1601 /**
1602 * @dataProvider provideGetOpenApiSpec
1603 */
1604 public function testGetOpenApiSpec(
1605 $paramSettings,
1606 $bodySettings,
1607 $requestTypes,
1608 $routeConfig,
1609 $method,
1610 $assertions
1611 ) {
1612 $handler = $this->newHandler( [
1613 'getParamSettings',
1614 'getBodyParamSettings',
1615 'getSupportedRequestTypes',
1616 ] );
1617 $handler->method( 'getParamSettings' )->willReturn( $paramSettings );
1618 $handler->method( 'getBodyParamSettings' )->willReturn( $bodySettings );
1619 $handler->method( 'getSupportedRequestTypes' )->willReturn( $requestTypes );
1620
1621 // The "body" parameter should be processed as "body", not as "parameter".
1622 $module = $this->createNoOpMock( Module::class );
1623 $handler->initContext(
1624 $module,
1625 $routeConfig['path'],
1626 $routeConfig
1627 );
1628 $spec = $handler->getOpenApiSpec( $method );
1629
1630 $assertions( $spec );
1631 }
1632
1633 }