aboutsummaryrefslogtreecommitdiffstats
path: root/includes/Rest/Handler.php
blob: aecdee4559211cc772c1c09c85672b6ef51587d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
<?php

namespace MediaWiki\Rest;

use DateTime;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Permissions\Authority;
use MediaWiki\Rest\Module\Module;
use MediaWiki\Rest\Validator\BodyValidator;
use MediaWiki\Rest\Validator\JsonBodyValidator;
use MediaWiki\Rest\Validator\NullBodyValidator;
use MediaWiki\Rest\Validator\Validator;
use MediaWiki\Session\Session;
use Wikimedia\Assert\Assert;
use Wikimedia\Message\MessageValue;

/**
 * Base class for REST route handlers.
 *
 * @stable to extend.
 */
abstract class Handler {

	/**
	 * @see Validator::KNOWN_PARAM_SOURCES
	 */
	public const KNOWN_PARAM_SOURCES = Validator::KNOWN_PARAM_SOURCES;

	/**
	 * @see Validator::PARAM_SOURCE
	 */
	public const PARAM_SOURCE = Validator::PARAM_SOURCE;

	/**
	 * @see Validator::PARAM_DESCRIPTION
	 */
	public const PARAM_DESCRIPTION = Validator::PARAM_DESCRIPTION;

	/** @var Module */
	private $module;

	/** @var RequestInterface */
	private $request;

	/** @var Authority */
	private $authority;

	/** @var string */
	private $path;

	/** @var array */
	private $config;

	/** @var ResponseFactory */
	private $responseFactory;

	/** @var array|null */
	private $validatedParams;

	/** @var mixed|null */
	private $validatedBody;

	/** @var ConditionalHeaderUtil */
	private $conditionalHeaderUtil;

	/** @var HookContainer */
	private $hookContainer;

	/** @var Session */
	private $session;

	/** @var HookRunner */
	private $hookRunner;

	/**
	 * Injects information about the handler's context in the Module.
	 * The framework should call this right after the object was constructed.
	 *
	 * First function of the initialization function, must be called before
	 * initServices().
	 *
	 * @param Module $module
	 * @param string $path
	 * @param array $routeConfig information about the route declaration.
	 *
	 * @internal
	 */
	final public function initContext( Module $module, string $path, array $routeConfig ) {
		Assert::precondition(
			$this->authority === null,
			'initContext() must be called before initServices()'
		);

		$this->module = $module;
		$this->path = $path;
		$this->config = $routeConfig;
	}

	/**
	 * Inject service objects.
	 *
	 * Second function of the initialization function, must be called after
	 * initContext() and before initSession().
	 *
	 * @param Authority $authority
	 * @param ResponseFactory $responseFactory
	 * @param HookContainer $hookContainer
	 *
	 * @internal
	 */
	final public function initServices(
		Authority $authority, ResponseFactory $responseFactory, HookContainer $hookContainer
	) {
		Assert::precondition(
			$this->module !== null,
			'initServices() must not be called before initContext()'
		);
		Assert::precondition(
			$this->session === null,
			'initServices() must be called before initSession()'
		);

		$this->authority = $authority;
		$this->responseFactory = $responseFactory;
		$this->hookContainer = $hookContainer;
		$this->hookRunner = new HookRunner( $hookContainer );
	}

	/**
	 * Inject session information.
	 *
	 * Third function of the initialization function, must be called after
	 * initServices() and before initForExecute().
	 *
	 * @param Session $session
	 *
	 * @internal
	 */
	final public function initSession( Session $session ) {
		Assert::precondition(
			$this->authority !== null,
			'initSession() must not be called before initContext()'
		);
		Assert::precondition(
			$this->request === null,
			'initSession() must be called before initForExecute()'
		);

		$this->session = $session;
	}

	/**
	 * Initialise for execution based on the given request.
	 *
	 * Last function of the initialization function, must be called after
	 * initSession() and before validate() and checkPreconditions().
	 *
	 * This function will call postInitSetup() to allow subclasses to
	 * perform their own initialization.
	 *
	 * The request object is updated with parsed body data if needed.
	 *
	 * @internal
	 *
	 * @param RequestInterface $request
	 *
	 * @throws HttpException if the handler does not accept the request for
	 *         some reason.
	 */
	final public function initForExecute( RequestInterface $request ) {
		Assert::precondition(
			$this->session !== null,
			'initForExecute() must not be called before initSession()'
		);

		if ( $request->getParsedBody() === null ) {
			$this->processRequestBody( $request );
		}

		$this->request = $request;

		$this->postInitSetup();
	}

	/**
	 * Process the request's request body and set the parsed body data
	 * if appropriate.
	 *
	 * @see parseBodyData()
	 *
	 * @throws HttpException if the request body is not acceptable.
	 */
	private function processRequestBody( RequestInterface $request ) {
		// fail if the request method is in NO_BODY_METHODS but has body
		$requestMethod = $request->getMethod();
		if ( in_array( $requestMethod, RequestInterface::NO_BODY_METHODS ) ) {
			// check if the request has a body
			if ( $request->hasBody() ) {
				// NOTE: Don't throw, see T359509.
				// TODO: Ignore only empty bodies, log a warning or fail if
				//       there is actual content.
				return;
			}
		}

		// fail if the request method expects a body but has no body
		if ( in_array( $requestMethod, RequestInterface::BODY_METHODS ) ) {
			// check if it has no body
			if ( !$request->hasBody() ) {
				throw new LocalizedHttpException(
					new MessageValue(
						"rest-request-body-expected",
						[ $requestMethod ]
					),
					411
				);
			}
		}

		// call parsedbody
		if ( $request->hasBody() ) {
			$parsedBody = $this->parseBodyData( $request );
			// Set the parsed body data on the request object
			$request->setParsedBody( $parsedBody );
		}
	}

	/**
	 * Returns the path this handler is bound to relative to the module prefix.
	 * Includes path variables.
	 *
	 * @return string
	 */
	public function getPath(): string {
		return $this->path;
	}

	/**
	 * Get a list of parameter placeholders present in the route's path
	 * as returned by getPath(). Note that this is independent of the parameters
	 * defined by getParamSettings(): required path parameters defined in
	 * getParamSettings() should be present in the path, but there is no
	 * mechanism to ensure that they are.
	 *
	 * @return string[]
	 */
	public function getSupportedPathParams(): array {
		$path = $this->getPath();

		preg_match_all( '/\{(.*?)\}/', $path, $matches, PREG_PATTERN_ORDER );

		return $matches[1] ?? [];
	}

	/**
	 * Get the Router.
	 *
	 * @return Router
	 */
	protected function getRouter(): Router {
		return $this->module->getRouter();
	}

	/**
	 * Get the Module this handler belongs to.
	 * Will fail hard if called before initContext().
	 *
	 * @return Module
	 */
	protected function getModule(): Module {
		return $this->module;
	}

	/**
	 * Get the URL of this handler's endpoint.
	 * Supports the substitution of path parameters, and additions of query parameters.
	 *
	 * @see Router::getRouteUrl()
	 *
	 * @param string[] $pathParams Path parameters to be injected into the path
	 * @param string[] $queryParams Query parameters to be attached to the URL
	 *
	 * @return string
	 */
	protected function getRouteUrl( $pathParams = [], $queryParams = [] ): string {
		$path = $this->getPath();
		return $this->getRouter()->getRouteUrl( $path, $pathParams, $queryParams );
	}

	/**
	 * URL-encode titles in a "pretty" way.
	 *
	 * Keeps intact ;@$!*(),~: (urlencode does not, but wfUrlencode does).
	 * Encodes spaces as underscores (wfUrlencode does not).
	 * Encodes slashes (wfUrlencode does not, but keeping them messes with REST paths).
	 * Encodes pluses (this is not necessary, and may change).
	 *
	 * @see wfUrlencode
	 *
	 * @param string $title
	 *
	 * @return string
	 */
	protected function urlEncodeTitle( $title ) {
		$title = str_replace( ' ', '_', $title );
		$title = urlencode( $title );

		// %3B_a_%40_b_%24_c_%21_d_%2A_e_%28_f_%29_g_%2C_h_~_i_%3A
		$replace = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%7E', '%3A' ];
		$with = [ ';', '@', '$', '!', '*', '(', ')', ',', '~', ':' ];

		return str_replace( $replace, $with, $title );
	}

	/**
	 * Get the current request. The return type declaration causes it to raise
	 * a fatal error if initForExecute() has not yet been called.
	 *
	 * @return RequestInterface
	 */
	public function getRequest(): RequestInterface {
		return $this->request;
	}

	/**
	 * Get the current acting authority. The return type declaration causes it to raise
	 * a fatal error if initServices() has not yet been called.
	 *
	 * @since 1.36
	 * @return Authority
	 */
	public function getAuthority(): Authority {
		return $this->authority;
	}

	/**
	 * Get the configuration array for the current route. The return type
	 * declaration causes it to raise a fatal error if initContext() has not
	 * been called.
	 *
	 * @return array
	 */
	public function getConfig(): array {
		return $this->config;
	}

	/**
	 * Get the ResponseFactory which can be used to generate Response objects.
	 * This will raise a fatal error if initServices() has not been
	 * called.
	 *
	 * @return ResponseFactory
	 */
	public function getResponseFactory(): ResponseFactory {
		return $this->responseFactory;
	}

	/**
	 * Get the Session.
	 * This will raise a fatal error if initSession() has not been
	 * called.
	 *
	 * @return Session
	 */
	public function getSession(): Session {
		return $this->session;
	}

	/**
	 * Validate the request parameters/attributes and body. If there is a validation
	 * failure, a response with an error message should be returned or an
	 * HttpException should be thrown.
	 *
	 * @stable to override
	 * @param Validator $restValidator
	 * @throws HttpException On validation failure.
	 */
	public function validate( Validator $restValidator ) {
		$legacyValidatedBody = $restValidator->validateBody( $this->request, $this );

		$this->validatedParams = $restValidator->validateParams(
			$this->getParamSettings()
		);

		if ( $legacyValidatedBody !== null ) {
			// TODO: warn if $bodyParamSettings is not empty
			// TODO: trigger a deprecation warning
			$this->validatedBody = $legacyValidatedBody;
		} else {
			$this->validatedBody = $restValidator->validateBodyParams(
				$this->getBodyParamSettings()
			);

			// If there is a body, check if it contains extra fields.
			if ( $this->getRequest()->hasBody() ) {
				$this->detectExtraneousBodyFields( $restValidator );
			}
		}

		$this->postValidationSetup();
	}

	/**
	 * Subclasses may override this to disable or modify checks for extraneous
	 * body fields.
	 *
	 * @since 1.42
	 * @stable to override
	 * @param Validator $restValidator
	 * @throws HttpException On validation failure.
	 */
	protected function detectExtraneousBodyFields( Validator $restValidator ) {
		$parsedBody = $this->getRequest()->getParsedBody();

		if ( !$parsedBody ) {
			// nothing to do
			return;
		}

		$restValidator->detectExtraneousBodyFields(
			$this->getBodyParamSettings(),
			$parsedBody
		);
	}

	/**
	 * Check the session (and session provider)
	 * @throws HttpException on failed check
	 * @internal
	 */
	public function checkSession() {
		if ( !$this->session->getProvider()->safeAgainstCsrf() ) {
			if ( $this->requireSafeAgainstCsrf() ) {
				throw new LocalizedHttpException(
					new MessageValue( 'rest-requires-safe-against-csrf' ),
					400
				);
			}
		} elseif ( !empty( $this->validatedBody['token'] ) ) {
			throw new LocalizedHttpException(
				new MessageValue( 'rest-extraneous-csrf-token' ),
				400
			);
		}
	}

	/**
	 * Get a ConditionalHeaderUtil object.
	 *
	 * On the first call to this method, the object will be initialized with
	 * validator values by calling getETag(), getLastModified() and
	 * hasRepresentation().
	 *
	 * @return ConditionalHeaderUtil
	 */
	protected function getConditionalHeaderUtil() {
		if ( $this->conditionalHeaderUtil === null ) {
			$this->conditionalHeaderUtil = new ConditionalHeaderUtil;
			$this->conditionalHeaderUtil->setValidators(
				$this->getETag(),
				$this->getLastModified(),
				$this->hasRepresentation()
			);
		}
		return $this->conditionalHeaderUtil;
	}

	/**
	 * Check the conditional request headers and generate a response if appropriate.
	 * This is called by the Router before execute() and may be overridden.
	 *
	 * @stable to override
	 *
	 * @return ResponseInterface|null
	 */
	public function checkPreconditions() {
		$status = $this->getConditionalHeaderUtil()->checkPreconditions( $this->getRequest() );
		if ( $status ) {
			$response = $this->getResponseFactory()->create();
			$response->setStatus( $status );
			return $response;
		}

		return null;
	}

	/**
	 * Apply verifier headers to the response, per RFC 7231 §7.2.
	 * This is called after execute() returns.
	 *
	 * For GET and HEAD requests, the default behavior is to set the ETag and
	 * Last-Modified headers based on the values returned by getETag() and
	 * getLastModified() when they were called before execute() was run.
	 *
	 * Other request methods are assumed to be state-changing, so no headers
	 * will be set by default.
	 *
	 * This may be overridden to modify the verifier headers sent in the response.
	 * However, handlers that modify the resource's state would typically just
	 * set the ETag and Last-Modified headers in the execute() method.
	 *
	 * @stable to override
	 *
	 * @param ResponseInterface $response
	 */
	public function applyConditionalResponseHeaders( ResponseInterface $response ) {
		$method = $this->getRequest()->getMethod();
		if ( $method === 'GET' || $method === 'HEAD' ) {
			$this->getConditionalHeaderUtil()->applyResponseHeaders( $response );
		}
	}

	/**
	 * Apply cache control to enforce privacy.
	 *
	 * @param ResponseInterface $response
	 */
	public function applyCacheControl( ResponseInterface $response ) {
		// NOTE: keep this consistent with the logic in OutputPage::sendCacheControl

		// If the response sets cookies, it must not be cached in proxies.
		// If there's an active cookie-based session (logged-in user or anonymous user with
		// session-scoped cookies), it is not safe to cache either, as the session manager may set
		// cookies in the response, or the response itself may vary on user-specific variables,
		// for example on private wikis where the 'read' permission is restricted. (T264631)
		if ( $response->getHeaderLine( 'Set-Cookie' ) || $this->getSession()->isPersistent() ) {
			$response->setHeader( 'Cache-Control', 'private,must-revalidate,s-maxage=0' );
		}

		if ( !$response->getHeaderLine( 'Cache-Control' ) ) {
			$rqMethod = $this->getRequest()->getMethod();
			if ( $rqMethod !== 'GET' && $rqMethod !== 'HEAD' ) {
				// Responses to requests other than GET or HEAD should not be cacheable by default.
				$response->setHeader( 'Cache-Control', 'private,no-cache,s-maxage=0' );
			}
		}
	}

	/**
	 * Fetch ParamValidator settings for parameters
	 *
	 * Every setting must include self::PARAM_SOURCE to specify which part of
	 * the request is to contain the parameter.
	 *
	 * Can be used for the request body as well, by setting self::PARAM_SOURCE
	 * to "post" or "body". Note that the values of "body" parameters will become
	 * accessible through getValidatedBody(), while the values of "post"
	 * parameters will be accessible through getValidatedParams(). "post"
	 * parameters are used with form data (application/x-www-form-urlencoded or
	 * multipart/form-data).
	 *
	 * For "query" and "body" parameters, a PARAM_REQUIRED setting of "false" means the caller
	 * does not have to supply the parameter. For "path" parameters, the path matcher will always
	 * require the caller to supply all path parameters for a route, regardless of the
	 * PARAM_REQUIRED setting. However, "path" parameters may be specified in getParamSettings()
	 * as non-required to indicate that the handler services multiple routes, some of which may
	 * not supply the parameter.
	 *
	 * @stable to override
	 *
	 * @return array[] Associative array mapping parameter names to
	 *  ParamValidator settings arrays
	 */
	public function getParamSettings() {
		return [];
	}

	/**
	 * Fetch ParamValidator settings for body fields. Parameters defined
	 * by this method are used to validate the request body. The parameter
	 * values will become available through getValidatedBody().
	 *
	 * The default implementation will call getParamSettings() and filter the
	 * return value to only include settings for parameters that have
	 * self::PARAM_SOURCE set to 'body'.
	 *
	 * Subclasses may override this method to specify what fields they support
	 * in the request body. All parameter settings returned by this method must
	 * have self::PARAM_SOURCE set to 'body'.
	 *
	 * @return array[]
	 */
	public function getBodyParamSettings(): array {
		return array_filter( $this->getParamSettings(),
			static function ( array $settings ) {
				return ( $settings[self::PARAM_SOURCE] ?? false ) === 'body';
			}
		);
	}

	/**
	 * Returns an OpenAPI Operation Object specification structure as an associative array.
	 *
	 * @see https://swagger.io/specification/#operation-object
	 *
	 * By default, this will contain information about the supported parameters, as well as
	 * the response for status 200.
	 *
	 * Subclasses may override this to provide additional information.
	 *
	 * @since 1.42
	 * @stable to override
	 *
	 * @param string $method The HTTP method to produce a spec for ("get", "post", etc).
	 *        Useful for handlers that behave differently depending on the
	 *        request method.
	 *
	 * @return array
	 */
	public function getOpenApiSpec( string $method ): array {
		$parameters = [];

		// XXX: Maybe we want to be able to define a spec file in the route definition?
		// NOTE: the route definition may not be loaded if this is called before initContext()!

		$supportedPathParams = array_flip( $this->getSupportedPathParams() );

		foreach ( $this->getParamSettings() as $name => $paramSetting ) {
			$param = Validator::getParameterSpec(
				$name,
				$paramSetting
			);

			$location = $param['in'];
			if ( $location === 'post' || $location === 'body' ) {
				// 'post' and 'body' are handled in getRequestSpec()
				// but others are added as normal parameters
				continue;
			}

			if ( $location === 'path' && !isset( $supportedPathParams[$name] ) ) {
				// Skip optional path param not used in the current path
				continue;
			}

			$parameters[] = $param;
		}

		$spec = [
			'parameters' => $parameters,
			'responses' => $this->generateResponseSpec(),
		];

		$requestBody = $this->getRequestSpec();
		if ( $requestBody ) {
			$spec['requestBody'] = $requestBody;
		}

		// TODO: Allow additional information about parameters and responses to
		//       be provided in the route definition.
		$oas = $this->getConfig()['OAS'] ?? [];
		$spec += $oas;

		return $spec;
	}

	/**
	 * Returns an OpenAPI Request Body Object specification structure as an associative array.
	 * @see https://swagger.io/specification/#request-body-object
	 *
	 * By default, this calls getBodyValidator() to get a SchemaValidator,
	 * and then calls getBodySpec() on it.
	 * If no SchemaValidator is supported, this returns null;
	 *
	 * Subclasses may override this to provide additional information about the structure of responses.
	 *
	 * @stable to override
	 * @return ?array
	 */
	protected function getRequestSpec(): ?array {
		$request = [];

		// TODO: Implement spec generation based on getBodyParamSettings(),
		//       since BodyValidator is going away soon (T358560).
		foreach ( $this->getSupportedRequestTypes() as $type ) {
			try {
				$validator = $this->getBodyValidator( $type );

				if ( $validator instanceof JsonBodyValidator ) {
					$schema = $validator->getOpenAPISpec();

					if ( $schema !== [] ) {
						$request['content'][$type]['schema'] = $schema;
					}
				}
			} catch ( HttpException $ex ) {
				// the type is not actually not supported, ignore.
			}
		}

		return $request ?: null;
	}

	/**
	 * Returns an OpenAPI Schema Object specification structure as an associative array.
	 * @see https://swagger.io/specification/#schema-object
	 *
	 * Returns null by default. Subclasses that return a JSON response should
	 * implement this method to return a schema of the response body.
	 *
	 * @stable to override
	 * @return ?array
	 */
	protected function getResponseBodySchema(): ?array {
		return null;
	}

	/**
	 * Returns an OpenAPI Responses Object specification structure as an associative array.
	 * @see https://swagger.io/specification/#responses-object
	 *
	 * By default, this will contain basic information response for status 200, 400, and 500.
	 * The getResponseBodySchema() method is used to determine the structure of the response for status 200.
	 *
	 * Subclasses may override this to provide additional information about the structure of responses.
	 *
	 * @stable to override
	 * @return array
	 */
	protected function generateResponseSpec(): array {
		$ok = [ 'description' => 'OK' ];

		$bodySchema = $this->getResponseBodySchema();

		if ( $bodySchema ) {
			$ok['content']['application/json']['schema'] = $bodySchema;
		}

		// XXX: we should add info about redirects, and maybe a default for errors?
		return [
			'200' => $ok,
			'400' => [ '$ref' => '#/components/responses/GenericErrorResponse' ],
			'500' => [ '$ref' => '#/components/responses/GenericErrorResponse' ],
		];
	}

	/**
	 * Fetch the BodyValidator
	 *
	 * @stable to override
	 *
	 * @param string $contentType Content type of the request.
	 * @return BodyValidator A {@see NullBodyValidator} in this default implementation
	 * @throws HttpException It's possible to fail early here when e.g. $contentType is unsupported,
	 *  or later when {@see BodyValidator::validateBody} is called
	 */
	public function getBodyValidator( $contentType ) {
		// TODO: Create a JsonBodyValidator if getParamSettings() returns body params.
		// XXX: also support multipart/form-data and application/x-www-form-urlencoded?
		return new NullBodyValidator();
	}

	/**
	 * Fetch the validated parameters. This must be called after validate() is
	 * called. During execute() is fine.
	 *
	 * @return array Array mapping parameter names to validated values
	 * @throws \RuntimeException If validate() has not been called
	 */
	public function getValidatedParams() {
		if ( $this->validatedParams === null ) {
			throw new \RuntimeException( 'getValidatedParams() called before validate()' );
		}
		return $this->validatedParams;
	}

	/**
	 * Fetch the validated body
	 * @return mixed|null Value returned by the body validator, or null if validate() was
	 *  not called yet, validation failed, there was no body, or the body was form data.
	 */
	public function getValidatedBody() {
		return $this->validatedBody;
	}

	/**
	 * Returns the parsed body of the request.
	 * Should only be called if $request->hasBody() returns true.
	 *
	 * The default implementation handles application/x-www-form-urlencoded
	 * and multipart/form-data by calling $request->getPostParams(),
	 * if the list returned by getSupportedRequestTypes() includes these types.
	 *
	 * The default implementation handles application/json by parsing
	 * the body content as JSON. Only object structures (maps) are supported,
	 * other types will trigger an HttpException with status 400.
	 *
	 * Other content types will trigger a HttpException with status 415 per
	 * default.
	 *
	 * Subclasses may override this method to support parsing additional
	 * content types or to disallow content types by throwing an HttpException
	 * with status 415. Subclasses may also return null to indicate that they
	 * support reading the content, but intend to handle it as an unparsed
	 * stream in their implementation of the execute() method.
	 *
	 * Subclasses that override this method to support additional request types
	 * should also override getSupportedRequestTypes() to allow  that support
	 * to be documented in the OpenAPI spec.
	 *
	 * @since 1.42
	 *
	 * @throws HttpException If the content type is not supported or the content
	 *         is malformed.
	 *
	 * @return array|null The body content represented as an associative array,
	 *         or null if the request body is accepted unparsed.
	 */
	public function parseBodyData( RequestInterface $request ): ?array {
		// Parse the body based on its content type
		$contentType = $request->getBodyType();

		// HACK: If the Handler uses a custom BodyValidator, the
		// getBodyValidator() is also responsible for checking whether
		// the content type is valid, and for parsing the body.
		// See T359149.
		$bodyValidator = $this->getBodyValidator( $contentType ?? 'unknown/unknown' );
		if ( !$bodyValidator instanceof NullBodyValidator ) {
			// TODO: Trigger a deprecation warning.
			return null;
		}

		$supportedTypes = $this->getSupportedRequestTypes();
		if ( $contentType !== null && !in_array( $contentType, $supportedTypes ) ) {
			throw new LocalizedHttpException(
				new MessageValue( 'rest-unsupported-content-type', [ $contentType ] ),
				415
			);
		}

		switch ( $contentType ) {
			case 'application/x-www-form-urlencoded':
			case 'multipart/form-data':
				return $request->getPostParams();
			case 'application/json':
				$jsonStream = $request->getBody();
				$parsedBody = json_decode( "$jsonStream", true );
				if ( !is_array( $parsedBody ) ) {
					throw new LocalizedHttpException(
						new MessageValue(
							'rest-json-body-parse-error',
							[ 'not a valid JSON object' ]
						),
						400
					);
				}
				return $parsedBody;
			case null:
				// Specifying no Content-Type is fine if the body is empty
				if ( $request->getBody()->getSize() === 0 ) {
					return null;
				}
				// no break, else fall through to the error below.
			default:
				throw new LocalizedHttpException(
					new MessageValue( 'rest-unsupported-content-type', [ $contentType ?? '(null)' ] ),
					415
				);
		}
	}

	/**
	 * Returns the content types that should be accepted by parseBodyData().
	 *
	 * Subclasses that support request types other than application/json
	 * should override this method.
	 *
	 * If "application/x-www-form-urlencoded" or "multipart/form-data" are
	 * returned, parseBodyData() will use $request->getPostParams() to determine
	 * the body data.
	 *
	 * @note The return value of this method is ignored for requests
	 * using a method listed in Validator::NO_BODY_METHODS,
	 * in particular for the GET method.
	 *
	 * @note for backwards compatibility, the default implementation of this
	 * method will examine the parameter definitions returned by getParamSettings()
	 * to see if any of the parameters are declared as "post" parameters. If this
	 * is the case, support for "application/x-www-form-urlencoded" and
	 * "multipart/form-data" is added. This may change in future releases.
	 * It is preferred to use "body" parameters and override this method explicitly
	 * when support for form data is desired.
	 *
	 * @stable to override
	 *
	 * @return string[] A list of content-types
	 */
	public function getSupportedRequestTypes(): array {
		$types = [
			'application/json'
		];

		foreach ( $this->getParamSettings() as $settings ) {
			if ( ( $settings[self::PARAM_SOURCE] ?? null ) === 'post' ) {
				$types[] = 'application/x-www-form-urlencoded';
				$types[] = 'multipart/form-data';
				break;
			}
		}

		return $types;
	}

	/**
	 * Get a HookContainer, for running extension hooks or for hook metadata.
	 *
	 * @since 1.35
	 * @return HookContainer
	 */
	protected function getHookContainer() {
		return $this->hookContainer;
	}

	/**
	 * Get a HookRunner for running core hooks.
	 *
	 * @internal This is for use by core only. Hook interfaces may be removed
	 *   without notice.
	 * @since 1.35
	 * @return HookRunner
	 */
	protected function getHookRunner() {
		return $this->hookRunner;
	}

	/**
	 * The subclass should override this to provide the maximum last modified
	 * timestamp of the requested resource. This is called before execute() in
	 * order to decide whether to send a 304. If the request is going to
	 * change the state of the resource, the time returned must represent
	 * the last modification date before the change. In other words, it must
	 * provide the timestamp of the entity that the change is going to be
	 * applied to.
	 *
	 * For GET and HEAD requests, this value will automatically be included
	 * in the response in the Last-Modified header.
	 *
	 * Handlers that modify the resource and want to return a Last-Modified
	 * header representing the new state in the response should set the header
	 * in the execute() method.
	 *
	 * See RFC 7231 §7.2 and RFC 7232 §2.3 for semantics.
	 *
	 * @stable to override
	 *
	 * @return string|int|float|DateTime|null
	 */
	protected function getLastModified() {
		return null;
	}

	/**
	 * The subclass should override this to provide an ETag for the current
	 * state of the requested resource. This is called before execute() in
	 * order to decide whether to send a 304. If the request is going to
	 * change the state of the resource, the ETag returned must represent
	 * the state before the change. In other words, it must identify
	 * the entity that the change is going to be applied to.
	 *
	 * For GET and HEAD requests, this ETag will also be included in the
	 * response.
	 *
	 * Handlers that modify the resource and want to return an ETag
	 * header representing the new state in the response should set the header
	 * in the execute() method. However, note that responses to PUT requests
	 * must not return an ETag unless the new content of the resource is exactly
	 * the data that was sent by the client in the request body.
	 *
	 * This must be a complete ETag, including double quotes.
	 * See RFC 7231 §7.2 and RFC 7232 §2.3 for semantics.
	 *
	 * @stable to override
	 *
	 * @return string|null
	 */
	protected function getETag() {
		return null;
	}

	/**
	 * The subclass should override this to indicate whether the resource
	 * exists. This is used for wildcard validators, for example "If-Match: *"
	 * fails if the resource does not exist.
	 *
	 * In a state-changing request, the return value of this method should
	 * reflect the state before the requested change is applied.
	 *
	 * @stable to override
	 *
	 * @return bool|null
	 */
	protected function hasRepresentation() {
		return null;
	}

	/**
	 * Indicates whether this route requires read rights.
	 *
	 * The handler should override this if it does not need to read from the
	 * wiki. This is uncommon, but may be useful for login and other account
	 * management APIs.
	 *
	 * @stable to override
	 *
	 * @return bool
	 */
	public function needsReadAccess() {
		return true;
	}

	/**
	 * Indicates whether this route requires write access.
	 *
	 * The handler should override this if the route does not need to write to
	 * the database.
	 *
	 * This should return true for routes that may require synchronous database writes.
	 * Modules that do not need such writes should also not rely on primary database access,
	 * since only read queries are needed and each primary DB is a single point of failure.
	 *
	 * @stable to override
	 *
	 * @return bool
	 */
	public function needsWriteAccess() {
		return true;
	}

	/**
	 * Indicates whether this route can be accessed only by session providers safe vs csrf
	 *
	 * The handler should override this if the route must only be accessed by session
	 * providers that are safe against csrf.
	 *
	 * A return value of false does not necessarily mean the route is vulnerable to csrf attacks.
	 * It means the route can be accessed by session providers that are not automatically safe
	 * against csrf attacks, so the possibility of csrf attacks must be considered.
	 *
	 * @stable to override
	 *
	 * @return bool
	 */
	public function requireSafeAgainstCsrf() {
		return false;
	}

	/**
	 * The handler can override this to do any necessary setup after the init functions
	 * are called to inject dependencies.
	 *
	 * @stable to override
	 * @throws HttpException if the handler does not accept the request for
	 *         some reason.
	 */
	protected function postInitSetup() {
	}

	/**
	 * The handler can override this to do any necessary setup after validate()
	 * has been called. This gives the handler an opportunity to do initialization
	 * based on parameters before pre-execution calls like getLastModified() or getETag().
	 *
	 * @stable to override
	 * @since 1.36
	 */
	protected function postValidationSetup() {
	}

	/**
	 * Execute the handler. This is called after parameter validation. The
	 * return value can either be a Response or any type accepted by
	 * ResponseFactory::createFromReturnValue().
	 *
	 * To automatically construct an error response, execute() should throw a
	 * \MediaWiki\Rest\HttpException. Such exceptions will not be logged like
	 * a normal exception.
	 *
	 * If execute() throws any other kind of exception, the exception will be
	 * logged and a generic 500 error page will be shown.
	 *
	 * @stable to override
	 *
	 * @return mixed
	 */
	abstract public function execute();
}